Atos Públicos
 
 
 
Número
Súmula
Downloads
Lei nº 1760 - 2013
LEI Nº 1760
Concede reajuste salarial aos Servidores Públicos Municipais de Dois Vizinhos.
ato_15.doc Atualizado em: 06/09/2019
Lei nº 1761 - 2013
LEI Nº 1761
Autoriza o Poder Executivo a criar o Programa Municipal de Desenvolvimento da Cadeia Produtiva da Aquicultura Familiar, bem como utilizar recursos na promoção de ações de apoio e incentivo à atividade.
ato_14.doc Atualizado em: 06/09/2019
Lei nº 1762 - 2013
LEI Nº 1762
Aprova o Loteamento Dal Prá II e dá outras providências.
ato_13.doc Atualizado em: 06/09/2019
Lei nº 1763 - 2013
LEI Nº 1763
Autoriza o Município de Dois Vizinhos a receber em doação área rural e dá outras providências.
ato_12.doc Atualizado em: 06/09/2019
Lei nº 1764 - 2013
LEI Nº 1764
Define Lote Rural como área de expansão urbana da cidade de Dois Vizinhos, e dá outras providências.  
ato_11.doc Atualizado em: 06/09/2019
Lei nº 1765 - 2013
LEI Nº 1765
Define Lote Rural como área de expansão urbana da cidade de Dois Vizinhos, e dá outras providências.
ato_10.doc Atualizado em: 06/09/2019
Lei nº 1766 - 2013
LEI Nº 1766
Define Lote Rural como área de expansão urbana da cidade de Dois Vizinhos, e dá outras providências.
ato_9.doc Atualizado em: 06/09/2019
Lei nº 1767 - 2013
LEI Nº 1767
"}while(all[0]);return v>4?v:undef}(),DOM=function(){return{html:doc.documentElement,body:doc.body,head:doc.getElementsByTagName("head")[0],title:doc.title}},IFRAME=window.parent!==window.self,_eventlist="data ready thumbnail loadstart loadfinish image play pause progress "+"fullscreen_enter fullscreen_exit idle_enter idle_exit rescale "+"lightbox_open lightbox_close lightbox_image",_events=function(){var evs=[];$.each(_eventlist.split(" "),function(i,ev){evs.push(ev);if(/_/.test(ev)){evs.push(ev.replace(/_/g,""))}});return evs}(),_legacyOptions=function(options){var n;if(typeof options!=="object"){return options}$.each(options,function(key,value){if(/^[a-z]+_/.test(key)){n="";$.each(key.split("_"),function(i,k){n+=i>0?k.substr(0,1).toUpperCase()+k.substr(1):k});options[n]=value;delete options[key]}});return options},_patchEvent=function(type){if($.inArray(type,_events)>-1){return Galleria[type.toUpperCase()]}return type},_video={youtube:{reg:/https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i,embed:function(id){return"http://www.youtube.com/embed/"+id},getThumb:function(id,success,fail){fail=fail||F;$.getJSON(window.location.protocol+"//gdata.youtube.com/feeds/api/videos/"+id+"?v=2&alt=json-in-script&callback=?",function(data){try{success(data.entry.media$group.media$thumbnail[0].url)}catch(e){fail()}}).error(fail)}},vimeo:{reg:/https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i,embed:function(id){return"http://player.vimeo.com/video/"+id},getThumb:function(id,success,fail){fail=fail||F;$.getJSON("http://vimeo.com/api/v2/video/"+id+".json?callback=?",function(data){try{success(data[0].thumbnail_medium)}catch(e){fail()}}).error(fail)}},dailymotion:{reg:/https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/,embed:function(id){return"http://www.dailymotion.com/embed/video/"+id},getThumb:function(id,success,fail){fail=fail||F;$.getJSON("https://api.dailymotion.com/video/"+id+"?fields=thumbnail_medium_url&callback=?",function(data){try{success(data.thumbnail_medium_url)}catch(e){fail()}}).error(fail)}}},_videoTest=function(url){var match;for(var v in _video){match=url&&url.match(_video[v].reg);if(match&&match.length){return{id:match[2],provider:v}}}return false},_nativeFullscreen={support:function(){var html=DOM().html;return!IFRAME&&(html.requestFullscreen||html.mozRequestFullScreen||html.webkitRequestFullScreen)}(),callback:F,enter:function(instance,callback,elem){this.instance=instance;this.callback=callback||F;elem=elem||DOM().html;if(elem.requestFullscreen){elem.requestFullscreen()}else if(elem.mozRequestFullScreen){elem.mozRequestFullScreen()}else if(elem.webkitRequestFullScreen){elem.webkitRequestFullScreen()}},exit:function(callback){this.callback=callback||F;if(doc.exitFullscreen){doc.exitFullscreen()}else if(doc.mozCancelFullScreen){doc.mozCancelFullScreen()}else if(doc.webkitCancelFullScreen){doc.webkitCancelFullScreen()}},instance:null,listen:function(){if(!this.support){return}var handler=function(){if(!_nativeFullscreen.instance){return}var fs=_nativeFullscreen.instance._fullscreen;if(doc.fullscreen||doc.mozFullScreen||doc.webkitIsFullScreen){fs._enter(_nativeFullscreen.callback)}else{fs._exit(_nativeFullscreen.callback)}};doc.addEventListener("fullscreenchange",handler,false);doc.addEventListener("mozfullscreenchange",handler,false);doc.addEventListener("webkitfullscreenchange",handler,false)}},_galleries=[],_instances=[],_hasError=false,_canvas=false,_pool=[],_themeLoad=function(theme){Galleria.theme=theme;$.each(_pool,function(i,instance){if(!instance._initialized){instance._init.call(instance)}});_pool=[]},Utils=function(){return{clearTimer:function(id){$.each(Galleria.get(),function(){this.clearTimer(id)})},addTimer:function(id){$.each(Galleria.get(),function(){this.addTimer(id)})},array:function(obj){return protoArray.slice.call(obj,0)},create:function(className,nodeName){nodeName=nodeName||"div";var elem=doc.createElement(nodeName);elem.className=className;return elem},removeFromArray:function(arr,elem){$.each(arr,function(i,el){if(el==elem){arr.splice(i,1);return false}});return arr},getScriptPath:function(src){src=src||$("script:last").attr("src");var slices=src.split("/");if(slices.length==1){return""}slices.pop();return slices.join("/")+"/"},animate:function(){var transition=function(style){var props="transition WebkitTransition MozTransition OTransition".split(" "),i;if(window.opera){return false}for(i=0;props[i];i++){if(typeof style[props[i]]!=="undefined"){return props[i]}}return false}((doc.body||doc.documentElement).style);var endEvent={MozTransition:"transitionend",OTransition:"oTransitionEnd",WebkitTransition:"webkitTransitionEnd",transition:"transitionend"}[transition];var easings={_default:[.25,.1,.25,1],galleria:[.645,.045,.355,1],galleriaIn:[.55,.085,.68,.53],galleriaOut:[.25,.46,.45,.94],ease:[.25,0,.25,1],linear:[.25,.25,.75,.75],"ease-in":[.42,0,1,1],"ease-out":[0,0,.58,1],"ease-in-out":[.42,0,.58,1]};var setStyle=function(elem,value,suffix){var css={};suffix=suffix||"transition";$.each("webkit moz ms o".split(" "),function(){css["-"+this+"-"+suffix]=value});elem.css(css)};var clearStyle=function(elem){setStyle(elem,"none","transition");if(Galleria.WEBKIT&&Galleria.TOUCH){setStyle(elem,"translate3d(0,0,0)","transform");if(elem.data("revert")){elem.css(elem.data("revert"));elem.data("revert",null)}}};var change,strings,easing,syntax,revert,form,css;return function(elem,to,options){options=$.extend({duration:400,complete:F,stop:false},options);elem=$(elem);if(!options.duration){elem.css(to);options.complete.call(elem[0]);return}if(!transition){elem.animate(to,options);return}if(options.stop){elem.unbind(endEvent);clearStyle(elem)}change=false;$.each(to,function(key,val){css=elem.css(key);if(Utils.parseValue(css)!=Utils.parseValue(val)){change=true}elem.css(key,css)});if(!change){window.setTimeout(function(){options.complete.call(elem[0])},options.duration);return}strings=[];easing=options.easing in easings?easings[options.easing]:easings._default;syntax=" "+options.duration+"ms"+" cubic-bezier("+easing.join(",")+")";window.setTimeout(function(elem,endEvent,to,syntax){return function(){elem.one(endEvent,function(elem){return function(){clearStyle(elem);options.complete.call(elem[0])}}(elem));if(Galleria.WEBKIT&&Galleria.TOUCH){revert={};form=[0,0,0];$.each(["left","top"],function(i,m){if(m in to){form[i]=Utils.parseValue(to[m])-Utils.parseValue(elem.css(m))+"px";revert[m]=to[m];delete to[m]}});if(form[0]||form[1]){elem.data("revert",revert);strings.push("-webkit-transform"+syntax);setStyle(elem,"translate3d("+form.join(",")+")","transform")}}$.each(to,function(p,val){strings.push(p+syntax)});setStyle(elem,strings.join(","));elem.css(to)}}(elem,endEvent,to,syntax),2)}}(),removeAlpha:function(elem){if(IE<9&&elem){var style=elem.style,currentStyle=elem.currentStyle,filter=currentStyle&¤tStyle.filter||style.filter||"";if(/alpha/.test(filter)){style.filter=filter.replace(/alpha\([^)]*\)/i,"")}}},forceStyles:function(elem,styles){elem=$(elem);if(elem.attr("style")){elem.data("styles",elem.attr("style")).removeAttr("style")}elem.css(styles)},revertStyles:function(){$.each(Utils.array(arguments),function(i,elem){elem=$(elem);elem.removeAttr("style");elem.attr("style","");if(elem.data("styles")){elem.attr("style",elem.data("styles")).data("styles",null)}})},moveOut:function(elem){Utils.forceStyles(elem,{position:"absolute",left:-1e4})},moveIn:function(){Utils.revertStyles.apply(Utils,Utils.array(arguments))},elem:function(elem){if(elem instanceof $){return{$:elem,dom:elem[0]}}else{return{$:$(elem),dom:elem}}},hide:function(elem,speed,callback){callback=callback||F;var el=Utils.elem(elem),$elem=el.$;elem=el.dom;if(!$elem.data("opacity")){$elem.data("opacity",$elem.css("opacity"))}var style={opacity:0};if(speed){var complete=IE<9&&elem?function(){Utils.removeAlpha(elem);elem.style.visibility="hidden";callback.call(elem)}:callback;Utils.animate(elem,style,{duration:speed,complete:complete,stop:true})}else{if(IE<9&&elem){Utils.removeAlpha(elem);elem.style.visibility="hidden"}else{$elem.css(style)}}},show:function(elem,speed,callback){callback=callback||F;var el=Utils.elem(elem),$elem=el.$;elem=el.dom;var saved=parseFloat($elem.data("opacity"))||1,style={opacity:saved};if(speed){if(IE<9){$elem.css("opacity",0);elem.style.visibility="visible"}var complete=IE<9&&elem?function(){if(style.opacity==1){Utils.removeAlpha(elem)}callback.call(elem)}:callback;Utils.animate(elem,style,{duration:speed,complete:complete,stop:true})}else{if(IE<9&&style.opacity==1&&elem){Utils.removeAlpha(elem);elem.style.visibility="visible"}else{$elem.css(style)}}},optimizeTouch:function(){var node,evs,fakes,travel,evt={},handler=function(e){e.preventDefault();evt=$.extend({},e,true)},attach=function(){this.evt=evt},fake=function(){this.handler.call(node,this.evt)};return function(elem){$(elem).bind("touchend",function(e){node=e.target;travel=true;while(node.parentNode&&node!=e.currentTarget&&travel){evs=$(node).data("events");fakes=$(node).data("fakes");if(evs&&"click"in evs){travel=false;e.preventDefault();$(node).click(handler).click();evs.click.pop();$.each(evs.click,attach);$(node).data("fakes",evs.click);delete evs.click}else if(fakes){travel=false;e.preventDefault();$.each(fakes,fake)}node=node.parentNode}})}}(),wait:function(options){options=$.extend({until:FALSE,success:F,error:function(){Galleria.raise("Could not complete wait function.")},timeout:3e3},options);var start=Utils.timestamp(),elapsed,now,fn=function(){now=Utils.timestamp();elapsed=now-start;if(options.until(elapsed)){options.success();return false}if(typeof options.timeout=="number"&&now>=start+options.timeout){options.error();return false}window.setTimeout(fn,10)};window.setTimeout(fn,10)},toggleQuality:function(img,force){if(IE!==7&&IE!==8||!img||img.nodeName.toUpperCase()!="IMG"){return}if(typeof force==="undefined"){force=img.style.msInterpolationMode==="nearest-neighbor"}img.style.msInterpolationMode=force?"bicubic":"nearest-neighbor"},insertStyleTag:function(styles,id){if(id&&$("#"+id).length){return}var style=doc.createElement("style");if(id){style.id=id}DOM().head.appendChild(style);if(style.styleSheet){style.styleSheet.cssText=styles}else{var cssText=doc.createTextNode(styles);style.appendChild(cssText)}},loadScript:function(url,callback){var done=false,script=$("").attr({src:url,async:true}).get(0);script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){done=true;script.onload=script.onreadystatechange=null;if(typeof callback==="function"){callback.call(this,this)}}};DOM().head.appendChild(script)},parseValue:function(val){if(typeof val==="number"){return val}else if(typeof val==="string"){var arr=val.match(/\-?\d|\./g);return arr&&arr.constructor===Array?arr.join("")*1:0}else{return 0}},timestamp:function(){return(new Date).getTime()},loadCSS:function(href,id,callback){var link,length;$("link[rel=stylesheet]").each(function(){if(new RegExp(href).test(this.href)){link=this;return false}});if(typeof id==="function"){callback=id;id=undef}callback=callback||F;if(link){callback.call(link,link);return link}length=doc.styleSheets.length;if($("#"+id).length){$("#"+id).attr("href",href);length--}else{link=$("").attr({rel:"stylesheet",href:href,id:id}).get(0);var styles=$('link[rel="stylesheet"], style');if(styles.length){styles.get(0).parentNode.insertBefore(link,styles[0])}else{DOM().head.appendChild(link)}if(IE){if(length>=31){Galleria.raise("You have reached the browser stylesheet limit (31)",true);return}}}if(typeof callback==="function"){var $loader=$("").attr("id","galleria-loader").hide().appendTo(DOM().body);Utils.wait({until:function(){return $loader.height()==1},success:function(){$loader.remove();callback.call(link,link)},error:function(){$loader.remove();Galleria.raise("Theme CSS could not load after 20 sec. "+(Galleria.QUIRK?"Your browser is in Quirks Mode, please add a correct doctype.":"Please download the latest theme at http://galleria.io/customer/."),true)},timeout:5e3})}return link}}}(),_transitions=function(){var _slide=function(params,complete,fade,door){var easing=this.getOptions("easing"),distance=this.getStageWidth(),from={left:distance*(params.rewind?-1:1)},to={left:0};if(fade){from.opacity=0;to.opacity=1}else{from.opacity=1}$(params.next).css(from);Utils.animate(params.next,to,{duration:params.speed,complete:function(elems){return function(){complete();elems.css({left:0})}}($(params.next).add(params.prev)),queue:false,easing:easing});if(door){params.rewind=!params.rewind}if(params.prev){from={left:0};to={left:distance*(params.rewind?1:-1)};if(fade){from.opacity=1;to.opacity=0}$(params.prev).css(from);Utils.animate(params.prev,to,{duration:params.speed,queue:false,easing:easing,complete:function(){$(this).css("opacity",0)}})}};return{active:false,init:function(effect,params,complete){if(_transitions.effects.hasOwnProperty(effect)){_transitions.effects[effect].call(this,params,complete)}},effects:{fade:function(params,complete){$(params.next).css({opacity:0,left:0});Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete});if(params.prev){$(params.prev).css("opacity",1).show();Utils.animate(params.prev,{opacity:0},{duration:params.speed})}},flash:function(params,complete){$(params.next).css({opacity:0,left:0});if(params.prev){Utils.animate(params.prev,{opacity:0},{duration:params.speed/2,complete:function(){Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete})}})}else{Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete})}},pulse:function(params,complete){if(params.prev){$(params.prev).hide()}$(params.next).css({opacity:0,left:0}).show();Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete})},slide:function(params,complete){_slide.apply(this,Utils.array(arguments))},fadeslide:function(params,complete){_slide.apply(this,Utils.array(arguments).concat([true]))},doorslide:function(params,complete){_slide.apply(this,Utils.array(arguments).concat([false,true]))}}}}();_nativeFullscreen.listen();Galleria=function(){var self=this;this._options={};this._playing=false;this._playtime=5e3;this._active=null;this._queue={length:0};this._data=[];this._dom={};this._thumbnails=[];this._layers=[];this._initialized=false;this._firstrun=false;this._stageWidth=0;this._stageHeight=0;this._target=undef;this._binds=[];this._id=parseInt(Math.random()*1e4,10);var divs="container stage images image-nav image-nav-left image-nav-right "+"info info-text info-title info-description "+"thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right "+"loader counter tooltip",spans="current total";$.each(divs.split(" "),function(i,elemId){self._dom[elemId]=Utils.create("galleria-"+elemId)});$.each(spans.split(" "),function(i,elemId){self._dom[elemId]=Utils.create("galleria-"+elemId,"span")});var keyboard=this._keyboard={keys:{UP:38,DOWN:40,LEFT:37,RIGHT:39,RETURN:13,ESCAPE:27,BACKSPACE:8,SPACE:32},map:{},bound:false,press:function(e){var key=e.keyCode||e.which;if(key in keyboard.map&&typeof keyboard.map[key]==="function"){keyboard.map[key].call(self,e)}},attach:function(map){var key,up;for(key in map){if(map.hasOwnProperty(key)){up=key.toUpperCase();if(up in keyboard.keys){keyboard.map[keyboard.keys[up]]=map[key]}else{keyboard.map[up]=map[key]}}}if(!keyboard.bound){keyboard.bound=true;$doc.bind("keydown",keyboard.press)}},detach:function(){keyboard.bound=false;keyboard.map={};$doc.unbind("keydown",keyboard.press)}};var controls=this._controls={0:undef,1:undef,active:0,swap:function(){controls.active=controls.active?0:1},getActive:function(){return controls[controls.active]},getNext:function(){return controls[1-controls.active]}};var carousel=this._carousel={next:self.$("thumb-nav-right"),prev:self.$("thumb-nav-left"),width:0,current:0,max:0,hooks:[],update:function(){var w=0,h=0,hooks=[0];$.each(self._thumbnails,function(i,thumb){if(thumb.ready){w+=thumb.outerWidth||$(thumb.container).outerWidth(true);hooks[i+1]=w;h=Math.max(h,thumb.outerHeight||$(thumb.container).outerHeight(true))}});self.$("thumbnails").css({width:w,height:h});carousel.max=w;carousel.hooks=hooks;carousel.width=self.$("thumbnails-list").width();carousel.setClasses();self.$("thumbnails-container").toggleClass("galleria-carousel",w>carousel.width);carousel.width=self.$("thumbnails-list").width()},bindControls:function(){var i;carousel.next.bind("click",function(e){e.preventDefault();if(self._options.carouselSteps==="auto"){for(i=carousel.current;icarousel.width){carousel.set(i-2);break}}}else{carousel.set(carousel.current+self._options.carouselSteps)}});carousel.prev.bind("click",function(e){e.preventDefault();if(self._options.carouselSteps==="auto"){for(i=carousel.current;i>=0;i--){if(carousel.hooks[carousel.current]-carousel.hooks[i]>carousel.width){carousel.set(i+2);break}else if(i===0){carousel.set(0);break}}}else{carousel.set(carousel.current-self._options.carouselSteps)}})},set:function(i){i=Math.max(i,0);while(carousel.hooks[i-1]+carousel.width>=carousel.max&&i>=0){i--}carousel.current=i;carousel.animate()},getLast:function(i){return(i||carousel.current)-1},follow:function(i){if(i===0||i===carousel.hooks.length-2){carousel.set(i);return}var last=carousel.current;while(carousel.hooks[last]-carousel.hooks[carousel.current]last){carousel.set(i-last+carousel.current+2)}},setClasses:function(){carousel.prev.toggleClass("disabled",!carousel.current);carousel.next.toggleClass("disabled",carousel.hooks[carousel.current]+carousel.width>=carousel.max)},animate:function(to){carousel.setClasses();var num=carousel.hooks[carousel.current]*-1;if(isNaN(num)){return}Utils.animate(self.get("thumbnails"),{left:num},{duration:self._options.carouselSpeed,easing:self._options.easing,queue:false})}};var tooltip=this._tooltip={initialized:false,open:false,timer:"tooltip"+self._id,swapTimer:"swap"+self._id,init:function(){tooltip.initialized=true;var css=".galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;"+"opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}";Utils.insertStyleTag(css,"galleria-tooltip");self.$("tooltip").css({opacity:.8,visibility:"visible",display:"none"})},move:function(e){var mouseX=self.getMousePosition(e).x,mouseY=self.getMousePosition(e).y,$elem=self.$("tooltip"),x=mouseX,y=mouseY,height=$elem.outerHeight(true)+1,width=$elem.outerWidth(true),limitY=height+15;var maxX=self.$("container").width()-width-2,maxY=self.$("container").height()-height-2;if(!isNaN(x)&&!isNaN(y)){x+=10;y-=height+8;x=Math.max(0,Math.min(maxX,x));y=Math.max(0,Math.min(maxY,y));if(mouseY7){cssMap.nextholder+="background:#000;filter:alpha(opacity=0);";cssMap.prevholder+="background:#000;filter:alpha(opacity=0);"}$.each(cssMap,function(key,value){css+=".galleria-"+prefix+key+"{"+value+"}"});css+=".galleria-"+prefix+"box.iframe .galleria-"+prefix+"prevholder,"+".galleria-"+prefix+"box.iframe .galleria-"+prefix+"nextholder{"+"width:100px;height:100px;top:50%;margin-top:-70px}";Utils.insertStyleTag(css,"galleria-lightbox");$.each(elems.split(" "),function(i,elemId){self.addElement("lightbox-"+elemId);el[elemId]=lightbox.elems[elemId]=self.get("lightbox-"+elemId)});lightbox.image=new Galleria.Picture;$.each({box:"shadow content close prevholder nextholder",info:"title counter",content:"info image",prevholder:"prev",nextholder:"next"},function(key,val){var arr=[];$.each(val.split(" "),function(i,prop){arr.push(prefix+prop)});appends[prefix+key]=arr});self.append(appends);$(el.image).append(lightbox.image.container);$(DOM().body).append(el.overlay,el.box);Utils.optimizeTouch(el.box);hover($(el.close).bind("click",lightbox.hide).html("×"));$.each(["Prev","Next"],function(i,dir){var $d=$(el[dir.toLowerCase()]).html(/v/.test(dir)?"‹ ":" ›"),$e=$(el[dir.toLowerCase()+"holder"]);$e.bind("click",function(){lightbox["show"+dir]()});if(IE<8||Galleria.TOUCH){$d.show();return}$e.hover(function(){$d.show()},function(e){$d.stop().fadeOut(200)})});$(el.overlay).bind("click",lightbox.hide);if(Galleria.IPAD){self._options.lightboxTransitionSpeed=0}},rescale:function(event){var width=Math.min($win.width()-40,lightbox.width),height=Math.min($win.height()-60,lightbox.height),ratio=Math.min(width/lightbox.width,height/lightbox.height),destWidth=Math.round(lightbox.width*ratio)+40,destHeight=Math.round(lightbox.height*ratio)+60,to={width:destWidth,height:destHeight,"margin-top":Math.ceil(destHeight/2)*-1,"margin-left":Math.ceil(destWidth/2)*-1}; if(event){$(lightbox.elems.box).css(to)}else{$(lightbox.elems.box).animate(to,{duration:self._options.lightboxTransitionSpeed,easing:self._options.easing,complete:function(){var image=lightbox.image,speed=self._options.lightboxFadeSpeed;self.trigger({type:Galleria.LIGHTBOX_IMAGE,imageTarget:image.image});$(image.container).show();$(image.image).animate({opacity:1},speed);Utils.show(lightbox.elems.info,speed)}})}},hide:function(){lightbox.image.image=null;$win.unbind("resize",lightbox.rescale);$(lightbox.elems.box).hide();Utils.hide(lightbox.elems.info);self.detachKeyboard();self.attachKeyboard(lightbox.keymap);lightbox.keymap=false;Utils.hide(lightbox.elems.overlay,200,function(){$(this).hide().css("opacity",self._options.overlayOpacity);self.trigger(Galleria.LIGHTBOX_CLOSE)})},showNext:function(){lightbox.show(self.getNext(lightbox.active))},showPrev:function(){lightbox.show(self.getPrev(lightbox.active))},show:function(index){lightbox.active=index=typeof index==="number"?index:self.getIndex()||0;if(!lightbox.initialized){lightbox.init()}if(!lightbox.keymap){lightbox.keymap=$.extend({},self._keyboard.map);self.attachKeyboard({escape:lightbox.hide,right:lightbox.showNext,left:lightbox.showPrev})}$win.unbind("resize",lightbox.rescale);var data=self.getData(index),total=self.getDataLength(),n=self.getNext(index),ndata,p,i;Utils.hide(lightbox.elems.info);try{for(i=self._options.preload;i>0;i--){p=new Galleria.Picture;ndata=self.getData(n);p.preload("big"in ndata?ndata.big:ndata.image);n=self.getNext(n)}}catch(e){}lightbox.image.isIframe=!!data.iframe;$(lightbox.elems.box).toggleClass("iframe",!!data.iframe);lightbox.image.load(data.iframe||data.big||data.image,function(image){if(image.isIframe){var cw=$(window).width(),ch=$(window).height();if(self._options.maxVideoSize){var r=Math.min(self._options.maxVideoSize/cw,self._options.maxVideoSize/ch);if(r<1){cw*=r;ch*=r}}lightbox.width=cw;lightbox.height=ch}else{lightbox.width=image.original.width;lightbox.height=image.original.height}$(image.image).css({width:image.isIframe?"100%":"100.1%",height:image.isIframe?"100%":"100.1%",top:0,zIndex:99998,opacity:0,visibility:"visible"});lightbox.elems.title.innerHTML=data.title||"";lightbox.elems.counter.innerHTML=index+1+" / "+total;$win.resize(lightbox.rescale);lightbox.rescale()});$(lightbox.elems.overlay).show().css("visibility","visible");$(lightbox.elems.box).show()}};var _timer=this._timer={trunk:{},add:function(id,fn,delay,loop){id=id||(new Date).getTime();loop=loop||false;this.clear(id);if(loop){var old=fn;fn=function(){old();_timer.add(id,fn,delay)}}this.trunk[id]=window.setTimeout(fn,delay)},clear:function(id){var del=function(i){window.clearTimeout(this.trunk[i]);delete this.trunk[i]},i;if(!!id&&id in this.trunk){del.call(this,id)}else if(typeof id==="undefined"){for(i in this.trunk){if(this.trunk.hasOwnProperty(i)){del.call(this,i)}}}}};return this};Galleria.prototype={constructor:Galleria,init:function(target,options){var self=this;options=_legacyOptions(options);this._original={target:target,options:options,data:null};this._target=this._dom.target=target.nodeName?target:$(target).get(0);this._original.html=this._target.innerHTML;_instances.push(this);if(!this._target){Galleria.raise("Target not found",true);return}this._options={autoplay:false,carousel:true,carouselFollow:true,carouselSpeed:400,carouselSteps:"auto",clicknext:false,dailymotion:{foreground:"%23EEEEEE",highlight:"%235BCEC5",background:"%23222222",logo:0,hideInfos:1},dataConfig:function(elem){return{}},dataSelector:"img",dataSort:false,dataSource:this._target,debug:undef,dummy:undef,easing:"galleria",extend:function(options){},fullscreenCrop:undef,fullscreenDoubleTap:true,fullscreenTransition:undef,height:0,idleMode:true,idleTime:3e3,idleSpeed:200,imageCrop:false,imageMargin:0,imagePan:false,imagePanSmoothness:12,imagePosition:"50%",imageTimeout:undef,initialTransition:undef,keepSource:false,layerFollow:true,lightbox:false,lightboxFadeSpeed:200,lightboxTransitionSpeed:200,linkSourceImages:true,maxScaleRatio:undef,maxVideoSize:undef,minScaleRatio:undef,overlayOpacity:.85,overlayBackground:"#0b0b0b",pauseOnInteraction:true,popupLinks:false,preload:2,queue:true,responsive:true,show:0,showInfo:true,showCounter:true,showImagenav:true,swipe:true,thumbCrop:true,thumbEventType:"click",thumbFit:true,thumbMargin:0,thumbQuality:"auto",thumbDisplayOrder:true,thumbnails:true,touchTransition:undef,transition:"fade",transitionInitial:undef,transitionSpeed:400,trueFullscreen:true,useCanvas:false,vimeo:{title:0,byline:0,portrait:0,color:"aaaaaa"},wait:5e3,width:"auto",youtube:{modestbranding:1,autohide:1,color:"white",hd:1,rel:0,showinfo:0}};this._options.initialTransition=this._options.initialTransition||this._options.transitionInitial;if(options&&options.debug===false){DEBUG=false}if(options&&typeof options.imageTimeout==="number"){TIMEOUT=options.imageTimeout}if(options&&typeof options.dummy==="string"){DUMMY=options.dummy}$(this._target).children().hide();if(Galleria.QUIRK){Galleria.raise("Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML and add a correct doctype.")}if(typeof Galleria.theme==="object"){this._init()}else{_pool.push(this)}return this},_init:function(){var self=this,options=this._options;if(this._initialized){Galleria.raise("Init failed: Gallery instance already initialized.");return this}this._initialized=true;if(!Galleria.theme){Galleria.raise("Init failed: No theme found.",true);return this}$.extend(true,options,Galleria.theme.defaults,this._original.options,Galleria.configure.options);(function(can){if(!("getContext"in can)){can=null;return}_canvas=_canvas||{elem:can,context:can.getContext("2d"),cache:{},length:0}})(doc.createElement("canvas"));this.bind(Galleria.DATA,function(){this._original.data=this._data;this.get("total").innerHTML=this.getDataLength();var $container=this.$("container");if(self._options.height<2){self._userRatio=self._ratio=self._options.height}var num={width:0,height:0};var testHeight=function(){return self.$("stage").height()};Utils.wait({until:function(){num=self._getWH();$container.width(num.width).height(num.height);return testHeight()&&num.width&&num.height>50},success:function(){self._width=num.width;self._height=num.height;self._ratio=self._ratio||num.height/num.width;if(Galleria.WEBKIT){window.setTimeout(function(){self._run()},1)}else{self._run()}},error:function(){if(testHeight()){Galleria.raise("Could not extract sufficient width/height of the gallery container. Traced measures: width:"+num.width+"px, height: "+num.height+"px.",true)}else{Galleria.raise("Could not extract a stage height from the CSS. Traced height: "+testHeight()+"px.",true)}},timeout:typeof this._options.wait=="number"?this._options.wait:false})});this.append({"info-text":["info-title","info-description"],info:["info-text"],"image-nav":["image-nav-right","image-nav-left"],stage:["images","loader","counter","image-nav"],"thumbnails-list":["thumbnails"],"thumbnails-container":["thumb-nav-left","thumbnails-list","thumb-nav-right"],container:["stage","thumbnails-container","info","tooltip"]});Utils.hide(this.$("counter").append(this.get("current"),doc.createTextNode(" / "),this.get("total")));this.setCounter("–");Utils.hide(self.get("tooltip"));this.$("container").addClass(Galleria.TOUCH?"touch":"notouch");$.each(new Array(2),function(i){var image=new Galleria.Picture;$(image.container).css({position:"absolute",top:0,left:0}).prepend(self._layers[i]=$(Utils.create("galleria-layer")).css({position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:2})[0]);self.$("images").append(image.container);self._controls[i]=image});this.$("images").css({position:"relative",top:0,left:0,width:"100%",height:"100%"});this.$("thumbnails, thumbnails-list").css({overflow:"hidden",position:"relative"});this.$("image-nav-right, image-nav-left").bind("click",function(e){if(options.clicknext){e.stopPropagation()}if(options.pauseOnInteraction){self.pause()}var fn=/right/.test(this.className)?"next":"prev";self[fn]()});$.each(["info","counter","image-nav"],function(i,el){if(options["show"+el.substr(0,1).toUpperCase()+el.substr(1).replace(/-/,"")]===false){Utils.moveOut(self.get(el.toLowerCase()))}});this.load();if(!options.keepSource&&!IE){this._target.innerHTML=""}if(this.get("errors")){this.appendChild("target","errors")}this.appendChild("target","container");if(options.carousel){var count=0,show=options.show;this.bind(Galleria.THUMBNAIL,function(){this.updateCarousel();if(++count==this.getDataLength()&&typeof show=="number"&&show>0){this._carousel.follow(show)}})}if(options.responsive){$win.bind("resize",function(){if(!self.isFullscreen()){self.resize()}})}if(options.swipe){(function(images){var swipeStart=[0,0],swipeStop=[0,0],limitX=30,limitY=100,multi=false,tid=0,data,ev={start:"touchstart",move:"touchmove",stop:"touchend"},getData=function(e){return e.originalEvent.touches?e.originalEvent.touches[0]:e},moveHandler=function(e){if(e.originalEvent.touches&&e.originalEvent.touches.length>1){return}data=getData(e);swipeStop=[data.pageX,data.pageY];if(!swipeStart[0]){swipeStart=swipeStop}if(Math.abs(swipeStart[0]-swipeStop[0])>10){e.preventDefault()}},upHandler=function(e){images.unbind(ev.move,moveHandler);if(e.originalEvent.touches&&e.originalEvent.touches.length||multi){multi=!multi;return}if(Utils.timestamp()-tid<1e3&&Math.abs(swipeStart[0]-swipeStop[0])>limitX&&Math.abs(swipeStart[1]-swipeStop[1])swipeStop[0]?"next":"prev"]()}swipeStart=swipeStop=[0,0]};images.bind(ev.start,function(e){if(e.originalEvent.touches&&e.originalEvent.touches.length>1){return}data=getData(e);tid=Utils.timestamp();swipeStart=swipeStop=[data.pageX,data.pageY];images.bind(ev.move,moveHandler).one(ev.stop,upHandler)})})(self.$("images"));if(options.fullscreenDoubleTap){this.$("stage").bind("touchstart",function(){var last,cx,cy,lx,ly,now,getData=function(e){return e.originalEvent.touches?e.originalEvent.touches[0]:e};return function(e){now=Galleria.utils.timestamp();cx=getData(e).pageX;cy=getData(e).pageY;if(now-last<500&&cx-lx<20&&cy-ly<20){self.toggleFullscreen();e.preventDefault();self.$("stage").unbind("touchend",arguments.callee);return}last=now;lx=cx;ly=cy}}())}}Utils.optimizeTouch(this.get("container"));$.each(Galleria.on.binds,function(i,bind){if($.inArray(bind.hash,self._binds)==-1){self.bind(bind.type,bind.callback)}});return this},addTimer:function(){this._timer.add.apply(this._timer,Utils.array(arguments));return this},clearTimer:function(){this._timer.clear.apply(this._timer,Utils.array(arguments));return this},_getWH:function(){var $container=this.$("container"),$target=this.$("target"),self=this,num={},arr;$.each(["width","height"],function(i,m){if(self._options[m]&&typeof self._options[m]==="number"){num[m]=self._options[m]}else{arr=[Utils.parseValue($container.css(m)),Utils.parseValue($target.css(m)),$container[m](),$target[m]()];if(!self["_"+m]){arr.splice(arr.length,Utils.parseValue($container.css("min-"+m)),Utils.parseValue($target.css("min-"+m)))}num[m]=Math.max.apply(Math,arr)}});if(self._userRatio){num.height=num.width*self._userRatio}return num},_createThumbnails:function(push){this.get("total").innerHTML=this.getDataLength();var src,thumb,data,special,$container,self=this,o=this._options,i=push?this._data.length-push.length:0,chunk=i,thumbchunk=[],loadindex=0,gif=IE<8?"http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif":"data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D",active=function(){var a=self.$("thumbnails").find(".active");if(!a.length){return false}return a.find("img").attr("src")}(),optval=typeof o.thumbnails==="string"?o.thumbnails.toLowerCase():null,getStyle=function(prop){return doc.defaultView&&doc.defaultView.getComputedStyle?doc.defaultView.getComputedStyle(thumb.container,null)[prop]:$container.css(prop)},fake=function(image,index,container){return function(){$(container).append(image);self.trigger({type:Galleria.THUMBNAIL,thumbTarget:image,index:index,galleriaData:self.getData(index)})}},onThumbEvent=function(e){if(o.pauseOnInteraction){self.pause()}var index=$(e.currentTarget).data("index");if(self.getIndex()!==index){self.show(index)}e.preventDefault()},thumbComplete=function(thumb,callback){$(thumb.container).css("visibility","visible");self.trigger({type:Galleria.THUMBNAIL,thumbTarget:thumb.image,index:thumb.data.order,galleriaData:self.getData(thumb.data.order)});if(typeof callback=="function"){callback.call(self,thumb)}},onThumbLoad=function(thumb,callback){thumb.scale({width:thumb.data.width,height:thumb.data.height,crop:o.thumbCrop,margin:o.thumbMargin,canvas:o.useCanvas,complete:function(thumb){var top=["left","top"],arr=["Width","Height"],m,css,data=self.getData(thumb.index),special=data.thumb.split(":");$.each(arr,function(i,measure){m=measure.toLowerCase();if((o.thumbCrop!==true||o.thumbCrop===m)&&o.thumbFit){css={};css[m]=thumb[m];$(thumb.container).css(css);css={};css[top[i]]=0;$(thumb.image).css(css)}thumb["outer"+measure]=$(thumb.container)["outer"+measure](true)});Utils.toggleQuality(thumb.image,o.thumbQuality===true||o.thumbQuality==="auto"&&thumb.original.widthself._thumbnails.length-1){return}var thumb=self._thumbnails[ind],data=thumb.data,special=data.src.split(":"),callback=function(){if(++loaded==arr.length&&typeof complete=="function"){complete.call(self)}},thumbload=$(thumb.container).data("thumbload");if(thumb.video){thumbload.call(self,thumb,callback)}else{thumb.load(data.src,function(thumb){thumbload.call(self,thumb,callback)})}});return this},lazyLoadChunks:function(size,delay){var len=this.getDataLength(),i=0,n=0,arr=[],temp=[],self=this;delay=delay||0;for(;i50},success:function(){_galleries.push(self);Utils.show(self.get("counter"));if(self._options.carousel){self._carousel.bindControls()}if(self._options.autoplay){self.pause();if(typeof self._options.autoplay==="number"){self._playtime=self._options.autoplay}self._playing=true}if(self._firstrun){if(self._options.autoplay){self.trigger(Galleria.PLAY)}if(typeof self._options.show==="number"){self.show(self._options.show)}return}self._firstrun=true;if(Galleria.History){Galleria.History.change(function(value){if(isNaN(value)){window.history.go(-1)}else{self.show(value,undef,true)}})}self.trigger(Galleria.READY);Galleria.theme.init.call(self,self._options);$.each(Galleria.ready.callbacks,function(i,fn){if(typeof fn=="function"){fn.call(self,self._options)}});self._options.extend.call(self,self._options);if(/^[0-9]{1,4}$/.test(HASH)&&Galleria.History){self.show(HASH,undef,true)}else if(self._data[self._options.show]){self.show(self._options.show)}if(self._options.autoplay){self.trigger(Galleria.PLAY)}},error:function(){Galleria.raise("Stage width or height is too small to show the gallery. Traced measures: width:"+self._stageWidth+"px, height: "+self._stageHeight+"px.",true)}})},load:function(source,selector,config){var self=this,o=this._options;this._data=[];this._thumbnails=[];this.$("thumbnails").empty();if(typeof selector==="function"){config=selector;selector=null}source=source||o.dataSource;selector=selector||o.dataSelector;config=config||o.dataConfig;if(/^function Object/.test(source.constructor)){source=[source]}if(source.constructor===Array){if(this.validate(source)){this._data=source}else{Galleria.raise("Load failed: JSON Array not valid.")}}else{selector+=",.video,.iframe";$(source).find(selector).each(function(i,elem){elem=$(elem);var data={},parent=elem.parent(),href=parent.attr("href"),rel=parent.attr("rel");if(href&&(elem[0].nodeName=="IMG"||elem.hasClass("video"))&&_videoTest(href)){data.video=href}else if(href&&elem.hasClass("iframe")){data.iframe=href}else{data.image=data.big=href}if(rel){data.big=rel}$.each("big title description link layer".split(" "),function(i,val){if(elem.data(val)){data[val]=elem.data(val)}});self._data.push($.extend({title:elem.attr("title")||"",thumb:elem.attr("src"),image:elem.attr("src"),big:elem.attr("src"),description:elem.attr("alt")||"",link:elem.attr("longdesc"),original:elem.get(0)},data,config(elem)))})}if(typeof o.dataSort=="function"){protoArray.sort.call(this._data,o.dataSort)}else if(o.dataSort=="random"){this._data.sort(function(){return Math.round(Math.random())-.5})}if(this.getDataLength()){this._parseData().trigger(Galleria.DATA)}return this},_parseData:function(){var self=this,current;$.each(this._data,function(i,data){current=self._data[i];if("thumb"in data===false){current.thumb=data.image}if(!"big"in data){current.big=data.image}if("video"in data){var result=_videoTest(data.video);if(result){current.iframe=_video[result.provider].embed(result.id)+function(){if(typeof self._options[result.provider]=="object"){var str="?",arr=[];$.each(self._options[result.provider],function(key,val){arr.push(key+"="+val)});if(result.provider=="youtube"){arr=["wmode=opaque"].concat(arr)}return str+arr.join("&")}return""}();delete current.video;if(!("thumb"in current)||!current.thumb){current.thumb=result.provider+":"+result.id}}}});return this},destroy:function(){this.$("target").data("galleria",null);this.$("container").unbind("galleria");this.get("target").innerHTML=this._original.html;this.clearTimer();Utils.removeFromArray(_instances,this);Utils.removeFromArray(_galleries,this);return this},splice:function(){var self=this,args=Utils.array(arguments);window.setTimeout(function(){protoArray.splice.apply(self._data,args);self._parseData()._createThumbnails()},2);return self},push:function(){var self=this,args=Utils.array(arguments);if(args.length==1&&args[0].constructor==Array){args=args[0]}window.setTimeout(function(){protoArray.push.apply(self._data,args);self._parseData()._createThumbnails(args)},2);return self},_getActive:function(){return this._controls.getActive()},validate:function(data){return true},bind:function(type,fn){type=_patchEvent(type);this.$("container").bind(type,this.proxy(fn));return this},unbind:function(type){type=_patchEvent(type);this.$("container").unbind(type);return this},trigger:function(type){type=typeof type==="object"?$.extend(type,{scope:this}):{type:_patchEvent(type),scope:this};this.$("container").trigger(type);return this},addIdleState:function(elem,styles,from,hide){this._idle.add.apply(this._idle,Utils.array(arguments));return this},removeIdleState:function(elem){this._idle.remove.apply(this._idle,Utils.array(arguments));return this},enterIdleMode:function(){this._idle.hide();return this},exitIdleMode:function(){this._idle.showAll();return this},enterFullscreen:function(callback){this._fullscreen.enter.apply(this,Utils.array(arguments));return this},exitFullscreen:function(callback){this._fullscreen.exit.apply(this,Utils.array(arguments));return this},toggleFullscreen:function(callback){this._fullscreen[this.isFullscreen()?"exit":"enter"].apply(this,Utils.array(arguments));return this},bindTooltip:function(elem,value){this._tooltip.bind.apply(this._tooltip,Utils.array(arguments));return this},defineTooltip:function(elem,value){this._tooltip.define.apply(this._tooltip,Utils.array(arguments));return this},refreshTooltip:function(elem){this._tooltip.show.apply(this._tooltip,Utils.array(arguments));return this},openLightbox:function(){this._lightbox.show.apply(this._lightbox,Utils.array(arguments));return this},closeLightbox:function(){this._lightbox.hide.apply(this._lightbox,Utils.array(arguments));return this},getActiveImage:function(){return this._getActive().image||undef},getActiveThumb:function(){return this._thumbnails[this._active].image||undef},getMousePosition:function(e){return{x:e.pageX-this.$("container").offset().left,y:e.pageY-this.$("container").offset().top}},addPan:function(img){if(this._options.imageCrop===false){return}img=$(img||this.getActiveImage());var self=this,x=img.width()/2,y=img.height()/2,destX=parseInt(img.css("left"),10),destY=parseInt(img.css("top"),10),curX=destX||0,curY=destY||0,distX=0,distY=0,active=false,ts=Utils.timestamp(),cache=0,move=0,position=function(dist,cur,pos){if(dist>0){move=Math.round(Math.max(dist*-1,Math.min(0,cur)));if(cache!==move){cache=move;if(IE===8){img.parent()["scroll"+pos](move*-1)}else{var css={};css[pos.toLowerCase()]=move;img.css(css)}}}},calculate=function(e){if(Utils.timestamp()-ts<50){return}active=true;x=self.getMousePosition(e).x;y=self.getMousePosition(e).y},loop=function(e){if(!active){return}distX=img.width()-self._stageWidth;distY=img.height()-self._stageHeight;destX=x/self._stageWidth*distX*-1;destY=y/self._stageHeight*distY*-1;curX+=(destX-curX)/self._options.imagePanSmoothness;curY+=(destY-curY)/self._options.imagePanSmoothness;position(distY,curY,"Top");position(distX,curX,"Left")};if(IE===8){img.parent().scrollTop(curY*-1).scrollLeft(curX*-1);img.css({top:0,left:0})}this.$("stage").unbind("mousemove",calculate).bind("mousemove",calculate);this.addTimer("pan"+self._id,loop,50,true);return this},proxy:function(fn,scope){if(typeof fn!=="function"){return F}scope=scope||this;return function(){return fn.apply(scope,Utils.array(arguments))}},removePan:function(){this.$("stage").unbind("mousemove");this.clearTimer("pan"+this._id);return this},addElement:function(id){var dom=this._dom;$.each(Utils.array(arguments),function(i,blueprint){dom[blueprint]=Utils.create("galleria-"+blueprint)});return this},attachKeyboard:function(map){this._keyboard.attach.apply(this._keyboard,Utils.array(arguments));return this},detachKeyboard:function(){this._keyboard.detach.apply(this._keyboard,Utils.array(arguments));return this},appendChild:function(parentID,childID){this.$(parentID).append(this.get(childID)||childID);return this},prependChild:function(parentID,childID){this.$(parentID).prepend(this.get(childID)||childID);return this},remove:function(elemID){this.$(Utils.array(arguments).join(",")).remove();return this},append:function(data){var i,j;for(i in data){if(data.hasOwnProperty(i)){if(data[i].constructor===Array){for(j=0;data[i][j];j++){this.appendChild(i,data[i][j])}}else{this.appendChild(i,data[i])}}}return this},_scaleImage:function(image,options){image=image||this._controls.getActive();if(!image){return}var self=this,complete,scaleLayer=function(img){$(img.container).children(":first").css({top:Math.max(0,Utils.parseValue(img.image.style.top)),left:Math.max(0,Utils.parseValue(img.image.style.left)),width:Utils.parseValue(img.image.width),height:Utils.parseValue(img.image.height)})};options=$.extend({width:this._stageWidth,height:this._stageHeight,crop:this._options.imageCrop,max:this._options.maxScaleRatio,min:this._options.minScaleRatio,margin:this._options.imageMargin,position:this._options.imagePosition,iframelimit:this._options.maxVideoSize},options);if(this._options.layerFollow&&this._options.imageCrop!==true){if(typeof options.complete=="function"){complete=options.complete;options.complete=function(){complete.call(image,image);scaleLayer(image)}}else{options.complete=scaleLayer}}else{$(image.container).children(":first").css({top:0,left:0})}image.scale(options);return this},updateCarousel:function(){this._carousel.update();return this},resize:function(measures,complete){if(typeof measures=="function"){complete=measures;measures=undef}measures=$.extend({width:0,height:0},measures);var self=this,$container=this.$("container");$.each(measures,function(m,val){if(!val){$container[m]("auto");measures[m]=self._getWH()[m]}});$.each(measures,function(m,val){$container[m](val)});return this.rescale(complete)},rescale:function(width,height,complete){var self=this;if(typeof width==="function"){complete=width;width=undef}var scale=function(){self._stageWidth=width||self.$("stage").width();self._stageHeight=height||self.$("stage").height();self._scaleImage();if(self._options.carousel){self.updateCarousel()}self.trigger(Galleria.RESCALE);if(typeof complete==="function"){complete.call(self)}};scale.call(self);return this},refreshImage:function(){this._scaleImage();if(this._options.imagePan){this.addPan()}return this},show:function(index,rewind,_history){if(this._queue.length>3||index===false||!this._options.queue&&this._queue.stalled){return}index=Math.max(0,Math.min(parseInt(index,10),this.getDataLength()-1));rewind=typeof rewind!=="undefined"?!!rewind:index1){return}if(self._options.clicknext&&!Galleria.TOUCH){if(self._options.pauseOnInteraction){self.pause()}self.next();return}if(data.link){if(self._options.popupLinks){win=window.open(data.link,"_blank")}else{window.location.href=data.link}return}if(self._options.lightbox){self.openLightbox()}})}self._playCheck();self.trigger({type:Galleria.IMAGE,index:queue.index,imageTarget:next.image,thumbTarget:thumb.image,galleriaData:data});protoArray.shift.call(self._queue);self._queue.stalled=false;if(self._queue.length){self._show()}}}(data,next,active,queue,thumb);if(this._options.carousel&&this._options.carouselFollow){this._carousel.follow(queue.index)}if(this._options.preload){var p,i,n=this.getNext(),ndata;try{for(i=this._options.preload;i>0;i--){p=new Galleria.Picture;ndata=self.getData(n);p.preload(this.isFullscreen()&&"big"in ndata?ndata.big:ndata.image);n=self.getNext(n)}}catch(e){}}Utils.show(next.container);next.isIframe=!!data.iframe;$(self._thumbnails[queue.index].container).addClass("active").siblings(".active").removeClass("active");self.trigger({type:Galleria.LOADSTART,cached:cached,index:queue.index,rewind:queue.rewind,imageTarget:next.image,thumbTarget:thumb.image,galleriaData:data});self._queue.stalled=true;next.load(src,function(next){var layer=$(self._layers[1-self._controls.active]).html(data.layer||"").hide();self._scaleImage(next,{complete:function(next){if("image"in active){Utils.toggleQuality(active.image,false)}Utils.toggleQuality(next.image,false);self.removePan();self.setInfo(queue.index);self.setCounter(queue.index);if(data.layer){layer.show();if(data.link||self._options.lightbox||self._options.clicknext){layer.css("cursor","pointer").unbind("mouseup").mouseup(mousetrigger)}}var transition=self._options.transition;$.each({initial:active.image===null,touch:Galleria.TOUCH,fullscreen:self.isFullscreen()},function(type,arg){if(arg&&self._options[type+"Transition"]!==undef){transition=self._options[type+"Transition"];return false}});if(transition in _transitions.effects===false){complete()}else{var params={prev:active.container,next:next.container,rewind:queue.rewind,speed:self._options.transitionSpeed||400};_transitions.active=true;_transitions.init.call(self,transition,params,complete)}self.trigger({type:Galleria.LOADFINISH,cached:cached,index:queue.index,rewind:queue.rewind,imageTarget:next.image,thumbTarget:self._thumbnails[queue.index].image,galleriaData:self.getData(queue.index)})}})})},getNext:function(base){base=typeof base==="number"?base:this.getIndex();return base===this.getDataLength()-1?0:base+1},getPrev:function(base){base=typeof base==="number"?base:this.getIndex();return base===0?this.getDataLength()-1:base-1},next:function(){if(this.getDataLength()>1){this.show(this.getNext(),false)}return this},prev:function(){if(this.getDataLength()>1){this.show(this.getPrev(),true)}return this},get:function(elemId){return elemId in this._dom?this._dom[elemId]:null},getData:function(index){return index in this._data?this._data[index]:this._data[this._active]},getDataLength:function(){return this._data.length},getIndex:function(){return typeof this._active==="number"?this._active:false},getStageHeight:function(){return this._stageHeight},getStageWidth:function(){return this._stageWidth},getOptions:function(key){return typeof key==="undefined"?this._options:this._options[key]},setOptions:function(key,value){if(typeof key==="object"){$.extend(this._options,key)}else{this._options[key]=value}return this},play:function(delay){this._playing=true; this._playtime=delay||this._playtime;this._playCheck();this.trigger(Galleria.PLAY);return this},pause:function(){this._playing=false;this.trigger(Galleria.PAUSE);return this},playToggle:function(delay){return this._playing?this.pause():this.play(delay)},isPlaying:function(){return this._playing},isFullscreen:function(){return this._fullscreen.active},_playCheck:function(){var self=this,played=0,interval=20,now=Utils.timestamp(),timer_id="play"+this._id;if(this._playing){this.clearTimer(timer_id);var fn=function(){played=Utils.timestamp()-now;if(played>=self._playtime&&self._playing){self.clearTimer(timer_id);self.next();return}if(self._playing){self.trigger({type:Galleria.PROGRESS,percent:Math.ceil(played/self._playtime*100),seconds:Math.floor(played/1e3),milliseconds:played});self.addTimer(timer_id,fn,interval)}};self.addTimer(timer_id,fn,interval)}},setPlaytime:function(delay){this._playtime=delay;return this},setIndex:function(val){this._active=val;return this},setCounter:function(index){if(typeof index==="number"){index++}else if(typeof index==="undefined"){index=this.getIndex()+1}this.get("current").innerHTML=index;if(IE){var count=this.$("counter"),opacity=count.css("opacity");if(parseInt(opacity,10)===1){Utils.removeAlpha(count[0])}else{this.$("counter").css("opacity",opacity)}}return this},setInfo:function(index){var self=this,data=this.getData(index);$.each(["title","description"],function(i,type){var elem=self.$("info-"+type);if(!!data[type]){elem[data[type].length?"show":"hide"]().html(data[type])}else{elem.empty().hide()}});return this},hasInfo:function(index){var check="title description".split(" "),i;for(i=0;check[i];i++){if(!!this.getData(index)[check[i]]){return true}}return false},jQuery:function(str){var self=this,ret=[];$.each(str.split(","),function(i,elemId){elemId=$.trim(elemId);if(self.get(elemId)){ret.push(elemId)}});var jQ=$(self.get(ret.shift()));$.each(ret,function(i,elemId){jQ=jQ.add(self.get(elemId))});return jQ},$:function(str){return this.jQuery.apply(this,Utils.array(arguments))}};$.each(_events,function(i,ev){var type=/_/.test(ev)?ev.replace(/_/g,""):ev;Galleria[ev.toUpperCase()]="galleria."+type});$.extend(Galleria,{IE9:IE===9,IE8:IE===8,IE7:IE===7,IE6:IE===6,IE:IE,WEBKIT:/webkit/.test(NAV),CHROME:/chrome/.test(NAV),SAFARI:/safari/.test(NAV)&&!/chrome/.test(NAV),QUIRK:IE&&doc.compatMode&&doc.compatMode==="BackCompat",MAC:/mac/.test(navigator.platform.toLowerCase()),OPERA:!!window.opera,IPHONE:/iphone/.test(NAV),IPAD:/ipad/.test(NAV),ANDROID:/android/.test(NAV),TOUCH:"ontouchstart"in doc});Galleria.addTheme=function(theme){if(!theme.name){Galleria.raise("No theme name specified")}if(typeof theme.defaults!=="object"){theme.defaults={}}else{theme.defaults=_legacyOptions(theme.defaults)}var css=false,reg;if(typeof theme.css==="string"){$("link").each(function(i,link){reg=new RegExp(theme.css);if(reg.test(link.href)){css=true;_themeLoad(theme);return false}});if(!css){$("script").each(function(i,script){reg=new RegExp("galleria\\."+theme.name.toLowerCase()+"\\.");if(reg.test(script.src)){css=script.src.replace(/[^\/]*$/,"")+theme.css;window.setTimeout(function(){Utils.loadCSS(css,"galleria-theme",function(){_themeLoad(theme)})},1)}})}if(!css){Galleria.raise("No theme CSS loaded")}}else{_themeLoad(theme)}return theme};Galleria.loadTheme=function(src,options){if($("script").filter(function(){return $(this).attr("src")==src}).length){return}var loaded=false,err;$(window).load(function(){if(!loaded){err=window.setTimeout(function(){if(!loaded&&!Galleria.theme){Galleria.raise("Galleria had problems loading theme at "+src+". Please check theme path or load manually.",true)}},2e4)}});Galleria.unloadTheme();Utils.loadScript(src,function(){loaded=true;window.clearTimeout(err)});return Galleria};Galleria.unloadTheme=function(){if(typeof Galleria.theme=="object"){$("script").each(function(i,script){if(new RegExp("galleria\\."+Galleria.theme.name+"\\.").test(script.src)){$(script).remove()}});Galleria.theme=undef}return Galleria};Galleria.get=function(index){if(!!_instances[index]){return _instances[index]}else if(typeof index!=="number"){return _instances}else{Galleria.raise("Gallery index "+index+" not found")}};Galleria.configure=function(key,value){var opts={};if(typeof key=="string"&&value){opts[key]=value;key=opts}else{$.extend(opts,key)}Galleria.configure.options=opts;$.each(Galleria.get(),function(i,instance){instance.setOptions(opts)});return Galleria};Galleria.configure.options={};Galleria.on=function(type,callback){if(!type){return}callback=callback||F;var hash=type+callback.toString().replace(/\s/g,"")+Utils.timestamp();$.each(Galleria.get(),function(i,instance){instance._binds.push(hash);instance.bind(type,callback)});Galleria.on.binds.push({type:type,callback:callback,hash:hash});return Galleria};Galleria.on.binds=[];Galleria.run=function(selector,options){if($.isFunction(options)){options={extend:options}}$(selector||"#galleria").galleria(options);return Galleria};Galleria.addTransition=function(name,fn){_transitions.effects[name]=fn;return Galleria};Galleria.utils=Utils;Galleria.log=function(){var args=Utils.array(arguments);if("console"in window&&"log"in window.console){try{return window.console.log.apply(window.console,args)}catch(e){$.each(args,function(){window.console.log(this)})}}else{return window.alert(args.join("
"))}};Galleria.ready=function(fn){if(typeof fn!="function"){return Galleria}$.each(_galleries,function(i,gallery){fn.call(gallery,gallery._options)});Galleria.ready.callbacks.push(fn);return Galleria};Galleria.ready.callbacks=[];Galleria.raise=function(msg,fatal){var type=fatal?"Fatal error":"Error",self=this,css={color:"#fff",position:"absolute",top:0,left:0,zIndex:1e5},echo=function(msg){var html='
'+(fatal?""+type+": ":"")+msg+"
";$.each(_instances,function(){var cont=this.$("errors"),target=this.$("target");if(!cont.length){target.css("position","relative");cont=this.addElement("errors").appendChild("target","errors").$("errors").css(css)}cont.append(html)});if(!_instances.length){$("
").css($.extend(css,{position:"fixed"})).append(html).appendTo(DOM().body)}};if(DEBUG){echo(msg);if(fatal){throw new Error(type+": "+msg)}}else if(fatal){if(_hasError){return}_hasError=true;fatal=false;echo("Gallery could not load.")}};Galleria.version=VERSION;Galleria.requires=function(version,msg){msg=msg||"You need to upgrade Galleria to version "+version+" to use one or more components.";if(Galleria.version",{src:src,frameborder:0,id:id,allowfullscreen:true,css:{visibility:"hidden"}})[0];$(this.container).find("iframe,img").remove();this.container.appendChild(this.image);$("#"+id).load(function(self,callback){return function(){window.setTimeout(function(){$(self.image).css("visibility","visible");if(typeof callback=="function"){callback.call(self,self)}},10)}}(this,callback));return this.container}this.image=new Image;if(Galleria.IE8){$(this.image).css("filter","inherit")}var i=0,reload=false,resort=false,$container=$(this.container),$image=$(this.image),onerror=function(){if(!reload){reload=true;window.setTimeout(function(image,src){return function(){image.attr("src",src+"?"+Utils.timestamp())}}($(this),src),50)}else{if(DUMMY){$(this).attr("src",DUMMY)}else{Galleria.raise("Image not found: "+src)}}},onload=function(self,callback,src){return function(){var complete=function(){$(this).unbind("load");self.original=size||{height:this.height,width:this.width};self.container.appendChild(this);self.cache[src]=src;if(typeof callback=="function"){window.setTimeout(function(){callback.call(self,self)},1)}};if(!this.width||!this.height){window.setTimeout(function(img){return function(){if(img.width&&img.height){complete.call(img)}else{if(!resort){$(new Image).load(onload).attr("src",img.src);resort=true}else{Galleria.raise("Could not extract width/height from image: "+img.src+". Traced measures: width:"+img.width+"px, height: "+img.height+"px.")}}}}(this),2)}else{complete.call(this)}}}(this,callback,src);$container.find("iframe,img").remove();$image.css("display","block");Utils.hide(this.image);$.each("minWidth minHeight maxWidth maxHeight".split(" "),function(i,prop){$image.css(prop,/min/.test(prop)?"0":"none")});$image.load(onload).error(onerror).attr("src",src);return this.container},scale:function(options){var self=this;options=$.extend({width:0,height:0,min:undef,max:undef,margin:0,complete:F,position:"center",crop:false,canvas:false,iframelimit:undef},options);if(this.isIframe){var cw=options.width,ch=options.height,nw,nh;if(options.iframelimit){var r=Math.min(options.iframelimit/cw,options.iframelimit/ch);if(r<1){nw=cw*r;nh=ch*r;$(this.image).css({top:ch/2-nh/2,left:cw/2-nw/2,position:"absolute"})}else{$(this.image).css({top:0,left:0})}}$(this.image).width(nw||cw).height(nh||ch).removeAttr("width").removeAttr("height");$(this.container).width(cw).height(ch);options.complete.call(self,self);try{if(this.image.contentWindow){$(this.image.contentWindow).trigger("resize")}}catch(e){}return this.container}if(!this.image){return this.container}var width,height,$container=$(self.container),data;Utils.wait({until:function(){width=options.width||$container.width()||Utils.parseValue($container.css("width"));height=options.height||$container.height()||Utils.parseValue($container.css("height"));return width&&height},success:function(){var newWidth=(width-options.margin*2)/self.original.width,newHeight=(height-options.margin*2)/self.original.height,min=Math.min(newWidth,newHeight),max=Math.max(newWidth,newHeight),cropMap={"true":max,width:newWidth,height:newHeight,"false":min,landscape:self.original.width>self.original.height?max:min,portrait:self.original.widthf?a:f)-e-1),this.slideWidth*c,0);a=this.circle(a),this.move(f,this.slideWidth*c,b),this.move(a,0,b),this.options.continuous&&this.move(this.circle(a-c),-(this.slideWidth*c),0)}else a=this.circle(a),this.animate(f*-this.slideWidth,a*-this.slideWidth,b);this.onslide(a)}},getIndex:function(){return this.index},getNumber:function(){return this.num},prev:function(){(this.options.continuous||this.index)&&this.slide(this.index-1)},next:function(){(this.options.continuous||this.index1&&(this.timeout=this.setTimeout(!this.requestAnimationFrame&&this.slide||function(a,c){b.animationFrameId=b.requestAnimationFrame.call(window,function(){b.slide(a,c)})},[this.index+1,this.options.slideshowTransitionSpeed],this.interval)),this.container.addClass(this.options.playingClass)},pause:function(){window.clearTimeout(this.timeout),this.interval=null,this.container.removeClass(this.options.playingClass)},add:function(a){var b;for(a.concat||(a=Array.prototype.slice.call(a)),this.list.concat||(this.list=Array.prototype.slice.call(this.list)),this.list=this.list.concat(a),this.num=this.list.length,this.num>2&&null===this.options.continuous&&(this.options.continuous=!0,this.container.removeClass(this.options.leftEdgeClass)),this.container.removeClass(this.options.rightEdgeClass).removeClass(this.options.singleClass),b=this.num-a.length;bc?(d.slidesContainer[0].style.left=b+"px",d.ontransitionend(),window.clearInterval(f),void 0):(d.slidesContainer[0].style.left=(b-a)*(Math.floor(100*(g/c))/100)+a+"px",void 0)},4)},preventDefault:function(a){a.preventDefault?a.preventDefault():a.returnValue=!1},onresize:function(){this.initSlides(!0)},onmousedown:function(a){a.which&&1===a.which&&"VIDEO"!==a.target.nodeName&&((a.originalEvent||a).touches=[{pageX:a.pageX,pageY:a.pageY}],this.ontouchstart(a))},onmousemove:function(a){this.touchStart&&((a.originalEvent||a).touches=[{pageX:a.pageX,pageY:a.pageY}],this.ontouchmove(a))},onmouseup:function(a){this.touchStart&&(this.ontouchend(a),delete this.touchStart)},onmouseout:function(b){if(this.touchStart){var c=b.target,d=b.relatedTarget;(!d||d!==c&&!a.contains(c,d))&&this.onmouseup(b)}},ontouchstart:function(a){var b=(a.originalEvent||a).touches[0];this.touchStart={x:b.pageX,y:b.pageY,time:Date.now()},this.isScrolling=void 0,this.touchDelta={}},ontouchmove:function(a){var b,c,d=(a.originalEvent||a).touches[0],e=(a.originalEvent||a).scale,f=this.index;if(!(d.length>1||e&&1!==e))if(this.options.disableScroll&&a.preventDefault(),this.touchDelta={x:d.pageX-this.touchStart.x,y:d.pageY-this.touchStart.y},b=this.touchDelta.x,void 0===this.isScrolling&&(this.isScrolling=this.isScrolling||Math.abs(b)0||f===this.num-1&&0>b?Math.abs(b)/this.slideWidth+1:1,c=[f],f&&c.push(f-1),f20||Math.abs(this.touchDelta.x)>h/2,k=!f&&this.touchDelta.x>0||f===this.num-1&&this.touchDelta.x<0,l=!j&&this.options.closeOnSwipeUpOrDown&&(i&&Math.abs(this.touchDelta.y)>20||Math.abs(this.touchDelta.y)>this.slideHeight/2);this.options.continuous&&(k=!1),a=this.touchDelta.x<0?-1:1,this.isScrolling?l?this.close():this.translateY(f,0,g):j&&!k?(b=f+a,c=f-a,d=h*a,e=-h*a,this.options.continuous?(this.move(this.circle(b),d,0),this.move(this.circle(f-2*a),e,0)):b>=0&&bthis.container[0].clientHeight&&(d.style.maxHeight=this.container[0].clientHeight),this.interval&&this.slides[this.index]===e&&this.play(),this.setTimeout(this.options.onslidecomplete,[c,e]))},onload:function(a){this.oncomplete(a)},onerror:function(a){this.oncomplete(a)},onkeydown:function(a){switch(a.which||a.keyCode){case 13:this.options.toggleControlsOnReturn&&(this.preventDefault(a),this.toggleControls());break;case 27:this.options.closeOnEscape&&this.close();break;case 32:this.options.toggleSlideshowOnSpace&&(this.preventDefault(a),this.toggleSlideshow());break;case 37:this.options.enableKeyboardNavigation&&(this.preventDefault(a),this.prev());break;case 39:this.options.enableKeyboardNavigation&&(this.preventDefault(a),this.next())}},handleClick:function(b){var c=this.options,d=b.target||b.srcElement,e=d.parentNode,f=function(b){return a(d).hasClass(b)||a(e).hasClass(b)};e===this.slidesContainer[0]?(this.preventDefault(b),c.closeOnSlideClick?this.close():this.toggleControls()):e.parentNode&&e.parentNode===this.slidesContainer[0]?(this.preventDefault(b),this.toggleControls()):f(c.toggleClass)?(this.preventDefault(b),this.toggleControls()):f(c.prevClass)?(this.preventDefault(b),this.prev()):f(c.nextClass)?(this.preventDefault(b),this.next()):f(c.closeClass)?(this.preventDefault(b),this.close()):f(c.playPauseClass)&&(this.preventDefault(b),this.toggleSlideshow())},onclick:function(a){return this.options.emulateTouchEvents&&this.touchDelta&&(Math.abs(this.touchDelta.x)>20||Math.abs(this.touchDelta.y)>20)?(delete this.touchDelta,void 0):this.handleClick(a)},updateEdgeClasses:function(a){a?this.container.removeClass(this.options.leftEdgeClass):this.container.addClass(this.options.leftEdgeClass),a===this.num-1?this.container.addClass(this.options.rightEdgeClass):this.container.removeClass(this.options.rightEdgeClass)},handleSlide:function(a){this.options.continuous||this.updateEdgeClasses(a),this.loadElements(a),this.options.unloadElements&&this.unloadElements(a),this.setTitle(a)},onslide:function(a){this.index=a,this.handleSlide(a),this.setTimeout(this.options.onslide,[a,this.slides[a]])},setTitle:function(a){var b=this.slides[a].firstChild.title,c=this.titleElement;c.length&&(this.titleElement.empty(),b&&c[0].appendChild(document.createTextNode(b)))},setTimeout:function(a,b,c){var d=this;return a&&window.setTimeout(function(){a.apply(d,b||[])},c||0)},imageFactory:function(b,c){var d,e,f,g=this,h=this.imagePrototype.cloneNode(!1),i=b,j=this.options.stretchImages,k=function(b){if(!d){if(b={type:b.type,target:e},!e.parentNode)return g.setTimeout(k,[b]);d=!0,a(h).off("load error",k),j&&"load"===b.type&&(e.style.background='url("'+i+'") center no-repeat',e.style.backgroundSize=j),c(b)}};return"string"!=typeof i&&(i=this.getItemProperty(b,this.options.urlProperty),f=this.getItemProperty(b,this.options.titleProperty)),j===!0&&(j="contain"),j=this.support.backgroundSize&&this.support.backgroundSize[j]&&j,j?e=this.elementPrototype.cloneNode(!1):(e=h,h.draggable=!1),f&&(e.title=f),a(h).on("load error",k),h.src=i,e},createElement:function(b,c){var d=b&&this.getItemProperty(b,this.options.typeProperty),e=d&&this[d.split("/")[0]+"Factory"]||this.imageFactory,f=b&&e.call(this,b,c);return f||(f=this.elementPrototype.cloneNode(!1),this.setTimeout(c,[{type:"error",target:f}])),a(f).addClass(this.options.slideContentClass),f},loadElement:function(b){this.elements[b]||(this.slides[b].firstChild?this.elements[b]=a(this.slides[b]).hasClass(this.options.slideErrorClass)?3:2:(this.elements[b]=1,a(this.slides[b]).addClass(this.options.slideLoadingClass),this.slides[b].appendChild(this.createElement(this.list[b],this.proxyListener))))},loadElements:function(a){var b,c=Math.min(this.num,2*this.options.preloadRange+1),d=a;for(b=0;c>b;b+=1)d+=b*(0===b%2?-1:1),d=this.circle(d),this.loadElement(d)},unloadElements:function(a){var b,c,d;for(b in this.elements)this.elements.hasOwnProperty(b)&&(d=Math.abs(a-b),d>this.options.preloadRange&&d+this.options.preloadRangea?-this.slideWidth:this.index-1) dominio=v.split("/")[0] caminho=v.replace(/[^\/]*/,"") dominio=dominio.replace(/[^\w\.\+-:@]/g,"") caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"") caminho=caminho.replace(/([\?&])=/,"$1") if(caminho!="")dominio=dominio.replace(/\.+$/,"") v="http://"+dominio+caminho return v } /*** Funcao Generica pra formatar usando uma mascara ex.: aplicarMascara(this,'##/##/####') ***/ function aplicarMascara(src, mask){ if(!nbr) nbr = (window.event)?window.event.keyCode:''; //alert(nbr); var allow = [8,9,13,35,36,37,38,39,40,46]; if($.inArray(nbr,allow) < 0){ var i = src.value.length; var max = mask.length; if (i > max-1) { src.value = src.value.substring(0,max); return; } var entrada = src.value; var saida = '#'; var texto = mask.substring(i); if(i==1 && (mask.substring(0,1) != saida)) src.value = mask.substring(0,1)+entrada; else if(texto.substring(0,1) != saida) { src.value += texto.substring(0,1); if(mask.substr(i+1,1) == ' ') src.value += ' '; } else if(mask.substr(i-2,1) == src.value.substr(i-1,1)) src.value = src.value.substr(0,i-1); } } /****CHAMADA DAS MASCARAS****/ $.fn.setMascara = function(maskFunc) { this.unbind('keyup').bind('keyup blur', function(e) { mascara(this, maskFunc); }); return this; }; function insertMasks(){ $('.form-filtro input:text').unbind('.maskFormFiltro').bind('click.maskFormFiltro', function(){ highlight(this.id); }); $('.mascaraSoNumeros').setMascara(mascaraSoNumeros); $('.mascaraData').setMascara(mascaraData); $('.mascaraValor').setMascara(mascaraValor); $('.mascaraCep').setMascara(mascaraCep); $('.mascaraFone').setMascara(mascaraTelefone); } $(document).ready(function(){insertMasks();}); /******************************************/ var lazyLoad, elemCenter, style, initLazyLoad; var useWebp = useWebp ? useWebp : false; initLazyLoad = function() { var lazyImages = [].slice.call(document.querySelectorAll("img.lazy")); var active = false; var lazyTimeout = null; lazyLoad = function() { // console.log('**Lazy Load'); if (lazyTimeout) clearTimeout(lazyTimeout); if (active === false) { active = true; setTimeout(function() { lazyImages.forEach(function(lazyImage) { if (isVisible(lazyImage)) { var imgSrc = ''; if (lazyImage.dataset.src) imgSrc = lazyImage.dataset.src; if (lazyImage.dataset.srcset) lazyImage.srcset = lazyImage.dataset.srcset; //Permitindo o resize de acordo com a div parent if (imgSrc && lazyImage.dataset.resizeWidth && lazyImage.dataset.resizeWidth == 'auto') { var rectParent = lazyImage.parentElement.getBoundingClientRect(); imgSrc = imgResizeUrl(imgSrc, parseInt(rectParent.width)); } lazyImage.src = imgSrc; lazyImage.classList.remove("lazy"); if (typeof imgload_callback == 'function') { imgload_callback(); } lazyImages = lazyImages.filter(function(image) { return image !== lazyImage; }); } }); if (lazyImages.length === 0) { document.removeEventListener("scroll", lazyLoad); window.removeEventListener("resize", lazyLoad); window.removeEventListener("orientationchange", lazyLoad); } else { lazyTimeout = setTimeout(lazyLoad, 500); } active = false; }, 200); } }; document.addEventListener("scroll", lazyLoad); window.addEventListener("resize", lazyLoad); window.addEventListener("orientationchange", lazyLoad); window.addEventListener("load", lazyLoad); }; document.addEventListener("DOMContentLoaded", initLazyLoad); //Carregando os backgrounds var loadBgsInt = null; var loadBgs = function(e) { clearTimeout(loadBgsInt); var bgs = document.querySelectorAll('[data-bgimgresp]'); for (var i = 0; i < bgs.length; i++) { // console.log('bg', bgs[i]); var w = Math.max(document.documentElement.clientWidth, window.innerWidth, 0); var sizeStr = w+'x'; if (bgs[i].dataset.bgwidth && !isNaN(bgs[i].dataset.bgwidth)) { sizeStr = parseInt(bgs[i].dataset.bgwidth)+'x'; } else if (bgs[i].dataset.bgsize && bgs[i].dataset.bgsize == 'cover') { var rectParent = bgs[i].getBoundingClientRect(); sizeStr = parseInt(rectParent.width)+'x'+parseInt(rectParent.height); } var bgUrl = bgs[i].dataset.bgimgresp; if (String(bgUrl).trim() == '') continue; bgUrl = sizeStr ? imgResizeUrl(bgUrl, sizeStr.split('x')[0], sizeStr.split('x')[1]) : bgUrl; bgs[i].style.backgroundImage = "url('"+bgUrl+"')"; if (typeof loadBgs_callback == 'function') { loadBgs_callback(); } } } window.addEventListener('resize', function() { clearTimeout(loadBgsInt); loadBgsInt = setTimeout(loadBgs, 1000); }); window.addEventListener('load',loadBgs); function isVisible(elem) { if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.'); style = getComputedStyle(elem); if (style.display === 'none') return false; if (style.visibility !== 'visible') return false; if (style.opacity < 0.1) return false; if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height + elem.getBoundingClientRect().width === 0) { return false; } elemCenter = { x: elem.getBoundingClientRect().left + elem.offsetWidth / 2, y: elem.getBoundingClientRect().top + elem.offsetHeight / 2 }; if (elemCenter.x < 0) return false; if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false; if (elemCenter.y < 0) return false; if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false; var pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y); return true; } function isGSpeed() { return (navigator.userAgent.indexOf('Chrome-Lighthouse') > -1 || navigator.userAgent.indexOf('Speed Insights') > -1); } function scriptsLazyLoad(e) { if (!isGSpeed()) { var itens = document.querySelectorAll('link,script,iframe'); for (var i = 0; i < itens.length; i++) { // console.log(itens[i].dataset['href'], itens[i].tagName); if (itens[i].dataset['src']) { itens[i].src = itens[i].dataset['src']; itens[i].dataset['src'] = ''; } if (itens[i].tagName == 'LINK' && itens[i].dataset['href']) { itens[i].href = itens[i].dataset['href']; itens[i].dataset['href'] = ''; } } var itens = document.querySelectorAll('.bg-lazyload'); var cntBgs = 0; for (var i = 0; i < itens.length; i++) { var t = itens[i]; if (t.dataset['backgroundimg']) { // console.log(t.dataset['backgroundimg']); cntBgs++; t.style.backgroundImage = 'url('+t.dataset['backgroundimg']+')'; t.dataset['backgroundimg'] = null; } } if (typeof scriptsLazyLoad_callback == 'function') { scriptsLazyLoad_callback(); } } } scriptsLazyLoad(); window.addEventListener('load',scriptsLazyLoad); var modalMain = { isMobile : (/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i).test(navigator.userAgent), htmlModal : '', htmlModalLoading : '', updateBinds : function(e, bindStr) { $('body').on('click', bindStr ? bindStr : ".open-modal, .thickbox", function(e) { e.preventDefault(); modalMain.open($(this).attr('href'), $(this).attr('title') ? $(this).attr('title') : $(this).text(), this); return false; }); }, updateBindsModalSelector: '.modal-content .open-modal', open : function(href, title, el) { // console.log('modalMain open href:', href); $("#modalMain, #modalLoading").remove(); $('body').append(modalMain.htmlModal).append(modalMain.htmlModalLoading); $("#modalMain .modal-body").css('overflow', 'visible'); $("#modalMain .modal-body").css('width', null); $("#modalMain .modal-body").css('height', null); $("#modalMain .modal-title").text(title); var iframeWidth = getParameterByName('width', href) ? getParameterByName('width', href) : 550; var iframeHeight = getParameterByName('height', href) ? getParameterByName('height', href) : 0; $("#modalMain").attr('data-height', iframeHeight); var iframeHTML = ''; $("#modalLoading").modal('show'); $("#modalLoading").on('hidden.bs.modal', function() { $('.modal-backdrop').remove(); window.setTimeout(function () { $("#modalMain").modal('show'); }, 1); }); if (el && $(el).data('modalsize')) { $("#modalMain .modal-dialog").addClass('modal-'+$(el).data('modalsize')); } else if (iframeWidth && !modalMain.isSmallDevice()) $("#modalMain .modal-dialog").width(iframeWidth); $("#modalMain").unbind('shown.bs.modal').on('shown.bs.modal', function(e) { modalMain.fixHeight(); }); if (getParameterByName('TB_iframe', href)) { $("#modalMain .modal-body").html(iframeHTML); $("#modalMain .modal-body #modalMainIframe").attr('src', href); } else if (getParameterByName('inlineId', href)) { var inlineId = getParameterByName('inlineId', href); $("#modalMain .modal-body").html($("#"+inlineId).html()); $("#modalLoading").modal('hide'); } else { $.get(href, {}, function(r) { if (r.indexOf('modal-header') > -1 || r.indexOf('modal-footer') > -1) { $("#modalMain .modal-content").html(r); } else { $("#modalMain .modal-body").html(r); } $("#modalLoading").modal('hide'); $("#modalMain .modal-title").text(title); }); } }, hide : function() { $("#modalMain").modal('hide'); }, fixHeight : function() { var limitHeight = $(window).height()*0.8-$('#modalMain').find('.modal-title').height(); var dataheight = Number($('#modalMain').attr('data-height')); if (dataheight > 0) { var targetHeight = dataheight > limitHeight ? limitHeight : dataheight; //console.log(targetHeight, dataheight, limitHeight); if ( ! $('#modalMain').find('iframe').length) { $("#modalMain .modal-body").css('overflow', 'scroll').css('overflow-x', 'hidden'); $("#modalMain .modal-body").css('height', targetHeight); } else { $("#modalMain .modal-body iframe").css('height', targetHeight).css('overflow', 'scroll').css('overflow-x', 'hidden'); } } }, iframeOnload : function() { if (!$('body').hasClass('modal-open')) return false; $("#modalLoading").modal('hide'); }, init : function() { //console.log('modalMain.init'); $(document).ready(function() { modalMain.updateBinds(); }); }, isSmallDevice : function() { if (modalMain.findBSEnv() == 'xs' || modalMain.findBSEnv() == 'sm') { return true; } return false; }, findBSEnv : function () { var envs = ['xs', 'sm', 'md', 'lg']; $el = $('
'); $el.appendTo($('body')); for (var i = envs.length - 1; i >= 0; i--) { var env = envs[i]; $el.addClass('hidden-'+env); if ($el.is(':hidden')) { $el.remove(); return env; } } } }; modalMain.init(); if (window.tb_remove) delete window.tb_remove; function tb_remove() { $("#modalMain").modal('hide'); } /*! jQuery v2.1.4 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){ return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*\s*$/g,ia={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '
'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '' + monthNames[drawMonth] + ''; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += ''; } if (!showMonthAfterYear) html += monthHtml + (secondary || !(changeMonth && changeYear) ? ' ' : ''); // year selection if ( !inst.yearshtml ) { inst.yearshtml = ''; if (secondary || !changeYear) html += '' + drawYear + ''; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var thisYear = new Date().getFullYear(); var determineYear = function(value) { var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; var year = determineYear(years[0]); var endYear = Math.max(year, determineYear(years[1] || '')); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += ''; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || !(changeMonth && changeYear) ? ' ' : '') + monthHtml; html += '
'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var newDate = (minDate && date < minDate ? minDate : date); newDate = (maxDate && newDate > maxDate ? maxDate : newDate); return newDate; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime())); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; return dpDiv.bind('mouseout', function(event) { var elem = $( event.target ).closest( selector ); if ( !elem.length ) { return; } elem.removeClass( "ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover" ); }) .bind('mouseover', function(event) { var elem = $( event.target ).closest( selector ); if ($.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0]) || !elem.length ) { return; } elem.parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); elem.addClass('ui-state-hover'); if (elem.hasClass('ui-datepicker-prev')) elem.addClass('ui-datepicker-prev-hover'); if (elem.hasClass('ui-datepicker-next')) elem.addClass('ui-datepicker-next-hover'); }); } /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Determine whether an object is an array. */ function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find('body').append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.8.16"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery); /* * jQuery UI Dialog 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Dialog * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.button.js * jquery.ui.draggable.js * jquery.ui.mouse.js * jquery.ui.position.js * jquery.ui.resizable.js */ (function( $, undefined ) { var uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all ', sizeRelatedOptions = { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions = { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, // support for jQuery 1.3.2 - handle common attrFn methods for dialog attrFn = $.attrFn || { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true, click: true }; $.widget("ui.dialog", { options: { autoOpen: true, buttons: {}, closeOnEscape: true, closeText: 'close', dialogClass: '', draggable: true, hide: null, height: 'auto', maxHeight: false, maxWidth: false, minHeight: 150, minWidth: 150, modal: false, position: { my: 'center', at: 'center', collision: 'fit', // ensure that the titlebar is never outside the document using: function(pos) { var topOffset = $(this).css(pos).offset().top; if (topOffset < 0) { $(this).css('top', pos.top - topOffset); } } }, resizable: true, show: null, stack: true, title: '', width: 300, zIndex: 1000 }, _create: function() { this.originalTitle = this.element.attr('title'); // #5742 - .attr() might return a DOMElement if ( typeof this.originalTitle !== "string" ) { this.originalTitle = ""; } this.options.title = this.options.title || this.originalTitle; var self = this, options = self.options, title = options.title || ' ', titleId = $.ui.dialog.getTitleId(self.element), uiDialog = (self.uiDialog = $('
')) .appendTo(document.body) .hide() .addClass(uiDialogClasses + options.dialogClass) .css({ zIndex: options.zIndex }) // setting tabIndex makes the div focusable // setting outline to 0 prevents a border on focus in Mozilla .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { if (options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { self.close(event); event.preventDefault(); } }) .attr({ role: 'dialog', 'aria-labelledby': titleId }) .mousedown(function(event) { self.moveToTop(false, event); }), uiDialogContent = self.element .show() .removeAttr('title') .addClass( 'ui-dialog-content ' + 'ui-widget-content') .appendTo(uiDialog), uiDialogTitlebar = (self.uiDialogTitlebar = $('
')) .addClass( 'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix' ) .prependTo(uiDialog), uiDialogTitlebarClose = $('') .addClass( 'ui-dialog-titlebar-close ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarClose.addClass('ui-state-hover'); }, function() { uiDialogTitlebarClose.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarClose.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarClose.removeClass('ui-state-focus'); }) .click(function(event) { self.close(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('')) .addClass( 'ui-icon ' + 'ui-icon-closethick' ) .text(options.closeText) .appendTo(uiDialogTitlebarClose), uiDialogTitle = $('') .addClass('ui-dialog-title') .attr('id', titleId) .html(title) .prependTo(uiDialogTitlebar); //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) { options.beforeClose = options.beforeclose; } uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); if (options.draggable && $.fn.draggable) { self._makeDraggable(); } if (options.resizable && $.fn.resizable) { self._makeResizable(); } self._createButtons(options.buttons); self._isOpen = false; if ($.fn.bgiframe) { uiDialog.bgiframe(); } }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, destroy: function() { var self = this; if (self.overlay) { self.overlay.destroy(); } self.uiDialog.hide(); self.element .unbind('.dialog') .removeData('dialog') .removeClass('ui-dialog-content ui-widget-content') .hide().appendTo('body'); self.uiDialog.remove(); if (self.originalTitle) { self.element.attr('title', self.originalTitle); } return self; }, widget: function() { return this.uiDialog; }, close: function(event) { var self = this, maxZ, thisZ; if (false === self._trigger('beforeClose', event)) { return; } if (self.overlay) { self.overlay.destroy(); } self.uiDialog.unbind('keypress.ui-dialog'); self._isOpen = false; if (self.options.hide) { self.uiDialog.hide(self.options.hide, function() { self._trigger('close', event); }); } else { self.uiDialog.hide(); self._trigger('close', event); } $.ui.dialog.overlay.resize(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if (self.options.modal) { maxZ = 0; $('.ui-dialog').each(function() { if (this !== self.uiDialog[0]) { thisZ = $(this).css('z-index'); if(!isNaN(thisZ)) { maxZ = Math.max(maxZ, thisZ); } } }); $.ui.dialog.maxZ = maxZ; } return self; }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function(force, event) { var self = this, options = self.options, saveScroll; if ((options.modal && !force) || (!options.stack && !options.modal)) { return self._trigger('focus', event); } if (options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = options.zIndex; } if (self.overlay) { $.ui.dialog.maxZ += 1; self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ); } //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 saveScroll = { scrollTop: self.element.scrollTop(), scrollLeft: self.element.scrollLeft() }; $.ui.dialog.maxZ += 1; self.uiDialog.css('z-index', $.ui.dialog.maxZ); self.element.attr(saveScroll); self._trigger('focus', event); return self; }, open: function() { if (this._isOpen) { return; } var self = this, options = self.options, uiDialog = self.uiDialog; self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null; self._size(); self._position(options.position); uiDialog.show(options.show); self.moveToTop(true); // prevent tabbing out of modal dialogs if (options.modal) { uiDialog.bind('keypress.ui-dialog', function(event) { if (event.keyCode !== $.ui.keyCode.TAB) { return; } var tabbables = $(':tabbable', this), first = tabbables.filter(':first'), last = tabbables.filter(':last'); if (event.target === last[0] && !event.shiftKey) { first.focus(1); return false; } else if (event.target === first[0] && event.shiftKey) { last.focus(1); return false; } }); } // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself $(self.element.find(':tabbable').get().concat( uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat( uiDialog.get()))).eq(0).focus(); self._isOpen = true; self._trigger('open'); return self; }, _createButtons: function(buttons) { var self = this, hasButtons = false, uiDialogButtonPane = $('
') .addClass( 'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix' ), uiButtonSet = $( "
" ) .addClass( "ui-dialog-buttonset" ) .appendTo( uiDialogButtonPane ); // if we already have a button pane, remove it self.uiDialog.find('.ui-dialog-buttonpane').remove(); if (typeof buttons === 'object' && buttons !== null) { $.each(buttons, function() { return !(hasButtons = true); }); } if (hasButtons) { $.each(buttons, function(name, props) { props = $.isFunction( props ) ? { click: props, text: name } : props; var button = $('') .click(function() { props.click.apply(self.element[0], arguments); }) .appendTo(uiButtonSet); // can't use .attr( props, true ) with jQuery 1.3.2. $.each( props, function( key, value ) { if ( key === "click" ) { return; } if ( key in attrFn ) { button[ key ]( value ); } else { button.attr( key, value ); } }); if ($.fn.button) { button.button(); } }); uiDialogButtonPane.appendTo(self.uiDialog); } }, _makeDraggable: function() { var self = this, options = self.options, doc = $(document), heightBeforeDrag; function filteredUi(ui) { return { position: ui.position, offset: ui.offset }; } self.uiDialog.draggable({ cancel: '.ui-dialog-content, .ui-dialog-titlebar-close', handle: '.ui-dialog-titlebar', containment: 'document', start: function(event, ui) { heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height(); $(this).height($(this).height()).addClass("ui-dialog-dragging"); self._trigger('dragStart', event, filteredUi(ui)); }, drag: function(event, ui) { self._trigger('drag', event, filteredUi(ui)); }, stop: function(event, ui) { options.position = [ui.position.left - doc.scrollLeft(), ui.position.top - doc.scrollTop()]; $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); self._trigger('dragStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function(handles) { handles = (handles === undefined ? this.options.resizable : handles); var self = this, options = self.options, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = self.uiDialog.css('position'), resizeHandles = (typeof handles === 'string' ? handles : 'n,e,s,w,se,sw,ne,nw' ); function filteredUi(ui) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } self.uiDialog.resizable({ cancel: '.ui-dialog-content', containment: 'document', alsoResize: self.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: self._minHeight(), handles: resizeHandles, start: function(event, ui) { $(this).addClass("ui-dialog-resizing"); self._trigger('resizeStart', event, filteredUi(ui)); }, resize: function(event, ui) { self._trigger('resize', event, filteredUi(ui)); }, stop: function(event, ui) { $(this).removeClass("ui-dialog-resizing"); options.height = $(this).height(); options.width = $(this).width(); self._trigger('resizeStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }) .css('position', position) .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); }, _minHeight: function() { var options = this.options; if (options.height === 'auto') { return options.minHeight; } else { return Math.min(options.minHeight, options.height); } }, _position: function(position) { var myAt = [], offset = [0, 0], isVisible; if (position) { // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( // if (typeof position == 'string' || $.isArray(position)) { // myAt = $.isArray(position) ? position : position.split(' '); if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) { myAt = position.split ? position.split(' ') : [position[0], position[1]]; if (myAt.length === 1) { myAt[1] = myAt[0]; } $.each(['left', 'top'], function(i, offsetPosition) { if (+myAt[i] === myAt[i]) { offset[i] = myAt[i]; myAt[i] = offsetPosition; } }); position = { my: myAt.join(" "), at: myAt.join(" "), offset: offset.join(" ") }; } position = $.extend({}, $.ui.dialog.prototype.options.position, position); } else { position = $.ui.dialog.prototype.options.position; } // need to show the dialog to get the actual offset in the position plugin isVisible = this.uiDialog.is(':visible'); if (!isVisible) { this.uiDialog.show(); } this.uiDialog // workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781 .css({ top: 0, left: 0 }) .position($.extend({ of: window }, position)); if (!isVisible) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var self = this, resizableOptions = {}, resize = false; $.each( options, function( key, value ) { self._setOption( key, value ); if ( key in sizeRelatedOptions ) { resize = true; } if ( key in resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); } if ( this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function(key, value){ var self = this, uiDialog = self.uiDialog; switch (key) { //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre case "beforeclose": key = "beforeClose"; break; case "buttons": self._createButtons(value); break; case "closeText": // ensure that we always pass a string self.uiDialogTitlebarCloseText.text("" + value); break; case "dialogClass": uiDialog .removeClass(self.options.dialogClass) .addClass(uiDialogClasses + value); break; case "disabled": if (value) { uiDialog.addClass('ui-dialog-disabled'); } else { uiDialog.removeClass('ui-dialog-disabled'); } break; case "draggable": var isDraggable = uiDialog.is( ":data(draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { self._makeDraggable(); } break; case "position": self._position(value); break; case "resizable": // currently resizable, becoming non-resizable var isResizable = uiDialog.is( ":data(resizable)" ); if (isResizable && !value) { uiDialog.resizable('destroy'); } // currently resizable, changing handles if (isResizable && typeof value === 'string') { uiDialog.resizable('option', 'handles', value); } // currently non-resizable, becoming resizable if (!isResizable && value !== false) { self._makeResizable(value); } break; case "title": // convert whatever was passed in o a string, for html() to not throw up $(".ui-dialog-title", self.uiDialogTitlebar).html("" + (value || ' ')); break; } $.Widget.prototype._setOption.apply(self, arguments); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var options = this.options, nonContentHeight, minContentHeight, isVisible = this.uiDialog.is( ":visible" ); // reset content sizing this.element.show().css({ width: 'auto', minHeight: 0, height: 0 }); if (options.minWidth > options.width) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: 'auto', width: options.width }) .height(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); if ( options.height === "auto" ) { // only needed for IE6 support if ( $.support.minHeight ) { this.element.css({ minHeight: minContentHeight, height: "auto" }); } else { this.uiDialog.show(); var autoHeight = this.element.css( "height", "auto" ).height(); if ( !isVisible ) { this.uiDialog.hide(); } this.element.height( Math.max( autoHeight, minContentHeight ) ); } } else { this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); } if (this.uiDialog.is(':data(resizable)')) { this.uiDialog.resizable('option', 'minHeight', this._minHeight()); } } }); $.extend($.ui.dialog, { version: "1.8.16", uuid: 0, maxZ: 0, getTitleId: function($el) { var id = $el.attr('id'); if (!id) { this.uuid += 1; id = this.uuid; } return 'ui-dialog-title-' + id; }, overlay: function(dialog) { this.$el = $.ui.dialog.overlay.create(dialog); } }); $.extend($.ui.dialog.overlay, { instances: [], // reuse old instances due to IE memory leak with alpha transparency (see #5185) oldInstances: [], maxZ: 0, events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' '), create: function(dialog) { if (this.instances.length === 0) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ($.ui.dialog.overlay.instances.length) { $(document).bind($.ui.dialog.overlay.events, function(event) { // stop events if the z-index of the target is < the z-index of the overlay // we cannot return true when we don't want to cancel the event (#3523) if ($(event.target).zIndex() < $.ui.dialog.overlay.maxZ) { return false; } }); } }, 1); // allow closing by pressing the escape key $(document).bind('keydown.dialog-overlay', function(event) { if (dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { dialog.close(event); event.preventDefault(); } }); // handle window resize $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); } var $el = (this.oldInstances.pop() || $('
').addClass('ui-widget-overlay')) .appendTo(document.body) .css({ width: this.width(), height: this.height() }); if ($.fn.bgiframe) { $el.bgiframe(); } this.instances.push($el); return $el; }, destroy: function($el) { var indexOf = $.inArray($el, this.instances); if (indexOf != -1){ this.oldInstances.push(this.instances.splice(indexOf, 1)[0]); } if (this.instances.length === 0) { $([document, window]).unbind('.dialog-overlay'); } $el.remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) var maxZ = 0; $.each(this.instances, function() { maxZ = Math.max(maxZ, this.css('z-index')); }); this.maxZ = maxZ; }, height: function() { var scrollHeight, offsetHeight; // handle IE 6 if ($.browser.msie && $.browser.version < 7) { scrollHeight = Math.max( document.documentElement.scrollHeight, document.body.scrollHeight ); offsetHeight = Math.max( document.documentElement.offsetHeight, document.body.offsetHeight ); if (scrollHeight < offsetHeight) { return $(window).height() + 'px'; } else { return scrollHeight + 'px'; } // handle "good" browsers } else { return $(document).height() + 'px'; } }, width: function() { var scrollWidth, offsetWidth; // handle IE if ( $.browser.msie ) { scrollWidth = Math.max( document.documentElement.scrollWidth, document.body.scrollWidth ); offsetWidth = Math.max( document.documentElement.offsetWidth, document.body.offsetWidth ); if (scrollWidth < offsetWidth) { return $(window).width() + 'px'; } else { return scrollWidth + 'px'; } // handle "good" browsers } else { return $(document).width() + 'px'; } }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $([]); $.each($.ui.dialog.overlay.instances, function() { $overlays = $overlays.add(this); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend($.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy(this.$el); } }); }(jQuery)); /* * jQuery UI Position 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Position */ (function( $, undefined ) { $.ui = $.ui || {}; var horizontalPositions = /left|center|right/, verticalPositions = /top|center|bottom/, center = "center", _position = $.fn.position, _offset = $.fn.offset; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var target = $( options.of ), targetElem = target[0], collision = ( options.collision || "flip" ).split( " " ), offset = options.offset ? options.offset.split( " " ) : [ 0, 0 ], targetWidth, targetHeight, basePosition; if ( targetElem.nodeType === 9 ) { targetWidth = target.width(); targetHeight = target.height(); basePosition = { top: 0, left: 0 }; // TODO: use $.isWindow() in 1.9 } else if ( targetElem.setTimeout ) { targetWidth = target.width(); targetHeight = target.height(); basePosition = { top: target.scrollTop(), left: target.scrollLeft() }; } else if ( targetElem.preventDefault ) { // force left top to allow flipping options.at = "left top"; targetWidth = targetHeight = 0; basePosition = { top: options.of.pageY, left: options.of.pageX }; } else { targetWidth = target.outerWidth(); targetHeight = target.outerHeight(); basePosition = target.offset(); } // force my and at to have valid horizontal and veritcal positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[this] || "" ).split( " " ); if ( pos.length === 1) { pos = horizontalPositions.test( pos[0] ) ? pos.concat( [center] ) : verticalPositions.test( pos[0] ) ? [ center ].concat( pos ) : [ center, center ]; } pos[ 0 ] = horizontalPositions.test( pos[0] ) ? pos[ 0 ] : center; pos[ 1 ] = verticalPositions.test( pos[1] ) ? pos[ 1 ] : center; options[ this ] = pos; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } // normalize offset option offset[ 0 ] = parseInt( offset[0], 10 ) || 0; if ( offset.length === 1 ) { offset[ 1 ] = offset[ 0 ]; } offset[ 1 ] = parseInt( offset[1], 10 ) || 0; if ( options.at[0] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[0] === center ) { basePosition.left += targetWidth / 2; } if ( options.at[1] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[1] === center ) { basePosition.top += targetHeight / 2; } basePosition.left += offset[ 0 ]; basePosition.top += offset[ 1 ]; return this.each(function() { var elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseInt( $.curCSS( this, "marginLeft", true ) ) || 0, marginTop = parseInt( $.curCSS( this, "marginTop", true ) ) || 0, collisionWidth = elemWidth + marginLeft + ( parseInt( $.curCSS( this, "marginRight", true ) ) || 0 ), collisionHeight = elemHeight + marginTop + ( parseInt( $.curCSS( this, "marginBottom", true ) ) || 0 ), position = $.extend( {}, basePosition ), collisionPosition; if ( options.my[0] === "right" ) { position.left -= elemWidth; } else if ( options.my[0] === center ) { position.left -= elemWidth / 2; } if ( options.my[1] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[1] === center ) { position.top -= elemHeight / 2; } // prevent fractions (see #5280) position.left = Math.round( position.left ); position.top = Math.round( position.top ); collisionPosition = { left: position.left - marginLeft, top: position.top - marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[i] ] ) { $.ui.position[ collision[i] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: offset, my: options.my, at: options.at }); } }); if ( $.fn.bgiframe ) { elem.bgiframe(); } elem.offset( $.extend( position, { using: options.using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var win = $( window ), over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft(); position.left = over > 0 ? position.left - over : Math.max( position.left - data.collisionPosition.left, position.left ); }, top: function( position, data ) { var win = $( window ), over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop(); position.top = over > 0 ? position.top - over : Math.max( position.top - data.collisionPosition.top, position.top ); } }, flip: { left: function( position, data ) { if ( data.at[0] === center ) { return; } var win = $( window ), over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft(), myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : -data.targetWidth, offset = -2 * data.offset[ 0 ]; position.left += data.collisionPosition.left < 0 ? myOffset + atOffset + offset : over > 0 ? myOffset + atOffset + offset : 0; }, top: function( position, data ) { if ( data.at[1] === center ) { return; } var win = $( window ), over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop(), myOffset = data.my[ 1 ] === "top" ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : -data.targetHeight, offset = -2 * data.offset[ 1 ]; position.top += data.collisionPosition.top < 0 ? myOffset + atOffset + offset : over > 0 ? myOffset + atOffset + offset : 0; } } }; // offset setter from jQuery 1.4 if ( !$.offset.setOffset ) { $.offset.setOffset = function( elem, options ) { // set position first, in-case top/left are set even on static elem if ( /static/.test( $.curCSS( elem, "position" ) ) ) { elem.style.position = "relative"; } var curElem = $( elem ), curOffset = curElem.offset(), curTop = parseInt( $.curCSS( elem, "top", true ), 10 ) || 0, curLeft = parseInt( $.curCSS( elem, "left", true ), 10) || 0, props = { top: (options.top - curOffset.top) + curTop, left: (options.left - curOffset.left) + curLeft }; if ( 'using' in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } }; $.fn.offset = function( options ) { var elem = this[ 0 ]; if ( !elem || !elem.ownerDocument ) { return null; } if ( options ) { return this.each(function() { $.offset.setOffset( this, options ); }); } return _offset.call( this ); }; } }( jQuery )); /* * jQuery UI Progressbar 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Progressbar * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { $.widget( "ui.progressbar", { options: { value: 0, max: 100 }, min: 0, _create: function() { this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ role: "progressbar", "aria-valuemin": this.min, "aria-valuemax": this.options.max, "aria-valuenow": this._value() }); this.valueDiv = $( "
" ) .appendTo( this.element ); this.oldValue = this._value(); this._refreshValue(); }, destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); $.Widget.prototype.destroy.apply( this, arguments ); }, value: function( newValue ) { if ( newValue === undefined ) { return this._value(); } this._setOption( "value", newValue ); return this; }, _setOption: function( key, value ) { if ( key === "value" ) { this.options.value = value; this._refreshValue(); if ( this._value() === this.options.max ) { this._trigger( "complete" ); } } $.Widget.prototype._setOption.apply( this, arguments ); }, _value: function() { var val = this.options.value; // normalize invalid value if ( typeof val !== "number" ) { val = 0; } return Math.min( this.options.max, Math.max( this.min, val ) ); }, _percentage: function() { return 100 * this._value() / this.options.max; }, _refreshValue: function() { var value = this.value(); var percentage = this._percentage(); if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } this.valueDiv .toggle( value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.attr( "aria-valuenow", value ); } }); $.extend( $.ui.progressbar, { version: "1.8.16" }); })( jQuery ); /* * jQuery UI Slider 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Slider * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function( $, undefined ) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget( "ui.slider", $.ui.mouse, { widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null }, _create: function() { var self = this, o = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "", handleCount = ( o.values && o.values.length ) || 1, handles = []; this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all" + ( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) ); this.range = $([]); if ( o.range ) { if ( o.range === true ) { if ( !o.values ) { o.values = [ this._valueMin(), this._valueMin() ]; } if ( o.values.length && o.values.length !== 2 ) { o.values = [ o.values[0], o.values[0] ]; } } this.range = $( "
" ) .appendTo( this.element ) .addClass( "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header" + ( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) ); } for ( var i = existingHandles.length; i < handleCount; i += 1 ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( self.element ) ); this.handle = this.handles.eq( 0 ); this.handles.add( this.range ).filter( "a" ) .click(function( event ) { event.preventDefault(); }) .hover(function() { if ( !o.disabled ) { $( this ).addClass( "ui-state-hover" ); } }, function() { $( this ).removeClass( "ui-state-hover" ); }) .focus(function() { if ( !o.disabled ) { $( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" ); $( this ).addClass( "ui-state-focus" ); } else { $( this ).blur(); } }) .blur(function() { $( this ).removeClass( "ui-state-focus" ); }); this.handles.each(function( i ) { $( this ).data( "index.ui-slider-handle", i ); }); this.handles .keydown(function( event ) { var ret = true, index = $( this ).data( "index.ui-slider-handle" ), allowed, curVal, newVal, step; if ( self.options.disabled ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: ret = false; if ( !self._keySliding ) { self._keySliding = true; $( this ).addClass( "ui-state-active" ); allowed = self._start( event, index ); if ( allowed === false ) { return; } } break; } step = self.options.step; if ( self.options.values && self.options.values.length ) { curVal = newVal = self.values( index ); } else { curVal = newVal = self.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = self._valueMin(); break; case $.ui.keyCode.END: newVal = self._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = self._trimAlignValue( curVal + ( (self._valueMax() - self._valueMin()) / numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = self._trimAlignValue( curVal - ( (self._valueMax() - self._valueMin()) / numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === self._valueMax() ) { return; } newVal = self._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === self._valueMin() ) { return; } newVal = self._trimAlignValue( curVal - step ); break; } self._slide( event, index, newVal ); return ret; }) .keyup(function( event ) { var index = $( this ).data( "index.ui-slider-handle" ); if ( self._keySliding ) { self._keySliding = false; self._stop( event, index ); self._change( event, index ); $( this ).removeClass( "ui-state-active" ); } }); this._refreshValue(); this._animateOff = false; }, destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-slider-disabled" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ) .removeData( "slider" ) .unbind( ".slider" ); this._mouseDestroy(); return this; }, _mouseCapture: function( event ) { var o = this.options, position, normValue, distance, closestHandle, self, index, allowed, offset, mouseOverHandle; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; self = this; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - self.values(i) ); if ( distance > thisDistance ) { distance = thisDistance; closestHandle = $( this ); index = i; } }); // workaround for bug #3736 (if both handles of a range are at 0, // the first is always used as the one with least distance, // and moving it is obviously prevented by preventing negative ranges) if( o.range === true && this.values(1) === o.min ) { index += 1; closestHandle = $( this.handles[index] ); } allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; self._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function( event ) { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal, true ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "disabled": if ( value ) { this.handles.filter( ".ui-state-focus" ).blur(); this.handles.removeClass( "ui-state-hover" ); this.handles.propAttr( "disabled", true ); this.element.addClass( "ui-disabled" ); } else { this.handles.propAttr( "disabled", false ); this.element.removeClass( "ui-disabled" ); } break; case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var oRange = this.options.range, o = this.options, self = this, animate = ( !this._animateOff ) ? o.animate : false, valPercent, _set = {}, lastValPercent, value, valueMin, valueMax; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i, j ) { valPercent = ( self.values(i) - self._valueMin() ) / ( self._valueMax() - self._valueMin() ) * 100; _set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( self.options.range === true ) { if ( self.orientation === "horizontal" ) { if ( i === 0 ) { self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { self.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { self.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } }); $.extend( $.ui.slider, { version: "1.8.16" }); }(jQuery)); /* * jQuery UI Tabs 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Tabs * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var tabId = 0, listId = 0; function getNextTabId() { return ++tabId; } function getNextListId() { return ++listId; } $.widget( "ui.tabs", { options: { add: null, ajaxOptions: null, cache: false, cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } collapsible: false, disable: null, disabled: [], enable: null, event: "click", fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 } idPrefix: "ui-tabs-", load: null, panelTemplate: "
", remove: null, select: null, show: null, spinner: "Loading…", tabTemplate: "
  • #{label}
  • " }, _create: function() { this._tabify( true ); }, _setOption: function( key, value ) { if ( key == "selected" ) { if (this.options.collapsible && value == this.options.selected ) { return; } this.select( value ); } else { this.options[ key ] = value; this._tabify(); } }, _tabId: function( a ) { return a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF-]/g, "" ) || this.options.idPrefix + getNextTabId(); }, _sanitizeSelector: function( hash ) { // we need this because an id may contain a ":" return hash.replace( /:/g, "\\:" ); }, _cookie: function() { var cookie = this.cookie || ( this.cookie = this.options.cookie.name || "ui-tabs-" + getNextListId() ); return $.cookie.apply( null, [ cookie ].concat( $.makeArray( arguments ) ) ); }, _ui: function( tab, panel ) { return { tab: tab, panel: panel, index: this.anchors.index( tab ) }; }, _cleanup: function() { // restore all former loading tabs labels this.lis.filter( ".ui-state-processing" ) .removeClass( "ui-state-processing" ) .find( "span:data(label.tabs)" ) .each(function() { var el = $( this ); el.html( el.data( "label.tabs" ) ).removeData( "label.tabs" ); }); }, _tabify: function( init ) { var self = this, o = this.options, fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash this.list = this.element.find( "ol,ul" ).eq( 0 ); this.lis = $( " > li:has(a[href])", this.list ); this.anchors = this.lis.map(function() { return $( "a", this )[ 0 ]; }); this.panels = $( [] ); this.anchors.each(function( i, a ) { var href = $( a ).attr( "href" ); // For dynamically created HTML that contains a hash as href IE < 8 expands // such href to the full page url with hash and then misinterprets tab as ajax. // Same consideration applies for an added tab with a fragment identifier // since a[href=#fragment-identifier] does unexpectedly not match. // Thus normalize href attribute... var hrefBase = href.split( "#" )[ 0 ], baseEl; if ( hrefBase && ( hrefBase === location.toString().split( "#" )[ 0 ] || ( baseEl = $( "base" )[ 0 ]) && hrefBase === baseEl.href ) ) { href = a.hash; a.href = href; } // inline tab if ( fragmentId.test( href ) ) { self.panels = self.panels.add( self.element.find( self._sanitizeSelector( href ) ) ); // remote tab // prevent loading the page itself if href is just "#" } else if ( href && href !== "#" ) { // required for restore on destroy $.data( a, "href.tabs", href ); // TODO until #3808 is fixed strip fragment identifier from url // (IE fails to load from such url) $.data( a, "load.tabs", href.replace( /#.*$/, "" ) ); var id = self._tabId( a ); a.href = "#" + id; var $panel = self.element.find( "#" + id ); if ( !$panel.length ) { $panel = $( o.panelTemplate ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .insertAfter( self.panels[ i - 1 ] || self.list ); $panel.data( "destroy.tabs", true ); } self.panels = self.panels.add( $panel ); // invalid tab href } else { o.disabled.push( i ); } }); // initialization from scratch if ( init ) { // attach necessary classes for styling this.element.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ); this.list.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ); this.lis.addClass( "ui-state-default ui-corner-top" ); this.panels.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ); // Selected tab // use "selected" option or try to retrieve: // 1. from fragment identifier in url // 2. from cookie // 3. from selected class attribute on
  • if ( o.selected === undefined ) { if ( location.hash ) { this.anchors.each(function( i, a ) { if ( a.hash == location.hash ) { o.selected = i; return false; } }); } if ( typeof o.selected !== "number" && o.cookie ) { o.selected = parseInt( self._cookie(), 10 ); } if ( typeof o.selected !== "number" && this.lis.filter( ".ui-tabs-selected" ).length ) { o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) ); } o.selected = o.selected || ( this.lis.length ? 0 : -1 ); } else if ( o.selected === null ) { // usage of null is deprecated, TODO remove in next release o.selected = -1; } // sanity check - default to first tab... o.selected = ( ( o.selected >= 0 && this.anchors[ o.selected ] ) || o.selected < 0 ) ? o.selected : 0; // Take disabling tabs via class attribute from HTML // into account and update option properly. // A selected tab cannot become disabled. o.disabled = $.unique( o.disabled.concat( $.map( this.lis.filter( ".ui-state-disabled" ), function( n, i ) { return self.lis.index( n ); }) ) ).sort(); if ( $.inArray( o.selected, o.disabled ) != -1 ) { o.disabled.splice( $.inArray( o.selected, o.disabled ), 1 ); } // highlight selected tab this.panels.addClass( "ui-tabs-hide" ); this.lis.removeClass( "ui-tabs-selected ui-state-active" ); // check for length avoids error when initializing empty list if ( o.selected >= 0 && this.anchors.length ) { self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) ).removeClass( "ui-tabs-hide" ); this.lis.eq( o.selected ).addClass( "ui-tabs-selected ui-state-active" ); // seems to be expected behavior that the show callback is fired self.element.queue( "tabs", function() { self._trigger( "show", null, self._ui( self.anchors[ o.selected ], self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) )[ 0 ] ) ); }); this.load( o.selected ); } // clean up to avoid memory leaks in certain versions of IE 6 // TODO: namespace this event $( window ).bind( "unload", function() { self.lis.add( self.anchors ).unbind( ".tabs" ); self.lis = self.anchors = self.panels = null; }); // update selected after add/remove } else { o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) ); } // update collapsible // TODO: use .toggleClass() this.element[ o.collapsible ? "addClass" : "removeClass" ]( "ui-tabs-collapsible" ); // set or update cookie after init and add/remove respectively if ( o.cookie ) { this._cookie( o.selected, o.cookie ); } // disable tabs for ( var i = 0, li; ( li = this.lis[ i ] ); i++ ) { $( li )[ $.inArray( i, o.disabled ) != -1 && // TODO: use .toggleClass() !$( li ).hasClass( "ui-tabs-selected" ) ? "addClass" : "removeClass" ]( "ui-state-disabled" ); } // reset cache if switching from cached to not cached if ( o.cache === false ) { this.anchors.removeData( "cache.tabs" ); } // remove all handlers before, tabify may run on existing tabs after add or option change this.lis.add( this.anchors ).unbind( ".tabs" ); if ( o.event !== "mouseover" ) { var addState = function( state, el ) { if ( el.is( ":not(.ui-state-disabled)" ) ) { el.addClass( "ui-state-" + state ); } }; var removeState = function( state, el ) { el.removeClass( "ui-state-" + state ); }; this.lis.bind( "mouseover.tabs" , function() { addState( "hover", $( this ) ); }); this.lis.bind( "mouseout.tabs", function() { removeState( "hover", $( this ) ); }); this.anchors.bind( "focus.tabs", function() { addState( "focus", $( this ).closest( "li" ) ); }); this.anchors.bind( "blur.tabs", function() { removeState( "focus", $( this ).closest( "li" ) ); }); } // set up animations var hideFx, showFx; if ( o.fx ) { if ( $.isArray( o.fx ) ) { hideFx = o.fx[ 0 ]; showFx = o.fx[ 1 ]; } else { hideFx = showFx = o.fx; } } // Reset certain styles left over from animation // and prevent IE's ClearType bug... function resetStyle( $el, fx ) { $el.css( "display", "" ); if ( !$.support.opacity && fx.opacity ) { $el[ 0 ].style.removeAttribute( "filter" ); } } // Show a tab... var showTab = showFx ? function( clicked, $show ) { $( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" ); $show.hide().removeClass( "ui-tabs-hide" ) // avoid flicker that way .animate( showFx, showFx.duration || "normal", function() { resetStyle( $show, showFx ); self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) ); }); } : function( clicked, $show ) { $( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" ); $show.removeClass( "ui-tabs-hide" ); self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) ); }; // Hide a tab, $show is optional... var hideTab = hideFx ? function( clicked, $hide ) { $hide.animate( hideFx, hideFx.duration || "normal", function() { self.lis.removeClass( "ui-tabs-selected ui-state-active" ); $hide.addClass( "ui-tabs-hide" ); resetStyle( $hide, hideFx ); self.element.dequeue( "tabs" ); }); } : function( clicked, $hide, $show ) { self.lis.removeClass( "ui-tabs-selected ui-state-active" ); $hide.addClass( "ui-tabs-hide" ); self.element.dequeue( "tabs" ); }; // attach tab event handler, unbind to avoid duplicates from former tabifying... this.anchors.bind( o.event + ".tabs", function() { var el = this, $li = $(el).closest( "li" ), $hide = self.panels.filter( ":not(.ui-tabs-hide)" ), $show = self.element.find( self._sanitizeSelector( el.hash ) ); // If tab is already selected and not collapsible or tab disabled or // or is already loading or click callback returns false stop here. // Check if click handler returns false last so that it is not executed // for a disabled or loading tab! if ( ( $li.hasClass( "ui-tabs-selected" ) && !o.collapsible) || $li.hasClass( "ui-state-disabled" ) || $li.hasClass( "ui-state-processing" ) || self.panels.filter( ":animated" ).length || self._trigger( "select", null, self._ui( this, $show[ 0 ] ) ) === false ) { this.blur(); return false; } o.selected = self.anchors.index( this ); self.abort(); // if tab may be closed if ( o.collapsible ) { if ( $li.hasClass( "ui-tabs-selected" ) ) { o.selected = -1; if ( o.cookie ) { self._cookie( o.selected, o.cookie ); } self.element.queue( "tabs", function() { hideTab( el, $hide ); }).dequeue( "tabs" ); this.blur(); return false; } else if ( !$hide.length ) { if ( o.cookie ) { self._cookie( o.selected, o.cookie ); } self.element.queue( "tabs", function() { showTab( el, $show ); }); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171 self.load( self.anchors.index( this ) ); this.blur(); return false; } } if ( o.cookie ) { self._cookie( o.selected, o.cookie ); } // show new tab if ( $show.length ) { if ( $hide.length ) { self.element.queue( "tabs", function() { hideTab( el, $hide ); }); } self.element.queue( "tabs", function() { showTab( el, $show ); }); self.load( self.anchors.index( this ) ); } else { throw "jQuery UI Tabs: Mismatching fragment identifier."; } // Prevent IE from keeping other link focussed when using the back button // and remove dotted border from clicked link. This is controlled via CSS // in modern browsers; blur() removes focus from address bar in Firefox // which can become a usability and annoying problem with tabs('rotate'). if ( $.browser.msie ) { this.blur(); } }); // disable click in any case this.anchors.bind( "click.tabs", function(){ return false; }); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. // also sanitizes numerical indexes to valid values. if ( typeof index == "string" ) { index = this.anchors.index( this.anchors.filter( "[href$=" + index + "]" ) ); } return index; }, destroy: function() { var o = this.options; this.abort(); this.element .unbind( ".tabs" ) .removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ) .removeData( "tabs" ); this.list.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ); this.anchors.each(function() { var href = $.data( this, "href.tabs" ); if ( href ) { this.href = href; } var $this = $( this ).unbind( ".tabs" ); $.each( [ "href", "load", "cache" ], function( i, prefix ) { $this.removeData( prefix + ".tabs" ); }); }); this.lis.unbind( ".tabs" ).add( this.panels ).each(function() { if ( $.data( this, "destroy.tabs" ) ) { $( this ).remove(); } else { $( this ).removeClass([ "ui-state-default", "ui-corner-top", "ui-tabs-selected", "ui-state-active", "ui-state-hover", "ui-state-focus", "ui-state-disabled", "ui-tabs-panel", "ui-widget-content", "ui-corner-bottom", "ui-tabs-hide" ].join( " " ) ); } }); if ( o.cookie ) { this._cookie( null, o.cookie ); } return this; }, add: function( url, label, index ) { if ( index === undefined ) { index = this.anchors.length; } var self = this, o = this.options, $li = $( o.tabTemplate.replace( /#\{href\}/g, url ).replace( /#\{label\}/g, label ) ), id = !url.indexOf( "#" ) ? url.replace( "#", "" ) : this._tabId( $( "a", $li )[ 0 ] ); $li.addClass( "ui-state-default ui-corner-top" ).data( "destroy.tabs", true ); // try to find an existing element before creating a new one var $panel = self.element.find( "#" + id ); if ( !$panel.length ) { $panel = $( o.panelTemplate ) .attr( "id", id ) .data( "destroy.tabs", true ); } $panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide" ); if ( index >= this.lis.length ) { $li.appendTo( this.list ); $panel.appendTo( this.list[ 0 ].parentNode ); } else { $li.insertBefore( this.lis[ index ] ); $panel.insertBefore( this.panels[ index ] ); } o.disabled = $.map( o.disabled, function( n, i ) { return n >= index ? ++n : n; }); this._tabify(); if ( this.anchors.length == 1 ) { o.selected = 0; $li.addClass( "ui-tabs-selected ui-state-active" ); $panel.removeClass( "ui-tabs-hide" ); this.element.queue( "tabs", function() { self._trigger( "show", null, self._ui( self.anchors[ 0 ], self.panels[ 0 ] ) ); }); this.load( 0 ); } this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); return this; }, remove: function( index ) { index = this._getIndex( index ); var o = this.options, $li = this.lis.eq( index ).remove(), $panel = this.panels.eq( index ).remove(); // If selected tab was removed focus tab to the right or // in case the last tab was removed the tab to the left. if ( $li.hasClass( "ui-tabs-selected" ) && this.anchors.length > 1) { this.select( index + ( index + 1 < this.anchors.length ? 1 : -1 ) ); } o.disabled = $.map( $.grep( o.disabled, function(n, i) { return n != index; }), function( n, i ) { return n >= index ? --n : n; }); this._tabify(); this._trigger( "remove", null, this._ui( $li.find( "a" )[ 0 ], $panel[ 0 ] ) ); return this; }, enable: function( index ) { index = this._getIndex( index ); var o = this.options; if ( $.inArray( index, o.disabled ) == -1 ) { return; } this.lis.eq( index ).removeClass( "ui-state-disabled" ); o.disabled = $.grep( o.disabled, function( n, i ) { return n != index; }); this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); return this; }, disable: function( index ) { index = this._getIndex( index ); var self = this, o = this.options; // cannot disable already selected tab if ( index != o.selected ) { this.lis.eq( index ).addClass( "ui-state-disabled" ); o.disabled.push( index ); o.disabled.sort(); this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); } return this; }, select: function( index ) { index = this._getIndex( index ); if ( index == -1 ) { if ( this.options.collapsible && this.options.selected != -1 ) { index = this.options.selected; } else { return this; } } this.anchors.eq( index ).trigger( this.options.event + ".tabs" ); return this; }, load: function( index ) { index = this._getIndex( index ); var self = this, o = this.options, a = this.anchors.eq( index )[ 0 ], url = $.data( a, "load.tabs" ); this.abort(); // not remote or from cache if ( !url || this.element.queue( "tabs" ).length !== 0 && $.data( a, "cache.tabs" ) ) { this.element.dequeue( "tabs" ); return; } // load remote from here on this.lis.eq( index ).addClass( "ui-state-processing" ); if ( o.spinner ) { var span = $( "span", a ); span.data( "label.tabs", span.html() ).html( o.spinner ); } this.xhr = $.ajax( $.extend( {}, o.ajaxOptions, { url: url, success: function( r, s ) { self.element.find( self._sanitizeSelector( a.hash ) ).html( r ); // take care of tab labels self._cleanup(); if ( o.cache ) { $.data( a, "cache.tabs", true ); } self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) ); try { o.ajaxOptions.success( r, s ); } catch ( e ) {} }, error: function( xhr, s, e ) { // take care of tab labels self._cleanup(); self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) ); try { // Passing index avoid a race condition when this method is // called after the user has selected another tab. // Pass the anchor that initiated this request allows // loadError to manipulate the tab content panel via $(a.hash) o.ajaxOptions.error( xhr, s, index, a ); } catch ( e ) {} } } ) ); // last, so that load event is fired before show... self.element.dequeue( "tabs" ); return this; }, abort: function() { // stop possibly running animations this.element.queue( [] ); this.panels.stop( false, true ); // "tabs" queue must not contain more than two elements, // which are the callbacks for the latest clicked tab... this.element.queue( "tabs", this.element.queue( "tabs" ).splice( -2, 2 ) ); // terminate pending requests from other tabs if ( this.xhr ) { this.xhr.abort(); delete this.xhr; } // take care of tab labels this._cleanup(); return this; }, url: function( index, url ) { this.anchors.eq( index ).removeData( "cache.tabs" ).data( "load.tabs", url ); return this; }, length: function() { return this.anchors.length; } }); $.extend( $.ui.tabs, { version: "1.8.16" }); /* * Tabs Extensions */ /* * Rotate */ $.extend( $.ui.tabs.prototype, { rotation: null, rotate: function( ms, continuing ) { var self = this, o = this.options; var rotate = self._rotate || ( self._rotate = function( e ) { clearTimeout( self.rotation ); self.rotation = setTimeout(function() { var t = o.selected; self.select( ++t < self.anchors.length ? t : 0 ); }, ms ); if ( e ) { e.stopPropagation(); } }); var stop = self._unrotate || ( self._unrotate = !continuing ? function(e) { if (e.clientX) { // in case of a true click self.rotate(null); } } : function( e ) { t = o.selected; rotate(); }); // start rotation if ( ms ) { this.element.bind( "tabsshow", rotate ); this.anchors.bind( o.event + ".tabs", stop ); rotate(); // stop rotation } else { clearTimeout( self.rotation ); this.element.unbind( "tabsshow", rotate ); this.anchors.unbind( o.event + ".tabs", stop ); delete this._rotate; delete this._unrotate; } return this; } }); })( jQuery ); /** * @license Input Mask plugin for jquery * http://github.com/RobinHerbots/jquery.inputmask * Copyright (c) 2010 - 2014 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 0.0.0 */ (function ($) { if ($.fn.inputmask === undefined) { //helper functions function isInputEventSupported(eventName) { var el = document.createElement('input'), eventName = 'on' + eventName, isSupported = (eventName in el); if (!isSupported) { el.setAttribute(eventName, 'return;'); isSupported = typeof el[eventName] == 'function'; } el = null; return isSupported; } function resolveAlias(aliasStr, options, 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; } return false; } function generateMaskSets(opts) { var ms = []; var genmasks = []; //used to keep track of the masks that where processed, to avoid duplicates function getMaskTemplate(mask) { if (opts.numericInput) { mask = mask.split('').reverse().join(''); } var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat; if (repeat == "*") greedy = false; //if (greedy == true && opts.placeholder == "") opts.placeholder = " "; if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask var singleMask = $.map(mask.split(""), function (element, index) { var outElem = []; if (element == opts.escapeChar) { escaped = true; } else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) { var maskdef = opts.definitions[element]; if (maskdef && !escaped) { for (var i = 0; i < maskdef.cardinality; i++) { outElem.push(opts.placeholder.charAt((outCount + i) % opts.placeholder.length)); } } else { outElem.push(element); escaped = false; } outCount += outElem.length; return outElem; } }); //allocate repetitions var repeatedMask = singleMask.slice(); for (var i = 1; i < repeat && greedy; i++) { repeatedMask = repeatedMask.concat(singleMask.slice()); } return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy }; } //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol} function getTestingChain(mask) { if (opts.numericInput) { mask = mask.split('').reverse().join(''); } var isOptional = false, escaped = false; var newBlockMarker = false; //indicates wheter the begin/ending of a block should be indicated return $.map(mask.split(""), function (element, index) { var outElem = []; if (element == opts.escapeChar) { escaped = true; } else if (element == opts.optionalmarker.start && !escaped) { isOptional = true; newBlockMarker = true; } else if (element == opts.optionalmarker.end && !escaped) { isOptional = false; newBlockMarker = true; } else { var maskdef = opts.definitions[element]; if (maskdef && !escaped) { var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0; for (var i = 1; i < maskdef.cardinality; i++) { var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"]; outElem.push({ fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function () { this.test = validator; } : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: isOptional, newBlockMarker: isOptional == true ? newBlockMarker : false, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element }); if (isOptional == true) //reset newBlockMarker newBlockMarker = false; } outElem.push({ fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function () { this.test = maskdef.validator; } : new RegExp("."), cardinality: maskdef.cardinality, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element }); } else { outElem.push({ fn: null, cardinality: 0, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: null, def: element }); escaped = false; } //reset newBlockMarker newBlockMarker = false; return outElem; } }); } function markOptional(maskPart) { //needed for the clearOptionalTail functionality return opts.optionalmarker.start + maskPart + opts.optionalmarker.end; } function splitFirstOptionalEndPart(maskPart) { var optionalStartMarkers = 0, optionalEndMarkers = 0, mpl = maskPart.length; for (var i = 0; i < mpl; i++) { if (maskPart.charAt(i) == opts.optionalmarker.start) { optionalStartMarkers++; } if (maskPart.charAt(i) == opts.optionalmarker.end) { optionalEndMarkers++; } if (optionalStartMarkers > 0 && optionalStartMarkers == optionalEndMarkers) break; } var maskParts = [maskPart.substring(0, i)]; if (i < mpl) { maskParts.push(maskPart.substring(i + 1, mpl)); } return maskParts; } function splitFirstOptionalStartPart(maskPart) { var mpl = maskPart.length; for (var i = 0; i < mpl; i++) { if (maskPart.charAt(i) == opts.optionalmarker.start) { break; } } var maskParts = [maskPart.substring(0, i)]; if (i < mpl) { maskParts.push(maskPart.substring(i + 1, mpl)); } return maskParts; } function generateMask(maskPrefix, maskPart, metadata) { var maskParts = splitFirstOptionalEndPart(maskPart); var newMask, maskTemplate; var masks = splitFirstOptionalStartPart(maskParts[0]); if (masks.length > 1) { newMask = maskPrefix + masks[0] + markOptional(masks[1]) + (maskParts.length > 1 ? maskParts[1] : ""); if ($.inArray(newMask, genmasks) == -1 && newMask != "") { genmasks.push(newMask); maskTemplate = getMaskTemplate(newMask); ms.push({ "mask": newMask, "_buffer": maskTemplate["mask"], "buffer": maskTemplate["mask"].slice(), "tests": getTestingChain(newMask), "lastValidPosition": -1, "greedy": maskTemplate["greedy"], "repeat": maskTemplate["repeat"], "metadata": metadata }); } newMask = maskPrefix + masks[0] + (maskParts.length > 1 ? maskParts[1] : ""); if ($.inArray(newMask, genmasks) == -1 && newMask != "") { genmasks.push(newMask); maskTemplate = getMaskTemplate(newMask); ms.push({ "mask": newMask, "_buffer": maskTemplate["mask"], "buffer": maskTemplate["mask"].slice(), "tests": getTestingChain(newMask), "lastValidPosition": -1, "greedy": maskTemplate["greedy"], "repeat": maskTemplate["repeat"], "metadata": metadata }); } if (splitFirstOptionalStartPart(masks[1]).length > 1) { //optional contains another optional generateMask(maskPrefix + masks[0], masks[1] + maskParts[1], metadata); } if (maskParts.length > 1 && splitFirstOptionalStartPart(maskParts[1]).length > 1) { generateMask(maskPrefix + masks[0] + markOptional(masks[1]), maskParts[1], metadata); generateMask(maskPrefix + masks[0], maskParts[1], metadata); } } else { newMask = maskPrefix + maskParts; if ($.inArray(newMask, genmasks) == -1 && newMask != "") { genmasks.push(newMask); maskTemplate = getMaskTemplate(newMask); ms.push({ "mask": newMask, "_buffer": maskTemplate["mask"], "buffer": maskTemplate["mask"].slice(), "tests": getTestingChain(newMask), "lastValidPosition": -1, "greedy": maskTemplate["greedy"], "repeat": maskTemplate["repeat"], "metadata": metadata }); } } } if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask opts.mask = opts.mask.call(this, opts); } if ($.isArray(opts.mask)) { $.each(opts.mask, function (ndx, msk) { if (msk["mask"] != undefined) { generateMask("", msk["mask"].toString(), msk); } else generateMask("", msk.toString()); }); } else generateMask("", opts.mask.toString()); return opts.greedy ? ms : ms.sort(function (a, b) { return a["mask"].length - b["mask"].length; }); } var msie10 = navigator.userAgent.match(new RegExp("msie 10", "i")) !== null, iphone = navigator.userAgent.match(new RegExp("iphone", "i")) !== null, android = navigator.userAgent.match(new RegExp("android.*safari.*", "i")) !== null, androidchrome = navigator.userAgent.match(new RegExp("android.*chrome.*", "i")) !== null, pasteEvent = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange"; //masking scope //actionObj definition see below function maskScope(masksets, activeMasksetIndex, opts, actionObj) { var isRTL = false, valueOnFocus = getActiveBuffer().join(''), $el, chromeValueOnInput, skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround skipInputEvent = false, //skip when triggered from within inputmask ignorable = false; //maskset helperfunctions function getActiveMaskSet() { return masksets[activeMasksetIndex]; } function getActiveTests() { return getActiveMaskSet()['tests']; } function getActiveBufferTemplate() { return getActiveMaskSet()['_buffer']; } function getActiveBuffer() { return getActiveMaskSet()['buffer']; } function isValid(pos, c, strict) { //strict 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, activeMaskset, c, strict) { var testPos = determineTestPosition(position), loopend = c ? 1 : 0, chrs = '', buffer = activeMaskset["buffer"]; for (var i = activeMaskset['tests'][testPos].cardinality; i > loopend; i--) { chrs += getBufferElement(buffer, testPos - (i - 1)); } if (c) { chrs += c; } //return is false or a json object => { pos: ??, c: ??} or true return activeMaskset['tests'][testPos].fn != null ? activeMaskset['tests'][testPos].fn.test(chrs, buffer, position, strict, opts) : (c == getBufferElement(activeMaskset['_buffer'], position, true) || c == opts.skipOptionalPartCharacter) ? { "refresh": true, c: getBufferElement(activeMaskset['_buffer'], position, true), pos: position } : false; } function PostProcessResults(maskForwards, results) { var hasValidActual = false; $.each(results, function (ndx, rslt) { hasValidActual = $.inArray(rslt["activeMasksetIndex"], maskForwards) == -1 && rslt["result"] !== false; if (hasValidActual) return false; }); if (hasValidActual) { //strip maskforwards results = $.map(results, function (rslt, ndx) { if ($.inArray(rslt["activeMasksetIndex"], maskForwards) == -1) { return rslt; } else { masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = actualLVP; } }); } else { //keep maskforwards with the least forward var lowestPos = -1, lowestIndex = -1, rsltValid; $.each(results, function (ndx, rslt) { if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1 && rslt["result"] !== false & (lowestPos == -1 || lowestPos > rslt["result"]["pos"])) { lowestPos = rslt["result"]["pos"]; lowestIndex = rslt["activeMasksetIndex"]; } }); results = $.map(results, function (rslt, ndx) { if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1) { if (rslt["result"]["pos"] == lowestPos) { return rslt; } else if (rslt["result"] !== false) { for (var i = pos; i < lowestPos; i++) { rsltValid = _isValid(i, masksets[rslt["activeMasksetIndex"]], masksets[lowestIndex]["buffer"][i], true); if (rsltValid === false) { masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos - 1; break; } else { setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], i, masksets[lowestIndex]["buffer"][i], true); masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = i; } } //also check check for the lowestpos with the new input rsltValid = _isValid(lowestPos, masksets[rslt["activeMasksetIndex"]], c, true); if (rsltValid !== false) { setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], lowestPos, c, true); masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos; } //console.log("ndx " + rslt["activeMasksetIndex"] + " validate " + masksets[rslt["activeMasksetIndex"]]["buffer"].join('') + " lv " + masksets[rslt["activeMasksetIndex"]]['lastValidPosition']); return rslt; } } }); } return results; } if (strict) { var result = _isValid(pos, getActiveMaskSet(), c, strict); //only check validity in current mask when validating strict if (result === true) { result = { "pos": pos }; //always take a possible corrected maskposition into account } return result; } var results = [], result = false, currentActiveMasksetIndex = activeMasksetIndex, actualBuffer = getActiveBuffer().slice(), actualLVP = getActiveMaskSet()["lastValidPosition"], actualPrevious = seekPrevious(pos), maskForwards = []; $.each(masksets, function (index, value) { if (typeof (value) == "object") { activeMasksetIndex = index; var maskPos = pos; var lvp = getActiveMaskSet()['lastValidPosition'], rsltValid; if (lvp == actualLVP) { if ((maskPos - actualLVP) > 1) { for (var i = lvp == -1 ? 0 : lvp; i < maskPos; i++) { rsltValid = _isValid(i, getActiveMaskSet(), actualBuffer[i], true); if (rsltValid === false) { break; } else { setBufferElement(getActiveBuffer(), i, actualBuffer[i], true); if (rsltValid === true) { rsltValid = { "pos": i }; //always take a possible corrected maskposition into account } var newValidPosition = rsltValid.pos || i; if (getActiveMaskSet()['lastValidPosition'] < newValidPosition) getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid } } } //does the input match on a further position? if (!isMask(maskPos) && !_isValid(maskPos, getActiveMaskSet(), c, strict)) { var maxForward = seekNext(maskPos) - maskPos; for (var fw = 0; fw < maxForward; fw++) { if (_isValid(++maskPos, getActiveMaskSet(), c, strict) !== false) break; } maskForwards.push(activeMasksetIndex); //console.log('maskforward ' + activeMasksetIndex + " pos " + pos + " maskPos " + maskPos); } } if (getActiveMaskSet()['lastValidPosition'] >= actualLVP || activeMasksetIndex == currentActiveMasksetIndex) { if (maskPos >= 0 && maskPos < getMaskLength()) { result = _isValid(maskPos, getActiveMaskSet(), c, strict); if (result !== false) { if (result === true) { result = { "pos": maskPos }; //always take a possible corrected maskposition into account } var newValidPosition = result.pos || maskPos; if (getActiveMaskSet()['lastValidPosition'] < newValidPosition) getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid } //console.log("pos " + pos + " ndx " + activeMasksetIndex + " validate " + getActiveBuffer().join('') + " lv " + getActiveMaskSet()['lastValidPosition']); results.push({ "activeMasksetIndex": index, "result": result }); } } } }); activeMasksetIndex = currentActiveMasksetIndex; //reset activeMasksetIndex return PostProcessResults(maskForwards, results); //return results of the multiple mask validations } function determineActiveMasksetIndex() { var currentMasksetIndex = activeMasksetIndex, highestValid = { "activeMasksetIndex": 0, "lastValidPosition": -1, "next": -1 }; $.each(masksets, function (index, value) { if (typeof (value) == "object") { activeMasksetIndex = index; if (getActiveMaskSet()['lastValidPosition'] > highestValid['lastValidPosition']) { highestValid["activeMasksetIndex"] = index; highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition']; highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']); } else if (getActiveMaskSet()['lastValidPosition'] == highestValid['lastValidPosition'] && (highestValid['next'] == -1 || highestValid['next'] > seekNext(getActiveMaskSet()['lastValidPosition']))) { highestValid["activeMasksetIndex"] = index; highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition']; highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']); } } }); activeMasksetIndex = highestValid["lastValidPosition"] != -1 && masksets[currentMasksetIndex]["lastValidPosition"] == highestValid["lastValidPosition"] ? currentMasksetIndex : highestValid["activeMasksetIndex"]; if (currentMasksetIndex != activeMasksetIndex) { clearBuffer(getActiveBuffer(), seekNext(highestValid["lastValidPosition"]), getMaskLength()); getActiveMaskSet()["writeOutBuffer"] = true; } $el.data('_inputmask')['activeMasksetIndex'] = activeMasksetIndex; //store the activeMasksetIndex } function isMask(pos) { var testPos = determineTestPosition(pos); var test = getActiveTests()[testPos]; return test != undefined ? test.fn : false; } function determineTestPosition(pos) { return pos % getActiveTests().length; } function getMaskLength() { return opts.getMaskLength(getActiveBufferTemplate(), getActiveMaskSet()['greedy'], getActiveMaskSet()['repeat'], getActiveBuffer(), opts); } //pos: from position function seekNext(pos) { var maskL = getMaskLength(); if (pos >= maskL) return maskL; var position = pos; while (++position < maskL && !isMask(position)) { } return position; } //pos: from position function seekPrevious(pos) { var position = pos; if (position <= 0) return 0; while (--position > 0 && !isMask(position)) { } return position; } function setBufferElement(buffer, position, element, autoPrepare) { if (autoPrepare) position = prepareBuffer(buffer, position); var test = getActiveTests()[determineTestPosition(position)]; var elem = element; if (elem != undefined && test != undefined) { switch (test.casing) { case "upper": elem = element.toUpperCase(); break; case "lower": elem = element.toLowerCase(); break; } } buffer[position] = elem; } function getBufferElement(buffer, position, autoPrepare) { if (autoPrepare) position = prepareBuffer(buffer, position); return buffer[position]; } //needed to handle the non-greedy mask repetitions function prepareBuffer(buffer, position) { var j; while (buffer[position] == undefined && buffer.length < getMaskLength()) { j = 0; while (getActiveBufferTemplate()[j] !== undefined) { //add a new buffer buffer.push(getActiveBufferTemplate()[j++]); } } return position; } function writeBuffer(input, buffer, caretPos) { input._valueSet(buffer.join('')); if (caretPos != undefined) { caret(input, caretPos); } } function clearBuffer(buffer, start, end, stripNomasks) { for (var i = start, maskL = getMaskLength() ; i < end && i < maskL; i++) { if (stripNomasks === true) { if (!isMask(i)) setBufferElement(buffer, i, ""); } else setBufferElement(buffer, i, getBufferElement(getActiveBufferTemplate().slice(), i, true)); } } function setReTargetPlaceHolder(buffer, pos) { var testPos = determineTestPosition(pos); setBufferElement(buffer, pos, getBufferElement(getActiveBufferTemplate(), testPos)); } function getPlaceHolder(pos) { return opts.placeholder.charAt(pos % opts.placeholder.length); } function checkVal(input, writeOut, strict, nptvl, intelliCheck) { var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split(''); $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { ms["buffer"] = ms["_buffer"].slice(); ms["lastValidPosition"] = -1; ms["p"] = -1; } }); if (strict !== true) activeMasksetIndex = 0; if (writeOut) input._valueSet(""); //initial clear var ml = getMaskLength(); $.each(inputValue, function (ndx, charCode) { if (intelliCheck === true) { var p = getActiveMaskSet()["p"], lvp = p == -1 ? p : seekPrevious(p), pos = lvp == -1 ? ndx : seekNext(lvp); if ($.inArray(charCode, getActiveBufferTemplate().slice(lvp + 1, pos)) == -1) { keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx); } } else { keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), writeOut, strict, ndx); } }); if (strict === true && getActiveMaskSet()["p"] != -1) { getActiveMaskSet()["lastValidPosition"] = seekPrevious(getActiveMaskSet()["p"]); } } function escapeRegex(str) { return $.inputmask.escapeRegex.call(this, str); } function truncateInput(inputValue) { return inputValue.replace(new RegExp("(" + escapeRegex(getActiveBufferTemplate().join('')) + ")*$"), ""); } function clearOptionalTail(input) { var buffer = getActiveBuffer(), tmpBuffer = buffer.slice(), testPos, pos; for (var pos = tmpBuffer.length - 1; pos >= 0; pos--) { var testPos = determineTestPosition(pos); if (getActiveTests()[testPos].optionality) { if (!isMask(pos) || !isValid(pos, buffer[pos], true)) tmpBuffer.pop(); else break; } else break; } writeBuffer(input, tmpBuffer); } function unmaskedvalue($input, skipDatepickerCheck) { if (getActiveTests() && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) { //checkVal(input, false, true); var umValue = $.map(getActiveBuffer(), function (element, index) { return isMask(index) && isValid(index, element, true) ? element : null; }); var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join(''); return opts.onUnMask != undefined ? opts.onUnMask.call(this, getActiveBuffer().join(''), unmaskedValue) : unmaskedValue; } else { return $input[0]._valueGet(); } } function TranslatePosition(pos) { if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) { var bffrLght = getActiveBuffer().length; pos = bffrLght - pos; } return pos; } function caret(input, begin, end) { var npt = input.jquery && input.length > 0 ? input[0] : input, range; if (typeof begin == 'number') { begin = TranslatePosition(begin); end = TranslatePosition(end); if (!$(input).is(':visible')) { return; } end = (typeof end == 'number') ? end : begin; npt.scrollLeft = npt.scrollWidth; if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode if (npt.setSelectionRange) { npt.selectionStart = begin; npt.selectionEnd = android ? begin : end; } else if (npt.createTextRange) { range = npt.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } } else { if (!$(input).is(':visible')) { return { "begin": 0, "end": 0 }; } if (npt.setSelectionRange) { begin = npt.selectionStart; end = npt.selectionEnd; } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } begin = TranslatePosition(begin); end = TranslatePosition(end); return { "begin": begin, "end": end }; } } function isComplete(buffer) { //return true / false / undefined (repeat *) if (opts.repeat == "*") return undefined; var complete = false, highestValidPosition = 0, currentActiveMasksetIndex = activeMasksetIndex; $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { activeMasksetIndex = ndx; var aml = seekPrevious(getMaskLength()); if (ms["lastValidPosition"] >= highestValidPosition && ms["lastValidPosition"] == aml) { var msComplete = true; for (var i = 0; i <= aml; i++) { var mask = isMask(i), testPos = determineTestPosition(i); if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceHolder(i))) || (!mask && buffer[i] != getActiveBufferTemplate()[testPos])) { msComplete = false; break; } } complete = complete || msComplete; if (complete) //break loop return false; } highestValidPosition = ms["lastValidPosition"]; } }); activeMasksetIndex = currentActiveMasksetIndex; //reset activeMaskset return complete; } function isSelection(begin, end) { return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) : (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode); } //private functions function installEventRuler(npt) { var events = $._data(npt).events; $.each(events, function (eventType, eventHandlers) { $.each(eventHandlers, function (ndx, eventHandler) { if (eventHandler.namespace == "inputmask") { if (eventHandler.type != "setvalue") { var handler = eventHandler.handler; eventHandler.handler = function (e) { if (this.readOnly || this.disabled) e.preventDefault; else return handler.apply(this, arguments); }; } } }); }); } function patchValueProperty(npt) { var valueProperty; if (Object.getOwnPropertyDescriptor) valueProperty = Object.getOwnPropertyDescriptor(npt, "value"); if (valueProperty && valueProperty.get) { if (!npt._valueGet) { var valueGet = valueProperty.get; var valueSet = valueProperty.set; npt._valueGet = function () { return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this); }; npt._valueSet = function (value) { valueSet.call(this, isRTL ? value.split('').reverse().join('') : value); }; Object.defineProperty(npt, "value", { get: function () { var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'], activeMasksetIndex = inputData['activeMasksetIndex']; return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : ''; }, set: function (value) { valueSet.call(this, value); $(this).triggerHandler('setvalue.inputmask'); } }); } } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) { if (!npt._valueGet) { var valueGet = npt.__lookupGetter__("value"); var valueSet = npt.__lookupSetter__("value"); npt._valueGet = function () { return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this); }; npt._valueSet = function (value) { valueSet.call(this, isRTL ? value.split('').reverse().join('') : value); }; npt.__defineGetter__("value", function () { var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'], activeMasksetIndex = inputData['activeMasksetIndex']; return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : ''; }); npt.__defineSetter__("value", function (value) { valueSet.call(this, value); $(this).triggerHandler('setvalue.inputmask'); }); } } else { if (!npt._valueGet) { npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; }; npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; }; } if ($.valHooks.text == undefined || $.valHooks.text.inputmaskpatch != true) { var valueGet = $.valHooks.text && $.valHooks.text.get ? $.valHooks.text.get : function (elem) { return elem.value; }; var valueSet = $.valHooks.text && $.valHooks.text.set ? $.valHooks.text.set : function (elem, value) { elem.value = value; return elem; }; jQuery.extend($.valHooks, { text: { get: function (elem) { var $elem = $(elem); if ($elem.data('_inputmask')) { if ($elem.data('_inputmask')['opts'].autoUnmask) return $elem.inputmask('unmaskedvalue'); else { var result = valueGet(elem), inputData = $elem.data('_inputmask'), masksets = inputData['masksets'], activeMasksetIndex = inputData['activeMasksetIndex']; return result != masksets[activeMasksetIndex]['_buffer'].join('') ? result : ''; } } else return valueGet(elem); }, set: function (elem, value) { var $elem = $(elem); var result = valueSet(elem, value); if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask'); return result; }, inputmaskpatch: true } }); } } } //shift chars to left from start to end and put c at end position if defined function shiftL(start, end, c, maskJumps) { var buffer = getActiveBuffer(); if (maskJumps !== false) //jumping over nonmask position while (!isMask(start) && start - 1 >= 0) start--; for (var i = start; i < end && i < getMaskLength() ; i++) { if (isMask(i)) { setReTargetPlaceHolder(buffer, i); var j = seekNext(i); var p = getBufferElement(buffer, j); if (p != getPlaceHolder(j)) { if (j < getMaskLength() && isValid(i, p, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) { setBufferElement(buffer, i, p, true); } else { if (isMask(i)) break; } } } else { setReTargetPlaceHolder(buffer, i); } } if (c != undefined) setBufferElement(buffer, seekPrevious(end), c); if (getActiveMaskSet()["greedy"] == false) { var trbuffer = truncateInput(buffer.join('')).split(''); buffer.length = trbuffer.length; for (var i = 0, bl = buffer.length; i < bl; i++) { buffer[i] = trbuffer[i]; } if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice(); } return start; //return the used start position } function shiftR(start, end, c) { var buffer = getActiveBuffer(); if (getBufferElement(buffer, start, true) != getPlaceHolder(start)) { for (var i = seekPrevious(end) ; i > start && i >= 0; i--) { if (isMask(i)) { var j = seekPrevious(i); var t = getBufferElement(buffer, j); if (t != getPlaceHolder(j)) { if (isValid(j, t, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) { setBufferElement(buffer, i, t, true); setReTargetPlaceHolder(buffer, j); } //else break; } } else setReTargetPlaceHolder(buffer, i); } } if (c != undefined && getBufferElement(buffer, start) == getPlaceHolder(start)) setBufferElement(buffer, start, c); var lengthBefore = buffer.length; if (getActiveMaskSet()["greedy"] == false) { var trbuffer = truncateInput(buffer.join('')).split(''); buffer.length = trbuffer.length; for (var i = 0, bl = buffer.length; i < bl; i++) { buffer[i] = trbuffer[i]; } if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice(); } return end - (lengthBefore - buffer.length); //return new start position } function HandleRemove(input, k, pos) { if (opts.numericInput || isRTL) { switch (k) { case opts.keyCode.BACKSPACE: k = opts.keyCode.DELETE; break; case opts.keyCode.DELETE: k = opts.keyCode.BACKSPACE; break; } if (isRTL) { var pend = pos.end; pos.end = pos.begin; pos.begin = pend; } } var isSelection = true; if (pos.begin == pos.end) { var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin; if (opts.isNumeric && opts.radixPoint != "" && getActiveBuffer()[posBegin] == opts.radixPoint) { pos.begin = (getActiveBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin); pos.end = pos.begin; } isSelection = false; if (k == opts.keyCode.BACKSPACE) pos.begin--; else if (k == opts.keyCode.DELETE) pos.end++; } else if (pos.end - pos.begin == 1 && !opts.insertMode) { isSelection = false; if (k == opts.keyCode.BACKSPACE) pos.begin--; } clearBuffer(getActiveBuffer(), pos.begin, pos.end); var ml = getMaskLength(); if (opts.greedy == false) { shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection)); } else { var newpos = pos.begin; for (var i = pos.begin; i < pos.end; i++) { //seeknext to skip placeholders at start in selection if (isMask(i) || !isSelection) newpos = shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection)); } if (!isSelection) pos.begin = newpos; } var firstMaskPos = seekNext(-1); clearBuffer(getActiveBuffer(), pos.begin, pos.end, true); checkVal(input, false, masksets[1] == undefined || firstMaskPos >= pos.end, getActiveBuffer()); if (getActiveMaskSet()['lastValidPosition'] < firstMaskPos) { getActiveMaskSet()["lastValidPosition"] = -1; getActiveMaskSet()["p"] = firstMaskPos; } else { getActiveMaskSet()["p"] = pos.begin; } } function keydownEvent(e) { //Safari 5.1.x - modal dialog fires keypress twice workaround skipKeyPressEvent = false; var input = this, $input = $(input), k = e.keyCode, pos = caret(input); //backspace, delete, and escape get special treatment if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete e.preventDefault(); //stop default action but allow propagation if (k == 88) valueOnFocus = getActiveBuffer().join(''); HandleRemove(input, k, pos); determineActiveMasksetIndex(); writeBuffer(input, getActiveBuffer(), getActiveMaskSet()["p"]); if (input._valueGet() == getActiveBufferTemplate().join('')) $input.trigger('cleared'); if (opts.showTooltip) { //update tooltip $input.prop("title", getActiveMaskSet()["mask"]); } } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch setTimeout(function () { var caretPos = seekNext(getActiveMaskSet()["lastValidPosition"]); if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--; caret(input, e.shiftKey ? pos.begin : caretPos, caretPos); }, 0); } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up caret(input, 0, e.shiftKey ? pos.begin : 0); } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo checkVal(input, true, false, valueOnFocus.split('')); $input.click(); } else if (k == opts.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.insertMode == false && !e.shiftKey) { if (k == opts.keyCode.RIGHT) { setTimeout(function () { var caretPos = caret(input); caret(input, caretPos.begin); }, 0); } else if (k == opts.keyCode.LEFT) { setTimeout(function () { var caretPos = caret(input); caret(input, caretPos.begin - 1); }, 0); } } var currentCaretPos = caret(input); if (opts.onKeyDown.call(this, e, getActiveBuffer(), opts) === true) //extra stuff to execute on keydown caret(input, currentCaretPos.begin, currentCaretPos.end); ignorable = $.inArray(k, opts.ignorables) != -1; } function keypressEvent(e, checkval, k, writeOut, strict, ndx) { //Safari 5.1.x - modal dialog fires keypress twice workaround if (k == undefined && skipKeyPressEvent) return false; skipKeyPressEvent = true; var input = this, $input = $(input); e = e || window.event; var k = checkval ? k : (e.which || e.charCode || e.keyCode); if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) { return true; } else { if (k) { //special treat the decimal separator if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44; var pos, results, result, c = String.fromCharCode(k); if (checkval) { var pcaret = strict ? ndx : getActiveMaskSet()["lastValidPosition"] + 1; pos = { begin: pcaret, end: pcaret }; } else { pos = caret(input); } //should we clear a possible selection?? var isSlctn = isSelection(pos.begin, pos.end), redetermineLVP = false, initialIndex = activeMasksetIndex; if (isSlctn) { activeMasksetIndex = initialIndex; $.each(masksets, function (ndx, lmnt) { //init undobuffer for recovery when not valid if (typeof (lmnt) == "object") { activeMasksetIndex = ndx; getActiveMaskSet()["undoBuffer"] = getActiveBuffer().join(''); } }); HandleRemove(input, opts.keyCode.DELETE, pos); if (!opts.insertMode) { //preserve some space $.each(masksets, function (ndx, lmnt) { if (typeof (lmnt) == "object") { activeMasksetIndex = ndx; shiftR(pos.begin, getMaskLength()); getActiveMaskSet()["lastValidPosition"] = seekNext(getActiveMaskSet()["lastValidPosition"]); } }); } activeMasksetIndex = initialIndex; //restore index } var radixPosition = getActiveBuffer().join('').indexOf(opts.radixPoint); if (opts.isNumeric && checkval !== true && radixPosition != -1) { if (opts.greedy && pos.begin <= radixPosition) { pos.begin = seekPrevious(pos.begin); pos.end = pos.begin; } else if (c == opts.radixPoint) { pos.begin = radixPosition; pos.end = pos.begin; } } var p = pos.begin; results = isValid(p, c, strict); if (strict === true) results = [{ "activeMasksetIndex": activeMasksetIndex, "result": results }]; var minimalForwardPosition = -1; $.each(results, function (index, result) { activeMasksetIndex = result["activeMasksetIndex"]; getActiveMaskSet()["writeOutBuffer"] = true; var np = result["result"]; if (np !== false) { var refresh = false, buffer = getActiveBuffer(); if (np !== true) { refresh = np["refresh"]; //only rewrite buffer from isValid p = np.pos != undefined ? np.pos : p; //set new position from isValid c = np.c != undefined ? np.c : c; //set new char from isValid } if (refresh !== true) { if (opts.insertMode == true) { var lastUnmaskedPosition = getMaskLength(); var bfrClone = buffer.slice(); while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) { lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(lastUnmaskedPosition); } if (lastUnmaskedPosition >= p) { shiftR(p, getMaskLength(), c); //shift the lvp if needed var lvp = getActiveMaskSet()["lastValidPosition"], nlvp = seekNext(lvp); if (nlvp != getMaskLength() && lvp >= p && (getBufferElement(getActiveBuffer(), nlvp, true) != getPlaceHolder(nlvp))) { getActiveMaskSet()["lastValidPosition"] = nlvp; } } else getActiveMaskSet()["writeOutBuffer"] = false; } else setBufferElement(buffer, p, c, true); if (minimalForwardPosition == -1 || minimalForwardPosition > seekNext(p)) { minimalForwardPosition = seekNext(p); } } else if (!strict) { var nextPos = p < getMaskLength() ? p + 1 : p; if (minimalForwardPosition == -1 || minimalForwardPosition > nextPos) { minimalForwardPosition = nextPos; } } if (minimalForwardPosition > getActiveMaskSet()["p"]) getActiveMaskSet()["p"] = minimalForwardPosition; //needed for checkval strict } }); if (strict !== true) { activeMasksetIndex = initialIndex; determineActiveMasksetIndex(); } if (writeOut !== false) { $.each(results, function (ndx, rslt) { if (rslt["activeMasksetIndex"] == activeMasksetIndex) { result = rslt; return false; } }); if (result != undefined) { var self = this; setTimeout(function () { opts.onKeyValidation.call(self, result["result"], opts); }, 0); if (getActiveMaskSet()["writeOutBuffer"] && result["result"] !== false) { var buffer = getActiveBuffer(); var newCaretPosition; if (checkval) { newCaretPosition = undefined; } else if (opts.numericInput) { if (p > radixPosition) { newCaretPosition = seekPrevious(minimalForwardPosition); } else if (c == opts.radixPoint) { newCaretPosition = minimalForwardPosition - 1; } else newCaretPosition = seekPrevious(minimalForwardPosition - 1); } else { newCaretPosition = minimalForwardPosition; } writeBuffer(input, buffer, newCaretPosition); if (checkval !== true) { setTimeout(function () { //timeout needed for IE if (isComplete(buffer) === true) $input.trigger("complete"); skipInputEvent = true; $input.trigger("input"); }, 0); } } else if (isSlctn) { getActiveMaskSet()["buffer"] = getActiveMaskSet()["undoBuffer"].split(''); } } } if (opts.showTooltip) { //update tooltip $input.prop("title", getActiveMaskSet()["mask"]); } //needed for IE8 and below if (e) e.preventDefault ? e.preventDefault() : e.returnValue = false; } } } function keyupEvent(e) { var $input = $(this), input = this, k = e.keyCode, buffer = getActiveBuffer(); if (androidchrome && k == opts.keyCode.BACKSPACE) { if (chromeValueOnInput == input._valueGet()) keydownEvent.call(this, e); } opts.onKeyUp.call(this, e, buffer, opts); //extra stuff to execute on keyup if (k == opts.keyCode.TAB && opts.showMaskOnFocus) { if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) { buffer = getActiveBufferTemplate().slice(); writeBuffer(input, buffer); caret(input, 0); valueOnFocus = getActiveBuffer().join(''); } else { writeBuffer(input, buffer); if (buffer.join('') == getActiveBufferTemplate().join('') && $.inArray(opts.radixPoint, buffer) != -1) { caret(input, TranslatePosition(0)); $input.click(); } else caret(input, TranslatePosition(0), TranslatePosition(getMaskLength())); } } } function inputEvent(e) { if (skipInputEvent === true) { skipInputEvent = false; return true; } var input = this, $input = $(input); chromeValueOnInput = getActiveBuffer().join(''); checkVal(input, false, false); writeBuffer(input, getActiveBuffer()); if (isComplete(getActiveBuffer()) === true) $input.trigger("complete"); $input.click(); } function mask(el) { $el = $(el); if ($el.is(":input")) { //store tests & original buffer in the input element - used to get the unmasked value $el.data('_inputmask', { 'masksets': masksets, 'activeMasksetIndex': activeMasksetIndex, 'opts': opts, 'isRTL': false }); //show tooltip if (opts.showTooltip) { $el.prop("title", getActiveMaskSet()["mask"]); } //correct greedy setting if needed getActiveMaskSet()['greedy'] = getActiveMaskSet()['greedy'] ? getActiveMaskSet()['greedy'] : getActiveMaskSet()['repeat'] == 0; //handle maxlength attribute if ($el.attr("maxLength") != null) //only when the attribute is set { var maxLength = $el.prop('maxLength'); if (maxLength > -1) { //handle *-repeat $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { if (ms["repeat"] == "*") { ms["repeat"] = maxLength; } } }); } if (getMaskLength() >= maxLength && maxLength > -1) { //FF sets no defined max length to -1 if (maxLength < getActiveBufferTemplate().length) getActiveBufferTemplate().length = maxLength; if (getActiveMaskSet()['greedy'] == false) { getActiveMaskSet()['repeat'] = Math.round(maxLength / getActiveBufferTemplate().length); } $el.prop('maxLength', getMaskLength() * 2); } } patchValueProperty(el); if (opts.numericInput) opts.isNumeric = opts.numericInput; if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics)) $el.css("text-align", "right"); if (el.dir == "rtl" || opts.numericInput) { el.dir = "ltr"; $el.removeAttr("dir"); var inputData = $el.data('_inputmask'); inputData['isRTL'] = true; $el.data('_inputmask', inputData); isRTL = true; } //unbind all events - to make sure that no other mask will interfere when re-masking $el.unbind(".inputmask"); $el.removeClass('focus.inputmask'); //bind events $el.closest('form').bind("submit", function () { //trigger change on submit if any if (valueOnFocus != getActiveBuffer().join('')) { $el.change(); } }).bind('reset', function () { setTimeout(function () { $el.trigger("setvalue"); }, 0); }); $el.bind("mouseenter.inputmask", function () { var $input = $(this), input = this; if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) { if (input._valueGet() != getActiveBuffer().join('')) { writeBuffer(input, getActiveBuffer()); } } }).bind("blur.inputmask", function () { var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getActiveBuffer(); $input.removeClass('focus.inputmask'); if (valueOnFocus != getActiveBuffer().join('')) { $input.change(); } if (opts.clearMaskOnLostFocus && nptValue != '') { if (nptValue == getActiveBufferTemplate().join('')) input._valueSet(''); else { //clearout optional tail of the mask clearOptionalTail(input); } } if (isComplete(buffer) === false) { $input.trigger("incomplete"); if (opts.clearIncomplete) { $.each(masksets, function (ndx, ms) { if (typeof (ms) == "object") { ms["buffer"] = ms["_buffer"].slice(); ms["lastValidPosition"] = -1; } }); activeMasksetIndex = 0; if (opts.clearMaskOnLostFocus) input._valueSet(''); else { buffer = getActiveBufferTemplate().slice(); writeBuffer(input, buffer); } } } }).bind("focus.inputmask", function () { var $input = $(this), input = this, nptValue = input._valueGet(); if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) { if (input._valueGet() != getActiveBuffer().join('')) { writeBuffer(input, getActiveBuffer(), seekNext(getActiveMaskSet()["lastValidPosition"])); } } $input.addClass('focus.inputmask'); valueOnFocus = getActiveBuffer().join(''); }).bind("mouseleave.inputmask", function () { var $input = $(this), input = this; if (opts.clearMaskOnLostFocus) { if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) { if (input._valueGet() == getActiveBufferTemplate().join('') || input._valueGet() == '') input._valueSet(''); else { //clearout optional tail of the mask clearOptionalTail(input); } } } }).bind("click.inputmask", function () { var input = this; setTimeout(function () { var selectedCaret = caret(input), buffer = getActiveBuffer(); if (selectedCaret.begin == selectedCaret.end) { var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin, lvp = getActiveMaskSet()["lastValidPosition"], lastPosition; if (opts.isNumeric) { lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ? (opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) : seekNext(lvp); } else { lastPosition = seekNext(lvp); } if (clickPosition < lastPosition) { if (isMask(clickPosition)) caret(input, clickPosition); else caret(input, seekNext(clickPosition)); } else caret(input, lastPosition); } }, 0); }).bind('dblclick.inputmask', function () { var input = this; setTimeout(function () { caret(input, 0, seekNext(getActiveMaskSet()["lastValidPosition"])); }, 0); }).bind(pasteEvent + ".inputmask dragdrop.inputmask drop.inputmask", function (e) { if (skipInputEvent === true) { skipInputEvent = false; return true; } var input = this, $input = $(input); //paste event for IE8 and lower I guess ;-) if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) { return true; } setTimeout(function () { var pasteValue = opts.onBeforePaste != undefined ? opts.onBeforePaste.call(this, input._valueGet()) : input._valueGet(); checkVal(input, true, false, pasteValue.split(''), true); if (isComplete(getActiveBuffer()) === true) $input.trigger("complete"); $input.click(); }, 0); }).bind('setvalue.inputmask', function () { var input = this; checkVal(input, true); valueOnFocus = getActiveBuffer().join(''); if (input._valueGet() == getActiveBufferTemplate().join('')) input._valueSet(''); }).bind('complete.inputmask', opts.oncomplete ).bind('incomplete.inputmask', opts.onincomplete ).bind('cleared.inputmask', opts.oncleared ).bind("keyup.inputmask", keyupEvent); if (androidchrome) { $el.bind("input.inputmask", inputEvent); } else { $el.bind("keydown.inputmask", keydownEvent ).bind("keypress.inputmask", keypressEvent); } if (msie10) $el.bind("input.inputmask", inputEvent); //apply mask checkVal(el, true, false); valueOnFocus = getActiveBuffer().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 (activeElement === el) { //position the caret when in focus $el.addClass('focus.inputmask'); caret(el, seekNext(getActiveMaskSet()["lastValidPosition"])); } else if (opts.clearMaskOnLostFocus) { if (getActiveBuffer().join('') == getActiveBufferTemplate().join('')) { el._valueSet(''); } else { clearOptionalTail(el); } } else { writeBuffer(el, getActiveBuffer()); } installEventRuler(el); } } //action object if (actionObj != undefined) { switch (actionObj["action"]) { case "isComplete": return isComplete(actionObj["buffer"]); case "unmaskedvalue": isRTL = actionObj["$input"].data('_inputmask')['isRTL']; return unmaskedvalue(actionObj["$input"], actionObj["skipDatepickerCheck"]); case "mask": mask(actionObj["el"]); break; case "format": $el = $({}); $el.data('_inputmask', { 'masksets': masksets, 'activeMasksetIndex': activeMasksetIndex, 'opts': opts, 'isRTL': opts.numericInput }); if (opts.numericInput) { opts.isNumeric = opts.numericInput; isRTL = true; } checkVal($el, false, false, actionObj["value"].split(''), true); return getActiveBuffer().join(''); } } } $.inputmask = { //options default defaults: { placeholder: "_", optionalmarker: { start: "[", end: "]" }, quantifiermarker: { start: "{", end: "}" }, groupmarker: { start: "(", end: ")" }, escapeChar: "\\", mask: null, 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 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 onKeyUp: $.noop, //override to implement autocomplete on certain keys for example onKeyDown: $.noop, //override to implement autocomplete on certain keys for example onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue => return processedValue onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue 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) //numeric basic properties isNumeric: false, //enable numeric features radixPoint: "", //".", // | "," skipRadixDance: false, //disable radixpoint caret positioning rightAlignNumerics: true, //align numerics to the right //numeric basic properties definitions: { '9': { validator: "[0-9]", cardinality: 1 }, 'a': { validator: "[A-Za-z\u0410-\u044F\u0401\u0451]", cardinality: 1 }, '*': { validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]", cardinality: 1 } }, keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 }, //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], getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) { var calculatedLength = buffer.length; if (!greedy) { if (repeat == "*") { calculatedLength = currentBuffer.length + 1; } else if (repeat > 1) { calculatedLength += (buffer.length * (repeat - 1)); } } return calculatedLength; } }, escapeRegex: function (str) { var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1'); }, format: function (value, options) { var opts = $.extend(true, {}, $.inputmask.defaults, options); resolveAlias(opts.alias, options, opts); return maskScope(generateMaskSets(opts), 0, opts, { "action": "format", "value": value }); } }; $.fn.inputmask = function (fn, options) { var opts = $.extend(true, {}, $.inputmask.defaults, options), masksets, activeMasksetIndex = 0; if (typeof fn === "string") { switch (fn) { case "mask": //resolve possible aliases given by options resolveAlias(opts.alias, options, opts); masksets = generateMaskSets(opts); if (masksets.length == 0) { return this; } return this.each(function () { maskScope($.extend(true, {}, masksets), 0, opts, { "action": "mask", "el": this }); }); case "unmaskedvalue": var $input = $(this), input = this; if ($input.data('_inputmask')) { masksets = $input.data('_inputmask')['masksets']; activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex']; opts = $input.data('_inputmask')['opts']; return maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input }); } else return $input.val(); case "remove": return this.each(function () { var $input = $(this), input = this; if ($input.data('_inputmask')) { masksets = $input.data('_inputmask')['masksets']; activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex']; opts = $input.data('_inputmask')['opts']; //writeout the unmaskedvalue input._valueSet(maskScope(masksets, activeMasksetIndex, opts, { "action": "unmaskedvalue", "$input": $input, "skipDatepickerCheck": true })); //clear data $input.removeData('_inputmask'); //unbind all events $input.unbind(".inputmask"); $input.removeClass('focus.inputmask'); //restore the value property var valueProperty; if (Object.getOwnPropertyDescriptor) valueProperty = Object.getOwnPropertyDescriptor(input, "value"); if (valueProperty && valueProperty.get) { if (input._valueGet) { Object.defineProperty(input, "value", { get: input._valueGet, set: input._valueSet }); } } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) { if (input._valueGet) { input.__defineGetter__("value", input._valueGet); input.__defineSetter__("value", input._valueSet); } } try { //try catch needed for IE7 as it does not supports deleting fns delete input._valueGet; delete input._valueSet; } catch (e) { input._valueGet = undefined; input._valueSet = undefined; } } }); break; case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation if (this.data('_inputmask')) { masksets = this.data('_inputmask')['masksets']; activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex']; return masksets[activeMasksetIndex]['_buffer'].join(''); } else return ""; case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false; case "isComplete": masksets = this.data('_inputmask')['masksets']; activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex']; opts = this.data('_inputmask')['opts']; return maskScope(masksets, activeMasksetIndex, opts, { "action": "isComplete", "buffer": this[0]._valueGet().split('') }); case "getmetadata": //return mask metadata if exists if (this.data('_inputmask')) { masksets = this.data('_inputmask')['masksets']; activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex']; return masksets[activeMasksetIndex]['metadata']; } else return undefined; default: //check if the fn is an alias if (!resolveAlias(fn, options, opts)) { //maybe fn is a mask so we try //set mask opts.mask = fn; } masksets = generateMaskSets(opts); if (masksets.length == 0) { return this; } return this.each(function () { maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this }); }); break; } } else if (typeof fn == "object") { opts = $.extend(true, {}, $.inputmask.defaults, fn); resolveAlias(opts.alias, fn, opts); //resolve aliases masksets = generateMaskSets(opts); if (masksets.length == 0) { return this; } return this.each(function () { maskScope($.extend(true, {}, masksets), activeMasksetIndex, opts, { "action": "mask", "el": this }); }); } else if (fn == undefined) { //look for data-inputmask atribute - the attribute should only contain optipns return this.each(function () { var attrOptions = $(this).attr("data-inputmask"); if (attrOptions && attrOptions != "") { try { attrOptions = attrOptions.replace(new RegExp("'", "g"), '"'); var dataoptions = $.parseJSON("{" + attrOptions + "}"); $.extend(true, dataoptions, options); opts = $.extend(true, {}, $.inputmask.defaults, dataoptions); resolveAlias(opts.alias, dataoptions, opts); opts.alias = undefined; $(this).inputmask(opts); } catch (ex) { } //need a more relax parseJSON } }); } }; } })(jQuery); /*! * Chart.js * http://chartjs.org/ * Version: 1.0.2 * * Copyright 2015 Nick Downie * Released under the MIT license * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md */ (function(){ "use strict"; //Declare root variable - window in the browser, global on the server var root = this, previous = root.Chart; //Occupy the global variable of Chart, and create a simple base class var Chart = function(context){ var chart = this; this.canvas = context.canvas; this.ctx = context; //Variables global to the chart var computeDimension = function(element,dimension) { if (element['offset'+dimension]) { return element['offset'+dimension]; } else { return document.defaultView.getComputedStyle(element).getPropertyValue(dimension); } } var width = this.width = computeDimension(context.canvas,'Width'); var height = this.height = computeDimension(context.canvas,'Height'); // Firefox requires this to work correctly context.canvas.width = width; context.canvas.height = height; var width = this.width = context.canvas.width; var height = this.height = context.canvas.height; this.aspectRatio = this.width / this.height; //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale. helpers.retinaScale(this); return this; }; //Globally expose the defaults to allow for user updating/changing Chart.defaults = { global: { // Boolean - Whether to animate the chart animation: true, // Number - Number of animation steps animationSteps: 60, // String - Animation easing effect animationEasing: "easeOutQuart", // Boolean - If we should show the scale at all showScale: true, // Boolean - If we want to override with a hard coded scale scaleOverride: false, // ** Required if scaleOverride is true ** // Number - The number of steps in a hard coded scale scaleSteps: null, // Number - The value jump in the hard coded scale scaleStepWidth: null, // Number - The scale starting value scaleStartValue: null, // String - Colour of the scale line scaleLineColor: "rgba(0,0,0,.1)", // Number - Pixel width of the scale line scaleLineWidth: 1, // Boolean - Whether to show labels on the scale scaleShowLabels: true, // Interpolated JS string - can access value scaleLabel: "<%=value%>", // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there scaleIntegersOnly: true, // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value scaleBeginAtZero: false, // String - Scale label font declaration for the scale label scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // Number - Scale label font size in pixels scaleFontSize: 12, // String - Scale label font weight style scaleFontStyle: "normal", // String - Scale label font colour scaleFontColor: "#666", // Boolean - whether or not the chart should be responsive and resize when the browser does. responsive: false, // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container maintainAspectRatio: true, // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove showTooltips: true, // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function customTooltips: false, // Array - Array of string names to attach tooltip events tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"], // String - Tooltip background colour tooltipFillColor: "rgba(0,0,0,0.8)", // String - Tooltip label font declaration for the scale label tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // Number - Tooltip label font size in pixels tooltipFontSize: 14, // String - Tooltip font weight style tooltipFontStyle: "normal", // String - Tooltip label font colour tooltipFontColor: "#fff", // String - Tooltip title font declaration for the scale label tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // Number - Tooltip title font size in pixels tooltipTitleFontSize: 14, // String - Tooltip title font weight style tooltipTitleFontStyle: "bold", // String - Tooltip title font colour tooltipTitleFontColor: "#fff", // Number - pixel width of padding around tooltip text tooltipYPadding: 6, // Number - pixel width of padding around tooltip text tooltipXPadding: 6, // Number - Size of the caret on the tooltip tooltipCaretSize: 8, // Number - Pixel radius of the tooltip border tooltipCornerRadius: 6, // Number - Pixel offset from point x to tooltip edge tooltipXOffset: 10, // String - Template string for single tooltips tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>", // String - Template string for single tooltips multiTooltipTemplate: "<%= value %>", // String - Colour behind the legend colour block multiTooltipKeyBackground: '#fff', // Function - Will fire on animation progression. onAnimationProgress: function(){}, // Function - Will fire on animation completion. onAnimationComplete: function(){} } }; //Create a dictionary of chart types, to allow for extension of existing types Chart.types = {}; //Global Chart helpers object for utility methods and classes var helpers = Chart.helpers = {}; //-- Basic js utility methods var each = helpers.each = function(loopable,callback,self){ var additionalArgs = Array.prototype.slice.call(arguments, 3); // Check to see if null or undefined firstly. if (loopable){ if (loopable.length === +loopable.length){ var i; for (i=0; i= 0; i--) { var currentItem = arrayToSearch[i]; if (filterCallback(currentItem)){ return currentItem; } } }, inherits = helpers.inherits = function(extensions){ //Basic javascript inheritance based on the model created in Backbone.js var parent = this; var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); }; var Surrogate = function(){ this.constructor = ChartElement;}; Surrogate.prototype = parent.prototype; ChartElement.prototype = new Surrogate(); ChartElement.extend = inherits; if (extensions) extend(ChartElement.prototype, extensions); ChartElement.__super__ = parent.prototype; return ChartElement; }, noop = helpers.noop = function(){}, uid = helpers.uid = (function(){ var id=0; return function(){ return "chart-" + id++; }; })(), warn = helpers.warn = function(str){ //Method for warning of errors if (window.console && typeof window.console.warn == "function") console.warn(str); }, amd = helpers.amd = (typeof define == 'function' && define.amd), //-- Math methods isNumber = helpers.isNumber = function(n){ return !isNaN(parseFloat(n)) && isFinite(n); }, max = helpers.max = function(array){ return Math.max.apply( Math, array ); }, min = helpers.min = function(array){ return Math.min.apply( Math, array ); }, cap = helpers.cap = function(valueToCap,maxValue,minValue){ if(isNumber(maxValue)) { if( valueToCap > maxValue ) { return maxValue; } } else if(isNumber(minValue)){ if ( valueToCap < minValue ){ return minValue; } } return valueToCap; }, getDecimalPlaces = helpers.getDecimalPlaces = function(num){ if (num%1!==0 && isNumber(num)){ return num.toString().split(".")[1].length; } else { return 0; } }, toRadians = helpers.radians = function(degrees){ return degrees * (Math.PI/180); }, // Gets the angle from vertical upright to the point about a centre. getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){ var distanceFromXCenter = anglePoint.x - centrePoint.x, distanceFromYCenter = anglePoint.y - centrePoint.y, radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter); //If the segment is in the top left quadrant, we need to add another rotation to the angle if (distanceFromXCenter < 0 && distanceFromYCenter < 0){ angle += Math.PI*2; } return { angle: angle, distance: radialDistanceFromCenter }; }, aliasPixel = helpers.aliasPixel = function(pixelWidth){ return (pixelWidth % 2 === 0) ? 0 : 0.5; }, splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){ //Props to Rob Spencer at scaled innovation for his post on splining between points //http://scaledinnovation.com/analytics/splines/aboutSplines.html var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)), d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)), fa=t*d01/(d01+d12),// scaling factor for triangle Ta fb=t*d12/(d01+d12); return { inner : { x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x), y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y) }, outer : { x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x), y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y) } }; }, calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){ return Math.floor(Math.log(val) / Math.LN10); }, calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){ //Set a minimum step of two - a point at the top of the graph, and a point at the base var minSteps = 2, maxSteps = Math.floor(drawingSize/(textSize * 1.5)), skipFitting = (minSteps >= maxSteps); var maxValue = max(valuesArray), minValue = min(valuesArray); // We need some degree of seperation here to calculate the scales if all the values are the same // Adding/minusing 0.5 will give us a range of 1. if (maxValue === minValue){ maxValue += 0.5; // So we don't end up with a graph with a negative start value if we've said always start from zero if (minValue >= 0.5 && !startFromZero){ minValue -= 0.5; } else{ // Make up a whole number above the values maxValue += 0.5; } } var valueRange = Math.abs(maxValue - minValue), rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange), graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude), graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude), graphRange = graphMax - graphMin, stepValue = Math.pow(10, rangeOrderOfMagnitude), numberOfSteps = Math.round(graphRange / stepValue); //If we have more space on the graph we'll use it to give more definition to the data while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) { if(numberOfSteps > maxSteps){ stepValue *=2; numberOfSteps = Math.round(graphRange/stepValue); // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps. if (numberOfSteps % 1 !== 0){ skipFitting = true; } } //We can fit in double the amount of scale points on the scale else{ //If user has declared ints only, and the step value isn't a decimal if (integersOnly && rangeOrderOfMagnitude >= 0){ //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float if(stepValue/2 % 1 === 0){ stepValue /=2; numberOfSteps = Math.round(graphRange/stepValue); } //If it would make it a float break out of the loop else{ break; } } //If the scale doesn't have to be an int, make the scale more granular anyway. else{ stepValue /=2; numberOfSteps = Math.round(graphRange/stepValue); } } } if (skipFitting){ numberOfSteps = minSteps; stepValue = graphRange / numberOfSteps; } return { steps : numberOfSteps, stepValue : stepValue, min : graphMin, max : graphMin + (numberOfSteps * stepValue) }; }, /* jshint ignore:start */ // Blows up jshint errors based on the new Function constructor //Templating methods //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/ template = helpers.template = function(templateString, valuesObject){ // If templateString is function rather than string-template - call the function for valuesObject if(templateString instanceof Function){ return templateString(valuesObject); } var cache = {}; function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');" ); // Provide some basic currying to the user return data ? fn( data ) : fn; } return tmpl(templateString,valuesObject); }, /* jshint ignore:end */ generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){ var labelsArray = new Array(numberOfSteps); if (labelTemplateString){ each(labelsArray,function(val,index){ labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))}); }); } return labelsArray; }, //--Animation methods //Easing functions adapted from Robert Penner's easing equations //http://www.robertpenner.com/easing/ easingEffects = helpers.easingEffects = { linear: function (t) { return t; }, easeInQuad: function (t) { return t * t; }, easeOutQuad: function (t) { return -1 * t * (t - 2); }, easeInOutQuad: function (t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t; return -1 / 2 * ((--t) * (t - 2) - 1); }, easeInCubic: function (t) { return t * t * t; }, easeOutCubic: function (t) { return 1 * ((t = t / 1 - 1) * t * t + 1); }, easeInOutCubic: function (t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t; return 1 / 2 * ((t -= 2) * t * t + 2); }, easeInQuart: function (t) { return t * t * t * t; }, easeOutQuart: function (t) { return -1 * ((t = t / 1 - 1) * t * t * t - 1); }, easeInOutQuart: function (t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t; return -1 / 2 * ((t -= 2) * t * t * t - 2); }, easeInQuint: function (t) { return 1 * (t /= 1) * t * t * t * t; }, easeOutQuint: function (t) { return 1 * ((t = t / 1 - 1) * t * t * t * t + 1); }, easeInOutQuint: function (t) { if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t; return 1 / 2 * ((t -= 2) * t * t * t * t + 2); }, easeInSine: function (t) { return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1; }, easeOutSine: function (t) { return 1 * Math.sin(t / 1 * (Math.PI / 2)); }, easeInOutSine: function (t) { return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1); }, easeInExpo: function (t) { return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1)); }, easeOutExpo: function (t) { return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1); }, easeInOutExpo: function (t) { if (t === 0) return 0; if (t === 1) return 1; if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1)); return 1 / 2 * (-Math.pow(2, -10 * --t) + 2); }, easeInCirc: function (t) { if (t >= 1) return t; return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1); }, easeOutCirc: function (t) { return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t); }, easeInOutCirc: function (t) { if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1); return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1); }, easeInElastic: function (t) { var s = 1.70158; var p = 0; var a = 1; if (t === 0) return 0; if ((t /= 1) == 1) return 1; if (!p) p = 1 * 0.3; if (a < Math.abs(1)) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p)); }, easeOutElastic: function (t) { var s = 1.70158; var p = 0; var a = 1; if (t === 0) return 0; if ((t /= 1) == 1) return 1; if (!p) p = 1 * 0.3; if (a < Math.abs(1)) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1; }, easeInOutElastic: function (t) { var s = 1.70158; var p = 0; var a = 1; if (t === 0) return 0; if ((t /= 1 / 2) == 2) return 1; if (!p) p = 1 * (0.3 * 1.5); if (a < Math.abs(1)) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p)); return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1; }, easeInBack: function (t) { var s = 1.70158; return 1 * (t /= 1) * t * ((s + 1) * t - s); }, easeOutBack: function (t) { var s = 1.70158; return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1); }, easeInOutBack: function (t) { var s = 1.70158; if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)); return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); }, easeInBounce: function (t) { return 1 - easingEffects.easeOutBounce(1 - t); }, easeOutBounce: function (t) { if ((t /= 1) < (1 / 2.75)) { return 1 * (7.5625 * t * t); } else if (t < (2 / 2.75)) { return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75); } else if (t < (2.5 / 2.75)) { return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375); } else { return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375); } }, easeInOutBounce: function (t) { if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5; return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5; } }, //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ requestAnimFrame = helpers.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; })(), cancelAnimFrame = helpers.cancelAnimFrame = (function(){ return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame || function(callback) { return window.clearTimeout(callback, 1000 / 60); }; })(), animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){ var currentStep = 0, easingFunction = easingEffects[easingString] || easingEffects.linear; var animationFrame = function(){ currentStep++; var stepDecimal = currentStep/totalSteps; var easeDecimal = easingFunction(stepDecimal); callback.call(chartInstance,easeDecimal,stepDecimal, currentStep); onProgress.call(chartInstance,easeDecimal,stepDecimal); if (currentStep < totalSteps){ chartInstance.animationFrame = requestAnimFrame(animationFrame); } else{ onComplete.apply(chartInstance); } }; requestAnimFrame(animationFrame); }, //-- DOM methods getRelativePosition = helpers.getRelativePosition = function(evt){ var mouseX, mouseY; var e = evt.originalEvent || evt, canvas = evt.currentTarget || evt.srcElement, boundingRect = canvas.getBoundingClientRect(); if (e.touches){ mouseX = e.touches[0].clientX - boundingRect.left; mouseY = e.touches[0].clientY - boundingRect.top; } else{ mouseX = e.clientX - boundingRect.left; mouseY = e.clientY - boundingRect.top; } return { x : mouseX, y : mouseY }; }, addEvent = helpers.addEvent = function(node,eventType,method){ if (node.addEventListener){ node.addEventListener(eventType,method); } else if (node.attachEvent){ node.attachEvent("on"+eventType, method); } else { node["on"+eventType] = method; } }, removeEvent = helpers.removeEvent = function(node, eventType, handler){ if (node.removeEventListener){ node.removeEventListener(eventType, handler, false); } else if (node.detachEvent){ node.detachEvent("on"+eventType,handler); } else{ node["on" + eventType] = noop; } }, bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){ // Create the events object if it's not already present if (!chartInstance.events) chartInstance.events = {}; each(arrayOfEvents,function(eventName){ chartInstance.events[eventName] = function(){ handler.apply(chartInstance, arguments); }; addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]); }); }, unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) { each(arrayOfEvents, function(handler,eventName){ removeEvent(chartInstance.chart.canvas, eventName, handler); }); }, getMaximumWidth = helpers.getMaximumWidth = function(domNode){ var container = domNode.parentNode; // TODO = check cross browser stuff with this. return container.clientWidth; }, getMaximumHeight = helpers.getMaximumHeight = function(domNode){ var container = domNode.parentNode; // TODO = check cross browser stuff with this. return container.clientHeight; }, getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support retinaScale = helpers.retinaScale = function(chart){ var ctx = chart.ctx, width = chart.canvas.width, height = chart.canvas.height; if (window.devicePixelRatio) { ctx.canvas.style.width = width + "px"; ctx.canvas.style.height = height + "px"; ctx.canvas.height = height * window.devicePixelRatio; ctx.canvas.width = width * window.devicePixelRatio; ctx.scale(window.devicePixelRatio, window.devicePixelRatio); } }, //-- Canvas methods clear = helpers.clear = function(chart){ chart.ctx.clearRect(0,0,chart.width,chart.height); }, fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){ return fontStyle + " " + pixelSize+"px " + fontFamily; }, longestText = helpers.longestText = function(ctx,font,arrayOfStrings){ ctx.font = font; var longest = 0; each(arrayOfStrings,function(string){ var textWidth = ctx.measureText(string).width; longest = (textWidth > longest) ? textWidth : longest; }); return longest; }, drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){ ctx.beginPath(); ctx.moveTo(x + radius, y); ctx.lineTo(x + width - radius, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius); ctx.lineTo(x + width, y + height - radius); ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); ctx.lineTo(x + radius, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - radius); ctx.lineTo(x, y + radius); ctx.quadraticCurveTo(x, y, x + radius, y); ctx.closePath(); }; //Store a reference to each instance - allowing us to globally resize chart instances on window resize. //Destroy method on the chart will remove the instance of the chart from this reference. Chart.instances = {}; Chart.Type = function(data,options,chart){ this.options = options; this.chart = chart; this.id = uid(); //Add the chart instance to the global namespace Chart.instances[this.id] = this; // Initialize is always called when a chart type is created // By default it is a no op, but it should be extended if (options.responsive){ this.resize(); } this.initialize.call(this,data); }; //Core methods that'll be a part of every chart type extend(Chart.Type.prototype,{ initialize : function(){return this;}, clear : function(){ clear(this.chart); return this; }, stop : function(){ // Stops any current animation loop occuring cancelAnimFrame(this.animationFrame); return this; }, resize : function(callback){ this.stop(); var canvas = this.chart.canvas, newWidth = getMaximumWidth(this.chart.canvas), newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas); canvas.width = this.chart.width = newWidth; canvas.height = this.chart.height = newHeight; retinaScale(this.chart); if (typeof callback === "function"){ callback.apply(this, Array.prototype.slice.call(arguments, 1)); } return this; }, reflow : noop, render : function(reflow){ if (reflow){ this.reflow(); } if (this.options.animation && !reflow){ helpers.animationLoop( this.draw, this.options.animationSteps, this.options.animationEasing, this.options.onAnimationProgress, this.options.onAnimationComplete, this ); } else{ this.draw(); this.options.onAnimationComplete.call(this); } return this; }, generateLegend : function(){ return template(this.options.legendTemplate,this); }, destroy : function(){ this.clear(); unbindEvents(this, this.events); var canvas = this.chart.canvas; // Reset canvas height/width attributes starts a fresh with the canvas context canvas.width = this.chart.width; canvas.height = this.chart.height; // < IE9 doesn't support removeProperty if (canvas.style.removeProperty) { canvas.style.removeProperty('width'); canvas.style.removeProperty('height'); } else { canvas.style.removeAttribute('width'); canvas.style.removeAttribute('height'); } delete Chart.instances[this.id]; }, showTooltip : function(ChartElements, forceRedraw){ // Only redraw the chart if we've actually changed what we're hovering on. if (typeof this.activeElements === 'undefined') this.activeElements = []; var isChanged = (function(Elements){ var changed = false; if (Elements.length !== this.activeElements.length){ changed = true; return changed; } each(Elements, function(element, index){ if (element !== this.activeElements[index]){ changed = true; } }, this); return changed; }).call(this, ChartElements); if (!isChanged && !forceRedraw){ return; } else{ this.activeElements = ChartElements; } this.draw(); if(this.options.customTooltips){ this.options.customTooltips(false); } if (ChartElements.length > 0){ // If we have multiple datasets, show a MultiTooltip for all of the data points at that index if (this.datasets && this.datasets.length > 1) { var dataArray, dataIndex; for (var i = this.datasets.length - 1; i >= 0; i--) { dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments; dataIndex = indexOf(dataArray, ChartElements[0]); if (dataIndex !== -1){ break; } } var tooltipLabels = [], tooltipColors = [], medianPosition = (function(index) { // Get all the points at that particular index var Elements = [], dataCollection, xPositions = [], yPositions = [], xMax, yMax, xMin, yMin; helpers.each(this.datasets, function(dataset){ dataCollection = dataset.points || dataset.bars || dataset.segments; if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){ Elements.push(dataCollection[dataIndex]); } }); helpers.each(Elements, function(element) { xPositions.push(element.x); yPositions.push(element.y); //Include any colour information about the element tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element)); tooltipColors.push({ fill: element._saved.fillColor || element.fillColor, stroke: element._saved.strokeColor || element.strokeColor }); }, this); yMin = min(yPositions); yMax = max(yPositions); xMin = min(xPositions); xMax = max(xPositions); return { x: (xMin > this.chart.width/2) ? xMin : xMax, y: (yMin + yMax)/2 }; }).call(this, dataIndex); new Chart.MultiTooltip({ x: medianPosition.x, y: medianPosition.y, xPadding: this.options.tooltipXPadding, yPadding: this.options.tooltipYPadding, xOffset: this.options.tooltipXOffset, fillColor: this.options.tooltipFillColor, textColor: this.options.tooltipFontColor, fontFamily: this.options.tooltipFontFamily, fontStyle: this.options.tooltipFontStyle, fontSize: this.options.tooltipFontSize, titleTextColor: this.options.tooltipTitleFontColor, titleFontFamily: this.options.tooltipTitleFontFamily, titleFontStyle: this.options.tooltipTitleFontStyle, titleFontSize: this.options.tooltipTitleFontSize, cornerRadius: this.options.tooltipCornerRadius, labels: tooltipLabels, legendColors: tooltipColors, legendColorBackground : this.options.multiTooltipKeyBackground, title: ChartElements[0].label, chart: this.chart, ctx: this.chart.ctx, custom: this.options.customTooltips }).draw(); } else { each(ChartElements, function(Element) { var tooltipPosition = Element.tooltipPosition(); new Chart.Tooltip({ x: Math.round(tooltipPosition.x), y: Math.round(tooltipPosition.y), xPadding: this.options.tooltipXPadding, yPadding: this.options.tooltipYPadding, fillColor: this.options.tooltipFillColor, textColor: this.options.tooltipFontColor, fontFamily: this.options.tooltipFontFamily, fontStyle: this.options.tooltipFontStyle, fontSize: this.options.tooltipFontSize, caretHeight: this.options.tooltipCaretSize, cornerRadius: this.options.tooltipCornerRadius, text: template(this.options.tooltipTemplate, Element), chart: this.chart, custom: this.options.customTooltips }).draw(); }, this); } } return this; }, toBase64Image : function(){ return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments); } }); Chart.Type.extend = function(extensions){ var parent = this; var ChartType = function(){ return parent.apply(this,arguments); }; //Copy the prototype object of the this class ChartType.prototype = clone(parent.prototype); //Now overwrite some of the properties in the base class with the new extensions extend(ChartType.prototype, extensions); ChartType.extend = Chart.Type.extend; if (extensions.name || parent.prototype.name){ var chartName = extensions.name || parent.prototype.name; //Assign any potential default values of the new chart type //If none are defined, we'll use a clone of the chart type this is being extended from. //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart //doesn't define some defaults of their own. var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {}; Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults); Chart.types[chartName] = ChartType; //Register this new chart type in the Chart prototype Chart.prototype[chartName] = function(data,options){ var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {}); return new ChartType(data,config,this); }; } else{ warn("Name not provided for this chart, so it hasn't been registered"); } return parent; }; Chart.Element = function(configuration){ extend(this,configuration); this.initialize.apply(this,arguments); this.save(); }; extend(Chart.Element.prototype,{ initialize : function(){}, restore : function(props){ if (!props){ extend(this,this._saved); } else { each(props,function(key){ this[key] = this._saved[key]; },this); } return this; }, save : function(){ this._saved = clone(this); delete this._saved._saved; return this; }, update : function(newProps){ each(newProps,function(value,key){ this._saved[key] = this[key]; this[key] = value; },this); return this; }, transition : function(props,ease){ each(props,function(value,key){ this[key] = ((value - this._saved[key]) * ease) + this._saved[key]; },this); return this; }, tooltipPosition : function(){ return { x : this.x, y : this.y }; }, hasValue: function(){ return isNumber(this.value); } }); Chart.Element.extend = inherits; Chart.Point = Chart.Element.extend({ display: true, inRange: function(chartX,chartY){ var hitDetectionRange = this.hitDetectionRadius + this.radius; return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2)); }, draw : function(){ if (this.display){ var ctx = this.ctx; ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2); ctx.closePath(); ctx.strokeStyle = this.strokeColor; ctx.lineWidth = this.strokeWidth; ctx.fillStyle = this.fillColor; ctx.fill(); ctx.stroke(); } //Quick debug for bezier curve splining //Highlights control points and the line between them. //Handy for dev - stripped in the min version. // ctx.save(); // ctx.fillStyle = "black"; // ctx.strokeStyle = "black" // ctx.beginPath(); // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2); // ctx.fill(); // ctx.beginPath(); // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2); // ctx.fill(); // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y); // ctx.lineTo(this.x, this.y); // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y); // ctx.stroke(); // ctx.restore(); } }); Chart.Arc = Chart.Element.extend({ inRange : function(chartX,chartY){ var pointRelativePosition = helpers.getAngleFromPoint(this, { x: chartX, y: chartY }); //Check if within the range of the open/close angle var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle), withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius); return (betweenAngles && withinRadius); //Ensure within the outside of the arc centre, but inside arc outer }, tooltipPosition : function(){ var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2), rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius; return { x : this.x + (Math.cos(centreAngle) * rangeFromCentre), y : this.y + (Math.sin(centreAngle) * rangeFromCentre) }; }, draw : function(animationPercent){ var easingDecimal = animationPercent || 1; var ctx = this.ctx; ctx.beginPath(); ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle); ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true); ctx.closePath(); ctx.strokeStyle = this.strokeColor; ctx.lineWidth = this.strokeWidth; ctx.fillStyle = this.fillColor; ctx.fill(); ctx.lineJoin = 'bevel'; if (this.showStroke){ ctx.stroke(); } } }); Chart.Rectangle = Chart.Element.extend({ draw : function(){ var ctx = this.ctx, halfWidth = this.width/2, leftX = this.x - halfWidth, rightX = this.x + halfWidth, top = this.base - (this.base - this.y), halfStroke = this.strokeWidth / 2; // Canvas doesn't allow us to stroke inside the width so we can // adjust the sizes to fit if we're setting a stroke on the line if (this.showStroke){ leftX += halfStroke; rightX -= halfStroke; top += halfStroke; } ctx.beginPath(); ctx.fillStyle = this.fillColor; ctx.strokeStyle = this.strokeColor; ctx.lineWidth = this.strokeWidth; // It'd be nice to keep this class totally generic to any rectangle // and simply specify which border to miss out. ctx.moveTo(leftX, this.base); ctx.lineTo(leftX, top); ctx.lineTo(rightX, top); ctx.lineTo(rightX, this.base); ctx.fill(); if (this.showStroke){ ctx.stroke(); } }, height : function(){ return this.base - this.y; }, inRange : function(chartX,chartY){ return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base); } }); Chart.Tooltip = Chart.Element.extend({ draw : function(){ var ctx = this.chart.ctx; ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily); this.xAlign = "center"; this.yAlign = "above"; //Distance between the actual element.y position and the start of the tooltip caret var caretPadding = this.caretPadding = 2; var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding, tooltipRectHeight = this.fontSize + 2*this.yPadding, tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding; if (this.x + tooltipWidth/2 >this.chart.width){ this.xAlign = "left"; } else if (this.x - tooltipWidth/2 < 0){ this.xAlign = "right"; } if (this.y - tooltipHeight < 0){ this.yAlign = "below"; } var tooltipX = this.x - tooltipWidth/2, tooltipY = this.y - tooltipHeight; ctx.fillStyle = this.fillColor; // Custom Tooltips if(this.custom){ this.custom(this); } else{ switch(this.yAlign) { case "above": //Draw a caret above the x/y ctx.beginPath(); ctx.moveTo(this.x,this.y - caretPadding); ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight)); ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight)); ctx.closePath(); ctx.fill(); break; case "below": tooltipY = this.y + caretPadding + this.caretHeight; //Draw a caret below the x/y ctx.beginPath(); ctx.moveTo(this.x, this.y + caretPadding); ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight); ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight); ctx.closePath(); ctx.fill(); break; } switch(this.xAlign) { case "left": tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight); break; case "right": tooltipX = this.x - (this.cornerRadius + this.caretHeight); break; } drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius); ctx.fill(); ctx.fillStyle = this.textColor; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2); } } }); Chart.MultiTooltip = Chart.Element.extend({ initialize : function(){ this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily); this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily); this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5; this.ctx.font = this.titleFont; var titleWidth = this.ctx.measureText(this.title).width, //Label has a legend square as well so account for this. labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3, longestTextWidth = max([labelWidth,titleWidth]); this.width = longestTextWidth + (this.xPadding*2); var halfHeight = this.height/2; //Check to ensure the height will fit on the canvas if (this.y - halfHeight < 0 ){ this.y = halfHeight; } else if (this.y + halfHeight > this.chart.height){ this.y = this.chart.height - halfHeight; } //Decide whether to align left or right based on position on canvas if (this.x > this.chart.width/2){ this.x -= this.xOffset + this.width; } else { this.x += this.xOffset; } }, getLineHeight : function(index){ var baseLineHeight = this.y - (this.height/2) + this.yPadding, afterTitleIndex = index-1; //If the index is zero, we're getting the title if (index === 0){ return baseLineHeight + this.titleFontSize/2; } else{ return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5; } }, draw : function(){ // Custom Tooltips if(this.custom){ this.custom(this); } else{ drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius); var ctx = this.ctx; ctx.fillStyle = this.fillColor; ctx.fill(); ctx.closePath(); ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillStyle = this.titleTextColor; ctx.font = this.titleFont; ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0)); ctx.font = this.font; helpers.each(this.labels,function(label,index){ ctx.fillStyle = this.textColor; ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1)); //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas) //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize); //Instead we'll make a white filled block to put the legendColour palette over. ctx.fillStyle = this.legendColorBackground; ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize); ctx.fillStyle = this.legendColors[index].fill; ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize); },this); } } }); Chart.Scale = Chart.Element.extend({ initialize : function(){ this.fit(); }, buildYLabels : function(){ this.yLabels = []; var stepDecimalPlaces = getDecimalPlaces(this.stepValue); for (var i=0; i<=this.steps; i++){ this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)})); } this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0; }, addXLabel : function(label){ this.xLabels.push(label); this.valuesCount++; this.fit(); }, removeXLabel : function(){ this.xLabels.shift(); this.valuesCount--; this.fit(); }, // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use fit: function(){ // First we need the width of the yLabels, assuming the xLabels aren't rotated // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation this.startPoint = (this.display) ? this.fontSize : 0; this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels // Apply padding settings to the start and end point. this.startPoint += this.padding; this.endPoint -= this.padding; // Cache the starting height, so can determine if we need to recalculate the scale yAxis var cachedHeight = this.endPoint - this.startPoint, cachedYLabelWidth; // Build the current yLabels so we have an idea of what size they'll be to start /* * This sets what is returned from calculateScaleRange as static properties of this class: * this.steps; this.stepValue; this.min; this.max; * */ this.calculateYRange(cachedHeight); // With these properties set we can now build the array of yLabels // and also the width of the largest yLabel this.buildYLabels(); this.calculateXLabelRotation(); while((cachedHeight > this.endPoint - this.startPoint)){ cachedHeight = this.endPoint - this.startPoint; cachedYLabelWidth = this.yLabelWidth; this.calculateYRange(cachedHeight); this.buildYLabels(); // Only go through the xLabel loop again if the yLabel width has changed if (cachedYLabelWidth < this.yLabelWidth){ this.calculateXLabelRotation(); } } }, calculateXLabelRotation : function(){ //Get the width of each grid by calculating the difference //between x offsets between 0 and 1. this.ctx.font = this.font; var firstWidth = this.ctx.measureText(this.xLabels[0]).width, lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width, firstRotated, lastRotated; this.xScalePaddingRight = lastWidth/2 + 3; this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10; this.xLabelRotation = 0; if (this.display){ var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels), cosRotation, firstRotatedWidth; this.xLabelWidth = originalLabelWidth; //Allow 3 pixels x2 padding either side for label readability var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6; //Max label rotate should be 90 - also act as a loop counter while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){ cosRotation = Math.cos(toRadians(this.xLabelRotation)); firstRotated = cosRotation * firstWidth; lastRotated = cosRotation * lastWidth; // We're right aligning the text now. if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){ this.xScalePaddingLeft = firstRotated + this.fontSize / 2; } this.xScalePaddingRight = this.fontSize/2; this.xLabelRotation++; this.xLabelWidth = cosRotation * originalLabelWidth; } if (this.xLabelRotation > 0){ this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3; } } else{ this.xLabelWidth = 0; this.xScalePaddingRight = this.padding; this.xScalePaddingLeft = this.padding; } }, // Needs to be overidden in each Chart type // Otherwise we need to pass all the data into the scale class calculateYRange: noop, drawingArea: function(){ return this.startPoint - this.endPoint; }, calculateY : function(value){ var scalingFactor = this.drawingArea() / (this.min - this.max); return this.endPoint - (scalingFactor * (value - this.min)); }, calculateX : function(index){ var isRotated = (this.xLabelRotation > 0), // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding, innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight), valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1), valueOffset = (valueWidth * index) + this.xScalePaddingLeft; if (this.offsetGridLines){ valueOffset += (valueWidth/2); } return Math.round(valueOffset); }, update : function(newProps){ helpers.extend(this, newProps); this.fit(); }, draw : function(){ var ctx = this.ctx, yLabelGap = (this.endPoint - this.startPoint) / this.steps, xStart = Math.round(this.xScalePaddingLeft); if (this.display){ ctx.fillStyle = this.textColor; ctx.font = this.font; each(this.yLabels,function(labelString,index){ var yLabelCenter = this.endPoint - (yLabelGap * index), linePositionY = Math.round(yLabelCenter), drawHorizontalLine = this.showHorizontalLines; ctx.textAlign = "right"; ctx.textBaseline = "middle"; if (this.showLabels){ ctx.fillText(labelString,xStart - 10,yLabelCenter); } // This is X axis, so draw it if (index === 0 && !drawHorizontalLine){ drawHorizontalLine = true; } if (drawHorizontalLine){ ctx.beginPath(); } if (index > 0){ // This is a grid line in the centre, so drop that ctx.lineWidth = this.gridLineWidth; ctx.strokeStyle = this.gridLineColor; } else { // This is the first line on the scale ctx.lineWidth = this.lineWidth; ctx.strokeStyle = this.lineColor; } linePositionY += helpers.aliasPixel(ctx.lineWidth); if(drawHorizontalLine){ ctx.moveTo(xStart, linePositionY); ctx.lineTo(this.width, linePositionY); ctx.stroke(); ctx.closePath(); } ctx.lineWidth = this.lineWidth; ctx.strokeStyle = this.lineColor; ctx.beginPath(); ctx.moveTo(xStart - 5, linePositionY); ctx.lineTo(xStart, linePositionY); ctx.stroke(); ctx.closePath(); },this); each(this.xLabels,function(label,index){ var xPos = this.calculateX(index) + aliasPixel(this.lineWidth), // Check to see if line/bar here and decide where to place the line linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth), isRotated = (this.xLabelRotation > 0), drawVerticalLine = this.showVerticalLines; // This is Y axis, so draw it if (index === 0 && !drawVerticalLine){ drawVerticalLine = true; } if (drawVerticalLine){ ctx.beginPath(); } if (index > 0){ // This is a grid line in the centre, so drop that ctx.lineWidth = this.gridLineWidth; ctx.strokeStyle = this.gridLineColor; } else { // This is the first line on the scale ctx.lineWidth = this.lineWidth; ctx.strokeStyle = this.lineColor; } if (drawVerticalLine){ ctx.moveTo(linePos,this.endPoint); ctx.lineTo(linePos,this.startPoint - 3); ctx.stroke(); ctx.closePath(); } ctx.lineWidth = this.lineWidth; ctx.strokeStyle = this.lineColor; // Small lines at the bottom of the base grid line ctx.beginPath(); ctx.moveTo(linePos,this.endPoint); ctx.lineTo(linePos,this.endPoint + 5); ctx.stroke(); ctx.closePath(); ctx.save(); ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8); ctx.rotate(toRadians(this.xLabelRotation)*-1); ctx.font = this.font; ctx.textAlign = (isRotated) ? "right" : "center"; ctx.textBaseline = (isRotated) ? "middle" : "top"; ctx.fillText(label, 0, 0); ctx.restore(); },this); } } }); Chart.RadialScale = Chart.Element.extend({ initialize: function(){ this.size = min([this.height, this.width]); this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2); }, calculateCenterOffset: function(value){ // Take into account half font size + the yPadding of the top value var scalingFactor = this.drawingArea / (this.max - this.min); return (value - this.min) * scalingFactor; }, update : function(){ if (!this.lineArc){ this.setScaleSize(); } else { this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2); } this.buildYLabels(); }, buildYLabels: function(){ this.yLabels = []; var stepDecimalPlaces = getDecimalPlaces(this.stepValue); for (var i=0; i<=this.steps; i++){ this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)})); } }, getCircumference : function(){ return ((Math.PI*2) / this.valuesCount); }, setScaleSize: function(){ /* * Right, this is really confusing and there is a lot of maths going on here * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 * * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif * * Solution: * * We assume the radius of the polygon is half the size of the canvas at first * at each index we check if the text overlaps. * * Where it does, we store that angle and that index. * * After finding the largest index and angle we calculate how much we need to remove * from the shape radius to move the point inwards by that x. * * We average the left and right distances to get the maximum shape radius that can fit in the box * along with labels. * * Once we have that, we can find the centre point for the chart, by taking the x text protrusion * on each side, removing that from the size, halving it and adding the left x protrusion width. * * This will mean we have a shape fitted to the canvas, as large as it can be with the labels * and position it in the most space efficient manner * * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif */ // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]), pointPosition, i, textWidth, halfTextWidth, furthestRight = this.width, furthestRightIndex, furthestRightAngle, furthestLeft = 0, furthestLeftIndex, furthestLeftAngle, xProtrusionLeft, xProtrusionRight, radiusReductionRight, radiusReductionLeft, maxWidthRadius; this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily); for (i=0;i furthestRight) { furthestRight = pointPosition.x + halfTextWidth; furthestRightIndex = i; } if (pointPosition.x - halfTextWidth < furthestLeft) { furthestLeft = pointPosition.x - halfTextWidth; furthestLeftIndex = i; } } else if (i < this.valuesCount/2) { // Less than half the values means we'll left align the text if (pointPosition.x + textWidth > furthestRight) { furthestRight = pointPosition.x + textWidth; furthestRightIndex = i; } } else if (i > this.valuesCount/2){ // More than half the values means we'll right align the text if (pointPosition.x - textWidth < furthestLeft) { furthestLeft = pointPosition.x - textWidth; furthestLeftIndex = i; } } } xProtrusionLeft = furthestLeft; xProtrusionRight = Math.ceil(furthestRight - this.width); furthestRightAngle = this.getIndexAngle(furthestRightIndex); furthestLeftAngle = this.getIndexAngle(furthestLeftIndex); radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2); radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2); // Ensure we actually need to reduce the size of the chart radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0; radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0; this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2; //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2]) this.setCenterPoint(radiusReductionLeft, radiusReductionRight); }, setCenterPoint: function(leftMovement, rightMovement){ var maxRight = this.width - rightMovement - this.drawingArea, maxLeft = leftMovement + this.drawingArea; this.xCenter = (maxLeft + maxRight)/2; // Always vertically in the centre as the text height doesn't change this.yCenter = (this.height/2); }, getIndexAngle : function(index){ var angleMultiplier = (Math.PI * 2) / this.valuesCount; // Start from the top instead of right, so remove a quarter of the circle return index * angleMultiplier - (Math.PI/2); }, getPointPosition : function(index, distanceFromCenter){ var thisAngle = this.getIndexAngle(index); return { x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter, y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter }; }, draw: function(){ if (this.display){ var ctx = this.ctx; each(this.yLabels, function(label, index){ // Don't draw a centre value if (index > 0){ var yCenterOffset = index * (this.drawingArea/this.steps), yHeight = this.yCenter - yCenterOffset, pointPosition; // Draw circular lines around the scale if (this.lineWidth > 0){ ctx.strokeStyle = this.lineColor; ctx.lineWidth = this.lineWidth; if(this.lineArc){ ctx.beginPath(); ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2); ctx.closePath(); ctx.stroke(); } else{ ctx.beginPath(); for (var i=0;i= 0; i--) { if (this.angleLineWidth > 0){ var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max)); ctx.beginPath(); ctx.moveTo(this.xCenter, this.yCenter); ctx.lineTo(outerPosition.x, outerPosition.y); ctx.stroke(); ctx.closePath(); } // Extra 3px out for some label spacing var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5); ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily); ctx.fillStyle = this.pointLabelFontColor; var labelsCount = this.labels.length, halfLabelsCount = this.labels.length/2, quarterLabelsCount = halfLabelsCount/2, upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount), exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount); if (i === 0){ ctx.textAlign = 'center'; } else if(i === halfLabelsCount){ ctx.textAlign = 'center'; } else if (i < halfLabelsCount){ ctx.textAlign = 'left'; } else { ctx.textAlign = 'right'; } // Set the correct text baseline based on outer positioning if (exactQuarter){ ctx.textBaseline = 'middle'; } else if (upperHalf){ ctx.textBaseline = 'bottom'; } else { ctx.textBaseline = 'top'; } ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y); } } } } }); // Attach global event to resize each chart instance when the browser resizes helpers.addEvent(window, "resize", (function(){ // Basic debounce of resize function so it doesn't hurt performance when resizing browser. var timeout; return function(){ clearTimeout(timeout); timeout = setTimeout(function(){ each(Chart.instances,function(instance){ // If the responsive flag is set in the chart instance config // Cascade the resize event down to the chart. if (instance.options.responsive){ instance.resize(instance.render, true); } }); }, 50); }; })()); if (amd) { define(function(){ return Chart; }); } else if (typeof module === 'object' && module.exports) { module.exports = Chart; } root.Chart = Chart; Chart.noConflict = function(){ root.Chart = previous; return Chart; }; }).call(this); (function(){ "use strict"; var root = this, Chart = root.Chart, helpers = Chart.helpers; var defaultConfig = { //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value scaleBeginAtZero : true, //Boolean - Whether grid lines are shown across the chart scaleShowGridLines : true, //String - Colour of the grid lines scaleGridLineColor : "rgba(0,0,0,.05)", //Number - Width of the grid lines scaleGridLineWidth : 1, //Boolean - Whether to show horizontal lines (except X axis) scaleShowHorizontalLines: true, //Boolean - Whether to show vertical lines (except Y axis) scaleShowVerticalLines: true, //Boolean - If there is a stroke on each bar barShowStroke : true, //Number - Pixel width of the bar stroke barStrokeWidth : 2, //Number - Spacing between each of the X value sets barValueSpacing : 5, //Number - Spacing between data sets within X values barDatasetSpacing : 1, //String - A legend template legendTemplate : "
      -legend\"><% for (var i=0; i
    • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
    • <%}%>
    " }; Chart.Type.extend({ name: "Bar", defaults : defaultConfig, initialize: function(data){ //Expose options as a scope variable here so we can access it in the ScaleClass var options = this.options; this.ScaleClass = Chart.Scale.extend({ offsetGridLines : true, calculateBarX : function(datasetCount, datasetIndex, barIndex){ //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar var xWidth = this.calculateBaseWidth(), xAbsolute = this.calculateX(barIndex) - (xWidth/2), barWidth = this.calculateBarWidth(datasetCount); return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2; }, calculateBaseWidth : function(){ return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing); }, calculateBarWidth : function(datasetCount){ //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing); return (baseWidth / datasetCount); } }); this.datasets = []; //Set up tooltip events on the chart if (this.options.showTooltips){ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){ var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : []; this.eachBars(function(bar){ bar.restore(['fillColor', 'strokeColor']); }); helpers.each(activeBars, function(activeBar){ activeBar.fillColor = activeBar.highlightFill; activeBar.strokeColor = activeBar.highlightStroke; }); this.showTooltip(activeBars); }); } //Declare the extension of the default point, to cater for the options passed in to the constructor this.BarClass = Chart.Rectangle.extend({ strokeWidth : this.options.barStrokeWidth, showStroke : this.options.barShowStroke, ctx : this.chart.ctx }); //Iterate through each of the datasets, and build this into a property of the chart helpers.each(data.datasets,function(dataset,datasetIndex){ var datasetObject = { label : dataset.label || null, fillColor : dataset.fillColor, strokeColor : dataset.strokeColor, bars : [] }; this.datasets.push(datasetObject); helpers.each(dataset.data,function(dataPoint,index){ //Add a new point for each piece of data, passing any required data to draw. datasetObject.bars.push(new this.BarClass({ value : dataPoint, label : data.labels[index], datasetLabel: dataset.label, strokeColor : dataset.strokeColor, fillColor : dataset.fillColor, highlightFill : dataset.highlightFill || dataset.fillColor, highlightStroke : dataset.highlightStroke || dataset.strokeColor })); },this); },this); this.buildScale(data.labels); this.BarClass.prototype.base = this.scale.endPoint; this.eachBars(function(bar, index, datasetIndex){ helpers.extend(bar, { width : this.scale.calculateBarWidth(this.datasets.length), x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index), y: this.scale.endPoint }); bar.save(); }, this); this.render(); }, update : function(){ this.scale.update(); // Reset any highlight colours before updating. helpers.each(this.activeElements, function(activeElement){ activeElement.restore(['fillColor', 'strokeColor']); }); this.eachBars(function(bar){ bar.save(); }); this.render(); }, eachBars : function(callback){ helpers.each(this.datasets,function(dataset, datasetIndex){ helpers.each(dataset.bars, callback, this, datasetIndex); },this); }, getBarsAtEvent : function(e){ var barsArray = [], eventPosition = helpers.getRelativePosition(e), datasetIterator = function(dataset){ barsArray.push(dataset.bars[barIndex]); }, barIndex; for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) { for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) { if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){ helpers.each(this.datasets, datasetIterator); return barsArray; } } } return barsArray; }, buildScale : function(labels){ var self = this; var dataTotal = function(){ var values = []; self.eachBars(function(bar){ values.push(bar.value); }); return values; }; var scaleOptions = { templateString : this.options.scaleLabel, height : this.chart.height, width : this.chart.width, ctx : this.chart.ctx, textColor : this.options.scaleFontColor, fontSize : this.options.scaleFontSize, fontStyle : this.options.scaleFontStyle, fontFamily : this.options.scaleFontFamily, valuesCount : labels.length, beginAtZero : this.options.scaleBeginAtZero, integersOnly : this.options.scaleIntegersOnly, calculateYRange: function(currentHeight){ var updatedRanges = helpers.calculateScaleRange( dataTotal(), currentHeight, this.fontSize, this.beginAtZero, this.integersOnly ); helpers.extend(this, updatedRanges); }, xLabels : labels, font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily), lineWidth : this.options.scaleLineWidth, lineColor : this.options.scaleLineColor, showHorizontalLines : this.options.scaleShowHorizontalLines, showVerticalLines : this.options.scaleShowVerticalLines, gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0, gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)", padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0, showLabels : this.options.scaleShowLabels, display : this.options.showScale }; if (this.options.scaleOverride){ helpers.extend(scaleOptions, { calculateYRange: helpers.noop, steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth) }); } this.scale = new this.ScaleClass(scaleOptions); }, addData : function(valuesArray,label){ //Map the values array for each of the datasets helpers.each(valuesArray,function(value,datasetIndex){ //Add a new point for each piece of data, passing any required data to draw. this.datasets[datasetIndex].bars.push(new this.BarClass({ value : value, label : label, x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1), y: this.scale.endPoint, width : this.scale.calculateBarWidth(this.datasets.length), base : this.scale.endPoint, strokeColor : this.datasets[datasetIndex].strokeColor, fillColor : this.datasets[datasetIndex].fillColor })); },this); this.scale.addXLabel(label); //Then re-render the chart. this.update(); }, removeData : function(){ this.scale.removeXLabel(); //Then re-render the chart. helpers.each(this.datasets,function(dataset){ dataset.bars.shift(); },this); this.update(); }, reflow : function(){ helpers.extend(this.BarClass.prototype,{ y: this.scale.endPoint, base : this.scale.endPoint }); var newScaleProps = helpers.extend({ height : this.chart.height, width : this.chart.width }); this.scale.update(newScaleProps); }, draw : function(ease){ var easingDecimal = ease || 1; this.clear(); var ctx = this.chart.ctx; this.scale.draw(easingDecimal); //Draw all the bars for each dataset helpers.each(this.datasets,function(dataset,datasetIndex){ helpers.each(dataset.bars,function(bar,index){ if (bar.hasValue()){ bar.base = this.scale.endPoint; //Transition then draw bar.transition({ x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index), y : this.scale.calculateY(bar.value), width : this.scale.calculateBarWidth(this.datasets.length) }, easingDecimal).draw(); } },this); },this); } }); }).call(this); (function(){ "use strict"; var root = this, Chart = root.Chart, //Cache a local reference to Chart.helpers helpers = Chart.helpers; var defaultConfig = { //Boolean - Whether we should show a stroke on each segment segmentShowStroke : true, //String - The colour of each segment stroke segmentStrokeColor : "#fff", //Number - The width of each segment stroke segmentStrokeWidth : 2, //The percentage of the chart that we cut out of the middle. percentageInnerCutout : 50, //Number - Amount of animation steps animationSteps : 100, //String - Animation easing effect animationEasing : "easeOutBounce", //Boolean - Whether we animate the rotation of the Doughnut animateRotate : true, //Boolean - Whether we animate scaling the Doughnut from the centre animateScale : false, //String - A legend template legendTemplate : "
      -legend\"><% for (var i=0; i
    • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
    • <%}%>
    " }; Chart.Type.extend({ //Passing in a name registers this chart in the Chart namespace name: "Doughnut", //Providing a defaults will also register the deafults in the chart namespace defaults : defaultConfig, //Initialize is fired when the chart is initialized - Data is passed in as a parameter //Config is automatically merged by the core of Chart.js, and is available at this.options initialize: function(data){ //Declare segments as a static property to prevent inheriting across the Chart type prototype this.segments = []; this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2; this.SegmentArc = Chart.Arc.extend({ ctx : this.chart.ctx, x : this.chart.width/2, y : this.chart.height/2 }); //Set up tooltip events on the chart if (this.options.showTooltips){ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){ var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : []; helpers.each(this.segments,function(segment){ segment.restore(["fillColor"]); }); helpers.each(activeSegments,function(activeSegment){ activeSegment.fillColor = activeSegment.highlightColor; }); this.showTooltip(activeSegments); }); } this.calculateTotal(data); helpers.each(data,function(datapoint, index){ this.addData(datapoint, index, true); },this); this.render(); }, getSegmentsAtEvent : function(e){ var segmentsArray = []; var location = helpers.getRelativePosition(e); helpers.each(this.segments,function(segment){ if (segment.inRange(location.x,location.y)) segmentsArray.push(segment); },this); return segmentsArray; }, addData : function(segment, atIndex, silent){ var index = atIndex || this.segments.length; this.segments.splice(index, 0, new this.SegmentArc({ value : segment.value, outerRadius : (this.options.animateScale) ? 0 : this.outerRadius, innerRadius : (this.options.animateScale) ? 0 : (this.outerRadius/100) * this.options.percentageInnerCutout, fillColor : segment.color, highlightColor : segment.highlight || segment.color, showStroke : this.options.segmentShowStroke, strokeWidth : this.options.segmentStrokeWidth, strokeColor : this.options.segmentStrokeColor, startAngle : Math.PI * 1.5, circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value), label : segment.label })); if (!silent){ this.reflow(); this.update(); } }, calculateCircumference : function(value){ return (Math.PI*2)*(Math.abs(value) / this.total); }, calculateTotal : function(data){ this.total = 0; helpers.each(data,function(segment){ this.total += Math.abs(segment.value); },this); }, update : function(){ this.calculateTotal(this.segments); // Reset any highlight colours before updating. helpers.each(this.activeElements, function(activeElement){ activeElement.restore(['fillColor']); }); helpers.each(this.segments,function(segment){ segment.save(); }); this.render(); }, removeData: function(atIndex){ var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1; this.segments.splice(indexToDelete, 1); this.reflow(); this.update(); }, reflow : function(){ helpers.extend(this.SegmentArc.prototype,{ x : this.chart.width/2, y : this.chart.height/2 }); this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2; helpers.each(this.segments, function(segment){ segment.update({ outerRadius : this.outerRadius, innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout }); }, this); }, draw : function(easeDecimal){ var animDecimal = (easeDecimal) ? easeDecimal : 1; this.clear(); helpers.each(this.segments,function(segment,index){ segment.transition({ circumference : this.calculateCircumference(segment.value), outerRadius : this.outerRadius, innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout },animDecimal); segment.endAngle = segment.startAngle + segment.circumference; segment.draw(); if (index === 0){ segment.startAngle = Math.PI * 1.5; } //Check to see if it's the last segment, if not get the next and update the start angle if (index < this.segments.length-1){ this.segments[index+1].startAngle = segment.endAngle; } },this); } }); Chart.types.Doughnut.extend({ name : "Pie", defaults : helpers.merge(defaultConfig,{percentageInnerCutout : 0}) }); }).call(this); (function(){ "use strict"; var root = this, Chart = root.Chart, helpers = Chart.helpers; var defaultConfig = { ///Boolean - Whether grid lines are shown across the chart scaleShowGridLines : true, //String - Colour of the grid lines scaleGridLineColor : "rgba(0,0,0,.05)", //Number - Width of the grid lines scaleGridLineWidth : 1, //Boolean - Whether to show horizontal lines (except X axis) scaleShowHorizontalLines: true, //Boolean - Whether to show vertical lines (except Y axis) scaleShowVerticalLines: true, //Boolean - Whether the line is curved between points bezierCurve : true, //Number - Tension of the bezier curve between points bezierCurveTension : 0.4, //Boolean - Whether to show a dot for each point pointDot : true, //Number - Radius of each point dot in pixels pointDotRadius : 4, //Number - Pixel width of point dot stroke pointDotStrokeWidth : 1, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point pointHitDetectionRadius : 20, //Boolean - Whether to show a stroke for datasets datasetStroke : true, //Number - Pixel width of dataset stroke datasetStrokeWidth : 2, //Boolean - Whether to fill the dataset with a colour datasetFill : true, //String - A legend template legendTemplate : "
      -legend\"><% for (var i=0; i
    • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
    • <%}%>
    " }; Chart.Type.extend({ name: "Line", defaults : defaultConfig, initialize: function(data){ //Declare the extension of the default point, to cater for the options passed in to the constructor this.PointClass = Chart.Point.extend({ strokeWidth : this.options.pointDotStrokeWidth, radius : this.options.pointDotRadius, display: this.options.pointDot, hitDetectionRadius : this.options.pointHitDetectionRadius, ctx : this.chart.ctx, inRange : function(mouseX){ return (Math.pow(mouseX-this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius,2)); } }); this.datasets = []; //Set up tooltip events on the chart if (this.options.showTooltips){ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){ var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : []; this.eachPoints(function(point){ point.restore(['fillColor', 'strokeColor']); }); helpers.each(activePoints, function(activePoint){ activePoint.fillColor = activePoint.highlightFill; activePoint.strokeColor = activePoint.highlightStroke; }); this.showTooltip(activePoints); }); } //Iterate through each of the datasets, and build this into a property of the chart helpers.each(data.datasets,function(dataset){ var datasetObject = { label : dataset.label || null, fillColor : dataset.fillColor, strokeColor : dataset.strokeColor, pointColor : dataset.pointColor, pointStrokeColor : dataset.pointStrokeColor, points : [] }; this.datasets.push(datasetObject); helpers.each(dataset.data,function(dataPoint,index){ //Add a new point for each piece of data, passing any required data to draw. datasetObject.points.push(new this.PointClass({ value : dataPoint, label : data.labels[index], datasetLabel: dataset.label, strokeColor : dataset.pointStrokeColor, fillColor : dataset.pointColor, highlightFill : dataset.pointHighlightFill || dataset.pointColor, highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor })); },this); this.buildScale(data.labels); this.eachPoints(function(point, index){ helpers.extend(point, { x: this.scale.calculateX(index), y: this.scale.endPoint }); point.save(); }, this); },this); this.render(); }, update : function(){ this.scale.update(); // Reset any highlight colours before updating. helpers.each(this.activeElements, function(activeElement){ activeElement.restore(['fillColor', 'strokeColor']); }); this.eachPoints(function(point){ point.save(); }); this.render(); }, eachPoints : function(callback){ helpers.each(this.datasets,function(dataset){ helpers.each(dataset.points,callback,this); },this); }, getPointsAtEvent : function(e){ var pointsArray = [], eventPosition = helpers.getRelativePosition(e); helpers.each(this.datasets,function(dataset){ helpers.each(dataset.points,function(point){ if (point.inRange(eventPosition.x,eventPosition.y)) pointsArray.push(point); }); },this); return pointsArray; }, buildScale : function(labels){ var self = this; var dataTotal = function(){ var values = []; self.eachPoints(function(point){ values.push(point.value); }); return values; }; var scaleOptions = { templateString : this.options.scaleLabel, height : this.chart.height, width : this.chart.width, ctx : this.chart.ctx, textColor : this.options.scaleFontColor, fontSize : this.options.scaleFontSize, fontStyle : this.options.scaleFontStyle, fontFamily : this.options.scaleFontFamily, valuesCount : labels.length, beginAtZero : this.options.scaleBeginAtZero, integersOnly : this.options.scaleIntegersOnly, calculateYRange : function(currentHeight){ var updatedRanges = helpers.calculateScaleRange( dataTotal(), currentHeight, this.fontSize, this.beginAtZero, this.integersOnly ); helpers.extend(this, updatedRanges); }, xLabels : labels, font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily), lineWidth : this.options.scaleLineWidth, lineColor : this.options.scaleLineColor, showHorizontalLines : this.options.scaleShowHorizontalLines, showVerticalLines : this.options.scaleShowVerticalLines, gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0, gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)", padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth, showLabels : this.options.scaleShowLabels, display : this.options.showScale }; if (this.options.scaleOverride){ helpers.extend(scaleOptions, { calculateYRange: helpers.noop, steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth) }); } this.scale = new Chart.Scale(scaleOptions); }, addData : function(valuesArray,label){ //Map the values array for each of the datasets helpers.each(valuesArray,function(value,datasetIndex){ //Add a new point for each piece of data, passing any required data to draw. this.datasets[datasetIndex].points.push(new this.PointClass({ value : value, label : label, x: this.scale.calculateX(this.scale.valuesCount+1), y: this.scale.endPoint, strokeColor : this.datasets[datasetIndex].pointStrokeColor, fillColor : this.datasets[datasetIndex].pointColor })); },this); this.scale.addXLabel(label); //Then re-render the chart. this.update(); }, removeData : function(){ this.scale.removeXLabel(); //Then re-render the chart. helpers.each(this.datasets,function(dataset){ dataset.points.shift(); },this); this.update(); }, reflow : function(){ var newScaleProps = helpers.extend({ height : this.chart.height, width : this.chart.width }); this.scale.update(newScaleProps); }, draw : function(ease){ var easingDecimal = ease || 1; this.clear(); var ctx = this.chart.ctx; // Some helper methods for getting the next/prev points var hasValue = function(item){ return item.value !== null; }, nextPoint = function(point, collection, index){ return helpers.findNextWhere(collection, hasValue, index) || point; }, previousPoint = function(point, collection, index){ return helpers.findPreviousWhere(collection, hasValue, index) || point; }; this.scale.draw(easingDecimal); helpers.each(this.datasets,function(dataset){ var pointsWithValues = helpers.where(dataset.points, hasValue); //Transition each point first so that the line and point drawing isn't out of sync //We can use this extra loop to calculate the control points of this dataset also in this loop helpers.each(dataset.points, function(point, index){ if (point.hasValue()){ point.transition({ y : this.scale.calculateY(point.value), x : this.scale.calculateX(index) }, easingDecimal); } },this); // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed if (this.options.bezierCurve){ helpers.each(pointsWithValues, function(point, index){ var tension = (index > 0 && index < pointsWithValues.length - 1) ? this.options.bezierCurveTension : 0; point.controlPoints = helpers.splineCurve( previousPoint(point, pointsWithValues, index), point, nextPoint(point, pointsWithValues, index), tension ); // Prevent the bezier going outside of the bounds of the graph // Cap puter bezier handles to the upper/lower scale bounds if (point.controlPoints.outer.y > this.scale.endPoint){ point.controlPoints.outer.y = this.scale.endPoint; } else if (point.controlPoints.outer.y < this.scale.startPoint){ point.controlPoints.outer.y = this.scale.startPoint; } // Cap inner bezier handles to the upper/lower scale bounds if (point.controlPoints.inner.y > this.scale.endPoint){ point.controlPoints.inner.y = this.scale.endPoint; } else if (point.controlPoints.inner.y < this.scale.startPoint){ point.controlPoints.inner.y = this.scale.startPoint; } },this); } //Draw the line between all the points ctx.lineWidth = this.options.datasetStrokeWidth; ctx.strokeStyle = dataset.strokeColor; ctx.beginPath(); helpers.each(pointsWithValues, function(point, index){ if (index === 0){ ctx.moveTo(point.x, point.y); } else{ if(this.options.bezierCurve){ var previous = previousPoint(point, pointsWithValues, index); ctx.bezierCurveTo( previous.controlPoints.outer.x, previous.controlPoints.outer.y, point.controlPoints.inner.x, point.controlPoints.inner.y, point.x, point.y ); } else{ ctx.lineTo(point.x,point.y); } } }, this); ctx.stroke(); if (this.options.datasetFill && pointsWithValues.length > 0){ //Round off the line by going to the base of the chart, back to the start, then fill. ctx.lineTo(pointsWithValues[pointsWithValues.length - 1].x, this.scale.endPoint); ctx.lineTo(pointsWithValues[0].x, this.scale.endPoint); ctx.fillStyle = dataset.fillColor; ctx.closePath(); ctx.fill(); } //Now draw the points over the line //A little inefficient double looping, but better than the line //lagging behind the point positions helpers.each(pointsWithValues,function(point){ point.draw(); }); },this); } }); }).call(this); (function(){ "use strict"; var root = this, Chart = root.Chart, //Cache a local reference to Chart.helpers helpers = Chart.helpers; var defaultConfig = { //Boolean - Show a backdrop to the scale label scaleShowLabelBackdrop : true, //String - The colour of the label backdrop scaleBackdropColor : "rgba(255,255,255,0.75)", // Boolean - Whether the scale should begin at zero scaleBeginAtZero : true, //Number - The backdrop padding above & below the label in pixels scaleBackdropPaddingY : 2, //Number - The backdrop padding to the side of the label in pixels scaleBackdropPaddingX : 2, //Boolean - Show line for each value in the scale scaleShowLine : true, //Boolean - Stroke a line around each segment in the chart segmentShowStroke : true, //String - The colour of the stroke on each segement. segmentStrokeColor : "#fff", //Number - The width of the stroke value in pixels segmentStrokeWidth : 2, //Number - Amount of animation steps animationSteps : 100, //String - Animation easing effect. animationEasing : "easeOutBounce", //Boolean - Whether to animate the rotation of the chart animateRotate : true, //Boolean - Whether to animate scaling the chart from the centre animateScale : false, //String - A legend template legendTemplate : "
      -legend\"><% for (var i=0; i
    • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
    • <%}%>
    " }; Chart.Type.extend({ //Passing in a name registers this chart in the Chart namespace name: "PolarArea", //Providing a defaults will also register the deafults in the chart namespace defaults : defaultConfig, //Initialize is fired when the chart is initialized - Data is passed in as a parameter //Config is automatically merged by the core of Chart.js, and is available at this.options initialize: function(data){ this.segments = []; //Declare segment class as a chart instance specific class, so it can share props for this instance this.SegmentArc = Chart.Arc.extend({ showStroke : this.options.segmentShowStroke, strokeWidth : this.options.segmentStrokeWidth, strokeColor : this.options.segmentStrokeColor, ctx : this.chart.ctx, innerRadius : 0, x : this.chart.width/2, y : this.chart.height/2 }); this.scale = new Chart.RadialScale({ display: this.options.showScale, fontStyle: this.options.scaleFontStyle, fontSize: this.options.scaleFontSize, fontFamily: this.options.scaleFontFamily, fontColor: this.options.scaleFontColor, showLabels: this.options.scaleShowLabels, showLabelBackdrop: this.options.scaleShowLabelBackdrop, backdropColor: this.options.scaleBackdropColor, backdropPaddingY : this.options.scaleBackdropPaddingY, backdropPaddingX: this.options.scaleBackdropPaddingX, lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0, lineColor: this.options.scaleLineColor, lineArc: true, width: this.chart.width, height: this.chart.height, xCenter: this.chart.width/2, yCenter: this.chart.height/2, ctx : this.chart.ctx, templateString: this.options.scaleLabel, valuesCount: data.length }); this.updateScaleRange(data); this.scale.update(); helpers.each(data,function(segment,index){ this.addData(segment,index,true); },this); //Set up tooltip events on the chart if (this.options.showTooltips){ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){ var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : []; helpers.each(this.segments,function(segment){ segment.restore(["fillColor"]); }); helpers.each(activeSegments,function(activeSegment){ activeSegment.fillColor = activeSegment.highlightColor; }); this.showTooltip(activeSegments); }); } this.render(); }, getSegmentsAtEvent : function(e){ var segmentsArray = []; var location = helpers.getRelativePosition(e); helpers.each(this.segments,function(segment){ if (segment.inRange(location.x,location.y)) segmentsArray.push(segment); },this); return segmentsArray; }, addData : function(segment, atIndex, silent){ var index = atIndex || this.segments.length; this.segments.splice(index, 0, new this.SegmentArc({ fillColor: segment.color, highlightColor: segment.highlight || segment.color, label: segment.label, value: segment.value, outerRadius: (this.options.animateScale) ? 0 : this.scale.calculateCenterOffset(segment.value), circumference: (this.options.animateRotate) ? 0 : this.scale.getCircumference(), startAngle: Math.PI * 1.5 })); if (!silent){ this.reflow(); this.update(); } }, removeData: function(atIndex){ var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1; this.segments.splice(indexToDelete, 1); this.reflow(); this.update(); }, calculateTotal: function(data){ this.total = 0; helpers.each(data,function(segment){ this.total += segment.value; },this); this.scale.valuesCount = this.segments.length; }, updateScaleRange: function(datapoints){ var valuesArray = []; helpers.each(datapoints,function(segment){ valuesArray.push(segment.value); }); var scaleSizes = (this.options.scaleOverride) ? { steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth) } : helpers.calculateScaleRange( valuesArray, helpers.min([this.chart.width, this.chart.height])/2, this.options.scaleFontSize, this.options.scaleBeginAtZero, this.options.scaleIntegersOnly ); helpers.extend( this.scale, scaleSizes, { size: helpers.min([this.chart.width, this.chart.height]), xCenter: this.chart.width/2, yCenter: this.chart.height/2 } ); }, update : function(){ this.calculateTotal(this.segments); helpers.each(this.segments,function(segment){ segment.save(); }); this.reflow(); this.render(); }, reflow : function(){ helpers.extend(this.SegmentArc.prototype,{ x : this.chart.width/2, y : this.chart.height/2 }); this.updateScaleRange(this.segments); this.scale.update(); helpers.extend(this.scale,{ xCenter: this.chart.width/2, yCenter: this.chart.height/2 }); helpers.each(this.segments, function(segment){ segment.update({ outerRadius : this.scale.calculateCenterOffset(segment.value) }); }, this); }, draw : function(ease){ var easingDecimal = ease || 1; //Clear & draw the canvas this.clear(); helpers.each(this.segments,function(segment, index){ segment.transition({ circumference : this.scale.getCircumference(), outerRadius : this.scale.calculateCenterOffset(segment.value) },easingDecimal); segment.endAngle = segment.startAngle + segment.circumference; // If we've removed the first segment we need to set the first one to // start at the top. if (index === 0){ segment.startAngle = Math.PI * 1.5; } //Check to see if it's the last segment, if not get the next and update the start angle if (index < this.segments.length - 1){ this.segments[index+1].startAngle = segment.endAngle; } segment.draw(); }, this); this.scale.draw(); } }); }).call(this); (function(){ "use strict"; var root = this, Chart = root.Chart, helpers = Chart.helpers; Chart.Type.extend({ name: "Radar", defaults:{ //Boolean - Whether to show lines for each scale point scaleShowLine : true, //Boolean - Whether we show the angle lines out of the radar angleShowLineOut : true, //Boolean - Whether to show labels on the scale scaleShowLabels : false, // Boolean - Whether the scale should begin at zero scaleBeginAtZero : true, //String - Colour of the angle line angleLineColor : "rgba(0,0,0,.1)", //Number - Pixel width of the angle line angleLineWidth : 1, //String - Point label font declaration pointLabelFontFamily : "'Arial'", //String - Point label font weight pointLabelFontStyle : "normal", //Number - Point label font size in pixels pointLabelFontSize : 10, //String - Point label font colour pointLabelFontColor : "#666", //Boolean - Whether to show a dot for each point pointDot : true, //Number - Radius of each point dot in pixels pointDotRadius : 3, //Number - Pixel width of point dot stroke pointDotStrokeWidth : 1, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point pointHitDetectionRadius : 20, //Boolean - Whether to show a stroke for datasets datasetStroke : true, //Number - Pixel width of dataset stroke datasetStrokeWidth : 2, //Boolean - Whether to fill the dataset with a colour datasetFill : true, //String - A legend template legendTemplate : "
      -legend\"><% for (var i=0; i
    • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
    • <%}%>
    " }, initialize: function(data){ this.PointClass = Chart.Point.extend({ strokeWidth : this.options.pointDotStrokeWidth, radius : this.options.pointDotRadius, display: this.options.pointDot, hitDetectionRadius : this.options.pointHitDetectionRadius, ctx : this.chart.ctx }); this.datasets = []; this.buildScale(data); //Set up tooltip events on the chart if (this.options.showTooltips){ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){ var activePointsCollection = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : []; this.eachPoints(function(point){ point.restore(['fillColor', 'strokeColor']); }); helpers.each(activePointsCollection, function(activePoint){ activePoint.fillColor = activePoint.highlightFill; activePoint.strokeColor = activePoint.highlightStroke; }); this.showTooltip(activePointsCollection); }); } //Iterate through each of the datasets, and build this into a property of the chart helpers.each(data.datasets,function(dataset){ var datasetObject = { label: dataset.label || null, fillColor : dataset.fillColor, strokeColor : dataset.strokeColor, pointColor : dataset.pointColor, pointStrokeColor : dataset.pointStrokeColor, points : [] }; this.datasets.push(datasetObject); helpers.each(dataset.data,function(dataPoint,index){ //Add a new point for each piece of data, passing any required data to draw. var pointPosition; if (!this.scale.animation){ pointPosition = this.scale.getPointPosition(index, this.scale.calculateCenterOffset(dataPoint)); } datasetObject.points.push(new this.PointClass({ value : dataPoint, label : data.labels[index], datasetLabel: dataset.label, x: (this.options.animation) ? this.scale.xCenter : pointPosition.x, y: (this.options.animation) ? this.scale.yCenter : pointPosition.y, strokeColor : dataset.pointStrokeColor, fillColor : dataset.pointColor, highlightFill : dataset.pointHighlightFill || dataset.pointColor, highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor })); },this); },this); this.render(); }, eachPoints : function(callback){ helpers.each(this.datasets,function(dataset){ helpers.each(dataset.points,callback,this); },this); }, getPointsAtEvent : function(evt){ var mousePosition = helpers.getRelativePosition(evt), fromCenter = helpers.getAngleFromPoint({ x: this.scale.xCenter, y: this.scale.yCenter }, mousePosition); var anglePerIndex = (Math.PI * 2) /this.scale.valuesCount, pointIndex = Math.round((fromCenter.angle - Math.PI * 1.5) / anglePerIndex), activePointsCollection = []; // If we're at the top, make the pointIndex 0 to get the first of the array. if (pointIndex >= this.scale.valuesCount || pointIndex < 0){ pointIndex = 0; } if (fromCenter.distance <= this.scale.drawingArea){ helpers.each(this.datasets, function(dataset){ activePointsCollection.push(dataset.points[pointIndex]); }); } return activePointsCollection; }, buildScale : function(data){ this.scale = new Chart.RadialScale({ display: this.options.showScale, fontStyle: this.options.scaleFontStyle, fontSize: this.options.scaleFontSize, fontFamily: this.options.scaleFontFamily, fontColor: this.options.scaleFontColor, showLabels: this.options.scaleShowLabels, showLabelBackdrop: this.options.scaleShowLabelBackdrop, backdropColor: this.options.scaleBackdropColor, backdropPaddingY : this.options.scaleBackdropPaddingY, backdropPaddingX: this.options.scaleBackdropPaddingX, lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0, lineColor: this.options.scaleLineColor, angleLineColor : this.options.angleLineColor, angleLineWidth : (this.options.angleShowLineOut) ? this.options.angleLineWidth : 0, // Point labels at the edge of each line pointLabelFontColor : this.options.pointLabelFontColor, pointLabelFontSize : this.options.pointLabelFontSize, pointLabelFontFamily : this.options.pointLabelFontFamily, pointLabelFontStyle : this.options.pointLabelFontStyle, height : this.chart.height, width: this.chart.width, xCenter: this.chart.width/2, yCenter: this.chart.height/2, ctx : this.chart.ctx, templateString: this.options.scaleLabel, labels: data.labels, valuesCount: data.datasets[0].data.length }); this.scale.setScaleSize(); this.updateScaleRange(data.datasets); this.scale.buildYLabels(); }, updateScaleRange: function(datasets){ var valuesArray = (function(){ var totalDataArray = []; helpers.each(datasets,function(dataset){ if (dataset.data){ totalDataArray = totalDataArray.concat(dataset.data); } else { helpers.each(dataset.points, function(point){ totalDataArray.push(point.value); }); } }); return totalDataArray; })(); var scaleSizes = (this.options.scaleOverride) ? { steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth) } : helpers.calculateScaleRange( valuesArray, helpers.min([this.chart.width, this.chart.height])/2, this.options.scaleFontSize, this.options.scaleBeginAtZero, this.options.scaleIntegersOnly ); helpers.extend( this.scale, scaleSizes ); }, addData : function(valuesArray,label){ //Map the values array for each of the datasets this.scale.valuesCount++; helpers.each(valuesArray,function(value,datasetIndex){ var pointPosition = this.scale.getPointPosition(this.scale.valuesCount, this.scale.calculateCenterOffset(value)); this.datasets[datasetIndex].points.push(new this.PointClass({ value : value, label : label, x: pointPosition.x, y: pointPosition.y, strokeColor : this.datasets[datasetIndex].pointStrokeColor, fillColor : this.datasets[datasetIndex].pointColor })); },this); this.scale.labels.push(label); this.reflow(); this.update(); }, removeData : function(){ this.scale.valuesCount--; this.scale.labels.shift(); helpers.each(this.datasets,function(dataset){ dataset.points.shift(); },this); this.reflow(); this.update(); }, update : function(){ this.eachPoints(function(point){ point.save(); }); this.reflow(); this.render(); }, reflow: function(){ helpers.extend(this.scale, { width : this.chart.width, height: this.chart.height, size : helpers.min([this.chart.width, this.chart.height]), xCenter: this.chart.width/2, yCenter: this.chart.height/2 }); this.updateScaleRange(this.datasets); this.scale.setScaleSize(); this.scale.buildYLabels(); }, draw : function(ease){ var easeDecimal = ease || 1, ctx = this.chart.ctx; this.clear(); this.scale.draw(); helpers.each(this.datasets,function(dataset){ //Transition each point first so that the line and point drawing isn't out of sync helpers.each(dataset.points,function(point,index){ if (point.hasValue()){ point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal); } },this); //Draw the line between all the points ctx.lineWidth = this.options.datasetStrokeWidth; ctx.strokeStyle = dataset.strokeColor; ctx.beginPath(); helpers.each(dataset.points,function(point,index){ if (index === 0){ ctx.moveTo(point.x,point.y); } else{ ctx.lineTo(point.x,point.y); } },this); ctx.closePath(); ctx.stroke(); ctx.fillStyle = dataset.fillColor; ctx.fill(); //Now draw the points over the line //A little inefficient double looping, but better than the line //lagging behind the point positions helpers.each(dataset.points,function(point){ if (point.hasValue()){ point.draw(); } }); },this); } }); }).call(this); /*! * Bootstrap v3.3.4 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.4",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.4",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.4",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.4",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.4",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport),this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-mp.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.4",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.4",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.4",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a(document.body).height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);