");return c.inlineElement=f,f}return b.updateStatus("ready"),b._parseMarkup(d,{},c),d}}});var H,I="ajax",J=function(){H&&a(document.body).removeClass(H)},K=function(){J(),b.req&&b.req.abort()};a.magnificPopup.registerModule(I,{options:{settings:null,cursor:"mfp-ajax-cur",tError:'
The content could not be loaded.'},proto:{initAjax:function(){b.types.push(I),H=b.st.ajax.cursor,w(h+"."+I,K),w("BeforeChange."+I,K)},getAjax:function(c){H&&a(document.body).addClass(H),b.updateStatus("loading");var d=a.extend({url:c.src,success:function(d,e,f){var g={data:d,xhr:f};y("ParseAjax",g),b.appendContent(a(g.data),I),c.finished=!0,J(),b._setFocus(),setTimeout(function(){b.wrap.addClass(q)},16),b.updateStatus("ready"),y("AjaxContentAdded")},error:function(){J(),c.finished=c.loadError=!0,b.updateStatus("error",b.st.ajax.tError.replace("%url%",c.src))}},b.st.ajax.settings);return b.req=a.ajax(d),""}}});var L,M=function(c){if(c.data&&void 0!==c.data.title)return c.data.title;var d=b.st.image.titleSrc;if(d){if(a.isFunction(d))return d.call(b,c);if(c.el)return c.el.attr(d)||""}return""};a.magnificPopup.registerModule("image",{options:{markup:'
',cursor:"mfp-zoom-out-cur",titleSrc:"title",verticalFit:!0,tError:'
The image could not be loaded.'},proto:{initImage:function(){var c=b.st.image,d=".image";b.types.push("image"),w(m+d,function(){"image"===b.currItem.type&&c.cursor&&a(document.body).addClass(c.cursor)}),w(h+d,function(){c.cursor&&a(document.body).removeClass(c.cursor),v.off("resize"+p)}),w("Resize"+d,b.resizeImage),b.isLowIE&&w("AfterChange",b.resizeImage)},resizeImage:function(){var a=b.currItem;if(a&&a.img&&b.st.image.verticalFit){var c=0;b.isLowIE&&(c=parseInt(a.img.css("padding-top"),10)+parseInt(a.img.css("padding-bottom"),10)),a.img.css("max-height",b.wH-c)}},_onImageHasSize:function(a){a.img&&(a.hasSize=!0,L&&clearInterval(L),a.isCheckingImgSize=!1,y("ImageHasSize",a),a.imgHidden&&(b.content&&b.content.removeClass("mfp-loading"),a.imgHidden=!1))},findImageSize:function(a){var c=0,d=a.img[0],e=function(f){L&&clearInterval(L),L=setInterval(function(){return d.naturalWidth>0?void b._onImageHasSize(a):(c>200&&clearInterval(L),c++,void(3===c?e(10):40===c?e(50):100===c&&e(500)))},f)};e(1)},getImage:function(c,d){var e=0,f=function(){c&&(c.img[0].complete?(c.img.off(".mfploader"),c===b.currItem&&(b._onImageHasSize(c),b.updateStatus("ready")),c.hasSize=!0,c.loaded=!0,y("ImageLoadComplete")):(e++,200>e?setTimeout(f,100):g()))},g=function(){c&&(c.img.off(".mfploader"),c===b.currItem&&(b._onImageHasSize(c),b.updateStatus("error",h.tError.replace("%url%",c.src))),c.hasSize=!0,c.loaded=!0,c.loadError=!0)},h=b.st.image,i=d.find(".mfp-img");if(i.length){var j=document.createElement("img");j.className="mfp-img",c.el&&c.el.find("img").length&&(j.alt=c.el.find("img").attr("alt")),c.img=a(j).on("load.mfploader",f).on("error.mfploader",g),j.src=c.src,i.is("img")&&(c.img=c.img.clone()),j=c.img[0],j.naturalWidth>0?c.hasSize=!0:j.width||(c.hasSize=!1)}return b._parseMarkup(d,{title:M(c),img_replaceWith:c.img},c),b.resizeImage(),c.hasSize?(L&&clearInterval(L),c.loadError?(d.addClass("mfp-loading"),b.updateStatus("error",h.tError.replace("%url%",c.src))):(d.removeClass("mfp-loading"),b.updateStatus("ready")),d):(b.updateStatus("loading"),c.loading=!0,c.hasSize||(c.imgHidden=!0,d.addClass("mfp-loading"),b.findImageSize(c)),d)}}});var N,O=function(){return void 0===N&&(N=void 0!==document.createElement("p").style.MozTransform),N};a.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(a){return a.is("img")?a:a.find("img")}},proto:{initZoom:function(){var a,c=b.st.zoom,d=".zoom";if(c.enabled&&b.supportsTransition){var e,f,g=c.duration,j=function(a){var b=a.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),d="all "+c.duration/1e3+"s "+c.easing,e={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},f="transition";return e["-webkit-"+f]=e["-moz-"+f]=e["-o-"+f]=e[f]=d,b.css(e),b},k=function(){b.content.css("visibility","visible")};w("BuildControls"+d,function(){if(b._allowZoom()){if(clearTimeout(e),b.content.css("visibility","hidden"),a=b._getItemToZoom(),!a)return void k();f=j(a),f.css(b._getOffset()),b.wrap.append(f),e=setTimeout(function(){f.css(b._getOffset(!0)),e=setTimeout(function(){k(),setTimeout(function(){f.remove(),a=f=null,y("ZoomAnimationEnded")},16)},g)},16)}}),w(i+d,function(){if(b._allowZoom()){if(clearTimeout(e),b.st.removalDelay=g,!a){if(a=b._getItemToZoom(),!a)return;f=j(a)}f.css(b._getOffset(!0)),b.wrap.append(f),b.content.css("visibility","hidden"),setTimeout(function(){f.css(b._getOffset())},16)}}),w(h+d,function(){b._allowZoom()&&(k(),f&&f.remove(),a=null)})}},_allowZoom:function(){return"image"===b.currItem.type},_getItemToZoom:function(){return b.currItem.hasSize?b.currItem.img:!1},_getOffset:function(c){var d;d=c?b.currItem.img:b.st.zoom.opener(b.currItem.el||b.currItem);var e=d.offset(),f=parseInt(d.css("padding-top"),10),g=parseInt(d.css("padding-bottom"),10);e.top-=a(window).scrollTop()-f;var h={width:d.width(),height:(u?d.innerHeight():d[0].offsetHeight)-g-f};return O()?h["-moz-transform"]=h.transform="translate("+e.left+"px,"+e.top+"px)":(h.left=e.left,h.top=e.top),h}}});var P="iframe",Q="//about:blank",R=function(a){if(b.currTemplate[P]){var c=b.currTemplate[P].find("iframe");c.length&&(a||(c[0].src=Q),b.isIE8&&c.css("display",a?"block":"none"))}};a.magnificPopup.registerModule(P,{options:{markup:'
',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){b.types.push(P),w("BeforeChange",function(a,b,c){b!==c&&(b===P?R():c===P&&R(!0))}),w(h+"."+P,function(){R()})},getIframe:function(c,d){var e=c.src,f=b.st.iframe;a.each(f.patterns,function(){return e.indexOf(this.index)>-1?(this.id&&(e="string"==typeof this.id?e.substr(e.lastIndexOf(this.id)+this.id.length,e.length):this.id.call(this,e)),e=this.src.replace("%id%",e),!1):void 0});var g={};return f.srcAction&&(g[f.srcAction]=e),b._parseMarkup(d,g,c),b.updateStatus("ready"),d}}});var S=function(a){var c=b.items.length;return a>c-1?a-c:0>a?c+a:a},T=function(a,b,c){return a.replace(/%curr%/gi,b+1).replace(/%total%/gi,c)};a.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'
',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var c=b.st.gallery,e=".mfp-gallery",g=Boolean(a.fn.mfpFastClick);return b.direction=!0,c&&c.enabled?(f+=" mfp-gallery",w(m+e,function(){c.navigateByImgClick&&b.wrap.on("click"+e,".mfp-img",function(){return b.items.length>1?(b.next(),!1):void 0}),d.on("keydown"+e,function(a){37===a.keyCode?b.prev():39===a.keyCode&&b.next()})}),w("UpdateStatus"+e,function(a,c){c.text&&(c.text=T(c.text,b.currItem.index,b.items.length))}),w(l+e,function(a,d,e,f){var g=b.items.length;e.counter=g>1?T(c.tCounter,f.index,g):""}),w("BuildControls"+e,function(){if(b.items.length>1&&c.arrows&&!b.arrowLeft){var d=c.arrowMarkup,e=b.arrowLeft=a(d.replace(/%title%/gi,c.tPrev).replace(/%dir%/gi,"left")).addClass(s),f=b.arrowRight=a(d.replace(/%title%/gi,c.tNext).replace(/%dir%/gi,"right")).addClass(s),h=g?"mfpFastClick":"click";e[h](function(){b.prev()}),f[h](function(){b.next()}),b.isIE7&&(x("b",e[0],!1,!0),x("a",e[0],!1,!0),x("b",f[0],!1,!0),x("a",f[0],!1,!0)),b.container.append(e.add(f))}}),w(n+e,function(){b._preloadTimeout&&clearTimeout(b._preloadTimeout),b._preloadTimeout=setTimeout(function(){b.preloadNearbyImages(),b._preloadTimeout=null},16)}),void w(h+e,function(){d.off(e),b.wrap.off("click"+e),b.arrowLeft&&g&&b.arrowLeft.add(b.arrowRight).destroyMfpFastClick(),b.arrowRight=b.arrowLeft=null})):!1},next:function(){b.direction=!0,b.index=S(b.index+1),b.updateItemHTML()},prev:function(){b.direction=!1,b.index=S(b.index-1),b.updateItemHTML()},goTo:function(a){b.direction=a>=b.index,b.index=a,b.updateItemHTML()},preloadNearbyImages:function(){var a,c=b.st.gallery.preload,d=Math.min(c[0],b.items.length),e=Math.min(c[1],b.items.length);for(a=1;a<=(b.direction?e:d);a++)b._preloadItem(b.index+a);for(a=1;a<=(b.direction?d:e);a++)b._preloadItem(b.index-a)},_preloadItem:function(c){if(c=S(c),!b.items[c].preloaded){var d=b.items[c];d.parsed||(d=b.parseEl(c)),y("LazyLoad",d),"image"===d.type&&(d.img=a('
![]()
').on("load.mfploader",function(){d.hasSize=!0}).on("error.mfploader",function(){d.hasSize=!0,d.loadError=!0,y("LazyLoadError",d)}).attr("src",d.src)),d.preloaded=!0}}}});var U="retina";a.magnificPopup.registerModule(U,{options:{replaceSrc:function(a){return a.src.replace(/\.\w+$/,function(a){return"@2x"+a})},ratio:1},proto:{initRetina:function(){if(window.devicePixelRatio>1){var a=b.st.retina,c=a.ratio;c=isNaN(c)?c():c,c>1&&(w("ImageHasSize."+U,function(a,b){b.img.css({"max-width":b.img[0].naturalWidth/c,width:"100%"})}),w("ElementParse."+U,function(b,d){d.src=a.replaceSrc(d,c)}))}}}}),function(){var b=1e3,c="ontouchstart"in window,d=function(){v.off("touchmove"+f+" touchend"+f)},e="mfpFastClick",f="."+e;a.fn.mfpFastClick=function(e){return a(this).each(function(){var g,h=a(this);if(c){var i,j,k,l,m,n;h.on("touchstart"+f,function(a){l=!1,n=1,m=a.originalEvent?a.originalEvent.touches[0]:a.touches[0],j=m.clientX,k=m.clientY,v.on("touchmove"+f,function(a){m=a.originalEvent?a.originalEvent.touches:a.touches,n=m.length,m=m[0],(Math.abs(m.clientX-j)>10||Math.abs(m.clientY-k)>10)&&(l=!0,d())}).on("touchend"+f,function(a){d(),l||n>1||(g=!0,a.preventDefault(),clearTimeout(i),i=setTimeout(function(){g=!1},b),e())})})}h.on("click"+f,function(){g||e()})})},a.fn.destroyMfpFastClick=function(){a(this).off("touchstart"+f+" click"+f),c&&v.off("touchmove"+f+" touchend"+f)}}(),A()});
/*
* jquery.mb.components
* file: jquery.mb.YTPlayer.js
* last modified: 19/08/14 20.13
* Open Lab s.r.l., Florence - Italy
* email: matteo@open-lab.com
* site: http://pupunzi.com
* http://open-lab.com
* blog: http://pupunzi.open-lab.com
* Q&A: http://jquery.pupunzi.com
* Licences: MIT, GPL
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Copyright (c) 2001-2014. Matteo Bicocchi (Pupunzi);
*/
function onYouTubePlayerAPIReady(){ytp.YTAPIReady||(ytp.YTAPIReady=!0,jQuery(document).trigger("YTAPIReady"))}var ytp=ytp||{};!function(jQuery,ytp){var nAgt=navigator.userAgent;if(!jQuery.browser){jQuery.browser={},jQuery.browser.mozilla=!1,jQuery.browser.webkit=!1,jQuery.browser.opera=!1,jQuery.browser.safari=!1,jQuery.browser.chrome=!1,jQuery.browser.msie=!1,jQuery.browser.ua=nAgt,jQuery.browser.name=navigator.appName,jQuery.browser.fullVersion=""+parseFloat(navigator.appVersion),jQuery.browser.majorVersion=parseInt(navigator.appVersion,10);var nameOffset,verOffset,ix;if(-1!=(verOffset=nAgt.indexOf("Opera")))jQuery.browser.opera=!0,jQuery.browser.name="Opera",jQuery.browser.fullVersion=nAgt.substring(verOffset+6),-1!=(verOffset=nAgt.indexOf("Version"))&&(jQuery.browser.fullVersion=nAgt.substring(verOffset+8));else if(-1!=(verOffset=nAgt.indexOf("MSIE")))jQuery.browser.msie=!0,jQuery.browser.name="Microsoft Internet Explorer",jQuery.browser.fullVersion=nAgt.substring(verOffset+5);else if(-1!=nAgt.indexOf("Trident")){jQuery.browser.msie=!0,jQuery.browser.name="Microsoft Internet Explorer";var start=nAgt.indexOf("rv:")+3,end=start+4;jQuery.browser.fullVersion=nAgt.substring(start,end)}else-1!=(verOffset=nAgt.indexOf("Chrome"))?(jQuery.browser.webkit=!0,jQuery.browser.chrome=!0,jQuery.browser.name="Chrome",jQuery.browser.fullVersion=nAgt.substring(verOffset+7)):-1!=(verOffset=nAgt.indexOf("Safari"))?(jQuery.browser.webkit=!0,jQuery.browser.safari=!0,jQuery.browser.name="Safari",jQuery.browser.fullVersion=nAgt.substring(verOffset+7),-1!=(verOffset=nAgt.indexOf("Version"))&&(jQuery.browser.fullVersion=nAgt.substring(verOffset+8))):-1!=(verOffset=nAgt.indexOf("AppleWebkit"))?(jQuery.browser.webkit=!0,jQuery.browser.name="Safari",jQuery.browser.fullVersion=nAgt.substring(verOffset+7),-1!=(verOffset=nAgt.indexOf("Version"))&&(jQuery.browser.fullVersion=nAgt.substring(verOffset+8))):-1!=(verOffset=nAgt.indexOf("Firefox"))?(jQuery.browser.mozilla=!0,jQuery.browser.name="Firefox",jQuery.browser.fullVersion=nAgt.substring(verOffset+8)):(nameOffset=nAgt.lastIndexOf(" ")+1)<(verOffset=nAgt.lastIndexOf("/"))&&(jQuery.browser.name=nAgt.substring(nameOffset,verOffset),jQuery.browser.fullVersion=nAgt.substring(verOffset+1),jQuery.browser.name.toLowerCase()==jQuery.browser.name.toUpperCase()&&(jQuery.browser.name=navigator.appName));-1!=(ix=jQuery.browser.fullVersion.indexOf(";"))&&(jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix)),-1!=(ix=jQuery.browser.fullVersion.indexOf(" "))&&(jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix)),jQuery.browser.majorVersion=parseInt(""+jQuery.browser.fullVersion,10),isNaN(jQuery.browser.majorVersion)&&(jQuery.browser.fullVersion=""+parseFloat(navigator.appVersion),jQuery.browser.majorVersion=parseInt(navigator.appVersion,10)),jQuery.browser.version=jQuery.browser.majorVersion}jQuery.browser.android=/Android/i.test(nAgt),jQuery.browser.blackberry=/BlackBerry|BB|PlayBook/i.test(nAgt),jQuery.browser.ios=/iPhone|iPad|iPod|webOS/i.test(nAgt),jQuery.browser.operaMobile=/Opera Mini/i.test(nAgt),jQuery.browser.kindle=/Kindle|Silk/i.test(nAgt),jQuery.browser.windowsMobile=/IEMobile|Windows Phone/i.test(nAgt),jQuery.browser.mobile=jQuery.browser.android||jQuery.browser.blackberry||jQuery.browser.ios||jQuery.browser.windowsMobile||jQuery.browser.operaMobile||jQuery.browser.kindle,jQuery.fn.CSSAnimate=function(a,b,c,d,e){function f(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}function g(a,b){return"string"!=typeof a||a.match(/^[\-0-9\.]+$/)?""+a+b:a}return jQuery.support.CSStransition=function(){var a=(document.body||document.documentElement).style;return void 0!==a.transition||void 0!==a.WebkitTransition||void 0!==a.MozTransition||void 0!==a.MsTransition||void 0!==a.OTransition}(),this.each(function(){var h=this,i=jQuery(this);h.id=h.id||"CSSA_"+(new Date).getTime();var j=j||{type:"noEvent"};if(h.CSSAIsRunning&&h.eventType==j.type)h.CSSqueue=function(){i.CSSAnimate(a,b,c,d,e)};else if(h.CSSqueue=null,h.eventType=j.type,0!==i.length&&a){if(h.CSSAIsRunning=!0,"function"==typeof b&&(e=b,b=jQuery.fx.speeds._default),"function"==typeof c&&(e=c,c=0),"function"==typeof d&&(e=d,d="cubic-bezier(0.65,0.03,0.36,0.72)"),"string"==typeof b)for(var k in jQuery.fx.speeds){if(b==k){b=jQuery.fx.speeds[k];break}b=jQuery.fx.speeds._default}if(b||(b=jQuery.fx.speeds._default),jQuery.support.CSStransition){j={"default":"ease","in":"ease-in",out:"ease-out","in-out":"ease-in-out",snap:"cubic-bezier(0,1,.5,1)",easeOutCubic:"cubic-bezier(.215,.61,.355,1)",easeInOutCubic:"cubic-bezier(.645,.045,.355,1)",easeInCirc:"cubic-bezier(.6,.04,.98,.335)",easeOutCirc:"cubic-bezier(.075,.82,.165,1)",easeInOutCirc:"cubic-bezier(.785,.135,.15,.86)",easeInExpo:"cubic-bezier(.95,.05,.795,.035)",easeOutExpo:"cubic-bezier(.19,1,.22,1)",easeInOutExpo:"cubic-bezier(1,0,0,1)",easeInQuad:"cubic-bezier(.55,.085,.68,.53)",easeOutQuad:"cubic-bezier(.25,.46,.45,.94)",easeInOutQuad:"cubic-bezier(.455,.03,.515,.955)",easeInQuart:"cubic-bezier(.895,.03,.685,.22)",easeOutQuart:"cubic-bezier(.165,.84,.44,1)",easeInOutQuart:"cubic-bezier(.77,0,.175,1)",easeInQuint:"cubic-bezier(.755,.05,.855,.06)",easeOutQuint:"cubic-bezier(.23,1,.32,1)",easeInOutQuint:"cubic-bezier(.86,0,.07,1)",easeInSine:"cubic-bezier(.47,0,.745,.715)",easeOutSine:"cubic-bezier(.39,.575,.565,1)",easeInOutSine:"cubic-bezier(.445,.05,.55,.95)",easeInBack:"cubic-bezier(.6,-.28,.735,.045)",easeOutBack:"cubic-bezier(.175, .885,.32,1.275)",easeInOutBack:"cubic-bezier(.68,-.55,.265,1.55)"},j[d]&&(d=j[d]);var l="",m="transitionEnd";jQuery.browser.webkit?(l="-webkit-",m="webkitTransitionEnd"):jQuery.browser.mozilla?(l="-moz-",m="transitionend"):jQuery.browser.opera?(l="-o-",m="otransitionend"):jQuery.browser.msie&&(l="-ms-",m="msTransitionEnd"),j=[];for(n in a)k=n,"transform"===k&&(k=l+"transform",a[k]=a[n],delete a[n]),"filter"===k&&(k=l+"filter",a[k]=a[n],delete a[n]),("transform-origin"===k||"origin"===k)&&(k=l+"transform-origin",a[k]=a[n],delete a[n]),"x"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" translateX("+g(a[n],"px")+")",delete a[n]),"y"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" translateY("+g(a[n],"px")+")",delete a[n]),"z"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" translateZ("+g(a[n],"px")+")",delete a[n]),"rotate"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" rotate("+g(a[n],"deg")+")",delete a[n]),"rotateX"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" rotateX("+g(a[n],"deg")+")",delete a[n]),"rotateY"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" rotateY("+g(a[n],"deg")+")",delete a[n]),"rotateZ"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" rotateZ("+g(a[n],"deg")+")",delete a[n]),"scale"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" scale("+g(a[n],"")+")",delete a[n]),"scaleX"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" scaleX("+g(a[n],"")+")",delete a[n]),"scaleY"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" scaleY("+g(a[n],"")+")",delete a[n]),"scaleZ"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" scaleZ("+g(a[n],"")+")",delete a[n]),"skew"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" skew("+g(a[n],"deg")+")",delete a[n]),"skewX"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" skewX("+g(a[n],"deg")+")",delete a[n]),"skewY"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" skewY("+g(a[n],"deg")+")",delete a[n]),"perspective"===k&&(k=l+"transform",a[k]=a[k]||"",a[k]+=" perspective("+g(a[n],"px")+")",delete a[n]),0>j.indexOf(k)&&j.push(f(k));var n=j.join(","),o=function(){i.off(m+"."+h.id),clearTimeout(h.timeout),i.css(l+"transition",""),"function"==typeof e&&e(i),h.called=!0,h.CSSAIsRunning=!1,"function"==typeof h.CSSqueue&&(h.CSSqueue(),h.CSSqueue=null)},p={};jQuery.extend(p,a),p[l+"transition-property"]=n,p[l+"transition-duration"]=b+"ms",p[l+"transition-delay"]=c+"ms",p[l+"transition-style"]="preserve-3d",p[l+"transition-timing-function"]=d,setTimeout(function(){i.one(m+"."+h.id,o),i.css(p)},1),h.timeout=setTimeout(function(){i.called||!e?(i.called=!1,h.CSSAIsRunning=!1):(i.css(l+"transition",""),e(i),h.CSSAIsRunning=!1,"function"==typeof h.CSSqueue&&(h.CSSqueue(),h.CSSqueue=null))},b+c+100)}else{for(var n in a)"transform"===n&&delete a[n],"filter"===n&&delete a[n],"transform-origin"===n&&delete a[n],"auto"===a[n]&&delete a[n];e&&"string"!=typeof e||(e="linear"),i.animate(a,b,e)}}})};var getYTPVideoID=function(a){var b,c;return a.indexOf("youtu.be")>0?(b=a.substr(a.lastIndexOf("/")+1,a.length),c=b.indexOf("?list=")>0?b.substr(b.lastIndexOf("="),b.length):null,b=c?b.substr(0,b.lastIndexOf("?")):b):a.indexOf("http")>-1?(b=a.match(/[\\?&]v=([^]*)/)[1],c=a.indexOf("list=")>0?a.match(/[\\?&]list=([^]*)/)[1]:null):(b=a.length>15?null:a,c=b?null:a),{videoID:b,playlistID:c}};jQuery.mbYTPlayer={name:"jquery.mb.YTPlayer",version:"2.8.0",author:"Matteo Bicocchi",defaults:{containment:"body",ratio:"auto",videoURL:null,playlistURL:null,startAt:0,stopAt:0,autoPlay:!0,vol:100,addRaster:!1,opacity:1,quality:"default",mute:!1,loop:!0,showControls:!0,showAnnotations:!1,showYTLogo:!0,stopMovieOnClick:!1,stopMovieOnBlur:!0,realfullscreen:!0,gaTrack:!0,optimizeDisplay:!0,onReady:function(){}},controls:{play:"P",pause:"p",mute:"M",unmute:"A",onlyYT:"O",showSite:"R",ytLogo:"Y"},locationProtocol:"https:",buildPlayer:function(options){return this.each(function(){var YTPlayer=this,$YTPlayer=jQuery(YTPlayer);YTPlayer.loop=0,YTPlayer.opt={},$YTPlayer.addClass("mb_YTPlayer");var property=$YTPlayer.data("property")&&"string"==typeof $YTPlayer.data("property")?eval("("+$YTPlayer.data("property")+")"):$YTPlayer.data("property");"undefined"!=typeof property&&"undefined"!=typeof property.vol&&(property.vol=0==property.vol?property.vol=1:property.vol),jQuery.extend(YTPlayer.opt,jQuery.mbYTPlayer.defaults,options,property);var isIframe=function(){var a=!1;try{self.location.href!=top.location.href&&(a=!0)}catch(b){a=!0}return a},canGoFullScreen=!(jQuery.browser.msie||jQuery.browser.opera||isIframe());canGoFullScreen||(YTPlayer.opt.realfullscreen=!1),$YTPlayer.attr("id")||$YTPlayer.attr("id","video_"+(new Date).getTime());var playerID="mbYTP_"+YTPlayer.id;YTPlayer.isAlone=!1,YTPlayer.hasFocus=!0;var videoID=this.opt.videoURL?getYTPVideoID(this.opt.videoURL).videoID:$YTPlayer.attr("href")?getYTPVideoID($YTPlayer.attr("href")).videoID:!1,playlistID=this.opt.videoURL?getYTPVideoID(this.opt.videoURL).playlistID:$YTPlayer.attr("href")?getYTPVideoID($YTPlayer.attr("href")).playlistID:!1;YTPlayer.videoID=videoID,YTPlayer.playlistID=playlistID,YTPlayer.opt.showAnnotations=YTPlayer.opt.showAnnotations?"0":"3";var playerVars={autoplay:0,modestbranding:1,controls:0,showinfo:0,rel:0,enablejsapi:1,version:3,playerapiid:playerID,origin:"*",allowfullscreen:!0,wmode:"transparent",iv_load_policy:YTPlayer.opt.showAnnotations},v=document.createElement("video");v.canPlayType&&jQuery.extend(playerVars,{html5:1}),jQuery.browser.msie&&jQuery.browser.version<9&&(this.opt.opacity=1);var playerBox=jQuery("
").attr("id",playerID).addClass("playerBox"),overlay=jQuery("
").css({position:"absolute",top:0,left:0,width:"100%",height:"100%"}).addClass("YTPOverlay");if(YTPlayer.isSelf="self"==YTPlayer.opt.containment,YTPlayer.opt.containment="self"==YTPlayer.opt.containment?jQuery(this):jQuery(YTPlayer.opt.containment),YTPlayer.isBackground="body"==YTPlayer.opt.containment.get(0).tagName.toLowerCase(),!YTPlayer.isBackground||!ytp.backgroundIsInited){var isPlayer=YTPlayer.opt.containment.is(jQuery(this));if(YTPlayer.canPlayOnMobile=isPlayer&&0==jQuery(this).children().length,isPlayer?YTPlayer.isPlayer=!0:$YTPlayer.hide(),jQuery.browser.mobile&&!YTPlayer.canPlayOnMobile)return $YTPlayer.remove(),void 0;if(YTPlayer.opt.addRaster){var classN="dot"==YTPlayer.opt.addRaster?"raster-dot":"raster",retina=window.retina||window.devicePixelRatio>1;overlay.addClass(retina?classN+" retina":classN)}else overlay.removeClass(function(a,b){var c=b.split(" "),d=[];return jQuery.each(c,function(a,b){/raster-.*/.test(b)&&d.push(b)}),d.push("retina"),d.join(" ")});var wrapper=jQuery("
").addClass("mbYTP_wrapper").attr("id","wrapper_"+playerID);if(wrapper.css({position:"absolute",zIndex:0,minWidth:"100%",minHeight:"100%",left:0,top:0,overflow:"hidden",opacity:0}),playerBox.css({position:"absolute",zIndex:0,width:"100%",height:"100%",top:0,left:0,overflow:"hidden"}),wrapper.append(playerBox),YTPlayer.opt.containment.children().not("script, style").each(function(){"static"==jQuery(this).css("position")&&jQuery(this).css("position","relative")}),YTPlayer.isBackground?(jQuery("body").css({boxSizing:"border-box"}),wrapper.css({position:"fixed",top:0,left:0,zIndex:0,webkitTransform:"translateZ(0)"}),$YTPlayer.hide()):"static"==YTPlayer.opt.containment.css("position")&&YTPlayer.opt.containment.css({position:"relative"}),YTPlayer.opt.containment.prepend(wrapper),YTPlayer.wrapper=wrapper,playerBox.css({opacity:1}),jQuery.browser.mobile||(playerBox.after(overlay),YTPlayer.overlay=overlay),YTPlayer.isBackground||overlay.on("mouseenter",function(){$YTPlayer.find(".mb_YTPBar").addClass("visible")}).on("mouseleave",function(){$YTPlayer.find(".mb_YTPBar").removeClass("visible")}),ytp.YTAPIReady)setTimeout(function(){jQuery(document).trigger("YTAPIReady")},100);else{jQuery("#YTAPI").remove();var tag=jQuery("").attr({src:jQuery.mbYTPlayer.locationProtocol+"//www.youtube.com/player_api?v="+jQuery.mbYTPlayer.version,id:"YTAPI"});jQuery("head title").after(tag)}jQuery(document).on("YTAPIReady",function(){YTPlayer.isBackground&&ytp.backgroundIsInited||YTPlayer.isInit||(YTPlayer.isBackground&&YTPlayer.opt.stopMovieOnClick&&jQuery(document).off("mousedown.ytplayer").on("mousedown.ytplayer",function(a){var b=jQuery(a.target);(b.is("a")||b.parents().is("a"))&&$YTPlayer.pauseYTP()}),YTPlayer.isBackground&&(ytp.backgroundIsInited=!0),YTPlayer.opt.autoPlay="undefined"==typeof YTPlayer.opt.autoPlay?YTPlayer.isBackground?!0:!1:YTPlayer.opt.autoPlay,YTPlayer.opt.vol=YTPlayer.opt.vol?YTPlayer.opt.vol:100,jQuery.mbYTPlayer.getDataFromFeed(YTPlayer),jQuery(YTPlayer).on("YTPChanged",function(){return YTPlayer.isInit?void 0:(YTPlayer.isInit=!0,jQuery.browser.mobile&&YTPlayer.canPlayOnMobile?(new YT.Player(playerID,{videoId:YTPlayer.videoID.toString(),height:"100%",width:"100%",videoId:YTPlayer.videoID,events:{onReady:function(a){YTPlayer.player=a.target,playerBox.css({opacity:1}),YTPlayer.wrapper.css({opacity:YTPlayer.opt.opacity}),$YTPlayer.optimizeDisplay()},onStateChange:function(){}}}),void 0):(new YT.Player(playerID,{videoId:YTPlayer.videoID.toString(),playerVars:playerVars,events:{onReady:function(a){if(YTPlayer.player=a.target,!YTPlayer.isReady){YTPlayer.isReady=!0,YTPlayer.playerEl=YTPlayer.player.getIframe(),$YTPlayer.optimizeDisplay(),YTPlayer.videoID=videoID,jQuery(window).on("resize.YTP",function(){$YTPlayer.optimizeDisplay()}),YTPlayer.opt.showControls&&jQuery(YTPlayer).buildYTPControls();var b=YTPlayer.opt.startAt?YTPlayer.opt.startAt:1;YTPlayer.player.setVolume(0),jQuery(YTPlayer).muteYTPVolume(),jQuery.mbYTPlayer.checkForState(YTPlayer),YTPlayer.checkForStartAt=setInterval(function(){var a=jQuery.browser.mozilla&&!window.MediaSource?!0:YTPlayer.player.getVideoLoadedFraction()>b/YTPlayer.player.getDuration();YTPlayer.player.getDuration()>0&&YTPlayer.player.getCurrentTime()>=b&&a?(clearInterval(YTPlayer.checkForStartAt),YTPlayer.player.setVolume(0),jQuery(YTPlayer).muteYTPVolume(),"function"==typeof YTPlayer.opt.onReady&&YTPlayer.opt.onReady(YTPlayer),YTPlayer.opt.mute||jQuery(YTPlayer).unmuteYTP(),YTPlayer.player.pauseVideo(),setTimeout(function(){YTPlayer.canTrigger=!0,YTPlayer.opt.autoPlay?($YTPlayer.playYTP(),$YTPlayer.css("background-image","none"),YTPlayer.wrapper.CSSAnimate({opacity:YTPlayer.isAlone?1:YTPlayer.opt.opacity},2e3)):YTPlayer.player.pauseVideo()},100)):(YTPlayer.player.playVideo(),YTPlayer.player.seekTo(b,!0))},1e3)}},onStateChange:function(event){if("function"==typeof event.target.getPlayerState){var state=event.target.getPlayerState();if(YTPlayer.state!=state){YTPlayer.state=state;var controls=jQuery("#controlBar_"+YTPlayer.id),eventType;switch(state){case-1:eventType="YTPUnstarted";break;case 0:eventType="YTPEnd";break;case 1:eventType="YTPStart",controls.find(".mb_YTPPlaypause").html(jQuery.mbYTPlayer.controls.pause),"undefined"!=typeof _gaq&&eval(YTPlayer.opt.gaTrack)&&_gaq.push(["_trackEvent","YTPlayer","Play",YTPlayer.videoTitle||YTPlayer.videoID.toString()]),"undefined"!=typeof ga&&eval(YTPlayer.opt.gaTrack)&&ga("send","event","YTPlayer","play",YTPlayer.videoTitle||YTPlayer.videoID.toString());break;case 2:eventType="YTPPause",controls.find(".mb_YTPPlaypause").html(jQuery.mbYTPlayer.controls.play);break;case 3:jQuery.browser.chrome||YTPlayer.player.setPlaybackQuality(YTPlayer.opt.quality),eventType="YTPBuffering",jQuery.browser.chrome||YTPlayer.player.setPlaybackQuality(YTPlayer.opt.quality),controls.find(".mb_YTPPlaypause").html(jQuery.mbYTPlayer.controls.play),setTimeout(function(){controls.show(1e3)},2e3);break;case 5:eventType="YTPCued"}var YTPevent=jQuery.Event(eventType);YTPevent.time=YTPlayer.player.time,YTPlayer.canTrigger&&jQuery(YTPlayer).trigger(YTPevent)}}},onPlaybackQualityChange:function(a){var b=a.target.getPlaybackQuality(),c=jQuery.Event("YTPQualityChange");c.quality=b,jQuery(YTPlayer).trigger(c)},onError:function(a){150==a.data&&(console.log("Embedding this video is restricted by Youtube."),YTPlayer.isPlayList&&jQuery(YTPlayer).playNext()),2==a.data&&YTPlayer.isPlayList&&jQuery(YTPlayer).playNext(),"function"==typeof YTPlayer.opt.onError&&YTPlayer.opt.onError($YTPlayer,a)}}}),void 0))}))})}})},getDataFromFeed:function(a){jQuery.browser.msie&&jQuery.browser.version<=9?("auto"==a.opt.ratio?a.opt.ratio="16/9":a.opt.ratio,a.hasData||(a.hasData=!0,setTimeout(function(){jQuery(a).trigger("YTPChanged")},100))):(jQuery.getJSON(jQuery.mbYTPlayer.locationProtocol+"//gdata.youtube.com/feeds/api/videos/"+a.videoID+"?v=2&alt=jsonc",function(b){a.dataReceived=!0,a.videoData=b.data,jQuery(a).trigger("YTPChanged");var e=jQuery.Event("YTPData");e.prop={};for(var f in a.videoData)e.prop[f]=a.videoData[f];if(jQuery(a).trigger(e),a.videoTitle=a.videoData.title,"auto"==a.opt.ratio&&(a.opt.ratio=a.videoData.aspectRatio&&"widescreen"===a.videoData.aspectRatio?"16/9":"4/3"),!a.hasData&&(a.hasData=!0,a.isPlayer)){var g=a.videoData.thumbnail.hqDefault;a.opt.containment.css({background:"rgba(0,0,0,0.5) url("+g+") center center",backgroundSize:"cover"})}}),setTimeout(function(){a.dataReceived||a.hasData||(a.hasData=!0,jQuery(a).trigger("YTPChanged"))},1500))},getVideoData:function(){var a=this.get(0);return a.videoData},getVideoID:function(){var a=this.get(0);return a.videoID||!1},setVideoQuality:function(a){var b=this.get(0);jQuery.browser.chrome||b.player.setPlaybackQuality(a)},YTPlaylist:function(a,b,c){var d=this.get(0);d.isPlayList=!0,b&&(a=jQuery.shuffle(a)),d.videoID||(d.videos=a,d.videoCounter=0,d.videoLength=a.length,jQuery(d).data("property",a[0]),jQuery(d).mb_YTPlayer()),"function"==typeof c&&jQuery(d).on("YTPChanged",function(){c(d)}),jQuery(d).on("YTPEnd",function(){jQuery(d).playNext()})},playNext:function(){var a=this.get(0);a.videoCounter++,a.videoCounter>=a.videoLength&&(a.videoCounter=0),jQuery(a.playerEl).css({opacity:0}),jQuery(a).changeMovie(a.videos[a.videoCounter])},playPrev:function(){var a=this.get(0);a.videoCounter--,a.videoCounter<0&&(a.videoCounter=a.videoLength-1),jQuery(a.playerEl).css({opacity:0}),jQuery(a).changeMovie(a.videos[a.videoCounter])},changeMovie:function(a){var b=this.get(0);b.opt.startAt=0,b.opt.stopAt=0,b.opt.mute=!0,a&&jQuery.extend(b.opt,a),b.videoID=getYTPVideoID(b.opt.videoURL).videoID,jQuery(b).pauseYTP();var c=jQuery.browser.msie?1e3:0;if(jQuery(b.playerEl).CSSAnimate({opacity:0},c),setTimeout(function(){var a=jQuery.browser.chrome?"default":b.opt.quality;jQuery(b).getPlayer().cueVideoByUrl(encodeURI(jQuery.mbYTPlayer.locationProtocol+"//www.youtube.com/v/"+b.videoID),1,a),jQuery(b).playYTP(),jQuery(b).one("YTPStart",function(){b.wrapper.CSSAnimate({opacity:b.isAlone?1:b.opt.opacity},1e3),jQuery(b.playerEl).CSSAnimate({opacity:1},c),b.opt.startAt&&b.player.seekTo(b.opt.startAt),jQuery.mbYTPlayer.checkForState(b),b.opt.autoPlay||jQuery(b).pauseYTP()}),b.opt.mute?jQuery(b).muteYTPVolume():jQuery(b).unmuteYTP()},c),b.opt.addRaster){var d=window.retina||window.devicePixelRatio>1;b.overlay.addClass(d?"raster retina":"raster")}else b.overlay.removeClass("raster"),b.overlay.removeClass("retina");jQuery("#controlBar_"+b.id).remove(),b.opt.showControls&&jQuery(b).buildYTPControls(),jQuery.mbYTPlayer.getDataFromFeed(b),jQuery(b).optimizeDisplay()},getPlayer:function(){return jQuery(this).get(0).player},playerDestroy:function(){var a=this.get(0);ytp.YTAPIReady=!1,ytp.backgroundIsInited=!1,a.isInit=!1,a.videoID=null;var b=a.wrapper;b.remove(),jQuery("#controlBar_"+a.id).remove()},fullscreen:function(real){function RunPrefixMethod(a,b){for(var e,f,c=["webkit","moz","ms","o",""],d=0;d
0||a&&b.player.getVolume()==a?jQuery(b).muteYTPVolume():b.opt.vol=a:jQuery(b).unmuteYTP(),b.player.setVolume(b.opt.vol)},muteYTP:function(){var a=this.get(0);a.player.mute(),a.player.setVolume(0);var b=jQuery("#controlBar_"+a.id),c=b.find(".mb_YTPMuteUnmute");c.html(jQuery.mbYTPlayer.controls.unmute),jQuery(a).addClass("isMuted"),jQuery(a).trigger("YTPMuted")},unmuteYTP:function(){var a=this.get(0);a.player.unMute(),a.player.setVolume(a.opt.vol);var b=jQuery("#controlBar_"+a.id),c=b.find(".mb_YTPMuteUnmute");c.html(jQuery.mbYTPlayer.controls.mute),jQuery(a).removeClass("isMuted"),jQuery(a).trigger("YTPUnmuted")},manageYTPProgress:function(){var a=this.get(0),b=jQuery("#controlBar_"+a.id),c=b.find(".mb_YTPProgress"),d=b.find(".mb_YTPLoaded"),e=b.find(".mb_YTPseekbar"),f=c.outerWidth(),g=Math.floor(a.player.getCurrentTime()),h=Math.floor(a.player.getDuration()),i=g*f/h,j=0,k=100*a.player.getVideoLoadedFraction();return d.css({left:j,width:k+"%"}),e.css({left:0,width:i}),{totalTime:h,currentTime:g}},buildYTPControls:function(){var YTPlayer=this.get(0),data=YTPlayer.opt;if(data.showYTLogo=data.showYTLogo||data.printUrl,!jQuery("#controlBar_"+YTPlayer.id).length){var controlBar=jQuery("").attr("id","controlBar_"+YTPlayer.id).addClass("mb_YTPBar").css({whiteSpace:"noWrap",position:YTPlayer.isBackground?"fixed":"absolute",zIndex:YTPlayer.isBackground?1e4:1e3}).hide();YTPlayer.controlBar=controlBar;var buttonBar=jQuery("").addClass("buttonBar"),playpause=jQuery(""+jQuery.mbYTPlayer.controls.play+"").addClass("mb_YTPPlaypause ytpicon").click(function(){1==YTPlayer.player.getPlayerState()?jQuery(YTPlayer).pauseYTP():jQuery(YTPlayer).playYTP()}),MuteUnmute=jQuery(""+jQuery.mbYTPlayer.controls.mute+"").addClass("mb_YTPMuteUnmute ytpicon").click(function(){0==YTPlayer.player.getVolume()?jQuery(YTPlayer).unmuteYTP():jQuery(YTPlayer).muteYTP()}),idx=jQuery("").addClass("mb_YTPTime"),vURL=data.videoURL?data.videoURL:"";vURL.indexOf("http")<0&&(vURL=jQuery.mbYTPlayer.locationProtocol+"//www.youtube.com/watch?v="+data.videoURL);var movieUrl=jQuery("").html(jQuery.mbYTPlayer.controls.ytLogo).addClass("mb_YTPUrl ytpicon").attr("title","view on YouTube").on("click",function(){window.open(vURL,"viewOnYT")}),onlyVideo=jQuery("").html(jQuery.mbYTPlayer.controls.onlyYT).addClass("mb_OnlyYT ytpicon").on("click",function(){jQuery(YTPlayer).fullscreen(data.realfullscreen)}),progressBar=jQuery("").addClass("mb_YTPProgress").css("position","absolute").click(function(a){timeBar.css({width:a.clientX-timeBar.offset().left}),YTPlayer.timeW=a.clientX-timeBar.offset().left,controlBar.find(".mb_YTPLoaded").css({width:0});var b=Math.floor(YTPlayer.player.getDuration());YTPlayer.goto=timeBar.outerWidth()*b/progressBar.outerWidth(),YTPlayer.player.seekTo(parseFloat(YTPlayer.goto),!0),controlBar.find(".mb_YTPLoaded").css({width:0})}),loadedBar=jQuery("").addClass("mb_YTPLoaded").css("position","absolute"),timeBar=jQuery("").addClass("mb_YTPseekbar").css("position","absolute");progressBar.append(loadedBar).append(timeBar),buttonBar.append(playpause).append(MuteUnmute).append(idx),data.showYTLogo&&buttonBar.append(movieUrl),(YTPlayer.isBackground||eval(YTPlayer.opt.realfullscreen)&&!YTPlayer.isBackground)&&buttonBar.append(onlyVideo),controlBar.append(buttonBar).append(progressBar),YTPlayer.isBackground?jQuery("body").after(controlBar):(controlBar.addClass("inlinePlayer"),YTPlayer.wrapper.before(controlBar))}},checkForState:function(YTPlayer){var interval=YTPlayer.opt.showControls?10:1e3;clearInterval(YTPlayer.getState),YTPlayer.getState=setInterval(function(){var prog=jQuery(YTPlayer).manageYTPProgress(),$YTPlayer=jQuery(YTPlayer),controlBar=jQuery("#controlBar_"+YTPlayer.id),data=YTPlayer.opt,startAt=YTPlayer.opt.startAt?YTPlayer.opt.startAt:1,stopAt=YTPlayer.opt.stopAt>YTPlayer.opt.startAt?YTPlayer.opt.stopAt:0;if(stopAt=stopAt0&&parseFloat(YTPlayer.player.getCurrentTime())>stopAt)){if(YTPlayer.isEnded)return;if(YTPlayer.isEnded=!0,setTimeout(function(){YTPlayer.isEnded=!1},2e3),YTPlayer.isPlayList){clearInterval(YTPlayer.getState);var YTPEnd=jQuery.Event("YTPEnd");return YTPEnd.time=YTPlayer.player.time,jQuery(YTPlayer).trigger(YTPEnd),void 0}data.loop?YTPlayer.player.seekTo(startAt,!0):(YTPlayer.player.pauseVideo(),YTPlayer.wrapper.CSSAnimate({opacity:0},1e3,function(){var a=jQuery.Event("YTPEnd");if(a.time=YTPlayer.player.time,jQuery(YTPlayer).trigger(a),YTPlayer.player.seekTo(startAt,!0),!YTPlayer.isBackground){var b=YTPlayer.videoData.thumbnail.hqDefault;jQuery(YTPlayer).css({background:"rgba(0,0,0,0.5) url("+b+") center center",backgroundSize:"cover"})}}))}},interval)},formatTime:function(a){var b=Math.floor(a/60),c=Math.floor(a-60*b);return(9>=b?"0"+b:b)+" : "+(9>=c?"0"+c:c)}},jQuery.fn.toggleVolume=function(){var a=this.get(0);if(a)return a.player.isMuted()?(jQuery(a).unmuteYTP(),!0):(jQuery(a).muteYTP(),!1)},jQuery.fn.optimizeDisplay=function(){var a=this.get(0),b=a.opt,c=jQuery(a.playerEl),d={},e=a.wrapper;d.width=e.outerWidth(),d.height=e.outerHeight();var f=24,g=100,h={};b.optimizeDisplay?(h.width=d.width+d.width*f/100,h.height="16/9"==b.ratio?Math.ceil(9*d.width/16):Math.ceil(3*d.width/4),h.marginTop=-((h.height-d.height)/2),h.marginLeft=-(d.width*(f/2)/100),h.height';
head.appendChild(div.childNodes[1]);
}
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
'iframe[src*="player.vimeo.com"]',
'iframe[src*="youtube.com"]',
'iframe[src*="youtube-nocookie.com"]',
'iframe[src*="kickstarter.com"][src*="video.html"]',
'object',
'embed'
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var ignoreList = '.fitvidsignore';
if(settings.ignore) {
ignoreList = ignoreList + ', ' + settings.ignore;
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos = $allVideos.not('object object'); // SwfObj conflict patch
$allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.
$allVideos.each(function(){
var $this = $(this);
if($this.parents(ignoreList).length > 0) {
return; // Disable FitVids on this video.
}
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width'))))
{
$this.attr('height', 9);
$this.attr('width', 16);
}
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+'%');
$this.removeAttr('height').removeAttr('width');
});
});
};
// Works with either jQuery or Zepto
})( window.jQuery || window.Zepto );
//===============================================
// ----------------- countTo -----------------
//===============================================
(function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
// set options for current element
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
// references & variables that will change with each update
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
// if an existing interval can be found, clear it first
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
// initialize the element with the starting value
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.text(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery));
//===============================================
// --------------- smoothscroll ---------------
//===============================================
// SmoothScroll for websites v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Michael Herf (Pulse Algorithm)
(function(){
// Scroll Variables (tweakable)
var defaultOptions = {
// Scrolling Core
frameRate : 150, // [Hz]
animationTime : 500, // [px]
stepSize : 150, // [px]
// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
pulseAlgorithm : true,
pulseScale : 4,
pulseNormalize : 1,
// Acceleration
accelerationDelta : 20, // 20
accelerationMax : 1, // 1
// Keyboard Settings
keyboardSupport : true, // option
arrowScroll : 50, // [px]
// Other
touchpadSupport : true,
fixedBackground : true,
excluded : ""
};
var options = defaultOptions;
// Other Variables
var isExcluded = false;
var isFrame = false;
var direction = { x: 0, y: 0 };
var initDone = false;
var root = document.documentElement;
var activeElement;
var observer;
var deltaBuffer = [ 120, 120, 120 ];
var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32,
pageup: 33, pagedown: 34, end: 35, home: 36 };
/***********************************************
* SETTINGS
***********************************************/
var options = defaultOptions;
/***********************************************
* INITIALIZE
***********************************************/
/**
* Tests if smooth scrolling is allowed. Shuts down everything if not.
*/
function initTest() {
var disableKeyboard = false;
// disable keyboard support if anything above requested it
if (disableKeyboard) {
removeEvent("keydown", keydown);
}
if (options.keyboardSupport && !disableKeyboard) {
addEvent("keydown", keydown);
}
}
/**
* Sets up scrolls array, determines if frames are involved.
*/
function init() {
if (!document.body) return;
var body = document.body;
var html = document.documentElement;
var windowHeight = window.innerHeight;
var scrollHeight = body.scrollHeight;
// check compat mode for root element
root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
activeElement = body;
initTest();
initDone = true;
// Checks if this script is running in a frame
if (top != self) {
isFrame = true;
}
/**
* This fixes a bug where the areas left and right to
* the content does not trigger the onmousewheel event
* on some pages. e.g.: html, body { height: 100% }
*/
else if (scrollHeight > windowHeight &&
(body.offsetHeight <= windowHeight ||
html.offsetHeight <= windowHeight)) {
// DOMChange (throttle): fix height
var pending = false;
var refresh = function () {
if (!pending && html.scrollHeight != document.height) {
pending = true; // add a new pending action
setTimeout(function () {
html.style.height = document.height + 'px';
pending = false;
}, 500); // act rarely to stay fast
}
};
html.style.height = 'auto';
setTimeout(refresh, 10);
// clearfix
if (root.offsetHeight <= windowHeight) {
var underlay = document.createElement("div");
underlay.style.clear = "both";
body.appendChild(underlay);
}
}
// disable fixed background
if (!options.fixedBackground && !isExcluded) {
body.style.backgroundAttachment = "scroll";
html.style.backgroundAttachment = "scroll";
}
}
/************************************************
* SCROLLING
************************************************/
var que = [];
var pending = false;
var lastScroll = +new Date;
/**
* Pushes scroll actions to the scrolling queue.
*/
function scrollArray(elem, left, top, delay) {
delay || (delay = 1000);
directionCheck(left, top);
if (options.accelerationMax != 1) {
var now = +new Date;
var elapsed = now - lastScroll;
if (elapsed < options.accelerationDelta) {
var factor = (1 + (30 / elapsed)) / 2;
if (factor > 1) {
factor = Math.min(factor, options.accelerationMax);
left *= factor;
top *= factor;
}
}
lastScroll = +new Date;
}
// push a scroll command
que.push({
x: left,
y: top,
lastX: (left < 0) ? 0.99 : -0.99,
lastY: (top < 0) ? 0.99 : -0.99,
start: +new Date
});
// don't act if there's a pending queue
if (pending) {
return;
}
var scrollWindow = (elem === document.body);
var step = function (time) {
var now = +new Date;
var scrollX = 0;
var scrollY = 0;
for (var i = 0; i < que.length; i++) {
var item = que[i];
var elapsed = now - item.start;
var finished = (elapsed >= options.animationTime);
// scroll position: [0, 1]
var position = (finished) ? 1 : elapsed / options.animationTime;
// easing [optional]
if (options.pulseAlgorithm) {
position = pulse(position);
}
// only need the difference
var x = (item.x * position - item.lastX) >> 0;
var y = (item.y * position - item.lastY) >> 0;
// add this to the total scrolling
scrollX += x;
scrollY += y;
// update last values
item.lastX += x;
item.lastY += y;
// delete and step back if it's over
if (finished) {
que.splice(i, 1); i--;
}
}
// scroll left and top
if (scrollWindow) {
window.scrollBy(scrollX, scrollY);
}
else {
if (scrollX) elem.scrollLeft += scrollX;
if (scrollY) elem.scrollTop += scrollY;
}
// clean up if there's nothing left to do
if (!left && !top) {
que = [];
}
if (que.length) {
requestFrame(step, elem, (delay / options.frameRate + 1));
} else {
pending = false;
}
};
// start a new queue of actions
requestFrame(step, elem, 0);
pending = true;
}
/***********************************************
* EVENTS
***********************************************/
/**
* Mouse wheel handler.
* @param {Object} event
*/
function wheel(event) {
if (!initDone) {
init();
}
var target = event.target;
var overflowing = overflowingAncestor(target);
// use default if there's no overflowing
// element or default action is prevented
if (!overflowing || event.defaultPrevented ||
isNodeName(activeElement, "embed") ||
(isNodeName(target, "embed") && /\.pdf/i.test(target.src))) {
return true;
}
var deltaX = event.wheelDeltaX || 0;
var deltaY = event.wheelDeltaY || 0;
// use wheelDelta if deltaX/Y is not available
if (!deltaX && !deltaY) {
deltaY = event.wheelDelta || 0;
}
// check if it's a touchpad scroll that should be ignored
if (!options.touchpadSupport && isTouchpad(deltaY)) {
return true;
}
// scale by step size
// delta is 120 most of the time
// synaptics seems to send 1 sometimes
if (Math.abs(deltaX) > 1.2) {
deltaX *= options.stepSize / 120;
}
if (Math.abs(deltaY) > 1.2) {
deltaY *= options.stepSize / 120;
}
scrollArray(overflowing, -deltaX, -deltaY);
event.preventDefault();
}
/**
* Keydown event handler.
* @param {Object} event
*/
function keydown(event) {
var target = event.target;
var modifier = event.ctrlKey || event.altKey || event.metaKey ||
(event.shiftKey && event.keyCode !== key.spacebar);
// do nothing if user is editing text
// or using a modifier key (except shift)
// or in a dropdown
if ( /input|textarea|select|embed/i.test(target.nodeName) ||
target.isContentEditable ||
event.defaultPrevented ||
modifier ) {
return true;
}
// spacebar should trigger button press
if (isNodeName(target, "button") &&
event.keyCode === key.spacebar) {
return true;
}
var shift, x = 0, y = 0;
var elem = overflowingAncestor(activeElement);
var clientHeight = elem.clientHeight;
if (elem == document.body) {
clientHeight = window.innerHeight;
}
switch (event.keyCode) {
case key.up:
y = -options.arrowScroll;
break;
case key.down:
y = options.arrowScroll;
break;
case key.spacebar: // (+ shift)
shift = event.shiftKey ? 1 : -1;
y = -shift * clientHeight * 0.9;
break;
case key.pageup:
y = -clientHeight * 0.9;
break;
case key.pagedown:
y = clientHeight * 0.9;
break;
case key.home:
y = -elem.scrollTop;
break;
case key.end:
var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
y = (damt > 0) ? damt+10 : 0;
break;
case key.left:
x = -options.arrowScroll;
break;
case key.right:
x = options.arrowScroll;
break;
default:
return true; // a key we don't care about
}
scrollArray(elem, x, y);
event.preventDefault();
}
/**
* Mousedown event only for updating activeElement
*/
function mousedown(event) {
activeElement = event.target;
}
/***********************************************
* OVERFLOW
***********************************************/
var cache = {}; // cleared out every once in while
setInterval(function () { cache = {}; }, 10 * 1000);
var uniqueID = (function () {
var i = 0;
return function (el) {
return el.uniqueID || (el.uniqueID = i++);
};
})();
function setCache(elems, overflowing) {
for (var i = elems.length; i--;)
cache[uniqueID(elems[i])] = overflowing;
return overflowing;
}
function overflowingAncestor(el) {
var elems = [];
var rootScrollHeight = root.scrollHeight;
do {
var cached = cache[uniqueID(el)];
if (cached) {
return setCache(elems, cached);
}
elems.push(el);
if (rootScrollHeight === el.scrollHeight) {
if (!isFrame || root.clientHeight + 10 < rootScrollHeight) {
return setCache(elems, document.body); // scrolling root in WebKit
}
} else if (el.clientHeight + 10 < el.scrollHeight) {
overflow = getComputedStyle(el, "").getPropertyValue("overflow-y");
if (overflow === "scroll" || overflow === "auto") {
return setCache(elems, el);
}
}
} while (el = el.parentNode);
}
/***********************************************
* HELPERS
***********************************************/
function addEvent(type, fn, bubble) {
window.addEventListener(type, fn, (bubble||false));
}
function removeEvent(type, fn, bubble) {
window.removeEventListener(type, fn, (bubble||false));
}
function isNodeName(el, tag) {
return (el.nodeName||"").toLowerCase() === tag.toLowerCase();
}
function directionCheck(x, y) {
x = (x > 0) ? 1 : -1;
y = (y > 0) ? 1 : -1;
if (direction.x !== x || direction.y !== y) {
direction.x = x;
direction.y = y;
que = [];
lastScroll = 0;
}
}
var deltaBufferTimer;
function isTouchpad(deltaY) {
if (!deltaY) return;
deltaY = Math.abs(deltaY)
deltaBuffer.push(deltaY);
deltaBuffer.shift();
clearTimeout(deltaBufferTimer);
var allDivisable = (isDivisible(deltaBuffer[0], 120) &&
isDivisible(deltaBuffer[1], 120) &&
isDivisible(deltaBuffer[2], 120));
return !allDivisable;
}
function isDivisible(n, divisor) {
return (Math.floor(n / divisor) == n / divisor);
}
var requestFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function (callback, element, delay) {
window.setTimeout(callback, delay || (1000/60));
};
})();
/***********************************************
* PULSE
***********************************************/
/**
* Viscous fluid with a pulse for part and decay for the rest.
* - Applies a fixed force over an interval (a damped acceleration), and
* - Lets the exponential bleed away the velocity over a longer interval
* - Michael Herf, http://stereopsis.com/stopping/
*/
function pulse_(x) {
var val, start, expx;
// test
x = x * options.pulseScale;
if (x < 1) { // acceleartion
val = x - (1 - Math.exp(-x));
} else { // tail
// the previous animation ended here:
start = Math.exp(-1);
// simple viscous drag
x -= 1;
expx = 1 - Math.exp(-x);
val = start + (expx * (1 - start));
}
return val * options.pulseNormalize;
}
function pulse(x) {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (options.pulseNormalize == 1) {
options.pulseNormalize /= pulse_(1);
}
return pulse_(x);
}
var isChrome = /chrome/i.test(window.navigator.userAgent);
var wheelEvent = null;
if ("onwheel" in document.createElement("div"))
wheelEvent = "wheel";
else if ("onmousewheel" in document.createElement("div"))
wheelEvent = "mousewheel";
if (wheelEvent && isChrome) {
addEvent(wheelEvent, wheel);
addEvent("mousedown", mousedown);
addEvent("load", init);
}
})();
$(function () {
'use strict';
// page transitions
$(".animsition").animsition({
inClass : 'fade-in',
outClass : 'fade-out',
inDuration : 2000,
outDuration : 800,
// linkElement : '.animsition-link',
linkElement : 'a:not([target="_blank"]):not([href^=#]):not([class*="gallery-item"]):not([class*="no-redirect"])',
loading : true,
loadingParentElement : 'body', //animsition wrapper element
loadingClass : 'animsition-loading',
unSupportCss : [ 'animation-duration',
'-webkit-animation-duration',
'-o-animation-duration'
],
overlay : false,
overlayClass : 'animsition-overlay-slide',
overlayParentElement : 'body'
});
// if element visible
// ---------------------------------
$.fn.isVisible = function(){
var st = $(window).scrollTop(),
wh = $(window).height(),
tt = $(this).offset().top,
th = $(this).height(),
r;
if(st+wh>=tt && tt+th>=st){r = 1}else{r = 0}
return r;
};
// smooth scroll
// ---------------------------------
$('.sscroll').click(function () {
var ti = $(this).attr('href'),
tt = $(ti).offset().top-100;
$('html, body').animate({ scrollTop: tt }, 600);
return false;
});
// scroll to top
// ---------------------------------
$(window).scroll(function () {
var wh = $(window).height(),
st = $(window).scrollTop();
if( st >= wh*0.7 ){ $('.to-top').fadeIn(); }else{ $('.to-top').fadeOut() }
});
$('.to-top').click(function () {
$('html, body').animate({ scrollTop: 0 }, 600);
return false;
});
// parallax
$.stellar({
horizontalScrolling: false,
responsive:true
});
// stellar fix - bg position on load
if( $('[data-stellar-background-ratio]').length > 0 ){
setTimeout(function () {
var st = $(window).scrollTop();
$(window).scrollTop(st+1);
setTimeout(function(){
$(window).scrollTop(st)
}, 200)
}, 200);
};
if( $('.hero-inner').length ){
$(window).resize(function () {
var hh = $('header').height();
$('.hero-inner').css('top', hh);
var hi = $('.hero-inner').height()/2;
$('.side-link').css('top', hh+hi);
}).resize();
}
// MOBILE NAVIGATION
$('.mob-nav').click(function () {
$(this).find('i').toggleClass('fa-bars fa-times');
$('#topmenu').slideToggle();
return false;
});
// side links
$('.side-link').each(function(){
var e = $(this);
var h = Math.round( e.height() );
if( (h%2)==1 ){
e.css({ height: '+=1' })
}
});
// map/info button
$('.map-button').click(function () {
var text = $(this).text();
$(this).text( text == "info" ? "map" : "info" );
$('.contact-info').fadeToggle();
});
// Hero slider
// ---------------------------------
if( $('.hero-slider').length ){
$(window).resize(function () {
$('.hero-slider .slide').height( $('.hero-inner').height() ).width( $('.hero-inner').width() );
}).resize();
$('.hero-slider').flexslider({
animation: "slide",
pauseOnAction: true,
animationLoop: true,
slideshow: true,
slideshowSpeed: 7000,
animationSpeed: 600,
controlNav: false,
directionNav: false
});
}
// YT Background
// ---------------------------------
$('.ytbg').YTPlayer({
mute:true,
showControls: false,
showYTLogo:false
});
// equal-height columns
$('.equal-height [class*="col-"]').matchHeight({
byRow: false
});
// responsive videos
// ---------------------------------
$('.video-container').fitVids();
// image slider
// ---------------------------------
$('.img-slider').flexslider({
animation: "slide",
animateHeight: false,
smoothHeight: true,
pauseOnAction: false,
controlNav: false,
directionNav: true,
prevText: "",
nextText: ""
});
$('.flex-direction-nav a').click(function (ev) {
ev.stopPropagation();
});
// BLOG
// ---------------------------------
$(window).load(function(){
var val, val2;
$('.blog').imagesLoaded(function () {
$('.blog').shuffle({
"itemSelector": ".post"
});
// fix
setTimeout(function () {
$('.blog').shuffle('shuffle');
}, 500);
if ( $.cookie("scroll") !== null ) {
val = Number("250");
val2 = Number($.cookie("scroll"));
$(document).scrollTop( val2 );
}
});
});
$( document ).ready(function() {
setTimeout(function () {
$('.blog').shuffle('shuffle');
}, 500);
});
// PORTFOLIO
// ---------------------------------
$(window).load(function () {
if( $('.portfolio.col-3').length ){
$('.item').width( 100/3+'%' );
$('.item.wide, .item.wide-tall').width( 100*2/3+'%' );
}
$('.portfolio').shuffle({
"itemSelector": ".item",
"delimeter": ','
});
// fix
setTimeout(function () {
$(window).resize();
}, 200);
});
// spaces between items
$('.portfolio[data-space]').each(function () {
var space = $(this).data('space');
$(this).find('.item-link').css({ 'margin': space });
$('.portfolio').css({
'margin-left': -space+'px',
'margin-right': -space+'px'
});
});
// FILTER
$('.filter ul li').click(function () {
var filter = $(this).data('group');
$('.portfolio').shuffle('shuffle', filter);
$('.filter ul li').removeClass('active');
$(this).addClass('active');
});
$(window).load(function () {
// skills
// ---------------------------------
$(window).scroll(function () {
$('.skill').each(function () {
if( $(this).isVisible() && !$(this).hasClass('animated') ){
var p = $(this).find('.skill-bar').data('perc');
$(this).find('.skill-bar').delay(200).animate({ width: p+'%' });
$(this).find('.skill-bar span').delay(2000).fadeIn('slow');
$(this).addClass('animated');
}
});
});
// counters
// ---------------------------------
$(window).scroll(function () {
$('.counter-num').each(function () {
if( $(this).isVisible() && $(this).html() == '' ){
$(this).countTo({ speed: 2500 });
}
});
});
// fix
// ---------------------------------
setTimeout(function () {
$(window).scroll();
}, 300);
});
// tabs
// ---------------------------------
$('.tab-nav li').click(function () {
if( !$(this).hasClass('active') ){
var p = $(this).data('tabpanel');
$(this).parents('.tabs').find('.tab-nav li').removeClass('active');
$(this).addClass('active');
$(this).parents('.tabs').find('.tab-panels > div').fadeOut(0).removeClass('active');
$(this).parents('.tabs').find(p).fadeIn().addClass('active');
}
});
// toggles
// ---------------------------------
$('.toggle .toggle-title').click(function () {
$(this).next('.toggle-content').slideToggle(200);
$(this).parent('.toggle').toggleClass('active');
return false;
});
// IMAGE POPUP
// ---------------------------------
// single
$('.popup-image').magnificPopup({
type: 'image',
mainClass: 'mfp-fade',
removalDelay: 300,
closeOnContentClick: true,
fixedContentPos: false,
fixedBgPos: false
});
// gallery mode
$('.gallery-item').magnificPopup({
gallery: {
enabled: true
},
mainClass: 'mfp-fade',
fixedContentPos: false,
type: 'image'
});
// YOUTUBE, VIMEO, GOOGLE MAPS POPUP
// ---------------------------------
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
type: 'iframe',
mainClass: 'mfp-fade',
disableOn: 0,
preloader: false,
removalDelay: 300,
fixedContentPos: false
});
// GALLERY POPUP
// ---------------------------------
// for portfolio
$('.popup-gallery').magnificPopup({
delegate: '.filtered a',
mainClass: 'mfp-fade',
gallery: {
enabled: true
},
fixedContentPos: false,
type: 'image'
});
// single gallery
$('.popup-single-gallery').each(function () {
$(this).magnificPopup({
delegate: 'a',
mainClass: 'mfp-fade',
gallery: {
enabled: true
},
fixedContentPos: false,
type: 'image'
});
});
/*$.pgwModal({
target: '#modalContent',
closable: false,
titleBar: false
}); */
// AJAX CONTACT FORM
// ---------------------------------
/* $('#contact form').submit(function () {
var url = $(this).attr('action');
// get information from contact form
var name = $('[name=name]').val();
var phone = $('[name=phone]').val();
var to = $('[name=to]').val();
var model_name = $('[name=model_name]').val();
var email = $('[name=email]').val();
var message = $('[name=message]').val();
// send information to contact.php
$.ajax({
type: "POST",
url: url,
data: { name: name, phone: phone, model_name: model_name, to: to, email: email, message: message },
success: function (response) {
// response from contact.php
$('.contact-message').html(response).slideDown(500);
$('#submit').hide();
},
error: function () {
// error message
$('.contact-message').html('Something went wrong, try again!
').slideDown('slow');
}
});
return false;
}); */
// ---------------------------------
/*$('.email_news form').submit(function () {
var url = $(this).attr('action');
// get information from contact form
var email = $('[name=email]').val();
// send information to contact.php
$.ajax({
type: "POST",
url: url,
data: { email: email},
success: function (response) {
// response from contact.php
$('.contact-message').html(response).slideDown(500);
$('#submit').hide();
},
error: function () {
// error message
$('.contact-message').html('Something went wrong, try again!
').slideDown('slow');
}
});
return false;
}); */
// AJAX CONTACT FORM
// ---------------------------------
$('#casting form').submit(function () {
var url = $(this).attr('action');
// get information from contact form
var name = $('[name=name]').val();
var email = $('[name=email]').val();
var working_name = $('[name=working_name]').val();
var mobile = $('[name=mobile]').val();
var adress = $('[name=adress]').val();
var age = $('[name=age]').val();
var hair = $('[name=hair]').val();
var eyes = $('[name=eyes]').val();
var height = $('[name=height]').val();
var dress_size = $('[name=dress_size]').val();
var bust = $('[name=bust]').val();
var waist = $('[name=waist]').val();
var hips = $('[name=hips]').val();
var breasts = $('[name=breasts]').val();
var nationality = $('[name=nationality]').val();
var languages = $('[name=languages]').val();
var education = $('[name=education]').val();
var images="";
$('input[name^="files_preview"]').each(function() {
images = $(this).val()+","+images;
});
var feedback = $('[name=feedback]').val();
// send information to contact.php
$.ajax({
type: "POST",
url: url,
data: { name: name, email: email, working_name: working_name, mobile: mobile, adress: adress, age: age, hair: hair, eyes: eyes, height: height, dress_size: dress_size, bust: bust, waist:waist, hips: hips, breasts:breasts, nationality: nationality, languages: languages, education: education, images: images, feedback: feedback},
success: function (response) {
// response from contact.php
$('.contact-message').html(response).slideDown(500);
$('#submit').hide();
},
error: function () {
// error message
$('.contact-message').html('Something went wrong, try again!
').slideDown('slow');
}
});
return false;
});
// GOOGLE MAP
// ----------------------------------
//set your google maps parameters
$(window).load(function () {
if( $('#google-map').length > 0 ){
var latitude = 51.5255069,
longitude = -0.0836207,
map_zoom = 14;
//google map custom marker icon
var marker_url = 'img/map-marker.png';
//we define here the style of the map
var style= [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];
//set google map options
var map_options = {
center: new google.maps.LatLng(latitude, longitude),
zoom: map_zoom,
panControl: false,
zoomControl: true,
mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
styles: style,
}
//inizialize the map
var map = new google.maps.Map(document.getElementById('google-map'), map_options);
//add a custom marker to the map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
visible: true,
icon: marker_url,
});
}
});
$(document).ready(function(){
if ($('#phone:input').length > 0) {
$("#phone:input").inputmask("mask", {"mask": "+999 9999-99-99"});
}
});
if(window.devicePixelRatio>=2)document.cookie='retina=1'
$('.rateit').bind('rated reset', function (e) {
var ri = $(this);
//if the use pressed reset, it will get value: 0 (to be compatible with the HTML range control), we could check if e.type == 'reset', and then set the value to null .
var value = ri.rateit('value');
var productID = ri.data('productid'); // if the product id was in some hidden field: ri.closest('li').find('input[name="productid"]').val()
//maybe we want to disable voting?
ri.rateit('readonly', true);
$.ajax({
url: 'http://leilaescorts.com/rating.php', //your server side script
data: { id: productID, value: value }, //our data
type: 'POST',
success: function (data) {
$('#response').append(data);
},
error: function (jxhr, msg, err) {
$('#response').append(msg);
}
});
});
})
/*
* Input Mask Core
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 0.0.0-dev
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
define(["inputmask.dependencyLib"], factory);
} else if (typeof exports === "object") {
module.exports = factory(require("./inputmask.dependencyLib.jquery"));
} else {
factory(window.dependencyLib || jQuery);
}
}
(function($) {
function Inputmask(alias, options) {
//allow instanciating without new
if (!(this instanceof Inputmask)) {
return new Inputmask(alias, options);
}
if (typeof alias === "object") {
options = alias;
} else {
options = options || {};
options.alias = alias;
}
this.el = undefined;
//init options
this.opts = $.extend(true, {}, this.defaults, options);
this.noMasksCache = options && options.definitions !== undefined;
this.userOptions = options || {}; //user passed options
resolveAlias(this.opts.alias, options, this.opts);
}
Inputmask.prototype = {
//options default
defaults: {
placeholder: "_",
optionalmarker: {
start: "[",
end: "]"
},
quantifiermarker: {
start: "{",
end: "}"
},
groupmarker: {
start: "(",
end: ")"
},
alternatormarker: "|",
escapeChar: "\\",
mask: null, //needs tobe null instead of undefined as the extend method does not consider props with the undefined value
oncomplete: $.noop, //executes when the mask is complete
onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
oncleared: $.noop, //executes when the mask is cleared
repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
removeMaskOnSubmit: false, //remove the mask before submitting the form.
clearMaskOnLostFocus: true,
insertMode: true, //insert the input or overwrite the input
clearIncomplete: false, //clear the incomplete input on blur
aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
alias: null,
onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example. args => event, buffer, caretPos, opts
onBeforeMask: null, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
onBeforePaste: function(pastedValue, opts) {
return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(pastedValue, opts) : pastedValue;
}, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
onBeforeWrite: null, //executes before writing to the masked element. args => event, opts
onUnMask: null, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
showMaskOnFocus: true, //show the mask-placeholder when the input has focus
showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
showTooltip: false, //show the activemask as tooltip
numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
rightAlign: false, //align to the right
undoOnEscape: true, //pressing escape reverts the value to the value before focus
//numeric basic properties
radixPoint: "", //".", // | ","
groupSeparator: "", //",", // | "."
radixFocus: false, //position caret to radixpoint on initial click
//numeric basic properties
nojumps: false, //do not jump over fixed parts in the mask
nojumpsThreshold: 0, //start nojumps as of
keepStatic: null, //try to keep the mask static while typing. Decisions to alter the mask will be posponed if possible - null see auto selection for multi masks
positionCaretOnTab: false, //when enabled the caret position is set after the latest valid position on TAB
tabThrough: false, //allows for tabbing through the different parts of the masked field
supportsInputType: [], //allow extra inputtypes for masking, ex. number can be allowed for numeric alias without pre-/suffix and standard radixpoint, groupSeparator
definitions: {
"9": {
validator: "[0-9]",
cardinality: 1,
definitionSymbol: "*"
},
"a": {
validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
cardinality: 1,
definitionSymbol: "*"
},
"*": {
validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
cardinality: 1
}
},
//specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
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],
isComplete: null, //override for isComplete - args => buffer, opts - return true || false
canClearPosition: $.noop, //hook to alter the clear behavior in the stripValidPositions args => maskset, position, lastValidPosition, opts => return true|false
postValidation: null //hook to postValidate the result from isValid. Usefull for validating the entry as a whole. args => buffer, opts => return true/false
},
masksCache: {},
mask: function(el) {
var scopedOpts = $.extend(true, {}, this.opts);
importAttributeOptions(el, scopedOpts, $.extend(true, {}, this.userOptions));
var maskset = generateMaskSet(scopedOpts, this.noMasksCache);
if (maskset !== undefined) {
if (el.inputmask !== undefined) {
el.inputmask.remove();
}
//store inputmask instance on the input with element reference
el.inputmask = new Inputmask();
el.inputmask.opts = scopedOpts;
el.inputmask.noMasksCache = this.noMasksCache;
el.inputmask.userOptions = $.extend(true, {}, this.userOptions);
el.inputmask.el = el;
el.inputmask.maskset = maskset;
el.inputmask.isRTL = false;
$.data(el, "_inputmask_opts", scopedOpts);
maskScope({
"action": "mask",
"el": el
});
}
return el.inputmask || this;
},
option: function(options) { //set extra options || retrieve value of a current option
if (typeof options === "string") {
return this.opts[options];
} else if (typeof options === "object") {
$.extend(this.opts, options);
$.extend(this.userOptions, options); //user passed options
//remask
if (this.el) {
if (options.mask !== undefined || options.alias !== undefined) {
this.mask(this.el);
} else {
$.data(this.el, "_inputmask_opts", this.opts);
maskScope({
"action": "mask",
"el": this.el
});
}
}
return this;
}
},
unmaskedvalue: function(value) {
return maskScope({
"action": "unmaskedvalue",
"el": this.el,
"value": value
}, this.el && this.el.inputmask ? this.el.inputmask.maskset : generateMaskSet(this.opts, this.noMasksCache), this.opts);
},
remove: function() {
if (this.el) {
maskScope({
"action": "remove",
"el": this.el
});
this.el.inputmask = undefined; //delete ~ undefined
return this.el;
}
},
getemptymask: function() { //return the default (empty) mask value, usefull for setting the default value in validation
return maskScope({
"action": "getemptymask"
}, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
},
hasMaskedValue: function() { //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
return !this.opts.autoUnmask;
},
isComplete: function() {
return maskScope({
"action": "isComplete",
"el": this.el //optional
}, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
},
getmetadata: function() { //return mask metadata if exists
return maskScope({
"action": "getmetadata"
}, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
},
isValid: function(value) {
return maskScope({
"action": "isValid",
"value": value
}, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
},
format: function(value, metadata) {
return maskScope({
"action": "format",
"value": value,
"metadata": metadata //true/false getmetadata
}, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts);
}
};
//apply defaults, definitions, aliases
Inputmask.extendDefaults = function(options) {
$.extend(Inputmask.prototype.defaults, options);
};
Inputmask.extendDefinitions = function(definition) {
$.extend(Inputmask.prototype.defaults.definitions, definition);
};
Inputmask.extendAliases = function(alias) {
$.extend(Inputmask.prototype.defaults.aliases, alias);
};
//static fn on inputmask
Inputmask.format = function(value, options, metadata) {
return Inputmask(options).format(value, metadata);
};
Inputmask.unmask = function(value, options) {
return Inputmask(options).unmaskedvalue(value);
};
Inputmask.isValid = function(value, options) {
return Inputmask(options).isValid(value);
};
Inputmask.escapeRegex = function(str) {
var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
};
Inputmask.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
};
//helper functions
function isInputEventSupported(eventName) {
var el = document.createElement("input"),
evName = "on" + eventName,
isSupported = (evName in el);
if (!isSupported) {
el.setAttribute(evName, "return;");
isSupported = typeof el[evName] == "function";
}
el = null;
return isSupported;
}
function isInputTypeSupported(inputType) {
var isSupported = inputType === "text" || inputType === "tel" || inputType === "password";
if (!isSupported) {
var el = document.createElement("input");
el.setAttribute("type", inputType);
isSupported = el.type === "text"; //apply mask only if the type is not natively supported
el = null;
}
return isSupported;
}
function resolveAlias(aliasStr, options, opts) {
var aliasDefinition = opts.aliases[aliasStr];
if (aliasDefinition) {
if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
$.extend(true, opts, aliasDefinition); //merge alias definition in the options
$.extend(true, opts, options); //reapply extra given options
return true;
} else //alias not found - try as mask
if (opts.mask === null) {
opts.mask = aliasStr;
}
return false;
}
function importAttributeOptions(npt, opts, userOptions) {
var attrOptions = npt.getAttribute("data-inputmask");
function importOption(option) {
var optionData = npt.getAttribute("data-inputmask-" + option.toLowerCase());
if (optionData !== null) {
optionData = typeof optionData == "boolean" ? optionData : optionData.toString();
/*eslint-disable no-eval */
if (typeof optionData === "string" && option.indexOf("on") === 0) {
optionData = eval("(" + optionData + ")");
}
/*eslint-enable no-eval */
if (option === "mask" && optionData.indexOf("[") === 0) {
userOptions[option] = optionData.replace(/[\s[\]]/g, "").split(",");
userOptions[option][0] = userOptions[option][0].replace("'", "");
userOptions[option][userOptions[option].length - 1] = userOptions[option][userOptions[option].length - 1].replace("'", "");
} else userOptions[option] = optionData;
}
}
if (attrOptions && attrOptions !== "") {
try {
attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
var dataoptions = $.parseJSON("{" + attrOptions + "}");
$.extend(true, userOptions, dataoptions);
} catch (ex) {
} //need a more relax parseJSON
}
for (var option in opts) {
importOption(option);
}
if (userOptions.alias) {
resolveAlias(userOptions.alias, userOptions, opts);
for (option in opts) {
importOption(option);
}
}
$.extend(true, opts, userOptions);
return opts;
}
function generateMaskSet(opts, nocache) {
var ms;
function analyseMask(mask) {
var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,
escaped = false,
currentToken = new MaskToken(),
match,
m,
openenings = [],
maskTokens = [],
openingToken,
currentOpeningToken,
alternator,
lastMatch,
groupToken;
function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
this.matches = [];
this.isGroup = isGroup || false;
this.isOptional = isOptional || false;
this.isQuantifier = isQuantifier || false;
this.isAlternator = isAlternator || false;
this.quantifier = {
min: 1,
max: 1
};
}
//test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
function insertTestDefinition(mtoken, element, position) {
var maskdef = opts.definitions[element];
position = position !== undefined ? position : mtoken.matches.length;
var prevMatch = mtoken.matches[position - 1];
if (maskdef && !escaped) {
maskdef.placeholder = $.isFunction(maskdef.placeholder) ? maskdef.placeholder(opts) : maskdef.placeholder;
var prevalidators = maskdef.prevalidator,
prevalidatorsL = prevalidators ? prevalidators.length : 0;
//handle prevalidators
for (var i = 1; i < maskdef.cardinality; i++) {
var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
validator = prevalidator.validator,
cardinality = prevalidator.cardinality;
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: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
casing: maskdef.casing,
def: maskdef.definitionSymbol || element,
placeholder: maskdef.placeholder,
mask: element
});
prevMatch = mtoken.matches[position - 1];
}
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: prevMatch === undefined || prevMatch.def !== (maskdef.definitionSymbol || element),
casing: maskdef.casing,
def: maskdef.definitionSymbol || element,
placeholder: maskdef.placeholder,
mask: element
});
} else {
mtoken.matches.splice(position++, 0, {
fn: null,
cardinality: 0,
optionality: mtoken.isOptional,
newBlockMarker: prevMatch === undefined || prevMatch.def !== element,
casing: null,
def: element,
placeholder: undefined,
mask: element
});
escaped = false;
}
}
function verifyGroupMarker(lastMatch, isOpenGroup) {
if (lastMatch.isGroup) { //this is not a group but a normal mask => convert
lastMatch.isGroup = false;
insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
if (isOpenGroup !== true) {
insertTestDefinition(lastMatch, opts.groupmarker.end);
}
}
}
function maskCurrentToken(m, currentToken, lastMatch, extraCondition) {
if (currentToken.matches.length > 0 && (extraCondition === undefined || extraCondition)) {
lastMatch = currentToken.matches[currentToken.matches.length - 1];
verifyGroupMarker(lastMatch);
}
insertTestDefinition(currentToken, m);
}
function defaultCase() {
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
maskCurrentToken(m, currentOpeningToken, lastMatch, !currentOpeningToken.isAlternator);
if (currentOpeningToken.isAlternator) { //handle alternator a | b case
alternator = openenings.pop();
for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
}
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
currentOpeningToken.matches.push(alternator);
} else {
currentToken.matches.push(alternator);
}
}
} else {
maskCurrentToken(m, currentToken, lastMatch);
}
}
function reverseTokens(maskToken) {
function reverseStatic(st) {
if (st === opts.optionalmarker.start) st = opts.optionalmarker.end;
else if (st === opts.optionalmarker.end) st = opts.optionalmarker.start;
else if (st === opts.groupmarker.start) st = opts.groupmarker.end;
else if (st === opts.groupmarker.end) st = opts.groupmarker.start;
return st;
}
maskToken.matches = maskToken.matches.reverse();
for (var match in maskToken.matches) {
var intMatch = parseInt(match);
if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier
var qt = maskToken.matches[match];
maskToken.matches.splice(match, 1);
maskToken.matches.splice(intMatch + 1, 0, qt);
}
if (maskToken.matches[match].matches !== undefined) {
maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
} else {
maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
}
}
return maskToken;
}
while (match = tokenizer.exec(mask)) {
m = match[0];
if (escaped) {
defaultCase();
continue;
}
switch (m.charAt(0)) {
case opts.escapeChar:
escaped = true;
break;
case opts.optionalmarker.end:
// optional closing
case opts.groupmarker.end:
// Group closing
openingToken = openenings.pop();
if (openingToken !== undefined) {
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
currentOpeningToken.matches.push(openingToken);
if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
alternator = openenings.pop();
for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
}
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
currentOpeningToken.matches.push(alternator);
} else {
currentToken.matches.push(alternator);
}
}
} else {
currentToken.matches.push(openingToken);
}
} else defaultCase();
break;
case opts.optionalmarker.start:
// optional opening
openenings.push(new MaskToken(false, true));
break;
case opts.groupmarker.start:
// Group opening
openenings.push(new MaskToken(true));
break;
case opts.quantifiermarker.start:
//Quantifier
var quantifier = new MaskToken(false, false, true);
m = m.replace(/[{}]/g, "");
var mq = m.split(","),
mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
if (mq1 === "*" || mq1 === "+") {
mq0 = mq1 === "*" ? 0 : 1;
}
quantifier.quantifier = {
min: mq0,
max: mq1
};
if (openenings.length > 0) {
var matches = openenings[openenings.length - 1].matches;
match = matches.pop();
if (!match.isGroup) {
groupToken = new MaskToken(true);
groupToken.matches.push(match);
match = groupToken;
}
matches.push(match);
matches.push(quantifier);
} else {
match = currentToken.matches.pop();
if (!match.isGroup) {
groupToken = new MaskToken(true);
groupToken.matches.push(match);
match = groupToken;
}
currentToken.matches.push(match);
currentToken.matches.push(quantifier);
}
break;
case opts.alternatormarker:
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
lastMatch = currentOpeningToken.matches.pop();
} else {
lastMatch = currentToken.matches.pop();
}
if (lastMatch.isAlternator) {
openenings.push(lastMatch);
} else {
alternator = new MaskToken(false, false, false, true);
alternator.matches.push(lastMatch);
openenings.push(alternator);
}
break;
default:
defaultCase();
}
}
while (openenings.length > 0) {
openingToken = openenings.pop();
verifyGroupMarker(openingToken, true);
currentToken.matches.push(openingToken);
}
if (currentToken.matches.length > 0) {
lastMatch = currentToken.matches[currentToken.matches.length - 1];
verifyGroupMarker(lastMatch);
maskTokens.push(currentToken);
}
if (opts.numericInput) {
reverseTokens(maskTokens[0]);
}
// console.log(JSON.stringify(maskTokens));
return maskTokens;
}
function generateMask(mask, metadata) {
if (mask === null || mask === "") {
return undefined;
} else {
if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
opts.placeholder = "";
} //hide placeholder with single non-greedy mask
if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
}
// console.log(mask);
var masksetDefinition;
if (Inputmask.prototype.masksCache[mask] === undefined || nocache === true) {
masksetDefinition = {
"mask": mask,
"maskToken": analyseMask(mask),
"validPositions": {},
"_buffer": undefined,
"buffer": undefined,
"tests": {},
"metadata": metadata
};
if (nocache !== true) {
Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition;
}
} else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[mask]);
return masksetDefinition;
}
}
function preProcessMask(mask) {
mask = mask.toString();
// if (opts.numericInput) {
// mask = mask.split('').reverse();
// mask = mask.join('');
// }
return mask;
}
if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
opts.mask = opts.mask(opts);
}
if ($.isArray(opts.mask)) {
if (opts.mask.length > 1) {
opts.keepStatic = opts.keepStatic === null ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
var altMask = "(";
$.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function(ndx, msk) {
if (altMask.length > 1) {
altMask += ")|(";
}
if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
altMask += preProcessMask(msk.mask);
} else {
altMask += preProcessMask(msk);
}
});
altMask += ")";
return generateMask(altMask, opts.mask);
} else opts.mask = opts.mask.pop();
}
if (opts.mask) {
if (opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
ms = generateMask(preProcessMask(opts.mask.mask), opts.mask);
} else {
ms = generateMask(preProcessMask(opts.mask), opts.mask);
}
}
return ms;
}
var ua = navigator.userAgent,
iphone = ua.match(new RegExp("iphone", "i")) !== null,
// android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
// 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),
PasteEventType = isInputEventSupported("paste") ? "paste" : isInputEventSupported("input") ? "input" : "propertychange";
//if (androidchrome) {
// var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
// version = parseInt(new RegExp(/[0-9]+/).exec(browser));
// androidchrome32 = (version == 32);
//}
//masking scope
//actionObj definition see below
function maskScope(actionObj, maskset, opts) {
var isRTL = false,
undoValue,
// compositionValidPos,
compositionCaretPos,
compositionData,
el, $el,
skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
skipInputEvent = false, //skip when triggered from within inputmask
ignorable = false,
maxLength,
mouseEnter = true;
//maskset helperfunctions
function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
minimalPos = minimalPos || 0;
var maskTemplate = [],
ndxIntlzr, pos = 0,
test, testPos;
do {
if (baseOnInput === true && getMaskSet().validPositions[pos]) {
var validPos = getMaskSet().validPositions[pos];
test = validPos.match;
ndxIntlzr = validPos.locator.slice();
maskTemplate.push(includeInput === true ? validPos.input : getPlaceholder(pos, test));
} else {
//console.log("getmasktemplate " + pos + " " + JSON.stringify(ndxIntlzr));
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
test = testPos.match;
ndxIntlzr = testPos.locator.slice();
maskTemplate.push(getPlaceholder(pos, test));
}
pos++;
} while ((maxLength === undefined || pos - 1 < maxLength) && test.fn !== null || (test.fn === null && test.def !== "") || minimalPos >= pos);
maskTemplate.pop(); //drop the last one which is empty
return maskTemplate;
}
function getMaskSet() {
return maskset;
}
function resetMaskSet(soft) {
var maskset = getMaskSet();
maskset.buffer = undefined;
maskset.tests = {};
if (soft !== true) {
maskset._buffer = undefined;
maskset.validPositions = {};
maskset.p = 0;
}
}
function getLastValidPosition(closestTo, strict) {
var maskset = getMaskSet(),
lastValidPosition = -1,
valids = maskset.validPositions;
if (closestTo === undefined) closestTo = -1;
var before = lastValidPosition,
after = lastValidPosition;
for (var posNdx in valids) {
var psNdx = parseInt(posNdx);
if (valids[psNdx] && (strict || valids[psNdx].match.fn !== null)) {
if (psNdx <= closestTo) before = psNdx;
if (psNdx >= closestTo) after = psNdx;
}
}
lastValidPosition = (before !== -1 && (closestTo - before) > 1) || after < closestTo ? before : after;
return lastValidPosition;
}
function setValidPosition(pos, validTest, fromSetValid) {
if (opts.insertMode && getMaskSet().validPositions[pos] !== undefined && fromSetValid === undefined) {
//reposition & revalidate others
var positionsClone = $.extend(true, {}, getMaskSet().validPositions),
lvp = getLastValidPosition(),
i;
for (i = pos; i <= lvp; i++) { //clear selection
delete getMaskSet().validPositions[i];
}
getMaskSet().validPositions[pos] = validTest;
var valid = true,
j, vps = getMaskSet().validPositions;
for (i = (j = pos); i <= lvp; i++) {
var t = positionsClone[i];
if (t !== undefined) {
var posMatch = j,
prevPosMatch = -1;
while (posMatch < getMaskLength() && ((t.match.fn == null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
//determine next position
if (t.match.fn === null || (!opts.keepStatic && vps[i] && (vps[i + 1] !== undefined && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || vps[i].alternation !== undefined))) {
posMatch++;
} else posMatch = seekNext(j);
//does it match
if (positionCanMatchDefinition(posMatch, t.match.def)) {
valid = isValid(posMatch, t.input, true, true) !== false;
j = posMatch;
break;
} else {
valid = t.match.fn == null;
if (prevPosMatch === posMatch) break; //prevent endless loop
prevPosMatch = posMatch;
}
}
}
if (!valid) break;
}
if (!valid) {
getMaskSet().validPositions = $.extend(true, {}, positionsClone);
return false;
}
} else getMaskSet().validPositions[pos] = validTest;
return true;
}
function stripValidPositions(start, end, nocheck, strict) {
var i, startPos = start;
getMaskSet().p = start; //needed for alternated position after overtype selection
for (i = startPos; i < end; i++) { //clear selection
if (getMaskSet().validPositions[i] !== undefined) {
if (nocheck === true || opts.canClearPosition(getMaskSet(), i, getLastValidPosition(), strict, opts) !== false) {
delete getMaskSet().validPositions[i];
}
}
}
resetMaskSet(true);
/*eslint-disable semi-spacing */
for (i = startPos + 1; i <= getLastValidPosition();) {
/*eslint-disable semi-spacing */
while (getMaskSet().validPositions[startPos] !== undefined) startPos++;
var s = getMaskSet().validPositions[startPos];
if (i < startPos) i = startPos + 1;
// while (getMaskSet().validPositions[i] == undefined) i++;
var t = getMaskSet().validPositions[i];
if (t !== undefined && isMask(i) && s === undefined) {
if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t.input, true) !== false) {
delete getMaskSet().validPositions[i];
i++;
}
startPos++;
} else i++;
}
//remove radixpoint if needed
var lvp = getLastValidPosition(),
ml = getMaskLength();
if (strict !== true && nocheck !== true && getMaskSet().validPositions[lvp] !== undefined && getMaskSet().validPositions[lvp].input === opts.radixPoint) {
delete getMaskSet().validPositions[lvp];
}
for (i = lvp + 1; i <= ml; i++) {
if (getMaskSet().validPositions[i]) {
delete getMaskSet().validPositions[i];
}
}
resetMaskSet(true);
}
function getTestTemplate(pos, ndxIntlzr, tstPs) {
var testPos = getMaskSet().validPositions[pos];
if (testPos === undefined) {
var testPositions = getTests(pos, ndxIntlzr, tstPs),
lvp = getLastValidPosition(),
lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0],
lvTestAltArr = (lvTest.alternation !== undefined) ? lvTest.locator[lvTest.alternation].toString().split(",") : [];
for (var ndx = 0; ndx < testPositions.length; ndx++) {
testPos = testPositions[ndx];
if (testPos.match &&
(((opts.greedy && testPos.match.optionalQuantifier !== true) || (testPos.match.optionality === false || testPos.match.newBlockMarker === false) && testPos.match.optionalQuantifier !== true) &&
((lvTest.alternation === undefined || lvTest.alternation !== testPos.alternation) ||
(testPos.locator[lvTest.alternation] !== undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
break;
}
}
}
return testPos;
}
function getTest(pos) {
if (getMaskSet().validPositions[pos]) {
return getMaskSet().validPositions[pos].match;
}
return getTests(pos)[0].match;
}
function positionCanMatchDefinition(pos, def) {
var valid = false,
tests = getTests(pos);
for (var tndx = 0; tndx < tests.length; tndx++) {
if (tests[tndx].match && tests[tndx].match.def === def) {
valid = true;
break;
}
}
return valid;
}
function getTests(pos, ndxIntlzr, tstPs, cacheable) {
var maskTokens = getMaskSet().maskToken,
testPos = ndxIntlzr ? tstPs : 0,
ndxInitializer = ndxIntlzr || [0],
matches = [],
insertStop = false,
latestMatch, isFirstMatch;
function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
function handleMatch(match, loopNdx, quantifierRecurse) {
if (testPos > 10000) {
throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask;
}
if (testPos === pos && match.matches === undefined) {
matches.push({
"match": match,
"locator": loopNdx.reverse()
});
return true;
} else if (match.matches !== undefined) {
if (match.isGroup && quantifierRecurse !== match) { //when a group pass along to the quantifier
match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx);
if (match) return true;
} else if (match.isOptional) {
var optionalToken = match;
match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
if (match) {
latestMatch = matches[matches.length - 1].match;
isFirstMatch = $.inArray(latestMatch, optionalToken.matches) === 0;
if (isFirstMatch) {
insertStop = true; //insert a stop
testPos = pos; //match the position after the group
} else return true;
}
} else if (match.isAlternator) {
var alternateToken = match,
malternateMatches = [],
maltMatches,
currentMatches = matches.slice(),
loopNdxCnt = loopNdx.length;
var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
if (altIndex === -1 || typeof altIndex === "string") {
var currentPos = testPos,
ndxInitializerClone = ndxInitializer.slice(),
altIndexArr = [];
if (typeof altIndex == "string") altIndexArr = altIndex.split(",");
for (var amndx = 0; amndx < alternateToken.matches.length; amndx++) {
matches = [];
match = handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
if (match !== true && match !== undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further
var ntndx = maskToken.matches.indexOf(match) + 1;
if (maskToken.matches.length > ntndx) {
match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse);
if (match) {
altIndexArr.push(ntndx.toString());
$.each(matches, function(ndx, lmnt) {
lmnt.alternation = loopNdx.length - 1;
});
}
}
}
maltMatches = matches.slice();
testPos = currentPos;
matches = [];
//cloneback
for (var i = 0; i < ndxInitializerClone.length; i++) {
ndxInitializer[i] = ndxInitializerClone[i];
}
//fuzzy merge matches
for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
var altMatch = maltMatches[ndx1];
altMatch.alternation = altMatch.alternation || loopNdxCnt;
for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
var altMatch2 = malternateMatches[ndx2];
//verify equality
if (altMatch.match.mask === altMatch2.match.mask && (typeof altIndex !== "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1)) {
maltMatches.splice(ndx1, 1);
ndx1--;
altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + "," + altMatch.locator[altMatch.alternation];
altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
break;
}
}
}
malternateMatches = malternateMatches.concat(maltMatches);
}
if (typeof altIndex == "string") { //filter matches
malternateMatches = $.map(malternateMatches, function(lmnt, ndx) {
if (isFinite(ndx)) {
var mamatch,
alternation = lmnt.alternation,
altLocArr = lmnt.locator[alternation].toString().split(",");
lmnt.locator[alternation] = undefined;
lmnt.alternation = undefined;
for (var alndx = 0; alndx < altLocArr.length; alndx++) {
mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;
if (mamatch) { //rebuild the locator with valid entries
if (lmnt.locator[alternation] !== undefined) {
lmnt.locator[alternation] += ",";
lmnt.locator[alternation] += altLocArr[alndx];
} else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
lmnt.alternation = alternation;
}
}
if (lmnt.locator[alternation] !== undefined) return lmnt;
}
});
}
matches = currentMatches.concat(malternateMatches);
testPos = pos;
insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate
} else {
if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
} else match = false;
}
if (match) return true;
} else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
var qt = match;
for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0;
(qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker
if (match) {
//get latest match
latestMatch = matches[matches.length - 1].match;
latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
if (isFirstMatch) { //search for next possible match
if (qndx > (qt.quantifier.min - 1)) {
insertStop = true;
testPos = pos; //match the position after the group
break; //stop quantifierloop
} else return true;
} else {
return true;
}
}
}
} else {
match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
if (match) return true;
}
} else testPos++;
}
for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0); tndx < maskToken.matches.length; tndx++) {
if (maskToken.matches[tndx].isQuantifier !== true) {
var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
if (match && testPos === pos) {
return match;
} else if (testPos > pos) {
break;
}
}
}
}
if (cacheable === true && getMaskSet().tests[pos]) {
return getMaskSet().tests[pos];
}
if (ndxIntlzr === undefined) {
var previousPos = pos - 1,
test;
while ((test = getMaskSet().validPositions[previousPos]) === undefined && previousPos > -1) {
if (getMaskSet().tests[previousPos] && (test = getMaskSet().tests[previousPos][0]) !== undefined) {
break;
}
previousPos--;
}
if (test !== undefined && previousPos > -1) {
testPos = previousPos;
ndxInitializer = test.locator.slice();
}
}
for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
if ((match && testPos === pos) || testPos > pos) {
break;
}
}
if (matches.length === 0 || insertStop) {
matches.push({
"match": {
fn: null,
cardinality: 0,
optionality: true,
casing: null,
def: ""
},
"locator": []
});
}
getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
// console.log(pos + " - " + JSON.stringify(matches));
return getMaskSet().tests[pos];
}
function getBufferTemplate() {
if (getMaskSet()._buffer === undefined) {
//generate template
getMaskSet()._buffer = getMaskTemplate(false, 1);
}
return getMaskSet()._buffer;
}
function getBuffer() {
if (getMaskSet().buffer === undefined) {
getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
}
return getMaskSet().buffer;
}
function refreshFromBuffer(start, end, buffer) {
var i;
buffer = buffer || getBuffer().slice(); //pass or work on clone
if (start === true) {
resetMaskSet();
start = 0;
end = buffer.length;
} else {
for (i = start; i < end; i++) {
delete getMaskSet().validPositions[i];
delete getMaskSet().tests[i];
}
}
for (i = start; i < end; i++) {
resetMaskSet(true); //prevents clobber from the buffer
if (buffer[i] !== opts.skipOptionalPartCharacter) {
isValid(i, buffer[i], true, true);
}
}
}
function casing(elem, test) {
switch (test.casing) {
case "upper":
elem = elem.toUpperCase();
break;
case "lower":
elem = elem.toLowerCase();
break;
}
return elem;
}
function checkAlternationMatch(altArr1, altArr2) {
var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
isMatch = false;
for (var alndx = 0; alndx < altArr1.length; alndx++) {
if ($.inArray(altArr1[alndx], altArrC) !== -1) {
isMatch = true;
break;
}
}
return isMatch;
}
function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
function _isValid(position, c, strict, fromSetValid) {
var rslt = false;
$.each(getTests(position), function(ndx, tst) {
var test = tst.match;
var loopend = c ? 1 : 0,
chrs = "";
for (var i = test.cardinality; i > loopend; i--) {
chrs += getBufferElement(position - (i - 1));
}
if (c) {
chrs += c;
}
//return is false or a json object => { pos: ??, c: ??} or true
rslt = test.fn != null ?
test.fn.test(chrs, getMaskSet(), position, strict, opts) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? //non mask
{
c: test.def,
pos: position
} : false;
if (rslt !== false) {
var elem = rslt.c !== undefined ? rslt.c : c;
elem = (elem === opts.skipOptionalPartCharacter && test.fn === null) ? test.def : elem;
var validatedPos = position,
possibleModifiedBuffer = getBuffer();
if (rslt.remove !== undefined) { //remove position(s)
if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
$.each(rslt.remove.sort(function(a, b) {
return b - a;
}), function(ndx, lmnt) {
stripValidPositions(lmnt, lmnt + 1, true);
});
}
if (rslt.insert !== undefined) { //insert position(s)
if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
$.each(rslt.insert.sort(function(a, b) {
return a - b;
}), function(ndx, lmnt) {
isValid(lmnt.pos, lmnt.c, true);
});
}
if (rslt.refreshFromBuffer) {
var refresh = rslt.refreshFromBuffer;
strict = true;
refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, possibleModifiedBuffer);
if (rslt.pos === undefined && rslt.c === undefined) {
rslt.pos = getLastValidPosition();
return false; //breakout if refreshFromBuffer && nothing to insert
}
validatedPos = rslt.pos !== undefined ? rslt.pos : position;
if (validatedPos !== position) {
rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
return false;
}
} else if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) { //their is a position offset
validatedPos = rslt.pos;
refreshFromBuffer(position, validatedPos);
if (validatedPos !== position) {
rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
return false;
}
}
if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
return false; //breakout if nothing to insert
}
if (ndx > 0) {
resetMaskSet(true);
}
if (!setValidPosition(validatedPos, $.extend({}, tst, {
"input": casing(elem, test)
}), fromSetValid)) {
rslt = false;
}
return false; //break from $.each
}
});
return rslt;
}
function alternate(pos, c, strict, fromSetValid) {
var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
lastAlt,
alternation,
isValidRslt,
altPos, i, validPos;
//find last modified alternation
for (var lAlt = getLastValidPosition(); lAlt >= 0; lAlt--) {
altPos = getMaskSet().validPositions[lAlt];
if (altPos && altPos.alternation !== undefined) {
lastAlt = lAlt;
alternation = getMaskSet().validPositions[lastAlt].alternation;
if (getTestTemplate(lastAlt).locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
break;
}
}
}
if (alternation !== undefined) {
//find first decision making position
lastAlt = parseInt(lastAlt);
for (var decisionPos in getMaskSet().validPositions) {
decisionPos = parseInt(decisionPos);
altPos = getMaskSet().validPositions[decisionPos];
if (decisionPos >= lastAlt && altPos.alternation !== undefined) {
var altNdxs = getMaskSet().validPositions[lastAlt].locator[alternation].toString().split(","),
decisionTaker = altPos.locator[alternation] || altNdxs[0]; //no match in the alternations (length mismatch)
if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
decisionTaker = decisionTaker.split(",")[0];
}
for (var mndx = 0; mndx < altNdxs.length; mndx++) {
if (decisionTaker < altNdxs[mndx]) {
var possibilityPos, possibilities;
for (var dp = decisionPos; dp >= 0; dp--) {
possibilityPos = getMaskSet().validPositions[dp];
if (possibilityPos !== undefined) {
possibilities = possibilityPos.locator[alternation]; //store to reset
//possibilityPos.alternation = undefined;
possibilityPos.locator[alternation] = parseInt(altNdxs[mndx]);
break;
}
}
if (decisionTaker !== possibilityPos.locator[alternation]) {
var validInputs = [],
staticInputsBeforePos = 0;
for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
validPos = getMaskSet().validPositions[i];
if (validPos) {
if (validPos.match.fn != null) {
validInputs.push(validPos.input);
} else if (i < pos) staticInputsBeforePos++;
}
delete getMaskSet().validPositions[i];
delete getMaskSet().tests[i];
}
resetMaskSet(true); //clear getbuffer
opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength
isValidRslt = true;
while (validInputs.length > 0) {
var input = validInputs.shift();
if (input !== opts.skipOptionalPartCharacter) {
if (!(isValidRslt = isValid(getLastValidPosition() + 1, input, false, true))) {
break;
}
}
}
possibilityPos.alternation = alternation;
possibilityPos.locator[alternation] = possibilities; //reset forceddecision ~ needed for proper delete
if (isValidRslt) {
var targetLvp = getLastValidPosition(pos) + 1;
var staticInputsBeforePosAlternate = 0;
for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
validPos = getMaskSet().validPositions[i];
if (validPos && validPos.match.fn == null && i < pos) {
staticInputsBeforePosAlternate++;
}
}
pos = pos + (staticInputsBeforePosAlternate - staticInputsBeforePos);
isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid);
}
opts.keepStatic = !opts.keepStatic; //enable keepStatic on getMaskLength
if (!isValidRslt) {
resetMaskSet();
getMaskSet().validPositions = $.extend(true, {}, validPsClone);
} else return isValidRslt;
}
}
}
break;
}
}
}
return false;
}
//set alternator choice on previous skipped placeholder positions
function trackbackAlternations(originalPos, newPos) {
var vp = getMaskSet().validPositions[newPos],
targetLocator = vp.locator,
tll = targetLocator.length;
for (var ps = originalPos; ps < newPos; ps++) {
if (!isMask(ps)) {
var tests = getTests(ps),
bestMatch = tests[0],
equality = -1;
$.each(tests, function(ndx, tst) {
for (var i = 0; i < tll; i++) {
if (tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(",")) && equality < i) {
equality = i;
bestMatch = tst;
}
}
});
setValidPosition(ps, $.extend({}, bestMatch, {
"input": bestMatch.match.def
}), true);
}
}
}
//Check for a nonmask before the pos
var buffer = getBuffer();
//find previous valid
for (var pndx = pos - 1; pndx > -1; pndx--) {
if (getMaskSet().validPositions[pndx]) {
break;
}
}
////fill missing nonmask and valid placeholders
pndx++;
for (; pndx < pos; pndx++) {
//console.log("missing " + pndx + " " + buffer[pndx] + " ismask " + isMask(pndx) + " plchldr " + getPlaceholder(pndx) + " nrt " + getTests(pndx).len);
if (getMaskSet().validPositions[pndx] === undefined && (((!isMask(pndx) || buffer[pndx] !== getPlaceholder(pndx)) && getTests(pndx).length > 1) || (buffer[pndx] === opts.radixPoint || buffer[pndx] === "0" && $.inArray(opts.radixPoint, buffer) < pndx))) //special case for decimals ~ = placeholder but yet valid input
{
//console.log("inject " + pndx + " " + buffer[pndx]);
_isValid(pndx, buffer[pndx], true);
}
}
var maskPos = pos,
result = false,
positionsClone = $.extend(true, {}, getMaskSet().validPositions); //clone the currentPositions
//if (fromSetValid && maskPos >= getMaskLength()) {
// resetMaskSet(true); //masklenght can be altered on the process => reset to get the actual length
//}
if (maskPos < getMaskLength()) {
getBuffer(); //make sure the buffer
result = _isValid(maskPos, c, strict, fromSetValid);
if ((!strict || fromSetValid) && result === false) {
var currentPosValid = getMaskSet().validPositions[maskPos];
if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
result = {
"caret": seekNext(maskPos)
};
} else if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos)) { //does the input match on a further position?
for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
result = _isValid(nPos, c, strict, fromSetValid);
if (result !== false) {
trackbackAlternations(maskPos, nPos);
maskPos = nPos;
break;
}
}
}
}
}
if (result === false && opts.keepStatic && isComplete(buffer)) { //try fuzzy alternator logic
result = alternate(pos, c, strict, fromSetValid);
}
if (result === true) {
result = {
"pos": maskPos
};
}
if ($.isFunction(opts.postValidation) && result !== false && !strict) {
resetMaskSet(true);
var postValidResult = opts.postValidation(getBuffer(), opts);
if (!postValidResult) {
resetMaskSet(true);
getMaskSet().validPositions = $.extend(true, {}, positionsClone); //revert validation changes
result = false;
} else if (postValidResult.refreshFromBuffer) {
var refresh = postValidResult.refreshFromBuffer;
refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postValidResult.buffer);
resetMaskSet(true);
result = postValidResult;
}
}
return result;
}
function isMask(pos) {
var test = getTest(pos);
if (test.fn != null) {
return test.fn;
} else if (pos > -1 && !opts.keepStatic && getMaskSet().validPositions[pos] === undefined) {
var tests = getTests(pos),
staticAlternations = true;
for (var i = 0; i < tests.length; i++) {
if (tests[i].match.def !== "" && ( /*tests[i].match.fn !== null || */ (tests[i].alternation === undefined || tests[i].locator[tests[i].alternation].length > 1))) {
staticAlternations = false;
break;
}
}
return staticAlternations;
}
return false;
}
function getMaskLength() {
var maskLength;
maxLength = el !== undefined ? el.maxLength : undefined;
if (maxLength === -1) maxLength = undefined; /* FF sets no defined max length to -1 */
var pos, lvp = getLastValidPosition(),
testPos = getMaskSet().validPositions[lvp],
ndxIntlzr = testPos !== undefined ? testPos.locator.slice() : undefined;
for (pos = lvp + 1; testPos === undefined || (testPos.match.fn !== null || (testPos.match.fn === null && testPos.match.def !== "")); pos++) {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
ndxIntlzr = testPos.locator.slice();
}
var lastTest = getTest(pos - 1);
maskLength = (lastTest.def !== "") ? pos : pos - 1;
return (maxLength === undefined || maskLength < maxLength) ? maskLength : maxLength;
}
function seekNext(pos, newBlock) {
var maskL = getMaskLength();
if (pos >= maskL) return maskL;
var position = pos;
while (++position < maskL && ((newBlock === true && (getTest(position).newBlockMarker !== true || !isMask(position))) || (newBlock !== true && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)))) {}
return position;
}
function seekPrevious(pos, newBlock) {
var position = pos;
if (position <= 0) return 0;
while (--position > 0 && ((newBlock === true && getTest(position).newBlockMarker !== true) || (newBlock !== true && !isMask(position)))) {}
return position;
}
function getBufferElement(position) {
return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
}
function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
if (event && $.isFunction(opts.onBeforeWrite)) {
var result = opts.onBeforeWrite.call(input, event, buffer, caretPos, opts);
if (result) {
if (result.refreshFromBuffer) {
var refresh = result.refreshFromBuffer;
refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
resetMaskSet(true);
buffer = getBuffer();
}
//only alter when intented !== undefined
if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
}
}
input.inputmask._valueSet(buffer.join(""));
if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
caret(input, caretPos);
}
if (triggerInputEvent === true) {
skipInputEvent = true;
$(input).trigger("input");
}
}
function getPlaceholder(pos, test) {
test = test || getTest(pos);
if (test.placeholder !== undefined) {
return test.placeholder;
} else if (test.fn === null) {
if (pos > -1 && !opts.keepStatic && getMaskSet().validPositions[pos] === undefined) {
var tests = getTests(pos),
hasAlternations = false,
prevTest;
for (var i = 0; i < tests.length; i++) {
if (prevTest && tests[i].match.def !== "" && (tests[i].match.def !== prevTest.match.def && (tests[i].alternation === undefined || tests[i].alternation === prevTest.alternation))) {
hasAlternations = true;
break;
}
if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true) {
prevTest = tests[i];
}
}
if (hasAlternations) {
return opts.placeholder.charAt(pos % opts.placeholder.length);
}
}
return test.def;
} else {
return opts.placeholder.charAt(pos % opts.placeholder.length);
}
}
function checkVal(input, writeOut, strict, nptvl) {
var inputValue = nptvl.slice(),
charCodes = "",
initialNdx = 0;
function isTemplateMatch() {
var isMatch = false;
var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes);
if (charCodeNdx !== -1 && !isMask(initialNdx)) {
isMatch = true;
var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
for (var i = 0; i < bufferTemplateArr.length; i++) {
if (bufferTemplateArr[i] !== " ") {
isMatch = false;
break;
}
}
}
return isMatch;
}
resetMaskSet();
getMaskSet().p = seekNext(-1);
// if (writeOut) input.inputmask._valueSet(""); //initial clear
if (!strict) {
if (opts.autoUnmask !== true) {
var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
if (matches && matches.length > 0) {
inputValue.splice(0, matches.length * staticInput.length);
initialNdx = seekNext(initialNdx);
}
} else {
initialNdx = seekNext(initialNdx);
}
}
$.each(inputValue, function(ndx, charCode) {
var keypress = $.Event("keypress");
keypress.which = charCode.charCodeAt(0);
charCodes += charCode;
var lvp = getLastValidPosition(undefined, true),
lvTest = getMaskSet().validPositions[lvp],
nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
if (!isTemplateMatch() || strict || opts.autoUnmask) {
var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
keypressEvent.call(input, keypress, true, false, strict, pos);
initialNdx = pos + 1;
charCodes = "";
} else {
keypressEvent.call(input, keypress, true, false, true, lvp + 1);
}
});
if (writeOut) {
writeBuffer(input, getBuffer(), document.activeElement === input ? seekNext(getLastValidPosition(0)) : undefined, $.Event("checkval"));
}
}
function unmaskedvalue(input) {
if (input && input.inputmask === undefined) {
return input.value;
}
var umValue = [],
vps = getMaskSet().validPositions;
for (var pndx in vps) {
if (vps[pndx].match && vps[pndx].match.fn != null) {
umValue.push(vps[pndx].input);
}
}
var unmaskedValue = umValue.length === 0 ? null : (isRTL ? umValue.reverse() : umValue).join("");
if (unmaskedValue !== null) {
var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
if ($.isFunction(opts.onUnMask)) {
unmaskedValue = (opts.onUnMask.call(input, bufferValue, unmaskedValue, opts) || unmaskedValue);
}
}
return unmaskedValue;
}
function caret(input, begin, end) {
function translatePosition(pos) {
if (isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
var bffrLght = getBuffer().join("").length; //join is needed because sometimes we get an empty buffer element which must not be counted for the caret position (numeric alias)
pos = bffrLght - pos;
}
return pos;
}
var range;
if (typeof begin === "number") {
begin = translatePosition(begin);
end = translatePosition(end);
end = (typeof end == "number") ? end : begin;
// if (!$(input).is(":visible")) {
// return;
// }
var scrollCalc = (input.ownerDocument.defaultView || window).getComputedStyle(input, null).fontSize.replace("px", "") * end;
input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
if (!androidchrome && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
if (input.setSelectionRange) {
input.selectionStart = begin;
input.selectionEnd = end;
} else if (window.getSelection) {
range = document.createRange();
if (input.firstChild === undefined) {
var textNode = document.createTextNode("");
input.appendChild(textNode);
}
range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
//input.focus();
} else if (input.createTextRange) {
range = input.createTextRange();
range.collapse(true);
range.moveEnd("character", end);
range.moveStart("character", begin);
range.select();
}
} else {
if (input.setSelectionRange) {
begin = input.selectionStart;
end = input.selectionEnd;
} else if (window.getSelection) {
range = window.getSelection().getRangeAt(0);
if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
begin = range.startOffset;
end = range.endOffset;
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart("character", -100000);
end = begin + range.text.length;
}
/*eslint-disable consistent-return */
return {
"begin": translatePosition(begin),
"end": translatePosition(end)
};
/*eslint-enable consistent-return */
}
}
function determineLastRequiredPosition(returnDefinition) {
var buffer = getBuffer(),
bl = buffer.length,
pos, lvp = getLastValidPosition(),
positions = {},
lvTest = getMaskSet().validPositions[lvp],
ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
testPos;
for (pos = lvp + 1; pos < buffer.length; pos++) {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
ndxIntlzr = testPos.locator.slice();
positions[pos] = $.extend(true, {}, testPos);
}
var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
for (pos = bl - 1; pos > lvp; pos--) {
testPos = positions[pos];
if ((testPos.match.optionality ||
testPos.match.optionalQuantifier ||
(lvTestAlt && ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
(testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) && buffer[pos] === getPlaceholder(pos, testPos.match)) {
bl--;
} else break;
}
return returnDefinition ? {
"l": bl,
"def": positions[bl] ? positions[bl].match : undefined
} : bl;
}
function clearOptionalTail(buffer) {
var rl = determineLastRequiredPosition(),
lmib = buffer.length - 1;
for (; lmib > rl; lmib--) {
if (isMask(lmib)) break; //fixme ismask is not good enough
}
buffer.splice(rl, lmib + 1 - rl);
return buffer;
}
function isComplete(buffer) { //return true / false / undefined (repeat *)
if ($.isFunction(opts.isComplete)) return opts.isComplete.call(el, buffer, opts);
if (opts.repeat === "*") return undefined;
var complete = false,
lrp = determineLastRequiredPosition(true),
aml = seekPrevious(lrp.l);
if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
complete = true;
for (var i = 0; i <= aml; i++) {
var test = getTestTemplate(i).match;
if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
complete = false;
break;
}
}
}
return complete;
}
function isSelection(begin, end) {
return isRTL ? (begin - end) > 1 || ((begin - end) === 1 && opts.insertMode) :
(end - begin) > 1 || ((end - begin) === 1 && opts.insertMode);
}
function wrapEvent(eventHandler) {
return function(e) {
// console.log("triggered " + e.type);
var inComposition = false;
if (this.inputmask === undefined) { //happens when cloning an object with jquery.clone
var imOpts = $.data(this, "_inputmask_opts");
if (imOpts)(new Inputmask(imOpts)).mask(this);
else $(this).off(".inputmask");
} else if (e.type !== "setvalue" && (this.disabled || (this.readOnly && !(e.type === "keydown" && (e.ctrlKey && e.keyCode === 67) || (opts.tabThrough === false && e.keyCode === Inputmask.keyCode.TAB))))) {
e.preventDefault();
} else {
switch (e.type) {
case "input":
if (skipInputEvent === true || inComposition === true) {
skipInputEvent = false;
return e.preventDefault();
}
break;
case "keydown":
//Safari 5.1.x - modal dialog fires keypress twice workaround
skipKeyPressEvent = false;
inComposition = false;
break;
case "keypress":
if (skipKeyPressEvent === true) {
return e.preventDefault();
}
skipKeyPressEvent = true;
break;
case "compositionstart":
inComposition = true;
break;
case "compositionupdate":
skipInputEvent = true;
break;
case "compositionend":
inComposition = false;
break;
}
//console.log("executed " + e.type);
return eventHandler.apply(this, arguments);
}
};
}
function patchValueProperty(npt) {
var valueGet;
var valueSet;
function patchValhook(type) {
if ($.valHooks && $.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true) {
var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
return elem.value;
};
var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
elem.value = value;
return elem;
};
$.valHooks[type] = {
get: function(elem) {
if (elem.inputmask) {
if (elem.inputmask.opts.autoUnmask) {
return elem.inputmask.unmaskedvalue();
} else {
var result = valhookGet(elem),
maskset = elem.inputmask.maskset,
bufferTemplate = maskset._buffer;
bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "";
return result !== bufferTemplate ? result : "";
}
} else return valhookGet(elem);
},
set: function(elem, value) {
var $elem = $(elem),
result;
result = valhookSet(elem, value);
if (elem.inputmask) {
$elem.trigger("setvalue.inputmask");
}
return result;
},
inputmaskpatch: true
};
}
}
function getter() {
if (this.inputmask) {
return this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : (valueGet.call(this) !== getBufferTemplate().join("") ? valueGet.call(this) : "");
} else return valueGet.call(this);
}
function setter(value) {
valueSet.call(this, value);
if (this.inputmask) {
$(this).trigger("setvalue.inputmask");
}
}
function installNativeValueSetFallback(npt) {
$(npt).on("mouseenter.inputmask", wrapEvent(function(event) {
var $input = $(this),
input = this,
value = input.inputmask._valueGet();
if (value !== "" && value !== getBuffer().join("")) {
$input.trigger("setvalue.inputmask");
}
}));
// //!! the bound handlers are executed in the order they where bound
// //reorder the events - the mouseenter event is internally mapped to the mouseover event
// var events = $._data(npt).events;
// var handlers = events.mouseover;
// if (handlers) {
// var ourHandler = handlers[handlers.length - 1];
// for (var i = handlers.length - 1; i > 0; i--) {
// handlers[i] = handlers[i - 1];
// }
// handlers[0] = ourHandler;
// }
}
if (!npt.inputmask.__valueGet) {
if (Object.getOwnPropertyDescriptor && npt.value === undefined) { // && npt.isContentEditable) {
valueGet = function() {
return this.textContent;
};
valueSet = function(value) {
this.textContent = value;
};
Object.defineProperty(npt, "value", {
get: getter,
set: setter
});
} else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
valueGet = npt.__lookupGetter__("value");
valueSet = npt.__lookupSetter__("value");
npt.__defineGetter__("value", getter);
npt.__defineSetter__("value", setter);
} else { //jquery.val
valueGet = function() {
return npt.value;
};
valueSet = function(value) {
npt.value = value;
};
patchValhook(npt.type);
installNativeValueSetFallback(npt);
}
npt.inputmask.__valueGet = valueGet; //store native property getter
npt.inputmask._valueGet = function(overruleRTL) {
return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
};
npt.inputmask.__valueSet = valueSet; //store native property setter
npt.inputmask._valueSet = function(value, overruleRTL) {
valueSet.call(this.el, (overruleRTL !== true && isRTL && value !== null && value !== undefined) ? value.split("").reverse().join("") : value);
};
}
}
function handleRemove(input, k, pos, strict) {
function generalize() {
if (opts.keepStatic) {
resetMaskSet(true);
var validInputs = [],
lastAlt, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
//find last alternation
for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) {
var validPos = getMaskSet().validPositions[lastAlt];
if (validPos) {
if (validPos.match.fn != null) {
validInputs.push(validPos.input);
}
delete getMaskSet().validPositions[lastAlt];
if (validPos.alternation !== undefined && validPos.locator[validPos.alternation] === getTestTemplate(lastAlt).locator[validPos.alternation]) {
break;
}
}
}
if (lastAlt > -1) {
while (validInputs.length > 0) {
getMaskSet().p = seekNext(getLastValidPosition());
var keypress = $.Event("keypress");
keypress.which = validInputs.pop().charCodeAt(0);
keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
}
} else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
}
}
if (opts.numericInput || isRTL) {
if (k === Inputmask.keyCode.BACKSPACE) {
k = Inputmask.keyCode.DELETE;
} else if (k === Inputmask.keyCode.DELETE) {
k = Inputmask.keyCode.BACKSPACE;
}
if (isRTL) {
var pend = pos.end;
pos.end = pos.begin;
pos.begin = pend;
}
}
if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
pos.begin = seekPrevious(pos.begin);
if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
pos.begin--;
}
} else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1;
if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
pos.end++;
}
}
stripValidPositions(pos.begin, pos.end, false, strict);
if (strict !== true) {
generalize(); //revert the alternation
}
var lvp = getLastValidPosition(pos.begin);
if (lvp < pos.begin) {
if (lvp === -1) resetMaskSet();
getMaskSet().p = seekNext(lvp);
} else if (strict !== true) {
getMaskSet().p = pos.begin;
}
}
function keydownEvent(e) {
var input = this,
$input = $(input),
k = e.keyCode,
pos = caret(input);
//backspace, delete, and escape get special treatment
if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || (iphone && k === 127) || (e.ctrlKey && k === 88 && !isInputEventSupported("cut"))) { //backspace/delete
e.preventDefault(); //stop default action but allow propagation
if (k === 88) undoValue = getBuffer().join("");
handleRemove(input, k, pos);
writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
$input.trigger("cleared");
} else if (isComplete(getBuffer()) === true) {
$input.trigger("complete");
}
if (opts.showTooltip) { //update tooltip
$input.prop("title", getMaskSet().mask);
}
} else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
setTimeout(function() {
var caretPos = seekNext(getLastValidPosition());
if (!opts.insertMode && caretPos === getMaskLength() && !e.shiftKey) caretPos--;
caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
}, 0);
} else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
caret(input, 0, e.shiftKey ? pos.begin : 0);
} else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
checkVal(input, true, false, undoValue.split(""));
$input.trigger("click");
} else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
opts.insertMode = !opts.insertMode;
caret(input, !opts.insertMode && pos.begin === getMaskLength() ? pos.begin - 1 : pos.begin);
} else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
if (e.shiftKey === true) {
if (getTest(pos.begin).fn === null) {
pos.begin = seekNext(pos.begin);
}
pos.end = seekPrevious(pos.begin, true);
pos.begin = seekPrevious(pos.end, true);
} else {
pos.begin = seekNext(pos.begin, true);
pos.end = seekNext(pos.begin, true);
if (pos.end < getMaskLength()) pos.end--;
}
if (pos.begin < getMaskLength()) {
e.preventDefault();
caret(input, pos.begin, pos.end);
}
} else if (opts.insertMode === false && !e.shiftKey) {
if (k === Inputmask.keyCode.RIGHT) {
setTimeout(function() {
var caretPos = caret(input);
caret(input, caretPos.begin);
}, 0);
} else if (k === Inputmask.keyCode.LEFT) {
setTimeout(function() {
var caretPos = caret(input);
caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
}, 0);
}
}
opts.onKeyDown(e, getBuffer(), caret(input).begin, opts);
ignorable = $.inArray(k, opts.ignorables) !== -1;
}
function keypressEvent(e, checkval, writeOut, strict, ndx) {
var input = this,
$input = $(input),
k = e.which || e.charCode || e.keyCode;
if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
setTimeout(function() {
$input.trigger("change");
undoValue = getBuffer().join("");
}, 0);
}
return true;
} else {
if (k) {
//special treat the decimal separator
if (k === 46 && e.shiftKey === false && opts.radixPoint === ",") k = 44;
var pos = checkval ? {
begin: ndx,
end: ndx
} : caret(input),
forwardPosition, c = String.fromCharCode(k);
//should we clear a possible selection??
var isSlctn = isSelection(pos.begin, pos.end);
if (isSlctn) {
getMaskSet().undoPositions = $.extend(true, {}, getMaskSet().validPositions); //init undobuffer for recovery when not valid
handleRemove(input, Inputmask.keyCode.DELETE, pos, true);
pos.begin = getMaskSet().p;
if (!opts.insertMode) { //preserve some space
opts.insertMode = !opts.insertMode;
setValidPosition(pos.begin, strict);
opts.insertMode = !opts.insertMode;
}
isSlctn = !opts.multi;
}
getMaskSet().writeOutBuffer = true;
var p = isRTL && !isSlctn ? pos.end : pos.begin;
var valResult = isValid(p, c, strict);
if (valResult !== false) {
if (valResult !== true) {
p = valResult.pos !== undefined ? valResult.pos : p; //set new position from isValid
c = valResult.c !== undefined ? valResult.c : c; //set new char from isValid
}
resetMaskSet(true);
if (valResult.caret !== undefined) {
forwardPosition = valResult.caret;
} else {
var vps = getMaskSet().validPositions;
if (!opts.keepStatic && (vps[p + 1] !== undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation !== undefined)) {
forwardPosition = p + 1;
} else forwardPosition = seekNext(p);
}
getMaskSet().p = forwardPosition; //needed for checkval
}
if (writeOut !== false) {
var self = this;
setTimeout(function() {
opts.onKeyValidation.call(self, valResult, opts);
}, 0);
if (getMaskSet().writeOutBuffer && valResult !== false) {
var buffer = getBuffer();
writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
if (checkval !== true) {
setTimeout(function() { //timeout needed for IE
if (isComplete(buffer) === true) $input.trigger("complete");
}, 0);
}
} else if (isSlctn) {
getMaskSet().buffer = undefined;
getMaskSet().validPositions = getMaskSet().undoPositions;
}
} else if (isSlctn) {
getMaskSet().buffer = undefined;
getMaskSet().validPositions = getMaskSet().undoPositions;
}
if (opts.showTooltip) { //update tooltip
$input.prop("title", getMaskSet().mask);
}
if (checkval && $.isFunction(opts.onBeforeWrite)) {
var result = opts.onBeforeWrite(e, getBuffer(), forwardPosition, opts);
if (result && result.refreshFromBuffer) {
var refresh = result.refreshFromBuffer;
refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
resetMaskSet(true);
if (result.caret) {
getMaskSet().p = result.caret;
}
}
}
e.preventDefault();
if (checkval) {
return valResult;
}
}
}
}
function pasteEvent(e) {
var input = this,
$input = $(input),
inputValue = input.inputmask._valueGet(true),
caretPos = caret(input);
//paste event for IE8 and lower I guess ;-)
if (e.type === "propertychange" && input.inputmask._valueGet().length <= getMaskLength()) {
return true;
} else if (e.type === "paste") {
var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
if (valueBeforeCaret === getBufferTemplate().slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
if (valueAfterCaret === getBufferTemplate().slice(caretPos.end).join("")) valueAfterCaret = "";
if (window.clipboardData && window.clipboardData.getData) { // IE
inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
} else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
inputValue = valueBeforeCaret + e.originalEvent.clipboardData.getData("text/plain") + valueAfterCaret;
}
}
var pasteValue = inputValue;
if ($.isFunction(opts.onBeforePaste)) {
pasteValue = opts.onBeforePaste.call(input, inputValue, opts);
if (pasteValue === false) {
e.preventDefault();
return false;
}
if (!pasteValue) {
pasteValue = inputValue;
}
}
checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
writeBuffer(input, getBuffer(), undefined, e, true);
$input.trigger("click");
if (isComplete(getBuffer()) === true) {
$input.trigger("complete");
}
return false;
}
function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
var input = this;
checkVal(input, true, false, input.inputmask._valueGet().split(''));
if (isComplete(getBuffer()) === true) {
$(input).trigger("complete");
}
e.preventDefault();
}
function compositionStartEvent(e) {
var input = this;
undoValue = getBuffer().join("");
if (compositionData === "" || e.originalEvent.data.indexOf(compositionData) !== 0) {
compositionCaretPos = caret(input);
}
}
function compositionUpdateEvent(e) {
var input = this,
caretPos = caret(input);
if (e.originalEvent.data.indexOf(compositionData) === 0) {
resetMaskSet();
caretPos = compositionCaretPos;
}
var newData = e.originalEvent.data;
caret(input, caretPos.begin, caretPos.end);
for (var i = 0; i < newData.length; i++) {
var keypress = $.Event("keypress");
keypress.which = newData.charCodeAt(i);
skipKeyPressEvent = false;
ignorable = false;
keypressEvent.call(input, keypress); //needs update
}
setTimeout(function() {
var forwardPosition = getMaskSet().p;
writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
}, 0);
compositionData = e.originalEvent.data;
}
function compositionEndEvent(e) {
//pickup by inputfallback
}
function setValueEvent(e) {
var input = this,
value = input.inputmask._valueGet();
checkVal(input, true, false, ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(input, value, opts) || value) : value).split(""));
undoValue = getBuffer().join("");
if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
input.inputmask._valueSet("");
}
}
function focusEvent(e) {
var input = this,
nptValue = input.inputmask._valueGet();
if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
if (input.inputmask._valueGet() !== getBuffer().join("")) {
writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
}
} else if (mouseEnter === false) { //only executed on focus without mouseenter
caret(input, seekNext(getLastValidPosition()));
}
if (opts.positionCaretOnTab === true) {
setTimeout(function() {
caret(input, seekNext(getLastValidPosition()));
}, 0);
}
undoValue = getBuffer().join("");
}
function mouseleaveEvent(e) {
var input = this;
mouseEnter = false;
if (opts.clearMaskOnLostFocus) {
var buffer = getBuffer().slice(),
nptValue = input.inputmask._valueGet();
if (document.activeElement !== input && nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
buffer = [];
} else { //clearout optional tail of the mask
clearOptionalTail(buffer);
}
writeBuffer(input, buffer);
}
}
}
function clickEvent(e) {
function doRadixFocus(clickPos) {
if (opts.radixFocus && opts.radixPoint !== "") {
var vps = getMaskSet().validPositions;
if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
if (clickPos < seekNext(-1)) return true;
var radixPos = $.inArray(opts.radixPoint, getBuffer());
if (radixPos !== -1) {
for (var vp in vps) {
if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
return false;
}
}
return true;
}
}
}
return false;
}
var input = this;
if (document.activeElement === input) {
var selectedCaret = caret(input);
if (selectedCaret.begin === selectedCaret.end) {
if (doRadixFocus(selectedCaret.begin)) {
caret(input, $.inArray(opts.radixPoint, getBuffer()));
} else {
var clickPosition = selectedCaret.begin,
lvclickPosition = getLastValidPosition(clickPosition),
lastPosition = seekNext(lvclickPosition);
if (clickPosition < lastPosition) {
caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
} else {
caret(input, opts.numericInput ? 0 : lastPosition);
}
}
}
}
}
function dblclickEvent(e) {
var input = this;
setTimeout(function() {
caret(input, 0, seekNext(getLastValidPosition()));
}, 0);
}
function cutEvent(e) {
skipInputEvent = true; //stop inputFallback
var input = this,
$input = $(input),
pos = caret(input);
//correct clipboardData
if (isRTL) {
var clipboardData = window.clipboardData || e.originalEvent.clipboardData,
clipData = clipboardData.getData("text").split("").reverse().join("");
clipboardData.setData("text", clipData);
}
handleRemove(input, Inputmask.keyCode.DELETE, pos);
writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
$input.trigger("cleared");
}
if (opts.showTooltip) { //update tooltip
input.title = getMaskSet().mask;
}
}
function blurEvent(e) {
var $input = $(this),
input = this;
if (input.inputmask) {
var nptValue = input.inputmask._valueGet(),
buffer = getBuffer().slice();
if (undoValue !== buffer.join("")) {
setTimeout(function() { //change event should be triggered after the other buffer manipulations on blur
$input.trigger("change");
undoValue = buffer.join("");
}, 0);
}
if (nptValue !== "") {
if (opts.clearMaskOnLostFocus) {
if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
buffer = [];
} else { //clearout optional tail of the mask
clearOptionalTail(buffer);
}
}
if (isComplete(buffer) === false) {
setTimeout(function() {
$input.trigger("incomplete");
}, 0);
if (opts.clearIncomplete) {
resetMaskSet();
if (opts.clearMaskOnLostFocus) {
buffer = [];
} else {
buffer = getBufferTemplate().slice();
}
}
}
writeBuffer(input, buffer, undefined, e);
}
}
}
function mouseenterEvent(e) {
var input = this;
mouseEnter = true;
if (document.activeElement !== input && opts.showMaskOnHover) {
if (input.inputmask._valueGet() !== getBuffer().join("")) {
writeBuffer(input, getBuffer());
}
}
}
function mask(elem) {
el = elem;
$el = $(el);
//show tooltip
if (opts.showTooltip) {
el.title = getMaskSet().mask;
}
if (el.dir === "rtl" || opts.rightAlign) {
el.style.textAlign = "right";
}
if (el.dir === "rtl" || opts.numericInput) {
el.dir = "ltr";
el.removeAttribute("dir");
el.inputmask.isRTL = true;
isRTL = true;
}
//unbind all events - to make sure that no other mask will interfere when re-masking
$el.off(".inputmask");
patchValueProperty(el);
if ((el.tagName === "INPUT" && isInputTypeSupported(el.getAttribute("type"))) || el.isContentEditable) {
//bind events
$(el.form).on("submit", function() { //trigger change on submit if any
if (undoValue !== getBuffer().join("")) {
$el.trigger("change");
}
if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
}
if (opts.removeMaskOnSubmit) {
el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
setTimeout(function() {
writeBuffer(el, getBuffer());
}, 0);
}
}).on("reset", function() {
setTimeout(function() {
$el.trigger("setvalue.inputmask");
}, 0);
});
$el.on("mouseenter.inputmask", wrapEvent(mouseenterEvent))
.on("blur.inputmask", wrapEvent(blurEvent))
.on("focus.inputmask", wrapEvent(focusEvent))
.on("mouseleave.inputmask", wrapEvent(mouseleaveEvent))
.on("click.inputmask", wrapEvent(clickEvent))
.on("dblclick.inputmask", wrapEvent(dblclickEvent))
.on(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", wrapEvent(pasteEvent))
.on("cut.inputmask", wrapEvent(cutEvent))
.on("complete.inputmask", wrapEvent(opts.oncomplete))
.on("incomplete.inputmask", wrapEvent(opts.onincomplete))
.on("cleared.inputmask", wrapEvent(opts.oncleared))
.on("keydown.inputmask", wrapEvent(keydownEvent))
.on("keypress.inputmask", wrapEvent(keypressEvent));
if (!androidfirefox) {
$el.on("compositionstart.inputmask", wrapEvent(compositionStartEvent))
.on("compositionupdate.inputmask", wrapEvent(compositionUpdateEvent))
.on("compositionend.inputmask", wrapEvent(compositionEndEvent));
}
if (PasteEventType === "paste") {
$el.on("input.inputmask", wrapEvent(inputFallBackEvent));
}
//if (android || androidfirefox || androidchrome || kindle) {
// $el.off("input.inputmask");
// $el.on("input.inputmask", mobileInputEvent);
//}
}
$el.on("setvalue.inputmask", wrapEvent(setValueEvent));
//apply mask
var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el.inputmask._valueGet(), opts) || el.inputmask._valueGet()) : el.inputmask._valueGet();
checkVal(el, true, false, initialValue.split(""));
var buffer = getBuffer().slice();
undoValue = buffer.join("");
// Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
var activeElement;
try {
activeElement = document.activeElement;
} catch (e) {}
if (isComplete(buffer) === false) {
if (opts.clearIncomplete) {
resetMaskSet();
}
}
if (opts.clearMaskOnLostFocus) {
if (buffer.join("") === getBufferTemplate().join("")) {
buffer = [];
} else {
clearOptionalTail(buffer);
}
}
writeBuffer(el, buffer);
if (activeElement === el) { //position the caret when in focus
caret(el, seekNext(getLastValidPosition()));
}
}
//action object
var valueBuffer;
if (actionObj !== undefined) {
switch (actionObj.action) {
case "isComplete":
el = actionObj.el;
return isComplete(getBuffer());
case "unmaskedvalue":
el = actionObj.el;
if (el !== undefined && el.inputmask !== undefined) {
maskset = el.inputmask.maskset;
opts = el.inputmask.opts;
isRTL = el.inputmask.isRTL;
valueBuffer = isRTL ? el.inputmask._valueGet().split("").reverse().join("") : el.inputmask._valueGet();
} else valueBuffer = actionObj.value;
if (opts.numericInput) {
isRTL = true;
}
valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
return unmaskedvalue(el);
case "mask":
el = actionObj.el;
maskset = el.inputmask.maskset;
opts = el.inputmask.opts;
isRTL = el.inputmask.isRTL;
undoValue = getBuffer().join("");
mask(el);
break;
case "format":
if (opts.numericInput) {
isRTL = true;
}
valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
if (actionObj.metadata) {
return {
value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
metadata: maskScope({
"action": "getmetadata"
}, maskset, opts)
};
}
return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
case "isValid":
if (opts.numericInput) {
isRTL = true;
}
valueBuffer = actionObj.value.split("");
checkVal(undefined, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
var buffer = getBuffer();
var rl = determineLastRequiredPosition(),
lmib = buffer.length - 1;
for (; lmib > rl; lmib--) {
if (isMask(lmib)) break;
}
buffer.splice(rl, lmib + 1 - rl);
return isComplete(buffer) && actionObj.value === buffer.join("");
case "getemptymask":
return getBufferTemplate();
case "remove":
el = actionObj.el;
$el = $(el);
maskset = el.inputmask.maskset;
opts = el.inputmask.opts;
//writeout the unmaskedvalue
el.inputmask._valueSet(unmaskedvalue(el));
//unbind all events
$el.off(".inputmask");
//restore the value property
var valueProperty;
if (Object.getOwnPropertyDescriptor) {
valueProperty = Object.getOwnPropertyDescriptor(el, "value");
}
if (valueProperty && valueProperty.get) {
if (el.inputmask.__valueGet) {
Object.defineProperty(el, "value", {
get: el.inputmask.__valueGet,
set: el.inputmask.__valueSet
});
}
} else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
if (el.inputmask.__valueGet) {
el.__defineGetter__("value", el.inputmask.__valueGet);
el.__defineSetter__("value", el.inputmask.__valueSet);
}
}
//clear data
el.inputmask = undefined;
break;
case "getmetadata":
if ($.isArray(maskset.metadata)) {
//find last alternation
var alternation, lvp = getLastValidPosition();
for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
if (getMaskSet().validPositions[firstAlt] && getMaskSet().validPositions[firstAlt].alternation !== undefined) {
alternation = getMaskSet().validPositions[firstAlt].alternation;
break;
}
}
if (alternation !== undefined) {
return maskset.metadata[getMaskSet().validPositions[lvp].locator[alternation]];
} else return maskset.metadata[0];
}
return maskset.metadata;
}
}
}
//make inputmask available
window.Inputmask = Inputmask;
return Inputmask;
}));