window.org=window.org||{};org.apache=org.apache||{};org.apache.myfaces=org.apache.myfaces||{};if(!org.apache.myfaces.Popup){org.apache.myfaces.popupFrameUnder=null;org.apache.myfaces.popupCurrentlyOpenedPopup=null;org.apache.myfaces.Popup=function(A,C,B){this.popupId=A;this.displayAtDistanceX=C;this.displayAtDistanceY=B;this.isIE6=document.all&&!window.opera&&!window.XMLHttpRequest;};org.apache.myfaces.Popup.prototype.display=function(B){if(org.apache.myfaces.popupCurrentlyOpenedPopup!=null){org.apache.myfaces.popupCurrentlyOpenedPopup.style.display="none";}var A;var D;if(window.event){if(org.apache.myfaces.popupFrameUnder!=null){org.apache.myfaces.popupFrameUnder.style.display="none";}A=window.event.clientX;A+=this.popupGetScrollingX();D=window.event.clientY;D+=this.popupGetScrollingY();}else{A=B.pageX;D=B.pageY;}A+=this.displayAtDistanceX;D+=this.displayAtDistanceY;var C=document.getElementById(this.popupId);if(C.style.display!="block"){C.style.display="block";C.style.left=""+A+"px";C.style.top=""+D+"px";org.apache.myfaces.popupCurrentlyOpenedPopup=C;}this.ieIFrameFix();};org.apache.myfaces.Popup.prototype.hide=function(){var A=document.getElementById(this.popupId);A.style.display="none";if(document.all&&(org.apache.myfaces.popupFrameUnder!=null)){org.apache.myfaces.popupFrameUnder.style.display="none";}this.ieIFrameFix();};org.apache.myfaces.Popup.prototype.redisplay=function(){var A=document.getElementById(this.popupId);A.style.display="block";org.apache.myfaces.popupCurrentlyOpenedPopup=A;this.ieIFrameFix();};org.apache.myfaces.Popup.prototype.popupGetScrollingX=function(){if(self.pageXOffset){return self.pageXOffset;}else{if(document.documentElement&&document.documentElement.scrollLeft){return document.documentElement.scrollLeft;}else{if(document.body){return document.body.scrollLeft;}else{return 0;}}}};org.apache.myfaces.Popup.prototype.popupGetScrollingY=function(){if(self.pageYOffset){return self.pageYOffset;}else{if(document.documentElement&&document.documentElement.scrollTop){return document.documentElement.scrollTop;}else{if(document.body){return document.body.scrollTop;}else{return 0;}}}};org.apache.myfaces.Popup.prototype.ieIFrameFix=function(){if(this.isIE6){if(org.apache.myfaces.popupCurrentlyOpenedPopup==null){return false;}var B=document.getElementById(org.apache.myfaces.popupCurrentlyOpenedPopup.id+"_IFRAME");if(B==null){org.apache.myfaces.popupFrameUnder=document.createElement("<iframe src='javascript:false;' id='"+org.apache.myfaces.popupCurrentlyOpenedPopup.id+"_IFRAME' style='visibility:hidden; position: absolute; top:0px;left:0px; filter:alpha(Opacity=0);' frameborder='0' scroll='none' />");document.body.insertBefore(org.apache.myfaces.popupFrameUnder);}else{org.apache.myfaces.popupFrameUnder=B;}var A=org.apache.myfaces.popupCurrentlyOpenedPopup;B=org.apache.myfaces.popupFrameUnder;if(A!=null&&(A.style.display=="block")){A.style.zIndex=99;B.style.zIndex=A.style.zIndex-1;B.style.width=A.offsetWidth;B.style.height=A.offsetHeight;B.style.top=A.style.top;B.style.left=A.style.left;B.style.marginTop=A.style.marginTop;B.style.marginLeft=A.style.marginLeft;B.style.marginRight=A.style.marginRight;B.style.marginBottem=A.style.marginBottom;B.style.display="block";B.style.visibility="visible";}else{B.style.display="none";}}return false;};}/*! jQuery UI - v1.13.0 - 2021-09-05
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, focusable.js, form-reset-mixin.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/draggable.js, widgets/droppable.js, widgets/resizable.js, widgets/selectable.js, widgets/sortable.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/selectmenu.js, widgets/slider.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function(a){if(typeof define==="function"&&define.amd){define(["jquery"],a)}else{a(jQuery)}})(function(ax){ax.ui=ax.ui||{};var F=ax.ui.version="1.13.0";
/*!
 * jQuery UI Widget 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var P=0;var av=Array.prototype.hasOwnProperty;var ay=Array.prototype.slice;ax.cleanData=(function(aK){return function(aL){var aN,aO,aM;for(aM=0;(aO=aL[aM])!=null;aM++){aN=ax._data(aO,"events");if(aN&&aN.remove){ax(aO).triggerHandler("remove")}}aK(aL)}})(ax.cleanData);ax.widget=function(aK,aL,aS){var aQ,aN,aR;var aM={};var aP=aK.split(".")[0];aK=aK.split(".")[1];var aO=aP+"-"+aK;if(!aS){aS=aL;aL=ax.Widget}if(Array.isArray(aS)){aS=ax.extend.apply(null,[{}].concat(aS))}ax.expr.pseudos[aO.toLowerCase()]=function(aT){return !!ax.data(aT,aO)};ax[aP]=ax[aP]||{};aQ=ax[aP][aK];aN=ax[aP][aK]=function(aT,aU){if(!this._createWidget){return new aN(aT,aU)}if(arguments.length){this._createWidget(aT,aU)}};ax.extend(aN,aQ,{version:aS.version,_proto:ax.extend({},aS),_childConstructors:[]});aR=new aL();aR.options=ax.widget.extend({},aR.options);ax.each(aS,function(aU,aT){if(typeof aT!=="function"){aM[aU]=aT;return}aM[aU]=(function(){function aV(){return aL.prototype[aU].apply(this,arguments)}function aW(aX){return aL.prototype[aU].apply(this,aX)}return function(){var aZ=this._super;var aX=this._superApply;var aY;this._super=aV;this._superApply=aW;aY=aT.apply(this,arguments);this._super=aZ;this._superApply=aX;return aY}})()});aN.prototype=ax.widget.extend(aR,{widgetEventPrefix:aQ?(aR.widgetEventPrefix||aK):aK},aM,{constructor:aN,namespace:aP,widgetName:aK,widgetFullName:aO});if(aQ){ax.each(aQ._childConstructors,function(aU,aV){var aT=aV.prototype;ax.widget(aT.namespace+"."+aT.widgetName,aN,aV._proto)});delete aQ._childConstructors}else{aL._childConstructors.push(aN)}ax.widget.bridge(aK,aN);return aN};ax.widget.extend=function(aP){var aL=ay.call(arguments,1);var aO=0;var aK=aL.length;var aM;var aN;for(;aO<aK;aO++){for(aM in aL[aO]){aN=aL[aO][aM];if(av.call(aL[aO],aM)&&aN!==undefined){if(ax.isPlainObject(aN)){aP[aM]=ax.isPlainObject(aP[aM])?ax.widget.extend({},aP[aM],aN):ax.widget.extend({},aN)}else{aP[aM]=aN}}}}return aP};ax.widget.bridge=function(aL,aK){var aM=aK.prototype.widgetFullName||aL;ax.fn[aL]=function(aP){var aN=typeof aP==="string";var aO=ay.call(arguments,1);var aQ=this;if(aN){if(!this.length&&aP==="instance"){aQ=undefined}else{this.each(function(){var aS;var aR=ax.data(this,aM);if(aP==="instance"){aQ=aR;return false}if(!aR){return ax.error("cannot call methods on "+aL+" prior to initialization; attempted to call method '"+aP+"'")}if(typeof aR[aP]!=="function"||aP.charAt(0)==="_"){return ax.error("no such method '"+aP+"' for "+aL+" widget instance")}aS=aR[aP].apply(aR,aO);if(aS!==aR&&aS!==undefined){aQ=aS&&aS.jquery?aQ.pushStack(aS.get()):aS;return false}})}}else{if(aO.length){aP=ax.widget.extend.apply(null,[aP].concat(aO))}this.each(function(){var aR=ax.data(this,aM);if(aR){aR.option(aP||{});if(aR._init){aR._init()}}else{ax.data(this,aM,new aK(aP,this))}})}return aQ}};ax.Widget=function(){};ax.Widget._childConstructors=[];ax.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:false,create:null},_createWidget:function(aK,aL){aL=ax(aL||this.defaultElement||this)[0];this.element=ax(aL);this.uuid=P++;this.eventNamespace="."+this.widgetName+this.uuid;this.bindings=ax();this.hoverable=ax();this.focusable=ax();this.classesElementLookup={};if(aL!==this){ax.data(aL,this.widgetFullName,this);this._on(true,this.element,{remove:function(aM){if(aM.target===aL){this.destroy()}}});this.document=ax(aL.style?aL.ownerDocument:aL.document||aL);this.window=ax(this.document[0].defaultView||this.document[0].parentWindow)}this.options=ax.widget.extend({},this.options,this._getCreateOptions(),aK);this._create();if(this.options.disabled){this._setOptionDisabled(this.options.disabled)}this._trigger("create",null,this._getCreateEventData());this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:ax.noop,_create:ax.noop,_init:ax.noop,destroy:function(){var aK=this;this._destroy();ax.each(this.classesElementLookup,function(aL,aM){aK._removeClass(aM,aL)});this.element.off(this.eventNamespace).removeData(this.widgetFullName);this.widget().off(this.eventNamespace).removeAttr("aria-disabled");this.bindings.off(this.eventNamespace)},_destroy:ax.noop,widget:function(){return this.element},option:function(aN,aO){var aK=aN;var aP;var aM;var aL;if(arguments.length===0){return ax.widget.extend({},this.options)}if(typeof aN==="string"){aK={};aP=aN.split(".");aN=aP.shift();if(aP.length){aM=aK[aN]=ax.widget.extend({},this.options[aN]);for(aL=0;aL<aP.length-1;aL++){aM[aP[aL]]=aM[aP[aL]]||{};aM=aM[aP[aL]]}aN=aP.pop();if(arguments.length===1){return aM[aN]===undefined?null:aM[aN]}aM[aN]=aO}else{if(arguments.length===1){return this.options[aN]===undefined?null:this.options[aN]}aK[aN]=aO}}this._setOptions(aK);return this},_setOptions:function(aK){var aL;for(aL in aK){this._setOption(aL,aK[aL])}return this},_setOption:function(aK,aL){if(aK==="classes"){this._setOptionClasses(aL)}this.options[aK]=aL;if(aK==="disabled"){this._setOptionDisabled(aL)}return this},_setOptionClasses:function(aN){var aK,aM,aL;for(aK in aN){aL=this.classesElementLookup[aK];if(aN[aK]===this.options.classes[aK]||!aL||!aL.length){continue}aM=ax(aL.get());this._removeClass(aL,aK);aM.addClass(this._classes({element:aM,keys:aK,classes:aN,add:true}))}},_setOptionDisabled:function(aK){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!aK);if(aK){this._removeClass(this.hoverable,null,"ui-state-hover");this._removeClass(this.focusable,null,"ui-state-focus")}},enable:function(){return this._setOptions({disabled:false})},disable:function(){return this._setOptions({disabled:true})},_classes:function(aL){var aM=[];var aN=this;aL=ax.extend({element:this.element,classes:this.options.classes||{}},aL);function aK(){aL.element.each(function(aQ,aR){var aP=ax.map(aN.classesElementLookup,function(aS){return aS}).some(function(aS){return aS.is(aR)});if(!aP){aN._on(ax(aR),{remove:"_untrackClassesElement"})}})}function aO(aQ,aS){var aR,aP;for(aP=0;aP<aQ.length;aP++){aR=aN.classesElementLookup[aQ[aP]]||ax();if(aL.add){aK();aR=ax(ax.uniqueSort(aR.get().concat(aL.element.get())))}else{aR=ax(aR.not(aL.element).get())}aN.classesElementLookup[aQ[aP]]=aR;aM.push(aQ[aP]);if(aS&&aL.classes[aQ[aP]]){aM.push(aL.classes[aQ[aP]])}}}if(aL.keys){aO(aL.keys.match(/\S+/g)||[],true)}if(aL.extra){aO(aL.extra.match(/\S+/g)||[])}return aM.join(" ")},_untrackClassesElement:function(aL){var aK=this;ax.each(aK.classesElementLookup,function(aM,aN){if(ax.inArray(aL.target,aN)!==-1){aK.classesElementLookup[aM]=ax(aN.not(aL.target).get())}});this._off(ax(aL.target))},_removeClass:function(aL,aM,aK){return this._toggleClass(aL,aM,aK,false)},_addClass:function(aL,aM,aK){return this._toggleClass(aL,aM,aK,true)},_toggleClass:function(aN,aO,aK,aP){aP=(typeof aP==="boolean")?aP:aK;var aL=(typeof aN==="string"||aN===null),aM={extra:aL?aO:aK,keys:aL?aN:aO,element:aL?this.element:aN,add:aP};aM.element.toggleClass(this._classes(aM),aP);return this},_on:function(aN,aM,aL){var aO;var aK=this;if(typeof aN!=="boolean"){aL=aM;aM=aN;aN=false}if(!aL){aL=aM;aM=this.element;aO=this.widget()}else{aM=aO=ax(aM);this.bindings=this.bindings.add(aM)}ax.each(aL,function(aU,aT){function aR(){if(!aN&&(aK.options.disabled===true||ax(this).hasClass("ui-state-disabled"))){return}return(typeof aT==="string"?aK[aT]:aT).apply(aK,arguments)}if(typeof aT!=="string"){aR.guid=aT.guid=aT.guid||aR.guid||ax.guid++}var aS=aU.match(/^([\w:-]*)\s*(.*)$/);var aQ=aS[1]+aK.eventNamespace;var aP=aS[2];if(aP){aO.on(aQ,aP,aR)}else{aM.on(aQ,aR)}})},_off:function(aL,aK){aK=(aK||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace;aL.off(aK);this.bindings=ax(this.bindings.not(aL).get());this.focusable=ax(this.focusable.not(aL).get());this.hoverable=ax(this.hoverable.not(aL).get())},_delay:function(aN,aM){function aL(){return(typeof aN==="string"?aK[aN]:aN).apply(aK,arguments)}var aK=this;return setTimeout(aL,aM||0)},_hoverable:function(aK){this.hoverable=this.hoverable.add(aK);this._on(aK,{mouseenter:function(aL){this._addClass(ax(aL.currentTarget),null,"ui-state-hover")},mouseleave:function(aL){this._removeClass(ax(aL.currentTarget),null,"ui-state-hover")}})},_focusable:function(aK){this.focusable=this.focusable.add(aK);this._on(aK,{focusin:function(aL){this._addClass(ax(aL.currentTarget),null,"ui-state-focus")},focusout:function(aL){this._removeClass(ax(aL.currentTarget),null,"ui-state-focus")}})},_trigger:function(aK,aL,aM){var aP,aO;var aN=this.options[aK];aM=aM||{};aL=ax.Event(aL);aL.type=(aK===this.widgetEventPrefix?aK:this.widgetEventPrefix+aK).toLowerCase();aL.target=this.element[0];aO=aL.originalEvent;if(aO){for(aP in aO){if(!(aP in aL)){aL[aP]=aO[aP]}}}this.element.trigger(aL,aM);return !(typeof aN==="function"&&aN.apply(this.element[0],[aL].concat(aM))===false||aL.isDefaultPrevented())}};ax.each({show:"fadeIn",hide:"fadeOut"},function(aL,aK){ax.Widget.prototype["_"+aL]=function(aO,aN,aQ){if(typeof aN==="string"){aN={effect:aN}}var aP;var aM=!aN?aL:aN===true||typeof aN==="number"?aK:aN.effect||aK;aN=aN||{};if(typeof aN==="number"){aN={duration:aN}}else{if(aN===true){aN={}}}aP=!ax.isEmptyObject(aN);aN.complete=aQ;if(aN.delay){aO.delay(aN.delay)}if(aP&&ax.effects&&ax.effects.effect[aM]){aO[aL](aN)}else{if(aM!==aL&&aO[aM]){aO[aM](aN.duration,aN.easing,aQ)}else{aO.queue(function(aR){ax(this)[aL]();if(aQ){aQ.call(aO[0])}aR()})}}}});var l=ax.widget;
/*!
 * jQuery UI Position 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */
(function(){var aS,aT=Math.max,aW=Math.abs,aN=/left|center|right/,aQ=/top|center|bottom/,aL=/[\+\-]\d+(\.[\d]+)?%?/,aU=/^\w+/,aM=/%$/,aP=ax.fn.position;function aV(aZ,aY,aX){return[parseFloat(aZ[0])*(aM.test(aZ[0])?aY/100:1),parseFloat(aZ[1])*(aM.test(aZ[1])?aX/100:1)]}function aR(aX,aY){return parseInt(ax.css(aX,aY),10)||0}function aK(aX){return aX!=null&&aX===aX.window}function aO(aY){var aX=aY[0];if(aX.nodeType===9){return{width:aY.width(),height:aY.height(),offset:{top:0,left:0}}}if(aK(aX)){return{width:aY.width(),height:aY.height(),offset:{top:aY.scrollTop(),left:aY.scrollLeft()}}}if(aX.preventDefault){return{width:0,height:0,offset:{top:aX.pageY,left:aX.pageX}}}return{width:aY.outerWidth(),height:aY.outerHeight(),offset:aY.offset()}}ax.position={scrollbarWidth:function(){if(aS!==undefined){return aS}var aY,aX,a0=ax("<div style='display:block;position:absolute;width:200px;height:200px;overflow:hidden;'><div style='height:300px;width:auto;'></div></div>"),aZ=a0.children()[0];ax("body").append(a0);aY=aZ.offsetWidth;a0.css("overflow","scroll");aX=aZ.offsetWidth;if(aY===aX){aX=a0[0].clientWidth}a0.remove();return(aS=aY-aX)},getScrollInfo:function(a1){var a0=a1.isWindow||a1.isDocument?"":a1.element.css("overflow-x"),aZ=a1.isWindow||a1.isDocument?"":a1.element.css("overflow-y"),aY=a0==="scroll"||(a0==="auto"&&a1.width<a1.element[0].scrollWidth),aX=aZ==="scroll"||(aZ==="auto"&&a1.height<a1.element[0].scrollHeight);return{width:aX?ax.position.scrollbarWidth():0,height:aY?ax.position.scrollbarWidth():0}},getWithinInfo:function(aY){var a0=ax(aY||window),aZ=aK(a0[0]),a1=!!a0[0]&&a0[0].nodeType===9,aX=!aZ&&!a1;return{element:a0,isWindow:aZ,isDocument:a1,offset:aX?ax(aY).offset():{left:0,top:0},scrollLeft:a0.scrollLeft(),scrollTop:a0.scrollTop(),width:a0.outerWidth(),height:a0.outerHeight()}}};ax.fn.position=function(a7){if(!a7||!a7.of){return aP.apply(this,arguments)}a7=ax.extend({},a7);var a8,a4,a2,a6,a1,aX,a3=typeof a7.of==="string"?ax(document).find(a7.of):ax(a7.of),a0=ax.position.getWithinInfo(a7.within),aY=ax.position.getScrollInfo(a0),a5=(a7.collision||"flip").split(" "),aZ={};aX=aO(a3);if(a3[0].preventDefault){a7.at="left top"}a4=aX.width;a2=aX.height;a6=aX.offset;a1=ax.extend({},a6);ax.each(["my","at"],function(){var bb=(a7[this]||"").split(" "),ba,a9;if(bb.length===1){bb=aN.test(bb[0])?bb.concat(["center"]):aQ.test(bb[0])?["center"].concat(bb):["center","center"]}bb[0]=aN.test(bb[0])?bb[0]:"center";bb[1]=aQ.test(bb[1])?bb[1]:"center";ba=aL.exec(bb[0]);a9=aL.exec(bb[1]);aZ[this]=[ba?ba[0]:0,a9?a9[0]:0];a7[this]=[aU.exec(bb[0])[0],aU.exec(bb[1])[0]]});if(a5.length===1){a5[1]=a5[0]}if(a7.at[0]==="right"){a1.left+=a4}else{if(a7.at[0]==="center"){a1.left+=a4/2}}if(a7.at[1]==="bottom"){a1.top+=a2}else{if(a7.at[1]==="center"){a1.top+=a2/2}}a8=aV(aZ.at,a4,a2);a1.left+=a8[0];a1.top+=a8[1];return this.each(function(){var ba,bj,bc=ax(this),be=bc.outerWidth(),bb=bc.outerHeight(),bd=aR(this,"marginLeft"),a9=aR(this,"marginTop"),bi=be+bd+aR(this,"marginRight")+aY.width,bh=bb+a9+aR(this,"marginBottom")+aY.height,bf=ax.extend({},a1),bg=aV(aZ.my,bc.outerWidth(),bc.outerHeight());if(a7.my[0]==="right"){bf.left-=be}else{if(a7.my[0]==="center"){bf.left-=be/2}}if(a7.my[1]==="bottom"){bf.top-=bb}else{if(a7.my[1]==="center"){bf.top-=bb/2}}bf.left+=bg[0];bf.top+=bg[1];ba={marginLeft:bd,marginTop:a9};ax.each(["left","top"],function(bl,bk){if(ax.ui.position[a5[bl]]){ax.ui.position[a5[bl]][bk](bf,{targetWidth:a4,targetHeight:a2,elemWidth:be,elemHeight:bb,collisionPosition:ba,collisionWidth:bi,collisionHeight:bh,offset:[a8[0]+bg[0],a8[1]+bg[1]],my:a7.my,at:a7.at,within:a0,elem:bc})}});if(a7.using){bj=function(bn){var bp=a6.left-bf.left,bm=bp+a4-be,bo=a6.top-bf.top,bl=bo+a2-bb,bk={target:{element:a3,left:a6.left,top:a6.top,width:a4,height:a2},element:{element:bc,left:bf.left,top:bf.top,width:be,height:bb},horizontal:bm<0?"left":bp>0?"right":"center",vertical:bl<0?"top":bo>0?"bottom":"middle"};if(a4<be&&aW(bp+bm)<a4){bk.horizontal="center"}if(a2<bb&&aW(bo+bl)<a2){bk.vertical="middle"}if(aT(aW(bp),aW(bm))>aT(aW(bo),aW(bl))){bk.important="horizontal"}else{bk.important="vertical"}a7.using.call(this,bn,bk)}}bc.offset(ax.extend(bf,{using:bj}))})};ax.ui.position={fit:{left:function(a1,a0){var aZ=a0.within,a3=aZ.isWindow?aZ.scrollLeft:aZ.offset.left,a5=aZ.width,a2=a1.left-a0.collisionPosition.marginLeft,a4=a3-a2,aY=a2+a0.collisionWidth-a5-a3,aX;if(a0.collisionWidth>a5){if(a4>0&&aY<=0){aX=a1.left+a4+a0.collisionWidth-a5-a3;a1.left+=a4-aX}else{if(aY>0&&a4<=0){a1.left=a3}else{if(a4>aY){a1.left=a3+a5-a0.collisionWidth}else{a1.left=a3}}}}else{if(a4>0){a1.left+=a4}else{if(aY>0){a1.left-=aY}else{a1.left=aT(a1.left-a2,a1.left)}}}},top:function(a0,aZ){var aY=aZ.within,a4=aY.isWindow?aY.scrollTop:aY.offset.top,a5=aZ.within.height,a2=a0.top-aZ.collisionPosition.marginTop,a3=a4-a2,a1=a2+aZ.collisionHeight-a5-a4,aX;if(aZ.collisionHeight>a5){if(a3>0&&a1<=0){aX=a0.top+a3+aZ.collisionHeight-a5-a4;a0.top+=a3-aX}else{if(a1>0&&a3<=0){a0.top=a4}else{if(a3>a1){a0.top=a4+a5-aZ.collisionHeight}else{a0.top=a4}}}}else{if(a3>0){a0.top+=a3}else{if(a1>0){a0.top-=a1}else{a0.top=aT(a0.top-a2,a0.top)}}}}},flip:{left:function(a3,a2){var a1=a2.within,a7=a1.offset.left+a1.scrollLeft,ba=a1.width,aZ=a1.isWindow?a1.scrollLeft:a1.offset.left,a4=a3.left-a2.collisionPosition.marginLeft,a8=a4-aZ,aY=a4+a2.collisionWidth-ba-aZ,a6=a2.my[0]==="left"?-a2.elemWidth:a2.my[0]==="right"?a2.elemWidth:0,a9=a2.at[0]==="left"?a2.targetWidth:a2.at[0]==="right"?-a2.targetWidth:0,a0=-2*a2.offset[0],aX,a5;if(a8<0){aX=a3.left+a6+a9+a0+a2.collisionWidth-ba-a7;if(aX<0||aX<aW(a8)){a3.left+=a6+a9+a0}}else{if(aY>0){a5=a3.left-a2.collisionPosition.marginLeft+a6+a9+a0-aZ;if(a5>0||aW(a5)<aY){a3.left+=a6+a9+a0}}}},top:function(a2,a1){var a0=a1.within,a9=a0.offset.top+a0.scrollTop,ba=a0.height,aX=a0.isWindow?a0.scrollTop:a0.offset.top,a4=a2.top-a1.collisionPosition.marginTop,a6=a4-aX,a3=a4+a1.collisionHeight-ba-aX,a7=a1.my[1]==="top",a5=a7?-a1.elemHeight:a1.my[1]==="bottom"?a1.elemHeight:0,bb=a1.at[1]==="top"?a1.targetHeight:a1.at[1]==="bottom"?-a1.targetHeight:0,aZ=-2*a1.offset[1],a8,aY;if(a6<0){aY=a2.top+a5+bb+aZ+a1.collisionHeight-ba-a9;if(aY<0||aY<aW(a6)){a2.top+=a5+bb+aZ}}else{if(a3>0){a8=a2.top-a1.collisionPosition.marginTop+a5+bb+aZ-aX;if(a8>0||aW(a8)<a3){a2.top+=a5+bb+aZ}}}}},flipfit:{left:function(){ax.ui.position.flip.left.apply(this,arguments);ax.ui.position.fit.left.apply(this,arguments)},top:function(){ax.ui.position.flip.top.apply(this,arguments);ax.ui.position.fit.top.apply(this,arguments)}}}})();var ar=ax.ui.position;
/*!
 * jQuery UI :data 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var s=ax.extend(ax.expr.pseudos,{data:ax.expr.createPseudo?ax.expr.createPseudo(function(aK){return function(aL){return !!ax.data(aL,aK)}}):function(aM,aL,aK){return !!ax.data(aM,aK[3])}});
/*!
 * jQuery UI Disable Selection 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var o=ax.fn.extend({disableSelection:(function(){var aK="onselectstart" in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(aK+".ui-disableSelection",function(aL){aL.preventDefault()})}})(),enableSelection:function(){return this.off(".ui-disableSelection")}});
/*!
 * jQuery UI Focusable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.ui.focusable=function(aN,aL){var aQ,aO,aM,aP,aK,aR=aN.nodeName.toLowerCase();if("area"===aR){aQ=aN.parentNode;aO=aQ.name;if(!aN.href||!aO||aQ.nodeName.toLowerCase()!=="map"){return false}aM=ax("img[usemap='#"+aO+"']");return aM.length>0&&aM.is(":visible")}if(/^(input|select|textarea|button|object)$/.test(aR)){aP=!aN.disabled;if(aP){aK=ax(aN).closest("fieldset")[0];if(aK){aP=!aK.disabled}}}else{if("a"===aR){aP=aN.href||aL}else{aP=aL}}return aP&&ax(aN).is(":visible")&&q(ax(aN))};function q(aL){var aK=aL.css("visibility");while(aK==="inherit"){aL=aL.parent();aK=aL.css("visibility")}return aK==="visible"}ax.extend(ax.expr.pseudos,{focusable:function(aK){return ax.ui.focusable(aK,ax.attr(aK,"tabindex")!=null)}});var aG=ax.ui.focusable;var h=ax.fn._form=function(){return typeof this[0].form==="string"?this.closest("form"):ax(this[0].form)};
/*!
 * jQuery UI Form Reset Mixin 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var V=ax.ui.formResetMixin={_formResetHandler:function(){var aK=ax(this);setTimeout(function(){var aL=aK.data("ui-form-reset-instances");ax.each(aL,function(){this.refresh()})})},_bindFormResetHandler:function(){this.form=this.element._form();if(!this.form.length){return}var aK=this.form.data("ui-form-reset-instances")||[];if(!aK.length){this.form.on("reset.ui-form-reset",this._formResetHandler)}aK.push(this);this.form.data("ui-form-reset-instances",aK)},_unbindFormResetHandler:function(){if(!this.form.length){return}var aK=this.form.data("ui-form-reset-instances");aK.splice(ax.inArray(this,aK),1);if(aK.length){this.form.data("ui-form-reset-instances",aK)}else{this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}};
/*!
 * jQuery UI Keycode 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var p=ax.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38};
/*!
 * jQuery UI Labels 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var az=ax.fn.labels=function(){var aL,aK,aO,aN,aM;if(!this.length){return this.pushStack([])}if(this[0].labels&&this[0].labels.length){return this.pushStack(this[0].labels)}aN=this.eq(0).parents("label");aO=this.attr("id");if(aO){aL=this.eq(0).parents().last();aM=aL.add(aL.length?aL.siblings():this.siblings());aK="label[for='"+ax.escapeSelector(aO)+"']";aN=aN.add(aM.find(aK).addBack(aK))}return this.pushStack(aN)};
/*!
 * jQuery UI Scroll Parent 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var ah=ax.fn.scrollParent=function(aM){var aL=this.css("position"),aK=aL==="absolute",aN=aM?/(auto|scroll|hidden)/:/(auto|scroll)/,aO=this.parents().filter(function(){var aP=ax(this);if(aK&&aP.css("position")==="static"){return false}return aN.test(aP.css("overflow")+aP.css("overflow-y")+aP.css("overflow-x"))}).eq(0);return aL==="fixed"||!aO.length?ax(this[0].ownerDocument||document):aO};
/*!
 * jQuery UI Tabbable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var f=ax.extend(ax.expr.pseudos,{tabbable:function(aM){var aL=ax.attr(aM,"tabindex"),aK=aL!=null;return(!aK||aL>=0)&&ax.ui.focusable(aM,aK)}});
/*!
 * jQuery UI Unique ID 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var ai=ax.fn.extend({uniqueId:(function(){var aK=0;return function(){return this.each(function(){if(!this.id){this.id="ui-id-"+(++aK)}})}})(),removeUniqueId:function(){return this.each(function(){if(/^ui-id-\d+$/.test(this.id)){ax(this).removeAttr("id")}})}});var T=ax.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());
/*!
 * jQuery UI Mouse 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var aj=false;ax(document).on("mouseup",function(){aj=false});var a=ax.widget("ui.mouse",{version:"1.13.0",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var aK=this;this.element.on("mousedown."+this.widgetName,function(aL){return aK._mouseDown(aL)}).on("click."+this.widgetName,function(aL){if(true===ax.data(aL.target,aK.widgetName+".preventClickEvent")){ax.removeData(aL.target,aK.widgetName+".preventClickEvent");aL.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.off("."+this.widgetName);if(this._mouseMoveDelegate){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)}},_mouseDown:function(aM){if(aj){return}this._mouseMoved=false;if(this._mouseStarted){this._mouseUp(aM)}this._mouseDownEvent=aM;var aL=this,aN=(aM.which===1),aK=(typeof this.options.cancel==="string"&&aM.target.nodeName?ax(aM.target).closest(this.options.cancel).length:false);if(!aN||aK||!this._mouseCapture(aM)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){aL.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(aM)&&this._mouseDelayMet(aM)){this._mouseStarted=(this._mouseStart(aM)!==false);if(!this._mouseStarted){aM.preventDefault();return true}}if(true===ax.data(aM.target,this.widgetName+".preventClickEvent")){ax.removeData(aM.target,this.widgetName+".preventClickEvent")}this._mouseMoveDelegate=function(aO){return aL._mouseMove(aO)};this._mouseUpDelegate=function(aO){return aL._mouseUp(aO)};this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate);aM.preventDefault();aj=true;return true},_mouseMove:function(aK){if(this._mouseMoved){if(ax.ui.ie&&(!document.documentMode||document.documentMode<9)&&!aK.button){return this._mouseUp(aK)}else{if(!aK.which){if(aK.originalEvent.altKey||aK.originalEvent.ctrlKey||aK.originalEvent.metaKey||aK.originalEvent.shiftKey){this.ignoreMissingWhich=true}else{if(!this.ignoreMissingWhich){return this._mouseUp(aK)}}}}}if(aK.which||aK.button){this._mouseMoved=true}if(this._mouseStarted){this._mouseDrag(aK);return aK.preventDefault()}if(this._mouseDistanceMet(aK)&&this._mouseDelayMet(aK)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,aK)!==false);if(this._mouseStarted){this._mouseDrag(aK)}else{this._mouseUp(aK)}}return !this._mouseStarted},_mouseUp:function(aK){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;if(aK.target===this._mouseDownEvent.target){ax.data(aK.target,this.widgetName+".preventClickEvent",true)}this._mouseStop(aK)}if(this._mouseDelayTimer){clearTimeout(this._mouseDelayTimer);delete this._mouseDelayTimer}this.ignoreMissingWhich=false;aj=false;aK.preventDefault()},_mouseDistanceMet:function(aK){return(Math.max(Math.abs(this._mouseDownEvent.pageX-aK.pageX),Math.abs(this._mouseDownEvent.pageY-aK.pageY))>=this.options.distance)},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}});var M=ax.ui.plugin={add:function(aL,aM,aO){var aK,aN=ax.ui[aL].prototype;for(aK in aO){aN.plugins[aK]=aN.plugins[aK]||[];aN.plugins[aK].push([aM,aO[aK]])}},call:function(aK,aN,aM,aL){var aO,aP=aK.plugins[aN];if(!aP){return}if(!aL&&(!aK.element[0].parentNode||aK.element[0].parentNode.nodeType===11)){return}for(aO=0;aO<aP.length;aO++){if(aK.options[aP[aO][0]]){aP[aO][1].apply(aK.element,aM)}}}};var i=ax.ui.safeActiveElement=function(aK){var aM;try{aM=aK.activeElement}catch(aL){aM=aK.body}if(!aM){aM=aK.body}if(!aM.nodeName){aM=aK.body}return aM};var c=ax.ui.safeBlur=function(aK){if(aK&&aK.nodeName.toLowerCase()!=="body"){ax(aK).trigger("blur")}};
/*!
 * jQuery UI Draggable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.draggable",ax.ui.mouse,{version:"1.13.0",widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false,drag:null,start:null,stop:null},_create:function(){if(this.options.helper==="original"){this._setPositionRelative()}if(this.options.addClasses){this._addClass("ui-draggable")}this._setHandleClassName();this._mouseInit()},_setOption:function(aK,aL){this._super(aK,aL);if(aK==="handle"){this._removeHandleClassName();this._setHandleClassName()}},_destroy:function(){if((this.helper||this.element).is(".ui-draggable-dragging")){this.destroyOnClear=true;return}this._removeHandleClassName();this._mouseDestroy()},_mouseCapture:function(aK){var aL=this.options;if(this.helper||aL.disabled||ax(aK.target).closest(".ui-resizable-handle").length>0){return false}this.handle=this._getHandle(aK);if(!this.handle){return false}this._blurActiveElement(aK);this._blockFrames(aL.iframeFix===true?"iframe":aL.iframeFix);return true},_blockFrames:function(aK){this.iframeBlocks=this.document.find(aK).map(function(){var aL=ax(this);return ax("<div>").css("position","absolute").appendTo(aL.parent()).outerWidth(aL.outerWidth()).outerHeight(aL.outerHeight()).offset(aL.offset())[0]})},_unblockFrames:function(){if(this.iframeBlocks){this.iframeBlocks.remove();delete this.iframeBlocks}},_blurActiveElement:function(aL){var aK=ax.ui.safeActiveElement(this.document[0]),aM=ax(aL.target);if(aM.closest(aK).length){return}ax.ui.safeBlur(aK)},_mouseStart:function(aK){var aL=this.options;this.helper=this._createHelper(aK);this._addClass(this.helper,"ui-draggable-dragging");this._cacheHelperProportions();if(ax.ui.ddmanager){ax.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent(true);this.offsetParent=this.helper.offsetParent();this.hasFixedAncestor=this.helper.parents().filter(function(){return ax(this).css("position")==="fixed"}).length>0;this.positionAbs=this.element.offset();this._refreshOffsets(aK);this.originalPosition=this.position=this._generatePosition(aK,false);this.originalPageX=aK.pageX;this.originalPageY=aK.pageY;if(aL.cursorAt){this._adjustOffsetFromHelper(aL.cursorAt)}this._setContainment();if(this._trigger("start",aK)===false){this._clear();return false}this._cacheHelperProportions();if(ax.ui.ddmanager&&!aL.dropBehaviour){ax.ui.ddmanager.prepareOffsets(this,aK)}this._mouseDrag(aK,true);if(ax.ui.ddmanager){ax.ui.ddmanager.dragStart(this,aK)}return true},_refreshOffsets:function(aK){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:false,parent:this._getParentOffset(),relative:this._getRelativeOffset()};this.offset.click={left:aK.pageX-this.offset.left,top:aK.pageY-this.offset.top}},_mouseDrag:function(aK,aM){if(this.hasFixedAncestor){this.offset.parent=this._getParentOffset()}this.position=this._generatePosition(aK,true);this.positionAbs=this._convertPositionTo("absolute");if(!aM){var aL=this._uiHash();if(this._trigger("drag",aK,aL)===false){this._mouseUp(new ax.Event("mouseup",aK));return false}this.position=aL.position}this.helper[0].style.left=this.position.left+"px";this.helper[0].style.top=this.position.top+"px";if(ax.ui.ddmanager){ax.ui.ddmanager.drag(this,aK)}return false},_mouseStop:function(aL){var aK=this,aM=false;if(ax.ui.ddmanager&&!this.options.dropBehaviour){aM=ax.ui.ddmanager.drop(this,aL)}if(this.dropped){aM=this.dropped;this.dropped=false}if((this.options.revert==="invalid"&&!aM)||(this.options.revert==="valid"&&aM)||this.options.revert===true||(typeof this.options.revert==="function"&&this.options.revert.call(this.element,aM))){ax(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){if(aK._trigger("stop",aL)!==false){aK._clear()}})}else{if(this._trigger("stop",aL)!==false){this._clear()}}return false},_mouseUp:function(aK){this._unblockFrames();if(ax.ui.ddmanager){ax.ui.ddmanager.dragStop(this,aK)}if(this.handleElement.is(aK.target)){this.element.trigger("focus")}return ax.ui.mouse.prototype._mouseUp.call(this,aK)},cancel:function(){if(this.helper.is(".ui-draggable-dragging")){this._mouseUp(new ax.Event("mouseup",{target:this.element[0]}))}else{this._clear()}return this},_getHandle:function(aK){return this.options.handle?!!ax(aK.target).closest(this.element.find(this.options.handle)).length:true},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element;this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(aL){var aN=this.options,aM=typeof aN.helper==="function",aK=aM?ax(aN.helper.apply(this.element[0],[aL])):(aN.helper==="clone"?this.element.clone().removeAttr("id"):this.element);if(!aK.parents("body").length){aK.appendTo((aN.appendTo==="parent"?this.element[0].parentNode:aN.appendTo))}if(aM&&aK[0]===this.element[0]){this._setPositionRelative()}if(aK[0]!==this.element[0]&&!(/(fixed|absolute)/).test(aK.css("position"))){aK.css("position","absolute")}return aK},_setPositionRelative:function(){if(!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}},_adjustOffsetFromHelper:function(aK){if(typeof aK==="string"){aK=aK.split(" ")}if(Array.isArray(aK)){aK={left:+aK[0],top:+aK[1]||0}}if("left" in aK){this.offset.click.left=aK.left+this.margins.left}if("right" in aK){this.offset.click.left=this.helperProportions.width-aK.right+this.margins.left}if("top" in aK){this.offset.click.top=aK.top+this.margins.top}if("bottom" in aK){this.offset.click.top=this.helperProportions.height-aK.bottom+this.margins.top}},_isRootNode:function(aK){return(/(html|body)/i).test(aK.tagName)||aK===this.document[0]},_getParentOffset:function(){var aL=this.offsetParent.offset(),aK=this.document[0];if(this.cssPosition==="absolute"&&this.scrollParent[0]!==aK&&ax.contains(this.scrollParent[0],this.offsetParent[0])){aL.left+=this.scrollParent.scrollLeft();aL.top+=this.scrollParent.scrollTop()}if(this._isRootNode(this.offsetParent[0])){aL={top:0,left:0}}return{top:aL.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:aL.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition!=="relative"){return{top:0,left:0}}var aK=this.element.position(),aL=this._isRootNode(this.scrollParent[0]);return{top:aK.top-(parseInt(this.helper.css("top"),10)||0)+(!aL?this.scrollParent.scrollTop():0),left:aK.left-(parseInt(this.helper.css("left"),10)||0)+(!aL?this.scrollParent.scrollLeft():0)}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0),right:(parseInt(this.element.css("marginRight"),10)||0),bottom:(parseInt(this.element.css("marginBottom"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var aL,aO,aM,aN=this.options,aK=this.document[0];this.relativeContainer=null;if(!aN.containment){this.containment=null;return}if(aN.containment==="window"){this.containment=[ax(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,ax(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,ax(window).scrollLeft()+ax(window).width()-this.helperProportions.width-this.margins.left,ax(window).scrollTop()+(ax(window).height()||aK.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return}if(aN.containment==="document"){this.containment=[0,0,ax(aK).width()-this.helperProportions.width-this.margins.left,(ax(aK).height()||aK.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return}if(aN.containment.constructor===Array){this.containment=aN.containment;return}if(aN.containment==="parent"){aN.containment=this.helper[0].parentNode}aO=ax(aN.containment);aM=aO[0];if(!aM){return}aL=/(scroll|auto)/.test(aO.css("overflow"));this.containment=[(parseInt(aO.css("borderLeftWidth"),10)||0)+(parseInt(aO.css("paddingLeft"),10)||0),(parseInt(aO.css("borderTopWidth"),10)||0)+(parseInt(aO.css("paddingTop"),10)||0),(aL?Math.max(aM.scrollWidth,aM.offsetWidth):aM.offsetWidth)-(parseInt(aO.css("borderRightWidth"),10)||0)-(parseInt(aO.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(aL?Math.max(aM.scrollHeight,aM.offsetHeight):aM.offsetHeight)-(parseInt(aO.css("borderBottomWidth"),10)||0)-(parseInt(aO.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relativeContainer=aO},_convertPositionTo:function(aL,aN){if(!aN){aN=this.position}var aK=aL==="absolute"?1:-1,aM=this._isRootNode(this.scrollParent[0]);return{top:(aN.top+this.offset.relative.top*aK+this.offset.parent.top*aK-((this.cssPosition==="fixed"?-this.offset.scroll.top:(aM?0:this.offset.scroll.top))*aK)),left:(aN.left+this.offset.relative.left*aK+this.offset.parent.left*aK-((this.cssPosition==="fixed"?-this.offset.scroll.left:(aM?0:this.offset.scroll.left))*aK))}},_generatePosition:function(aL,aR){var aK,aS,aT,aN,aM=this.options,aQ=this._isRootNode(this.scrollParent[0]),aP=aL.pageX,aO=aL.pageY;if(!aQ||!this.offset.scroll){this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}}if(aR){if(this.containment){if(this.relativeContainer){aS=this.relativeContainer.offset();aK=[this.containment[0]+aS.left,this.containment[1]+aS.top,this.containment[2]+aS.left,this.containment[3]+aS.top]}else{aK=this.containment}if(aL.pageX-this.offset.click.left<aK[0]){aP=aK[0]+this.offset.click.left}if(aL.pageY-this.offset.click.top<aK[1]){aO=aK[1]+this.offset.click.top}if(aL.pageX-this.offset.click.left>aK[2]){aP=aK[2]+this.offset.click.left}if(aL.pageY-this.offset.click.top>aK[3]){aO=aK[3]+this.offset.click.top}}if(aM.grid){aT=aM.grid[1]?this.originalPageY+Math.round((aO-this.originalPageY)/aM.grid[1])*aM.grid[1]:this.originalPageY;aO=aK?((aT-this.offset.click.top>=aK[1]||aT-this.offset.click.top>aK[3])?aT:((aT-this.offset.click.top>=aK[1])?aT-aM.grid[1]:aT+aM.grid[1])):aT;aN=aM.grid[0]?this.originalPageX+Math.round((aP-this.originalPageX)/aM.grid[0])*aM.grid[0]:this.originalPageX;aP=aK?((aN-this.offset.click.left>=aK[0]||aN-this.offset.click.left>aK[2])?aN:((aN-this.offset.click.left>=aK[0])?aN-aM.grid[0]:aN+aM.grid[0])):aN}if(aM.axis==="y"){aP=this.originalPageX}if(aM.axis==="x"){aO=this.originalPageY}}return{top:(aO-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.offset.scroll.top:(aQ?0:this.offset.scroll.top))),left:(aP-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.offset.scroll.left:(aQ?0:this.offset.scroll.left)))}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging");if(this.helper[0]!==this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false;if(this.destroyOnClear){this.destroy()}},_trigger:function(aK,aL,aM){aM=aM||this._uiHash();ax.ui.plugin.call(this,aK,[aL,aM,this],true);if(/^(drag|start|stop)/.test(aK)){this.positionAbs=this._convertPositionTo("absolute");aM.offset=this.positionAbs}return ax.Widget.prototype._trigger.call(this,aK,aL,aM)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});ax.ui.plugin.add("draggable","connectToSortable",{start:function(aM,aN,aK){var aL=ax.extend({},aN,{item:aK.element});aK.sortables=[];ax(aK.options.connectToSortable).each(function(){var aO=ax(this).sortable("instance");if(aO&&!aO.options.disabled){aK.sortables.push(aO);aO.refreshPositions();aO._trigger("activate",aM,aL)}})},stop:function(aM,aN,aK){var aL=ax.extend({},aN,{item:aK.element});aK.cancelHelperRemoval=false;ax.each(aK.sortables,function(){var aO=this;if(aO.isOver){aO.isOver=0;aK.cancelHelperRemoval=true;aO.cancelHelperRemoval=false;aO._storedCSS={position:aO.placeholder.css("position"),top:aO.placeholder.css("top"),left:aO.placeholder.css("left")};aO._mouseStop(aM);aO.options.helper=aO.options._helper}else{aO.cancelHelperRemoval=true;aO._trigger("deactivate",aM,aL)}})},drag:function(aL,aM,aK){ax.each(aK.sortables,function(){var aN=false,aO=this;aO.positionAbs=aK.positionAbs;aO.helperProportions=aK.helperProportions;aO.offset.click=aK.offset.click;if(aO._intersectsWith(aO.containerCache)){aN=true;ax.each(aK.sortables,function(){this.positionAbs=aK.positionAbs;this.helperProportions=aK.helperProportions;this.offset.click=aK.offset.click;if(this!==aO&&this._intersectsWith(this.containerCache)&&ax.contains(aO.element[0],this.element[0])){aN=false}return aN})}if(aN){if(!aO.isOver){aO.isOver=1;aK._parent=aM.helper.parent();aO.currentItem=aM.helper.appendTo(aO.element).data("ui-sortable-item",true);aO.options._helper=aO.options.helper;aO.options.helper=function(){return aM.helper[0]};aL.target=aO.currentItem[0];aO._mouseCapture(aL,true);aO._mouseStart(aL,true,true);aO.offset.click.top=aK.offset.click.top;aO.offset.click.left=aK.offset.click.left;aO.offset.parent.left-=aK.offset.parent.left-aO.offset.parent.left;aO.offset.parent.top-=aK.offset.parent.top-aO.offset.parent.top;aK._trigger("toSortable",aL);aK.dropped=aO.element;ax.each(aK.sortables,function(){this.refreshPositions()});aK.currentItem=aK.element;aO.fromOutside=aK}if(aO.currentItem){aO._mouseDrag(aL);aM.position=aO.position}}else{if(aO.isOver){aO.isOver=0;aO.cancelHelperRemoval=true;aO.options._revert=aO.options.revert;aO.options.revert=false;aO._trigger("out",aL,aO._uiHash(aO));aO._mouseStop(aL,true);aO.options.revert=aO.options._revert;aO.options.helper=aO.options._helper;if(aO.placeholder){aO.placeholder.remove()}aM.helper.appendTo(aK._parent);aK._refreshOffsets(aL);aM.position=aK._generatePosition(aL,true);aK._trigger("fromSortable",aL);aK.dropped=false;ax.each(aK.sortables,function(){this.refreshPositions()})}}})}});ax.ui.plugin.add("draggable","cursor",{start:function(aM,aN,aK){var aL=ax("body"),aO=aK.options;if(aL.css("cursor")){aO._cursor=aL.css("cursor")}aL.css("cursor",aO.cursor)},stop:function(aL,aM,aK){var aN=aK.options;if(aN._cursor){ax("body").css("cursor",aN._cursor)}}});ax.ui.plugin.add("draggable","opacity",{start:function(aM,aN,aK){var aL=ax(aN.helper),aO=aK.options;if(aL.css("opacity")){aO._opacity=aL.css("opacity")}aL.css("opacity",aO.opacity)},stop:function(aL,aM,aK){var aN=aK.options;if(aN._opacity){ax(aM.helper).css("opacity",aN._opacity)}}});ax.ui.plugin.add("draggable","scroll",{start:function(aL,aM,aK){if(!aK.scrollParentNotHidden){aK.scrollParentNotHidden=aK.helper.scrollParent(false)}if(aK.scrollParentNotHidden[0]!==aK.document[0]&&aK.scrollParentNotHidden[0].tagName!=="HTML"){aK.overflowOffset=aK.scrollParentNotHidden.offset()}},drag:function(aN,aO,aM){var aP=aM.options,aL=false,aQ=aM.scrollParentNotHidden[0],aK=aM.document[0];if(aQ!==aK&&aQ.tagName!=="HTML"){if(!aP.axis||aP.axis!=="x"){if((aM.overflowOffset.top+aQ.offsetHeight)-aN.pageY<aP.scrollSensitivity){aQ.scrollTop=aL=aQ.scrollTop+aP.scrollSpeed}else{if(aN.pageY-aM.overflowOffset.top<aP.scrollSensitivity){aQ.scrollTop=aL=aQ.scrollTop-aP.scrollSpeed}}}if(!aP.axis||aP.axis!=="y"){if((aM.overflowOffset.left+aQ.offsetWidth)-aN.pageX<aP.scrollSensitivity){aQ.scrollLeft=aL=aQ.scrollLeft+aP.scrollSpeed}else{if(aN.pageX-aM.overflowOffset.left<aP.scrollSensitivity){aQ.scrollLeft=aL=aQ.scrollLeft-aP.scrollSpeed}}}}else{if(!aP.axis||aP.axis!=="x"){if(aN.pageY-ax(aK).scrollTop()<aP.scrollSensitivity){aL=ax(aK).scrollTop(ax(aK).scrollTop()-aP.scrollSpeed)}else{if(ax(window).height()-(aN.pageY-ax(aK).scrollTop())<aP.scrollSensitivity){aL=ax(aK).scrollTop(ax(aK).scrollTop()+aP.scrollSpeed)}}}if(!aP.axis||aP.axis!=="y"){if(aN.pageX-ax(aK).scrollLeft()<aP.scrollSensitivity){aL=ax(aK).scrollLeft(ax(aK).scrollLeft()-aP.scrollSpeed)}else{if(ax(window).width()-(aN.pageX-ax(aK).scrollLeft())<aP.scrollSensitivity){aL=ax(aK).scrollLeft(ax(aK).scrollLeft()+aP.scrollSpeed)}}}}if(aL!==false&&ax.ui.ddmanager&&!aP.dropBehaviour){ax.ui.ddmanager.prepareOffsets(aM,aN)}}});ax.ui.plugin.add("draggable","snap",{start:function(aL,aM,aK){var aN=aK.options;aK.snapElements=[];ax(aN.snap.constructor!==String?(aN.snap.items||":data(ui-draggable)"):aN.snap).each(function(){var aP=ax(this),aO=aP.offset();if(this!==aK.element[0]){aK.snapElements.push({item:this,width:aP.outerWidth(),height:aP.outerHeight(),top:aO.top,left:aO.left})}})},drag:function(aW,aT,aN){var aK,a1,aP,aQ,aV,aS,aR,a2,aX,aO,aU=aN.options,a0=aU.snapTolerance,aZ=aT.offset.left,aY=aZ+aN.helperProportions.width,aM=aT.offset.top,aL=aM+aN.helperProportions.height;for(aX=aN.snapElements.length-1;aX>=0;aX--){aV=aN.snapElements[aX].left-aN.margins.left;aS=aV+aN.snapElements[aX].width;aR=aN.snapElements[aX].top-aN.margins.top;a2=aR+aN.snapElements[aX].height;if(aY<aV-a0||aZ>aS+a0||aL<aR-a0||aM>a2+a0||!ax.contains(aN.snapElements[aX].item.ownerDocument,aN.snapElements[aX].item)){if(aN.snapElements[aX].snapping){if(aN.options.snap.release){aN.options.snap.release.call(aN.element,aW,ax.extend(aN._uiHash(),{snapItem:aN.snapElements[aX].item}))}}aN.snapElements[aX].snapping=false;continue}if(aU.snapMode!=="inner"){aK=Math.abs(aR-aL)<=a0;a1=Math.abs(a2-aM)<=a0;aP=Math.abs(aV-aY)<=a0;aQ=Math.abs(aS-aZ)<=a0;if(aK){aT.position.top=aN._convertPositionTo("relative",{top:aR-aN.helperProportions.height,left:0}).top}if(a1){aT.position.top=aN._convertPositionTo("relative",{top:a2,left:0}).top}if(aP){aT.position.left=aN._convertPositionTo("relative",{top:0,left:aV-aN.helperProportions.width}).left}if(aQ){aT.position.left=aN._convertPositionTo("relative",{top:0,left:aS}).left}}aO=(aK||a1||aP||aQ);if(aU.snapMode!=="outer"){aK=Math.abs(aR-aM)<=a0;a1=Math.abs(a2-aL)<=a0;aP=Math.abs(aV-aZ)<=a0;aQ=Math.abs(aS-aY)<=a0;if(aK){aT.position.top=aN._convertPositionTo("relative",{top:aR,left:0}).top}if(a1){aT.position.top=aN._convertPositionTo("relative",{top:a2-aN.helperProportions.height,left:0}).top}if(aP){aT.position.left=aN._convertPositionTo("relative",{top:0,left:aV}).left}if(aQ){aT.position.left=aN._convertPositionTo("relative",{top:0,left:aS-aN.helperProportions.width}).left}}if(!aN.snapElements[aX].snapping&&(aK||a1||aP||aQ||aO)){if(aN.options.snap.snap){aN.options.snap.snap.call(aN.element,aW,ax.extend(aN._uiHash(),{snapItem:aN.snapElements[aX].item}))}}aN.snapElements[aX].snapping=(aK||a1||aP||aQ||aO)}}});ax.ui.plugin.add("draggable","stack",{start:function(aM,aN,aK){var aL,aP=aK.options,aO=ax.makeArray(ax(aP.stack)).sort(function(aR,aQ){return(parseInt(ax(aR).css("zIndex"),10)||0)-(parseInt(ax(aQ).css("zIndex"),10)||0)});if(!aO.length){return}aL=parseInt(ax(aO[0]).css("zIndex"),10)||0;ax(aO).each(function(aQ){ax(this).css("zIndex",aL+aQ)});this.css("zIndex",(aL+aO.length))}});ax.ui.plugin.add("draggable","zIndex",{start:function(aM,aN,aK){var aL=ax(aN.helper),aO=aK.options;if(aL.css("zIndex")){aO._zIndex=aL.css("zIndex")}aL.css("zIndex",aO.zIndex)},stop:function(aL,aM,aK){var aN=aK.options;if(aN._zIndex){ax(aM.helper).css("zIndex",aN._zIndex)}}});var C=ax.ui.draggable;
/*!
 * jQuery UI Droppable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.droppable",{version:"1.13.0",widgetEventPrefix:"drop",options:{accept:"*",addClasses:true,greedy:false,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var aL,aM=this.options,aK=aM.accept;this.isover=false;this.isout=true;this.accept=typeof aK==="function"?aK:function(aN){return aN.is(aK)};this.proportions=function(){if(arguments.length){aL=arguments[0]}else{return aL?aL:aL={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}}};this._addToManager(aM.scope);if(aM.addClasses){this._addClass("ui-droppable")}},_addToManager:function(aK){ax.ui.ddmanager.droppables[aK]=ax.ui.ddmanager.droppables[aK]||[];ax.ui.ddmanager.droppables[aK].push(this)},_splice:function(aK){var aL=0;for(;aL<aK.length;aL++){if(aK[aL]===this){aK.splice(aL,1)}}},_destroy:function(){var aK=ax.ui.ddmanager.droppables[this.options.scope];this._splice(aK)},_setOption:function(aL,aM){if(aL==="accept"){this.accept=typeof aM==="function"?aM:function(aN){return aN.is(aM)}}else{if(aL==="scope"){var aK=ax.ui.ddmanager.droppables[this.options.scope];this._splice(aK);this._addToManager(aM)}}this._super(aL,aM)},_activate:function(aL){var aK=ax.ui.ddmanager.current;this._addActiveClass();if(aK){this._trigger("activate",aL,this.ui(aK))}},_deactivate:function(aL){var aK=ax.ui.ddmanager.current;this._removeActiveClass();if(aK){this._trigger("deactivate",aL,this.ui(aK))}},_over:function(aL){var aK=ax.ui.ddmanager.current;if(!aK||(aK.currentItem||aK.element)[0]===this.element[0]){return}if(this.accept.call(this.element[0],(aK.currentItem||aK.element))){this._addHoverClass();this._trigger("over",aL,this.ui(aK))}},_out:function(aL){var aK=ax.ui.ddmanager.current;if(!aK||(aK.currentItem||aK.element)[0]===this.element[0]){return}if(this.accept.call(this.element[0],(aK.currentItem||aK.element))){this._removeHoverClass();this._trigger("out",aL,this.ui(aK))}},_drop:function(aL,aM){var aK=aM||ax.ui.ddmanager.current,aN=false;if(!aK||(aK.currentItem||aK.element)[0]===this.element[0]){return false}this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var aO=ax(this).droppable("instance");if(aO.options.greedy&&!aO.options.disabled&&aO.options.scope===aK.options.scope&&aO.accept.call(aO.element[0],(aK.currentItem||aK.element))&&ax.ui.intersect(aK,ax.extend(aO,{offset:aO.element.offset()}),aO.options.tolerance,aL)){aN=true;return false}});if(aN){return false}if(this.accept.call(this.element[0],(aK.currentItem||aK.element))){this._removeActiveClass();this._removeHoverClass();this._trigger("drop",aL,this.ui(aK));return this.element}return false},ui:function(aK){return{draggable:(aK.currentItem||aK.element),helper:aK.helper,position:aK.position,offset:aK.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}});ax.ui.intersect=(function(){function aK(aM,aL,aN){return(aM>=aL)&&(aM<(aL+aN))}return function(aW,aQ,aU,aM){if(!aQ.offset){return false}var aO=(aW.positionAbs||aW.position.absolute).left+aW.margins.left,aT=(aW.positionAbs||aW.position.absolute).top+aW.margins.top,aN=aO+aW.helperProportions.width,aS=aT+aW.helperProportions.height,aP=aQ.offset.left,aV=aQ.offset.top,aL=aP+aQ.proportions().width,aR=aV+aQ.proportions().height;switch(aU){case"fit":return(aP<=aO&&aN<=aL&&aV<=aT&&aS<=aR);case"intersect":return(aP<aO+(aW.helperProportions.width/2)&&aN-(aW.helperProportions.width/2)<aL&&aV<aT+(aW.helperProportions.height/2)&&aS-(aW.helperProportions.height/2)<aR);case"pointer":return aK(aM.pageY,aV,aQ.proportions().height)&&aK(aM.pageX,aP,aQ.proportions().width);case"touch":return((aT>=aV&&aT<=aR)||(aS>=aV&&aS<=aR)||(aT<aV&&aS>aR))&&((aO>=aP&&aO<=aL)||(aN>=aP&&aN<=aL)||(aO<aP&&aN>aL));default:return false}}})();ax.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(aN,aP){var aM,aL,aK=ax.ui.ddmanager.droppables[aN.options.scope]||[],aO=aP?aP.type:null,aQ=(aN.currentItem||aN.element).find(":data(ui-droppable)").addBack();droppablesLoop:for(aM=0;aM<aK.length;aM++){if(aK[aM].options.disabled||(aN&&!aK[aM].accept.call(aK[aM].element[0],(aN.currentItem||aN.element)))){continue}for(aL=0;aL<aQ.length;aL++){if(aQ[aL]===aK[aM].element[0]){aK[aM].proportions().height=0;continue droppablesLoop}}aK[aM].visible=aK[aM].element.css("display")!=="none";if(!aK[aM].visible){continue}if(aO==="mousedown"){aK[aM]._activate.call(aK[aM],aP)}aK[aM].offset=aK[aM].element.offset();aK[aM].proportions({width:aK[aM].element[0].offsetWidth,height:aK[aM].element[0].offsetHeight})}},drop:function(aK,aL){var aM=false;ax.each((ax.ui.ddmanager.droppables[aK.options.scope]||[]).slice(),function(){if(!this.options){return}if(!this.options.disabled&&this.visible&&ax.ui.intersect(aK,this,this.options.tolerance,aL)){aM=this._drop.call(this,aL)||aM}if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],(aK.currentItem||aK.element))){this.isout=true;this.isover=false;this._deactivate.call(this,aL)}});return aM},dragStart:function(aK,aL){aK.element.parentsUntil("body").on("scroll.droppable",function(){if(!aK.options.refreshPositions){ax.ui.ddmanager.prepareOffsets(aK,aL)}})},drag:function(aK,aL){if(aK.options.refreshPositions){ax.ui.ddmanager.prepareOffsets(aK,aL)}ax.each(ax.ui.ddmanager.droppables[aK.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible){return}var aP,aN,aM,aO=ax.ui.intersect(aK,this,this.options.tolerance,aL),aQ=!aO&&this.isover?"isout":(aO&&!this.isover?"isover":null);if(!aQ){return}if(this.options.greedy){aN=this.options.scope;aM=this.element.parents(":data(ui-droppable)").filter(function(){return ax(this).droppable("instance").options.scope===aN});if(aM.length){aP=ax(aM[0]).droppable("instance");aP.greedyChild=(aQ==="isover")}}if(aP&&aQ==="isover"){aP.isover=false;aP.isout=true;aP._out.call(aP,aL)}this[aQ]=true;this[aQ==="isout"?"isover":"isout"]=false;this[aQ==="isover"?"_over":"_out"].call(this,aL);if(aP&&aQ==="isout"){aP.isout=false;aP.isover=true;aP._over.call(aP,aL)}})},dragStop:function(aK,aL){aK.element.parentsUntil("body").off("scroll.droppable");if(!aK.options.refreshPositions){ax.ui.ddmanager.prepareOffsets(aK,aL)}}};if(ax.uiBackCompat!==false){ax.widget("ui.droppable",ax.ui.droppable,{options:{hoverClass:false,activeClass:false},_addActiveClass:function(){this._super();if(this.options.activeClass){this.element.addClass(this.options.activeClass)}},_removeActiveClass:function(){this._super();if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}},_addHoverClass:function(){this._super();if(this.options.hoverClass){this.element.addClass(this.options.hoverClass)}},_removeHoverClass:function(){this._super();if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}}})}var ad=ax.ui.droppable;
/*!
 * jQuery UI Resizable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.resizable",ax.ui.mouse,{version:"1.13.0",widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(aK){return parseFloat(aK)||0},_isNumber:function(aK){return !isNaN(parseFloat(aK))},_hasScroll:function(aN,aL){if(ax(aN).css("overflow")==="hidden"){return false}var aK=(aL&&aL==="left")?"scrollLeft":"scrollTop",aM=false;if(aN[aK]>0){return true}try{aN[aK]=1;aM=(aN[aK]>0);aN[aK]=0}catch(aO){}return aM},_create:function(){var aL,aM=this.options,aK=this;this._addClass("ui-resizable");ax.extend(this,{_aspectRatio:!!(aM.aspectRatio),aspectRatio:aM.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:aM.helper||aM.ghost||aM.animate?aM.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)){this.element.wrap(ax("<div class='ui-wrapper'></div>").css({overflow:"hidden",position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance"));this.elementIsWrapper=true;aL={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")};this.element.css(aL);this.originalElement.css("margin",0);this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css(aL);this._proportionallyResize()}this._setupHandles();if(aM.autoHide){ax(this.element).on("mouseenter",function(){if(aM.disabled){return}aK._removeClass("ui-resizable-autohide");aK._handles.show()}).on("mouseleave",function(){if(aM.disabled){return}if(!aK.resizing){aK._addClass("ui-resizable-autohide");aK._handles.hide()}})}this._mouseInit()},_destroy:function(){this._mouseDestroy();this._addedHandles.remove();var aL,aK=function(aM){ax(aM).removeData("resizable").removeData("ui-resizable").off(".resizable")};if(this.elementIsWrapper){aK(this.element);aL=this.element;this.originalElement.css({position:aL.css("position"),width:aL.outerWidth(),height:aL.outerHeight(),top:aL.css("top"),left:aL.css("left")}).insertAfter(aL);aL.remove()}this.originalElement.css("resize",this.originalResizeStyle);aK(this.originalElement);return this},_setOption:function(aK,aL){this._super(aK,aL);switch(aK){case"handles":this._removeHandles();this._setupHandles();break;case"aspectRatio":this._aspectRatio=!!aL;break;default:break}},_setupHandles:function(){var aP=this.options,aO,aL,aQ,aK,aM,aN=this;this.handles=aP.handles||(!ax(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});this._handles=ax();this._addedHandles=ax();if(this.handles.constructor===String){if(this.handles==="all"){this.handles="n,e,s,w,se,sw,ne,nw"}aQ=this.handles.split(",");this.handles={};for(aL=0;aL<aQ.length;aL++){aO=String.prototype.trim.call(aQ[aL]);aK="ui-resizable-"+aO;aM=ax("<div>");this._addClass(aM,"ui-resizable-handle "+aK);aM.css({zIndex:aP.zIndex});this.handles[aO]=".ui-resizable-"+aO;if(!this.element.children(this.handles[aO]).length){this.element.append(aM);this._addedHandles=this._addedHandles.add(aM)}}}this._renderAxis=function(aV){var aS,aT,aR,aU;aV=aV||this.element;for(aS in this.handles){if(this.handles[aS].constructor===String){this.handles[aS]=this.element.children(this.handles[aS]).first().show()}else{if(this.handles[aS].jquery||this.handles[aS].nodeType){this.handles[aS]=ax(this.handles[aS]);this._on(this.handles[aS],{mousedown:aN._mouseDown})}}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)){aT=ax(this.handles[aS],this.element);aU=/sw|ne|nw|se|n|s/.test(aS)?aT.outerHeight():aT.outerWidth();aR=["padding",/ne|nw|n/.test(aS)?"Top":/se|sw|s/.test(aS)?"Bottom":/^e$/.test(aS)?"Right":"Left"].join("");aV.css(aR,aU);this._proportionallyResize()}this._handles=this._handles.add(this.handles[aS])}};this._renderAxis(this.element);this._handles=this._handles.add(this.element.find(".ui-resizable-handle"));this._handles.disableSelection();this._handles.on("mouseover",function(){if(!aN.resizing){if(this.className){aM=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}aN.axis=aM&&aM[1]?aM[1]:"se"}});if(aP.autoHide){this._handles.hide();this._addClass("ui-resizable-autohide")}},_removeHandles:function(){this._addedHandles.remove()},_mouseCapture:function(aM){var aL,aN,aK=false;for(aL in this.handles){aN=ax(this.handles[aL])[0];if(aN===aM.target||ax.contains(aN,aM.target)){aK=true}}return !this.options.disabled&&aK},_mouseStart:function(aL){var aP,aM,aO,aN=this.options,aK=this.element;this.resizing=true;this._renderProxy();aP=this._num(this.helper.css("left"));aM=this._num(this.helper.css("top"));if(aN.containment){aP+=ax(aN.containment).scrollLeft()||0;aM+=ax(aN.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:aP,top:aM};this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:aK.width(),height:aK.height()};this.originalSize=this._helper?{width:aK.outerWidth(),height:aK.outerHeight()}:{width:aK.width(),height:aK.height()};this.sizeDiff={width:aK.outerWidth()-aK.width(),height:aK.outerHeight()-aK.height()};this.originalPosition={left:aP,top:aM};this.originalMousePosition={left:aL.pageX,top:aL.pageY};this.aspectRatio=(typeof aN.aspectRatio==="number")?aN.aspectRatio:((this.originalSize.width/this.originalSize.height)||1);aO=ax(".ui-resizable-"+this.axis).css("cursor");ax("body").css("cursor",aO==="auto"?this.axis+"-resize":aO);this._addClass("ui-resizable-resizing");this._propagate("start",aL);return true},_mouseDrag:function(aP){var aQ,aO,aR=this.originalMousePosition,aL=this.axis,aM=(aP.pageX-aR.left)||0,aK=(aP.pageY-aR.top)||0,aN=this._change[aL];this._updatePrevProperties();if(!aN){return false}aQ=aN.apply(this,[aP,aM,aK]);this._updateVirtualBoundaries(aP.shiftKey);if(this._aspectRatio||aP.shiftKey){aQ=this._updateRatio(aQ,aP)}aQ=this._respectSize(aQ,aP);this._updateCache(aQ);this._propagate("resize",aP);aO=this._applyChanges();if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize()}if(!ax.isEmptyObject(aO)){this._updatePrevProperties();this._trigger("resize",aP,this.ui());this._applyChanges()}return false},_mouseStop:function(aN){this.resizing=false;var aM,aK,aL,aQ,aT,aP,aS,aO=this.options,aR=this;if(this._helper){aM=this._proportionallyResizeElements;aK=aM.length&&(/textarea/i).test(aM[0].nodeName);aL=aK&&this._hasScroll(aM[0],"left")?0:aR.sizeDiff.height;aQ=aK?0:aR.sizeDiff.width;aT={width:(aR.helper.width()-aQ),height:(aR.helper.height()-aL)};aP=(parseFloat(aR.element.css("left"))+(aR.position.left-aR.originalPosition.left))||null;aS=(parseFloat(aR.element.css("top"))+(aR.position.top-aR.originalPosition.top))||null;if(!aO.animate){this.element.css(ax.extend(aT,{top:aS,left:aP}))}aR.helper.height(aR.size.height);aR.helper.width(aR.size.width);if(this._helper&&!aO.animate){this._proportionallyResize()}}ax("body").css("cursor","auto");this._removeClass("ui-resizable-resizing");this._propagate("stop",aN);if(this._helper){this.helper.remove()}return false},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left};this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var aK={};if(this.position.top!==this.prevPosition.top){aK.top=this.position.top+"px"}if(this.position.left!==this.prevPosition.left){aK.left=this.position.left+"px"}if(this.size.width!==this.prevSize.width){aK.width=this.size.width+"px"}if(this.size.height!==this.prevSize.height){aK.height=this.size.height+"px"}this.helper.css(aK);return aK},_updateVirtualBoundaries:function(aM){var aO,aN,aL,aQ,aK,aP=this.options;aK={minWidth:this._isNumber(aP.minWidth)?aP.minWidth:0,maxWidth:this._isNumber(aP.maxWidth)?aP.maxWidth:Infinity,minHeight:this._isNumber(aP.minHeight)?aP.minHeight:0,maxHeight:this._isNumber(aP.maxHeight)?aP.maxHeight:Infinity};if(this._aspectRatio||aM){aO=aK.minHeight*this.aspectRatio;aL=aK.minWidth/this.aspectRatio;aN=aK.maxHeight*this.aspectRatio;aQ=aK.maxWidth/this.aspectRatio;if(aO>aK.minWidth){aK.minWidth=aO}if(aL>aK.minHeight){aK.minHeight=aL}if(aN<aK.maxWidth){aK.maxWidth=aN}if(aQ<aK.maxHeight){aK.maxHeight=aQ}}this._vBoundaries=aK},_updateCache:function(aK){this.offset=this.helper.offset();if(this._isNumber(aK.left)){this.position.left=aK.left}if(this._isNumber(aK.top)){this.position.top=aK.top}if(this._isNumber(aK.height)){this.size.height=aK.height}if(this._isNumber(aK.width)){this.size.width=aK.width}},_updateRatio:function(aM){var aN=this.position,aL=this.size,aK=this.axis;if(this._isNumber(aM.height)){aM.width=(aM.height*this.aspectRatio)}else{if(this._isNumber(aM.width)){aM.height=(aM.width/this.aspectRatio)}}if(aK==="sw"){aM.left=aN.left+(aL.width-aM.width);aM.top=null}if(aK==="nw"){aM.top=aN.top+(aL.height-aM.height);aM.left=aN.left+(aL.width-aM.width)}return aM},_respectSize:function(aP){var aM=this._vBoundaries,aS=this.axis,aU=this._isNumber(aP.width)&&aM.maxWidth&&(aM.maxWidth<aP.width),aQ=this._isNumber(aP.height)&&aM.maxHeight&&(aM.maxHeight<aP.height),aN=this._isNumber(aP.width)&&aM.minWidth&&(aM.minWidth>aP.width),aT=this._isNumber(aP.height)&&aM.minHeight&&(aM.minHeight>aP.height),aL=this.originalPosition.left+this.originalSize.width,aR=this.originalPosition.top+this.originalSize.height,aO=/sw|nw|w/.test(aS),aK=/nw|ne|n/.test(aS);if(aN){aP.width=aM.minWidth}if(aT){aP.height=aM.minHeight}if(aU){aP.width=aM.maxWidth}if(aQ){aP.height=aM.maxHeight}if(aN&&aO){aP.left=aL-aM.minWidth}if(aU&&aO){aP.left=aL-aM.maxWidth}if(aT&&aK){aP.top=aR-aM.minHeight}if(aQ&&aK){aP.top=aR-aM.maxHeight}if(!aP.width&&!aP.height&&!aP.left&&aP.top){aP.top=null}else{if(!aP.width&&!aP.height&&!aP.top&&aP.left){aP.left=null}}return aP},_getPaddingPlusBorderDimensions:function(aM){var aL=0,aN=[],aO=[aM.css("borderTopWidth"),aM.css("borderRightWidth"),aM.css("borderBottomWidth"),aM.css("borderLeftWidth")],aK=[aM.css("paddingTop"),aM.css("paddingRight"),aM.css("paddingBottom"),aM.css("paddingLeft")];for(;aL<4;aL++){aN[aL]=(parseFloat(aO[aL])||0);aN[aL]+=(parseFloat(aK[aL])||0)}return{height:aN[0]+aN[2],width:aN[1]+aN[3]}},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length){return}var aM,aL=0,aK=this.helper||this.element;for(;aL<this._proportionallyResizeElements.length;aL++){aM=this._proportionallyResizeElements[aL];if(!this.outerDimensions){this.outerDimensions=this._getPaddingPlusBorderDimensions(aM)}aM.css({height:(aK.height()-this.outerDimensions.height)||0,width:(aK.width()-this.outerDimensions.width)||0})}},_renderProxy:function(){var aK=this.element,aL=this.options;this.elementOffset=aK.offset();if(this._helper){this.helper=this.helper||ax("<div></div>").css({overflow:"hidden"});this._addClass(this.helper,this._helper);this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++aL.zIndex});this.helper.appendTo("body").disableSelection()}else{this.helper=this.element}},_change:{e:function(aL,aK){return{width:this.originalSize.width+aK}},w:function(aM,aK){var aL=this.originalSize,aN=this.originalPosition;return{left:aN.left+aK,width:aL.width-aK}},n:function(aN,aL,aK){var aM=this.originalSize,aO=this.originalPosition;return{top:aO.top+aK,height:aM.height-aK}},s:function(aM,aL,aK){return{height:this.originalSize.height+aK}},se:function(aM,aL,aK){return ax.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[aM,aL,aK]))},sw:function(aM,aL,aK){return ax.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[aM,aL,aK]))},ne:function(aM,aL,aK){return ax.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[aM,aL,aK]))},nw:function(aM,aL,aK){return ax.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[aM,aL,aK]))}},_propagate:function(aL,aK){ax.ui.plugin.call(this,aL,[aK,this.ui()]);if(aL!=="resize"){this._trigger(aL,aK,this.ui())}},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});ax.ui.plugin.add("resizable","animate",{stop:function(aN){var aS=ax(this).resizable("instance"),aP=aS.options,aM=aS._proportionallyResizeElements,aK=aM.length&&(/textarea/i).test(aM[0].nodeName),aL=aK&&aS._hasScroll(aM[0],"left")?0:aS.sizeDiff.height,aR=aK?0:aS.sizeDiff.width,aO={width:(aS.size.width-aR),height:(aS.size.height-aL)},aQ=(parseFloat(aS.element.css("left"))+(aS.position.left-aS.originalPosition.left))||null,aT=(parseFloat(aS.element.css("top"))+(aS.position.top-aS.originalPosition.top))||null;aS.element.animate(ax.extend(aO,aT&&aQ?{top:aT,left:aQ}:{}),{duration:aP.animateDuration,easing:aP.animateEasing,step:function(){var aU={width:parseFloat(aS.element.css("width")),height:parseFloat(aS.element.css("height")),top:parseFloat(aS.element.css("top")),left:parseFloat(aS.element.css("left"))};if(aM&&aM.length){ax(aM[0]).css({width:aU.width,height:aU.height})}aS._updateCache(aU);aS._propagate("resize",aN)}})}});ax.ui.plugin.add("resizable","containment",{start:function(){var aS,aM,aU,aK,aR,aN,aV,aT=ax(this).resizable("instance"),aQ=aT.options,aP=aT.element,aL=aQ.containment,aO=(aL instanceof ax)?aL.get(0):(/parent/.test(aL))?aP.parent().get(0):aL;if(!aO){return}aT.containerElement=ax(aO);if(/document/.test(aL)||aL===document){aT.containerOffset={left:0,top:0};aT.containerPosition={left:0,top:0};aT.parentData={element:ax(document),left:0,top:0,width:ax(document).width(),height:ax(document).height()||document.body.parentNode.scrollHeight}}else{aS=ax(aO);aM=[];ax(["Top","Right","Left","Bottom"]).each(function(aX,aW){aM[aX]=aT._num(aS.css("padding"+aW))});aT.containerOffset=aS.offset();aT.containerPosition=aS.position();aT.containerSize={height:(aS.innerHeight()-aM[3]),width:(aS.innerWidth()-aM[1])};aU=aT.containerOffset;aK=aT.containerSize.height;aR=aT.containerSize.width;aN=(aT._hasScroll(aO,"left")?aO.scrollWidth:aR);aV=(aT._hasScroll(aO)?aO.scrollHeight:aK);aT.parentData={element:aO,left:aU.left,top:aU.top,width:aN,height:aV}}},resize:function(aL){var aR,aW,aQ,aO,aS=ax(this).resizable("instance"),aN=aS.options,aU=aS.containerOffset,aT=aS.position,aV=aS._aspectRatio||aL.shiftKey,aK={top:0,left:0},aM=aS.containerElement,aP=true;if(aM[0]!==document&&(/static/).test(aM.css("position"))){aK=aU}if(aT.left<(aS._helper?aU.left:0)){aS.size.width=aS.size.width+(aS._helper?(aS.position.left-aU.left):(aS.position.left-aK.left));if(aV){aS.size.height=aS.size.width/aS.aspectRatio;aP=false}aS.position.left=aN.helper?aU.left:0}if(aT.top<(aS._helper?aU.top:0)){aS.size.height=aS.size.height+(aS._helper?(aS.position.top-aU.top):aS.position.top);if(aV){aS.size.width=aS.size.height*aS.aspectRatio;aP=false}aS.position.top=aS._helper?aU.top:0}aQ=aS.containerElement.get(0)===aS.element.parent().get(0);aO=/relative|absolute/.test(aS.containerElement.css("position"));if(aQ&&aO){aS.offset.left=aS.parentData.left+aS.position.left;aS.offset.top=aS.parentData.top+aS.position.top}else{aS.offset.left=aS.element.offset().left;aS.offset.top=aS.element.offset().top}aR=Math.abs(aS.sizeDiff.width+(aS._helper?aS.offset.left-aK.left:(aS.offset.left-aU.left)));aW=Math.abs(aS.sizeDiff.height+(aS._helper?aS.offset.top-aK.top:(aS.offset.top-aU.top)));if(aR+aS.size.width>=aS.parentData.width){aS.size.width=aS.parentData.width-aR;if(aV){aS.size.height=aS.size.width/aS.aspectRatio;aP=false}}if(aW+aS.size.height>=aS.parentData.height){aS.size.height=aS.parentData.height-aW;if(aV){aS.size.width=aS.size.height*aS.aspectRatio;aP=false}}if(!aP){aS.position.left=aS.prevPosition.left;aS.position.top=aS.prevPosition.top;aS.size.width=aS.prevSize.width;aS.size.height=aS.prevSize.height}},stop:function(){var aP=ax(this).resizable("instance"),aL=aP.options,aQ=aP.containerOffset,aK=aP.containerPosition,aM=aP.containerElement,aN=ax(aP.helper),aS=aN.offset(),aR=aN.outerWidth()-aP.sizeDiff.width,aO=aN.outerHeight()-aP.sizeDiff.height;if(aP._helper&&!aL.animate&&(/relative/).test(aM.css("position"))){ax(this).css({left:aS.left-aK.left-aQ.left,width:aR,height:aO})}if(aP._helper&&!aL.animate&&(/static/).test(aM.css("position"))){ax(this).css({left:aS.left-aK.left-aQ.left,width:aR,height:aO})}}});ax.ui.plugin.add("resizable","alsoResize",{start:function(){var aK=ax(this).resizable("instance"),aL=aK.options;ax(aL.alsoResize).each(function(){var aM=ax(this);aM.data("ui-resizable-alsoresize",{width:parseFloat(aM.width()),height:parseFloat(aM.height()),left:parseFloat(aM.css("left")),top:parseFloat(aM.css("top"))})})},resize:function(aL,aN){var aK=ax(this).resizable("instance"),aO=aK.options,aM=aK.originalSize,aQ=aK.originalPosition,aP={height:(aK.size.height-aM.height)||0,width:(aK.size.width-aM.width)||0,top:(aK.position.top-aQ.top)||0,left:(aK.position.left-aQ.left)||0};ax(aO.alsoResize).each(function(){var aT=ax(this),aU=ax(this).data("ui-resizable-alsoresize"),aS={},aR=aT.parents(aN.originalElement[0]).length?["width","height"]:["width","height","top","left"];ax.each(aR,function(aV,aX){var aW=(aU[aX]||0)+(aP[aX]||0);if(aW&&aW>=0){aS[aX]=aW||null}});aT.css(aS)})},stop:function(){ax(this).removeData("ui-resizable-alsoresize")}});ax.ui.plugin.add("resizable","ghost",{start:function(){var aL=ax(this).resizable("instance"),aK=aL.size;aL.ghost=aL.originalElement.clone();aL.ghost.css({opacity:0.25,display:"block",position:"relative",height:aK.height,width:aK.width,margin:0,left:0,top:0});aL._addClass(aL.ghost,"ui-resizable-ghost");if(ax.uiBackCompat!==false&&typeof aL.options.ghost==="string"){aL.ghost.addClass(this.options.ghost)}aL.ghost.appendTo(aL.helper)},resize:function(){var aK=ax(this).resizable("instance");if(aK.ghost){aK.ghost.css({position:"relative",height:aK.size.height,width:aK.size.width})}},stop:function(){var aK=ax(this).resizable("instance");if(aK.ghost&&aK.helper){aK.helper.get(0).removeChild(aK.ghost.get(0))}}});ax.ui.plugin.add("resizable","grid",{resize:function(){var aN,aS=ax(this).resizable("instance"),aW=aS.options,aQ=aS.size,aR=aS.originalSize,aT=aS.originalPosition,a1=aS.axis,aK=typeof aW.grid==="number"?[aW.grid,aW.grid]:aW.grid,aZ=(aK[0]||1),aY=(aK[1]||1),aP=Math.round((aQ.width-aR.width)/aZ)*aZ,aO=Math.round((aQ.height-aR.height)/aY)*aY,aU=aR.width+aP,aX=aR.height+aO,aM=aW.maxWidth&&(aW.maxWidth<aU),aV=aW.maxHeight&&(aW.maxHeight<aX),a0=aW.minWidth&&(aW.minWidth>aU),aL=aW.minHeight&&(aW.minHeight>aX);aW.grid=aK;if(a0){aU+=aZ}if(aL){aX+=aY}if(aM){aU-=aZ}if(aV){aX-=aY}if(/^(se|s|e)$/.test(a1)){aS.size.width=aU;aS.size.height=aX}else{if(/^(ne)$/.test(a1)){aS.size.width=aU;aS.size.height=aX;aS.position.top=aT.top-aO}else{if(/^(sw)$/.test(a1)){aS.size.width=aU;aS.size.height=aX;aS.position.left=aT.left-aP}else{if(aX-aY<=0||aU-aZ<=0){aN=aS._getPaddingPlusBorderDimensions(this)}if(aX-aY>0){aS.size.height=aX;aS.position.top=aT.top-aO}else{aX=aY-aN.height;aS.size.height=aX;aS.position.top=aT.top+aR.height-aX}if(aU-aZ>0){aS.size.width=aU;aS.position.left=aT.left-aP}else{aU=aZ-aN.width;aS.size.width=aU;aS.position.left=aT.left+aR.width-aU}}}}}});var H=ax.ui.resizable;
/*!
 * jQuery UI Selectable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var u=ax.widget("ui.selectable",ax.ui.mouse,{version:"1.13.0",options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var aK=this;this._addClass("ui-selectable");this.dragged=false;this.refresh=function(){aK.elementPos=ax(aK.element[0]).offset();aK.selectees=ax(aK.options.filter,aK.element[0]);aK._addClass(aK.selectees,"ui-selectee");aK.selectees.each(function(){var aM=ax(this),aL=aM.offset(),aN={left:aL.left-aK.elementPos.left,top:aL.top-aK.elementPos.top};ax.data(this,"selectable-item",{element:this,$element:aM,left:aN.left,top:aN.top,right:aN.left+aM.outerWidth(),bottom:aN.top+aM.outerHeight(),startselected:false,selected:aM.hasClass("ui-selected"),selecting:aM.hasClass("ui-selecting"),unselecting:aM.hasClass("ui-unselecting")})})};this.refresh();this._mouseInit();this.helper=ax("<div>");this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item");this._mouseDestroy()},_mouseStart:function(aM){var aL=this,aK=this.options;this.opos=[aM.pageX,aM.pageY];this.elementPos=ax(this.element[0]).offset();if(this.options.disabled){return}this.selectees=ax(aK.filter,this.element[0]);this._trigger("start",aM);ax(aK.appendTo).append(this.helper);this.helper.css({left:aM.pageX,top:aM.pageY,width:0,height:0});if(aK.autoRefresh){this.refresh()}this.selectees.filter(".ui-selected").each(function(){var aN=ax.data(this,"selectable-item");aN.startselected=true;if(!aM.metaKey&&!aM.ctrlKey){aL._removeClass(aN.$element,"ui-selected");aN.selected=false;aL._addClass(aN.$element,"ui-unselecting");aN.unselecting=true;aL._trigger("unselecting",aM,{unselecting:aN.element})}});ax(aM.target).parents().addBack().each(function(){var aN,aO=ax.data(this,"selectable-item");if(aO){aN=(!aM.metaKey&&!aM.ctrlKey)||!aO.$element.hasClass("ui-selected");aL._removeClass(aO.$element,aN?"ui-unselecting":"ui-selected")._addClass(aO.$element,aN?"ui-selecting":"ui-unselecting");aO.unselecting=!aN;aO.selecting=aN;aO.selected=aN;if(aN){aL._trigger("selecting",aM,{selecting:aO.element})}else{aL._trigger("unselecting",aM,{unselecting:aO.element})}return false}})},_mouseDrag:function(aR){this.dragged=true;if(this.options.disabled){return}var aO,aQ=this,aM=this.options,aL=this.opos[0],aP=this.opos[1],aK=aR.pageX,aN=aR.pageY;if(aL>aK){aO=aK;aK=aL;aL=aO}if(aP>aN){aO=aN;aN=aP;aP=aO}this.helper.css({left:aL,top:aP,width:aK-aL,height:aN-aP});this.selectees.each(function(){var aS=ax.data(this,"selectable-item"),aT=false,aU={};if(!aS||aS.element===aQ.element[0]){return}aU.left=aS.left+aQ.elementPos.left;aU.right=aS.right+aQ.elementPos.left;aU.top=aS.top+aQ.elementPos.top;aU.bottom=aS.bottom+aQ.elementPos.top;if(aM.tolerance==="touch"){aT=(!(aU.left>aK||aU.right<aL||aU.top>aN||aU.bottom<aP))}else{if(aM.tolerance==="fit"){aT=(aU.left>aL&&aU.right<aK&&aU.top>aP&&aU.bottom<aN)}}if(aT){if(aS.selected){aQ._removeClass(aS.$element,"ui-selected");aS.selected=false}if(aS.unselecting){aQ._removeClass(aS.$element,"ui-unselecting");aS.unselecting=false}if(!aS.selecting){aQ._addClass(aS.$element,"ui-selecting");aS.selecting=true;aQ._trigger("selecting",aR,{selecting:aS.element})}}else{if(aS.selecting){if((aR.metaKey||aR.ctrlKey)&&aS.startselected){aQ._removeClass(aS.$element,"ui-selecting");aS.selecting=false;aQ._addClass(aS.$element,"ui-selected");aS.selected=true}else{aQ._removeClass(aS.$element,"ui-selecting");aS.selecting=false;if(aS.startselected){aQ._addClass(aS.$element,"ui-unselecting");aS.unselecting=true}aQ._trigger("unselecting",aR,{unselecting:aS.element})}}if(aS.selected){if(!aR.metaKey&&!aR.ctrlKey&&!aS.startselected){aQ._removeClass(aS.$element,"ui-selected");aS.selected=false;aQ._addClass(aS.$element,"ui-unselecting");aS.unselecting=true;aQ._trigger("unselecting",aR,{unselecting:aS.element})}}}});return false},_mouseStop:function(aL){var aK=this;this.dragged=false;ax(".ui-unselecting",this.element[0]).each(function(){var aM=ax.data(this,"selectable-item");aK._removeClass(aM.$element,"ui-unselecting");aM.unselecting=false;aM.startselected=false;aK._trigger("unselected",aL,{unselected:aM.element})});ax(".ui-selecting",this.element[0]).each(function(){var aM=ax.data(this,"selectable-item");aK._removeClass(aM.$element,"ui-selecting")._addClass(aM.$element,"ui-selected");aM.selecting=false;aM.selected=true;aM.startselected=true;aK._trigger("selected",aL,{selected:aM.element})});this._trigger("stop",aL);this.helper.remove();return false}});
/*!
 * jQuery UI Sortable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var aa=ax.widget("ui.sortable",ax.ui.mouse,{version:"1.13.0",widgetEventPrefix:"sort",ready:false,options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(aL,aK,aM){return(aL>=aK)&&(aL<(aK+aM))},_isFloating:function(aK){return(/left|right/).test(aK.css("float"))||(/inline|table-cell/).test(aK.css("display"))},_create:function(){this.containerCache={};this._addClass("ui-sortable");this.refresh();this.offset=this.element.offset();this._mouseInit();this._setHandleClassName();this.ready=true},_setOption:function(aK,aL){this._super(aK,aL);if(aK==="handle"){this._setHandleClassName()}},_setHandleClassName:function(){var aK=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle");ax.each(this.items,function(){aK._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var aK=this.items.length-1;aK>=0;aK--){this.items[aK].item.removeData(this.widgetName+"-item")}return this},_mouseCapture:function(aM,aN){var aK=null,aO=false,aL=this;if(this.reverting){return false}if(this.options.disabled||this.options.type==="static"){return false}this._refreshItems(aM);ax(aM.target).parents().each(function(){if(ax.data(this,aL.widgetName+"-item")===aL){aK=ax(this);return false}});if(ax.data(aM.target,aL.widgetName+"-item")===aL){aK=ax(aM.target)}if(!aK){return false}if(this.options.handle&&!aN){ax(this.options.handle,aK).find("*").addBack().each(function(){if(this===aM.target){aO=true}});if(!aO){return false}}this.currentItem=aK;this._removeCurrentsFromItems();return true},_mouseStart:function(aN,aO,aL){var aM,aK,aP=this.options;this.currentContainer=this;this.refreshPositions();this.appendTo=ax(aP.appendTo!=="parent"?aP.appendTo:this.currentItem.parent());this.helper=this._createHelper(aN);this._cacheHelperProportions();this._cacheMargins();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};ax.extend(this.offset,{click:{left:aN.pageX-this.offset.left,top:aN.pageY-this.offset.top},relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");if(aP.cursorAt){this._adjustOffsetFromHelper(aP.cursorAt)}this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!==this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();this.scrollParent=this.placeholder.scrollParent();ax.extend(this.offset,{parent:this._getParentOffset()});if(aP.containment){this._setContainment()}if(aP.cursor&&aP.cursor!=="auto"){aK=this.document.find("body");this.storedCursor=aK.css("cursor");aK.css("cursor",aP.cursor);this.storedStylesheet=ax("<style>*{ cursor: "+aP.cursor+" !important; }</style>").appendTo(aK)}if(aP.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",aP.zIndex)}if(aP.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",aP.opacity)}if(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0].tagName!=="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",aN,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!aL){for(aM=this.containers.length-1;aM>=0;aM--){this.containers[aM]._trigger("activate",aN,this._uiHash(this))}}if(ax.ui.ddmanager){ax.ui.ddmanager.current=this}if(ax.ui.ddmanager&&!aP.dropBehaviour){ax.ui.ddmanager.prepareOffsets(this,aN)}this.dragging=true;this._addClass(this.helper,"ui-sortable-helper");if(!this.helper.parent().is(this.appendTo)){this.helper.detach().appendTo(this.appendTo);this.offset.parent=this._getParentOffset()}this.position=this.originalPosition=this._generatePosition(aN);this.originalPageX=aN.pageX;this.originalPageY=aN.pageY;this.lastPositionAbs=this.positionAbs=this._convertPositionTo("absolute");this._mouseDrag(aN);return true},_scroll:function(aL){var aM=this.options,aK=false;if(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0].tagName!=="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-aL.pageY<aM.scrollSensitivity){this.scrollParent[0].scrollTop=aK=this.scrollParent[0].scrollTop+aM.scrollSpeed}else{if(aL.pageY-this.overflowOffset.top<aM.scrollSensitivity){this.scrollParent[0].scrollTop=aK=this.scrollParent[0].scrollTop-aM.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-aL.pageX<aM.scrollSensitivity){this.scrollParent[0].scrollLeft=aK=this.scrollParent[0].scrollLeft+aM.scrollSpeed}else{if(aL.pageX-this.overflowOffset.left<aM.scrollSensitivity){this.scrollParent[0].scrollLeft=aK=this.scrollParent[0].scrollLeft-aM.scrollSpeed}}}else{if(aL.pageY-this.document.scrollTop()<aM.scrollSensitivity){aK=this.document.scrollTop(this.document.scrollTop()-aM.scrollSpeed)}else{if(this.window.height()-(aL.pageY-this.document.scrollTop())<aM.scrollSensitivity){aK=this.document.scrollTop(this.document.scrollTop()+aM.scrollSpeed)}}if(aL.pageX-this.document.scrollLeft()<aM.scrollSensitivity){aK=this.document.scrollLeft(this.document.scrollLeft()-aM.scrollSpeed)}else{if(this.window.width()-(aL.pageX-this.document.scrollLeft())<aM.scrollSensitivity){aK=this.document.scrollLeft(this.document.scrollLeft()+aM.scrollSpeed)}}}return aK},_mouseDrag:function(aN){var aL,aM,aK,aP,aO=this.options;this.position=this._generatePosition(aN);this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!=="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!=="x"){this.helper[0].style.top=this.position.top+"px"}this._contactContainers(aN);if(this.innermostContainer!==null){if(aO.scroll){if(this._scroll(aN)!==false){this._refreshItemPositions(true);if(ax.ui.ddmanager&&!aO.dropBehaviour){ax.ui.ddmanager.prepareOffsets(this,aN)}}}this.dragDirection={vertical:this._getDragVerticalDirection(),horizontal:this._getDragHorizontalDirection()};for(aL=this.items.length-1;aL>=0;aL--){aM=this.items[aL];aK=aM.item[0];aP=this._intersectsWithPointer(aM);if(!aP){continue}if(aM.instance!==this.currentContainer){continue}if(aK!==this.currentItem[0]&&this.placeholder[aP===1?"next":"prev"]()[0]!==aK&&!ax.contains(this.placeholder[0],aK)&&(this.options.type==="semi-dynamic"?!ax.contains(this.element[0],aK):true)){this.direction=aP===1?"down":"up";if(this.options.tolerance==="pointer"||this._intersectsWithSides(aM)){this._rearrange(aN,aM)}else{break}this._trigger("change",aN,this._uiHash());break}}}if(ax.ui.ddmanager){ax.ui.ddmanager.drag(this,aN)}this._trigger("sort",aN,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(aM,aO){if(!aM){return}if(ax.ui.ddmanager&&!this.options.dropBehaviour){ax.ui.ddmanager.drop(this,aM)}if(this.options.revert){var aL=this,aP=this.placeholder.offset(),aK=this.options.axis,aN={};if(!aK||aK==="x"){aN.left=aP.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)}if(!aK||aK==="y"){aN.top=aP.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)}this.reverting=true;ax(this.helper).animate(aN,parseInt(this.options.revert,10)||500,function(){aL._clear(aM)})}else{this._clear(aM,aO)}return false},cancel:function(){if(this.dragging){this._mouseUp(new ax.Event("mouseup",{target:null}));if(this.options.helper==="original"){this.currentItem.css(this._storedCSS);this._removeClass(this.currentItem,"ui-sortable-helper")}else{this.currentItem.show()}for(var aK=this.containers.length-1;aK>=0;aK--){this.containers[aK]._trigger("deactivate",null,this._uiHash(this));if(this.containers[aK].containerCache.over){this.containers[aK]._trigger("out",null,this._uiHash(this));this.containers[aK].containerCache.over=0}}}if(this.placeholder){if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!=="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}ax.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){ax(this.domPosition.prev).after(this.currentItem)}else{ax(this.domPosition.parent).prepend(this.currentItem)}}return this},serialize:function(aM){var aK=this._getItemsAsjQuery(aM&&aM.connected),aL=[];aM=aM||{};ax(aK).each(function(){var aN=(ax(aM.item||this).attr(aM.attribute||"id")||"").match(aM.expression||(/(.+)[\-=_](.+)/));if(aN){aL.push((aM.key||aN[1]+"[]")+"="+(aM.key&&aM.expression?aN[1]:aN[2]))}});if(!aL.length&&aM.key){aL.push(aM.key+"=")}return aL.join("&")},toArray:function(aM){var aK=this._getItemsAsjQuery(aM&&aM.connected),aL=[];aM=aM||{};aK.each(function(){aL.push(ax(aM.item||this).attr(aM.attribute||"id")||"")});return aL},_intersectsWith:function(aV){var aM=this.positionAbs.left,aL=aM+this.helperProportions.width,aT=this.positionAbs.top,aS=aT+this.helperProportions.height,aN=aV.left,aK=aN+aV.width,aW=aV.top,aR=aW+aV.height,aX=this.offset.click.top,aQ=this.offset.click.left,aP=(this.options.axis==="x")||((aT+aX)>aW&&(aT+aX)<aR),aU=(this.options.axis==="y")||((aM+aQ)>aN&&(aM+aQ)<aK),aO=aP&&aU;if(this.options.tolerance==="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!=="pointer"&&this.helperProportions[this.floating?"width":"height"]>aV[this.floating?"width":"height"])){return aO}else{return(aN<aM+(this.helperProportions.width/2)&&aL-(this.helperProportions.width/2)<aK&&aW<aT+(this.helperProportions.height/2)&&aS-(this.helperProportions.height/2)<aR)}},_intersectsWithPointer:function(aM){var aL,aP,aN=(this.options.axis==="x")||this._isOverAxis(this.positionAbs.top+this.offset.click.top,aM.top,aM.height),aK=(this.options.axis==="y")||this._isOverAxis(this.positionAbs.left+this.offset.click.left,aM.left,aM.width),aO=aN&&aK;if(!aO){return false}aL=this.dragDirection.vertical;aP=this.dragDirection.horizontal;return this.floating?((aP==="right"||aL==="down")?2:1):(aL&&(aL==="down"?2:1))},_intersectsWithSides:function(aN){var aL=this._isOverAxis(this.positionAbs.top+this.offset.click.top,aN.top+(aN.height/2),aN.height),aM=this._isOverAxis(this.positionAbs.left+this.offset.click.left,aN.left+(aN.width/2),aN.width),aK=this.dragDirection.vertical,aO=this.dragDirection.horizontal;if(this.floating&&aO){return((aO==="right"&&aM)||(aO==="left"&&!aM))}else{return aK&&((aK==="down"&&aL)||(aK==="up"&&!aL))}},_getDragVerticalDirection:function(){var aK=this.positionAbs.top-this.lastPositionAbs.top;return aK!==0&&(aK>0?"down":"up")},_getDragHorizontalDirection:function(){var aK=this.positionAbs.left-this.lastPositionAbs.left;return aK!==0&&(aK>0?"right":"left")},refresh:function(aK){this._refreshItems(aK);this._setHandleClassName();this.refreshPositions();return this},_connectWith:function(){var aK=this.options;return aK.connectWith.constructor===String?[aK.connectWith]:aK.connectWith},_getItemsAsjQuery:function(aK){var aM,aL,aR,aO,aP=[],aN=[],aQ=this._connectWith();if(aQ&&aK){for(aM=aQ.length-1;aM>=0;aM--){aR=ax(aQ[aM],this.document[0]);for(aL=aR.length-1;aL>=0;aL--){aO=ax.data(aR[aL],this.widgetFullName);if(aO&&aO!==this&&!aO.options.disabled){aN.push([typeof aO.options.items==="function"?aO.options.items.call(aO.element):ax(aO.options.items,aO.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),aO])}}}}aN.push([typeof this.options.items==="function"?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):ax(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);function aS(){aP.push(this)}for(aM=aN.length-1;aM>=0;aM--){aN[aM][0].each(aS)}return ax(aP)},_removeCurrentsFromItems:function(){var aK=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=ax.grep(this.items,function(aM){for(var aL=0;aL<aK.length;aL++){if(aK[aL]===aM.item[0]){return false}}return true})},_refreshItems:function(aK){this.items=[];this.containers=[this];var aO,aM,aT,aP,aS,aL,aV,aU,aQ=this.items,aN=[[typeof this.options.items==="function"?this.options.items.call(this.element[0],aK,{item:this.currentItem}):ax(this.options.items,this.element),this]],aR=this._connectWith();if(aR&&this.ready){for(aO=aR.length-1;aO>=0;aO--){aT=ax(aR[aO],this.document[0]);for(aM=aT.length-1;aM>=0;aM--){aP=ax.data(aT[aM],this.widgetFullName);if(aP&&aP!==this&&!aP.options.disabled){aN.push([typeof aP.options.items==="function"?aP.options.items.call(aP.element[0],aK,{item:this.currentItem}):ax(aP.options.items,aP.element),aP]);this.containers.push(aP)}}}}for(aO=aN.length-1;aO>=0;aO--){aS=aN[aO][1];aL=aN[aO][0];for(aM=0,aU=aL.length;aM<aU;aM++){aV=ax(aL[aM]);aV.data(this.widgetName+"-item",aS);aQ.push({item:aV,instance:aS,width:0,height:0,left:0,top:0})}}},_refreshItemPositions:function(aK){var aM,aN,aL,aO;for(aM=this.items.length-1;aM>=0;aM--){aN=this.items[aM];if(this.currentContainer&&aN.instance!==this.currentContainer&&aN.item[0]!==this.currentItem[0]){continue}aL=this.options.toleranceElement?ax(this.options.toleranceElement,aN.item):aN.item;if(!aK){aN.width=aL.outerWidth();aN.height=aL.outerHeight()}aO=aL.offset();aN.left=aO.left;aN.top=aO.top}},refreshPositions:function(aK){this.floating=this.items.length?this.options.axis==="x"||this._isFloating(this.items[0].item):false;if(this.innermostContainer!==null){this._refreshItemPositions(aK)}var aL,aM;if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(aL=this.containers.length-1;aL>=0;aL--){aM=this.containers[aL].element.offset();this.containers[aL].containerCache.left=aM.left;this.containers[aL].containerCache.top=aM.top;this.containers[aL].containerCache.width=this.containers[aL].element.outerWidth();this.containers[aL].containerCache.height=this.containers[aL].element.outerHeight()}}return this},_createPlaceholder:function(aL){aL=aL||this;var aK,aN,aM=aL.options;if(!aM.placeholder||aM.placeholder.constructor===String){aK=aM.placeholder;aN=aL.currentItem[0].nodeName.toLowerCase();aM.placeholder={element:function(){var aO=ax("<"+aN+">",aL.document[0]);aL._addClass(aO,"ui-sortable-placeholder",aK||aL.currentItem[0].className)._removeClass(aO,"ui-sortable-helper");if(aN==="tbody"){aL._createTrPlaceholder(aL.currentItem.find("tr").eq(0),ax("<tr>",aL.document[0]).appendTo(aO))}else{if(aN==="tr"){aL._createTrPlaceholder(aL.currentItem,aO)}else{if(aN==="img"){aO.attr("src",aL.currentItem.attr("src"))}}}if(!aK){aO.css("visibility","hidden")}return aO},update:function(aO,aP){if(aK&&!aM.forcePlaceholderSize){return}if(!aP.height()||(aM.forcePlaceholderSize&&(aN==="tbody"||aN==="tr"))){aP.height(aL.currentItem.innerHeight()-parseInt(aL.currentItem.css("paddingTop")||0,10)-parseInt(aL.currentItem.css("paddingBottom")||0,10))}if(!aP.width()){aP.width(aL.currentItem.innerWidth()-parseInt(aL.currentItem.css("paddingLeft")||0,10)-parseInt(aL.currentItem.css("paddingRight")||0,10))}}}}aL.placeholder=ax(aM.placeholder.element.call(aL.element,aL.currentItem));aL.currentItem.after(aL.placeholder);aM.placeholder.update(aL,aL.placeholder)},_createTrPlaceholder:function(aL,aK){var aM=this;aL.children().each(function(){ax("<td>&#160;</td>",aM.document[0]).attr("colspan",ax(this).attr("colspan")||1).appendTo(aK)})},_contactContainers:function(aK){var aP,aN,aT,aQ,aR,aV,aW,aO,aS,aM,aL=null,aU=null;for(aP=this.containers.length-1;aP>=0;aP--){if(ax.contains(this.currentItem[0],this.containers[aP].element[0])){continue}if(this._intersectsWith(this.containers[aP].containerCache)){if(aL&&ax.contains(this.containers[aP].element[0],aL.element[0])){continue}aL=this.containers[aP];aU=aP}else{if(this.containers[aP].containerCache.over){this.containers[aP]._trigger("out",aK,this._uiHash(this));this.containers[aP].containerCache.over=0}}}this.innermostContainer=aL;if(!aL){return}if(this.containers.length===1){if(!this.containers[aU].containerCache.over){this.containers[aU]._trigger("over",aK,this._uiHash(this));this.containers[aU].containerCache.over=1}}else{aT=10000;aQ=null;aS=aL.floating||this._isFloating(this.currentItem);aR=aS?"left":"top";aV=aS?"width":"height";aM=aS?"pageX":"pageY";for(aN=this.items.length-1;aN>=0;aN--){if(!ax.contains(this.containers[aU].element[0],this.items[aN].item[0])){continue}if(this.items[aN].item[0]===this.currentItem[0]){continue}aW=this.items[aN].item.offset()[aR];aO=false;if(aK[aM]-aW>this.items[aN][aV]/2){aO=true}if(Math.abs(aK[aM]-aW)<aT){aT=Math.abs(aK[aM]-aW);aQ=this.items[aN];this.direction=aO?"up":"down"}}if(!aQ&&!this.options.dropOnEmpty){return}if(this.currentContainer===this.containers[aU]){if(!this.currentContainer.containerCache.over){this.containers[aU]._trigger("over",aK,this._uiHash());this.currentContainer.containerCache.over=1}return}if(aQ){this._rearrange(aK,aQ,null,true)}else{this._rearrange(aK,null,this.containers[aU].element,true)}this._trigger("change",aK,this._uiHash());this.containers[aU]._trigger("change",aK,this._uiHash(this));this.currentContainer=this.containers[aU];this.options.placeholder.update(this.currentContainer,this.placeholder);this.scrollParent=this.placeholder.scrollParent();if(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0].tagName!=="HTML"){this.overflowOffset=this.scrollParent.offset()}this.containers[aU]._trigger("over",aK,this._uiHash(this));this.containers[aU].containerCache.over=1}},_createHelper:function(aL){var aM=this.options,aK=typeof aM.helper==="function"?ax(aM.helper.apply(this.element[0],[aL,this.currentItem])):(aM.helper==="clone"?this.currentItem.clone():this.currentItem);if(!aK.parents("body").length){this.appendTo[0].appendChild(aK[0])}if(aK[0]===this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(!aK[0].style.width||aM.forceHelperSize){aK.width(this.currentItem.width())}if(!aK[0].style.height||aM.forceHelperSize){aK.height(this.currentItem.height())}return aK},_adjustOffsetFromHelper:function(aK){if(typeof aK==="string"){aK=aK.split(" ")}if(Array.isArray(aK)){aK={left:+aK[0],top:+aK[1]||0}}if("left" in aK){this.offset.click.left=aK.left+this.margins.left}if("right" in aK){this.offset.click.left=this.helperProportions.width-aK.right+this.margins.left}if("top" in aK){this.offset.click.top=aK.top+this.margins.top}if("bottom" in aK){this.offset.click.top=this.helperProportions.height-aK.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var aK=this.offsetParent.offset();if(this.cssPosition==="absolute"&&this.scrollParent[0]!==this.document[0]&&ax.contains(this.scrollParent[0],this.offsetParent[0])){aK.left+=this.scrollParent.scrollLeft();aK.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]===this.document[0].body||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()==="html"&&ax.ui.ie)){aK={top:0,left:0}}return{top:aK.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:aK.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition==="relative"){var aK=this.currentItem.position();return{top:aK.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:aK.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var aL,aN,aK,aM=this.options;if(aM.containment==="parent"){aM.containment=this.helper[0].parentNode}if(aM.containment==="document"||aM.containment==="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,aM.containment==="document"?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,(aM.containment==="document"?(this.document.height()||document.body.parentNode.scrollHeight):this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(aM.containment)){aL=ax(aM.containment)[0];aN=ax(aM.containment).offset();aK=(ax(aL).css("overflow")!=="hidden");this.containment=[aN.left+(parseInt(ax(aL).css("borderLeftWidth"),10)||0)+(parseInt(ax(aL).css("paddingLeft"),10)||0)-this.margins.left,aN.top+(parseInt(ax(aL).css("borderTopWidth"),10)||0)+(parseInt(ax(aL).css("paddingTop"),10)||0)-this.margins.top,aN.left+(aK?Math.max(aL.scrollWidth,aL.offsetWidth):aL.offsetWidth)-(parseInt(ax(aL).css("borderLeftWidth"),10)||0)-(parseInt(ax(aL).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,aN.top+(aK?Math.max(aL.scrollHeight,aL.offsetHeight):aL.offsetHeight)-(parseInt(ax(aL).css("borderTopWidth"),10)||0)-(parseInt(ax(aL).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(aM,aO){if(!aO){aO=this.position}var aL=aM==="absolute"?1:-1,aK=this.cssPosition==="absolute"&&!(this.scrollParent[0]!==this.document[0]&&ax.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,aN=(/(html|body)/i).test(aK[0].tagName);return{top:(aO.top+this.offset.relative.top*aL+this.offset.parent.top*aL-((this.cssPosition==="fixed"?-this.scrollParent.scrollTop():(aN?0:aK.scrollTop()))*aL)),left:(aO.left+this.offset.relative.left*aL+this.offset.parent.left*aL-((this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():aN?0:aK.scrollLeft())*aL))}},_generatePosition:function(aN){var aP,aO,aQ=this.options,aM=aN.pageX,aL=aN.pageY,aK=this.cssPosition==="absolute"&&!(this.scrollParent[0]!==this.document[0]&&ax.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,aR=(/(html|body)/i).test(aK[0].tagName);if(this.cssPosition==="relative"&&!(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}if(this.originalPosition){if(this.containment){if(aN.pageX-this.offset.click.left<this.containment[0]){aM=this.containment[0]+this.offset.click.left}if(aN.pageY-this.offset.click.top<this.containment[1]){aL=this.containment[1]+this.offset.click.top}if(aN.pageX-this.offset.click.left>this.containment[2]){aM=this.containment[2]+this.offset.click.left}if(aN.pageY-this.offset.click.top>this.containment[3]){aL=this.containment[3]+this.offset.click.top}}if(aQ.grid){aP=this.originalPageY+Math.round((aL-this.originalPageY)/aQ.grid[1])*aQ.grid[1];aL=this.containment?((aP-this.offset.click.top>=this.containment[1]&&aP-this.offset.click.top<=this.containment[3])?aP:((aP-this.offset.click.top>=this.containment[1])?aP-aQ.grid[1]:aP+aQ.grid[1])):aP;aO=this.originalPageX+Math.round((aM-this.originalPageX)/aQ.grid[0])*aQ.grid[0];aM=this.containment?((aO-this.offset.click.left>=this.containment[0]&&aO-this.offset.click.left<=this.containment[2])?aO:((aO-this.offset.click.left>=this.containment[0])?aO-aQ.grid[0]:aO+aQ.grid[0])):aO}}return{top:(aL-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+((this.cssPosition==="fixed"?-this.scrollParent.scrollTop():(aR?0:aK.scrollTop())))),left:(aM-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+((this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():aR?0:aK.scrollLeft())))}},_rearrange:function(aO,aN,aL,aM){if(aL){aL[0].appendChild(this.placeholder[0])}else{aN.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction==="down"?aN.item[0]:aN.item[0].nextSibling))}this.counter=this.counter?++this.counter:1;var aK=this.counter;this._delay(function(){if(aK===this.counter){this.refreshPositions(!aM)}})},_clear:function(aL,aN){this.reverting=false;var aK,aO=[];if(!this._noFinalSort&&this.currentItem.parent().length){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(aK in this._storedCSS){if(this._storedCSS[aK]==="auto"||this._storedCSS[aK]==="static"){this._storedCSS[aK]=""}}this.currentItem.css(this._storedCSS);this._removeClass(this.currentItem,"ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!aN){aO.push(function(aP){this._trigger("receive",aP,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!==this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!==this.currentItem.parent()[0])&&!aN){aO.push(function(aP){this._trigger("update",aP,this._uiHash())})}if(this!==this.currentContainer){if(!aN){aO.push(function(aP){this._trigger("remove",aP,this._uiHash())});aO.push((function(aP){return function(aQ){aP._trigger("receive",aQ,this._uiHash(this))}}).call(this,this.currentContainer));aO.push((function(aP){return function(aQ){aP._trigger("update",aQ,this._uiHash(this))}}).call(this,this.currentContainer))}}function aM(aR,aP,aQ){return function(aS){aQ._trigger(aR,aS,aP._uiHash(aP))}}for(aK=this.containers.length-1;aK>=0;aK--){if(!aN){aO.push(aM("deactivate",this,this.containers[aK]))}if(this.containers[aK].containerCache.over){aO.push(aM("out",this,this.containers[aK]));this.containers[aK].containerCache.over=0}}if(this.storedCursor){this.document.find("body").css("cursor",this.storedCursor);this.storedStylesheet.remove()}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex==="auto"?"":this._storedZIndex)}this.dragging=false;if(!aN){this._trigger("beforeStop",aL,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(!this.cancelHelperRemoval){if(this.helper[0]!==this.currentItem[0]){this.helper.remove()}this.helper=null}if(!aN){for(aK=0;aK<aO.length;aK++){aO[aK].call(this,aL)}this._trigger("stop",aL,this._uiHash())}this.fromOutside=false;return !this.cancelHelperRemoval},_trigger:function(){if(ax.Widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(aK){var aL=aK||this;return{helper:aL.helper,placeholder:aL.placeholder||ax([]),position:aL.position,originalPosition:aL.originalPosition,offset:aL.positionAbs,item:aL.currentItem,sender:aK?aK.element:null}}});
/*!
 * jQuery UI Accordion 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var d=ax.widget("ui.accordion",{version:"1.13.0",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:false,event:"click",header:function(aK){return aK.find("> li > :first-child").add(aK.find("> :not(li)").even())},heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var aK=this.options;this.prevShow=this.prevHide=ax();this._addClass("ui-accordion","ui-widget ui-helper-reset");this.element.attr("role","tablist");if(!aK.collapsible&&(aK.active===false||aK.active==null)){aK.active=0}this._processPanels();if(aK.active<0){aK.active+=this.headers.length}this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:!this.active.length?ax():this.active.next()}},_createIcons:function(){var aM,aL,aK=this.options.icons;if(aK){aM=ax("<span>");this._addClass(aM,"ui-accordion-header-icon","ui-icon "+aK.header);aM.prependTo(this.headers);aL=this.active.children(".ui-accordion-header-icon");this._removeClass(aL,aK.header)._addClass(aL,null,aK.activeHeader)._addClass(this.headers,"ui-accordion-icons")}},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons");this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var aK;this.element.removeAttr("role");this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId();this._destroyIcons();aK=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId();if(this.options.heightStyle!=="content"){aK.css("height","")}},_setOption:function(aK,aL){if(aK==="active"){this._activate(aL);return}if(aK==="event"){if(this.options.event){this._off(this.headers,this.options.event)}this._setupEvents(aL)}this._super(aK,aL);if(aK==="collapsible"&&!aL&&this.options.active===false){this._activate(0)}if(aK==="icons"){this._destroyIcons();if(aL){this._createIcons()}}},_setOptionDisabled:function(aK){this._super(aK);this.element.attr("aria-disabled",aK);this._toggleClass(null,"ui-state-disabled",!!aK);this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!aK)},_keydown:function(aN){if(aN.altKey||aN.ctrlKey){return}var aO=ax.ui.keyCode,aM=this.headers.length,aK=this.headers.index(aN.target),aL=false;switch(aN.keyCode){case aO.RIGHT:case aO.DOWN:aL=this.headers[(aK+1)%aM];break;case aO.LEFT:case aO.UP:aL=this.headers[(aK-1+aM)%aM];break;case aO.SPACE:case aO.ENTER:this._eventHandler(aN);break;case aO.HOME:aL=this.headers[0];break;case aO.END:aL=this.headers[aM-1];break}if(aL){ax(aN.target).attr("tabIndex",-1);ax(aL).attr("tabIndex",0);ax(aL).trigger("focus");aN.preventDefault()}},_panelKeyDown:function(aK){if(aK.keyCode===ax.ui.keyCode.UP&&aK.ctrlKey){ax(aK.currentTarget).prev().trigger("focus")}},refresh:function(){var aK=this.options;this._processPanels();if((aK.active===false&&aK.collapsible===true)||!this.headers.length){aK.active=false;this.active=ax()}else{if(aK.active===false){this._activate(0)}else{if(this.active.length&&!ax.contains(this.element[0],this.active[0])){if(this.headers.length===this.headers.find(".ui-state-disabled").length){aK.active=false;this.active=ax()}else{this._activate(Math.max(0,aK.active-1))}}else{aK.active=this.headers.index(this.active)}}}this._destroyIcons();this._refresh()},_processPanels:function(){var aL=this.headers,aK=this.panels;if(typeof this.options.header==="function"){this.headers=this.options.header(this.element)}else{this.headers=this.element.find(this.options.header)}this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default");this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide();this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content");if(aK){this._off(aL.not(this.headers));this._off(aK.not(this.panels))}},_refresh:function(){var aN,aL=this.options,aK=aL.heightStyle,aM=this.element.parent();this.active=this._findActive(aL.active);this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed");this._addClass(this.active.next(),"ui-accordion-content-active");this.active.next().show();this.headers.attr("role","tab").each(function(){var aR=ax(this),aQ=aR.uniqueId().attr("id"),aO=aR.next(),aP=aO.uniqueId().attr("id");aR.attr("aria-controls",aP);aO.attr("aria-labelledby",aQ)}).next().attr("role","tabpanel");this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide();if(!this.active.length){this.headers.eq(0).attr("tabIndex",0)}else{this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"})}this._createIcons();this._setupEvents(aL.event);if(aK==="fill"){aN=aM.height();this.element.siblings(":visible").each(function(){var aP=ax(this),aO=aP.css("position");if(aO==="absolute"||aO==="fixed"){return}aN-=aP.outerHeight(true)});this.headers.each(function(){aN-=ax(this).outerHeight(true)});this.headers.next().each(function(){ax(this).height(Math.max(0,aN-ax(this).innerHeight()+ax(this).height()))}).css("overflow","auto")}else{if(aK==="auto"){aN=0;this.headers.next().each(function(){var aO=ax(this).is(":visible");if(!aO){ax(this).show()}aN=Math.max(aN,ax(this).css("height","").height());if(!aO){ax(this).hide()}}).height(aN)}}},_activate:function(aK){var aL=this._findActive(aK)[0];if(aL===this.active[0]){return}aL=aL||this.active[0];this._eventHandler({target:aL,currentTarget:aL,preventDefault:ax.noop})},_findActive:function(aK){return typeof aK==="number"?this.headers.eq(aK):ax()},_setupEvents:function(aL){var aK={keydown:"_keydown"};if(aL){ax.each(aL.split(" "),function(aN,aM){aK[aM]="_eventHandler"})}this._off(this.headers.add(this.headers.next()));this._on(this.headers,aK);this._on(this.headers.next(),{keydown:"_panelKeyDown"});this._hoverable(this.headers);this._focusable(this.headers)},_eventHandler:function(aL){var aM,aN,aU=this.options,aP=this.active,aQ=ax(aL.currentTarget),aS=aQ[0]===aP[0],aO=aS&&aU.collapsible,aK=aO?ax():aQ.next(),aR=aP.next(),aT={oldHeader:aP,oldPanel:aR,newHeader:aO?ax():aQ,newPanel:aK};aL.preventDefault();if((aS&&!aU.collapsible)||(this._trigger("beforeActivate",aL,aT)===false)){return}aU.active=aO?false:this.headers.index(aQ);this.active=aS?ax():aQ;this._toggle(aT);this._removeClass(aP,"ui-accordion-header-active","ui-state-active");if(aU.icons){aM=aP.children(".ui-accordion-header-icon");this._removeClass(aM,null,aU.icons.activeHeader)._addClass(aM,null,aU.icons.header)}if(!aS){this._removeClass(aQ,"ui-accordion-header-collapsed")._addClass(aQ,"ui-accordion-header-active","ui-state-active");if(aU.icons){aN=aQ.children(".ui-accordion-header-icon");this._removeClass(aN,null,aU.icons.header)._addClass(aN,null,aU.icons.activeHeader)}this._addClass(aQ.next(),"ui-accordion-content-active")}},_toggle:function(aM){var aK=aM.newPanel,aL=this.prevShow.length?this.prevShow:aM.oldPanel;this.prevShow.add(this.prevHide).stop(true,true);this.prevShow=aK;this.prevHide=aL;if(this.options.animate){this._animate(aK,aL,aM)}else{aL.hide();aK.show();this._toggleComplete(aM)}aL.attr({"aria-hidden":"true"});aL.prev().attr({"aria-selected":"false","aria-expanded":"false"});if(aK.length&&aL.length){aL.prev().attr({tabIndex:-1,"aria-expanded":"false"})}else{if(aK.length){this.headers.filter(function(){return parseInt(ax(this).attr("tabIndex"),10)===0}).attr("tabIndex",-1)}}aK.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(aK,aT,aP){var aS,aR,aO,aQ=this,aU=0,aN=aK.css("box-sizing"),aV=aK.length&&(!aT.length||(aK.index()<aT.index())),aM=this.options.animate||{},aW=aV&&aM.down||aM,aL=function(){aQ._toggleComplete(aP)};if(typeof aW==="number"){aO=aW}if(typeof aW==="string"){aR=aW}aR=aR||aW.easing||aM.easing;aO=aO||aW.duration||aM.duration;if(!aT.length){return aK.animate(this.showProps,aO,aR,aL)}if(!aK.length){return aT.animate(this.hideProps,aO,aR,aL)}aS=aK.show().outerHeight();aT.animate(this.hideProps,{duration:aO,easing:aR,step:function(aX,aY){aY.now=Math.round(aX)}});aK.hide().animate(this.showProps,{duration:aO,easing:aR,complete:aL,step:function(aX,aY){aY.now=Math.round(aX);if(aY.prop!=="height"){if(aN==="content-box"){aU+=aY.now}}else{if(aQ.options.heightStyle!=="content"){aY.now=Math.round(aS-aT.outerHeight()-aU);aU=0}}}})},_toggleComplete:function(aM){var aK=aM.oldPanel,aL=aK.prev();this._removeClass(aK,"ui-accordion-content-active");this._removeClass(aL,"ui-accordion-header-active")._addClass(aL,"ui-accordion-header-collapsed");if(aK.length){aK.parent()[0].className=aK.parent()[0].className}this._trigger("activate",null,aM)}});
/*!
 * jQuery UI Menu 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var r=ax.widget("ui.menu",{version:"1.13.0",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element;this.mouseHandled=false;this.lastMousePosition={x:null,y:null};this.element.uniqueId().attr({role:this.options.role,tabIndex:0});this._addClass("ui-menu","ui-widget ui-widget-content");this._on({"mousedown .ui-menu-item":function(aK){aK.preventDefault();this._activateItem(aK)},"click .ui-menu-item":function(aK){var aM=ax(aK.target);var aL=ax(ax.ui.safeActiveElement(this.document[0]));if(!this.mouseHandled&&aM.not(".ui-state-disabled").length){this.select(aK);if(!aK.isPropagationStopped()){this.mouseHandled=true}if(aM.has(".ui-menu").length){this.expand(aK)}else{if(!this.element.is(":focus")&&aL.closest(".ui-menu").length){this.element.trigger("focus",[true]);if(this.active&&this.active.parents(".ui-menu").length===1){clearTimeout(this.timer)}}}}},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(aM,aK){var aL=this.active||this._menuItems().first();if(!aK){this.focus(aM,aL)}},blur:function(aK){this._delay(function(){var aL=!ax.contains(this.element[0],ax.ui.safeActiveElement(this.document[0]));if(aL){this.collapseAll(aK)}})},keydown:"_keydown"});this.refresh();this._on(this.document,{click:function(aK){if(this._closeOnDocumentClick(aK)){this.collapseAll(aK,true)}this.mouseHandled=false}})},_activateItem:function(aK){if(this.previousFilter){return}if(aK.clientX===this.lastMousePosition.x&&aK.clientY===this.lastMousePosition.y){return}this.lastMousePosition={x:aK.clientX,y:aK.clientY};var aL=ax(aK.target).closest(".ui-menu-item"),aM=ax(aK.currentTarget);if(aL[0]!==aM[0]){return}if(aM.is(".ui-state-active")){return}this._removeClass(aM.siblings().children(".ui-state-active"),null,"ui-state-active");this.focus(aK,aM)},_destroy:function(){var aL=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),aK=aL.children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show();aK.children().each(function(){var aM=ax(this);if(aM.data("ui-menu-submenu-caret")){aM.remove()}})},_keydown:function(aO){var aL,aN,aP,aM,aK=true;switch(aO.keyCode){case ax.ui.keyCode.PAGE_UP:this.previousPage(aO);break;case ax.ui.keyCode.PAGE_DOWN:this.nextPage(aO);break;case ax.ui.keyCode.HOME:this._move("first","first",aO);break;case ax.ui.keyCode.END:this._move("last","last",aO);break;case ax.ui.keyCode.UP:this.previous(aO);break;case ax.ui.keyCode.DOWN:this.next(aO);break;case ax.ui.keyCode.LEFT:this.collapse(aO);break;case ax.ui.keyCode.RIGHT:if(this.active&&!this.active.is(".ui-state-disabled")){this.expand(aO)}break;case ax.ui.keyCode.ENTER:case ax.ui.keyCode.SPACE:this._activate(aO);break;case ax.ui.keyCode.ESCAPE:this.collapse(aO);break;default:aK=false;aN=this.previousFilter||"";aM=false;aP=aO.keyCode>=96&&aO.keyCode<=105?(aO.keyCode-96).toString():String.fromCharCode(aO.keyCode);clearTimeout(this.filterTimer);if(aP===aN){aM=true}else{aP=aN+aP}aL=this._filterMenuItems(aP);aL=aM&&aL.index(this.active.next())!==-1?this.active.nextAll(".ui-menu-item"):aL;if(!aL.length){aP=String.fromCharCode(aO.keyCode);aL=this._filterMenuItems(aP)}if(aL.length){this.focus(aO,aL);this.previousFilter=aP;this.filterTimer=this._delay(function(){delete this.previousFilter},1000)}else{delete this.previousFilter}}if(aK){aO.preventDefault()}},_activate:function(aK){if(this.active&&!this.active.is(".ui-state-disabled")){if(this.active.children("[aria-haspopup='true']").length){this.expand(aK)}else{this.select(aK)}}},refresh:function(){var aR,aM,aP,aN,aK,aQ=this,aO=this.options.icons.submenu,aL=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length);aP=aL.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var aU=ax(this),aS=aU.prev(),aT=ax("<span>").data("ui-menu-submenu-caret",true);aQ._addClass(aT,"ui-menu-icon","ui-icon "+aO);aS.attr("aria-haspopup","true").prepend(aT);aU.attr("aria-labelledby",aS.attr("id"))});this._addClass(aP,"ui-menu","ui-widget ui-widget-content ui-front");aR=aL.add(this.element);aM=aR.find(this.options.items);aM.not(".ui-menu-item").each(function(){var aS=ax(this);if(aQ._isDivider(aS)){aQ._addClass(aS,"ui-menu-divider","ui-widget-content")}});aN=aM.not(".ui-menu-item, .ui-menu-divider");aK=aN.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()});this._addClass(aN,"ui-menu-item")._addClass(aK,"ui-menu-item-wrapper");aM.filter(".ui-state-disabled").attr("aria-disabled","true");if(this.active&&!ax.contains(this.element[0],this.active[0])){this.blur()}},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(aL,aM){if(aL==="icons"){var aK=this.element.find(".ui-menu-icon");this._removeClass(aK,null,this.options.icons.submenu)._addClass(aK,null,aM.submenu)}this._super(aL,aM)},_setOptionDisabled:function(aK){this._super(aK);this.element.attr("aria-disabled",String(aK));this._toggleClass(null,"ui-state-disabled",!!aK)},focus:function(aM,aL){var aO,aN,aK;this.blur(aM,aM&&aM.type==="focus");this._scrollIntoView(aL);this.active=aL.first();aN=this.active.children(".ui-menu-item-wrapper");this._addClass(aN,null,"ui-state-active");if(this.options.role){this.element.attr("aria-activedescendant",aN.attr("id"))}aK=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper");this._addClass(aK,null,"ui-state-active");if(aM&&aM.type==="keydown"){this._close()}else{this.timer=this._delay(function(){this._close()},this.delay)}aO=aL.children(".ui-menu");if(aO.length&&aM&&(/^mouse/.test(aM.type))){this._startOpening(aO)}this.activeMenu=aL.parent();this._trigger("focus",aM,{item:aL})},_scrollIntoView:function(aN){var aQ,aM,aO,aK,aL,aP;if(this._hasScroll()){aQ=parseFloat(ax.css(this.activeMenu[0],"borderTopWidth"))||0;aM=parseFloat(ax.css(this.activeMenu[0],"paddingTop"))||0;aO=aN.offset().top-this.activeMenu.offset().top-aQ-aM;aK=this.activeMenu.scrollTop();aL=this.activeMenu.height();aP=aN.outerHeight();if(aO<0){this.activeMenu.scrollTop(aK+aO)}else{if(aO+aP>aL){this.activeMenu.scrollTop(aK+aO-aL+aP)}}}},blur:function(aL,aK){if(!aK){clearTimeout(this.timer)}if(!this.active){return}this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active");this._trigger("blur",aL,{item:this.active});this.active=null},_startOpening:function(aK){clearTimeout(this.timer);if(aK.attr("aria-hidden")!=="true"){return}this.timer=this._delay(function(){this._close();this._open(aK)},this.delay)},_open:function(aL){var aK=ax.extend({of:this.active},this.options.position);clearTimeout(this.timer);this.element.find(".ui-menu").not(aL.parents(".ui-menu")).hide().attr("aria-hidden","true");aL.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(aK)},collapseAll:function(aL,aK){clearTimeout(this.timer);this.timer=this._delay(function(){var aM=aK?this.element:ax(aL&&aL.target).closest(this.element.find(".ui-menu"));if(!aM.length){aM=this.element}this._close(aM);this.blur(aL);this._removeClass(aM.find(".ui-state-active"),null,"ui-state-active");this.activeMenu=aM},aK?0:this.delay)},_close:function(aK){if(!aK){aK=this.active?this.active.parent():this.element}aK.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(aK){return !ax(aK.target).closest(".ui-menu").length},_isDivider:function(aK){return !/[^\-\u2014\u2013\s]/.test(aK.text())},collapse:function(aL){var aK=this.active&&this.active.parent().closest(".ui-menu-item",this.element);if(aK&&aK.length){this._close();this.focus(aL,aK)}},expand:function(aL){var aK=this.active&&this._menuItems(this.active.children(".ui-menu")).first();if(aK&&aK.length){this._open(aK.parent());this._delay(function(){this.focus(aL,aK)})}},next:function(aK){this._move("next","first",aK)},previous:function(aK){this._move("prev","last",aK)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_menuItems:function(aK){return(aK||this.element).find(this.options.items).filter(".ui-menu-item")},_move:function(aN,aL,aM){var aK;if(this.active){if(aN==="first"||aN==="last"){aK=this.active[aN==="first"?"prevAll":"nextAll"](".ui-menu-item").last()}else{aK=this.active[aN+"All"](".ui-menu-item").first()}}if(!aK||!aK.length||!this.active){aK=this._menuItems(this.activeMenu)[aL]()}this.focus(aM,aK)},nextPage:function(aM){var aL,aN,aK;if(!this.active){this.next(aM);return}if(this.isLastItem()){return}if(this._hasScroll()){aN=this.active.offset().top;aK=this.element.innerHeight();if(ax.fn.jquery.indexOf("3.2.")===0){aK+=this.element[0].offsetHeight-this.element.outerHeight()}this.active.nextAll(".ui-menu-item").each(function(){aL=ax(this);return aL.offset().top-aN-aK<0});this.focus(aM,aL)}else{this.focus(aM,this._menuItems(this.activeMenu)[!this.active?"first":"last"]())}},previousPage:function(aM){var aL,aN,aK;if(!this.active){this.next(aM);return}if(this.isFirstItem()){return}if(this._hasScroll()){aN=this.active.offset().top;aK=this.element.innerHeight();if(ax.fn.jquery.indexOf("3.2.")===0){aK+=this.element[0].offsetHeight-this.element.outerHeight()}this.active.prevAll(".ui-menu-item").each(function(){aL=ax(this);return aL.offset().top-aN+aK>0});this.focus(aM,aL)}else{this.focus(aM,this._menuItems(this.activeMenu).first())}},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(aK){this.active=this.active||ax(aK.target).closest(".ui-menu-item");var aL={item:this.active};if(!this.active.has(".ui-menu").length){this.collapseAll(aK,true)}this._trigger("select",aK,aL)},_filterMenuItems:function(aM){var aK=aM.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),aL=new RegExp("^"+aK,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return aL.test(String.prototype.trim.call(ax(this).children(".ui-menu-item-wrapper").text()))})}});
/*!
 * jQuery UI Autocomplete 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.autocomplete",{version:"1.13.0",defaultElement:"<input>",options:{appendTo:null,autoFocus:false,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var aM,aK,aN,aP=this.element[0].nodeName.toLowerCase(),aO=aP==="textarea",aL=aP==="input";this.isMultiLine=aO||!aL&&this._isContentEditable(this.element);this.valueMethod=this.element[aO||aL?"val":"text"];this.isNewMenu=true;this._addClass("ui-autocomplete-input");this.element.attr("autocomplete","off");this._on(this.element,{keydown:function(aQ){if(this.element.prop("readOnly")){aM=true;aN=true;aK=true;return}aM=false;aN=false;aK=false;var aR=ax.ui.keyCode;switch(aQ.keyCode){case aR.PAGE_UP:aM=true;this._move("previousPage",aQ);break;case aR.PAGE_DOWN:aM=true;this._move("nextPage",aQ);break;case aR.UP:aM=true;this._keyEvent("previous",aQ);break;case aR.DOWN:aM=true;this._keyEvent("next",aQ);break;case aR.ENTER:if(this.menu.active){aM=true;aQ.preventDefault();this.menu.select(aQ)}break;case aR.TAB:if(this.menu.active){this.menu.select(aQ)}break;case aR.ESCAPE:if(this.menu.element.is(":visible")){if(!this.isMultiLine){this._value(this.term)}this.close(aQ);aQ.preventDefault()}break;default:aK=true;this._searchTimeout(aQ);break}},keypress:function(aQ){if(aM){aM=false;if(!this.isMultiLine||this.menu.element.is(":visible")){aQ.preventDefault()}return}if(aK){return}var aR=ax.ui.keyCode;switch(aQ.keyCode){case aR.PAGE_UP:this._move("previousPage",aQ);break;case aR.PAGE_DOWN:this._move("nextPage",aQ);break;case aR.UP:this._keyEvent("previous",aQ);break;case aR.DOWN:this._keyEvent("next",aQ);break}},input:function(aQ){if(aN){aN=false;aQ.preventDefault();return}this._searchTimeout(aQ)},focus:function(){this.selectedItem=null;this.previous=this._value()},blur:function(aQ){clearTimeout(this.searching);this.close(aQ);this._change(aQ)}});this._initSource();this.menu=ax("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().attr({unselectable:"on"}).menu("instance");this._addClass(this.menu.element,"ui-autocomplete","ui-front");this._on(this.menu.element,{mousedown:function(aQ){aQ.preventDefault()},menufocus:function(aS,aT){var aQ,aR;if(this.isNewMenu){this.isNewMenu=false;if(aS.originalEvent&&/^mouse/.test(aS.originalEvent.type)){this.menu.blur();this.document.one("mousemove",function(){ax(aS.target).trigger(aS.originalEvent)});return}}aR=aT.item.data("ui-autocomplete-item");if(false!==this._trigger("focus",aS,{item:aR})){if(aS.originalEvent&&/^key/.test(aS.originalEvent.type)){this._value(aR.value)}}aQ=aT.item.attr("aria-label")||aR.value;if(aQ&&String.prototype.trim.call(aQ).length){this.liveRegion.children().hide();ax("<div>").text(aQ).appendTo(this.liveRegion)}},menuselect:function(aS,aT){var aR=aT.item.data("ui-autocomplete-item"),aQ=this.previous;if(this.element[0]!==ax.ui.safeActiveElement(this.document[0])){this.element.trigger("focus");this.previous=aQ;this._delay(function(){this.previous=aQ;this.selectedItem=aR})}if(false!==this._trigger("select",aS,{item:aR})){this._value(aR.value)}this.term=this._value();this.close(aS);this.selectedItem=aR}});this.liveRegion=ax("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body);this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible");this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching);this.element.removeAttr("autocomplete");this.menu.element.remove();this.liveRegion.remove()},_setOption:function(aK,aL){this._super(aK,aL);if(aK==="source"){this._initSource()}if(aK==="appendTo"){this.menu.element.appendTo(this._appendTo())}if(aK==="disabled"&&aL&&this.xhr){this.xhr.abort()}},_isEventTargetInWidget:function(aK){var aL=this.menu.element[0];return aK.target===this.element[0]||aK.target===aL||ax.contains(aL,aK.target)},_closeOnClickOutside:function(aK){if(!this._isEventTargetInWidget(aK)){this.close()}},_appendTo:function(){var aK=this.options.appendTo;if(aK){aK=aK.jquery||aK.nodeType?ax(aK):this.document.find(aK).eq(0)}if(!aK||!aK[0]){aK=this.element.closest(".ui-front, dialog")}if(!aK.length){aK=this.document[0].body}return aK},_initSource:function(){var aM,aK,aL=this;if(Array.isArray(this.options.source)){aM=this.options.source;this.source=function(aO,aN){aN(ax.ui.autocomplete.filter(aM,aO.term))}}else{if(typeof this.options.source==="string"){aK=this.options.source;this.source=function(aO,aN){if(aL.xhr){aL.xhr.abort()}aL.xhr=ax.ajax({url:aK,data:aO,dataType:"json",success:function(aP){aN(aP)},error:function(){aN([])}})}}else{this.source=this.options.source}}},_searchTimeout:function(aK){clearTimeout(this.searching);this.searching=this._delay(function(){var aM=this.term===this._value(),aL=this.menu.element.is(":visible"),aN=aK.altKey||aK.ctrlKey||aK.metaKey||aK.shiftKey;if(!aM||(aM&&!aL&&!aN)){this.selectedItem=null;this.search(null,aK)}},this.options.delay)},search:function(aL,aK){aL=aL!=null?aL:this._value();this.term=this._value();if(aL.length<this.options.minLength){return this.close(aK)}if(this._trigger("search",aK)===false){return}return this._search(aL)},_search:function(aK){this.pending++;this._addClass("ui-autocomplete-loading");this.cancelSearch=false;this.source({term:aK},this._response())},_response:function(){var aK=++this.requestIndex;return function(aL){if(aK===this.requestIndex){this.__response(aL)}this.pending--;if(!this.pending){this._removeClass("ui-autocomplete-loading")}}.bind(this)},__response:function(aK){if(aK){aK=this._normalize(aK)}this._trigger("response",null,{content:aK});if(!this.options.disabled&&aK&&aK.length&&!this.cancelSearch){this._suggest(aK);this._trigger("open")}else{this._close()}},close:function(aK){this.cancelSearch=true;this._close(aK)},_close:function(aK){this._off(this.document,"mousedown");if(this.menu.element.is(":visible")){this.menu.element.hide();this.menu.blur();this.isNewMenu=true;this._trigger("close",aK)}},_change:function(aK){if(this.previous!==this._value()){this._trigger("change",aK,{item:this.selectedItem})}},_normalize:function(aK){if(aK.length&&aK[0].label&&aK[0].value){return aK}return ax.map(aK,function(aL){if(typeof aL==="string"){return{label:aL,value:aL}}return ax.extend({},aL,{label:aL.label||aL.value,value:aL.value||aL.label})})},_suggest:function(aK){var aL=this.menu.element.empty();this._renderMenu(aL,aK);this.isNewMenu=true;this.menu.refresh();aL.show();this._resizeMenu();aL.position(ax.extend({of:this.element},this.options.position));if(this.options.autoFocus){this.menu.next()}this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var aK=this.menu.element;aK.outerWidth(Math.max(aK.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(aL,aK){var aM=this;ax.each(aK,function(aN,aO){aM._renderItemData(aL,aO)})},_renderItemData:function(aK,aL){return this._renderItem(aK,aL).data("ui-autocomplete-item",aL)},_renderItem:function(aK,aL){return ax("<li>").append(ax("<div>").text(aL.label)).appendTo(aK)},_move:function(aL,aK){if(!this.menu.element.is(":visible")){this.search(null,aK);return}if(this.menu.isFirstItem()&&/^previous/.test(aL)||this.menu.isLastItem()&&/^next/.test(aL)){if(!this.isMultiLine){this._value(this.term)}this.menu.blur();return}this.menu[aL](aK)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(aL,aK){if(!this.isMultiLine||this.menu.element.is(":visible")){this._move(aL,aK);aK.preventDefault()}},_isContentEditable:function(aL){if(!aL.length){return false}var aK=aL.prop("contentEditable");if(aK==="inherit"){return this._isContentEditable(aL.parent())}return aK==="true"}});ax.extend(ax.ui.autocomplete,{escapeRegex:function(aK){return aK.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(aM,aK){var aL=new RegExp(ax.ui.autocomplete.escapeRegex(aK),"i");return ax.grep(aM,function(aN){return aL.test(aN.label||aN.value||aN)})}});ax.widget("ui.autocomplete",ax.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(aK){return aK+(aK>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(aL){var aK;this._superApply(arguments);if(this.options.disabled||this.cancelSearch){return}if(aL&&aL.length){aK=this.options.messages.results(aL.length)}else{aK=this.options.messages.noResults}this.liveRegion.children().hide();ax("<div>").text(aK).appendTo(this.liveRegion)}});var aB=ax.ui.autocomplete;
/*!
 * jQuery UI Controlgroup 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var g=/ui-corner-([a-z]){2,6}/g;var y=ax.widget("ui.controlgroup",{version:"1.13.0",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:true,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar");this.refresh()},_destroy:function(){this._callChildMethod("destroy");this.childWidgets.removeData("ui-controlgroup-data");this.element.removeAttr("role");if(this.options.items.controlgroupLabel){this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()}},_initWidgets:function(){var aL=this,aK=[];ax.each(this.options.items,function(aO,aM){var aP;var aN={};if(!aM){return}if(aO==="controlgroupLabel"){aP=aL.element.find(aM);aP.each(function(){var aQ=ax(this);if(aQ.children(".ui-controlgroup-label-contents").length){return}aQ.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")});aL._addClass(aP,null,"ui-widget ui-widget-content ui-state-default");aK=aK.concat(aP.get());return}if(!ax.fn[aO]){return}if(aL["_"+aO+"Options"]){aN=aL["_"+aO+"Options"]("middle")}else{aN={classes:{}}}aL.element.find(aM).each(function(){var aR=ax(this);var aQ=aR[aO]("instance");var aS=ax.widget.extend({},aN);if(aO==="button"&&aR.parent(".ui-spinner").length){return}if(!aQ){aQ=aR[aO]()[aO]("instance")}if(aQ){aS.classes=aL._resolveClassesValues(aS.classes,aQ)}aR[aO](aS);var aT=aR[aO]("widget");ax.data(aT[0],"ui-controlgroup-data",aQ?aQ:aR[aO]("instance"));aK.push(aT[0])})});this.childWidgets=ax(ax.uniqueSort(aK));this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(aK){this.childWidgets.each(function(){var aL=ax(this),aM=aL.data("ui-controlgroup-data");if(aM&&aM[aK]){aM[aK]()}})},_updateCornerClass:function(aM,aL){var aK="ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";var aN=this._buildSimpleOptions(aL,"label").classes.label;this._removeClass(aM,null,aK);this._addClass(aM,null,aN)},_buildSimpleOptions:function(aL,aM){var aN=this.options.direction==="vertical";var aK={classes:{}};aK.classes[aM]={middle:"",first:"ui-corner-"+(aN?"top":"left"),last:"ui-corner-"+(aN?"bottom":"right"),only:"ui-corner-all"}[aL];return aK},_spinnerOptions:function(aK){var aL=this._buildSimpleOptions(aK,"ui-spinner");aL.classes["ui-spinner-up"]="";aL.classes["ui-spinner-down"]="";return aL},_buttonOptions:function(aK){return this._buildSimpleOptions(aK,"ui-button")},_checkboxradioOptions:function(aK){return this._buildSimpleOptions(aK,"ui-checkboxradio-label")},_selectmenuOptions:function(aK){var aL=this.options.direction==="vertical";return{width:aL?"auto":false,classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(aL?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(aL?"top":"left")},last:{"ui-selectmenu-button-open":aL?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(aL?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[aK]}},_resolveClassesValues:function(aM,aL){var aK={};ax.each(aM,function(aN){var aO=aL.options.classes[aN]||"";aO=String.prototype.trim.call(aO.replace(g,""));aK[aN]=(aO+" "+aM[aN]).replace(/\s+/g," ")});return aK},_setOption:function(aK,aL){if(aK==="direction"){this._removeClass("ui-controlgroup-"+this.options.direction)}this._super(aK,aL);if(aK==="disabled"){this._callChildMethod(aL?"disable":"enable");return}this.refresh()},refresh:function(){var aK,aL=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction);if(this.options.direction==="horizontal"){this._addClass(null,"ui-helper-clearfix")}this._initWidgets();aK=this.childWidgets;if(this.options.onlyVisible){aK=aK.filter(":visible")}if(aK.length){ax.each(["first","last"],function(aO,aP){var aM=aK[aP]().data("ui-controlgroup-data");if(aM&&aL["_"+aM.widgetName+"Options"]){var aN=aL["_"+aM.widgetName+"Options"](aK.length===1?"only":aP);aN.classes=aL._resolveClassesValues(aN.classes,aM);aM.element[aM.widgetName](aN)}else{aL._updateCornerClass(aK[aP](),aP)}});this._callChildMethod("refresh")}}});
/*!
 * jQuery UI Checkboxradio 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.checkboxradio",[ax.ui.formResetMixin,{version:"1.13.0",options:{disabled:null,label:null,icon:true,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var aL,aN;var aM=this;var aK=this._super()||{};this._readType();aN=this.element.labels();this.label=ax(aN[aN.length-1]);if(!this.label.length){ax.error("No label found for checkboxradio widget")}this.originalLabel="";this.label.contents().not(this.element[0]).each(function(){aM.originalLabel+=this.nodeType===3?ax(this).text():this.outerHTML});if(this.originalLabel){aK.label=this.originalLabel}aL=this.element[0].disabled;if(aL!=null){aK.disabled=aL}return aK},_create:function(){var aK=this.element[0].checked;this._bindFormResetHandler();if(this.options.disabled==null){this.options.disabled=this.element[0].disabled}this._setOption("disabled",this.options.disabled);this._addClass("ui-checkboxradio","ui-helper-hidden-accessible");this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget");if(this.type==="radio"){this._addClass(this.label,"ui-checkboxradio-radio-label")}if(this.options.label&&this.options.label!==this.originalLabel){this._updateLabel()}else{if(this.originalLabel){this.options.label=this.originalLabel}}this._enhance();if(aK){this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active")}this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var aK=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type;if(aK!=="input"||!/radio|checkbox/.test(this.type)){ax.error("Can't create checkboxradio on element.nodeName="+aK+" and element.type="+this.type)}},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var aM;var aK=this.element[0].name;var aL="input[name='"+ax.escapeSelector(aK)+"']";if(!aK){return ax([])}if(this.form.length){aM=ax(this.form[0].elements).filter(aL)}else{aM=ax(aL).filter(function(){return ax(this)._form().length===0})}return aM.not(this.element)},_toggleClasses:function(){var aK=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",aK);if(this.options.icon&&this.type==="checkbox"){this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",aK)._toggleClass(this.icon,null,"ui-icon-blank",!aK)}if(this.type==="radio"){this._getRadioGroup().each(function(){var aL=ax(this).checkboxradio("instance");if(aL){aL._removeClass(aL.label,"ui-checkboxradio-checked","ui-state-active")}})}},_destroy:function(){this._unbindFormResetHandler();if(this.icon){this.icon.remove();this.iconSpace.remove()}},_setOption:function(aK,aL){if(aK==="label"&&!aL){return}this._super(aK,aL);if(aK==="disabled"){this._toggleClass(this.label,null,"ui-state-disabled",aL);this.element[0].disabled=aL;return}this.refresh()},_updateIcon:function(aL){var aK="ui-icon ui-icon-background ";if(this.options.icon){if(!this.icon){this.icon=ax("<span>");this.iconSpace=ax("<span> </span>");this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")}if(this.type==="checkbox"){aK+=aL?"ui-icon-check ui-state-checked":"ui-icon-blank";this._removeClass(this.icon,null,aL?"ui-icon-blank":"ui-icon-check")}else{aK+="ui-icon-blank"}this._addClass(this.icon,"ui-checkboxradio-icon",aK);if(!aL){this._removeClass(this.icon,null,"ui-icon-check ui-state-checked")}this.icon.prependTo(this.label).after(this.iconSpace)}else{if(this.icon!==undefined){this.icon.remove();this.iconSpace.remove();delete this.icon}}},_updateLabel:function(){var aK=this.label.contents().not(this.element[0]);if(this.icon){aK=aK.not(this.icon[0])}if(this.iconSpace){aK=aK.not(this.iconSpace[0])}aK.remove();this.label.append(this.options.label)},refresh:function(){var aL=this.element[0].checked,aK=this.element[0].disabled;this._updateIcon(aL);this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",aL);if(this.options.label!==null){this._updateLabel()}if(aK!==this.options.disabled){this._setOptions({disabled:aK})}}}]);var aC=ax.ui.checkboxradio;
/*!
 * jQuery UI Button 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.button",{version:"1.13.0",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:true},_getCreateOptions:function(){var aL,aK=this._super()||{};this.isInput=this.element.is("input");aL=this.element[0].disabled;if(aL!=null){aK.disabled=aL}this.originalLabel=this.isInput?this.element.val():this.element.html();if(this.originalLabel){aK.label=this.originalLabel}return aK},_create:function(){if(!this.option.showLabel&!this.options.icon){this.options.showLabel=true}if(this.options.disabled==null){this.options.disabled=this.element[0].disabled||false}this.hasTitle=!!this.element.attr("title");if(this.options.label&&this.options.label!==this.originalLabel){if(this.isInput){this.element.val(this.options.label)}else{this.element.html(this.options.label)}}this._addClass("ui-button","ui-widget");this._setOption("disabled",this.options.disabled);this._enhance();if(this.element.is("a")){this._on({keyup:function(aK){if(aK.keyCode===ax.ui.keyCode.SPACE){aK.preventDefault();if(this.element[0].click){this.element[0].click()}else{this.element.trigger("click")}}}})}},_enhance:function(){if(!this.element.is("button")){this.element.attr("role","button")}if(this.options.icon){this._updateIcon("icon",this.options.icon);this._updateTooltip()}},_updateTooltip:function(){this.title=this.element.attr("title");if(!this.options.showLabel&&!this.title){this.element.attr("title",this.options.label)}},_updateIcon:function(aM,aO){var aL=aM!=="iconPosition",aK=aL?this.options.iconPosition:aO,aN=aK==="top"||aK==="bottom";if(!this.icon){this.icon=ax("<span>");this._addClass(this.icon,"ui-button-icon","ui-icon");if(!this.options.showLabel){this._addClass("ui-button-icon-only")}}else{if(aL){this._removeClass(this.icon,null,this.options.icon)}}if(aL){this._addClass(this.icon,null,aO)}this._attachIcon(aK);if(aN){this._addClass(this.icon,null,"ui-widget-icon-block");if(this.iconSpace){this.iconSpace.remove()}}else{if(!this.iconSpace){this.iconSpace=ax("<span> </span>");this._addClass(this.iconSpace,"ui-button-icon-space")}this._removeClass(this.icon,null,"ui-wiget-icon-block");this._attachIconSpace(aK)}},_destroy:function(){this.element.removeAttr("role");if(this.icon){this.icon.remove()}if(this.iconSpace){this.iconSpace.remove()}if(!this.hasTitle){this.element.removeAttr("title")}},_attachIconSpace:function(aK){this.icon[/^(?:end|bottom)/.test(aK)?"before":"after"](this.iconSpace)},_attachIcon:function(aK){this.element[/^(?:end|bottom)/.test(aK)?"append":"prepend"](this.icon)},_setOptions:function(aL){var aM=aL.showLabel===undefined?this.options.showLabel:aL.showLabel,aK=aL.icon===undefined?this.options.icon:aL.icon;if(!aM&&!aK){aL.showLabel=true}this._super(aL)},_setOption:function(aK,aL){if(aK==="icon"){if(aL){this._updateIcon(aK,aL)}else{if(this.icon){this.icon.remove();if(this.iconSpace){this.iconSpace.remove()}}}}if(aK==="iconPosition"){this._updateIcon(aK,aL)}if(aK==="showLabel"){this._toggleClass("ui-button-icon-only",null,!aL);this._updateTooltip()}if(aK==="label"){if(this.isInput){this.element.val(aL)}else{this.element.html(aL);if(this.icon){this._attachIcon(this.options.iconPosition);this._attachIconSpace(this.options.iconPosition)}}}this._super(aK,aL);if(aK==="disabled"){this._toggleClass(null,"ui-state-disabled",aL);this.element[0].disabled=aL;if(aL){this.element.trigger("blur")}}},refresh:function(){var aK=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");if(aK!==this.options.disabled){this._setOptions({disabled:aK})}this._updateTooltip()}});if(ax.uiBackCompat!==false){ax.widget("ui.button",ax.ui.button,{options:{text:true,icons:{primary:null,secondary:null}},_create:function(){if(this.options.showLabel&&!this.options.text){this.options.showLabel=this.options.text}if(!this.options.showLabel&&this.options.text){this.options.text=this.options.showLabel}if(!this.options.icon&&(this.options.icons.primary||this.options.icons.secondary)){if(this.options.icons.primary){this.options.icon=this.options.icons.primary}else{this.options.icon=this.options.icons.secondary;this.options.iconPosition="end"}}else{if(this.options.icon){this.options.icons.primary=this.options.icon}}this._super()},_setOption:function(aK,aL){if(aK==="text"){this._super("showLabel",aL);return}if(aK==="showLabel"){this.options.text=aL}if(aK==="icon"){this.options.icons.primary=aL}if(aK==="icons"){if(aL.primary){this._super("icon",aL.primary);this._super("iconPosition","beginning")}else{if(aL.secondary){this._super("icon",aL.secondary);this._super("iconPosition","end")}}}this._superApply(arguments)}});ax.fn.button=(function(aK){return function(aN){var aL=typeof aN==="string";var aM=Array.prototype.slice.call(arguments,1);var aO=this;if(aL){if(!this.length&&aN==="instance"){aO=undefined}else{this.each(function(){var aS;var aR=ax(this).attr("type");var aQ=aR!=="checkbox"&&aR!=="radio"?"button":"checkboxradio";var aP=ax.data(this,"ui-"+aQ);if(aN==="instance"){aO=aP;return false}if(!aP){return ax.error("cannot call methods on button prior to initialization; attempted to call method '"+aN+"'")}if(typeof aP[aN]!=="function"||aN.charAt(0)==="_"){return ax.error("no such method '"+aN+"' for button widget instance")}aS=aP[aN].apply(aP,aM);if(aS!==aP&&aS!==undefined){aO=aS&&aS.jquery?aO.pushStack(aS.get()):aS;return false}})}}else{if(aM.length){aN=ax.widget.extend.apply(null,[aN].concat(aM))}this.each(function(){var aR=ax(this).attr("type");var aQ=aR!=="checkbox"&&aR!=="radio"?"button":"checkboxradio";var aP=ax.data(this,"ui-"+aQ);if(aP){aP.option(aN||{});if(aP._init){aP._init()}}else{if(aQ==="button"){aK.call(ax(this),aN);return}ax(this).checkboxradio(ax.extend({icon:false},aN))}})}return aO}})(ax.fn.button);ax.fn.buttonset=function(){if(!ax.ui.controlgroup){ax.error("Controlgroup widget missing")}if(arguments[0]==="option"&&arguments[1]==="items"&&arguments[2]){return this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]])}if(arguments[0]==="option"&&arguments[1]==="items"){return this.controlgroup.apply(this,[arguments[0],"items.button"])}if(typeof arguments[0]==="object"&&arguments[0].items){arguments[0].items={button:arguments[0].items}}return this.controlgroup.apply(this,arguments)}}var I=ax.ui.button;
/*!
 * jQuery UI Datepicker 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.extend(ax.ui,{datepicker:{version:"1.13.0"}});var aF;function ao(aL){var aK,aM;while(aL.length&&aL[0]!==document){aK=aL.css("position");if(aK==="absolute"||aK==="relative"||aK==="fixed"){aM=parseInt(aL.css("zIndex"),10);if(!isNaN(aM)&&aM!==0){return aM}}aL=aL.parent()}return 0}function W(){this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:"",selectMonthLabel:"Select month",selectYearLabel:"Select year"};this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,onUpdateDatepicker:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false,disabled:false};ax.extend(this._defaults,this.regional[""]);this.regional.en=ax.extend(true,{},this.regional[""]);this.regional["en-US"]=ax.extend(true,{},this.regional.en);this.dpDiv=af(ax("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}ax.extend(W.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(aK){L(this._defaults,aK||{});return this},_attachDatepicker:function(aN,aK){var aO,aM,aL;aO=aN.nodeName.toLowerCase();aM=(aO==="div"||aO==="span");if(!aN.id){this.uuid+=1;aN.id="dp"+this.uuid}aL=this._newInst(ax(aN),aM);aL.settings=ax.extend({},aK||{});if(aO==="input"){this._connectDatepicker(aN,aL)}else{if(aM){this._inlineDatepicker(aN,aL)}}},_newInst:function(aL,aK){var aM=aL[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:aM,input:aL,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:aK,dpDiv:(!aK?this.dpDiv:af(ax("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}},_connectDatepicker:function(aM,aL){var aK=ax(aM);aL.append=ax([]);aL.trigger=ax([]);if(aK.hasClass(this.markerClassName)){return}this._attachments(aK,aL);aK.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp);this._autoSize(aL);ax.data(aM,"datepicker",aL);if(aL.settings.disabled){this._disableDatepicker(aM)}},_attachments:function(aM,aP){var aL,aO,aK,aQ=this._get(aP,"appendText"),aN=this._get(aP,"isRTL");if(aP.append){aP.append.remove()}if(aQ){aP.append=ax("<span>").addClass(this._appendClass).text(aQ);aM[aN?"before":"after"](aP.append)}aM.off("focus",this._showDatepicker);if(aP.trigger){aP.trigger.remove()}aL=this._get(aP,"showOn");if(aL==="focus"||aL==="both"){aM.on("focus",this._showDatepicker)}if(aL==="button"||aL==="both"){aO=this._get(aP,"buttonText");aK=this._get(aP,"buttonImage");if(this._get(aP,"buttonImageOnly")){aP.trigger=ax("<img>").addClass(this._triggerClass).attr({src:aK,alt:aO,title:aO})}else{aP.trigger=ax("<button type='button'>").addClass(this._triggerClass);if(aK){aP.trigger.html(ax("<img>").attr({src:aK,alt:aO,title:aO}))}else{aP.trigger.text(aO)}}aM[aN?"before":"after"](aP.trigger);aP.trigger.on("click",function(){if(ax.datepicker._datepickerShowing&&ax.datepicker._lastInput===aM[0]){ax.datepicker._hideDatepicker()}else{if(ax.datepicker._datepickerShowing&&ax.datepicker._lastInput!==aM[0]){ax.datepicker._hideDatepicker();ax.datepicker._showDatepicker(aM[0])}else{ax.datepicker._showDatepicker(aM[0])}}return false})}},_autoSize:function(aQ){if(this._get(aQ,"autoSize")&&!aQ.inline){var aN,aL,aM,aP,aO=new Date(2009,12-1,20),aK=this._get(aQ,"dateFormat");if(aK.match(/[DM]/)){aN=function(aR){aL=0;aM=0;for(aP=0;aP<aR.length;aP++){if(aR[aP].length>aL){aL=aR[aP].length;aM=aP}}return aM};aO.setMonth(aN(this._get(aQ,(aK.match(/MM/)?"monthNames":"monthNamesShort"))));aO.setDate(aN(this._get(aQ,(aK.match(/DD/)?"dayNames":"dayNamesShort")))+20-aO.getDay())}aQ.input.attr("size",this._formatDate(aQ,aO).length)}},_inlineDatepicker:function(aL,aK){var aM=ax(aL);if(aM.hasClass(this.markerClassName)){return}aM.addClass(this.markerClassName).append(aK.dpDiv);ax.data(aL,"datepicker",aK);this._setDate(aK,this._getDefaultDate(aK),true);this._updateDatepicker(aK);this._updateAlternate(aK);if(aK.settings.disabled){this._disableDatepicker(aL)}aK.dpDiv.css("display","block")},_dialogDatepicker:function(aR,aL,aP,aM,aQ){var aK,aU,aO,aT,aS,aN=this._dialogInst;if(!aN){this.uuid+=1;aK="dp"+this.uuid;this._dialogInput=ax("<input type='text' id='"+aK+"' style='position: absolute; top: -100px; width: 0px;'/>");this._dialogInput.on("keydown",this._doKeyDown);ax("body").append(this._dialogInput);aN=this._dialogInst=this._newInst(this._dialogInput,false);aN.settings={};ax.data(this._dialogInput[0],"datepicker",aN)}L(aN.settings,aM||{});aL=(aL&&aL.constructor===Date?this._formatDate(aN,aL):aL);this._dialogInput.val(aL);this._pos=(aQ?(aQ.length?aQ:[aQ.pageX,aQ.pageY]):null);if(!this._pos){aU=document.documentElement.clientWidth;aO=document.documentElement.clientHeight;aT=document.documentElement.scrollLeft||document.body.scrollLeft;aS=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(aU/2)-100+aT,(aO/2)-150+aS]}this._dialogInput.css("left",(this._pos[0]+20)+"px").css("top",this._pos[1]+"px");aN.settings.onSelect=aP;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if(ax.blockUI){ax.blockUI(this.dpDiv)}ax.data(this._dialogInput[0],"datepicker",aN);return this},_destroyDatepicker:function(aM){var aN,aK=ax(aM),aL=ax.data(aM,"datepicker");if(!aK.hasClass(this.markerClassName)){return}aN=aM.nodeName.toLowerCase();ax.removeData(aM,"datepicker");if(aN==="input"){aL.append.remove();aL.trigger.remove();aK.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)}else{if(aN==="div"||aN==="span"){aK.removeClass(this.markerClassName).empty()}}if(aF===aL){aF=null;this._curInst=null}},_enableDatepicker:function(aN){var aO,aM,aK=ax(aN),aL=ax.data(aN,"datepicker");if(!aK.hasClass(this.markerClassName)){return}aO=aN.nodeName.toLowerCase();if(aO==="input"){aN.disabled=false;aL.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else{if(aO==="div"||aO==="span"){aM=aK.children("."+this._inlineClass);aM.children().removeClass("ui-state-disabled");aM.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",false)}}this._disabledInputs=ax.map(this._disabledInputs,function(aP){return(aP===aN?null:aP)})},_disableDatepicker:function(aN){var aO,aM,aK=ax(aN),aL=ax.data(aN,"datepicker");if(!aK.hasClass(this.markerClassName)){return}aO=aN.nodeName.toLowerCase();if(aO==="input"){aN.disabled=true;aL.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else{if(aO==="div"||aO==="span"){aM=aK.children("."+this._inlineClass);aM.children().addClass("ui-state-disabled");aM.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",true)}}this._disabledInputs=ax.map(this._disabledInputs,function(aP){return(aP===aN?null:aP)});this._disabledInputs[this._disabledInputs.length]=aN},_isDisabledDatepicker:function(aL){if(!aL){return false}for(var aK=0;aK<this._disabledInputs.length;aK++){if(this._disabledInputs[aK]===aL){return true}}return false},_getInst:function(aL){try{return ax.data(aL,"datepicker")}catch(aK){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(aQ,aL,aP){var aM,aK,aO,aR,aN=this._getInst(aQ);if(arguments.length===2&&typeof aL==="string"){return(aL==="defaults"?ax.extend({},ax.datepicker._defaults):(aN?(aL==="all"?ax.extend({},aN.settings):this._get(aN,aL)):null))}aM=aL||{};if(typeof aL==="string"){aM={};aM[aL]=aP}if(aN){if(this._curInst===aN){this._hideDatepicker()}aK=this._getDateDatepicker(aQ,true);aO=this._getMinMaxDate(aN,"min");aR=this._getMinMaxDate(aN,"max");L(aN.settings,aM);if(aO!==null&&aM.dateFormat!==undefined&&aM.minDate===undefined){aN.settings.minDate=this._formatDate(aN,aO)}if(aR!==null&&aM.dateFormat!==undefined&&aM.maxDate===undefined){aN.settings.maxDate=this._formatDate(aN,aR)}if("disabled" in aM){if(aM.disabled){this._disableDatepicker(aQ)}else{this._enableDatepicker(aQ)}}this._attachments(ax(aQ),aN);this._autoSize(aN);this._setDate(aN,aK);this._updateAlternate(aN);this._updateDatepicker(aN)}},_changeDatepicker:function(aM,aK,aL){this._optionDatepicker(aM,aK,aL)},_refreshDatepicker:function(aL){var aK=this._getInst(aL);if(aK){this._updateDatepicker(aK)}},_setDateDatepicker:function(aM,aK){var aL=this._getInst(aM);if(aL){this._setDate(aL,aK);this._updateDatepicker(aL);this._updateAlternate(aL)}},_getDateDatepicker:function(aM,aK){var aL=this._getInst(aM);if(aL&&!aL.inline){this._setDateFromField(aL,aK)}return(aL?this._getDate(aL):null)},_doKeyDown:function(aN){var aL,aK,aP,aO=ax.datepicker._getInst(aN.target),aQ=true,aM=aO.dpDiv.is(".ui-datepicker-rtl");aO._keyEvent=true;if(ax.datepicker._datepickerShowing){switch(aN.keyCode){case 9:ax.datepicker._hideDatepicker();aQ=false;break;case 13:aP=ax("td."+ax.datepicker._dayOverClass+":not(."+ax.datepicker._currentClass+")",aO.dpDiv);if(aP[0]){ax.datepicker._selectDay(aN.target,aO.selectedMonth,aO.selectedYear,aP[0])}aL=ax.datepicker._get(aO,"onSelect");if(aL){aK=ax.datepicker._formatDate(aO);aL.apply((aO.input?aO.input[0]:null),[aK,aO])}else{ax.datepicker._hideDatepicker()}return false;case 27:ax.datepicker._hideDatepicker();break;case 33:ax.datepicker._adjustDate(aN.target,(aN.ctrlKey?-ax.datepicker._get(aO,"stepBigMonths"):-ax.datepicker._get(aO,"stepMonths")),"M");break;case 34:ax.datepicker._adjustDate(aN.target,(aN.ctrlKey?+ax.datepicker._get(aO,"stepBigMonths"):+ax.datepicker._get(aO,"stepMonths")),"M");break;case 35:if(aN.ctrlKey||aN.metaKey){ax.datepicker._clearDate(aN.target)}aQ=aN.ctrlKey||aN.metaKey;break;case 36:if(aN.ctrlKey||aN.metaKey){ax.datepicker._gotoToday(aN.target)}aQ=aN.ctrlKey||aN.metaKey;break;case 37:if(aN.ctrlKey||aN.metaKey){ax.datepicker._adjustDate(aN.target,(aM?+1:-1),"D")}aQ=aN.ctrlKey||aN.metaKey;if(aN.originalEvent.altKey){ax.datepicker._adjustDate(aN.target,(aN.ctrlKey?-ax.datepicker._get(aO,"stepBigMonths"):-ax.datepicker._get(aO,"stepMonths")),"M")}break;case 38:if(aN.ctrlKey||aN.metaKey){ax.datepicker._adjustDate(aN.target,-7,"D")}aQ=aN.ctrlKey||aN.metaKey;break;case 39:if(aN.ctrlKey||aN.metaKey){ax.datepicker._adjustDate(aN.target,(aM?-1:+1),"D")}aQ=aN.ctrlKey||aN.metaKey;if(aN.originalEvent.altKey){ax.datepicker._adjustDate(aN.target,(aN.ctrlKey?+ax.datepicker._get(aO,"stepBigMonths"):+ax.datepicker._get(aO,"stepMonths")),"M")}break;case 40:if(aN.ctrlKey||aN.metaKey){ax.datepicker._adjustDate(aN.target,+7,"D")}aQ=aN.ctrlKey||aN.metaKey;break;default:aQ=false}}else{if(aN.keyCode===36&&aN.ctrlKey){ax.datepicker._showDatepicker(this)}else{aQ=false}}if(aQ){aN.preventDefault();aN.stopPropagation()}},_doKeyPress:function(aM){var aL,aK,aN=ax.datepicker._getInst(aM.target);if(ax.datepicker._get(aN,"constrainInput")){aL=ax.datepicker._possibleChars(ax.datepicker._get(aN,"dateFormat"));aK=String.fromCharCode(aM.charCode==null?aM.keyCode:aM.charCode);return aM.ctrlKey||aM.metaKey||(aK<" "||!aL||aL.indexOf(aK)>-1)}},_doKeyUp:function(aM){var aK,aN=ax.datepicker._getInst(aM.target);if(aN.input.val()!==aN.lastVal){try{aK=ax.datepicker.parseDate(ax.datepicker._get(aN,"dateFormat"),(aN.input?aN.input.val():null),ax.datepicker._getFormatConfig(aN));if(aK){ax.datepicker._setDateFromField(aN);ax.datepicker._updateAlternate(aN);ax.datepicker._updateDatepicker(aN)}}catch(aL){}}return true},_showDatepicker:function(aL){aL=aL.target||aL;if(aL.nodeName.toLowerCase()!=="input"){aL=ax("input",aL.parentNode)[0]}if(ax.datepicker._isDisabledDatepicker(aL)||ax.datepicker._lastInput===aL){return}var aN,aR,aM,aP,aQ,aK,aO;aN=ax.datepicker._getInst(aL);if(ax.datepicker._curInst&&ax.datepicker._curInst!==aN){ax.datepicker._curInst.dpDiv.stop(true,true);if(aN&&ax.datepicker._datepickerShowing){ax.datepicker._hideDatepicker(ax.datepicker._curInst.input[0])}}aR=ax.datepicker._get(aN,"beforeShow");aM=aR?aR.apply(aL,[aL,aN]):{};if(aM===false){return}L(aN.settings,aM);aN.lastVal=null;ax.datepicker._lastInput=aL;ax.datepicker._setDateFromField(aN);if(ax.datepicker._inDialog){aL.value=""}if(!ax.datepicker._pos){ax.datepicker._pos=ax.datepicker._findPos(aL);ax.datepicker._pos[1]+=aL.offsetHeight}aP=false;ax(aL).parents().each(function(){aP|=ax(this).css("position")==="fixed";return !aP});aQ={left:ax.datepicker._pos[0],top:ax.datepicker._pos[1]};ax.datepicker._pos=null;aN.dpDiv.empty();aN.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});ax.datepicker._updateDatepicker(aN);aQ=ax.datepicker._checkOffset(aN,aQ,aP);aN.dpDiv.css({position:(ax.datepicker._inDialog&&ax.blockUI?"static":(aP?"fixed":"absolute")),display:"none",left:aQ.left+"px",top:aQ.top+"px"});if(!aN.inline){aK=ax.datepicker._get(aN,"showAnim");aO=ax.datepicker._get(aN,"duration");aN.dpDiv.css("z-index",ao(ax(aL))+1);ax.datepicker._datepickerShowing=true;if(ax.effects&&ax.effects.effect[aK]){aN.dpDiv.show(aK,ax.datepicker._get(aN,"showOptions"),aO)}else{aN.dpDiv[aK||"show"](aK?aO:null)}if(ax.datepicker._shouldFocusInput(aN)){aN.input.trigger("focus")}ax.datepicker._curInst=aN}},_updateDatepicker:function(aN){this.maxRows=4;aF=aN;aN.dpDiv.empty().append(this._generateHTML(aN));this._attachHandlers(aN);var aQ,aK=this._getNumberOfMonths(aN),aP=aK[1],aM=17,aL=aN.dpDiv.find("."+this._dayOverClass+" a"),aO=ax.datepicker._get(aN,"onUpdateDatepicker");if(aL.length>0){R.apply(aL.get(0))}aN.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");if(aP>1){aN.dpDiv.addClass("ui-datepicker-multi-"+aP).css("width",(aM*aP)+"em")}aN.dpDiv[(aK[0]!==1||aK[1]!==1?"add":"remove")+"Class"]("ui-datepicker-multi");aN.dpDiv[(this._get(aN,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(aN===ax.datepicker._curInst&&ax.datepicker._datepickerShowing&&ax.datepicker._shouldFocusInput(aN)){aN.input.trigger("focus")}if(aN.yearshtml){aQ=aN.yearshtml;setTimeout(function(){if(aQ===aN.yearshtml&&aN.yearshtml){aN.dpDiv.find("select.ui-datepicker-year").first().replaceWith(aN.yearshtml)}aQ=aN.yearshtml=null},0)}if(aO){aO.apply((aN.input?aN.input[0]:null),[aN])}},_shouldFocusInput:function(aK){return aK.input&&aK.input.is(":visible")&&!aK.input.is(":disabled")&&!aK.input.is(":focus")},_checkOffset:function(aP,aN,aM){var aO=aP.dpDiv.outerWidth(),aS=aP.dpDiv.outerHeight(),aR=aP.input?aP.input.outerWidth():0,aK=aP.input?aP.input.outerHeight():0,aQ=document.documentElement.clientWidth+(aM?0:ax(document).scrollLeft()),aL=document.documentElement.clientHeight+(aM?0:ax(document).scrollTop());aN.left-=(this._get(aP,"isRTL")?(aO-aR):0);aN.left-=(aM&&aN.left===aP.input.offset().left)?ax(document).scrollLeft():0;aN.top-=(aM&&aN.top===(aP.input.offset().top+aK))?ax(document).scrollTop():0;aN.left-=Math.min(aN.left,(aN.left+aO>aQ&&aQ>aO)?Math.abs(aN.left+aO-aQ):0);aN.top-=Math.min(aN.top,(aN.top+aS>aL&&aL>aS)?Math.abs(aS+aK):0);return aN},_findPos:function(aN){var aK,aM=this._getInst(aN),aL=this._get(aM,"isRTL");while(aN&&(aN.type==="hidden"||aN.nodeType!==1||ax.expr.pseudos.hidden(aN))){aN=aN[aL?"previousSibling":"nextSibling"]}aK=ax(aN).offset();return[aK.left,aK.top]},_hideDatepicker:function(aM){var aL,aP,aO,aK,aN=this._curInst;if(!aN||(aM&&aN!==ax.data(aM,"datepicker"))){return}if(this._datepickerShowing){aL=this._get(aN,"showAnim");aP=this._get(aN,"duration");aO=function(){ax.datepicker._tidyDialog(aN)};if(ax.effects&&(ax.effects.effect[aL]||ax.effects[aL])){aN.dpDiv.hide(aL,ax.datepicker._get(aN,"showOptions"),aP,aO)}else{aN.dpDiv[(aL==="slideDown"?"slideUp":(aL==="fadeIn"?"fadeOut":"hide"))]((aL?aP:null),aO)}if(!aL){aO()}this._datepickerShowing=false;aK=this._get(aN,"onClose");if(aK){aK.apply((aN.input?aN.input[0]:null),[(aN.input?aN.input.val():""),aN])}this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if(ax.blockUI){ax.unblockUI();ax("body").append(this.dpDiv)}}this._inDialog=false}},_tidyDialog:function(aK){aK.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(aL){if(!ax.datepicker._curInst){return}var aK=ax(aL.target),aM=ax.datepicker._getInst(aK[0]);if(((aK[0].id!==ax.datepicker._mainDivId&&aK.parents("#"+ax.datepicker._mainDivId).length===0&&!aK.hasClass(ax.datepicker.markerClassName)&&!aK.closest("."+ax.datepicker._triggerClass).length&&ax.datepicker._datepickerShowing&&!(ax.datepicker._inDialog&&ax.blockUI)))||(aK.hasClass(ax.datepicker.markerClassName)&&ax.datepicker._curInst!==aM)){ax.datepicker._hideDatepicker()}},_adjustDate:function(aO,aN,aM){var aL=ax(aO),aK=this._getInst(aL[0]);if(this._isDisabledDatepicker(aL[0])){return}this._adjustInstDate(aK,aN,aM);this._updateDatepicker(aK)},_gotoToday:function(aN){var aK,aM=ax(aN),aL=this._getInst(aM[0]);if(this._get(aL,"gotoCurrent")&&aL.currentDay){aL.selectedDay=aL.currentDay;aL.drawMonth=aL.selectedMonth=aL.currentMonth;aL.drawYear=aL.selectedYear=aL.currentYear}else{aK=new Date();aL.selectedDay=aK.getDate();aL.drawMonth=aL.selectedMonth=aK.getMonth();aL.drawYear=aL.selectedYear=aK.getFullYear()}this._notifyChange(aL);this._adjustDate(aM)},_selectMonthYear:function(aO,aK,aN){var aM=ax(aO),aL=this._getInst(aM[0]);aL["selected"+(aN==="M"?"Month":"Year")]=aL["draw"+(aN==="M"?"Month":"Year")]=parseInt(aK.options[aK.selectedIndex].value,10);this._notifyChange(aL);this._adjustDate(aM)},_selectDay:function(aP,aN,aK,aO){var aL,aM=ax(aP);if(ax(aO).hasClass(this._unselectableClass)||this._isDisabledDatepicker(aM[0])){return}aL=this._getInst(aM[0]);aL.selectedDay=aL.currentDay=parseInt(ax("a",aO).attr("data-date"));aL.selectedMonth=aL.currentMonth=aN;aL.selectedYear=aL.currentYear=aK;this._selectDate(aP,this._formatDate(aL,aL.currentDay,aL.currentMonth,aL.currentYear))},_clearDate:function(aL){var aK=ax(aL);this._selectDate(aK,"")},_selectDate:function(aO,aK){var aL,aN=ax(aO),aM=this._getInst(aN[0]);aK=(aK!=null?aK:this._formatDate(aM));if(aM.input){aM.input.val(aK)}this._updateAlternate(aM);aL=this._get(aM,"onSelect");if(aL){aL.apply((aM.input?aM.input[0]:null),[aK,aM])}else{if(aM.input){aM.input.trigger("change")}}if(aM.inline){this._updateDatepicker(aM)}else{this._hideDatepicker();this._lastInput=aM.input[0];if(typeof(aM.input[0])!=="object"){aM.input.trigger("focus")}this._lastInput=null}},_updateAlternate:function(aO){var aN,aM,aK,aL=this._get(aO,"altField");if(aL){aN=this._get(aO,"altFormat")||this._get(aO,"dateFormat");aM=this._getDate(aO);aK=this.formatDate(aN,aM,this._getFormatConfig(aO));ax(document).find(aL).val(aK)}},noWeekends:function(aL){var aK=aL.getDay();return[(aK>0&&aK<6),""]},iso8601Week:function(aK){var aL,aM=new Date(aK.getTime());aM.setDate(aM.getDate()+4-(aM.getDay()||7));aL=aM.getTime();aM.setMonth(0);aM.setDate(1);return Math.floor(Math.round((aL-aM)/86400000)/7)+1},parseDate:function(a0,aV,a2){if(a0==null||aV==null){throw"Invalid arguments"}aV=(typeof aV==="object"?aV.toString():aV+"");if(aV===""){return null}var aN,aX,aL,a1=0,aQ=(a2?a2.shortYearCutoff:null)||this._defaults.shortYearCutoff,aM=(typeof aQ!=="string"?aQ:new Date().getFullYear()%100+parseInt(aQ,10)),aT=(a2?a2.dayNamesShort:null)||this._defaults.dayNamesShort,a4=(a2?a2.dayNames:null)||this._defaults.dayNames,aK=(a2?a2.monthNamesShort:null)||this._defaults.monthNamesShort,aO=(a2?a2.monthNames:null)||this._defaults.monthNames,aP=-1,a5=-1,aZ=-1,aS=-1,aY=false,a3,aU=function(a7){var a8=(aN+1<a0.length&&a0.charAt(aN+1)===a7);if(a8){aN++}return a8},a6=function(a9){var a7=aU(a9),ba=(a9==="@"?14:(a9==="!"?20:(a9==="y"&&a7?4:(a9==="o"?3:2)))),bc=(a9==="y"?ba:1),bb=new RegExp("^\\d{"+bc+","+ba+"}"),a8=aV.substring(a1).match(bb);if(!a8){throw"Missing number at position "+a1}a1+=a8[0].length;return parseInt(a8[0],10)},aR=function(a8,a9,bb){var a7=-1,ba=ax.map(aU(a8)?bb:a9,function(bd,bc){return[[bc,bd]]}).sort(function(bd,bc){return -(bd[1].length-bc[1].length)});ax.each(ba,function(bd,be){var bc=be[1];if(aV.substr(a1,bc.length).toLowerCase()===bc.toLowerCase()){a7=be[0];a1+=bc.length;return false}});if(a7!==-1){return a7+1}else{throw"Unknown name at position "+a1}},aW=function(){if(aV.charAt(a1)!==a0.charAt(aN)){throw"Unexpected literal at position "+a1}a1++};for(aN=0;aN<a0.length;aN++){if(aY){if(a0.charAt(aN)==="'"&&!aU("'")){aY=false}else{aW()}}else{switch(a0.charAt(aN)){case"d":aZ=a6("d");break;case"D":aR("D",aT,a4);break;case"o":aS=a6("o");break;case"m":a5=a6("m");break;case"M":a5=aR("M",aK,aO);break;case"y":aP=a6("y");break;case"@":a3=new Date(a6("@"));aP=a3.getFullYear();a5=a3.getMonth()+1;aZ=a3.getDate();break;case"!":a3=new Date((a6("!")-this._ticksTo1970)/10000);aP=a3.getFullYear();a5=a3.getMonth()+1;aZ=a3.getDate();break;case"'":if(aU("'")){aW()}else{aY=true}break;default:aW()}}}if(a1<aV.length){aL=aV.substr(a1);if(!/^\s+/.test(aL)){throw"Extra/unparsed characters found in date: "+aL}}if(aP===-1){aP=new Date().getFullYear()}else{if(aP<100){aP+=new Date().getFullYear()-new Date().getFullYear()%100+(aP<=aM?0:-100)}}if(aS>-1){a5=1;aZ=aS;do{aX=this._getDaysInMonth(aP,a5-1);if(aZ<=aX){break}a5++;aZ-=aX}while(true)}a3=this._daylightSavingAdjust(new Date(aP,a5-1,aZ));if(a3.getFullYear()!==aP||a3.getMonth()+1!==a5||a3.getDate()!==aZ){throw"Invalid date"}return a3},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(((1970-1)*365+Math.floor(1970/4)-Math.floor(1970/100)+Math.floor(1970/400))*24*60*60*10000000),formatDate:function(aT,aN,aO){if(!aN){return""}var aV,aW=(aO?aO.dayNamesShort:null)||this._defaults.dayNamesShort,aL=(aO?aO.dayNames:null)||this._defaults.dayNames,aR=(aO?aO.monthNamesShort:null)||this._defaults.monthNamesShort,aP=(aO?aO.monthNames:null)||this._defaults.monthNames,aU=function(aX){var aY=(aV+1<aT.length&&aT.charAt(aV+1)===aX);if(aY){aV++}return aY},aK=function(aZ,a0,aX){var aY=""+a0;if(aU(aZ)){while(aY.length<aX){aY="0"+aY}}return aY},aQ=function(aX,aZ,aY,a0){return(aU(aX)?a0[aZ]:aY[aZ])},aM="",aS=false;if(aN){for(aV=0;aV<aT.length;aV++){if(aS){if(aT.charAt(aV)==="'"&&!aU("'")){aS=false}else{aM+=aT.charAt(aV)}}else{switch(aT.charAt(aV)){case"d":aM+=aK("d",aN.getDate(),2);break;case"D":aM+=aQ("D",aN.getDay(),aW,aL);break;case"o":aM+=aK("o",Math.round((new Date(aN.getFullYear(),aN.getMonth(),aN.getDate()).getTime()-new Date(aN.getFullYear(),0,0).getTime())/86400000),3);break;case"m":aM+=aK("m",aN.getMonth()+1,2);break;case"M":aM+=aQ("M",aN.getMonth(),aR,aP);break;case"y":aM+=(aU("y")?aN.getFullYear():(aN.getFullYear()%100<10?"0":"")+aN.getFullYear()%100);break;case"@":aM+=aN.getTime();break;case"!":aM+=aN.getTime()*10000+this._ticksTo1970;break;case"'":if(aU("'")){aM+="'"}else{aS=true}break;default:aM+=aT.charAt(aV)}}}}return aM},_possibleChars:function(aO){var aN,aM="",aL=false,aK=function(aP){var aQ=(aN+1<aO.length&&aO.charAt(aN+1)===aP);if(aQ){aN++}return aQ};for(aN=0;aN<aO.length;aN++){if(aL){if(aO.charAt(aN)==="'"&&!aK("'")){aL=false}else{aM+=aO.charAt(aN)}}else{switch(aO.charAt(aN)){case"d":case"m":case"y":case"@":aM+="0123456789";break;case"D":case"M":return null;case"'":if(aK("'")){aM+="'"}else{aL=true}break;default:aM+=aO.charAt(aN)}}}return aM},_get:function(aL,aK){return aL.settings[aK]!==undefined?aL.settings[aK]:this._defaults[aK]},_setDateFromField:function(aP,aM){if(aP.input.val()===aP.lastVal){return}var aK=this._get(aP,"dateFormat"),aR=aP.lastVal=aP.input?aP.input.val():null,aQ=this._getDefaultDate(aP),aL=aQ,aN=this._getFormatConfig(aP);try{aL=this.parseDate(aK,aR,aN)||aQ}catch(aO){aR=(aM?"":aR)}aP.selectedDay=aL.getDate();aP.drawMonth=aP.selectedMonth=aL.getMonth();aP.drawYear=aP.selectedYear=aL.getFullYear();aP.currentDay=(aR?aL.getDate():0);aP.currentMonth=(aR?aL.getMonth():0);aP.currentYear=(aR?aL.getFullYear():0);this._adjustInstDate(aP)},_getDefaultDate:function(aK){return this._restrictMinMax(aK,this._determineDate(aK,this._get(aK,"defaultDate"),new Date()))},_determineDate:function(aO,aL,aP){var aN=function(aR){var aQ=new Date();aQ.setDate(aQ.getDate()+aR);return aQ},aM=function(aX){try{return ax.datepicker.parseDate(ax.datepicker._get(aO,"dateFormat"),aX,ax.datepicker._getFormatConfig(aO))}catch(aW){}var aR=(aX.toLowerCase().match(/^c/)?ax.datepicker._getDate(aO):null)||new Date(),aS=aR.getFullYear(),aV=aR.getMonth(),aQ=aR.getDate(),aU=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,aT=aU.exec(aX);while(aT){switch(aT[2]||"d"){case"d":case"D":aQ+=parseInt(aT[1],10);break;case"w":case"W":aQ+=parseInt(aT[1],10)*7;break;case"m":case"M":aV+=parseInt(aT[1],10);aQ=Math.min(aQ,ax.datepicker._getDaysInMonth(aS,aV));break;case"y":case"Y":aS+=parseInt(aT[1],10);aQ=Math.min(aQ,ax.datepicker._getDaysInMonth(aS,aV));break}aT=aU.exec(aX)}return new Date(aS,aV,aQ)},aK=(aL==null||aL===""?aP:(typeof aL==="string"?aM(aL):(typeof aL==="number"?(isNaN(aL)?aP:aN(aL)):new Date(aL.getTime()))));aK=(aK&&aK.toString()==="Invalid Date"?aP:aK);if(aK){aK.setHours(0);aK.setMinutes(0);aK.setSeconds(0);aK.setMilliseconds(0)}return this._daylightSavingAdjust(aK)},_daylightSavingAdjust:function(aK){if(!aK){return null}aK.setHours(aK.getHours()>12?aK.getHours()+2:0);return aK},_setDate:function(aQ,aN,aP){var aK=!aN,aM=aQ.selectedMonth,aO=aQ.selectedYear,aL=this._restrictMinMax(aQ,this._determineDate(aQ,aN,new Date()));aQ.selectedDay=aQ.currentDay=aL.getDate();aQ.drawMonth=aQ.selectedMonth=aQ.currentMonth=aL.getMonth();aQ.drawYear=aQ.selectedYear=aQ.currentYear=aL.getFullYear();if((aM!==aQ.selectedMonth||aO!==aQ.selectedYear)&&!aP){this._notifyChange(aQ)}this._adjustInstDate(aQ);if(aQ.input){aQ.input.val(aK?"":this._formatDate(aQ))}},_getDate:function(aL){var aK=(!aL.currentYear||(aL.input&&aL.input.val()==="")?null:this._daylightSavingAdjust(new Date(aL.currentYear,aL.currentMonth,aL.currentDay)));return aK},_attachHandlers:function(aL){var aK=this._get(aL,"stepMonths"),aM="#"+aL.id.replace(/\\\\/g,"\\");aL.dpDiv.find("[data-handler]").map(function(){var aN={prev:function(){ax.datepicker._adjustDate(aM,-aK,"M")},next:function(){ax.datepicker._adjustDate(aM,+aK,"M")},hide:function(){ax.datepicker._hideDatepicker()},today:function(){ax.datepicker._gotoToday(aM)},selectDay:function(){ax.datepicker._selectDay(aM,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this);return false},selectMonth:function(){ax.datepicker._selectMonthYear(aM,this,"M");return false},selectYear:function(){ax.datepicker._selectMonthYear(aM,this,"Y");return false}};ax(this).on(this.getAttribute("data-event"),aN[this.getAttribute("data-handler")])})},_generateHTML:function(bq){var a3,a2,bl,bd,aO,bu,bo,bh,bx,bb,bB,aV,aX,aW,aL,bt,aT,a6,bw,bj,bC,a5,ba,aU,aP,bm,bf,bi,bg,aS,a8,aY,bp,bs,aN,bv,bz,be,aZ,br=new Date(),a4=this._daylightSavingAdjust(new Date(br.getFullYear(),br.getMonth(),br.getDate())),by=this._get(bq,"isRTL"),bA=this._get(bq,"showButtonPanel"),bk=this._get(bq,"hideIfNoPrevNext"),a9=this._get(bq,"navigationAsDateFormat"),a0=this._getNumberOfMonths(bq),aR=this._get(bq,"showCurrentAtPos"),bc=this._get(bq,"stepMonths"),a7=(a0[0]!==1||a0[1]!==1),aM=this._daylightSavingAdjust((!bq.currentDay?new Date(9999,9,9):new Date(bq.currentYear,bq.currentMonth,bq.currentDay))),aQ=this._getMinMaxDate(bq,"min"),a1=this._getMinMaxDate(bq,"max"),aK=bq.drawMonth-aR,bn=bq.drawYear;if(aK<0){aK+=12;bn--}if(a1){a3=this._daylightSavingAdjust(new Date(a1.getFullYear(),a1.getMonth()-(a0[0]*a0[1])+1,a1.getDate()));a3=(aQ&&a3<aQ?aQ:a3);while(this._daylightSavingAdjust(new Date(bn,aK,1))>a3){aK--;if(aK<0){aK=11;bn--}}}bq.drawMonth=aK;bq.drawYear=bn;a2=this._get(bq,"prevText");a2=(!a9?a2:this.formatDate(a2,this._daylightSavingAdjust(new Date(bn,aK-bc,1)),this._getFormatConfig(bq)));if(this._canAdjustMonth(bq,-1,bn,aK)){bl=ax("<a>").attr({"class":"ui-datepicker-prev ui-corner-all","data-handler":"prev","data-event":"click",title:a2}).append(ax("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(by?"e":"w")).text(a2))[0].outerHTML}else{if(bk){bl=""}else{bl=ax("<a>").attr({"class":"ui-datepicker-prev ui-corner-all ui-state-disabled",title:a2}).append(ax("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(by?"e":"w")).text(a2))[0].outerHTML}}bd=this._get(bq,"nextText");bd=(!a9?bd:this.formatDate(bd,this._daylightSavingAdjust(new Date(bn,aK+bc,1)),this._getFormatConfig(bq)));if(this._canAdjustMonth(bq,+1,bn,aK)){aO=ax("<a>").attr({"class":"ui-datepicker-next ui-corner-all","data-handler":"next","data-event":"click",title:bd}).append(ax("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(by?"w":"e")).text(bd))[0].outerHTML}else{if(bk){aO=""}else{aO=ax("<a>").attr({"class":"ui-datepicker-next ui-corner-all ui-state-disabled",title:bd}).append(ax("<span>").attr("class","ui-icon ui-icon-circle-triangle-"+(by?"w":"e")).text(bd))[0].outerHTML}}bu=this._get(bq,"currentText");bo=(this._get(bq,"gotoCurrent")&&bq.currentDay?aM:a4);bu=(!a9?bu:this.formatDate(bu,bo,this._getFormatConfig(bq)));bh="";if(!bq.inline){bh=ax("<button>").attr({type:"button","class":"ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all","data-handler":"hide","data-event":"click"}).text(this._get(bq,"closeText"))[0].outerHTML}bx="";if(bA){bx=ax("<div class='ui-datepicker-buttonpane ui-widget-content'>").append(by?bh:"").append(this._isInRange(bq,bo)?ax("<button>").attr({type:"button","class":"ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all","data-handler":"today","data-event":"click"}).text(bu):"").append(by?"":bh)[0].outerHTML}bb=parseInt(this._get(bq,"firstDay"),10);bb=(isNaN(bb)?0:bb);bB=this._get(bq,"showWeek");aV=this._get(bq,"dayNames");aX=this._get(bq,"dayNamesMin");aW=this._get(bq,"monthNames");aL=this._get(bq,"monthNamesShort");bt=this._get(bq,"beforeShowDay");aT=this._get(bq,"showOtherMonths");a6=this._get(bq,"selectOtherMonths");bw=this._getDefaultDate(bq);bj="";for(a5=0;a5<a0[0];a5++){ba="";this.maxRows=4;for(aU=0;aU<a0[1];aU++){aP=this._daylightSavingAdjust(new Date(bn,aK,bq.selectedDay));bm=" ui-corner-all";bf="";if(a7){bf+="<div class='ui-datepicker-group";if(a0[1]>1){switch(aU){case 0:bf+=" ui-datepicker-group-first";bm=" ui-corner-"+(by?"right":"left");break;case a0[1]-1:bf+=" ui-datepicker-group-last";bm=" ui-corner-"+(by?"left":"right");break;default:bf+=" ui-datepicker-group-middle";bm="";break}}bf+="'>"}bf+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+bm+"'>"+(/all|left/.test(bm)&&a5===0?(by?aO:bl):"")+(/all|right/.test(bm)&&a5===0?(by?bl:aO):"")+this._generateMonthYearHeader(bq,aK,bn,aQ,a1,a5>0||aU>0,aW,aL)+"</div><table class='ui-datepicker-calendar'><thead><tr>";bi=(bB?"<th class='ui-datepicker-week-col'>"+this._get(bq,"weekHeader")+"</th>":"");for(bC=0;bC<7;bC++){bg=(bC+bb)%7;bi+="<th scope='col'"+((bC+bb+6)%7>=5?" class='ui-datepicker-week-end'":"")+"><span title='"+aV[bg]+"'>"+aX[bg]+"</span></th>"}bf+=bi+"</tr></thead><tbody>";aS=this._getDaysInMonth(bn,aK);if(bn===bq.selectedYear&&aK===bq.selectedMonth){bq.selectedDay=Math.min(bq.selectedDay,aS)}a8=(this._getFirstDayOfMonth(bn,aK)-bb+7)%7;aY=Math.ceil((a8+aS)/7);bp=(a7?this.maxRows>aY?this.maxRows:aY:aY);this.maxRows=bp;bs=this._daylightSavingAdjust(new Date(bn,aK,1-a8));for(aN=0;aN<bp;aN++){bf+="<tr>";bv=(!bB?"":"<td class='ui-datepicker-week-col'>"+this._get(bq,"calculateWeek")(bs)+"</td>");for(bC=0;bC<7;bC++){bz=(bt?bt.apply((bq.input?bq.input[0]:null),[bs]):[true,""]);be=(bs.getMonth()!==aK);aZ=(be&&!a6)||!bz[0]||(aQ&&bs<aQ)||(a1&&bs>a1);bv+="<td class='"+((bC+bb+6)%7>=5?" ui-datepicker-week-end":"")+(be?" ui-datepicker-other-month":"")+((bs.getTime()===aP.getTime()&&aK===bq.selectedMonth&&bq._keyEvent)||(bw.getTime()===bs.getTime()&&bw.getTime()===aP.getTime())?" "+this._dayOverClass:"")+(aZ?" "+this._unselectableClass+" ui-state-disabled":"")+(be&&!aT?"":" "+bz[1]+(bs.getTime()===aM.getTime()?" "+this._currentClass:"")+(bs.getTime()===a4.getTime()?" ui-datepicker-today":""))+"'"+((!be||aT)&&bz[2]?" title='"+bz[2].replace(/'/g,"&#39;")+"'":"")+(aZ?"":" data-handler='selectDay' data-event='click' data-month='"+bs.getMonth()+"' data-year='"+bs.getFullYear()+"'")+">"+(be&&!aT?"&#xa0;":(aZ?"<span class='ui-state-default'>"+bs.getDate()+"</span>":"<a class='ui-state-default"+(bs.getTime()===a4.getTime()?" ui-state-highlight":"")+(bs.getTime()===aM.getTime()?" ui-state-active":"")+(be?" ui-priority-secondary":"")+"' href='#' aria-current='"+(bs.getTime()===aM.getTime()?"true":"false")+"' data-date='"+bs.getDate()+"'>"+bs.getDate()+"</a>"))+"</td>";bs.setDate(bs.getDate()+1);bs=this._daylightSavingAdjust(bs)}bf+=bv+"</tr>"}aK++;if(aK>11){aK=0;bn++}bf+="</tbody></table>"+(a7?"</div>"+((a0[0]>0&&aU===a0[1]-1)?"<div class='ui-datepicker-row-break'></div>":""):"");ba+=bf}bj+=ba}bj+=bx;bq._keyEvent=false;return bj},_generateMonthYearHeader:function(aP,aM,aX,aR,aV,aZ,aT,aK){var a3,aL,a4,a1,aQ,a0,aW,aS,aN=this._get(aP,"changeMonth"),a5=this._get(aP,"changeYear"),a6=this._get(aP,"showMonthAfterYear"),aO=this._get(aP,"selectMonthLabel"),aY=this._get(aP,"selectYearLabel"),aU="<div class='ui-datepicker-title'>",a2="";if(aZ||!aN){a2+="<span class='ui-datepicker-month'>"+aT[aM]+"</span>"}else{a3=(aR&&aR.getFullYear()===aX);aL=(aV&&aV.getFullYear()===aX);a2+="<select class='ui-datepicker-month' aria-label='"+aO+"' data-handler='selectMonth' data-event='change'>";for(a4=0;a4<12;a4++){if((!a3||a4>=aR.getMonth())&&(!aL||a4<=aV.getMonth())){a2+="<option value='"+a4+"'"+(a4===aM?" selected='selected'":"")+">"+aK[a4]+"</option>"}}a2+="</select>"}if(!a6){aU+=a2+(aZ||!(aN&&a5)?"&#xa0;":"")}if(!aP.yearshtml){aP.yearshtml="";if(aZ||!a5){aU+="<span class='ui-datepicker-year'>"+aX+"</span>"}else{a1=this._get(aP,"yearRange").split(":");aQ=new Date().getFullYear();a0=function(a8){var a7=(a8.match(/c[+\-].*/)?aX+parseInt(a8.substring(1),10):(a8.match(/[+\-].*/)?aQ+parseInt(a8,10):parseInt(a8,10)));return(isNaN(a7)?aQ:a7)};aW=a0(a1[0]);aS=Math.max(aW,a0(a1[1]||""));aW=(aR?Math.max(aW,aR.getFullYear()):aW);aS=(aV?Math.min(aS,aV.getFullYear()):aS);aP.yearshtml+="<select class='ui-datepicker-year' aria-label='"+aY+"' data-handler='selectYear' data-event='change'>";for(;aW<=aS;aW++){aP.yearshtml+="<option value='"+aW+"'"+(aW===aX?" selected='selected'":"")+">"+aW+"</option>"}aP.yearshtml+="</select>";aU+=aP.yearshtml;aP.yearshtml=null}}aU+=this._get(aP,"yearSuffix");if(a6){aU+=(aZ||!(aN&&a5)?"&#xa0;":"")+a2}aU+="</div>";return aU},_adjustInstDate:function(aN,aQ,aP){var aM=aN.selectedYear+(aP==="Y"?aQ:0),aO=aN.selectedMonth+(aP==="M"?aQ:0),aK=Math.min(aN.selectedDay,this._getDaysInMonth(aM,aO))+(aP==="D"?aQ:0),aL=this._restrictMinMax(aN,this._daylightSavingAdjust(new Date(aM,aO,aK)));aN.selectedDay=aL.getDate();aN.drawMonth=aN.selectedMonth=aL.getMonth();aN.drawYear=aN.selectedYear=aL.getFullYear();if(aP==="M"||aP==="Y"){this._notifyChange(aN)}},_restrictMinMax:function(aN,aL){var aM=this._getMinMaxDate(aN,"min"),aO=this._getMinMaxDate(aN,"max"),aK=(aM&&aL<aM?aM:aL);return(aO&&aK>aO?aO:aK)},_notifyChange:function(aL){var aK=this._get(aL,"onChangeMonthYear");if(aK){aK.apply((aL.input?aL.input[0]:null),[aL.selectedYear,aL.selectedMonth+1,aL])}},_getNumberOfMonths:function(aL){var aK=this._get(aL,"numberOfMonths");return(aK==null?[1,1]:(typeof aK==="number"?[1,aK]:aK))},_getMinMaxDate:function(aL,aK){return this._determineDate(aL,this._get(aL,aK+"Date"),null)},_getDaysInMonth:function(aK,aL){return 32-this._daylightSavingAdjust(new Date(aK,aL,32)).getDate()},_getFirstDayOfMonth:function(aK,aL){return new Date(aK,aL,1).getDay()},_canAdjustMonth:function(aN,aP,aM,aO){var aK=this._getNumberOfMonths(aN),aL=this._daylightSavingAdjust(new Date(aM,aO+(aP<0?aP:aK[0]*aK[1]),1));if(aP<0){aL.setDate(this._getDaysInMonth(aL.getFullYear(),aL.getMonth()))}return this._isInRange(aN,aL)},_isInRange:function(aO,aM){var aL,aR,aN=this._getMinMaxDate(aO,"min"),aK=this._getMinMaxDate(aO,"max"),aS=null,aP=null,aQ=this._get(aO,"yearRange");if(aQ){aL=aQ.split(":");aR=new Date().getFullYear();aS=parseInt(aL[0],10);aP=parseInt(aL[1],10);if(aL[0].match(/[+\-].*/)){aS+=aR}if(aL[1].match(/[+\-].*/)){aP+=aR}}return((!aN||aM.getTime()>=aN.getTime())&&(!aK||aM.getTime()<=aK.getTime())&&(!aS||aM.getFullYear()>=aS)&&(!aP||aM.getFullYear()<=aP))},_getFormatConfig:function(aK){var aL=this._get(aK,"shortYearCutoff");aL=(typeof aL!=="string"?aL:new Date().getFullYear()%100+parseInt(aL,10));return{shortYearCutoff:aL,dayNamesShort:this._get(aK,"dayNamesShort"),dayNames:this._get(aK,"dayNames"),monthNamesShort:this._get(aK,"monthNamesShort"),monthNames:this._get(aK,"monthNames")}},_formatDate:function(aN,aK,aO,aM){if(!aK){aN.currentDay=aN.selectedDay;aN.currentMonth=aN.selectedMonth;aN.currentYear=aN.selectedYear}var aL=(aK?(typeof aK==="object"?aK:this._daylightSavingAdjust(new Date(aM,aO,aK))):this._daylightSavingAdjust(new Date(aN.currentYear,aN.currentMonth,aN.currentDay)));return this.formatDate(this._get(aN,"dateFormat"),aL,this._getFormatConfig(aN))}});function af(aL){var aK="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return aL.on("mouseout",aK,function(){ax(this).removeClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!==-1){ax(this).removeClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!==-1){ax(this).removeClass("ui-datepicker-next-hover")}}).on("mouseover",aK,R)}function R(){if(!ax.datepicker._isDisabledDatepicker(aF.inline?aF.dpDiv.parent()[0]:aF.input[0])){ax(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");ax(this).addClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!==-1){ax(this).addClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!==-1){ax(this).addClass("ui-datepicker-next-hover")}}}function L(aM,aL){ax.extend(aM,aL);for(var aK in aL){if(aL[aK]==null){aM[aK]=aL[aK]}}return aM}ax.fn.datepicker=function(aL){if(!this.length){return this}if(!ax.datepicker.initialized){ax(document).on("mousedown",ax.datepicker._checkExternalClick);ax.datepicker.initialized=true}if(ax("#"+ax.datepicker._mainDivId).length===0){ax("body").append(ax.datepicker.dpDiv)}var aK=Array.prototype.slice.call(arguments,1);if(typeof aL==="string"&&(aL==="isDisabled"||aL==="getDate"||aL==="widget")){return ax.datepicker["_"+aL+"Datepicker"].apply(ax.datepicker,[this[0]].concat(aK))}if(aL==="option"&&arguments.length===2&&typeof arguments[1]==="string"){return ax.datepicker["_"+aL+"Datepicker"].apply(ax.datepicker,[this[0]].concat(aK))}return this.each(function(){if(typeof aL==="string"){ax.datepicker["_"+aL+"Datepicker"].apply(ax.datepicker,[this].concat(aK))}else{ax.datepicker._attachDatepicker(this,aL)}})};ax.datepicker=new W();ax.datepicker.initialized=false;ax.datepicker.uuid=new Date().getTime();ax.datepicker.version="1.13.0";var j=ax.datepicker;
/*!
 * jQuery UI Dialog 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.dialog",{version:"1.13.0",options:{appendTo:"body",autoOpen:true,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:true,closeText:"Close",draggable:true,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:false,position:{my:"center",at:"center",of:window,collision:"fit",using:function(aL){var aK=ax(this).css(aL).offset().top;if(aK<0){ax(this).css("top",aL.top-aK)}}},resizable:true,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:true,height:true,maxHeight:true,maxWidth:true,minHeight:true,minWidth:true,width:true},resizableRelatedOptions:{maxHeight:true,maxWidth:true,minHeight:true,minWidth:true},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height};this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)};this.originalTitle=this.element.attr("title");if(this.options.title==null&&this.originalTitle!=null){this.options.title=this.originalTitle}if(this.options.disabled){this.options.disabled=false}this._createWrapper();this.element.show().removeAttr("title").appendTo(this.uiDialog);this._addClass("ui-dialog-content","ui-widget-content");this._createTitlebar();this._createButtonPane();if(this.options.draggable&&ax.fn.draggable){this._makeDraggable()}if(this.options.resizable&&ax.fn.resizable){this._makeResizable()}this._isOpen=false;this._trackFocus()},_init:function(){if(this.options.autoOpen){this.open()}},_appendTo:function(){var aK=this.options.appendTo;if(aK&&(aK.jquery||aK.nodeType)){return ax(aK)}return this.document.find(aK||"body").eq(0)},_destroy:function(){var aL,aK=this.originalPosition;this._untrackInstance();this._destroyOverlay();this.element.removeUniqueId().css(this.originalCss).detach();this.uiDialog.remove();if(this.originalTitle){this.element.attr("title",this.originalTitle)}aL=aK.parent.children().eq(aK.index);if(aL.length&&aL[0]!==this.element[0]){aL.before(this.element)}else{aK.parent.append(this.element)}},widget:function(){return this.uiDialog},disable:ax.noop,enable:ax.noop,close:function(aL){var aK=this;if(!this._isOpen||this._trigger("beforeClose",aL)===false){return}this._isOpen=false;this._focusedElement=null;this._destroyOverlay();this._untrackInstance();if(!this.opener.filter(":focusable").trigger("focus").length){ax.ui.safeBlur(ax.ui.safeActiveElement(this.document[0]))}this._hide(this.uiDialog,this.options.hide,function(){aK._trigger("close",aL)})},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(aO,aK){var aN=false,aM=this.uiDialog.siblings(".ui-front:visible").map(function(){return +ax(this).css("z-index")}).get(),aL=Math.max.apply(null,aM);if(aL>=+this.uiDialog.css("z-index")){this.uiDialog.css("z-index",aL+1);aN=true}if(aN&&!aK){this._trigger("focus",aO)}return aN},open:function(){var aK=this;if(this._isOpen){if(this._moveToTop()){this._focusTabbable()}return}this._isOpen=true;this.opener=ax(ax.ui.safeActiveElement(this.document[0]));this._size();this._position();this._createOverlay();this._moveToTop(null,true);if(this.overlay){this.overlay.css("z-index",this.uiDialog.css("z-index")-1)}this._show(this.uiDialog,this.options.show,function(){aK._focusTabbable();aK._trigger("focus")});this._makeFocusTarget();this._trigger("open")},_focusTabbable:function(){var aK=this._focusedElement;if(!aK){aK=this.element.find("[autofocus]")}if(!aK.length){aK=this.element.find(":tabbable")}if(!aK.length){aK=this.uiDialogButtonPane.find(":tabbable")}if(!aK.length){aK=this.uiDialogTitlebarClose.filter(":tabbable")}if(!aK.length){aK=this.uiDialog}aK.eq(0).trigger("focus")},_restoreTabbableFocus:function(){var aL=ax.ui.safeActiveElement(this.document[0]),aK=this.uiDialog[0]===aL||ax.contains(this.uiDialog[0],aL);if(!aK){this._focusTabbable()}},_keepFocus:function(aK){aK.preventDefault();this._restoreTabbableFocus();this._delay(this._restoreTabbableFocus)},_createWrapper:function(){this.uiDialog=ax("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo());this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front");this._on(this.uiDialog,{keydown:function(aM){if(this.options.closeOnEscape&&!aM.isDefaultPrevented()&&aM.keyCode&&aM.keyCode===ax.ui.keyCode.ESCAPE){aM.preventDefault();this.close(aM);return}if(aM.keyCode!==ax.ui.keyCode.TAB||aM.isDefaultPrevented()){return}var aL=this.uiDialog.find(":tabbable"),aN=aL.first(),aK=aL.last();if((aM.target===aK[0]||aM.target===this.uiDialog[0])&&!aM.shiftKey){this._delay(function(){aN.trigger("focus")});aM.preventDefault()}else{if((aM.target===aN[0]||aM.target===this.uiDialog[0])&&aM.shiftKey){this._delay(function(){aK.trigger("focus")});aM.preventDefault()}}},mousedown:function(aK){if(this._moveToTop(aK)){this._focusTabbable()}}});if(!this.element.find("[aria-describedby]").length){this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})}},_createTitlebar:function(){var aK;this.uiDialogTitlebar=ax("<div>");this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix");this._on(this.uiDialogTitlebar,{mousedown:function(aL){if(!ax(aL.target).closest(".ui-dialog-titlebar-close")){this.uiDialog.trigger("focus")}}});this.uiDialogTitlebarClose=ax("<button type='button'></button>").button({label:ax("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:false}).appendTo(this.uiDialogTitlebar);this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close");this._on(this.uiDialogTitlebarClose,{click:function(aL){aL.preventDefault();this.close(aL)}});aK=ax("<span>").uniqueId().prependTo(this.uiDialogTitlebar);this._addClass(aK,"ui-dialog-title");this._title(aK);this.uiDialogTitlebar.prependTo(this.uiDialog);this.uiDialog.attr({"aria-labelledby":aK.attr("id")})},_title:function(aK){if(this.options.title){aK.text(this.options.title)}else{aK.html("&#160;")}},_createButtonPane:function(){this.uiDialogButtonPane=ax("<div>");this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix");this.uiButtonSet=ax("<div>").appendTo(this.uiDialogButtonPane);this._addClass(this.uiButtonSet,"ui-dialog-buttonset");this._createButtons()},_createButtons:function(){var aL=this,aK=this.options.buttons;this.uiDialogButtonPane.remove();this.uiButtonSet.empty();if(ax.isEmptyObject(aK)||(Array.isArray(aK)&&!aK.length)){this._removeClass(this.uiDialog,"ui-dialog-buttons");return}ax.each(aK,function(aM,aN){var aO,aP;aN=typeof aN==="function"?{click:aN,text:aM}:aN;aN=ax.extend({type:"button"},aN);aO=aN.click;aP={icon:aN.icon,iconPosition:aN.iconPosition,showLabel:aN.showLabel,icons:aN.icons,text:aN.text};delete aN.click;delete aN.icon;delete aN.iconPosition;delete aN.showLabel;delete aN.icons;if(typeof aN.text==="boolean"){delete aN.text}ax("<button></button>",aN).button(aP).appendTo(aL.uiButtonSet).on("click",function(){aO.apply(aL.element[0],arguments)})});this._addClass(this.uiDialog,"ui-dialog-buttons");this.uiDialogButtonPane.appendTo(this.uiDialog)},_makeDraggable:function(){var aM=this,aL=this.options;function aK(aN){return{position:aN.position,offset:aN.offset}}this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(aN,aO){aM._addClass(ax(this),"ui-dialog-dragging");aM._blockFrames();aM._trigger("dragStart",aN,aK(aO))},drag:function(aN,aO){aM._trigger("drag",aN,aK(aO))},stop:function(aN,aO){var aQ=aO.offset.left-aM.document.scrollLeft(),aP=aO.offset.top-aM.document.scrollTop();aL.position={my:"left top",at:"left"+(aQ>=0?"+":"")+aQ+" top"+(aP>=0?"+":"")+aP,of:aM.window};aM._removeClass(ax(this),"ui-dialog-dragging");aM._unblockFrames();aM._trigger("dragStop",aN,aK(aO))}})},_makeResizable:function(){var aP=this,aN=this.options,aO=aN.resizable,aK=this.uiDialog.css("position"),aM=typeof aO==="string"?aO:"n,e,s,w,se,sw,ne,nw";function aL(aQ){return{originalPosition:aQ.originalPosition,originalSize:aQ.originalSize,position:aQ.position,size:aQ.size}}this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:aN.maxWidth,maxHeight:aN.maxHeight,minWidth:aN.minWidth,minHeight:this._minHeight(),handles:aM,start:function(aQ,aR){aP._addClass(ax(this),"ui-dialog-resizing");aP._blockFrames();aP._trigger("resizeStart",aQ,aL(aR))},resize:function(aQ,aR){aP._trigger("resize",aQ,aL(aR))},stop:function(aQ,aR){var aU=aP.uiDialog.offset(),aT=aU.left-aP.document.scrollLeft(),aS=aU.top-aP.document.scrollTop();aN.height=aP.uiDialog.height();aN.width=aP.uiDialog.width();aN.position={my:"left top",at:"left"+(aT>=0?"+":"")+aT+" top"+(aS>=0?"+":"")+aS,of:aP.window};aP._removeClass(ax(this),"ui-dialog-resizing");aP._unblockFrames();aP._trigger("resizeStop",aQ,aL(aR))}}).css("position",aK)},_trackFocus:function(){this._on(this.widget(),{focusin:function(aK){this._makeFocusTarget();this._focusedElement=ax(aK.target)}})},_makeFocusTarget:function(){this._untrackInstance();this._trackingInstances().unshift(this)},_untrackInstance:function(){var aL=this._trackingInstances(),aK=ax.inArray(this,aL);if(aK!==-1){aL.splice(aK,1)}},_trackingInstances:function(){var aK=this.document.data("ui-dialog-instances");if(!aK){aK=[];this.document.data("ui-dialog-instances",aK)}return aK},_minHeight:function(){var aK=this.options;return aK.height==="auto"?aK.minHeight:Math.min(aK.minHeight,aK.height)},_position:function(){var aK=this.uiDialog.is(":visible");if(!aK){this.uiDialog.show()}this.uiDialog.position(this.options.position);if(!aK){this.uiDialog.hide()}},_setOptions:function(aM){var aN=this,aL=false,aK={};ax.each(aM,function(aO,aP){aN._setOption(aO,aP);if(aO in aN.sizeRelatedOptions){aL=true}if(aO in aN.resizableRelatedOptions){aK[aO]=aP}});if(aL){this._size();this._position()}if(this.uiDialog.is(":data(ui-resizable)")){this.uiDialog.resizable("option",aK)}},_setOption:function(aM,aN){var aL,aO,aK=this.uiDialog;if(aM==="disabled"){return}this._super(aM,aN);if(aM==="appendTo"){this.uiDialog.appendTo(this._appendTo())}if(aM==="buttons"){this._createButtons()}if(aM==="closeText"){this.uiDialogTitlebarClose.button({label:ax("<a>").text(""+this.options.closeText).html()})}if(aM==="draggable"){aL=aK.is(":data(ui-draggable)");if(aL&&!aN){aK.draggable("destroy")}if(!aL&&aN){this._makeDraggable()}}if(aM==="position"){this._position()}if(aM==="resizable"){aO=aK.is(":data(ui-resizable)");if(aO&&!aN){aK.resizable("destroy")}if(aO&&typeof aN==="string"){aK.resizable("option","handles",aN)}if(!aO&&aN!==false){this._makeResizable()}}if(aM==="title"){this._title(this.uiDialogTitlebar.find(".ui-dialog-title"))}},_size:function(){var aK,aM,aN,aL=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0});if(aL.minWidth>aL.width){aL.width=aL.minWidth}aK=this.uiDialog.css({height:"auto",width:aL.width}).outerHeight();aM=Math.max(0,aL.minHeight-aK);aN=typeof aL.maxHeight==="number"?Math.max(0,aL.maxHeight-aK):"none";if(aL.height==="auto"){this.element.css({minHeight:aM,maxHeight:aN,height:"auto"})}else{this.element.height(Math.max(0,aL.height-aK))}if(this.uiDialog.is(":data(ui-resizable)")){this.uiDialog.resizable("option","minHeight",this._minHeight())}},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var aK=ax(this);return ax("<div>").css({position:"absolute",width:aK.outerWidth(),height:aK.outerHeight()}).appendTo(aK.parent()).offset(aK.offset())[0]})},_unblockFrames:function(){if(this.iframeBlocks){this.iframeBlocks.remove();delete this.iframeBlocks}},_allowInteraction:function(aK){if(ax(aK.target).closest(".ui-dialog").length){return true}return !!ax(aK.target).closest(".ui-datepicker").length},_createOverlay:function(){if(!this.options.modal){return}var aK=ax.fn.jquery.substring(0,4);var aL=true;this._delay(function(){aL=false});if(!this.document.data("ui-dialog-overlays")){this.document.on("focusin.ui-dialog",function(aN){if(aL){return}var aM=this._trackingInstances()[0];if(!aM._allowInteraction(aN)){aN.preventDefault();aM._focusTabbable();if(aK==="3.4."||aK==="3.5."){aM._delay(aM._restoreTabbableFocus)}}}.bind(this))}this.overlay=ax("<div>").appendTo(this._appendTo());this._addClass(this.overlay,null,"ui-widget-overlay ui-front");this._on(this.overlay,{mousedown:"_keepFocus"});this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)},_destroyOverlay:function(){if(!this.options.modal){return}if(this.overlay){var aK=this.document.data("ui-dialog-overlays")-1;if(!aK){this.document.off("focusin.ui-dialog");this.document.removeData("ui-dialog-overlays")}else{this.document.data("ui-dialog-overlays",aK)}this.overlay.remove();this.overlay=null}}});if(ax.uiBackCompat!==false){ax.widget("ui.dialog",ax.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super();this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(aK,aL){if(aK==="dialogClass"){this.uiDialog.removeClass(this.options.dialogClass).addClass(aL)}this._superApply(arguments)}})}var ak=ax.ui.dialog;
/*!
 * jQuery UI Progressbar 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var ag=ax.widget("ui.progressbar",{version:"1.13.0",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue();this.element.attr({role:"progressbar","aria-valuemin":this.min});this._addClass("ui-progressbar","ui-widget ui-widget-content");this.valueDiv=ax("<div>").appendTo(this.element);this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header");this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow");this.valueDiv.remove()},value:function(aK){if(aK===undefined){return this.options.value}this.options.value=this._constrainedValue(aK);this._refreshValue()},_constrainedValue:function(aK){if(aK===undefined){aK=this.options.value}this.indeterminate=aK===false;if(typeof aK!=="number"){aK=0}return this.indeterminate?false:Math.min(this.options.max,Math.max(this.min,aK))},_setOptions:function(aK){var aL=aK.value;delete aK.value;this._super(aK);this.options.value=this._constrainedValue(aL);this._refreshValue()},_setOption:function(aK,aL){if(aK==="max"){aL=Math.max(this.min,aL)}this._super(aK,aL)},_setOptionDisabled:function(aK){this._super(aK);this.element.attr("aria-disabled",aK);this._toggleClass(null,"ui-state-disabled",!!aK)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var aL=this.options.value,aK=this._percentage();this.valueDiv.toggle(this.indeterminate||aL>this.min).width(aK.toFixed(0)+"%");this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,aL===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate);if(this.indeterminate){this.element.removeAttr("aria-valuenow");if(!this.overlayDiv){this.overlayDiv=ax("<div>").appendTo(this.valueDiv);this._addClass(this.overlayDiv,"ui-progressbar-overlay")}}else{this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":aL});if(this.overlayDiv){this.overlayDiv.remove();this.overlayDiv=null}}if(this.oldValue!==aL){this.oldValue=aL;this._trigger("change")}if(aL===this.options.max){this._trigger("complete")}}});
/*!
 * jQuery UI Selectmenu 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var e=ax.widget("ui.selectmenu",[ax.ui.formResetMixin,{version:"1.13.0",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:false,change:null,close:null,focus:null,open:null,select:null},_create:function(){var aK=this.element.uniqueId().attr("id");this.ids={element:aK,button:aK+"-button",menu:aK+"-menu"};this._drawButton();this._drawMenu();this._bindFormResetHandler();this._rendered=false;this.menuItems=ax()},_drawButton:function(){var aK,aM=this,aL=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button);this._on(this.labels,{click:function(aN){this.button.trigger("focus");aN.preventDefault()}});this.element.hide();this.button=ax("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element);this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget");aK=ax("<span>").appendTo(this.button);this._addClass(aK,"ui-selectmenu-icon","ui-icon "+this.options.icons.button);this.buttonItem=this._renderButtonItem(aL).appendTo(this.button);if(this.options.width!==false){this._resizeButton()}this._on(this.button,this._buttonEvents);this.button.one("focusin",function(){if(!aM._rendered){aM._refreshMenu()}})},_drawMenu:function(){var aK=this;this.menu=ax("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu});this.menuWrap=ax("<div>").append(this.menu);this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front");this.menuWrap.appendTo(this._appendTo());this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(aL,aM){aL.preventDefault();aK._setSelection();aK._select(aM.item.data("ui-selectmenu-item"),aL)},focus:function(aM,aN){var aL=aN.item.data("ui-selectmenu-item");if(aK.focusIndex!=null&&aL.index!==aK.focusIndex){aK._trigger("focus",aM,{item:aL});if(!aK.isOpen){aK._select(aL,aM)}}aK.focusIndex=aL.index;aK.button.attr("aria-activedescendant",aK.menuItems.eq(aL.index).attr("id"))}}).menu("instance");this.menuInstance._off(this.menu,"mouseleave");this.menuInstance._closeOnDocumentClick=function(){return false};this.menuInstance._isDivider=function(){return false}},refresh:function(){this._refreshMenu();this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{}));if(this.options.width===null){this._resizeButton()}},_refreshMenu:function(){var aL,aK=this.element.find("option");this.menu.empty();this._parseOptions(aK);this._renderMenu(this.menu,this.items);this.menuInstance.refresh();this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper");this._rendered=true;if(!aK.length){return}aL=this._getSelectedItem();this.menuInstance.focus(null,aL);this._setAria(aL.data("ui-selectmenu-item"));this._setOption("disabled",this.element.prop("disabled"))},open:function(aK){if(this.options.disabled){return}if(!this._rendered){this._refreshMenu()}else{this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active");this.menuInstance.focus(null,this._getSelectedItem())}if(!this.menuItems.length){return}this.isOpen=true;this._toggleAttr();this._resizeMenu();this._position();this._on(this.document,this._documentClick);this._trigger("open",aK)},_position:function(){this.menuWrap.position(ax.extend({of:this.button},this.options.position))},close:function(aK){if(!this.isOpen){return}this.isOpen=false;this._toggleAttr();this.range=null;this._off(this.document);this._trigger("close",aK)},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(aL){var aK=ax("<span>");this._setText(aK,aL.label);this._addClass(aK,"ui-selectmenu-text");return aK},_renderMenu:function(aM,aL){var aN=this,aK="";ax.each(aL,function(aP,aQ){var aO;if(aQ.optgroup!==aK){aO=ax("<li>",{text:aQ.optgroup});aN._addClass(aO,"ui-selectmenu-optgroup","ui-menu-divider"+(aQ.element.parent("optgroup").prop("disabled")?" ui-state-disabled":""));aO.appendTo(aM);aK=aQ.optgroup}aN._renderItemData(aM,aQ)})},_renderItemData:function(aK,aL){return this._renderItem(aK,aL).data("ui-selectmenu-item",aL)},_renderItem:function(aL,aM){var aK=ax("<li>"),aN=ax("<div>",{title:aM.element.attr("title")});if(aM.disabled){this._addClass(aK,null,"ui-state-disabled")}this._setText(aN,aM.label);return aK.append(aN).appendTo(aL)},_setText:function(aK,aL){if(aL){aK.text(aL)}else{aK.html("&#160;")}},_move:function(aO,aN){var aM,aL,aK=".ui-menu-item";if(this.isOpen){aM=this.menuItems.eq(this.focusIndex).parent("li")}else{aM=this.menuItems.eq(this.element[0].selectedIndex).parent("li");aK+=":not(.ui-state-disabled)"}if(aO==="first"||aO==="last"){aL=aM[aO==="first"?"prevAll":"nextAll"](aK).eq(-1)}else{aL=aM[aO+"All"](aK).eq(0)}if(aL.length){this.menuInstance.focus(aN,aL)}},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(aK){this[this.isOpen?"close":"open"](aK)},_setSelection:function(){var aK;if(!this.range){return}if(window.getSelection){aK=window.getSelection();aK.removeAllRanges();aK.addRange(this.range)}else{this.range.select()}this.button.focus()},_documentClick:{mousedown:function(aK){if(!this.isOpen){return}if(!ax(aK.target).closest(".ui-selectmenu-menu, #"+ax.escapeSelector(this.ids.button)).length){this.close(aK)}}},_buttonEvents:{mousedown:function(){var aK;if(window.getSelection){aK=window.getSelection();if(aK.rangeCount){this.range=aK.getRangeAt(0)}}else{this.range=document.selection.createRange()}},click:function(aK){this._setSelection();this._toggle(aK)},keydown:function(aL){var aK=true;switch(aL.keyCode){case ax.ui.keyCode.TAB:case ax.ui.keyCode.ESCAPE:this.close(aL);aK=false;break;case ax.ui.keyCode.ENTER:if(this.isOpen){this._selectFocusedItem(aL)}break;case ax.ui.keyCode.UP:if(aL.altKey){this._toggle(aL)}else{this._move("prev",aL)}break;case ax.ui.keyCode.DOWN:if(aL.altKey){this._toggle(aL)}else{this._move("next",aL)}break;case ax.ui.keyCode.SPACE:if(this.isOpen){this._selectFocusedItem(aL)}else{this._toggle(aL)}break;case ax.ui.keyCode.LEFT:this._move("prev",aL);break;case ax.ui.keyCode.RIGHT:this._move("next",aL);break;case ax.ui.keyCode.HOME:case ax.ui.keyCode.PAGE_UP:this._move("first",aL);break;case ax.ui.keyCode.END:case ax.ui.keyCode.PAGE_DOWN:this._move("last",aL);break;default:this.menu.trigger(aL);aK=false}if(aK){aL.preventDefault()}}},_selectFocusedItem:function(aL){var aK=this.menuItems.eq(this.focusIndex).parent("li");if(!aK.hasClass("ui-state-disabled")){this._select(aK.data("ui-selectmenu-item"),aL)}},_select:function(aL,aK){var aM=this.element[0].selectedIndex;this.element[0].selectedIndex=aL.index;this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(aL));this._setAria(aL);this._trigger("select",aK,{item:aL});if(aL.index!==aM){this._trigger("change",aK,{item:aL})}this.close(aK)},_setAria:function(aK){var aL=this.menuItems.eq(aK.index).attr("id");this.button.attr({"aria-labelledby":aL,"aria-activedescendant":aL});this.menu.attr("aria-activedescendant",aL)},_setOption:function(aK,aM){if(aK==="icons"){var aL=this.button.find("span.ui-icon");this._removeClass(aL,null,this.options.icons.button)._addClass(aL,null,aM.button)}this._super(aK,aM);if(aK==="appendTo"){this.menuWrap.appendTo(this._appendTo())}if(aK==="width"){this._resizeButton()}},_setOptionDisabled:function(aK){this._super(aK);this.menuInstance.option("disabled",aK);this.button.attr("aria-disabled",aK);this._toggleClass(this.button,null,"ui-state-disabled",aK);this.element.prop("disabled",aK);if(aK){this.button.attr("tabindex",-1);this.close()}else{this.button.attr("tabindex",0)}},_appendTo:function(){var aK=this.options.appendTo;if(aK){aK=aK.jquery||aK.nodeType?ax(aK):this.document.find(aK).eq(0)}if(!aK||!aK[0]){aK=this.element.closest(".ui-front, dialog")}if(!aK.length){aK=this.document[0].body}return aK},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen);this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen);this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var aK=this.options.width;if(aK===false){this.button.css("width","");return}if(aK===null){aK=this.element.show().outerWidth();this.element.hide()}this.button.outerWidth(aK)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){var aK=this._super();aK.disabled=this.element.prop("disabled");return aK},_parseOptions:function(aK){var aL=this,aM=[];aK.each(function(aN,aO){if(aO.hidden){return}aM.push(aL._parseOption(ax(aO),aN))});this.items=aM},_parseOption:function(aM,aL){var aK=aM.parent("optgroup");return{element:aM,index:aL,value:aM.val(),label:aM.text(),optgroup:aK.attr("label")||"",disabled:aK.prop("disabled")||aM.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler();this.menuWrap.remove();this.button.remove();this.element.show();this.element.removeUniqueId();this.labels.attr("for",this.ids.element)}}]);
/*!
 * jQuery UI Slider 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var X=ax.widget("ui.slider",ax.ui.mouse,{version:"1.13.0",widgetEventPrefix:"slide",options:{animate:false,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=false;this._mouseSliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this._calculateNewMax();this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content");this._refresh();this._animateOff=false},_refresh:function(){this._createRange();this._createHandles();this._setupEvents();this._refreshValue()},_createHandles:function(){var aN,aK,aL=this.options,aP=this.element.find(".ui-slider-handle"),aO="<span tabindex='0'></span>",aM=[];aK=(aL.values&&aL.values.length)||1;if(aP.length>aK){aP.slice(aK).remove();aP=aP.slice(0,aK)}for(aN=aP.length;aN<aK;aN++){aM.push(aO)}this.handles=aP.add(ax(aM.join("")).appendTo(this.element));this._addClass(this.handles,"ui-slider-handle","ui-state-default");this.handle=this.handles.eq(0);this.handles.each(function(aQ){ax(this).data("ui-slider-handle-index",aQ).attr("tabIndex",0)})},_createRange:function(){var aK=this.options;if(aK.range){if(aK.range===true){if(!aK.values){aK.values=[this._valueMin(),this._valueMin()]}else{if(aK.values.length&&aK.values.length!==2){aK.values=[aK.values[0],aK.values[0]]}else{if(Array.isArray(aK.values)){aK.values=aK.values.slice(0)}}}}if(!this.range||!this.range.length){this.range=ax("<div>").appendTo(this.element);this._addClass(this.range,"ui-slider-range")}else{this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max");this.range.css({left:"",bottom:""})}if(aK.range==="min"||aK.range==="max"){this._addClass(this.range,"ui-slider-range-"+aK.range)}}else{if(this.range){this.range.remove()}this.range=null}},_setupEvents:function(){this._off(this.handles);this._on(this.handles,this._handleEvents);this._hoverable(this.handles);this._focusable(this.handles)},_destroy:function(){this.handles.remove();if(this.range){this.range.remove()}this._mouseDestroy()},_mouseCapture:function(aM){var aQ,aT,aL,aO,aS,aU,aP,aK,aR=this,aN=this.options;if(aN.disabled){return false}this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();aQ={x:aM.pageX,y:aM.pageY};aT=this._normValueFromMouse(aQ);aL=this._valueMax()-this._valueMin()+1;this.handles.each(function(aV){var aW=Math.abs(aT-aR.values(aV));if((aL>aW)||(aL===aW&&(aV===aR._lastChangedValue||aR.values(aV)===aN.min))){aL=aW;aO=ax(this);aS=aV}});aU=this._start(aM,aS);if(aU===false){return false}this._mouseSliding=true;this._handleIndex=aS;this._addClass(aO,null,"ui-state-active");aO.trigger("focus");aP=aO.offset();aK=!ax(aM.target).parents().addBack().is(".ui-slider-handle");this._clickOffset=aK?{left:0,top:0}:{left:aM.pageX-aP.left-(aO.width()/2),top:aM.pageY-aP.top-(aO.height()/2)-(parseInt(aO.css("borderTopWidth"),10)||0)-(parseInt(aO.css("borderBottomWidth"),10)||0)+(parseInt(aO.css("marginTop"),10)||0)};if(!this.handles.hasClass("ui-state-hover")){this._slide(aM,aS,aT)}this._animateOff=true;return true},_mouseStart:function(){return true},_mouseDrag:function(aM){var aK={x:aM.pageX,y:aM.pageY},aL=this._normValueFromMouse(aK);this._slide(aM,this._handleIndex,aL);return false},_mouseStop:function(aK){this._removeClass(this.handles,null,"ui-state-active");this._mouseSliding=false;this._stop(aK,this._handleIndex);this._change(aK,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(aL){var aK,aO,aN,aM,aP;if(this.orientation==="horizontal"){aK=this.elementSize.width;aO=aL.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{aK=this.elementSize.height;aO=aL.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}aN=(aO/aK);if(aN>1){aN=1}if(aN<0){aN=0}if(this.orientation==="vertical"){aN=1-aN}aM=this._valueMax()-this._valueMin();aP=this._valueMin()+aN*aM;return this._trimAlignValue(aP)},_uiHash:function(aM,aN,aK){var aL={handle:this.handles[aM],handleIndex:aM,value:aN!==undefined?aN:this.value()};if(this._hasMultipleValues()){aL.value=aN!==undefined?aN:this.values(aM);aL.values=aK||this.values()}return aL},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(aL,aK){return this._trigger("start",aL,this._uiHash(aK))},_slide:function(aP,aN,aM){var aQ,aK,aO=this.value(),aL=this.values();if(this._hasMultipleValues()){aK=this.values(aN?0:1);aO=this.values(aN);if(this.options.values.length===2&&this.options.range===true){aM=aN===0?Math.min(aK,aM):Math.max(aK,aM)}aL[aN]=aM}if(aM===aO){return}aQ=this._trigger("slide",aP,this._uiHash(aN,aM,aL));if(aQ===false){return}if(this._hasMultipleValues()){this.values(aN,aM)}else{this.value(aM)}},_stop:function(aL,aK){this._trigger("stop",aL,this._uiHash(aK))},_change:function(aL,aK){if(!this._keySliding&&!this._mouseSliding){this._lastChangedValue=aK;this._trigger("change",aL,this._uiHash(aK))}},value:function(aK){if(arguments.length){this.options.value=this._trimAlignValue(aK);this._refreshValue();this._change(null,0);return}return this._value()},values:function(aL,aO){var aN,aK,aM;if(arguments.length>1){this.options.values[aL]=this._trimAlignValue(aO);this._refreshValue();this._change(null,aL);return}if(arguments.length){if(Array.isArray(arguments[0])){aN=this.options.values;aK=arguments[0];for(aM=0;aM<aN.length;aM+=1){aN[aM]=this._trimAlignValue(aK[aM]);this._change(null,aM)}this._refreshValue()}else{if(this._hasMultipleValues()){return this._values(aL)}else{return this.value()}}}else{return this._values()}},_setOption:function(aL,aM){var aK,aN=0;if(aL==="range"&&this.options.range===true){if(aM==="min"){this.options.value=this._values(0);this.options.values=null}else{if(aM==="max"){this.options.value=this._values(this.options.values.length-1);this.options.values=null}}}if(Array.isArray(this.options.values)){aN=this.options.values.length}this._super(aL,aM);switch(aL){case"orientation":this._detectOrientation();this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation);this._refreshValue();if(this.options.range){this._refreshRange(aM)}this.handles.css(aM==="horizontal"?"bottom":"left","");break;case"value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case"values":this._animateOff=true;this._refreshValue();for(aK=aN-1;aK>=0;aK--){this._change(null,aK)}this._animateOff=false;break;case"step":case"min":case"max":this._animateOff=true;this._calculateNewMax();this._refreshValue();this._animateOff=false;break;case"range":this._animateOff=true;this._refresh();this._animateOff=false;break}},_setOptionDisabled:function(aK){this._super(aK);this._toggleClass(null,"ui-state-disabled",!!aK)},_value:function(){var aK=this.options.value;aK=this._trimAlignValue(aK);return aK},_values:function(aK){var aN,aM,aL;if(arguments.length){aN=this.options.values[aK];aN=this._trimAlignValue(aN);return aN}else{if(this._hasMultipleValues()){aM=this.options.values.slice();for(aL=0;aL<aM.length;aL+=1){aM[aL]=this._trimAlignValue(aM[aL])}return aM}else{return[]}}},_trimAlignValue:function(aN){if(aN<=this._valueMin()){return this._valueMin()}if(aN>=this._valueMax()){return this._valueMax()}var aK=(this.options.step>0)?this.options.step:1,aM=(aN-this._valueMin())%aK,aL=aN-aM;if(Math.abs(aM)*2>=aK){aL+=(aM>0)?aK:(-aK)}return parseFloat(aL.toFixed(5))},_calculateNewMax:function(){var aK=this.options.max,aL=this._valueMin(),aM=this.options.step,aN=Math.round((aK-aL)/aM)*aM;aK=aN+aL;if(aK>this.options.max){aK-=aM}this.max=parseFloat(aK.toFixed(this._precision()))},_precision:function(){var aK=this._precisionOf(this.options.step);if(this.options.min!==null){aK=Math.max(aK,this._precisionOf(this.options.min))}return aK},_precisionOf:function(aL){var aM=aL.toString(),aK=aM.indexOf(".");return aK===-1?0:aM.length-aK-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(aK){if(aK==="vertical"){this.range.css({width:"",left:""})}if(aK==="horizontal"){this.range.css({height:"",bottom:""})}},_refreshValue:function(){var aP,aO,aS,aQ,aT,aN=this.options.range,aM=this.options,aR=this,aL=(!this._animateOff)?aM.animate:false,aK={};if(this._hasMultipleValues()){this.handles.each(function(aU){aO=(aR.values(aU)-aR._valueMin())/(aR._valueMax()-aR._valueMin())*100;aK[aR.orientation==="horizontal"?"left":"bottom"]=aO+"%";ax(this).stop(1,1)[aL?"animate":"css"](aK,aM.animate);if(aR.options.range===true){if(aR.orientation==="horizontal"){if(aU===0){aR.range.stop(1,1)[aL?"animate":"css"]({left:aO+"%"},aM.animate)}if(aU===1){aR.range[aL?"animate":"css"]({width:(aO-aP)+"%"},{queue:false,duration:aM.animate})}}else{if(aU===0){aR.range.stop(1,1)[aL?"animate":"css"]({bottom:(aO)+"%"},aM.animate)}if(aU===1){aR.range[aL?"animate":"css"]({height:(aO-aP)+"%"},{queue:false,duration:aM.animate})}}}aP=aO})}else{aS=this.value();aQ=this._valueMin();aT=this._valueMax();aO=(aT!==aQ)?(aS-aQ)/(aT-aQ)*100:0;aK[this.orientation==="horizontal"?"left":"bottom"]=aO+"%";this.handle.stop(1,1)[aL?"animate":"css"](aK,aM.animate);if(aN==="min"&&this.orientation==="horizontal"){this.range.stop(1,1)[aL?"animate":"css"]({width:aO+"%"},aM.animate)}if(aN==="max"&&this.orientation==="horizontal"){this.range.stop(1,1)[aL?"animate":"css"]({width:(100-aO)+"%"},aM.animate)}if(aN==="min"&&this.orientation==="vertical"){this.range.stop(1,1)[aL?"animate":"css"]({height:aO+"%"},aM.animate)}if(aN==="max"&&this.orientation==="vertical"){this.range.stop(1,1)[aL?"animate":"css"]({height:(100-aO)+"%"},aM.animate)}}},_handleEvents:{keydown:function(aO){var aP,aM,aL,aN,aK=ax(aO.target).data("ui-slider-handle-index");switch(aO.keyCode){case ax.ui.keyCode.HOME:case ax.ui.keyCode.END:case ax.ui.keyCode.PAGE_UP:case ax.ui.keyCode.PAGE_DOWN:case ax.ui.keyCode.UP:case ax.ui.keyCode.RIGHT:case ax.ui.keyCode.DOWN:case ax.ui.keyCode.LEFT:aO.preventDefault();if(!this._keySliding){this._keySliding=true;this._addClass(ax(aO.target),null,"ui-state-active");aP=this._start(aO,aK);if(aP===false){return}}break}aN=this.options.step;if(this._hasMultipleValues()){aM=aL=this.values(aK)}else{aM=aL=this.value()}switch(aO.keyCode){case ax.ui.keyCode.HOME:aL=this._valueMin();break;case ax.ui.keyCode.END:aL=this._valueMax();break;case ax.ui.keyCode.PAGE_UP:aL=this._trimAlignValue(aM+((this._valueMax()-this._valueMin())/this.numPages));break;case ax.ui.keyCode.PAGE_DOWN:aL=this._trimAlignValue(aM-((this._valueMax()-this._valueMin())/this.numPages));break;case ax.ui.keyCode.UP:case ax.ui.keyCode.RIGHT:if(aM===this._valueMax()){return}aL=this._trimAlignValue(aM+aN);break;case ax.ui.keyCode.DOWN:case ax.ui.keyCode.LEFT:if(aM===this._valueMin()){return}aL=this._trimAlignValue(aM-aN);break}this._slide(aO,aK,aL)},keyup:function(aL){var aK=ax(aL.target).data("ui-slider-handle-index");if(this._keySliding){this._keySliding=false;this._stop(aL,aK);this._change(aL,aK);this._removeClass(ax(aL.target),null,"ui-state-active")}}}});
/*!
 * jQuery UI Spinner 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
function n(aK){return function(){var aL=this.element.val();aK.apply(this,arguments);this._refresh();if(aL!==this.element.val()){this._trigger("change")}}}ax.widget("ui.spinner",{version:"1.13.0",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:true,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max);this._setOption("min",this.options.min);this._setOption("step",this.options.step);if(this.value()!==""){this._value(this.element.val(),true)}this._draw();this._on(this._events);this._refresh();this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var aK=this._super();var aL=this.element;ax.each(["min","max","step"],function(aM,aN){var aO=aL.attr(aN);if(aO!=null&&aO.length){aK[aN]=aO}});return aK},_events:{keydown:function(aK){if(this._start(aK)&&this._keydown(aK)){aK.preventDefault()}},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(aK){if(this.cancelBlur){delete this.cancelBlur;return}this._stop();this._refresh();if(this.previous!==this.element.val()){this._trigger("change",aK)}},mousewheel:function(aM,aN){var aL=ax.ui.safeActiveElement(this.document[0]);var aK=this.element[0]===aL;if(!aK||!aN){return}if(!this.spinning&&!this._start(aM)){return false}this._spin((aN>0?1:-1)*this.options.step,aM);clearTimeout(this.mousewheelTimer);this.mousewheelTimer=this._delay(function(){if(this.spinning){this._stop(aM)}},100);aM.preventDefault()},"mousedown .ui-spinner-button":function(aL){var aK;aK=this.element[0]===ax.ui.safeActiveElement(this.document[0])?this.previous:this.element.val();function aM(){var aN=this.element[0]===ax.ui.safeActiveElement(this.document[0]);if(!aN){this.element.trigger("focus");this.previous=aK;this._delay(function(){this.previous=aK})}}aL.preventDefault();aM.call(this);this.cancelBlur=true;this._delay(function(){delete this.cancelBlur;aM.call(this)});if(this._start(aL)===false){return}this._repeat(null,ax(aL.currentTarget).hasClass("ui-spinner-up")?1:-1,aL)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(aK){if(!ax(aK.currentTarget).hasClass("ui-state-active")){return}if(this._start(aK)===false){return false}this._repeat(null,ax(aK.currentTarget).hasClass("ui-spinner-up")?1:-1,aK)},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance();this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content");this._addClass("ui-spinner-input");this.element.attr("role","spinbutton");this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",true).button({classes:{"ui-button":""}});this._removeClass(this.buttons,"ui-corner-all");this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up");this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down");this.buttons.first().button({icon:this.options.icons.up,showLabel:false});this.buttons.last().button({icon:this.options.icons.down,showLabel:false});if(this.buttons.height()>Math.ceil(this.uiSpinner.height()*0.5)&&this.uiSpinner.height()>0){this.uiSpinner.height(this.uiSpinner.height())}},_keydown:function(aL){var aK=this.options,aM=ax.ui.keyCode;switch(aL.keyCode){case aM.UP:this._repeat(null,1,aL);return true;case aM.DOWN:this._repeat(null,-1,aL);return true;case aM.PAGE_UP:this._repeat(null,aK.page,aL);return true;case aM.PAGE_DOWN:this._repeat(null,-aK.page,aL);return true}return false},_start:function(aK){if(!this.spinning&&this._trigger("start",aK)===false){return false}if(!this.counter){this.counter=1}this.spinning=true;return true},_repeat:function(aL,aK,aM){aL=aL||500;clearTimeout(this.timer);this.timer=this._delay(function(){this._repeat(40,aK,aM)},aL);this._spin(aK*this.options.step,aM)},_spin:function(aL,aK){var aM=this.value()||0;if(!this.counter){this.counter=1}aM=this._adjustValue(aM+aL*this._increment(this.counter));if(!this.spinning||this._trigger("spin",aK,{value:aM})!==false){this._value(aM);this.counter++}},_increment:function(aK){var aL=this.options.incremental;if(aL){return typeof aL==="function"?aL(aK):Math.floor(aK*aK*aK/50000-aK*aK/500+17*aK/200+1)}return 1},_precision:function(){var aK=this._precisionOf(this.options.step);if(this.options.min!==null){aK=Math.max(aK,this._precisionOf(this.options.min))}return aK},_precisionOf:function(aL){var aM=aL.toString(),aK=aM.indexOf(".");return aK===-1?0:aM.length-aK-1},_adjustValue:function(aM){var aL,aN,aK=this.options;aL=aK.min!==null?aK.min:0;aN=aM-aL;aN=Math.round(aN/aK.step)*aK.step;aM=aL+aN;aM=parseFloat(aM.toFixed(this._precision()));if(aK.max!==null&&aM>aK.max){return aK.max}if(aK.min!==null&&aM<aK.min){return aK.min}return aM},_stop:function(aK){if(!this.spinning){return}clearTimeout(this.timer);clearTimeout(this.mousewheelTimer);this.counter=0;this.spinning=false;this._trigger("stop",aK)},_setOption:function(aK,aM){var aN,aO,aL;if(aK==="culture"||aK==="numberFormat"){aN=this._parse(this.element.val());this.options[aK]=aM;this.element.val(this._format(aN));return}if(aK==="max"||aK==="min"||aK==="step"){if(typeof aM==="string"){aM=this._parse(aM)}}if(aK==="icons"){aO=this.buttons.first().find(".ui-icon");this._removeClass(aO,null,this.options.icons.up);this._addClass(aO,null,aM.up);aL=this.buttons.last().find(".ui-icon");this._removeClass(aL,null,this.options.icons.down);this._addClass(aL,null,aM.down)}this._super(aK,aM)},_setOptionDisabled:function(aK){this._super(aK);this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!aK);this.element.prop("disabled",!!aK);this.buttons.button(aK?"disable":"enable")},_setOptions:n(function(aK){this._super(aK)}),_parse:function(aK){if(typeof aK==="string"&&aK!==""){aK=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(aK,10,this.options.culture):+aK}return aK===""||isNaN(aK)?null:aK},_format:function(aK){if(aK===""){return""}return window.Globalize&&this.options.numberFormat?Globalize.format(aK,this.options.numberFormat,this.options.culture):aK},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var aK=this.value();if(aK===null){return false}return aK===this._adjustValue(aK)},_value:function(aM,aK){var aL;if(aM!==""){aL=this._parse(aM);if(aL!==null){if(!aK){aL=this._adjustValue(aL)}aM=this._format(aL)}}this.element.val(aM);this._refresh()},_destroy:function(){this.element.prop("disabled",false).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow");this.uiSpinner.replaceWith(this.element)},stepUp:n(function(aK){this._stepUp(aK)}),_stepUp:function(aK){if(this._start()){this._spin((aK||1)*this.options.step);this._stop()}},stepDown:n(function(aK){this._stepDown(aK)}),_stepDown:function(aK){if(this._start()){this._spin((aK||1)*-this.options.step);this._stop()}},pageUp:n(function(aK){this._stepUp((aK||1)*this.options.page)}),pageDown:n(function(aK){this._stepDown((aK||1)*this.options.page)}),value:function(aK){if(!arguments.length){return this._parse(this.element.val())}n(this._value).call(this,aK)},widget:function(){return this.uiSpinner}});if(ax.uiBackCompat!==false){ax.widget("ui.spinner",ax.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}})}var ap=ax.ui.spinner;
/*!
 * jQuery UI Tabs 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.tabs",{version:"1.13.0",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:false,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:(function(){var aK=/#.*$/;return function(aM){var aO,aN;aO=aM.href.replace(aK,"");aN=location.href.replace(aK,"");try{aO=decodeURIComponent(aO)}catch(aL){}try{aN=decodeURIComponent(aN)}catch(aL){}return aM.hash.length>1&&aO===aN}})(),_create:function(){var aL=this,aK=this.options;this.running=false;this._addClass("ui-tabs","ui-widget ui-widget-content");this._toggleClass("ui-tabs-collapsible",null,aK.collapsible);this._processTabs();aK.active=this._initialActive();if(Array.isArray(aK.disabled)){aK.disabled=ax.uniqueSort(aK.disabled.concat(ax.map(this.tabs.filter(".ui-state-disabled"),function(aM){return aL.tabs.index(aM)}))).sort()}if(this.options.active!==false&&this.anchors.length){this.active=this._findActive(aK.active)}else{this.active=ax()}this._refresh();if(this.active.length){this.load(aK.active)}},_initialActive:function(){var aL=this.options.active,aK=this.options.collapsible,aM=location.hash.substring(1);if(aL===null){if(aM){this.tabs.each(function(aN,aO){if(ax(aO).attr("aria-controls")===aM){aL=aN;return false}})}if(aL===null){aL=this.tabs.index(this.tabs.filter(".ui-tabs-active"))}if(aL===null||aL===-1){aL=this.tabs.length?0:false}}if(aL!==false){aL=this.tabs.index(this.tabs.eq(aL));if(aL===-1){aL=aK?false:0}}if(!aK&&aL===false&&this.anchors.length){aL=0}return aL},_getCreateEventData:function(){return{tab:this.active,panel:!this.active.length?ax():this._getPanelForTab(this.active)}},_tabKeydown:function(aM){var aL=ax(ax.ui.safeActiveElement(this.document[0])).closest("li"),aK=this.tabs.index(aL),aN=true;if(this._handlePageNav(aM)){return}switch(aM.keyCode){case ax.ui.keyCode.RIGHT:case ax.ui.keyCode.DOWN:aK++;break;case ax.ui.keyCode.UP:case ax.ui.keyCode.LEFT:aN=false;aK--;break;case ax.ui.keyCode.END:aK=this.anchors.length-1;break;case ax.ui.keyCode.HOME:aK=0;break;case ax.ui.keyCode.SPACE:aM.preventDefault();clearTimeout(this.activating);this._activate(aK);return;case ax.ui.keyCode.ENTER:aM.preventDefault();clearTimeout(this.activating);this._activate(aK===this.options.active?false:aK);return;default:return}aM.preventDefault();clearTimeout(this.activating);aK=this._focusNextTab(aK,aN);if(!aM.ctrlKey&&!aM.metaKey){aL.attr("aria-selected","false");this.tabs.eq(aK).attr("aria-selected","true");this.activating=this._delay(function(){this.option("active",aK)},this.delay)}},_panelKeydown:function(aK){if(this._handlePageNav(aK)){return}if(aK.ctrlKey&&aK.keyCode===ax.ui.keyCode.UP){aK.preventDefault();this.active.trigger("focus")}},_handlePageNav:function(aK){if(aK.altKey&&aK.keyCode===ax.ui.keyCode.PAGE_UP){this._activate(this._focusNextTab(this.options.active-1,false));return true}if(aK.altKey&&aK.keyCode===ax.ui.keyCode.PAGE_DOWN){this._activate(this._focusNextTab(this.options.active+1,true));return true}},_findNextTab:function(aL,aM){var aK=this.tabs.length-1;function aN(){if(aL>aK){aL=0}if(aL<0){aL=aK}return aL}while(ax.inArray(aN(),this.options.disabled)!==-1){aL=aM?aL+1:aL-1}return aL},_focusNextTab:function(aK,aL){aK=this._findNextTab(aK,aL);this.tabs.eq(aK).trigger("focus");return aK},_setOption:function(aK,aL){if(aK==="active"){this._activate(aL);return}this._super(aK,aL);if(aK==="collapsible"){this._toggleClass("ui-tabs-collapsible",null,aL);if(!aL&&this.options.active===false){this._activate(0)}}if(aK==="event"){this._setupEvents(aL)}if(aK==="heightStyle"){this._setupHeightStyle(aL)}},_sanitizeSelector:function(aK){return aK?aK.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var aL=this.options,aK=this.tablist.children(":has(a[href])");aL.disabled=ax.map(aK.filter(".ui-state-disabled"),function(aM){return aK.index(aM)});this._processTabs();if(aL.active===false||!this.anchors.length){aL.active=false;this.active=ax()}else{if(this.active.length&&!ax.contains(this.tablist[0],this.active[0])){if(this.tabs.length===aL.disabled.length){aL.active=false;this.active=ax()}else{this._activate(this._findNextTab(Math.max(0,aL.active-1),false))}}else{aL.active=this.tabs.index(this.active)}}this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled);this._setupEvents(this.options.event);this._setupHeightStyle(this.options.heightStyle);this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1});this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"});if(!this.active.length){this.tabs.eq(0).attr("tabIndex",0)}else{this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0});this._addClass(this.active,"ui-tabs-active","ui-state-active");this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})}},_processTabs:function(){var aM=this,aN=this.tabs,aL=this.anchors,aK=this.panels;this.tablist=this._getList().attr("role","tablist");this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header");this.tablist.on("mousedown"+this.eventNamespace,"> li",function(aO){if(ax(this).is(".ui-state-disabled")){aO.preventDefault()}}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){if(ax(this).closest("li").is(".ui-state-disabled")){this.blur()}});this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1});this._addClass(this.tabs,"ui-tabs-tab","ui-state-default");this.anchors=this.tabs.map(function(){return ax("a",this)[0]}).attr({tabIndex:-1});this._addClass(this.anchors,"ui-tabs-anchor");this.panels=ax();this.anchors.each(function(aT,aR){var aO,aP,aS,aQ=ax(aR).uniqueId().attr("id"),aU=ax(aR).closest("li"),aV=aU.attr("aria-controls");if(aM._isLocal(aR)){aO=aR.hash;aS=aO.substring(1);aP=aM.element.find(aM._sanitizeSelector(aO))}else{aS=aU.attr("aria-controls")||ax({}).uniqueId()[0].id;aO="#"+aS;aP=aM.element.find(aO);if(!aP.length){aP=aM._createPanel(aS);aP.insertAfter(aM.panels[aT-1]||aM.tablist)}aP.attr("aria-live","polite")}if(aP.length){aM.panels=aM.panels.add(aP)}if(aV){aU.data("ui-tabs-aria-controls",aV)}aU.attr({"aria-controls":aS,"aria-labelledby":aQ});aP.attr("aria-labelledby",aQ)});this.panels.attr("role","tabpanel");this._addClass(this.panels,"ui-tabs-panel","ui-widget-content");if(aN){this._off(aN.not(this.tabs));this._off(aL.not(this.anchors));this._off(aK.not(this.panels))}},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(aK){return ax("<div>").attr("id",aK).data("ui-tabs-destroy",true)},_setOptionDisabled:function(aN){var aM,aK,aL;if(Array.isArray(aN)){if(!aN.length){aN=false}else{if(aN.length===this.anchors.length){aN=true}}}for(aL=0;(aK=this.tabs[aL]);aL++){aM=ax(aK);if(aN===true||ax.inArray(aL,aN)!==-1){aM.attr("aria-disabled","true");this._addClass(aM,null,"ui-state-disabled")}else{aM.removeAttr("aria-disabled");this._removeClass(aM,null,"ui-state-disabled")}}this.options.disabled=aN;this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,aN===true)},_setupEvents:function(aL){var aK={};if(aL){ax.each(aL.split(" "),function(aN,aM){aK[aM]="_eventHandler"})}this._off(this.anchors.add(this.tabs).add(this.panels));this._on(true,this.anchors,{click:function(aM){aM.preventDefault()}});this._on(this.anchors,aK);this._on(this.tabs,{keydown:"_tabKeydown"});this._on(this.panels,{keydown:"_panelKeydown"});this._focusable(this.tabs);this._hoverable(this.tabs)},_setupHeightStyle:function(aK){var aM,aL=this.element.parent();if(aK==="fill"){aM=aL.height();aM-=this.element.outerHeight()-this.element.height();this.element.siblings(":visible").each(function(){var aO=ax(this),aN=aO.css("position");if(aN==="absolute"||aN==="fixed"){return}aM-=aO.outerHeight(true)});this.element.children().not(this.panels).each(function(){aM-=ax(this).outerHeight(true)});this.panels.each(function(){ax(this).height(Math.max(0,aM-ax(this).innerHeight()+ax(this).height()))}).css("overflow","auto")}else{if(aK==="auto"){aM=0;this.panels.each(function(){aM=Math.max(aM,ax(this).height("").height())}).height(aM)}}},_eventHandler:function(aK){var aT=this.options,aO=this.active,aP=ax(aK.currentTarget),aN=aP.closest("li"),aR=aN[0]===aO[0],aL=aR&&aT.collapsible,aM=aL?ax():this._getPanelForTab(aN),aQ=!aO.length?ax():this._getPanelForTab(aO),aS={oldTab:aO,oldPanel:aQ,newTab:aL?ax():aN,newPanel:aM};aK.preventDefault();if(aN.hasClass("ui-state-disabled")||aN.hasClass("ui-tabs-loading")||this.running||(aR&&!aT.collapsible)||(this._trigger("beforeActivate",aK,aS)===false)){return}aT.active=aL?false:this.tabs.index(aN);this.active=aR?ax():aN;if(this.xhr){this.xhr.abort()}if(!aQ.length&&!aM.length){ax.error("jQuery UI Tabs: Mismatching fragment identifier.")}if(aM.length){this.load(this.tabs.index(aN),aK)}this._toggle(aK,aS)},_toggle:function(aQ,aP){var aO=this,aK=aP.newPanel,aN=aP.oldPanel;this.running=true;function aM(){aO.running=false;aO._trigger("activate",aQ,aP)}function aL(){aO._addClass(aP.newTab.closest("li"),"ui-tabs-active","ui-state-active");if(aK.length&&aO.options.show){aO._show(aK,aO.options.show,aM)}else{aK.show();aM()}}if(aN.length&&this.options.hide){this._hide(aN,this.options.hide,function(){aO._removeClass(aP.oldTab.closest("li"),"ui-tabs-active","ui-state-active");aL()})}else{this._removeClass(aP.oldTab.closest("li"),"ui-tabs-active","ui-state-active");aN.hide();aL()}aN.attr("aria-hidden","true");aP.oldTab.attr({"aria-selected":"false","aria-expanded":"false"});if(aK.length&&aN.length){aP.oldTab.attr("tabIndex",-1)}else{if(aK.length){this.tabs.filter(function(){return ax(this).attr("tabIndex")===0}).attr("tabIndex",-1)}}aK.attr("aria-hidden","false");aP.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(aL){var aK,aM=this._findActive(aL);if(aM[0]===this.active[0]){return}if(!aM.length){aM=this.active}aK=aM.find(".ui-tabs-anchor")[0];this._eventHandler({target:aK,currentTarget:aK,preventDefault:ax.noop})},_findActive:function(aK){return aK===false?ax():this.tabs.eq(aK)},_getIndex:function(aK){if(typeof aK==="string"){aK=this.anchors.index(this.anchors.filter("[href$='"+ax.escapeSelector(aK)+"']"))}return aK},_destroy:function(){if(this.xhr){this.xhr.abort()}this.tablist.removeAttr("role").off(this.eventNamespace);this.anchors.removeAttr("role tabIndex").removeUniqueId();this.tabs.add(this.panels).each(function(){if(ax.data(this,"ui-tabs-destroy")){ax(this).remove()}else{ax(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}});this.tabs.each(function(){var aK=ax(this),aL=aK.data("ui-tabs-aria-controls");if(aL){aK.attr("aria-controls",aL).removeData("ui-tabs-aria-controls")}else{aK.removeAttr("aria-controls")}});this.panels.show();if(this.options.heightStyle!=="content"){this.panels.css("height","")}},enable:function(aK){var aL=this.options.disabled;if(aL===false){return}if(aK===undefined){aL=false}else{aK=this._getIndex(aK);if(Array.isArray(aL)){aL=ax.map(aL,function(aM){return aM!==aK?aM:null})}else{aL=ax.map(this.tabs,function(aM,aN){return aN!==aK?aN:null})}}this._setOptionDisabled(aL)},disable:function(aK){var aL=this.options.disabled;if(aL===true){return}if(aK===undefined){aL=true}else{aK=this._getIndex(aK);if(ax.inArray(aK,aL)!==-1){return}if(Array.isArray(aL)){aL=ax.merge([aK],aL).sort()}else{aL=[aK]}}this._setOptionDisabled(aL)},load:function(aN,aR){aN=this._getIndex(aN);var aQ=this,aO=this.tabs.eq(aN),aM=aO.find(".ui-tabs-anchor"),aL=this._getPanelForTab(aO),aP={tab:aO,panel:aL},aK=function(aT,aS){if(aS==="abort"){aQ.panels.stop(false,true)}aQ._removeClass(aO,"ui-tabs-loading");aL.removeAttr("aria-busy");if(aT===aQ.xhr){delete aQ.xhr}};if(this._isLocal(aM[0])){return}this.xhr=ax.ajax(this._ajaxSettings(aM,aR,aP));if(this.xhr&&this.xhr.statusText!=="canceled"){this._addClass(aO,"ui-tabs-loading");aL.attr("aria-busy","true");this.xhr.done(function(aT,aS,aU){setTimeout(function(){aL.html(aT);aQ._trigger("load",aR,aP);aK(aU,aS)},1)}).fail(function(aT,aS){setTimeout(function(){aK(aT,aS)},1)})}},_ajaxSettings:function(aK,aN,aM){var aL=this;return{url:aK.attr("href").replace(/#.*$/,""),beforeSend:function(aP,aO){return aL._trigger("beforeLoad",aN,ax.extend({jqXHR:aP,ajaxSettings:aO},aM))}}},_getPanelForTab:function(aK){var aL=ax(aK).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+aL))}});if(ax.uiBackCompat!==false){ax.widget("ui.tabs",ax.ui.tabs,{_processTabs:function(){this._superApply(arguments);this._addClass(this.tabs,"ui-tab")}})}var Y=ax.ui.tabs;
/*!
 * jQuery UI Tooltip 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
ax.widget("ui.tooltip",{version:"1.13.0",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var aK=ax(this).attr("title");return ax("<a>").text(aK).html()},hide:true,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:true,track:false,close:null,open:null},_addDescribedBy:function(aL,aM){var aK=(aL.attr("aria-describedby")||"").split(/\s+/);aK.push(aM);aL.data("ui-tooltip-id",aM).attr("aria-describedby",String.prototype.trim.call(aK.join(" ")))},_removeDescribedBy:function(aM){var aN=aM.data("ui-tooltip-id"),aL=(aM.attr("aria-describedby")||"").split(/\s+/),aK=ax.inArray(aN,aL);if(aK!==-1){aL.splice(aK,1)}aM.removeData("ui-tooltip-id");aL=String.prototype.trim.call(aL.join(" "));if(aL){aM.attr("aria-describedby",aL)}else{aM.removeAttr("aria-describedby")}},_create:function(){this._on({mouseover:"open",focusin:"open"});this.tooltips={};this.parents={};this.liveRegion=ax("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body);this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible");this.disabledTitles=ax([])},_setOption:function(aK,aM){var aL=this;this._super(aK,aM);if(aK==="content"){ax.each(this.tooltips,function(aO,aN){aL._updateContent(aN.element)})}},_setOptionDisabled:function(aK){this[aK?"_disable":"_enable"]()},_disable:function(){var aK=this;ax.each(this.tooltips,function(aN,aM){var aL=ax.Event("blur");aL.target=aL.currentTarget=aM.element[0];aK.close(aL,true)});this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var aL=ax(this);if(aL.is("[title]")){return aL.data("ui-tooltip-title",aL.attr("title")).removeAttr("title")}}))},_enable:function(){this.disabledTitles.each(function(){var aK=ax(this);if(aK.data("ui-tooltip-title")){aK.attr("title",aK.data("ui-tooltip-title"))}});this.disabledTitles=ax([])},open:function(aL){var aK=this,aM=ax(aL?aL.target:this.element).closest(this.options.items);if(!aM.length||aM.data("ui-tooltip-id")){return}if(aM.attr("title")){aM.data("ui-tooltip-title",aM.attr("title"))}aM.data("ui-tooltip-open",true);if(aL&&aL.type==="mouseover"){aM.parents().each(function(){var aO=ax(this),aN;if(aO.data("ui-tooltip-open")){aN=ax.Event("blur");aN.target=aN.currentTarget=this;aK.close(aN,true)}if(aO.attr("title")){aO.uniqueId();aK.parents[this.id]={element:this,title:aO.attr("title")};aO.attr("title","")}})}this._registerCloseHandlers(aL,aM);this._updateContent(aM,aL)},_updateContent:function(aP,aO){var aN,aK=this.options.content,aM=this,aL=aO?aO.type:null;if(typeof aK==="string"||aK.nodeType||aK.jquery){return this._open(aO,aP,aK)}aN=aK.call(aP[0],function(aQ){aM._delay(function(){if(!aP.data("ui-tooltip-open")){return}if(aO){aO.type=aL}this._open(aO,aP,aQ)})});if(aN){this._open(aO,aP,aN)}},_open:function(aL,aO,aP){var aK,aS,aR,aM,aQ=ax.extend({},this.options.position);if(!aP){return}aK=this._find(aO);if(aK){aK.tooltip.find(".ui-tooltip-content").html(aP);return}if(aO.is("[title]")){if(aL&&aL.type==="mouseover"){aO.attr("title","")}else{aO.removeAttr("title")}}aK=this._tooltip(aO);aS=aK.tooltip;this._addDescribedBy(aO,aS.attr("id"));aS.find(".ui-tooltip-content").html(aP);this.liveRegion.children().hide();aM=ax("<div>").html(aS.find(".ui-tooltip-content").html());aM.removeAttr("name").find("[name]").removeAttr("name");aM.removeAttr("id").find("[id]").removeAttr("id");aM.appendTo(this.liveRegion);function aN(aT){aQ.of=aT;if(aS.is(":hidden")){return}aS.position(aQ)}if(this.options.track&&aL&&/^mouse/.test(aL.type)){this._on(this.document,{mousemove:aN});aN(aL)}else{aS.position(ax.extend({of:aO},this.options.position))}aS.hide();this._show(aS,this.options.show);if(this.options.track&&this.options.show&&this.options.show.delay){aR=this.delayedShow=setInterval(function(){if(aS.is(":visible")){aN(aQ.of);clearInterval(aR)}},13)}this._trigger("open",aL,{tooltip:aS})},_registerCloseHandlers:function(aL,aM){var aK={keyup:function(aN){if(aN.keyCode===ax.ui.keyCode.ESCAPE){var aO=ax.Event(aN);aO.currentTarget=aM[0];this.close(aO,true)}}};if(aM[0]!==this.element[0]){aK.remove=function(){this._removeTooltip(this._find(aM).tooltip)}}if(!aL||aL.type==="mouseover"){aK.mouseleave="close"}if(!aL||aL.type==="focusin"){aK.focusout="close"}this._on(true,aM,aK)},close:function(aL){var aN,aK=this,aO=ax(aL?aL.currentTarget:this.element),aM=this._find(aO);if(!aM){aO.removeData("ui-tooltip-open");return}aN=aM.tooltip;if(aM.closing){return}clearInterval(this.delayedShow);if(aO.data("ui-tooltip-title")&&!aO.attr("title")){aO.attr("title",aO.data("ui-tooltip-title"))}this._removeDescribedBy(aO);aM.hiding=true;aN.stop(true);this._hide(aN,this.options.hide,function(){aK._removeTooltip(ax(this))});aO.removeData("ui-tooltip-open");this._off(aO,"mouseleave focusout keyup");if(aO[0]!==this.element[0]){this._off(aO,"remove")}this._off(this.document,"mousemove");if(aL&&aL.type==="mouseleave"){ax.each(this.parents,function(aQ,aP){ax(aP.element).attr("title",aP.title);delete aK.parents[aQ]})}aM.closing=true;this._trigger("close",aL,{tooltip:aN});if(!aM.hiding){aM.closing=false}},_tooltip:function(aK){var aM=ax("<div>").attr("role","tooltip"),aL=ax("<div>").appendTo(aM),aN=aM.uniqueId().attr("id");this._addClass(aL,"ui-tooltip-content");this._addClass(aM,"ui-tooltip","ui-widget ui-widget-content");aM.appendTo(this._appendTo(aK));return this.tooltips[aN]={element:aK,tooltip:aM}},_find:function(aK){var aL=aK.data("ui-tooltip-id");return aL?this.tooltips[aL]:null},_removeTooltip:function(aK){clearInterval(this.delayedShow);aK.remove();delete this.tooltips[aK.attr("id")]},_appendTo:function(aL){var aK=aL.closest(".ui-front, dialog");if(!aK.length){aK=this.document[0].body}return aK},_destroy:function(){var aK=this;ax.each(this.tooltips,function(aO,aN){var aM=ax.Event("blur"),aL=aN.element;aM.target=aM.currentTarget=aL[0];aK.close(aM,true);ax("#"+aO).remove();if(aL.data("ui-tooltip-title")){if(!aL.attr("title")){aL.attr("title",aL.data("ui-tooltip-title"))}aL.removeData("ui-tooltip-title")}});this.liveRegion.remove()}});if(ax.uiBackCompat!==false){ax.widget("ui.tooltip",ax.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var aK=this._superApply(arguments);if(this.options.tooltipClass){aK.tooltip.addClass(this.options.tooltipClass)}return aK}})}var J=ax.ui.tooltip;var b=ax;
/*!
 * jQuery Color Animations v2.2.0
 * https://github.com/jquery/jquery-color
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Sun May 10 09:02:36 2020 +0200
 */
var Q="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",aw={},al=aw.toString,z=/^([\-+])=\s*(\d+\.?\d*)/,ae=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(aK){return[aK[1],aK[2],aK[3],aK[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(aK){return[aK[1]*2.55,aK[2]*2.55,aK[3]*2.55,aK[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?/,parse:function(aK){return[parseInt(aK[1],16),parseInt(aK[2],16),parseInt(aK[3],16),aK[4]?(parseInt(aK[4],16)/255).toFixed(2):1]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?/,parse:function(aK){return[parseInt(aK[1]+aK[1],16),parseInt(aK[2]+aK[2],16),parseInt(aK[3]+aK[3],16),aK[4]?(parseInt(aK[4]+aK[4],16)/255).toFixed(2):1]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(aK){return[aK[1],aK[2]/100,aK[3]/100,aK[4]]}}],t=b.Color=function(aL,aM,aK,aN){return new b.Color.fn.parse(aL,aM,aK,aN)},A={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},m={"byte":{floor:true,max:255},percent:{max:1},degrees:{mod:360,floor:true}},aD=t.support={},ab=b("<p>")[0],au,aH=b.each;ab.style.cssText="background-color:rgba(1,1,1,.5)";aD.rgba=ab.style.backgroundColor.indexOf("rgba")>-1;aH(A,function(aK,aL){aL.cache="_"+aK;aL.props.alpha={idx:3,type:"percent",def:1}});b.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(aL,aK){aw["[object "+aK+"]"]=aK.toLowerCase()});function v(aK){if(aK==null){return aK+""}return typeof aK==="object"?aw[al.call(aK)]||"object":typeof aK}function aA(aL,aN,aM){var aK=m[aN.type]||{};if(aL==null){return(aM||!aN.def)?null:aN.def}aL=aK.floor?~~aL:parseFloat(aL);if(isNaN(aL)){return aN.def}if(aK.mod){return(aL+aK.mod)%aK.mod}return Math.min(aK.max,Math.max(0,aL))}function D(aK){var aM=t(),aL=aM._rgba=[];aK=aK.toLowerCase();aH(ae,function(aR,aS){var aP,aQ=aS.re.exec(aK),aO=aQ&&aS.parse(aQ),aN=aS.space||"rgba";if(aO){aP=aM[aN](aO);aM[A[aN].cache]=aP[A[aN].cache];aL=aM._rgba=aP._rgba;return false}});if(aL.length){if(aL.join()==="0,0,0,0"){b.extend(aL,au.transparent)}return aM}return au[aK]}t.fn=b.extend(t.prototype,{parse:function(aQ,aO,aK,aP){if(aQ===undefined){this._rgba=[null,null,null,null];return this}if(aQ.jquery||aQ.nodeType){aQ=b(aQ).css(aO);aO=undefined}var aN=this,aM=v(aQ),aL=this._rgba=[];if(aO!==undefined){aQ=[aQ,aO,aK,aP];aM="array"}if(aM==="string"){return this.parse(D(aQ)||au._default)}if(aM==="array"){aH(A.rgba.props,function(aR,aS){aL[aS.idx]=aA(aQ[aS.idx],aS)});return this}if(aM==="object"){if(aQ instanceof t){aH(A,function(aR,aS){if(aQ[aS.cache]){aN[aS.cache]=aQ[aS.cache].slice()}})}else{aH(A,function(aS,aT){var aR=aT.cache;aH(aT.props,function(aU,aV){if(!aN[aR]&&aT.to){if(aU==="alpha"||aQ[aU]==null){return}aN[aR]=aT.to(aN._rgba)}aN[aR][aV.idx]=aA(aQ[aU],aV,true)});if(aN[aR]&&b.inArray(null,aN[aR].slice(0,3))<0){if(aN[aR][3]==null){aN[aR][3]=1}if(aT.from){aN._rgba=aT.from(aN[aR])}}})}return this}},is:function(aM){var aK=t(aM),aN=true,aL=this;aH(A,function(aO,aQ){var aR,aP=aK[aQ.cache];if(aP){aR=aL[aQ.cache]||aQ.to&&aQ.to(aL._rgba)||[];aH(aQ.props,function(aS,aT){if(aP[aT.idx]!=null){aN=(aP[aT.idx]===aR[aT.idx]);return aN}})}return aN});return aN},_space:function(){var aK=[],aL=this;aH(A,function(aM,aN){if(aL[aN.cache]){aK.push(aM)}});return aK.pop()},transition:function(aL,aR){var aM=t(aL),aN=aM._space(),aO=A[aN],aP=this.alpha()===0?t("transparent"):this,aQ=aP[aO.cache]||aO.to(aP._rgba),aK=aQ.slice();aM=aM[aO.cache];aH(aO.props,function(aW,aX){var aU=aX.idx,aT=aQ[aU],aS=aM[aU],aV=m[aX.type]||{};if(aS===null){return}if(aT===null){aK[aU]=aS}else{if(aV.mod){if(aS-aT>aV.mod/2){aT+=aV.mod}else{if(aT-aS>aV.mod/2){aT-=aV.mod}}}aK[aU]=aA((aS-aT)*aR+aT,aX)}});return this[aN](aK)},blend:function(aN){if(this._rgba[3]===1){return this}var aM=this._rgba.slice(),aL=aM.pop(),aK=t(aN)._rgba;return t(b.map(aM,function(aO,aP){return(1-aL)*aK[aP]+aL*aO}))},toRgbaString:function(){var aL="rgba(",aK=b.map(this._rgba,function(aM,aN){if(aM!=null){return aM}return aN>2?1:0});if(aK[3]===1){aK.pop();aL="rgb("}return aL+aK.join()+")"},toHslaString:function(){var aL="hsla(",aK=b.map(this.hsla(),function(aM,aN){if(aM==null){aM=aN>2?1:0}if(aN&&aN<3){aM=Math.round(aM*100)+"%"}return aM});if(aK[3]===1){aK.pop();aL="hsl("}return aL+aK.join()+")"},toHexString:function(aK){var aL=this._rgba.slice(),aM=aL.pop();if(aK){aL.push(~~(aM*255))}return"#"+b.map(aL,function(aN){aN=(aN||0).toString(16);return aN.length===1?"0"+aN:aN}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}});t.fn.parse.prototype=t.fn;function k(aM,aL,aK){aK=(aK+1)%1;if(aK*6<1){return aM+(aL-aM)*aK*6}if(aK*2<1){return aL}if(aK*3<2){return aM+(aL-aM)*((2/3)-aK)*6}return aM}A.hsla.to=function(aM){if(aM[0]==null||aM[1]==null||aM[2]==null){return[null,null,null,aM[3]]}var aK=aM[0]/255,aP=aM[1]/255,aQ=aM[2]/255,aS=aM[3],aR=Math.max(aK,aP,aQ),aN=Math.min(aK,aP,aQ),aT=aR-aN,aU=aR+aN,aL=aU*0.5,aO,aV;if(aN===aR){aO=0}else{if(aK===aR){aO=(60*(aP-aQ)/aT)+360}else{if(aP===aR){aO=(60*(aQ-aK)/aT)+120}else{aO=(60*(aK-aP)/aT)+240}}}if(aT===0){aV=0}else{if(aL<=0.5){aV=aT/aU}else{aV=aT/(2-aU)}}return[Math.round(aO)%360,aV,aL,aS==null?1:aS]};A.hsla.from=function(aO){if(aO[0]==null||aO[1]==null||aO[2]==null){return[null,null,null,aO[3]]}var aN=aO[0]/360,aM=aO[1],aL=aO[2],aK=aO[3],aP=aL<=0.5?aL*(1+aM):aL+aM-aL*aM,aQ=2*aL-aP;return[Math.round(k(aQ,aP,aN+(1/3))*255),Math.round(k(aQ,aP,aN)*255),Math.round(k(aQ,aP,aN-(1/3))*255),aK]};aH(A,function(aL,aN){var aM=aN.props,aK=aN.cache,aP=aN.to,aO=aN.from;t.fn[aL]=function(aU){if(aP&&!this[aK]){this[aK]=aP(this._rgba)}if(aU===undefined){return this[aK].slice()}var aR,aT=v(aU),aQ=(aT==="array"||aT==="object")?aU:arguments,aS=this[aK].slice();aH(aM,function(aV,aX){var aW=aQ[aT==="object"?aV:aX.idx];if(aW==null){aW=aS[aX.idx]}aS[aX.idx]=aA(aW,aX)});if(aO){aR=t(aO(aS));aR[aK]=aS;return aR}else{return t(aS)}};aH(aM,function(aQ,aR){if(t.fn[aQ]){return}t.fn[aQ]=function(aV){var aT,aX,aS,aU,aW=v(aV);if(aQ==="alpha"){aU=this._hsla?"hsla":"rgba"}else{aU=aL}aT=this[aU]();aX=aT[aR.idx];if(aW==="undefined"){return aX}if(aW==="function"){aV=aV.call(this,aX);aW=v(aV)}if(aV==null&&aR.empty){return this}if(aW==="string"){aS=z.exec(aV);if(aS){aV=aX+parseFloat(aS[2])*(aS[1]==="+"?1:-1)}}aT[aR.idx]=aV;return this[aU](aT)}})});t.hook=function(aL){var aK=aL.split(" ");aH(aK,function(aN,aM){b.cssHooks[aM]={set:function(aR,aS){var aP,aQ,aO="";if(aS!=="transparent"&&(v(aS)!=="string"||(aP=D(aS)))){aS=t(aP||aS);if(!aD.rgba&&aS._rgba[3]!==1){aQ=aM==="backgroundColor"?aR.parentNode:aR;while((aO===""||aO==="transparent")&&aQ&&aQ.style){try{aO=b.css(aQ,"backgroundColor");aQ=aQ.parentNode}catch(aT){}}aS=aS.blend(aO&&aO!=="transparent"?aO:"_default")}aS=aS.toRgbaString()}try{aR.style[aM]=aS}catch(aT){}}};b.fx.step[aM]=function(aO){if(!aO.colorInit){aO.start=t(aO.elem,aM);aO.end=t(aO.end);aO.colorInit=true}b.cssHooks[aM].set(aO.elem,aO.start.transition(aO.end,aO.pos))}})};t.hook(Q);b.cssHooks.borderColor={expand:function(aL){var aK={};aH(["Top","Right","Bottom","Left"],function(aN,aM){aK["border"+aM+"Color"]=aL});return aK}};au=b.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"};
/*!
 * jQuery UI Effects 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var w="ui-effects-",am="ui-effects-style",aE="ui-effects-animated";ax.effects={effect:{}};(function(){var aL=["add","remove","toggle"],aN={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};ax.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(aP,aQ){ax.fx.step[aQ]=function(aR){if(aR.end!=="none"&&!aR.setAttr||aR.pos===1&&!aR.setAttr){b.style(aR.elem,aQ,aR.end);aR.setAttr=true}}});function aM(aP){return aP.replace(/-([\da-z])/gi,function(aQ,aR){return aR.toUpperCase()})}function aO(aT){var aQ,aP,aR=aT.ownerDocument.defaultView?aT.ownerDocument.defaultView.getComputedStyle(aT,null):aT.currentStyle,aS={};if(aR&&aR.length&&aR[0]&&aR[aR[0]]){aP=aR.length;while(aP--){aQ=aR[aP];if(typeof aR[aQ]==="string"){aS[aM(aQ)]=aR[aQ]}}}else{for(aQ in aR){if(typeof aR[aQ]==="string"){aS[aQ]=aR[aQ]}}}return aS}function aK(aP,aR){var aT={},aQ,aS;for(aQ in aR){aS=aR[aQ];if(aP[aQ]!==aS){if(!aN[aQ]){if(ax.fx.step[aQ]||!isNaN(parseFloat(aS))){aT[aQ]=aS}}}}return aT}if(!ax.fn.addBack){ax.fn.addBack=function(aP){return this.add(aP==null?this.prevObject:this.prevObject.filter(aP))}}ax.effects.animateClass=function(aP,aQ,aT,aS){var aR=ax.speed(aQ,aT,aS);return this.queue(function(){var aW=ax(this),aU=aW.attr("class")||"",aV,aX=aR.children?aW.find("*").addBack():aW;aX=aX.map(function(){var aY=ax(this);return{el:aY,start:aO(this)}});aV=function(){ax.each(aL,function(aY,aZ){if(aP[aZ]){aW[aZ+"Class"](aP[aZ])}})};aV();aX=aX.map(function(){this.end=aO(this.el[0]);this.diff=aK(this.start,this.end);return this});aW.attr("class",aU);aX=aX.map(function(){var a0=this,aY=ax.Deferred(),aZ=ax.extend({},aR,{queue:false,complete:function(){aY.resolve(a0)}});this.el.animate(this.diff,aZ);return aY.promise()});ax.when.apply(ax,aX.get()).done(function(){aV();ax.each(arguments,function(){var aY=this.el;ax.each(this.diff,function(aZ){aY.css(aZ,"")})});aR.complete.call(aW[0])})})};ax.fn.extend({addClass:(function(aP){return function(aR,aQ,aT,aS){return aQ?ax.effects.animateClass.call(this,{add:aR},aQ,aT,aS):aP.apply(this,arguments)}})(ax.fn.addClass),removeClass:(function(aP){return function(aR,aQ,aT,aS){return arguments.length>1?ax.effects.animateClass.call(this,{remove:aR},aQ,aT,aS):aP.apply(this,arguments)}})(ax.fn.removeClass),toggleClass:(function(aP){return function(aS,aR,aQ,aU,aT){if(typeof aR==="boolean"||aR===undefined){if(!aQ){return aP.apply(this,arguments)}else{return ax.effects.animateClass.call(this,(aR?{add:aS}:{remove:aS}),aQ,aU,aT)}}else{return ax.effects.animateClass.call(this,{toggle:aS},aR,aQ,aU)}}})(ax.fn.toggleClass),switchClass:function(aP,aR,aQ,aT,aS){return ax.effects.animateClass.call(this,{add:aR,remove:aP},aQ,aT,aS)}})})();(function(){if(ax.expr&&ax.expr.pseudos&&ax.expr.pseudos.animated){ax.expr.pseudos.animated=(function(aN){return function(aO){return !!ax(aO).data(aE)||aN(aO)}})(ax.expr.pseudos.animated)}if(ax.uiBackCompat!==false){ax.extend(ax.effects,{save:function(aO,aQ){var aN=0,aP=aQ.length;for(;aN<aP;aN++){if(aQ[aN]!==null){aO.data(w+aQ[aN],aO[0].style[aQ[aN]])}}},restore:function(aO,aR){var aQ,aN=0,aP=aR.length;for(;aN<aP;aN++){if(aR[aN]!==null){aQ=aO.data(w+aR[aN]);aO.css(aR[aN],aQ)}}},setMode:function(aN,aO){if(aO==="toggle"){aO=aN.is(":hidden")?"show":"hide"}return aO},createWrapper:function(aO){if(aO.parent().is(".ui-effects-wrapper")){return aO.parent()}var aP={width:aO.outerWidth(true),height:aO.outerHeight(true),"float":aO.css("float")},aS=ax("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),aN={width:aO.width(),height:aO.height()},aR=document.activeElement;try{aR.id}catch(aQ){aR=document.body}aO.wrap(aS);if(aO[0]===aR||ax.contains(aO[0],aR)){ax(aR).trigger("focus")}aS=aO.parent();if(aO.css("position")==="static"){aS.css({position:"relative"});aO.css({position:"relative"})}else{ax.extend(aP,{position:aO.css("position"),zIndex:aO.css("z-index")});ax.each(["top","left","bottom","right"],function(aT,aU){aP[aU]=aO.css(aU);if(isNaN(parseInt(aP[aU],10))){aP[aU]="auto"}});aO.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})}aO.css(aN);return aS.css(aP).show()},removeWrapper:function(aN){var aO=document.activeElement;if(aN.parent().is(".ui-effects-wrapper")){aN.parent().replaceWith(aN);if(aN[0]===aO||ax.contains(aN[0],aO)){ax(aO).trigger("focus")}}return aN}})}ax.extend(ax.effects,{version:"1.13.0",define:function(aN,aP,aO){if(!aO){aO=aP;aP="effect"}ax.effects.effect[aN]=aO;ax.effects.effect[aN].mode=aP;return aO},scaledDimensions:function(aO,aP,aQ){if(aP===0){return{height:0,width:0,outerHeight:0,outerWidth:0}}var aN=aQ!=="horizontal"?((aP||100)/100):1,aR=aQ!=="vertical"?((aP||100)/100):1;return{height:aO.height()*aR,width:aO.width()*aN,outerHeight:aO.outerHeight()*aR,outerWidth:aO.outerWidth()*aN}},clipToBox:function(aN){return{width:aN.clip.right-aN.clip.left,height:aN.clip.bottom-aN.clip.top,left:aN.clip.left,top:aN.clip.top}},unshift:function(aO,aQ,aP){var aN=aO.queue();if(aQ>1){aN.splice.apply(aN,[1,0].concat(aN.splice(aQ,aP)))}aO.dequeue()},saveStyle:function(aN){aN.data(am,aN[0].style.cssText)},restoreStyle:function(aN){aN[0].style.cssText=aN.data(am)||"";aN.removeData(am)},mode:function(aN,aP){var aO=aN.is(":hidden");if(aP==="toggle"){aP=aO?"show":"hide"}if(aO?aP==="hide":aP==="show"){aP="none"}return aP},getBaseline:function(aO,aP){var aQ,aN;switch(aO[0]){case"top":aQ=0;break;case"middle":aQ=0.5;break;case"bottom":aQ=1;break;default:aQ=aO[0]/aP.height}switch(aO[1]){case"left":aN=0;break;case"center":aN=0.5;break;case"right":aN=1;break;default:aN=aO[1]/aP.width}return{x:aN,y:aQ}},createPlaceholder:function(aO){var aQ,aP=aO.css("position"),aN=aO.position();aO.css({marginTop:aO.css("marginTop"),marginBottom:aO.css("marginBottom"),marginLeft:aO.css("marginLeft"),marginRight:aO.css("marginRight")}).outerWidth(aO.outerWidth()).outerHeight(aO.outerHeight());if(/^(static|relative)/.test(aP)){aP="absolute";aQ=ax("<"+aO[0].nodeName+">").insertAfter(aO).css({display:/^(inline|ruby)/.test(aO.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:aO.css("marginTop"),marginBottom:aO.css("marginBottom"),marginLeft:aO.css("marginLeft"),marginRight:aO.css("marginRight"),"float":aO.css("float")}).outerWidth(aO.outerWidth()).outerHeight(aO.outerHeight()).addClass("ui-effects-placeholder");aO.data(w+"placeholder",aQ)}aO.css({position:aP,left:aN.left,top:aN.top});return aQ},removePlaceholder:function(aN){var aP=w+"placeholder",aO=aN.data(aP);if(aO){aO.remove();aN.removeData(aP)}},cleanUp:function(aN){ax.effects.restoreStyle(aN);ax.effects.removePlaceholder(aN)},setTransition:function(aO,aQ,aN,aP){aP=aP||{};ax.each(aQ,function(aS,aR){var aT=aO.cssUnit(aR);if(aT[0]>0){aP[aR]=aT[0]*aN+aT[1]}});return aP}});function aL(aO,aN,aP,aQ){if(ax.isPlainObject(aO)){aN=aO;aO=aO.effect}aO={effect:aO};if(aN==null){aN={}}if(typeof aN==="function"){aQ=aN;aP=null;aN={}}if(typeof aN==="number"||ax.fx.speeds[aN]){aQ=aP;aP=aN;aN={}}if(typeof aP==="function"){aQ=aP;aP=null}if(aN){ax.extend(aO,aN)}aP=aP||aN.duration;aO.duration=ax.fx.off?0:typeof aP==="number"?aP:aP in ax.fx.speeds?ax.fx.speeds[aP]:ax.fx.speeds._default;aO.complete=aQ||aN.complete;return aO}function aM(aN){if(!aN||typeof aN==="number"||ax.fx.speeds[aN]){return true}if(typeof aN==="string"&&!ax.effects.effect[aN]){return true}if(typeof aN==="function"){return true}if(typeof aN==="object"&&!aN.effect){return true}return false}ax.fn.extend({effect:function(){var aV=aL.apply(this,arguments),aU=ax.effects.effect[aV.effect],aR=aU.mode,aT=aV.queue,aQ=aT||"fx",aN=aV.complete,aS=aV.mode,aO=[],aW=function(aZ){var aY=ax(this),aX=ax.effects.mode(aY,aS)||aR;aY.data(aE,true);aO.push(aX);if(aR&&(aX==="show"||(aX===aR&&aX==="hide"))){aY.show()}if(!aR||aX!=="none"){ax.effects.saveStyle(aY)}if(typeof aZ==="function"){aZ()}};if(ax.fx.off||!aU){if(aS){return this[aS](aV.duration,aN)}else{return this.each(function(){if(aN){aN.call(this)}})}}function aP(aZ){var a0=ax(this);function aY(){a0.removeData(aE);ax.effects.cleanUp(a0);if(aV.mode==="hide"){a0.hide()}aX()}function aX(){if(typeof aN==="function"){aN.call(a0[0])}if(typeof aZ==="function"){aZ()}}aV.mode=aO.shift();if(ax.uiBackCompat!==false&&!aR){if(a0.is(":hidden")?aS==="hide":aS==="show"){a0[aS]();aX()}else{aU.call(a0[0],aV,aX)}}else{if(aV.mode==="none"){a0[aS]();aX()}else{aU.call(a0[0],aV,aY)}}}return aT===false?this.each(aW).each(aP):this.queue(aQ,aW).queue(aQ,aP)},show:(function(aN){return function(aP){if(aM(aP)){return aN.apply(this,arguments)}else{var aO=aL.apply(this,arguments);aO.mode="show";return this.effect.call(this,aO)}}})(ax.fn.show),hide:(function(aN){return function(aP){if(aM(aP)){return aN.apply(this,arguments)}else{var aO=aL.apply(this,arguments);aO.mode="hide";return this.effect.call(this,aO)}}})(ax.fn.hide),toggle:(function(aN){return function(aP){if(aM(aP)||typeof aP==="boolean"){return aN.apply(this,arguments)}else{var aO=aL.apply(this,arguments);aO.mode="toggle";return this.effect.call(this,aO)}}})(ax.fn.toggle),cssUnit:function(aN){var aO=this.css(aN),aP=[];ax.each(["em","px","%","pt"],function(aQ,aR){if(aO.indexOf(aR)>0){aP=[parseFloat(aO),aR]}});return aP},cssClip:function(aN){if(aN){return this.css("clip","rect("+aN.top+"px "+aN.right+"px "+aN.bottom+"px "+aN.left+"px)")}return aK(this.css("clip"),this)},transfer:function(aY,aQ){var aS=ax(this),aU=ax(aY.to),aX=aU.css("position")==="fixed",aT=ax("body"),aV=aX?aT.scrollTop():0,aW=aX?aT.scrollLeft():0,aN=aU.offset(),aP={top:aN.top-aV,left:aN.left-aW,height:aU.innerHeight(),width:aU.innerWidth()},aR=aS.offset(),aO=ax("<div class='ui-effects-transfer'></div>");aO.appendTo("body").addClass(aY.className).css({top:aR.top-aV,left:aR.left-aW,height:aS.innerHeight(),width:aS.innerWidth(),position:aX?"fixed":"absolute"}).animate(aP,aY.duration,aY.easing,function(){aO.remove();if(typeof aQ==="function"){aQ()}})}});function aK(aS,aP){var aR=aP.outerWidth(),aQ=aP.outerHeight(),aO=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,aN=aO.exec(aS)||["",0,aR,aQ,0];return{top:parseFloat(aN[1])||0,right:aN[2]==="auto"?aR:parseFloat(aN[2]),bottom:aN[3]==="auto"?aQ:parseFloat(aN[3]),left:parseFloat(aN[4])||0}}ax.fx.step.clip=function(aN){if(!aN.clipInit){aN.start=ax(aN.elem).cssClip();if(typeof aN.end==="string"){aN.end=aK(aN.end,aN.elem)}aN.clipInit=true}ax(aN.elem).cssClip({top:aN.pos*(aN.end.top-aN.start.top)+aN.start.top,right:aN.pos*(aN.end.right-aN.start.right)+aN.start.right,bottom:aN.pos*(aN.end.bottom-aN.start.bottom)+aN.start.bottom,left:aN.pos*(aN.end.left-aN.start.left)+aN.start.left})}})();(function(){var aK={};ax.each(["Quad","Cubic","Quart","Quint","Expo"],function(aM,aL){aK[aL]=function(aN){return Math.pow(aN,aM+2)}});ax.extend(aK,{Sine:function(aL){return 1-Math.cos(aL*Math.PI/2)},Circ:function(aL){return 1-Math.sqrt(1-aL*aL)},Elastic:function(aL){return aL===0||aL===1?aL:-Math.pow(2,8*(aL-1))*Math.sin(((aL-1)*80-7.5)*Math.PI/15)},Back:function(aL){return aL*aL*(3*aL-2)},Bounce:function(aN){var aL,aM=4;while(aN<((aL=Math.pow(2,--aM))-1)/11){}return 1/Math.pow(4,3-aM)-7.5625*Math.pow((aL*3-2)/22-aN,2)}});ax.each(aK,function(aM,aL){ax.easing["easeIn"+aM]=aL;ax.easing["easeOut"+aM]=function(aN){return 1-aL(1-aN)};ax.easing["easeInOut"+aM]=function(aN){return aN<0.5?aL(aN*2)/2:1-aL(aN*-2+2)/2}})})();var N=ax.effects;
/*!
 * jQuery UI Effects Blind 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var K=ax.effects.define("blind","hide",function(aM,aK){var aP={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},aN=ax(this),aO=aM.direction||"up",aR=aN.cssClip(),aL={clip:ax.extend({},aR)},aQ=ax.effects.createPlaceholder(aN);aL.clip[aP[aO][0]]=aL.clip[aP[aO][1]];if(aM.mode==="show"){aN.cssClip(aL.clip);if(aQ){aQ.css(ax.effects.clipToBox(aL))}aL.clip=aR}if(aQ){aQ.animate(ax.effects.clipToBox(aL),aM.duration,aM.easing)}aN.animate(aL,{queue:false,duration:aM.duration,easing:aM.easing,complete:aK})});
/*!
 * jQuery UI Effects Bounce 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var E=ax.effects.define("bounce",function(aL,aS){var aO,aW,aZ,aK=ax(this),aR=aL.mode,aQ=aR==="hide",a0=aR==="show",a1=aL.direction||"up",aM=aL.distance,aP=aL.times||5,a2=aP*2+(a0||aQ?1:0),aY=aL.duration/a2,aU=aL.easing,aN=(a1==="up"||a1==="down")?"top":"left",aT=(a1==="up"||a1==="left"),aX=0,aV=aK.queue().length;ax.effects.createPlaceholder(aK);aZ=aK.css(aN);if(!aM){aM=aK[aN==="top"?"outerHeight":"outerWidth"]()/3}if(a0){aW={opacity:1};aW[aN]=aZ;aK.css("opacity",0).css(aN,aT?-aM*2:aM*2).animate(aW,aY,aU)}if(aQ){aM=aM/Math.pow(2,aP-1)}aW={};aW[aN]=aZ;for(;aX<aP;aX++){aO={};aO[aN]=(aT?"-=":"+=")+aM;aK.animate(aO,aY,aU).animate(aW,aY,aU);aM=aQ?aM*2:aM/2}if(aQ){aO={opacity:0};aO[aN]=(aT?"-=":"+=")+aM;aK.animate(aO,aY,aU)}aK.queue(aS);ax.effects.unshift(aK,aV,a2+1)});
/*!
 * jQuery UI Effects Clip 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var an=ax.effects.define("clip","hide",function(aS,aO){var aL,aM={},aP=ax(this),aR=aS.direction||"vertical",aQ=aR==="both",aK=aQ||aR==="horizontal",aN=aQ||aR==="vertical";aL=aP.cssClip();aM.clip={top:aN?(aL.bottom-aL.top)/2:aL.top,right:aK?(aL.right-aL.left)/2:aL.right,bottom:aN?(aL.bottom-aL.top)/2:aL.bottom,left:aK?(aL.right-aL.left)/2:aL.left};ax.effects.createPlaceholder(aP);if(aS.mode==="show"){aP.cssClip(aM.clip);aM.clip=aL}aP.animate(aM,{queue:false,duration:aS.duration,easing:aS.easing,complete:aO})});
/*!
 * jQuery UI Effects Drop 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var ac=ax.effects.define("drop","hide",function(aU,aN){var aK,aO=ax(this),aQ=aU.mode,aS=aQ==="show",aR=aU.direction||"left",aL=(aR==="up"||aR==="down")?"top":"left",aT=(aR==="up"||aR==="left")?"-=":"+=",aP=(aT==="+=")?"-=":"+=",aM={opacity:0};ax.effects.createPlaceholder(aO);aK=aU.distance||aO[aL==="top"?"outerHeight":"outerWidth"](true)/2;aM[aL]=aT+aK;if(aS){aO.css(aM);aM[aL]=aP+aK;aM.opacity=1}aO.animate(aM,{queue:false,duration:aU.duration,easing:aU.easing,complete:aN})});
/*!
 * jQuery UI Effects Explode 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var aI=ax.effects.define("explode","hide",function(aL,aX){var a0,aZ,aN,aV,aU,aS,aR=aL.pieces?Math.round(Math.sqrt(aL.pieces)):3,aM=aR,aK=ax(this),aT=aL.mode,a1=aT==="show",aP=aK.show().css("visibility","hidden").offset(),aY=Math.ceil(aK.outerWidth()/aM),aW=Math.ceil(aK.outerHeight()/aR),aQ=[];function a2(){aQ.push(this);if(aQ.length===aR*aM){aO()}}for(a0=0;a0<aR;a0++){aV=aP.top+a0*aW;aS=a0-(aR-1)/2;for(aZ=0;aZ<aM;aZ++){aN=aP.left+aZ*aY;aU=aZ-(aM-1)/2;aK.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-aZ*aY,top:-a0*aW}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:aY,height:aW,left:aN+(a1?aU*aY:0),top:aV+(a1?aS*aW:0),opacity:a1?0:1}).animate({left:aN+(a1?0:aU*aY),top:aV+(a1?0:aS*aW),opacity:a1?1:0},aL.duration||500,aL.easing,a2)}}function aO(){aK.css({visibility:"visible"});ax(aQ).remove();aX()}});
/*!
 * jQuery UI Effects Fade 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var aJ=ax.effects.define("fade","toggle",function(aM,aL){var aK=aM.mode==="show";ax(this).css("opacity",aK?0:1).animate({opacity:aK?1:0},{queue:false,duration:aM.duration,easing:aM.easing,complete:aL})});
/*!
 * jQuery UI Effects Fold 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var x=ax.effects.define("fold","hide",function(a0,aP){var aQ=ax(this),aR=a0.mode,aX=aR==="show",aS=aR==="hide",aZ=a0.size||15,aT=/([0-9]+)%/.exec(aZ),aY=!!a0.horizFirst,aN=aY?["right","bottom"]:["bottom","right"],aO=a0.duration/2,aW=ax.effects.createPlaceholder(aQ),aL=aQ.cssClip(),aV={clip:ax.extend({},aL)},aU={clip:ax.extend({},aL)},aK=[aL[aN[0]],aL[aN[1]]],aM=aQ.queue().length;if(aT){aZ=parseInt(aT[1],10)/100*aK[aS?0:1]}aV.clip[aN[0]]=aZ;aU.clip[aN[0]]=aZ;aU.clip[aN[1]]=0;if(aX){aQ.cssClip(aU.clip);if(aW){aW.css(ax.effects.clipToBox(aU))}aU.clip=aL}aQ.queue(function(a1){if(aW){aW.animate(ax.effects.clipToBox(aV),aO,a0.easing).animate(ax.effects.clipToBox(aU),aO,a0.easing)}a1()}).animate(aV,aO,a0.easing).animate(aU,aO,a0.easing).queue(aP);ax.effects.unshift(aQ,aM,4)});
/*!
 * jQuery UI Effects Highlight 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var O=ax.effects.define("highlight","show",function(aL,aK){var aM=ax(this),aN={backgroundColor:aM.css("backgroundColor")};if(aL.mode==="hide"){aN.opacity=0}ax.effects.saveStyle(aM);aM.css({backgroundImage:"none",backgroundColor:aL.color||"#ffff99"}).animate(aN,{queue:false,duration:aL.duration,easing:aL.easing,complete:aK})});
/*!
 * jQuery UI Effects Size 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var Z=ax.effects.define("size",function(aN,aT){var aR,aS,aX,aK=ax(this),aP=["fontSize"],aY=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],aM=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],aQ=aN.mode,aW=aQ!=="effect",a1=aN.scale||"both",aZ=aN.origin||["middle","center"],a0=aK.css("position"),aO=aK.position(),aU=ax.effects.scaledDimensions(aK),aV=aN.from||aU,aL=aN.to||ax.effects.scaledDimensions(aK,0);ax.effects.createPlaceholder(aK);if(aQ==="show"){aX=aV;aV=aL;aL=aX}aS={from:{y:aV.height/aU.height,x:aV.width/aU.width},to:{y:aL.height/aU.height,x:aL.width/aU.width}};if(a1==="box"||a1==="both"){if(aS.from.y!==aS.to.y){aV=ax.effects.setTransition(aK,aY,aS.from.y,aV);aL=ax.effects.setTransition(aK,aY,aS.to.y,aL)}if(aS.from.x!==aS.to.x){aV=ax.effects.setTransition(aK,aM,aS.from.x,aV);aL=ax.effects.setTransition(aK,aM,aS.to.x,aL)}}if(a1==="content"||a1==="both"){if(aS.from.y!==aS.to.y){aV=ax.effects.setTransition(aK,aP,aS.from.y,aV);aL=ax.effects.setTransition(aK,aP,aS.to.y,aL)}}if(aZ){aR=ax.effects.getBaseline(aZ,aU);aV.top=(aU.outerHeight-aV.outerHeight)*aR.y+aO.top;aV.left=(aU.outerWidth-aV.outerWidth)*aR.x+aO.left;aL.top=(aU.outerHeight-aL.outerHeight)*aR.y+aO.top;aL.left=(aU.outerWidth-aL.outerWidth)*aR.x+aO.left}delete aV.outerHeight;delete aV.outerWidth;aK.css(aV);if(a1==="content"||a1==="both"){aY=aY.concat(["marginTop","marginBottom"]).concat(aP);aM=aM.concat(["marginLeft","marginRight"]);aK.find("*[width]").each(function(){var a5=ax(this),a2=ax.effects.scaledDimensions(a5),a4={height:a2.height*aS.from.y,width:a2.width*aS.from.x,outerHeight:a2.outerHeight*aS.from.y,outerWidth:a2.outerWidth*aS.from.x},a3={height:a2.height*aS.to.y,width:a2.width*aS.to.x,outerHeight:a2.height*aS.to.y,outerWidth:a2.width*aS.to.x};if(aS.from.y!==aS.to.y){a4=ax.effects.setTransition(a5,aY,aS.from.y,a4);a3=ax.effects.setTransition(a5,aY,aS.to.y,a3)}if(aS.from.x!==aS.to.x){a4=ax.effects.setTransition(a5,aM,aS.from.x,a4);a3=ax.effects.setTransition(a5,aM,aS.to.x,a3)}if(aW){ax.effects.saveStyle(a5)}a5.css(a4);a5.animate(a3,aN.duration,aN.easing,function(){if(aW){ax.effects.restoreStyle(a5)}})})}aK.animate(aL,{queue:false,duration:aN.duration,easing:aN.easing,complete:function(){var a2=aK.offset();if(aL.opacity===0){aK.css("opacity",aV.opacity)}if(!aW){aK.css("position",a0==="static"?"relative":a0).offset(a2);ax.effects.saveStyle(aK)}aT()}})});
/*!
 * jQuery UI Effects Scale 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var U=ax.effects.define("scale",function(aL,aK){var aM=ax(this),aP=aL.mode,aN=parseInt(aL.percent,10)||(parseInt(aL.percent,10)===0?0:(aP!=="effect"?0:100)),aO=ax.extend(true,{from:ax.effects.scaledDimensions(aM),to:ax.effects.scaledDimensions(aM,aN,aL.direction||"both"),origin:aL.origin||["middle","center"]},aL);if(aL.fade){aO.from.opacity=1;aO.to.opacity=0}ax.effects.effect.size.call(this,aO,aK)});
/*!
 * jQuery UI Effects Puff 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var G=ax.effects.define("puff","hide",function(aL,aK){var aM=ax.extend(true,{},aL,{fade:true,percent:parseInt(aL.percent,10)||150});ax.effects.effect.scale.call(this,aM,aK)});
/*!
 * jQuery UI Effects Pulsate 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var B=ax.effects.define("pulsate","show",function(aV,aM){var aO=ax(this),aP=aV.mode,aT=aP==="show",aQ=aP==="hide",aU=aT||aQ,aR=((aV.times||5)*2)+(aU?1:0),aL=aV.duration/aR,aS=0,aN=1,aK=aO.queue().length;if(aT||!aO.is(":visible")){aO.css("opacity",0).show();aS=1}for(;aN<aR;aN++){aO.animate({opacity:aS},aL,aV.easing);aS=1-aS}aO.animate({opacity:aS},aL,aV.easing);aO.queue(aM);ax.effects.unshift(aO,aK,aR+1)});
/*!
 * jQuery UI Effects Shake 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var at=ax.effects.define("shake",function(aY,aR){var aS=1,aT=ax(this),aV=aY.direction||"left",aK=aY.distance||20,aL=aY.times||3,aW=aL*2+1,aP=Math.round(aY.duration/aW),aO=(aV==="up"||aV==="down")?"top":"left",aM=(aV==="up"||aV==="left"),aQ={},aX={},aU={},aN=aT.queue().length;ax.effects.createPlaceholder(aT);aQ[aO]=(aM?"-=":"+=")+aK;aX[aO]=(aM?"+=":"-=")+aK*2;aU[aO]=(aM?"-=":"+=")+aK*2;aT.animate(aQ,aP,aY.easing);for(;aS<aL;aS++){aT.animate(aX,aP,aY.easing).animate(aU,aP,aY.easing)}aT.animate(aX,aP,aY.easing).animate(aQ,aP/2,aY.easing).queue(aR);ax.effects.unshift(aT,aN,aW+1)});
/*!
 * jQuery UI Effects Slide 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var aq=ax.effects.define("slide","show",function(aV,aR){var aO,aL,aS=ax(this),aM={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},aT=aV.mode,aU=aV.direction||"left",aP=(aU==="up"||aU==="down")?"top":"left",aN=(aU==="up"||aU==="left"),aK=aV.distance||aS[aP==="top"?"outerHeight":"outerWidth"](true),aQ={};ax.effects.createPlaceholder(aS);aO=aS.cssClip();aL=aS.position()[aP];aQ[aP]=(aN?-1:1)*aK+aL;aQ.clip=aS.cssClip();aQ.clip[aM[aU][1]]=aQ.clip[aM[aU][0]];if(aT==="show"){aS.cssClip(aQ.clip);aS.css(aP,aQ[aP]);aQ.clip=aO;aQ[aP]=aL}aS.animate(aQ,{queue:false,duration:aV.duration,easing:aV.easing,complete:aR})});
/*!
 * jQuery UI Effects Transfer 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
var N;if(ax.uiBackCompat!==false){N=ax.effects.define("transfer",function(aL,aK){ax(this).transfer(aL,aK)})}var S=N});
/*! jQuery Timepicker Addon - v1.6.3 - 2016-04-20
* http://trentrichardson.com/examples/timepicker
* Copyright (c) 2016 Trent Richardson; Licensed MIT */
(function(a){if(typeof define==="function"&&define.amd){define(["jquery","jquery-ui"],a)}else{a(jQuery)}}(function($){$.ui.timepicker=$.ui.timepicker||{};if($.ui.timepicker.version){return}$.extend($.ui,{timepicker:{version:"1.6.3"}});var Timepicker=function(){this.regional=[];this.regional[""]={currentText:"Now",closeText:"Done",amNames:["AM","A"],pmNames:["PM","P"],timeFormat:"HH:mm",timeSuffix:"",timeOnlyTitle:"Choose Time",timeText:"Time",hourText:"Hour",minuteText:"Minute",secondText:"Second",millisecText:"Millisecond",microsecText:"Microsecond",timezoneText:"Time Zone",isRTL:false};this._defaults={showButtonPanel:true,timeOnly:false,timeOnlyShowDate:false,showHour:null,showMinute:null,showSecond:null,showMillisec:null,showMicrosec:null,showTimezone:null,showTime:true,stepHour:1,stepMinute:1,stepSecond:1,stepMillisec:1,stepMicrosec:1,hour:0,minute:0,second:0,millisec:0,microsec:0,timezone:null,hourMin:0,minuteMin:0,secondMin:0,millisecMin:0,microsecMin:0,hourMax:23,minuteMax:59,secondMax:59,millisecMax:999,microsecMax:999,minDateTime:null,maxDateTime:null,maxTime:null,minTime:null,onSelect:null,hourGrid:0,minuteGrid:0,secondGrid:0,millisecGrid:0,microsecGrid:0,alwaysSetTime:true,separator:" ",altFieldTimeOnly:true,altTimeFormat:null,altSeparator:null,altTimeSuffix:null,altRedirectFocus:true,pickerTimeFormat:null,pickerTimeSuffix:null,showTimepicker:true,timezoneList:null,addSliderAccess:false,sliderAccessArgs:null,controlType:"slider",oneLine:false,defaultValue:null,parse:"strict",afterInject:null};$.extend(this._defaults,this.regional[""])};$.extend(Timepicker.prototype,{$input:null,$altInput:null,$timeObj:null,inst:null,hour_slider:null,minute_slider:null,second_slider:null,millisec_slider:null,microsec_slider:null,timezone_select:null,maxTime:null,minTime:null,hour:0,minute:0,second:0,millisec:0,microsec:0,timezone:null,hourMinOriginal:null,minuteMinOriginal:null,secondMinOriginal:null,millisecMinOriginal:null,microsecMinOriginal:null,hourMaxOriginal:null,minuteMaxOriginal:null,secondMaxOriginal:null,millisecMaxOriginal:null,microsecMaxOriginal:null,ampm:"",formattedDate:"",formattedTime:"",formattedDateTime:"",timezoneList:null,units:["hour","minute","second","millisec","microsec"],support:{},control:null,setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_newInst:function($input,opts){var tp_inst=new Timepicker(),inlineSettings={},fns={},overrides,i;for(var attrName in this._defaults){if(this._defaults.hasOwnProperty(attrName)){var attrValue=$input.attr("time:"+attrName);if(attrValue){try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}}overrides={beforeShow:function(input,dp_inst){if(typeof tp_inst._defaults.evnts.beforeShow==="function"){return tp_inst._defaults.evnts.beforeShow.call($input[0],input,dp_inst,tp_inst)}},onChangeMonthYear:function(year,month,dp_inst){if(typeof tp_inst._defaults.evnts.onChangeMonthYear==="function"){tp_inst._defaults.evnts.onChangeMonthYear.call($input[0],year,month,dp_inst,tp_inst)}},onClose:function(dateText,dp_inst){if(tp_inst.timeDefined===true&&$input.val()!==""){tp_inst._updateDateTime(dp_inst)}if(typeof tp_inst._defaults.evnts.onClose==="function"){tp_inst._defaults.evnts.onClose.call($input[0],dateText,dp_inst,tp_inst)}}};for(i in overrides){if(overrides.hasOwnProperty(i)){fns[i]=opts[i]||this._defaults[i]||null}}tp_inst._defaults=$.extend({},this._defaults,inlineSettings,opts,overrides,{evnts:fns,timepicker:tp_inst});tp_inst.amNames=$.map(tp_inst._defaults.amNames,function(val){return val.toUpperCase()});tp_inst.pmNames=$.map(tp_inst._defaults.pmNames,function(val){return val.toUpperCase()});tp_inst.support=detectSupport(tp_inst._defaults.timeFormat+(tp_inst._defaults.pickerTimeFormat?tp_inst._defaults.pickerTimeFormat:"")+(tp_inst._defaults.altTimeFormat?tp_inst._defaults.altTimeFormat:""));if(typeof(tp_inst._defaults.controlType)==="string"){if(tp_inst._defaults.controlType==="slider"&&typeof($.ui.slider)==="undefined"){tp_inst._defaults.controlType="select"}tp_inst.control=tp_inst._controls[tp_inst._defaults.controlType]}else{tp_inst.control=tp_inst._defaults.controlType}var timezoneList=[-720,-660,-600,-570,-540,-480,-420,-360,-300,-270,-240,-210,-180,-120,-60,0,60,120,180,210,240,270,300,330,345,360,390,420,480,525,540,570,600,630,660,690,720,765,780,840];if(tp_inst._defaults.timezoneList!==null){timezoneList=tp_inst._defaults.timezoneList}var tzl=timezoneList.length,tzi=0,tzv=null;if(tzl>0&&typeof timezoneList[0]!=="object"){for(;tzi<tzl;tzi++){tzv=timezoneList[tzi];timezoneList[tzi]={value:tzv,label:$.timepicker.timezoneOffsetString(tzv,tp_inst.support.iso8601)}}}tp_inst._defaults.timezoneList=timezoneList;tp_inst.timezone=tp_inst._defaults.timezone!==null?$.timepicker.timezoneOffsetNumber(tp_inst._defaults.timezone):((new Date()).getTimezoneOffset()*-1);tp_inst.hour=tp_inst._defaults.hour<tp_inst._defaults.hourMin?tp_inst._defaults.hourMin:tp_inst._defaults.hour>tp_inst._defaults.hourMax?tp_inst._defaults.hourMax:tp_inst._defaults.hour;tp_inst.minute=tp_inst._defaults.minute<tp_inst._defaults.minuteMin?tp_inst._defaults.minuteMin:tp_inst._defaults.minute>tp_inst._defaults.minuteMax?tp_inst._defaults.minuteMax:tp_inst._defaults.minute;tp_inst.second=tp_inst._defaults.second<tp_inst._defaults.secondMin?tp_inst._defaults.secondMin:tp_inst._defaults.second>tp_inst._defaults.secondMax?tp_inst._defaults.secondMax:tp_inst._defaults.second;tp_inst.millisec=tp_inst._defaults.millisec<tp_inst._defaults.millisecMin?tp_inst._defaults.millisecMin:tp_inst._defaults.millisec>tp_inst._defaults.millisecMax?tp_inst._defaults.millisecMax:tp_inst._defaults.millisec;tp_inst.microsec=tp_inst._defaults.microsec<tp_inst._defaults.microsecMin?tp_inst._defaults.microsecMin:tp_inst._defaults.microsec>tp_inst._defaults.microsecMax?tp_inst._defaults.microsecMax:tp_inst._defaults.microsec;tp_inst.ampm="";tp_inst.$input=$input;if(tp_inst._defaults.altField){tp_inst.$altInput=$(tp_inst._defaults.altField);if(tp_inst._defaults.altRedirectFocus===true){tp_inst.$altInput.css({cursor:"pointer"}).on("focus",function(){$input.trigger("focus")})}}if(tp_inst._defaults.minDate===0||tp_inst._defaults.minDateTime===0){tp_inst._defaults.minDate=new Date()}if(tp_inst._defaults.maxDate===0||tp_inst._defaults.maxDateTime===0){tp_inst._defaults.maxDate=new Date()}if(tp_inst._defaults.minDate!==undefined&&tp_inst._defaults.minDate instanceof Date){tp_inst._defaults.minDateTime=new Date(tp_inst._defaults.minDate.getTime())}if(tp_inst._defaults.minDateTime!==undefined&&tp_inst._defaults.minDateTime instanceof Date){tp_inst._defaults.minDate=new Date(tp_inst._defaults.minDateTime.getTime())}if(tp_inst._defaults.maxDate!==undefined&&tp_inst._defaults.maxDate instanceof Date){tp_inst._defaults.maxDateTime=new Date(tp_inst._defaults.maxDate.getTime())}if(tp_inst._defaults.maxDateTime!==undefined&&tp_inst._defaults.maxDateTime instanceof Date){tp_inst._defaults.maxDate=new Date(tp_inst._defaults.maxDateTime.getTime())}tp_inst.$input.on("focus",function(){tp_inst._onFocus()});return tp_inst},_addTimePicker:function(dp_inst){var currDT=PrimeFaces.trim((this.$altInput&&this._defaults.altFieldTimeOnly)?this.$input.val()+" "+this.$altInput.val():this.$input.val());this.timeDefined=this._parseTime(currDT);this._limitMinMaxDateTime(dp_inst,false);this._injectTimePicker();this._afterInject()},_parseTime:function(timeString,withDate){if(!this.inst){this.inst=$.datepicker._getInst(this.$input[0])}if(withDate||!this._defaults.timeOnly){var dp_dateFormat=$.datepicker._get(this.inst,"dateFormat");try{var parseRes=parseDateTimeInternal(dp_dateFormat,this._defaults.timeFormat,timeString,$.datepicker._getFormatConfig(this.inst),this._defaults);if(!parseRes.timeObj){return false}$.extend(this,parseRes.timeObj)}catch(err){$.timepicker.log("Error parsing the date/time string: "+err+"\ndate/time string = "+timeString+"\ntimeFormat = "+this._defaults.timeFormat+"\ndateFormat = "+dp_dateFormat);return false}return true}else{var timeObj=$.datepicker.parseTime(this._defaults.timeFormat,timeString,this._defaults);if(!timeObj){return false}$.extend(this,timeObj);return true}},_afterInject:function(){var o=this.inst.settings;if(typeof o.afterInject==="function"){o.afterInject.call(this)}},_injectTimePicker:function(){var $dp=this.inst.dpDiv,o=this.inst.settings,tp_inst=this,litem="",uitem="",show=null,max={},gridSize={},size=null,i=0,l=0;if($dp.find("div.ui-timepicker-div").length===0&&o.showTimepicker){var noDisplay=" ui_tpicker_unit_hide",html='<div class="ui-timepicker-div'+(o.isRTL?" ui-timepicker-rtl":"")+(o.oneLine&&o.controlType==="select"?" ui-timepicker-oneLine":"")+'"><dl><dt class="ui_tpicker_time_label'+((o.showTime)?"":noDisplay)+'">'+o.timeText+'</dt><dd class="ui_tpicker_time '+((o.showTime)?"":noDisplay)+'"><input class="ui_tpicker_time_input" '+(o.timeInput?"":"disabled")+"></input></dd>";for(i=0,l=this.units.length;i<l;i++){litem=this.units[i];uitem=litem.substr(0,1).toUpperCase()+litem.substr(1);show=o["show"+uitem]!==null?o["show"+uitem]:this.support[litem];max[litem]=parseInt((o[litem+"Max"]-((o[litem+"Max"]-o[litem+"Min"])%o["step"+uitem])),10);gridSize[litem]=0;html+='<dt class="ui_tpicker_'+litem+"_label"+(show?"":noDisplay)+'">'+o[litem+"Text"]+'</dt><dd class="ui_tpicker_'+litem+(show?"":noDisplay)+'"><div class="ui_tpicker_'+litem+"_slider"+(show?"":noDisplay)+'"></div>';if(show&&o[litem+"Grid"]>0){html+='<div style="padding-left: 1px"><table class="ui-tpicker-grid-label"><tr>';if(litem==="hour"){for(var h=o[litem+"Min"];h<=max[litem];h+=parseInt(o[litem+"Grid"],10)){gridSize[litem]++;var tmph=$.datepicker.formatTime(this.support.ampm?"hht":"HH",{hour:h},o);html+='<td data-for="'+litem+'">'+tmph+"</td>"}}else{for(var m=o[litem+"Min"];m<=max[litem];m+=parseInt(o[litem+"Grid"],10)){gridSize[litem]++;html+='<td data-for="'+litem+'">'+((m<10)?"0":"")+m+"</td>"}}html+="</tr></table></div>"}html+="</dd>"}var showTz=o.showTimezone!==null?o.showTimezone:this.support.timezone;html+='<dt class="ui_tpicker_timezone_label'+(showTz?"":noDisplay)+'">'+o.timezoneText+"</dt>";html+='<dd class="ui_tpicker_timezone'+(showTz?"":noDisplay)+'"></dd>';html+="</dl></div>";var $tp=$(html);if(o.timeOnly===true){$tp.prepend('<div class="ui-widget-header ui-helper-clearfix ui-corner-all"><div class="ui-datepicker-title">'+PrimeFaces.escapeHTML(o.timeOnlyTitle)+"</div></div>");$dp.find(".ui-datepicker-header, .ui-datepicker-calendar").hide()}for(i=0,l=tp_inst.units.length;i<l;i++){litem=tp_inst.units[i];uitem=litem.substr(0,1).toUpperCase()+litem.substr(1);show=o["show"+uitem]!==null?o["show"+uitem]:this.support[litem];tp_inst[litem+"_slider"]=tp_inst.control.create(tp_inst,$tp.find(".ui_tpicker_"+litem+"_slider"),litem,tp_inst[litem],o[litem+"Min"],max[litem],o["step"+uitem]);if(show&&o[litem+"Grid"]>0){size=100*gridSize[litem]*o[litem+"Grid"]/(max[litem]-o[litem+"Min"]);$tp.find(".ui_tpicker_"+litem+" table").css({width:size+"%",marginLeft:o.isRTL?"0":((size/(-2*gridSize[litem]))+"%"),marginRight:o.isRTL?((size/(-2*gridSize[litem]))+"%"):"0px",borderCollapse:"collapse"}).find("td").on("click",function(e){var $t=$(this),h=$t.html(),n=parseInt(h.replace(/[^0-9]/g),10),ap=h.replace(/[^apm]/ig),f=$t.data("for");if(f==="hour"){if(ap.indexOf("p")!==-1&&n<12){n+=12}else{if(ap.indexOf("a")!==-1&&n===12){n=0}}}tp_inst.control.value(tp_inst,tp_inst[f+"_slider"],litem,n);tp_inst._onTimeChange();tp_inst._onSelectHandler()}).css({cursor:"pointer",width:(100/gridSize[litem])+"%",textAlign:"center",overflow:"hidden"})}}this.timezone_select=$tp.find(".ui_tpicker_timezone").append("<select></select>").find("select");$.fn.append.apply(this.timezone_select,$.map(o.timezoneList,function(val,idx){return $("<option></option>").val(typeof val==="object"?val.value:val).text(typeof val==="object"?val.label:val)}));if(typeof(this.timezone)!=="undefined"&&this.timezone!==null&&this.timezone!==""){var local_timezone=(new Date(this.inst.selectedYear,this.inst.selectedMonth,this.inst.selectedDay,12)).getTimezoneOffset()*-1;if(local_timezone===this.timezone){selectLocalTimezone(tp_inst)}else{this.timezone_select.val(this.timezone)}}else{if(typeof(this.hour)!=="undefined"&&this.hour!==null&&this.hour!==""){this.timezone_select.val(o.timezone)}else{selectLocalTimezone(tp_inst)}}this.timezone_select.on("change",function(){tp_inst._onTimeChange();tp_inst._onSelectHandler();tp_inst._afterInject()});var $buttonPanel=$dp.find(".ui-datepicker-buttonpane");if($buttonPanel.length){$buttonPanel.before($tp)}else{$dp.append($tp)}this.$timeObj=$tp.find(".ui_tpicker_time_input");this.$timeObj.on("change",function(){var timeFormat=tp_inst.inst.settings.timeFormat;var parsedTime=$.datepicker.parseTime(timeFormat,this.value);var update=new Date();if(parsedTime){update.setHours(parsedTime.hour);update.setMinutes(parsedTime.minute);update.setSeconds(parsedTime.second);$.datepicker._setTime(tp_inst.inst,update)}else{this.value=tp_inst.formattedTime;this.trigger("blur")}});if(this.inst!==null){var timeDefined=this.timeDefined;this._onTimeChange();this.timeDefined=timeDefined}if(this._defaults.addSliderAccess){var sliderAccessArgs=this._defaults.sliderAccessArgs,rtl=this._defaults.isRTL;sliderAccessArgs.isRTL=rtl;setTimeout(function(){if($tp.find(".ui-slider-access").length===0){$tp.find(".ui-slider:visible").sliderAccess(sliderAccessArgs);var sliderAccessWidth=$tp.find(".ui-slider-access:eq(0)").outerWidth(true);if(sliderAccessWidth){$tp.find("table:visible").each(function(){var $g=$(this),oldWidth=$g.outerWidth(),oldMarginLeft=$g.css(rtl?"marginRight":"marginLeft").toString().replace("%",""),newWidth=oldWidth-sliderAccessWidth,newMarginLeft=((oldMarginLeft*newWidth)/oldWidth)+"%",css={width:newWidth+"px",marginRight:"0px",marginLeft:"0px"};css[rtl?"marginRight":"marginLeft"]=newMarginLeft;$g.css(css)})}}},10)}tp_inst._limitMinMaxDateTime(this.inst,true)}},_limitMinMaxDateTime:function(dp_inst,adjustSliders){var o=this._defaults,dp_date=new Date(dp_inst.selectedYear,dp_inst.selectedMonth,dp_inst.selectedDay);if(!this._defaults.showTimepicker){return}if($.datepicker._get(dp_inst,"minDateTime")!==null&&$.datepicker._get(dp_inst,"minDateTime")!==undefined&&dp_date){var minDateTime=$.datepicker._get(dp_inst,"minDateTime"),minDateTimeDate=new Date(minDateTime.getFullYear(),minDateTime.getMonth(),minDateTime.getDate(),0,0,0,0);if(this.hourMinOriginal===null||this.minuteMinOriginal===null||this.secondMinOriginal===null||this.millisecMinOriginal===null||this.microsecMinOriginal===null){this.hourMinOriginal=o.hourMin;this.minuteMinOriginal=o.minuteMin;this.secondMinOriginal=o.secondMin;this.millisecMinOriginal=o.millisecMin;this.microsecMinOriginal=o.microsecMin}if(dp_inst.settings.timeOnly||minDateTimeDate.getTime()===dp_date.getTime()){this._defaults.hourMin=minDateTime.getHours();if(this.hour<=this._defaults.hourMin){this.hour=this._defaults.hourMin;this._defaults.minuteMin=minDateTime.getMinutes();if(this.minute<=this._defaults.minuteMin){this.minute=this._defaults.minuteMin;this._defaults.secondMin=minDateTime.getSeconds();if(this.second<=this._defaults.secondMin){this.second=this._defaults.secondMin;this._defaults.millisecMin=minDateTime.getMilliseconds();if(this.millisec<=this._defaults.millisecMin){this.millisec=this._defaults.millisecMin;this._defaults.microsecMin=minDateTime.getMicroseconds()}else{if(this.microsec<this._defaults.microsecMin){this.microsec=this._defaults.microsecMin}this._defaults.microsecMin=this.microsecMinOriginal}}else{this._defaults.millisecMin=this.millisecMinOriginal;this._defaults.microsecMin=this.microsecMinOriginal}}else{this._defaults.secondMin=this.secondMinOriginal;this._defaults.millisecMin=this.millisecMinOriginal;this._defaults.microsecMin=this.microsecMinOriginal}}else{this._defaults.minuteMin=this.minuteMinOriginal;this._defaults.secondMin=this.secondMinOriginal;this._defaults.millisecMin=this.millisecMinOriginal;this._defaults.microsecMin=this.microsecMinOriginal}}else{this._defaults.hourMin=this.hourMinOriginal;this._defaults.minuteMin=this.minuteMinOriginal;this._defaults.secondMin=this.secondMinOriginal;this._defaults.millisecMin=this.millisecMinOriginal;this._defaults.microsecMin=this.microsecMinOriginal}}if($.datepicker._get(dp_inst,"maxDateTime")!==null&&$.datepicker._get(dp_inst,"maxDateTime")!==undefined&&dp_date){var maxDateTime=$.datepicker._get(dp_inst,"maxDateTime"),maxDateTimeDate=new Date(maxDateTime.getFullYear(),maxDateTime.getMonth(),maxDateTime.getDate(),0,0,0,0);if(this.hourMaxOriginal===null||this.minuteMaxOriginal===null||this.secondMaxOriginal===null||this.millisecMaxOriginal===null){this.hourMaxOriginal=o.hourMax;this.minuteMaxOriginal=o.minuteMax;this.secondMaxOriginal=o.secondMax;this.millisecMaxOriginal=o.millisecMax;this.microsecMaxOriginal=o.microsecMax}if(dp_inst.settings.timeOnly||maxDateTimeDate.getTime()===dp_date.getTime()){this._defaults.hourMax=maxDateTime.getHours();if(this.hour>=this._defaults.hourMax){this.hour=this._defaults.hourMax;this._defaults.minuteMax=maxDateTime.getMinutes();if(this.minute>=this._defaults.minuteMax){this.minute=this._defaults.minuteMax;this._defaults.secondMax=maxDateTime.getSeconds();if(this.second>=this._defaults.secondMax){this.second=this._defaults.secondMax;this._defaults.millisecMax=maxDateTime.getMilliseconds();if(this.millisec>=this._defaults.millisecMax){this.millisec=this._defaults.millisecMax;this._defaults.microsecMax=maxDateTime.getMicroseconds()}else{if(this.microsec>this._defaults.microsecMax){this.microsec=this._defaults.microsecMax}this._defaults.microsecMax=this.microsecMaxOriginal}}else{this._defaults.millisecMax=this.millisecMaxOriginal;this._defaults.microsecMax=this.microsecMaxOriginal}}else{this._defaults.secondMax=this.secondMaxOriginal;this._defaults.millisecMax=this.millisecMaxOriginal;this._defaults.microsecMax=this.microsecMaxOriginal}}else{this._defaults.minuteMax=this.minuteMaxOriginal;this._defaults.secondMax=this.secondMaxOriginal;this._defaults.millisecMax=this.millisecMaxOriginal;this._defaults.microsecMax=this.microsecMaxOriginal}}else{this._defaults.hourMax=this.hourMaxOriginal;this._defaults.minuteMax=this.minuteMaxOriginal;this._defaults.secondMax=this.secondMaxOriginal;this._defaults.millisecMax=this.millisecMaxOriginal;this._defaults.microsecMax=this.microsecMaxOriginal}}if(dp_inst.settings.minTime!==null){var tempMinTime=new Date("01/01/1970 "+dp_inst.settings.minTime);if(this.hour<tempMinTime.getHours()){this.hour=this._defaults.hourMin=tempMinTime.getHours();this.minute=this._defaults.minuteMin=tempMinTime.getMinutes()}else{if(this.hour===tempMinTime.getHours()&&this.minute<tempMinTime.getMinutes()){this.minute=this._defaults.minuteMin=tempMinTime.getMinutes()}else{if(this._defaults.hourMin<tempMinTime.getHours()){this._defaults.hourMin=tempMinTime.getHours();this._defaults.minuteMin=tempMinTime.getMinutes()}else{if(this._defaults.hourMin===tempMinTime.getHours()===this.hour&&this._defaults.minuteMin<tempMinTime.getMinutes()){this._defaults.minuteMin=tempMinTime.getMinutes()}else{this._defaults.minuteMin=0}}}}}if(dp_inst.settings.maxTime!==null){var tempMaxTime=new Date("01/01/1970 "+dp_inst.settings.maxTime);if(this.hour>tempMaxTime.getHours()){this.hour=this._defaults.hourMax=tempMaxTime.getHours();this.minute=this._defaults.minuteMax=tempMaxTime.getMinutes()}else{if(this.hour===tempMaxTime.getHours()&&this.minute>tempMaxTime.getMinutes()){this.minute=this._defaults.minuteMax=tempMaxTime.getMinutes()}else{if(this._defaults.hourMax>tempMaxTime.getHours()){this._defaults.hourMax=tempMaxTime.getHours();this._defaults.minuteMax=tempMaxTime.getMinutes()}else{if(this._defaults.hourMax===tempMaxTime.getHours()===this.hour&&this._defaults.minuteMax>tempMaxTime.getMinutes()){this._defaults.minuteMax=tempMaxTime.getMinutes()}else{this._defaults.minuteMax=59}}}}}if(adjustSliders!==undefined&&adjustSliders===true){var hourMax=parseInt((this._defaults.hourMax-((this._defaults.hourMax-this._defaults.hourMin)%this._defaults.stepHour)),10),minMax=parseInt((this._defaults.minuteMax-((this._defaults.minuteMax-this._defaults.minuteMin)%this._defaults.stepMinute)),10),secMax=parseInt((this._defaults.secondMax-((this._defaults.secondMax-this._defaults.secondMin)%this._defaults.stepSecond)),10),millisecMax=parseInt((this._defaults.millisecMax-((this._defaults.millisecMax-this._defaults.millisecMin)%this._defaults.stepMillisec)),10),microsecMax=parseInt((this._defaults.microsecMax-((this._defaults.microsecMax-this._defaults.microsecMin)%this._defaults.stepMicrosec)),10);if(this.hour_slider){this.control.options(this,this.hour_slider,"hour",{min:this._defaults.hourMin,max:hourMax,step:this._defaults.stepHour});this.control.value(this,this.hour_slider,"hour",this.hour-(this.hour%this._defaults.stepHour))}if(this.minute_slider){this.control.options(this,this.minute_slider,"minute",{min:this._defaults.minuteMin,max:minMax,step:this._defaults.stepMinute});this.control.value(this,this.minute_slider,"minute",this.minute-(this.minute%this._defaults.stepMinute))}if(this.second_slider){this.control.options(this,this.second_slider,"second",{min:this._defaults.secondMin,max:secMax,step:this._defaults.stepSecond});this.control.value(this,this.second_slider,"second",this.second-(this.second%this._defaults.stepSecond))}if(this.millisec_slider){this.control.options(this,this.millisec_slider,"millisec",{min:this._defaults.millisecMin,max:millisecMax,step:this._defaults.stepMillisec});this.control.value(this,this.millisec_slider,"millisec",this.millisec-(this.millisec%this._defaults.stepMillisec))}if(this.microsec_slider){this.control.options(this,this.microsec_slider,"microsec",{min:this._defaults.microsecMin,max:microsecMax,step:this._defaults.stepMicrosec});this.control.value(this,this.microsec_slider,"microsec",this.microsec-(this.microsec%this._defaults.stepMicrosec))}}},_onTimeChange:function(){if(!this._defaults.showTimepicker){return}var hour=(this.hour_slider)?this.control.value(this,this.hour_slider,"hour"):false,minute=(this.minute_slider)?this.control.value(this,this.minute_slider,"minute"):false,second=(this.second_slider)?this.control.value(this,this.second_slider,"second"):false,millisec=(this.millisec_slider)?this.control.value(this,this.millisec_slider,"millisec"):false,microsec=(this.microsec_slider)?this.control.value(this,this.microsec_slider,"microsec"):false,timezone=(this.timezone_select)?this.timezone_select.val():false,o=this._defaults,pickerTimeFormat=o.pickerTimeFormat||o.timeFormat,pickerTimeSuffix=o.pickerTimeSuffix||o.timeSuffix;if(typeof(hour)==="object"){hour=false}if(typeof(minute)==="object"){minute=false}if(typeof(second)==="object"){second=false}if(typeof(millisec)==="object"){millisec=false}if(typeof(microsec)==="object"){microsec=false}if(typeof(timezone)==="object"){timezone=false}if(hour!==false){hour=parseInt(hour,10)}if(minute!==false){minute=parseInt(minute,10)}if(second!==false){second=parseInt(second,10)}if(millisec!==false){millisec=parseInt(millisec,10)}if(microsec!==false){microsec=parseInt(microsec,10)}if(timezone!==false){timezone=timezone.toString()}var ampm=o[hour<12?"amNames":"pmNames"][0];var hasChanged=(hour!==parseInt(this.hour,10)||minute!==parseInt(this.minute,10)||second!==parseInt(this.second,10)||millisec!==parseInt(this.millisec,10)||microsec!==parseInt(this.microsec,10)||(this.ampm.length>0&&(hour<12)!==($.inArray(this.ampm.toUpperCase(),this.amNames)!==-1))||(this.timezone!==null&&timezone!==this.timezone.toString()));if(hasChanged){if(hour!==false){this.hour=hour}if(minute!==false){this.minute=minute}if(second!==false){this.second=second}if(millisec!==false){this.millisec=millisec}if(microsec!==false){this.microsec=microsec}if(timezone!==false){this.timezone=timezone}if(!this.inst){this.inst=$.datepicker._getInst(this.$input[0])}this._limitMinMaxDateTime(this.inst,true)}if(this.support.ampm){this.ampm=ampm}this.formattedTime=$.datepicker.formatTime(o.timeFormat,this,o);if(this.$timeObj){if(pickerTimeFormat===o.timeFormat){this.$timeObj.val(this.formattedTime+pickerTimeSuffix)}else{this.$timeObj.val($.datepicker.formatTime(pickerTimeFormat,this,o)+pickerTimeSuffix)}if(this.$timeObj[0].setSelectionRange){var sPos=this.$timeObj[0].selectionStart;var ePos=this.$timeObj[0].selectionEnd}}this.timeDefined=true;if(hasChanged){this._updateDateTime()}},_onSelectHandler:function(){var onSelect=this._defaults.onSelect||this.inst.settings.onSelect;var inputEl=this.$input?this.$input[0]:null;if(onSelect&&inputEl){onSelect.apply(inputEl,[this.formattedDateTime,this])}},_updateDateTime:function(dp_inst){dp_inst=this.inst||dp_inst;var dtTmp=(dp_inst.currentYear>0?new Date(dp_inst.currentYear,dp_inst.currentMonth,dp_inst.currentDay):new Date(dp_inst.selectedYear,dp_inst.selectedMonth,dp_inst.selectedDay)),dt=$.datepicker._daylightSavingAdjust(dtTmp),dateFmt=$.datepicker._get(dp_inst,"dateFormat"),formatCfg=$.datepicker._getFormatConfig(dp_inst),timeAvailable=dt!==null&&this.timeDefined;this.formattedDate=$.datepicker.formatDate(dateFmt,(dt===null?new Date():dt),formatCfg);var formattedDateTime=this.formattedDate;if(dp_inst.lastVal===""){dp_inst.currentYear=dp_inst.selectedYear;dp_inst.currentMonth=dp_inst.selectedMonth;dp_inst.currentDay=dp_inst.selectedDay}if(this._defaults.timeOnly===true&&this._defaults.timeOnlyShowDate===false){formattedDateTime=this.formattedTime}else{if((this._defaults.timeOnly!==true&&(this._defaults.alwaysSetTime||timeAvailable))||(this._defaults.timeOnly===true&&this._defaults.timeOnlyShowDate===true)){formattedDateTime+=this._defaults.separator+this.formattedTime+this._defaults.timeSuffix}}this.formattedDateTime=formattedDateTime;if(!this._defaults.showTimepicker){this.$input.val(this.formattedDate)}else{if(this.$altInput&&this._defaults.timeOnly===false&&this._defaults.altFieldTimeOnly===true){this.$altInput.val(this.formattedTime);this.$input.val(this.formattedDate)}else{if(this.$altInput){this.$input.val(formattedDateTime);var altFormattedDateTime="",altSeparator=this._defaults.altSeparator!==null?this._defaults.altSeparator:this._defaults.separator,altTimeSuffix=this._defaults.altTimeSuffix!==null?this._defaults.altTimeSuffix:this._defaults.timeSuffix;if(!this._defaults.timeOnly){if(this._defaults.altFormat){altFormattedDateTime=$.datepicker.formatDate(this._defaults.altFormat,(dt===null?new Date():dt),formatCfg)}else{altFormattedDateTime=this.formattedDate}if(altFormattedDateTime){altFormattedDateTime+=altSeparator}}if(this._defaults.altTimeFormat!==null){altFormattedDateTime+=$.datepicker.formatTime(this._defaults.altTimeFormat,this,this._defaults)+altTimeSuffix}else{altFormattedDateTime+=this.formattedTime+altTimeSuffix}this.$altInput.val(altFormattedDateTime)}else{this.$input.val(formattedDateTime)}}}this.$input.trigger("change")},_onFocus:function(){if(!this.$input.val()&&this._defaults.defaultValue){this.$input.val(this._defaults.defaultValue);var inst=$.datepicker._getInst(this.$input.get(0)),tp_inst=$.datepicker._get(inst,"timepicker");if(tp_inst){if(tp_inst._defaults.timeOnly&&(inst.input.val()!==inst.lastVal)){try{$.datepicker._updateDatepicker(inst)}catch(err){$.timepicker.log(err)}}}}},_controls:{slider:{create:function(tp_inst,obj,unit,val,min,max,step){var rtl=tp_inst._defaults.isRTL;return obj.prop("slide",null).slider({orientation:"horizontal",value:rtl?val*-1:val,min:rtl?max*-1:min,max:rtl?min*-1:max,step:step,slide:function(event,ui){tp_inst.control.value(tp_inst,$(this),unit,rtl?ui.value*-1:ui.value);tp_inst._onTimeChange()},stop:function(event,ui){tp_inst._onSelectHandler()}})},options:function(tp_inst,obj,unit,opts,val){if(tp_inst._defaults.isRTL){if(typeof(opts)==="string"){if(opts==="min"||opts==="max"){if(val!==undefined){return obj.slider(opts,val*-1)}return Math.abs(obj.slider(opts))}return obj.slider(opts)}var min=opts.min,max=opts.max;opts.min=opts.max=null;if(min!==undefined){opts.max=min*-1}if(max!==undefined){opts.min=max*-1}return obj.slider(opts)}if(typeof(opts)==="string"&&val!==undefined){return obj.slider(opts,val)}return obj.slider(opts)},value:function(tp_inst,obj,unit,val){if(tp_inst._defaults.isRTL){if(val!==undefined){return obj.slider("value",val*-1)}return Math.abs(obj.slider("value"))}if(val!==undefined){return obj.slider("value",val)}return obj.slider("value")}},select:{create:function(tp_inst,obj,unit,val,min,max,step){var sel='<select class="ui-timepicker-select ui-state-default ui-corner-all" data-unit="'+unit+'" data-min="'+min+'" data-max="'+max+'" data-step="'+step+'">',format=tp_inst._defaults.pickerTimeFormat||tp_inst._defaults.timeFormat;for(var i=min;i<=max;i+=step){sel+='<option value="'+i+'"'+(i===val?" selected":"")+">";if(unit==="hour"){sel+=$.datepicker.formatTime(PrimeFaces.trim(format.replace(/[^ht ]/ig,"")),{hour:i},tp_inst._defaults)}else{if(unit==="millisec"||unit==="microsec"||i>=10){sel+=i}else{sel+="0"+i.toString()}}sel+="</option>"}sel+="</select>";obj.children("select").remove();$(sel).appendTo(obj).on("change",function(e){tp_inst._onTimeChange();tp_inst._onSelectHandler();tp_inst._afterInject()});return obj},options:function(tp_inst,obj,unit,opts,val){var o={},$t=obj.children("select");if(typeof(opts)==="string"){if(val===undefined){return $t.data(opts)}o[opts]=val}else{o=opts}return tp_inst.control.create(tp_inst,obj,$t.data("unit"),$t.val(),o.min>=0?o.min:$t.data("min"),o.max||$t.data("max"),o.step||$t.data("step"))},value:function(tp_inst,obj,unit,val){var $t=obj.children("select");if(val!==undefined){return $t.val(val)}return $t.val()}}}});$.fn.extend({timepicker:function(o){o=o||{};var tmp_args=Array.prototype.slice.call(arguments);if(typeof o==="object"){tmp_args[0]=$.extend(o,{timeOnly:true})}return $(this).each(function(){$.fn.datetimepicker.apply($(this),tmp_args)})},datetimepicker:function(o){o=o||{};var tmp_args=arguments;if(typeof(o)==="string"){if(o==="getDate"||(o==="option"&&tmp_args.length===2&&typeof(tmp_args[1])==="string")){return $.fn.datepicker.apply($(this[0]),tmp_args)}else{return this.each(function(){var $t=$(this);$t.datepicker.apply($t,tmp_args)})}}else{return this.each(function(){var $t=$(this);$t.datepicker($.timepicker._newInst($t,o)._defaults)})}}});$.datepicker.parseDateTime=function(dateFormat,timeFormat,dateTimeString,dateSettings,timeSettings){var parseRes=parseDateTimeInternal(dateFormat,timeFormat,dateTimeString,dateSettings,timeSettings);if(parseRes.timeObj){var t=parseRes.timeObj;parseRes.date.setHours(t.hour,t.minute,t.second,t.millisec);parseRes.date.setMicroseconds(t.microsec)}return parseRes.date};$.datepicker.parseTime=function(timeFormat,timeString,options){var o=extendRemove(extendRemove({},$.timepicker._defaults),options||{}),iso8601=(timeFormat.replace(/\'.*?\'/g,"").indexOf("Z")!==-1);var strictParse=function(f,s,o){var getPatternAmpm=function(amNames,pmNames){var markers=[];if(amNames){$.merge(markers,amNames)}if(pmNames){$.merge(markers,pmNames)}markers=$.map(markers,function(val){return val.replace(/[.*+?|()\[\]{}\\]/g,"\\$&")});return"("+markers.join("|")+")?"};var getFormatPositions=function(timeFormat){var finds=timeFormat.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|c{1}|t{1,2}|z|'.*?')/g),orders={h:-1,m:-1,s:-1,l:-1,c:-1,t:-1,z:-1};if(finds){for(var i=0;i<finds.length;i++){if(orders[finds[i].toString().charAt(0)]===-1){orders[finds[i].toString().charAt(0)]=i+1}}}return orders};var regstr="^"+f.toString().replace(/([hH]{1,2}|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g,function(match){var ml=match.length;switch(match.charAt(0).toLowerCase()){case"h":return ml===1?"(\\d?\\d)":"(\\d{"+ml+"})";case"m":return ml===1?"(\\d?\\d)":"(\\d{"+ml+"})";case"s":return ml===1?"(\\d?\\d)":"(\\d{"+ml+"})";case"l":return"(\\d?\\d?\\d)";case"c":return"(\\d?\\d?\\d)";case"z":return"(z|[-+]\\d\\d:?\\d\\d|\\S+)?";case"t":return getPatternAmpm(o.amNames,o.pmNames);default:return"("+match.replace(/\'/g,"").replace(/(\.|\$|\^|\\|\/|\(|\)|\[|\]|\?|\+|\*)/g,function(m){return"\\"+m})+")?"}}).replace(/\s/g,"\\s?")+o.timeSuffix+"$",order=getFormatPositions(f),ampm="",treg;treg=s.match(new RegExp(regstr,"i"));var resTime={hour:0,minute:0,second:0,millisec:0,microsec:0};if(treg){if(order.t!==-1){if(treg[order.t]===undefined||treg[order.t].length===0){ampm="";resTime.ampm=""}else{ampm=$.inArray(treg[order.t].toUpperCase(),$.map(o.amNames,function(x,i){return x.toUpperCase()}))!==-1?"AM":"PM";resTime.ampm=o[ampm==="AM"?"amNames":"pmNames"][0]}}if(order.h!==-1){if(ampm==="AM"&&treg[order.h]==="12"){resTime.hour=0}else{if(ampm==="PM"&&treg[order.h]!=="12"){resTime.hour=parseInt(treg[order.h],10)+12}else{resTime.hour=Number(treg[order.h])}}}if(order.m!==-1){resTime.minute=Number(treg[order.m])}if(order.s!==-1){resTime.second=Number(treg[order.s])}if(order.l!==-1){resTime.millisec=Number(treg[order.l])}if(order.c!==-1){resTime.microsec=Number(treg[order.c])}if(order.z!==-1&&treg[order.z]!==undefined){resTime.timezone=$.timepicker.timezoneOffsetNumber(treg[order.z])}return resTime}return false};var looseParse=function(f,s,o){try{var d=new Date("2012-01-01 "+s);if(isNaN(d.getTime())){d=new Date("2012-01-01T"+s);if(isNaN(d.getTime())){d=new Date("01/01/2012 "+s);if(isNaN(d.getTime())){throw"Unable to parse time with native Date: "+s}}}return{hour:d.getHours(),minute:d.getMinutes(),second:d.getSeconds(),millisec:d.getMilliseconds(),microsec:d.getMicroseconds(),timezone:d.getTimezoneOffset()*-1}}catch(err){try{return strictParse(f,s,o)}catch(err2){$.timepicker.log("Unable to parse \ntimeString: "+s+"\ntimeFormat: "+f)}}return false};if(typeof o.parse==="function"){return o.parse(timeFormat,timeString,o)}if(o.parse==="loose"){return looseParse(timeFormat,timeString,o)}return strictParse(timeFormat,timeString,o)};$.datepicker.formatTime=function(format,time,options){options=options||{};options=$.extend({},$.timepicker._defaults,options);time=$.extend({hour:0,minute:0,second:0,millisec:0,microsec:0,timezone:null},time);var tmptime=format,ampmName=options.amNames[0],hour=parseInt(time.hour,10);if(hour>11){ampmName=options.pmNames[0]}tmptime=tmptime.replace(/(?:HH?|hh?|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g,function(match){switch(match){case"HH":return("0"+hour).slice(-2);case"H":return hour;case"hh":return("0"+convert24to12(hour)).slice(-2);case"h":return convert24to12(hour);case"mm":return("0"+time.minute).slice(-2);case"m":return time.minute;case"ss":return("0"+time.second).slice(-2);case"s":return time.second;case"l":return("00"+time.millisec).slice(-3);case"c":return("00"+time.microsec).slice(-3);case"z":return $.timepicker.timezoneOffsetString(time.timezone===null?options.timezone:time.timezone,false);case"Z":return $.timepicker.timezoneOffsetString(time.timezone===null?options.timezone:time.timezone,true);case"T":return ampmName.charAt(0).toUpperCase();case"TT":return ampmName.toUpperCase();case"t":return ampmName.charAt(0).toLowerCase();case"tt":return ampmName.toLowerCase();default:return match.replace(/'/g,"")}});return tmptime};$.datepicker._base_selectDate=$.datepicker._selectDate;$.datepicker._selectDate=function(id,dateStr){var inst=this._getInst($(id)[0]),tp_inst=this._get(inst,"timepicker"),was_inline;if(tp_inst&&inst.settings.showTimepicker){tp_inst._limitMinMaxDateTime(inst,true);was_inline=inst.inline;inst.inline=inst.stay_open=true;this._base_selectDate(id,dateStr);inst.inline=was_inline;inst.stay_open=false;this._notifyChange(inst);this._updateDatepicker(inst)}else{this._base_selectDate(id,dateStr)}};$.datepicker._base_updateDatepicker=$.datepicker._updateDatepicker;$.datepicker._updateDatepicker=function(inst){var input=inst.input[0];if($.datepicker._curInst&&$.datepicker._curInst!==inst&&$.datepicker._datepickerShowing&&$.datepicker._lastInput!==input){return}if(typeof(inst.stay_open)!=="boolean"||inst.stay_open===false){this._base_updateDatepicker(inst);var tp_inst=this._get(inst,"timepicker");if(tp_inst){tp_inst._addTimePicker(inst)}}};$.datepicker._base_doKeyPress=$.datepicker._doKeyPress;$.datepicker._doKeyPress=function(event){var inst=$.datepicker._getInst(event.target),tp_inst=$.datepicker._get(inst,"timepicker");if(tp_inst){if($.datepicker._get(inst,"constrainInput")){var ampm=tp_inst.support.ampm,tz=tp_inst._defaults.showTimezone!==null?tp_inst._defaults.showTimezone:tp_inst.support.timezone,dateChars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat")),datetimeChars=tp_inst._defaults.timeFormat.toString().replace(/[hms]/g,"").replace(/TT/g,ampm?"APM":"").replace(/Tt/g,ampm?"AaPpMm":"").replace(/tT/g,ampm?"AaPpMm":"").replace(/T/g,ampm?"AP":"").replace(/tt/g,ampm?"apm":"").replace(/t/g,ampm?"ap":"")+" "+tp_inst._defaults.separator+tp_inst._defaults.timeSuffix+(tz?tp_inst._defaults.timezoneList.join(""):"")+(tp_inst._defaults.amNames.join(""))+(tp_inst._defaults.pmNames.join(""))+dateChars,chr=String.fromCharCode(event.charCode===undefined?event.keyCode:event.charCode);return event.ctrlKey||(chr<" "||!dateChars||datetimeChars.indexOf(chr)>-1)}}return $.datepicker._base_doKeyPress(event)};$.datepicker._base_updateAlternate=$.datepicker._updateAlternate;$.datepicker._updateAlternate=function(inst){var tp_inst=this._get(inst,"timepicker");if(tp_inst){var altField=tp_inst._defaults.altField;if(altField){var altFormat=tp_inst._defaults.altFormat||tp_inst._defaults.dateFormat,date=this._getDate(inst),formatCfg=$.datepicker._getFormatConfig(inst),altFormattedDateTime="",altSeparator=tp_inst._defaults.altSeparator?tp_inst._defaults.altSeparator:tp_inst._defaults.separator,altTimeSuffix=tp_inst._defaults.altTimeSuffix?tp_inst._defaults.altTimeSuffix:tp_inst._defaults.timeSuffix,altTimeFormat=tp_inst._defaults.altTimeFormat!==null?tp_inst._defaults.altTimeFormat:tp_inst._defaults.timeFormat;altFormattedDateTime+=$.datepicker.formatTime(altTimeFormat,tp_inst,tp_inst._defaults)+altTimeSuffix;if(!tp_inst._defaults.timeOnly&&!tp_inst._defaults.altFieldTimeOnly&&date!==null){if(tp_inst._defaults.altFormat){altFormattedDateTime=$.datepicker.formatDate(tp_inst._defaults.altFormat,date,formatCfg)+altSeparator+altFormattedDateTime}else{altFormattedDateTime=tp_inst.formattedDate+altSeparator+altFormattedDateTime}}$(altField).val(inst.input.val()?altFormattedDateTime:"")}}else{$.datepicker._base_updateAlternate(inst)}};$.datepicker._base_doKeyUp=$.datepicker._doKeyUp;$.datepicker._doKeyUp=function(event){var inst=$.datepicker._getInst(event.target),tp_inst=$.datepicker._get(inst,"timepicker");if(tp_inst){if(tp_inst._defaults.timeOnly&&(inst.input.val()!==inst.lastVal)){try{$.datepicker._updateDatepicker(inst)}catch(err){$.timepicker.log(err)}}}return $.datepicker._base_doKeyUp(event)};$.datepicker._base_gotoToday=$.datepicker._gotoToday;$.datepicker._gotoToday=function(id){var inst=this._getInst($(id)[0]);this._base_gotoToday(id);var tp_inst=this._get(inst,"timepicker");if(!tp_inst){return}var tzoffset=$.timepicker.timezoneOffsetNumber(tp_inst.timezone);var now=new Date();now.setMinutes(now.getMinutes()+now.getTimezoneOffset()+parseInt(tzoffset,10));this._setTime(inst,now);this._setDate(inst,now);tp_inst._onSelectHandler()};$.datepicker._disableTimepickerDatepicker=function(target){var inst=this._getInst(target);if(!inst){return}var tp_inst=this._get(inst,"timepicker");$(target).datepicker("getDate");if(tp_inst){inst.settings.showTimepicker=false;tp_inst._defaults.showTimepicker=false;tp_inst._updateDateTime(inst)}};$.datepicker._enableTimepickerDatepicker=function(target){var inst=this._getInst(target);if(!inst){return}var tp_inst=this._get(inst,"timepicker");$(target).datepicker("getDate");if(tp_inst){inst.settings.showTimepicker=true;tp_inst._defaults.showTimepicker=true;tp_inst._addTimePicker(inst);tp_inst._updateDateTime(inst)}};$.datepicker._setTime=function(inst,date){var tp_inst=this._get(inst,"timepicker");if(tp_inst){var defaults=tp_inst._defaults;tp_inst.hour=date?date.getHours():defaults.hour;tp_inst.minute=date?date.getMinutes():defaults.minute;tp_inst.second=date?date.getSeconds():defaults.second;tp_inst.millisec=date?date.getMilliseconds():defaults.millisec;tp_inst.microsec=date?date.getMicroseconds():defaults.microsec;tp_inst._limitMinMaxDateTime(inst,true);tp_inst._onTimeChange();tp_inst._updateDateTime(inst)}};$.datepicker._setTimeDatepicker=function(target,date,withDate){var inst=this._getInst(target);if(!inst){return}var tp_inst=this._get(inst,"timepicker");if(tp_inst){this._setDateFromField(inst);var tp_date;if(date){if(typeof date==="string"){tp_inst._parseTime(date,withDate);tp_date=new Date();tp_date.setHours(tp_inst.hour,tp_inst.minute,tp_inst.second,tp_inst.millisec);tp_date.setMicroseconds(tp_inst.microsec)}else{tp_date=new Date(date.getTime());tp_date.setMicroseconds(date.getMicroseconds())}if(tp_date.toString()==="Invalid Date"){tp_date=undefined}this._setTime(inst,tp_date)}}};$.datepicker._base_setDateDatepicker=$.datepicker._setDateDatepicker;$.datepicker._setDateDatepicker=function(target,_date){var inst=this._getInst(target);var date=_date;if(!inst){return}if(typeof(_date)==="string"){date=new Date(_date);if(!date.getTime()){this._base_setDateDatepicker.apply(this,arguments);date=$(target).datepicker("getDate")}}var tp_inst=this._get(inst,"timepicker");var tp_date;if(date instanceof Date){tp_date=new Date(date.getTime());tp_date.setMicroseconds(date.getMicroseconds())}else{tp_date=date}if(tp_inst&&tp_date){if(!tp_inst.support.timezone&&tp_inst._defaults.timezone===null){tp_inst.timezone=tp_date.getTimezoneOffset()*-1}date=$.timepicker.timezoneAdjust(date,$.timepicker.timezoneOffsetString(-date.getTimezoneOffset()),tp_inst.timezone);tp_date=$.timepicker.timezoneAdjust(tp_date,$.timepicker.timezoneOffsetString(-tp_date.getTimezoneOffset()),tp_inst.timezone)}this._updateDatepicker(inst);this._base_setDateDatepicker.apply(this,arguments);this._setTimeDatepicker(target,tp_date,true)};$.datepicker._base_getDateDatepicker=$.datepicker._getDateDatepicker;$.datepicker._getDateDatepicker=function(target,noDefault){var inst=this._getInst(target);if(!inst){return}var tp_inst=this._get(inst,"timepicker");if(tp_inst){if(inst.lastVal===undefined){this._setDateFromField(inst,noDefault)}var date=this._getDate(inst);var currDT=null;if(tp_inst.$altInput&&tp_inst._defaults.altFieldTimeOnly){currDT=tp_inst.$input.val()+" "+tp_inst.$altInput.val()}else{if(tp_inst.$input.get(0).tagName!=="INPUT"&&tp_inst.$altInput){currDT=tp_inst.$altInput.val()}else{currDT=tp_inst.$input.val()}}if(date&&tp_inst._parseTime(currDT,!inst.settings.timeOnly)){date.setHours(tp_inst.hour,tp_inst.minute,tp_inst.second,tp_inst.millisec);date.setMicroseconds(tp_inst.microsec);if(tp_inst.timezone!=null){if(!tp_inst.support.timezone&&tp_inst._defaults.timezone===null){tp_inst.timezone=date.getTimezoneOffset()*-1}date=$.timepicker.timezoneAdjust(date,tp_inst.timezone,$.timepicker.timezoneOffsetString(-date.getTimezoneOffset()))}}return date}return this._base_getDateDatepicker(target,noDefault)};$.datepicker._base_parseDate=$.datepicker.parseDate;$.datepicker.parseDate=function(format,value,settings){var date;try{date=this._base_parseDate(format,value,settings)}catch(err){if(err.indexOf(":")>=0){date=this._base_parseDate(format,value.substring(0,value.length-(err.length-err.indexOf(":")-2)),settings);$.timepicker.log("Error parsing the date string: "+err+"\ndate string = "+value+"\ndate format = "+format)}else{throw err}}return date};$.datepicker._base_formatDate=$.datepicker._formatDate;$.datepicker._formatDate=function(inst,day,month,year){var tp_inst=this._get(inst,"timepicker");if(tp_inst){tp_inst._updateDateTime(inst);return tp_inst.$input.val()}return this._base_formatDate(inst)};$.datepicker._base_optionDatepicker=$.datepicker._optionDatepicker;$.datepicker._optionDatepicker=function(target,name,value){var inst=this._getInst(target),name_clone;if(!inst){return null}var tp_inst=this._get(inst,"timepicker");if(tp_inst){var min=null,max=null,onselect=null,overrides=tp_inst._defaults.evnts,fns={},prop,ret,oldVal,$target;if(typeof name==="string"){if(name==="minDate"||name==="minDateTime"){min=value}else{if(name==="maxDate"||name==="maxDateTime"){max=value}else{if(name==="onSelect"){onselect=value}else{if(overrides.hasOwnProperty(name)){if(typeof(value)==="undefined"){return overrides[name]}fns[name]=value;name_clone={}}}}}}else{if(typeof name==="object"){if(name.minDate){min=name.minDate}else{if(name.minDateTime){min=name.minDateTime}else{if(name.maxDate){max=name.maxDate}else{if(name.maxDateTime){max=name.maxDateTime}}}}for(prop in overrides){if(overrides.hasOwnProperty(prop)&&name[prop]){fns[prop]=name[prop]}}}}for(prop in fns){if(fns.hasOwnProperty(prop)){overrides[prop]=fns[prop];if(!name_clone){name_clone=$.extend({},name)}delete name_clone[prop]}}if(name_clone&&isEmptyObject(name_clone)){return}if(min){if(min===0){min=new Date()}else{min=new Date(min)}tp_inst._defaults.minDate=min;tp_inst._defaults.minDateTime=min}else{if(max){if(max===0){max=new Date()}else{max=new Date(max)}tp_inst._defaults.maxDate=max;tp_inst._defaults.maxDateTime=max}else{if(onselect){tp_inst._defaults.onSelect=onselect}}}if(min||max){$target=$(target);oldVal=$target.datetimepicker("getDate");ret=this._base_optionDatepicker.call($.datepicker,target,name_clone||name,value);$target.datetimepicker("setDate",oldVal);return ret}}if(value===undefined){return this._base_optionDatepicker.call($.datepicker,target,name)}return this._base_optionDatepicker.call($.datepicker,target,name_clone||name,value)};var isEmptyObject=function(obj){var prop;for(prop in obj){if(obj.hasOwnProperty(prop)){return false}}return true};var extendRemove=function(target,props){$.extend(target,props);for(var name in props){if(props[name]===null||props[name]===undefined){target[name]=props[name]}}return target};var detectSupport=function(timeFormat){var tf=timeFormat.replace(/'.*?'/g,"").toLowerCase(),isIn=function(f,t){return f.indexOf(t)!==-1?true:false};return{hour:isIn(tf,"h"),minute:isIn(tf,"m"),second:isIn(tf,"s"),millisec:isIn(tf,"l"),microsec:isIn(tf,"c"),timezone:isIn(tf,"z"),ampm:isIn(tf,"t")&&isIn(timeFormat,"h"),iso8601:isIn(timeFormat,"Z")}};var convert24to12=function(hour){hour%=12;if(hour===0){hour=12}return String(hour)};var computeEffectiveSetting=function(settings,property){return settings&&settings[property]?settings[property]:$.timepicker._defaults[property]};var splitDateTime=function(dateTimeString,timeSettings){var separator=computeEffectiveSetting(timeSettings,"separator"),format=computeEffectiveSetting(timeSettings,"timeFormat"),timeParts=format.split(separator),timePartsLen=timeParts.length,allParts=dateTimeString.split(separator),allPartsLen=allParts.length;if(allPartsLen>1){return{dateString:allParts.splice(0,allPartsLen-timePartsLen).join(separator),timeString:allParts.splice(0,timePartsLen).join(separator)}}return{dateString:dateTimeString,timeString:""}};var parseDateTimeInternal=function(dateFormat,timeFormat,dateTimeString,dateSettings,timeSettings){var date,parts,parsedTime;parts=splitDateTime(dateTimeString,timeSettings);date=$.datepicker._base_parseDate(dateFormat,parts.dateString,dateSettings);if(parts.timeString===""){return{date:date}}parsedTime=$.datepicker.parseTime(timeFormat,parts.timeString,timeSettings);if(!parsedTime){throw"Wrong time format"}return{date:date,timeObj:parsedTime}};var selectLocalTimezone=function(tp_inst,date){if(tp_inst&&tp_inst.timezone_select){var now=date||new Date();tp_inst.timezone_select.val(-now.getTimezoneOffset())}};$.timepicker=new Timepicker();$.timepicker.timezoneOffsetString=function(tzMinutes,iso8601){if(isNaN(tzMinutes)||tzMinutes>840||tzMinutes<-720){return tzMinutes}var off=tzMinutes,minutes=off%60,hours=(off-minutes)/60,iso=iso8601?":":"",tz=(off>=0?"+":"-")+("0"+Math.abs(hours)).slice(-2)+iso+("0"+Math.abs(minutes)).slice(-2);if(tz==="+00:00"){return"Z"}return tz};$.timepicker.timezoneOffsetNumber=function(tzString){var normalized=tzString.toString().replace(":","");if(normalized.toUpperCase()==="Z"){return 0}if(!/^(\-|\+)\d{4}$/.test(normalized)){return parseInt(tzString,10)}return((normalized.substr(0,1)==="-"?-1:1)*((parseInt(normalized.substr(1,2),10)*60)+parseInt(normalized.substr(3,2),10)))};$.timepicker.timezoneAdjust=function(date,fromTimezone,toTimezone){var fromTz=$.timepicker.timezoneOffsetNumber(fromTimezone);var toTz=$.timepicker.timezoneOffsetNumber(toTimezone);if(!isNaN(toTz)){date.setMinutes(date.getMinutes()+(-fromTz)-(-toTz))}return date};$.timepicker.timeRange=function(startTime,endTime,options){return $.timepicker.handleRange("timepicker",startTime,endTime,options)};$.timepicker.datetimeRange=function(startTime,endTime,options){$.timepicker.handleRange("datetimepicker",startTime,endTime,options)};$.timepicker.dateRange=function(startTime,endTime,options){$.timepicker.handleRange("datepicker",startTime,endTime,options)};$.timepicker.handleRange=function(method,startTime,endTime,options){options=$.extend({},{minInterval:0,maxInterval:0,start:{},end:{}},options);var timeOnly=false;if(method==="timepicker"){timeOnly=true;method="datetimepicker"}function checkDates(changed,other){var startdt=startTime[method]("getDate"),enddt=endTime[method]("getDate"),changeddt=changed[method]("getDate");if(startdt!==null){var minDate=new Date(startdt.getTime()),maxDate=new Date(startdt.getTime());minDate.setMilliseconds(minDate.getMilliseconds()+options.minInterval);maxDate.setMilliseconds(maxDate.getMilliseconds()+options.maxInterval);if(options.minInterval>0&&minDate>enddt){endTime[method]("setDate",minDate)}else{if(options.maxInterval>0&&maxDate<enddt){endTime[method]("setDate",maxDate)}else{if(startdt>enddt){other[method]("setDate",changeddt)}}}}}function selected(changed,other,option){if(!changed.val()){return}var date=changed[method].call(changed,"getDate");if(date!==null&&options.minInterval>0){if(option==="minDate"){date.setMilliseconds(date.getMilliseconds()+options.minInterval)}if(option==="maxDate"){date.setMilliseconds(date.getMilliseconds()-options.minInterval)}}if(date.getTime){other[method].call(other,"option",option,date)}}$.fn[method].call(startTime,$.extend({timeOnly:timeOnly,onClose:function(dateText,inst){checkDates($(this),endTime)},onSelect:function(selectedDateTime){selected($(this),endTime,"minDate")}},options,options.start));$.fn[method].call(endTime,$.extend({timeOnly:timeOnly,onClose:function(dateText,inst){checkDates($(this),startTime)},onSelect:function(selectedDateTime){selected($(this),startTime,"maxDate")}},options,options.end));checkDates(startTime,endTime);selected(startTime,endTime,"minDate");selected(endTime,startTime,"maxDate");return $([startTime.get(0),endTime.get(0)])};$.timepicker.log=function(){if(window.console&&window.console.log&&window.console.log.apply){window.console.log.apply(window.console,Array.prototype.slice.call(arguments))}};$.timepicker._util={_extendRemove:extendRemove,_isEmptyObject:isEmptyObject,_convert24to12:convert24to12,_detectSupport:detectSupport,_selectLocalTimezone:selectLocalTimezone,_computeEffectiveSetting:computeEffectiveSetting,_splitDateTime:splitDateTime,_parseDateTimeInternal:parseDateTimeInternal};if(!Date.prototype.getMicroseconds){Date.prototype.microseconds=0;Date.prototype.getMicroseconds=function(){return this.microseconds};Date.prototype.setMicroseconds=function(m){this.setMilliseconds(this.getMilliseconds()+Math.floor(m/1000));this.microseconds=m%1000;return this}}$.timepicker.version="1.6.3"}));
$(function(){var a={primaryStyles:["fontFamily","fontSize","fontWeight","fontVariant","fontStyle","paddingLeft","paddingTop","paddingBottom","paddingRight","marginLeft","marginTop","marginBottom","marginRight","borderLeftColor","borderTopColor","borderBottomColor","borderRightColor","borderLeftStyle","borderTopStyle","borderBottomStyle","borderRightStyle","borderLeftWidth","borderTopWidth","borderBottomWidth","borderRightWidth","line-height","outline"],specificStyle:{"word-wrap":"break-word","overflow-x":"hidden","overflow-y":"auto"},simulator:$('<div id="textarea_simulator"></div>').css({position:"absolute",top:"0px",left:"0px",visibility:"hidden"}).appendTo(document.body),toHtml:function(b){return PrimeFaces.escapeHTML(b).replace(/\n/g,"<br>").split(" ").join('<span style="white-space:prev-wrap">&nbsp;</span>')},getCaretPosition:function(){var c=a,n=this,g=n[0],d=n.offset();if($.browser.msie&&document.selection&&document.selection.createRange){g.focus();var h=document.selection.createRange();$("#hskeywords").val(g.scrollTop);return{left:h.boundingLeft-d.left,top:parseInt(h.boundingTop)-d.top+g.scrollTop+document.documentElement.scrollTop+parseInt(n.getComputedStyle("fontSize"))}}c.simulator.empty();$.each(c.primaryStyles,function(p,q){n.cloneStyle(c.simulator,q)});c.simulator.css($.extend({width:n.width()+"px",height:n.height()+"px"},c.specificStyle));var l=n.val(),e=n.getCursorPosition();var f=l.substring(0,e),m=l.substring(e);var j=$('<span class="before"></span>').html(c.toHtml(f)),o=$('<span class="focus"></span>'),b=$('<span class="after"></span>').html(c.toHtml(m));c.simulator.append(j).append(o).append(b);var i=o.offset(),k=c.simulator.offset();return{top:i.top-k.top-g.scrollTop+($.browser.mozilla?0:parseInt(n.getComputedStyle("fontSize"))),left:o[0].offsetLeft-c.simulator[0].offsetLeft-g.scrollLeft}}};$.fn.extend({getComputedStyle:function(c){if(this.length==0){return}var d=this[0];var b=this.css(c);b=b||($.browser.msie?d.currentStyle[c]:document.defaultView.getComputedStyle(d,null)[c]);return b},cloneStyle:function(c,b){var d=this.getComputedStyle(b);if(!!d){$(c).css(b,d)}},cloneAllStyle:function(e,d){var c=this[0];for(var b in c.style){var f=c.style[b];typeof f=="string"||typeof f=="number"?this.cloneStyle(e,b):NaN}},getCursorPosition:function(){var e=this[0],b=0;if("selectionStart" in e){b=e.selectionStart}else{if("selection" in document){var c=document.selection.createRange();if(parseInt($.browser.version)>6){e.focus();var g=document.selection.createRange().text.length;c.moveStart("character",-e.value.length);b=c.text.length-g}else{var h=document.body.createTextRange();h.moveToElementText(e);for(;h.compareEndPoints("StartToStart",c)<0;b++){h.moveStart("character",1)}for(var d=0;d<=b;d++){if(e.value.charAt(d)=="\n"){b++}}var f=e.value.split("\n").length-1;b-=f;return b}}}return b},getCaretPosition:a.getCaretPosition})});
/*!
	autosize 4.0.2
	license: MIT
	http://www.jacklmoore.com/autosize
*/
(function(c,a){if(typeof define==="function"&&define.amd){define(["module","exports"],a)}else{if(typeof exports!=="undefined"){a(module,exports)}else{var b={exports:{}};a(b,b.exports);c.autosize=b.exports}}})(this,function(b,d){var a=typeof Map==="function"?new Map():function(){var n=[];var k=[];return{has:function m(p){return n.indexOf(p)>-1},get:function l(p){return k[n.indexOf(p)]},set:function o(p,q){if(n.indexOf(p)===-1){n.push(p);k.push(q)}},_delete:function e(q){var p=n.indexOf(q);if(p>-1){n.splice(p,1);k.splice(p,1)}}}}();var h=function h(e){return new Event(e,{bubbles:true})};try{new Event("test")}catch(f){h=function h(k){var e=document.createEvent("Event");e.initEvent(k,true,false);return e}}function j(n){if(!n||!n.nodeName||n.nodeName!=="TEXTAREA"||a.has(n)){return}var e=null;var r=null;var k=null;function t(){var u=window.getComputedStyle(n,null);if(u.resize==="vertical"){n.style.resize="none"}else{if(u.resize==="both"){n.style.resize="horizontal"}}if(u.boxSizing==="content-box"){e=-(parseFloat(u.paddingTop)+parseFloat(u.paddingBottom))}else{e=parseFloat(u.borderTopWidth)+parseFloat(u.borderBottomWidth)}if(isNaN(e)){e=0}m()}function p(v){var u=n.style.width;n.style.width="0px";n.offsetWidth;n.style.width=u;n.style.overflowY=v}function s(v){var u=[];while(v&&v.parentNode&&v.parentNode instanceof Element){if(v.parentNode.scrollTop){u.push({node:v.parentNode,scrollTop:v.parentNode.scrollTop})}v=v.parentNode}return u}function l(){if(n.scrollHeight===0){return}var v=s(n);var u=document.documentElement&&document.documentElement.scrollTop;n.style.height="";n.style.height=n.scrollHeight+e+"px";r=n.clientWidth;v.forEach(function(w){w.node.scrollTop=w.scrollTop});if(u){document.documentElement.scrollTop=u}}function m(){l();var y=Math.round(parseFloat(n.style.height));var w=window.getComputedStyle(n,null);var x=w.boxSizing==="content-box"?Math.round(parseFloat(w.height)):n.offsetHeight;if(x<y){if(w.overflowY==="hidden"){p("scroll");l();x=w.boxSizing==="content-box"?Math.round(parseFloat(window.getComputedStyle(n,null).height)):n.offsetHeight}}else{if(w.overflowY!=="hidden"){p("hidden");l();x=w.boxSizing==="content-box"?Math.round(parseFloat(window.getComputedStyle(n,null).height)):n.offsetHeight}}if(k!==x){k=x;var u=h("autosize:resized");try{n.dispatchEvent(u)}catch(v){}}}var o=function o(){if(n.clientWidth!==r){m()}};var q=function(u){window.removeEventListener("resize",o,false);n.removeEventListener("input",m,false);n.removeEventListener("keyup",m,false);n.removeEventListener("autosize:destroy",q,false);n.removeEventListener("autosize:update",m,false);Object.keys(u).forEach(function(v){n.style[v]=u[v]});a._delete(n)}.bind(n,{height:n.style.height,resize:n.style.resize,overflowY:n.style.overflowY,overflowX:n.style.overflowX,wordWrap:n.style.wordWrap});n.addEventListener("autosize:destroy",q,false);if("onpropertychange" in n&&"oninput" in n){n.addEventListener("keyup",m,false)}window.addEventListener("resize",o,false);n.addEventListener("input",m,false);n.addEventListener("autosize:update",m,false);n.style.overflowX="hidden";n.style.wordWrap="break-word";a.set(n,{destroy:q,update:m});t()}function g(k){var e=a.get(k);if(e){e.destroy()}}function c(k){var e=a.get(k);if(e){e.update()}}var i=null;if(typeof window==="undefined"||typeof window.getComputedStyle!=="function"){i=function i(e){return e};i.destroy=function(e){return e};i.update=function(e){return e}}else{i=function i(k,e){if(k){Array.prototype.forEach.call(k.length?k:[k],function(l){return j(l,e)})}return k};i.destroy=function(e){if(e){Array.prototype.forEach.call(e.length?e:[e],g)}return e};i.update=function(e){if(e){Array.prototype.forEach.call(e.length?e:[e],c)}return e}}b.exports=i});
/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 */
(function(a){if(typeof define==="function"&&define.amd){define(["jquery"],a)}else{if(typeof exports==="object"){module.exports=a}else{a(jQuery)}}}(function(c){var d=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],k=("onwheel" in document||document.documentMode>=9)?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],h=Array.prototype.slice,j,b;if(c.event.fixHooks){for(var e=d.length;e;){c.event.fixHooks[d[--e]]=c.event.mouseHooks}}var f=c.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener){for(var m=k.length;m;){this.addEventListener(k[--m],l,false)}}else{this.onmousewheel=l}c.data(this,"mousewheel-line-height",f.getLineHeight(this));c.data(this,"mousewheel-page-height",f.getPageHeight(this))},teardown:function(){if(this.removeEventListener){for(var m=k.length;m;){this.removeEventListener(k[--m],l,false)}}else{this.onmousewheel=null}c.removeData(this,"mousewheel-line-height");c.removeData(this,"mousewheel-page-height")},getLineHeight:function(m){var i=c(m),n=i["offsetParent" in c.fn?"offsetParent":"parent"]();if(!n.length){n=c("body")}return parseInt(n.css("fontSize"),10)||parseInt(i.css("fontSize"),10)||16},getPageHeight:function(i){return c(i).height()},settings:{adjustOldDeltas:true,normalizeOffset:true}};c.fn.extend({mousewheel:function(i){return i?this.on("mousewheel",i):this.trigger("mousewheel")},unmousewheel:function(i){return this.off("mousewheel",i)}});function l(i){var o=i||window.event,u=h.call(arguments,1),w=0,q=0,p=0,t=0,s=0,r=0;i=c.event.fix(o);i.type="mousewheel";if("detail" in o){p=o.detail*-1}if("wheelDelta" in o){p=o.wheelDelta}if("wheelDeltaY" in o){p=o.wheelDeltaY}if("wheelDeltaX" in o){q=o.wheelDeltaX*-1}if("axis" in o&&o.axis===o.HORIZONTAL_AXIS){q=p*-1;p=0}w=p===0?q:p;if("deltaY" in o){p=o.deltaY*-1;w=p}if("deltaX" in o){q=o.deltaX;if(p===0){w=q*-1}}if(p===0&&q===0){return}if(o.deltaMode===1){var v=c.data(this,"mousewheel-line-height");w*=v;p*=v;q*=v}else{if(o.deltaMode===2){var n=c.data(this,"mousewheel-page-height");w*=n;p*=n;q*=n}}t=Math.max(Math.abs(p),Math.abs(q));if(!b||t<b){b=t;if(a(o,t)){b/=40}}if(a(o,t)){w/=40;q/=40;p/=40}w=Math[w>=1?"floor":"ceil"](w/b);q=Math[q>=1?"floor":"ceil"](q/b);p=Math[p>=1?"floor":"ceil"](p/b);if(f.settings.normalizeOffset&&this.getBoundingClientRect){var m=this.getBoundingClientRect();s=i.clientX-m.left;r=i.clientY-m.top}i.deltaX=q;i.deltaY=p;i.deltaFactor=b;i.offsetX=s;i.offsetY=r;i.deltaMode=0;u.unshift(i,w,q,p);if(j){clearTimeout(j)}j=setTimeout(g,200);return(c.event.dispatch||c.event.handle).apply(this,u)}function g(){b=null}function a(m,i){return f.settings.adjustOldDeltas&&m.type==="mousewheel"&&i%120===0}}));
(function(c){var l="undefined";var d,g,q,f,b;var n,i,m,p;function j(s,v){var u=typeof s[v];return u==="function"||(!!(u=="object"&&s[v]))||u=="unknown"}function k(s,t){return typeof(s[t])!=l}function e(s,t){return !!(typeof(s[t])=="object"&&s[t])}function h(s){if(window.console&&window.console.log){window.console.log("TextInputs module for Rangy not supported in your browser. Reason: "+s)}}function o(t,u,s){if(u<0){u+=t.value.length}if(typeof s==l){s=u}if(s<0){s+=t.value.length}return{start:u,end:s}}function a(t,u,s){return{start:u,end:s,length:s-u,text:t.value.slice(u,s)}}function r(){return e(document,"body")?document.body:document.getElementsByTagName("body")[0]}c(document).ready(function(){var t=document.createElement("textarea");r().appendChild(t);if(k(t,"selectionStart")&&k(t,"selectionEnd")){d=function(w){var x=w.selectionStart,v=w.selectionEnd;return a(w,x,v)};g=function(x,v,w){var y=o(x,v,w);x.selectionStart=y.start;x.selectionEnd=y.end};p=function(w,v){if(v){w.selectionEnd=w.selectionStart}else{w.selectionStart=w.selectionEnd}}}else{if(j(t,"createTextRange")&&e(document,"selection")&&j(document.selection,"createRange")){d=function(z){var C=0,x=0,B,w,v,A;var y=document.selection.createRange();if(y&&y.parentElement()==z){v=z.value.length;B=z.value.replace(/\r\n/g,"\n");w=z.createTextRange();w.moveToBookmark(y.getBookmark());A=z.createTextRange();A.collapse(false);if(w.compareEndPoints("StartToEnd",A)>-1){C=x=v}else{C=-w.moveStart("character",-v);C+=B.slice(0,C).split("\n").length-1;if(w.compareEndPoints("EndToEnd",A)>-1){x=v}else{x=-w.moveEnd("character",-v);x+=B.slice(0,x).split("\n").length-1}}}return a(z,C,x)};var u=function(v,w){return w-(v.value.slice(0,w).split("\r\n").length-1)};g=function(z,v,y){var A=o(z,v,y);var x=z.createTextRange();var w=u(z,A.start);x.collapse(true);if(A.start==A.end){x.move("character",w)}else{x.moveEnd("character",u(z,A.end));x.moveStart("character",w)}x.select()};p=function(x,w){var v=document.selection.createRange();v.collapse(w);v.select()}}else{r().removeChild(t);h("No means of finding text input caret position");return}}r().removeChild(t);f=function(w,z,v,x){var y;if(z!=v){y=w.value;w.value=y.slice(0,z)+y.slice(v)}if(x){g(w,z,z)}};q=function(v){var w=d(v);f(v,w.start,w.end,true)};m=function(v){var w=d(v),x;if(w.start!=w.end){x=v.value;v.value=x.slice(0,w.start)+x.slice(w.end)}g(v,w.start,w.start);return w.text};b=function(w,z,v,x){var y=w.value,A;w.value=y.slice(0,v)+z+y.slice(v);if(x){A=v+z.length;g(w,A,A)}};n=function(v,y){var w=d(v),x=v.value;v.value=x.slice(0,w.start)+y+x.slice(w.end);var z=w.start+y.length;g(v,z,z)};i=function(v,y,B){var x=d(v),A=v.value;v.value=A.slice(0,x.start)+y+x.text+B+A.slice(x.end);var z=x.start+y.length;var w=z+x.length;g(v,z,w)};function s(v,w){return function(){var z=this.jquery?this[0]:this;var A=z.nodeName.toLowerCase();if(z.nodeType==1&&(A=="textarea"||(A=="input"&&z.type=="text"))){var y=[z].concat(Array.prototype.slice.call(arguments));var x=v.apply(this,y);if(!w){return x}}if(w){return this}}}c.fn.extend({getSelection:s(d,false),setSelection:s(g,true),collapseSelection:s(p,true),deleteSelectedText:s(q,true),deleteText:s(f,true),extractSelectedText:s(m,false),insertText:s(b,true),replaceSelectedText:s(n,true),surroundSelectedText:s(i,true)})})})(jQuery);
/*!
 * jQuery UI Touch Punch 1.0.8 as modified by RWAP Software
 * based on original touchpunch v0.2.3 which has not been updated since 2014
 *
 * Updates by RWAP Software to take account of various suggested changes on the original code issues
 *
 * Original: https://github.com/furf/jquery-ui-touch-punch
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Fork: https://github.com/RWAP/jquery-ui-touch-punch
 *
 * Depends:
 * jquery.ui.widget.js
 * jquery.ui.mouse.js
 */
(function(a){if(typeof define==="function"&&define.amd){define(["jquery","jquery.ui"],a)}else{a(jQuery)}}(function(c){c.support.mspointer=window.navigator.msPointerEnabled;c.support.touch=("ontouchstart" in document||"ontouchstart" in window||window.TouchEvent||(window.DocumentTouch&&document instanceof DocumentTouch)||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0);if((!c.support.touch&&!c.support.mspointer)||!c.ui.mouse){return}var e=c.ui.mouse.prototype,g=e._mouseInit,d=e._mouseDestroy,b;function a(h){return{x:h.originalEvent.changedTouches[0].pageX,y:h.originalEvent.changedTouches[0].pageY}}function f(i,j){if(i.originalEvent.touches.length>1){return}if(i.cancelable){i.preventDefault()}var k=i.originalEvent.changedTouches[0],h=document.createEvent("MouseEvents");h.initMouseEvent(j,true,true,window,1,k.screenX,k.screenY,k.clientX,k.clientY,false,false,false,false,0,null);i.target.dispatchEvent(h)}e._touchStart=function(i){var h=this;this._startedMove=i.timeStamp;h._startPos=a(i);if(b||!h._mouseCapture(i.originalEvent.changedTouches[0])){return}b=true;h._touchMoved=false;f(i,"mouseover");f(i,"mousemove");f(i,"mousedown")};e._touchMove=function(h){if(!b){return}this._touchMoved=true;f(h,"mousemove")};e._touchEnd=function(j){if(!b){return}f(j,"mouseup");f(j,"mouseout");var h=j.timeStamp-this._startedMove;if(!this._touchMoved||h<500){f(j,"click")}else{var i=a(j);if((Math.abs(i.x-this._startPos.x)<10)&&(Math.abs(i.y-this._startPos.y)<10)){if(!this._touchMoved||j.originalEvent.changedTouches[0].touchType==="stylus"){f(j,"click")}}}this._touchMoved=false;b=false};e._mouseInit=function(){var h=this;if(c.support.mspointer){h.element[0].style.msTouchAction="none"}h.element.on({touchstart:c.proxy(h,"_touchStart"),touchmove:c.proxy(h,"_touchMove"),touchend:c.proxy(h,"_touchEnd")});g.call(h)};e._mouseDestroy=function(){var h=this;h.element.off({touchstart:c.proxy(h,"_touchStart"),touchmove:c.proxy(h,"_touchMove"),touchend:c.proxy(h,"_touchEnd")});d.call(h)}}));
(function(){var a=$.datepicker._gotoToday;$.datepicker._gotoToday=function(d){var c=$(d),b=this._getInst(c[0]);a.call(this,d);this._selectDate(d,this._formatDate(b,b.selectedDay,b.drawMonth,b.drawYear))};$.datepicker._attachHandlers=function(c){var b=this._get(c,"stepMonths"),d="#"+c.id.replace(/\\\\/g,"\\");c.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){$.datepicker._adjustDate(d,-b,"M");$.datepicker._updateDatePickerPosition(c)},next:function(){$.datepicker._adjustDate(d,+b,"M");$.datepicker._updateDatePickerPosition(c)},hide:function(){$.datepicker._hideDatepicker()},today:function(){$.datepicker._gotoToday(d);$.datepicker._updateDatePickerPosition(c)},selectDay:function(){$.datepicker._selectDay(d,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this);$.datepicker._updateDatePickerPosition(c);return false},selectMonth:function(){$.datepicker._selectMonthYear(d,this,"M");$.datepicker._updateDatePickerPosition(c);return false},selectYear:function(){$.datepicker._selectMonthYear(d,this,"Y");$.datepicker._updateDatePickerPosition(c);return false}};$(this).on(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})};$.datepicker._updateDatePickerPosition=function(d){if(d.inline){return}var b=d.input[0];if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(b);$.datepicker._pos[1]+=b.offsetHeight}var f={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;var e=false;$(b).parents().each(function(){e|=$(this).css("position")==="fixed";return !e});var c=$.datepicker._checkOffset(d,f,e);d.dpDiv.css({top:c.top+"px"})};$.datepicker._generateMonthYearHeader=function(f,d,n,h,l,o,j,b){var s,c,t,q,g,p,m,i,e=this._get(f,"changeMonth"),u=this._get(f,"changeYear"),v=this._get(f,"showMonthAfterYear"),k="<div class='ui-datepicker-title'>",r="";if(o||!e){r+="<span class='ui-datepicker-month' aria-label='select month'>"+j[d]+"</span>"}else{s=(h&&h.getFullYear()===n);c=(l&&l.getFullYear()===n);r+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change' aria-label='select month'>";for(t=0;t<12;t++){if((!s||t>=h.getMonth())&&(!c||t<=l.getMonth())){r+="<option value='"+t+"'"+(t===d?" selected='selected'":"")+">"+b[t]+"</option>"}}r+="</select>"}if(!v){k+=r+(o||!(e&&u)?"&#xa0;":"")}if(!f.yearshtml){f.yearshtml="";if(o||!u){k+="<span class='ui-datepicker-year' aria-label='select year'>"+n+"</span>"}else{q=this._get(f,"yearRange").split(":");g=new Date().getFullYear();p=function(x){var w=(x.match(/c[+\-].*/)?n+parseInt(x.substring(1),10):(x.match(/[+\-].*/)?g+parseInt(x,10):parseInt(x,10)));return(isNaN(w)?g:w)};m=p(q[0]);i=Math.max(m,p(q[1]||""));m=(h?Math.max(m,h.getFullYear()):m);i=(l?Math.min(i,l.getFullYear()):i);f.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change' aria-label='select year'>";for(;m<=i;m++){f.yearshtml+="<option value='"+m+"'"+(m===n?" selected='selected'":"")+">"+m+"</option>"}f.yearshtml+="</select>";k+=f.yearshtml;f.yearshtml=null}}k+=this._get(f,"yearSuffix");if(v){k+=(o||!(e&&u)?"&#xa0;":"")+r}k+="</div>";return k};$.datepicker._updateDatepicker=function(c){var b=c.input[0];if($.datepicker._curInst&&$.datepicker._curInst!==c&&$.datepicker._datepickerShowing&&$.datepicker._lastInput!==b){return}if(typeof(c.stay_open)!=="boolean"||c.stay_open===false){var d=this;setTimeout(function(){d._base_updateDatepicker(c);var e=d._get(c,"timepicker");if(e){e._addTimePicker(c)}d._updateDatePickerPosition(c)},0)}};$.datepicker._base_disableDatepicker=$.datepicker._disableDatepicker;$.datepicker._disableDatepicker=function(b){setTimeout(function(){$.datepicker._base_disableDatepicker(b)},0)}})();(function(){$.fn.extend({focus:(function(a){return function(b,c){return typeof b==="number"?this.each(function(){var d=this;setTimeout(function(){$(d).trigger("focus");if(c){c.call(d)}},b)}):a.apply(this,arguments)}})($.fn.focus),disableSelection:(function(){var a="onselectstart" in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(a+".ui-disableSelection",function(b){b.preventDefault()})}})(),enableSelection:function(){return this.off(".ui-disableSelection")},zIndex:function(d){if(d!==undefined){return this.css("zIndex",String(d))}if(this.length){var b=$(this[0]),a,c;while(b.length&&b[0]!==document){a=b.css("position");if(a==="absolute"||a==="relative"||a==="fixed"){c=parseInt(b.css("zIndex"),10);if(!isNaN(c)&&c!==0){return c}}b=b.parent()}}return 0}})})();$.widget("ui.sortable",$.ui.sortable,{_setHandleClassName:function(){this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle");$.each(this.items,function(){(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item).addClass("ui-sortable-handle")})}});(function(){$.extend(Object.getPrototypeOf($.timepicker),{_updateDateTime:function(h){h=this.inst||h;var e=(h.currentYear>0?new Date(h.currentYear,h.currentMonth,h.currentDay):new Date(h.selectedYear,h.selectedMonth,h.selectedDay)),b=$.datepicker._daylightSavingAdjust(e),i=$.datepicker._get(h,"dateFormat"),c=$.datepicker._getFormatConfig(h),g=b!==null&&this.timeDefined;this.formattedDate=$.datepicker.formatDate(i,(b===null?new Date():b),c);var a=this.formattedDate;var j=h.lastVal;if(j===""){h.currentYear=h.selectedYear;h.currentMonth=h.selectedMonth;h.currentDay=h.selectedDay}if(this._defaults.timeOnly===true&&this._defaults.timeOnlyShowDate===false){a=this.formattedTime}else{if((this._defaults.timeOnly!==true&&(this._defaults.alwaysSetTime||g))||(this._defaults.timeOnly===true&&this._defaults.timeOnlyShowDate===true)){a+=this._defaults.separator+this.formattedTime+this._defaults.timeSuffix}}this.formattedDateTime=a;if(!this._defaults.showTimepicker){this.$input.val(this.formattedDate)}else{if(this.$altInput&&this._defaults.timeOnly===false&&this._defaults.altFieldTimeOnly===true){this.$altInput.val(this.formattedTime);this.$input.val(this.formattedDate)}else{if(this.$altInput){this.$input.val(a);var f="",k=this._defaults.altSeparator!==null?this._defaults.altSeparator:this._defaults.separator,d=this._defaults.altTimeSuffix!==null?this._defaults.altTimeSuffix:this._defaults.timeSuffix;if(!this._defaults.timeOnly){if(this._defaults.altFormat){f=$.datepicker.formatDate(this._defaults.altFormat,(b===null?new Date():b),c)}else{f=this.formattedDate}if(f){f+=k}}if(this._defaults.altTimeFormat!==null){f+=$.datepicker.formatTime(this._defaults.altTimeFormat,this,this._defaults)+d}else{f+=this.formattedTime+d}this.$altInput.val(f)}else{this.$input.val(a)}}}if(j!=a){this.$input.trigger("change")}},_addTimePicker:function(b){var a=PrimeFaces.trim((this.$altInput&&this._defaults.altFieldTimeOnly)?this.$input.val()+" "+this.$altInput.val():(b.inline?this.$input.next().val():this.$input.val()));this.timeDefined=this._parseTime(a);this._limitMinMaxDateTime(b,false);this._injectTimePicker();this._afterInject()},_controls:{slider:{create:function(b,g,e,h,c,a,d){var f=b._defaults.isRTL;return g.prop("slide",null).slider({orientation:"horizontal",value:f?h*-1:h,min:f?a*-1:c,max:f?c*-1:a,step:d,slide:function(i,j){b.control.value(b,$(this),e,f?j.value*-1:j.value);b._onTimeChange()},stop:function(i,j){b._onSelectHandler()}})},options:function(b,f,e,d,g){if(b._defaults.isRTL){if(typeof(d)==="string"){if(d==="min"||d==="max"){if(g!==undefined){return f.slider(d,g*-1)}return Math.abs(f.slider(d))}return f.slider(d)}var c=d.min,a=d.max;d.min=d.max=null;if(c!==undefined){d.max=c*-1}if(a!==undefined){d.min=a*-1}return f.slider(d)}if(typeof(d)==="string"&&g!==undefined){return f.slider(d,g)}return f.slider(d)},value:function(a,c,b,d){if(a._defaults.isRTL){if(d!==undefined){return c.slider("value",d*-1)}return Math.abs(c.slider("value"))}if(d!==undefined){return c.slider("value",d)}return c.slider("value")}},select:{create:function(g,f,k,b,d,h,c){var a='<select class="ui-timepicker-select ui-state-default ui-corner-all" data-unit="'+k+'" data-min="'+d+'" data-max="'+h+'" data-step="'+c+'" aria-label="select '+k+'">',j=g._defaults.pickerTimeFormat||g._defaults.timeFormat;for(var e=d;e<=h;e+=c){a+='<option value="'+e+'"'+(e===b?" selected":"")+">";if(k==="hour"){a+=$.datepicker.formatTime(PrimeFaces.trim(j.replace(/[^ht ]/ig,"")),{hour:e},g._defaults)}else{if(k==="millisec"||k==="microsec"||e>=10){a+=e}else{a+="0"+e.toString()}}a+="</option>"}a+="</select>";f.children("select").remove();$(a).appendTo(f).on("change",function(i){g._onTimeChange();g._onSelectHandler();g._afterInject()});return f},options:function(a,d,c,b,f){var e={},g=d.children("select");if(typeof(b)==="string"){if(f===undefined){return g.data(b)}e[b]=f}else{e=b}return a.control.create(a,d,g.data("unit"),g.val(),e.min>=0?e.min:g.data("min"),e.max||g.data("max"),e.step||g.data("step"))},value:function(a,c,b,d){var e=c.children("select");if(d!==undefined){return e.val(d)}return e.val()}}}})})();
/*!
 * jQuery Browser Plugin 0.1.0
 * https://github.com/gabceb/jquery-browser-plugin
 *
 * Original jquery-browser code Copyright 2005, 2015 jQuery Foundation, Inc. and other contributors
 * http://jquery.org/license
 *
 * Modifications Copyright 2015 Gabriel Cebrian
 * https://github.com/gabceb
 *
 * Released under the MIT license
 *
 * Date: 05-07-2015
 */
(function(a){if(typeof define==="function"&&define.amd){define(["jquery"],function(b){return a(b)})}else{if(typeof module==="object"&&typeof module.exports==="object"){module.exports=a(require("jquery"))}else{a(window.jQuery)}}}(function(b){function a(d){if(d===undefined){d=window.navigator.userAgent}d=d.toLowerCase();var j=/(edge)\/([\w.]+)/.exec(d)||/(opr)[\/]([\w.]+)/.exec(d)||/(chrome)[ \/]([\w.]+)/.exec(d)||/(iemobile)[\/]([\w.]+)/.exec(d)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(d)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(d)||/(webkit)[ \/]([\w.]+)/.exec(d)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(d)||/(msie) ([\w.]+)/.exec(d)||d.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(d)||d.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(d)||[];var i=/(ipad)/.exec(d)||/(ipod)/.exec(d)||/(windows phone)/.exec(d)||/(iphone)/.exec(d)||/(kindle)/.exec(d)||/(silk)/.exec(d)||/(android)/.exec(d)||/(win)/.exec(d)||/(mac)/.exec(d)||/(linux)/.exec(d)||/(cros)/.exec(d)||/(playbook)/.exec(d)||/(bb)/.exec(d)||/(blackberry)/.exec(d)||[];var k={},e={browser:j[5]||j[3]||j[1]||"",version:j[2]||j[4]||"0",versionNumber:j[4]||j[2]||"0",platform:i[0]||""};if(e.browser){k[e.browser]=true;k.version=e.version;k.versionNumber=parseInt(e.versionNumber,10)}if(e.platform){k[e.platform]=true}if(k.android||k.bb||k.blackberry||k.ipad||k.iphone||k.ipod||k.kindle||k.playbook||k.silk||k["windows phone"]){k.mobile=true}if(k.cros||k.mac||k.linux||k.win){k.desktop=true}if(k.chrome||k.opr||k.safari){k.webkit=true}if(k.rv||k.iemobile){var c="msie";e.browser=c;k[c]=true}if(k.edge){delete k.edge;var m="msedge";e.browser=m;k[m]=true}if(k.safari&&k.blackberry){var g="blackberry";e.browser=g;k[g]=true}if(k.safari&&k.playbook){var p="playbook";e.browser=p;k[p]=true}if(k.bb){var n="blackberry";e.browser=n;k[n]=true}if(k.opr){var h="opera";e.browser=h;k[h]=true}if(k.safari&&k.android){var f="android";e.browser=f;k[f]=true}if(k.safari&&k.kindle){var o="kindle";e.browser=o;k[o]=true}if(k.safari&&k.silk){var l="silk";e.browser=l;k[l]=true}k.name=e.browser;k.platform=e.platform;return k}window.jQBrowser=a(window.navigator.userAgent);window.jQBrowser.uaMatch=a;if(b){b.browser=window.jQBrowser}return window.jQBrowser}));
/*! js-cookie v3.0.0-rc.0 | MIT */
(function(b,a){typeof exports==="object"&&typeof module!=="undefined"?module.exports=a():typeof define==="function"&&define.amd?define(a):(b=b||self,(function(){var d=b.Cookies;var c=b.Cookies=a();c.noConflict=function(){b.Cookies=d;return c}}()))}(this,(function(){function b(h){for(var f=1;f<arguments.length;f++){var g=arguments[f];for(var e in g){h[e]=g[e]}}return h}var a={read:function(e){return e.replace(/%3B/g,";")},write:function(e){return e.replace(/;/g,"%3B")}};function d(g,e){function h(k,m,i){if(typeof document==="undefined"){return}i=b({},e,i);if(typeof i.expires==="number"){i.expires=new Date(Date.now()+i.expires*86400000)}if(i.expires){i.expires=i.expires.toUTCString()}k=a.write(k).replace(/=/g,"%3D");m=g.write(String(m),k);var l="";for(var j in i){if(!i[j]){continue}l+="; "+j;if(i[j]===true){continue}l+="="+i[j].split(";")[0]}return(document.cookie=k+"="+m+l)}function f(l){if(typeof document==="undefined"||(arguments.length&&!l)){return}var m=document.cookie?document.cookie.split("; "):[];var o={};for(var k=0;k<m.length;k++){var p=m[k].split("=");var n=p.slice(1).join("=");var j=a.read(p[0]).replace(/%3D/g,"=");o[j]=g.read(n,j);if(l===j){break}}return l?o[l]:o}return Object.create({set:h,get:f,remove:function(j,i){h(j,"",b({},i,{expires:-1}))},withAttributes:function(i){return d(this.converter,b({},this.attributes,i))},withConverter:function(i){return d(b({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(g)}})}var c=d(a,{path:"/"});return c})));
(function(a){if(a.PrimeFaces){a.PrimeFaces.debug("PrimeFaces already loaded, ignoring duplicate execution.");return}var b={escapeClientId:function(c){return"#"+c.replace(/:/g,"\\:")},onElementLoad:function(c,d){if(c.prop("complete")){d()}else{c.on("load",d)}},getWidgetById:function(e){for(var d in b.widgets){var c=b.widgets[d];if(c&&c.id===e){return c}}return null},getWidgetsByType:function(c){return $.map(this.widgets,function(e,d){return c.prototype.isPrototypeOf(e)?e:null})},addSubmitParam:function(d,f){var e=$(this.escapeClientId(d));for(var c in f){e.append('<input type="hidden" name="'+b.escapeHTML(c)+'" value="'+b.escapeHTML(f[c])+'" class="ui-submit-param"></input>')}return this},submit:function(f,e){var c=$(this.escapeClientId(f));var d;if(e){d=c.attr("target");c.attr("target",e)}c.trigger("submit");c.children("input.ui-submit-param").remove();if(e){if(d!==undefined){c.attr("target",d)}else{c.removeAttr("target")}}},abortXHRs:function(){b.ajax.Queue.abortAll()},attachBehaviors:function(d,c){$.each(c,function(f,e){d.on(f,function(g){e.call(d,g)})})},getCookie:function(c){return Cookies.get(c)},setCookie:function(d,e,c){if(location.protocol==="https:"&&b.settings.cookiesSecure){c.secure=true;if(b.settings.cookiesSameSite){c.sameSite=b.settings.cookiesSameSite}}Cookies.set(d,e,c)},deleteCookie:function(d,c){Cookies.remove(d,c)},cookiesEnabled:function(){var c=(navigator.cookieEnabled)?true:false;if(typeof navigator.cookieEnabled==="undefined"&&!c){document.cookie="testcookie";c=(document.cookie.indexOf("testcookie")!==-1)?true:false}return(c)},createStorageKey:function(f,d,e){var c=b.settings.contextPath.replace(/\//g,"-")+(e?"":b.settings.viewId.replace(/\//g,"-"))+f+"-"+d;return c.toLowerCase()},updateFilledState:function(c,d){var e=c.val();if(typeof(e)=="undefined"){return}if(e.length){c.addClass("ui-state-filled");if(d.is("span:not('.ui-float-label')")){d.addClass("ui-inputwrapper-filled")}}else{c.removeClass("ui-state-filled");d.removeClass("ui-inputwrapper-filled")}},skinInput:function(c){var d=c.parent(),e=function(){if(d.hasClass("ui-inputwrapper-focus")){d.removeClass("ui-inputwrapper-focus")}b.updateFilledState(c,d)};b.updateFilledState(c,d);c.on("mouseenter",function(){$(this).addClass("ui-state-hover")}).on("mouseleave",function(){$(this).removeClass("ui-state-hover")}).on("focus",function(){$(this).addClass("ui-state-focus");if(d.is("span:not('.ui-float-label')")){d.addClass("ui-inputwrapper-focus")}}).on("blur",function(){$(this).removeClass("ui-state-focus");if(c.hasClass("hasDatepicker")){setTimeout(function(){e()},150)}else{e()}});if(c.is(':not([type="password"])')){c.attr("role","textbox").attr("aria-readonly",c.prop("readonly"))}c.attr("aria-disabled",c.is(":disabled"));if(c.is("textarea")){c.attr("aria-multiline",true)}return this},skinButton:function(c){c.on("mouseover",function(){var e=$(this);if(!c.prop("disabled")){e.addClass("ui-state-hover")}}).on("mouseout",function(){$(this).removeClass("ui-state-active ui-state-hover")}).on("mousedown",function(){var e=$(this);if(!c.prop("disabled")){e.addClass("ui-state-active").removeClass("ui-state-hover")}}).on("mouseup",function(){$(this).removeClass("ui-state-active").addClass("ui-state-hover")}).on("focus",function(){$(this).addClass("ui-state-focus")}).on("blur",function(){$(this).removeClass("ui-state-focus ui-state-active")}).on("keydown",function(f){if(f.which===$.ui.keyCode.SPACE||f.which===$.ui.keyCode.ENTER){$(this).addClass("ui-state-active")}}).on("keyup",function(){$(this).removeClass("ui-state-active")});var d=c.attr("role");if(!d){c.attr("role","button")}c.attr("aria-disabled",c.prop("disabled"));return this},skinSelect:function(c){c.on("mouseover",function(){var d=$(this);if(!d.hasClass("ui-state-focus")){d.addClass("ui-state-hover")}}).on("mouseout",function(){$(this).removeClass("ui-state-hover")}).on("focus",function(){$(this).addClass("ui-state-focus").removeClass("ui-state-hover")}).on("blur",function(){$(this).removeClass("ui-state-focus ui-state-hover")});return this},info:function(c){if(this.logger){this.logger.info(c)}},debug:function(c){if(this.logger){this.logger.debug(c)}},warn:function(c){if(this.logger){this.logger.warn(c)}if(b.isDevelopmentProjectStage()&&a.console){console.log(c)}},error:function(c){if(this.logger){this.logger.error(c)}if(b.isDevelopmentProjectStage()&&a.console){console.error(c)}},isDevelopmentProjectStage:function(){return b.settings.projectStage==="Development"},isProductionProjectStage:function(){return b.settings.projectStage==="Production"},widgetNotAvailable:function(c){b.error("Widget for var '"+c+"' not available!")},setCaretToEnd:function(d){if(d){d.trigger("focus");var e=d.value.length;if(e>0){if(d.setSelectionRange){d.setSelectionRange(0,e)}else{if(d.createTextRange){var c=d.createTextRange();c.collapse(true);c.moveEnd("character",1);c.moveStart("character",1);c.select()}}}}},getThemeLink:function(){var c=$('link[href*="'+b.RESOURCE_IDENTIFIER+'/theme.css"]');if(c.length===0){c=$('link[href*="'+b.RESOURCE_IDENTIFIER+'=theme.css"]')}return c},getTheme:function(){var f=b.getThemeLink();if(f.length===0){return""}var e=f.attr("href"),d=e.split("&")[0],c=d.split("ln=primefaces-")[1];return c},changeTheme:function(g){if(g&&g!==""){var h=b.getThemeLink();var f=h.attr("href"),e=f.split("&")[0],d=e.split("ln=")[1],c=f.replace(d,"primefaces-"+g);h.attr("href",c)}},escapeRegExp:function(c){return this.escapeHTML(c.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1"))},escapeHTML:function(c){return String(c).replace(/[&<>"'`=\/]/g,function(d){return b.entityMap[d]})},clearSelection:function(){if(a.getSelection){if(a.getSelection().empty){a.getSelection().empty()}else{if(a.getSelection().removeAllRanges&&a.getSelection().rangeCount>0&&a.getSelection().getRangeAt(0).getClientRects().length>0){a.getSelection().removeAllRanges()}}}else{if(document.selection&&document.selection.empty){try{document.selection.empty()}catch(c){}}}},getSelection:function(){var c="";if(a.getSelection){c=a.getSelection()}else{if(document.getSelection){c=document.getSelection()}else{if(document.selection){c=document.selection.createRange().text}}}return c},hasSelection:function(){return this.getSelection().length>0},cw:function(d,e,c){this.createWidget(d,e,c)},getFacesResource:function(e,d,c){return b.resources.getFacesResource(e,d,c)},createWidget:function(d,f,c){c.widgetVar=f;if(this.widget[d]){var e=this.widgets[f];if(e&&(e.constructor===this.widget[d])){e.refresh(c)}else{this.widgets[f]=new this.widget[d](c);if(this.settings.legacyWidgetNamespace){a[f]=this.widgets[f]}}}else{b.error("Widget class '"+d+"' not found!")}},inArray:function(c,e){for(var d=0;d<c.length;d++){if(c[d]===e){return true}}return false},isNumber:function(c){return typeof c==="number"&&isFinite(c)},focus:function(e,d){var c=":not(:submit):not(:button):input:visible:enabled[name]";setTimeout(function(){if(e){var h=$(b.escapeClientId(e));if(h.is(c)){h.trigger("focus")}else{var f=h.find(c).eq(0);b.focusElement(f)}}else{if(d){var f=$(b.escapeClientId(d)).find(c).eq(0);b.focusElement(f)}else{var g=$(c),f=g.eq(0);b.focusElement(f)}}},50);b.customFocus=true},focusElement:function(d){if(d.is(":radio")){if(d.hasClass("ui-helper-hidden-accessible")){d.parent().trigger("focus")}else{var c=$(':radio[name="'+$.escapeSelector(d.attr("name"))+'"]').filter(":checked");if(c.length){c.trigger("focus")}else{d.trigger("focus")}}}else{d.trigger("focus")}},monitorDownload:function(g,c,e){if(this.cookiesEnabled()){if(g){g()}var f="primefaces.download"+b.settings.viewId.replace(/\//g,"_");if(e&&e!==""){f+="_"+e}var d=b.settings.contextPath;if(!d||d===""){d="/"}a.downloadMonitor=setInterval(function(){var h=b.getCookie(f);if(h==="true"){if(c){c()}clearInterval(a.downloadMonitor);b.setCookie(f,null,{path:d})}},1000)}},scrollTo:function(d){var c=$(b.escapeClientId(d)).offset();$("html,body").animate({scrollTop:c.top,scrollLeft:c.left},{easing:"easeInCirc"},1000)},scrollInView:function(d,g){if(g===null||g.length===0){return}var j=parseFloat(d.css("borderTopWidth"))||0,f=parseFloat(d.css("paddingTop"))||0,h=g.offset().top-d.offset().top-j-f,c=d.scrollTop(),e=d.height(),i=g.outerHeight(true);if(h<0){d.scrollTop(c+h)}else{if((h+i)>e){d.scrollTop(c+h-e+i)}}},calculateScrollbarWidth:function(){if(!this.scrollbarWidth){var c=$("<div></div>").css({width:"100px",height:"100px",overflow:"auto",position:"absolute",top:"-1000px",left:"-1000px"}).prependTo("body").append("<div></div>").find("div").css({width:"100%",height:"200px"});this.scrollbarWidth=100-c.width();c.parent().remove()}return this.scrollbarWidth},bcn:function(d,e,g){if(g){for(var c=0;c<g.length;c++){var f=g[c].call(d,e);if(f===false){if(e.preventDefault){e.preventDefault()}else{e.returnValue=false}break}}}},bcnu:function(e,f,d){if(d){for(var c=0;c<d.length;c++){var g=d[c].call(this,e,f);if(g===false){break}}}},openDialog:function(c){b.dialog.DialogHandler.openDialog(c)},closeDialog:function(c){b.dialog.DialogHandler.closeDialog(c)},showMessageInDialog:function(c){b.dialog.DialogHandler.showMessageInDialog(c)},confirm:function(c){if(c.type==="popup"&&b.confirmPopup){b.confirmPopup.showMessage(c)}else{b.dialog.DialogHandler.confirm(c)}},deferredRenders:[],addDeferredRender:function(e,c,d){this.deferredRenders.push({widget:e,container:c,callback:d})},removeDeferredRenders:function(e){for(var d=(this.deferredRenders.length-1);d>=0;d--){var c=this.deferredRenders[d];if(c.widget===e){this.deferredRenders.splice(d,1)}}},invokeDeferredRenders:function(c){var g=[];for(var f=0;f<this.deferredRenders.length;f++){var d=this.deferredRenders[f];if(d.container===c){var h=d.callback.call();if(h){g.push(d.widget)}}}for(var e=0;e<g.length;e++){this.removeDeferredRenders(g[e])}},getLocaleSettings:function(e){var c;if(e){c=b.locales[e]}else{if(this.localeSettings){return this.localeSettings}c=b.locales[b.settings.locale]}if(!c){var d=e?e:b.settings.locale;c=b.locales[d.split("_")[0]]}if(!c){c=b.locales.en_US}if(!e){this.localeSettings=c}return c},getAriaLabel:function(d){var c=this.getLocaleSettings()["aria"];return(c&&c[d])?c[d]:b.locales.en_US["aria"][d]},trim:function(c){if(!c){return""}if(typeof c==="string"||c instanceof String){return c.trim()}return c},uuid:function(){var d=[];for(var c=0;c<256;c++){d[c]=(c<16?"0":"")+(c).toString(16)}var h=Math.random()*4294967295|0;var g=Math.random()*4294967295|0;var f=Math.random()*4294967295|0;var e=Math.random()*4294967295|0;return d[h&255]+d[h>>8&255]+d[h>>16&255]+d[h>>24&255]+"-"+d[g&255]+d[g>>8&255]+"-"+d[g>>16&15|64]+d[g>>24&255]+"-"+d[f&63|128]+d[f>>8&255]+"-"+d[f>>16&255]+d[f>>24&255]+d[e&255]+d[e>>8&255]+d[e>>16&255]+d[e>>24&255]},nextZindex:function(){return String(++b.zindex)},toISOString:function(c){return new Date(c.getTime()-(c.getTimezoneOffset()*60000)).toISOString()},version:function(){var c="PrimeFaces "+b.VERSION+" (jQuery "+jQuery.fn.jquery+" / UI "+$.ui.version+")";console.log(c)},zindex:1000,animationEnabled:true,animationActive:false,customFocus:false,detachedWidgets:[],PARTIAL_REQUEST_PARAM:"javax.faces.partial.ajax",PARTIAL_UPDATE_PARAM:"javax.faces.partial.render",PARTIAL_PROCESS_PARAM:"javax.faces.partial.execute",PARTIAL_SOURCE_PARAM:"javax.faces.source",BEHAVIOR_EVENT_PARAM:"javax.faces.behavior.event",PARTIAL_EVENT_PARAM:"javax.faces.partial.event",RESET_VALUES_PARAM:"primefaces.resetvalues",IGNORE_AUTO_UPDATE_PARAM:"primefaces.ignoreautoupdate",SKIP_CHILDREN_PARAM:"primefaces.skipchildren",VIEW_STATE:"javax.faces.ViewState",CLIENT_WINDOW:"javax.faces.ClientWindow",VIEW_ROOT:"javax.faces.ViewRoot",CLIENT_ID_DATA:"primefaces.clientid",RESOURCE_IDENTIFIER:"javax.faces.resource",VERSION:"11.0.0"};b.settings={};b.util={};b.widgets={};b.locales={en_US:{closeText:"Close",prevText:"Previous",nextText:"Next",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["S","M","T","W ","T","F ","S"],weekHeader:"Week",weekNumberTitle:"W",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:"",timeOnlyTitle:"Only Time",timeText:"Time",hourText:"Hour",minuteText:"Minute",secondText:"Second",millisecondText:"Millisecond",currentText:"Current Date",ampm:false,year:"Year",month:"Month",week:"Week",day:"Day",list:"Agenda",allDayText:"All Day",moreLinkText:"More...",noEventsText:"No Events",aria:{"paginator.PAGE":"Page {0}","calendar.BUTTON":"Show Calendar","datatable.sort.ASC":"activate to sort column ascending","datatable.sort.DESC":"activate to sort column descending","datatable.sort.NONE":"activate to remove sorting on column","columntoggler.CLOSE":"Close","overlaypanel.CLOSE":"Close"}}};b.locales.en=b.locales.en_US;b.entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};PF=function(d){var c=b.widgets[d];if(!c){b.widgetNotAvailable(d)}return c};a.PrimeFaces=b})(window);
if(!PrimeFaces.env){PrimeFaces.env={mobile:false,touch:false,ios:false,browser:null,init:function(){this.browser=$.browser;this.mobile=(this.browser.mobile)?true:false;this.touch="ontouchstart" in window||window.navigator.msMaxTouchPoints||PrimeFaces.env.mobile;this.ios=/iPhone|iPad|iPod/i.test(window.navigator.userAgent)||(/mac/i.test(window.navigator.userAgent)&&PrimeFaces.env.touch)},isIE:function(a){return(a===undefined)?this.browser.msie:(this.browser.msie&&parseInt(this.browser.version,10)===a)},isLtIE:function(a){return(this.browser.msie)?parseInt(this.browser.version,10)<a:false},isTouchable:function(a){var b=(a==undefined)||(a.touchable!=undefined?a.touchable:true);return PrimeFaces.env.touch&&b}};PrimeFaces.env.init()};
if(!PrimeFaces.ajax){PrimeFaces.ab=function(a,c){for(var b in a){if(!a.hasOwnProperty(b)){continue}if(PrimeFaces.ajax.CFG_SHORTCUTS[b]){a[PrimeFaces.ajax.CFG_SHORTCUTS[b]]=a[b];delete a[b]}}return PrimeFaces.ajax.Request.handle(a,c)};PrimeFaces.ajax={VIEW_HEAD:"javax.faces.ViewHead",VIEW_BODY:"javax.faces.ViewBody",RESOURCE:"javax.faces.Resource",CFG_SHORTCUTS:{s:"source",f:"formId",p:"process",u:"update",e:"event",a:"async",g:"global",d:"delay",t:"timeout",sc:"skipChildren",iau:"ignoreAutoUpdate",ps:"partialSubmit",psf:"partialSubmitFilter",rv:"resetValues",fp:"fragmentProcess",fu:"fragmentUpdate",pa:"params",onst:"onstart",oner:"onerror",onsu:"onsuccess",onco:"oncomplete"},Utils:{getContent:function(c){var b="";for(var a=0;a<c.childNodes.length;a++){b+=c.childNodes[a].nodeValue}return b},getPostUrl:function(a){var c=a.attr("action");var b=a.children("input[name*='javax.faces.encodedURL']");if(b.length>0){c=b.val()}return c},getPorletForms:function(a,c){var b=a.children("input[name*='javax.faces.encodedURL']");if(b.length>0){return'form[id*="'+c+'"]'}return null},updateFormStateInput:function(b,g,j){var e=PrimeFaces.trim(g);var a=null;if(j&&j.pfSettings&&j.pfSettings.portletForms){a=$(j.pfSettings.portletForms)}else{a=$("form")}var h="";if(j&&j.pfArgs&&j.pfArgs.parameterPrefix){h=j.pfArgs.parameterPrefix}for(var d=0;d<a.length;d++){var c=a.eq(d);if(c.attr("method")==="post"){var f=c.children("input[name='"+$.escapeSelector(h+b)+"']");if(f.length>0){f.val(e)}else{c.append('<input type="hidden" name="'+h+b+'" value="'+e+'" autocomplete="off"></input>')}}}},updateHead:function(d){var b=$.ajaxSetup()["cache"];$.ajaxSetup()["cache"]=true;var a=new RegExp("<head[^>]*>","gi").exec(d)[0];var c=d.indexOf(a)+a.length;$("head").html(d.substring(c,d.lastIndexOf("</head>")));$.ajaxSetup()["cache"]=b},updateBody:function(b){var c=new RegExp("<body[^>]*>","gi").exec(b)[0];var a=b.indexOf(c)+c.length;$("body").html(b.substring(a,b.lastIndexOf("</body>")))},updateElement:function(d,b,c){if(d.indexOf(PrimeFaces.VIEW_STATE)!==-1){PrimeFaces.ajax.Utils.updateFormStateInput(PrimeFaces.VIEW_STATE,b,c)}else{if(d.indexOf(PrimeFaces.CLIENT_WINDOW)!==-1){PrimeFaces.ajax.Utils.updateFormStateInput(PrimeFaces.CLIENT_WINDOW,b,c)}else{if(d===PrimeFaces.VIEW_ROOT){var a=PrimeFaces.ajax.Utils;window.PrimeFaces=null;a.updateHead(b);a.updateBody(b)}else{if(d===PrimeFaces.ajax.VIEW_HEAD){PrimeFaces.ajax.Utils.updateHead(b)}else{if(d===PrimeFaces.ajax.VIEW_BODY){PrimeFaces.ajax.Utils.updateBody(b)}else{if(d===PrimeFaces.ajax.RESOURCE){$("head").append(b)}else{if(d===$("head")[0].id){PrimeFaces.ajax.Utils.updateHead(b)}else{$(PrimeFaces.escapeClientId(d)).replaceWith(b)}}}}}}}}},Queue:{delays:{},requests:new Array(),xhrs:new Array(),offer:function(a){if(a.delay){var b=null,d=this,b=(typeof(a.source)==="string")?a.source:$(a.source).attr("id"),c=function(){return setTimeout(function(){d.requests.push(a);if(d.requests.length===1){PrimeFaces.ajax.Request.send(a)}},a.delay)};if(this.delays[b]){clearTimeout(this.delays[b].timeout);this.delays[b].timeout=c()}else{this.delays[b]={timeout:c()}}}else{this.requests.push(a);if(this.requests.length===1){PrimeFaces.ajax.Request.send(a)}}},poll:function(){if(this.isEmpty()){return null}var b=this.requests.shift(),a=this.peek();if(a){PrimeFaces.ajax.Request.send(a)}return b},peek:function(){if(this.isEmpty()){return null}return this.requests[0]},isEmpty:function(){return this.requests.length===0},addXHR:function(a){this.xhrs.push(a)},removeXHR:function(b){var a=$.inArray(b,this.xhrs);if(a>-1){this.xhrs.splice(a,1)}},abortAll:function(){this.requests=new Array();for(var a=0;a<this.xhrs.length;a++){var b=this.xhrs[a];if(b.readyState!==4){b.abort()}}this.xhrs=new Array()}},Request:{handle:function(a,b){a.ext=b;a.promise=a.promise||$.Deferred();if(PrimeFaces.settings.earlyPostParamEvaluation){a.earlyPostParams=PrimeFaces.ajax.Request.collectEarlyPostParams(a)}if(a.async){PrimeFaces.ajax.Request.send(a)}else{PrimeFaces.ajax.Queue.offer(a)}return a.promise.promise()},collectEarlyPostParams:function(b){var c;var d;if(typeof(b.source)==="string"){d=$(PrimeFaces.escapeClientId(b.source))}else{d=$(b.source)}if(d.is(":input")&&d.is(":not(:button)")){c=[];if(d.is(":checkbox")){var a=$("input[name='"+$.escapeSelector(d.attr("name"))+"']").filter(":checked").serializeArray();$.merge(c,a)}else{c.push({name:d.attr("name"),value:d.val()})}}else{c=d.serializeArray()}return c},send:function(g){PrimeFaces.debug("Initiating ajax request.");PrimeFaces.customFocus=false;var q=(g.global===true||g.global===undefined)?true:false,c=null,j=null,A=null;if(g.onstart){A=g.onstart.call(this,g)}if(g.ext&&g.ext.onstart){A=g.ext.onstart.call(this,g)}if(A===false){PrimeFaces.debug("AJAX request cancelled by onstart callback.");if(!g.async){PrimeFaces.ajax.Queue.poll()}if(g.promise){g.promise.reject({textStatus:"error",errorThrown:"AJAX request cancelled by onstart callback."})}return false}if(q){$(document).trigger("pfAjaxStart")}if(typeof(g.source)==="string"){j=g.source}else{j=$(g.source).attr("id")}if(g.formId){c=PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector(g.formId)}else{var x=$(PrimeFaces.escapeClientId(j));c=x.closest("form");if(c.length===0){c=$("form").eq(0)}}PrimeFaces.debug("Form to post "+c.attr("id")+".");var r;var e;var o=c.attr("enctype")==="multipart/form-data";if(o){r=new FormData();e=$()}var C=PrimeFaces.ajax.Utils.getPostUrl(c);var k=[];var B=PrimeFaces.ajax.Request.extractParameterNamespace(c);PrimeFaces.debug("URL to post "+C+".");PrimeFaces.ajax.Request.addParam(k,PrimeFaces.PARTIAL_REQUEST_PARAM,true,B);PrimeFaces.ajax.Request.addParam(k,PrimeFaces.PARTIAL_SOURCE_PARAM,j,B);if(g.resetValues){PrimeFaces.ajax.Request.addParam(k,PrimeFaces.RESET_VALUES_PARAM,true,B)}if(g.ignoreAutoUpdate){PrimeFaces.ajax.Request.addParam(k,PrimeFaces.IGNORE_AUTO_UPDATE_PARAM,true,B)}if(g.skipChildren===false){PrimeFaces.ajax.Request.addParam(k,PrimeFaces.SKIP_CHILDREN_PARAM,false,B)}var y=PrimeFaces.ajax.Request.resolveComponentsForAjaxCall(g,"process");if(g.fragmentProcess){y.push(g.fragmentProcess)}var b="@none";if(y.length>0){b=y.join(" ")}else{var m=PrimeFaces.ajax.Request.resolveComponentsForAjaxCall(g,"process");if(m===undefined||m.length===0){b="@all"}}if(!b.includes("@none")){PrimeFaces.ajax.Request.addParam(k,PrimeFaces.PARTIAL_PROCESS_PARAM,b,B)}var f=PrimeFaces.ajax.Request.resolveComponentsForAjaxCall(g,"update");if(g.fragmentUpdate){f.push(g.fragmentUpdate)}if(f.length>0){PrimeFaces.ajax.Request.addParam(k,PrimeFaces.PARTIAL_UPDATE_PARAM,f.join(" "),B)}if(g.event){PrimeFaces.ajax.Request.addParam(k,PrimeFaces.BEHAVIOR_EVENT_PARAM,g.event,B);var p=g.event;if(g.event==="valueChange"){p="change"}else{if(g.event==="action"){p="click"}}PrimeFaces.ajax.Request.addParam(k,PrimeFaces.PARTIAL_EVENT_PARAM,p,B)}else{PrimeFaces.ajax.Request.addParam(k,j,j,B)}if(g.params){PrimeFaces.ajax.Request.addParams(k,g.params,B)}if(g.ext&&g.ext.params){PrimeFaces.ajax.Request.addParams(k,g.ext.params,B)}if(g.partialSubmit===undefined){g.partialSubmit=PrimeFaces.settings.partialSubmit}if(g.ext&&g.ext.partialSubmit){g.partialSubmit=g.ext.partialSubmit}if(g.partialSubmit&&b.indexOf("@all")===-1){var s=false;if(b.indexOf("@none")===-1){var l=g.partialSubmitFilter||":input";for(var u=0;u<y.length;u++){var n=$(PrimeFaces.escapeClientId(y[u]));var D=null;if(n.is("form")){D=n.serializeArray();s=true;if(o){e=e.add(n)}}else{if(n.is(":input")){D=n.serializeArray();if(o){e=e.add(n)}}else{var h=n.find(l);D=h.serializeArray();if(o){e=e.add(h)}}}k=PrimeFaces.ajax.Request.arrayCompare(D,k);if(g.ext&&g.ext.partialSubmitParameterFilter){var a=g.ext.partialSubmitParameterFilter.call(this,D);$.merge(k,a)}else{$.merge(k,D)}}}if(!s){PrimeFaces.ajax.Request.addParamFromInput(k,PrimeFaces.VIEW_STATE,c,B);PrimeFaces.ajax.Request.addParamFromInput(k,PrimeFaces.CLIENT_WINDOW,c,B);PrimeFaces.ajax.Request.addParamFromInput(k,PrimeFaces.csp.NONCE_INPUT,c,B);PrimeFaces.ajax.Request.addParamFromInput(k,"dsPostWindowId",c,B);PrimeFaces.ajax.Request.addParamFromInput(k,"dspwid",c,B)}}else{$.merge(k,c.serializeArray());if(o){e=e.add(c)}}if(PrimeFaces.settings.earlyPostParamEvaluation&&g.earlyPostParams){k=PrimeFaces.ajax.Request.arrayCompare(g.earlyPostParams,k);$.merge(k,g.earlyPostParams)}if(o){var t=$();e.each(function(i,F){var E=$(F);if(E.is(':input[type="file"]')){t=t.add(E)}else{t=t.add(E.find('input[type="file"]'))}});t.each(function(E,G){for(var F=0;F<G.files.length;F++){r.append(G.id,G.files[F])}})}var v={url:C,type:"POST",cache:false,dataType:"xml",portletForms:PrimeFaces.ajax.Utils.getPorletForms(c,B),source:g.source,global:false,beforeSend:function(E,i){E.setRequestHeader("Faces-Request","partial/ajax");E.pfSettings=i;E.pfArgs={};if(q){$(document).trigger("pfAjaxSend",[E,this])}}};if(o){$.each(k,function(i,E){r.append(E.name,E.value)});v.data=r;v.enctype="multipart/form-data";v.processData=false;v.contentType=false}else{var d=$.param(k);PrimeFaces.debug("Post Data:"+d);v.data=d}var w=c.children("input[name='"+$.escapeSelector(PrimeFaces.csp.NONCE_INPUT)+"']");if(w.length>0){v.nonce=w.val()}if(g.timeout){v.timeout=g.timeout}var z=$.ajax(v).fail(function(G,E,F){if(g.promise){g.promise.reject({jqXHR:G,textStatus:E,errorThrown:F})}var i=G.getResponseHeader("Location");if(G.status===401&&i){PrimeFaces.debug("Unauthorized status received. Redirecting to "+i);window.location=i;return}if(g.onerror){g.onerror.call(this,G,E,F)}if(g.ext&&g.ext.onerror){g.ext.onerror.call(this,G,E,F)}$(document).trigger("pfAjaxError",[G,this,F]);PrimeFaces.error("Request return with error:"+E+".")}).done(function(G,i,H){PrimeFaces.debug("Response received successfully.");try{var E;if(g.promise){g.promise.resolve({document:G,textStatus:i,jqXHR:H})}if(g.onsuccess){E=g.onsuccess.call(this,G,i,H)}if(g.ext&&g.ext.onsuccess&&!E){E=g.ext.onsuccess.call(this,G,i,H)}if(q){$(document).trigger("pfAjaxSuccess",[H,this])}if(E){return}else{PrimeFaces.ajax.Response.handle(G,i,H)}}catch(F){PrimeFaces.error(F)}PrimeFaces.debug("DOM is updated.")}).always(function(E,i,F){if(g.ext&&g.ext.oncomplete){g.ext.oncomplete.call(this,F,i,F.pfArgs,E)}if(g.oncomplete){g.oncomplete.call(this,F,i,F.pfArgs,E)}if(q){$(document).trigger("pfAjaxComplete",[F,this])}PrimeFaces.debug("Response completed.");PrimeFaces.ajax.Queue.removeXHR(F);if(!g.async){PrimeFaces.ajax.Queue.poll()}});PrimeFaces.ajax.Queue.addXHR(z)},resolveExpressionsForAjaxCall:function(a,b){var c="";if(a[b]){c+=a[b]}if(a.ext&&a.ext[b]){c+=" "+a.ext[b]}return c},resolveComponentsForAjaxCall:function(a,b){var c=PrimeFaces.ajax.Request.resolveExpressionsForAjaxCall(a,b);return PrimeFaces.expressions.SearchExpressionFacade.resolveComponents(c)},addParam:function(c,a,b,d){if(d||!a.indexOf(d)===0){c.push({name:d+a,value:b})}else{c.push({name:a,value:b})}},addFormData:function(c,a,b,d){if(d||!a.indexOf(d)===0){c.append(d+a,b)}else{c.append(a,b)}},addParams:function(d,a,e){for(var b=0;b<a.length;b++){var c=a[b];if(e&&!c.name.indexOf(e)===0){c.name=e+c.name}d.push(c)}},addParamFromInput:function(f,c,d,g){var b=null,a=$.escapeSelector(c);if(g){b=d.children("input[name*='"+a+"']")}else{b=d.children("input[name='"+a+"']")}if(b&&b.length>0){var e=b.val();PrimeFaces.ajax.Request.addParam(f,c,e,g)}},addFormDataFromInput:function(f,c,d,g){var b=null,a=$.escapeSelector(c);if(g){b=d.children("input[name*='"+a+"']")}else{b=d.children("input[name='"+a+"']")}if(b&&b.length>0){var e=b.val();PrimeFaces.ajax.Request.addFormData(f,c,e,g)}},extractParameterNamespace:function(c){var a=c.children("input[name*='"+PrimeFaces.VIEW_STATE+"']");if(a&&a.length>0){var b=a[0].name;if(b.length>PrimeFaces.VIEW_STATE.length){return b.substring(0,b.indexOf(PrimeFaces.VIEW_STATE))}}return null},arrayCompare:function(b,a){$.each(b,function(d,c){a=$.grep(a,function(e,f){if(e.name===c.name){return false}return true})});return a},createFacesAjaxFormData:function(a,f,b,d,e){var c=new FormData();PrimeFaces.ajax.Request.addFormData(c,PrimeFaces.PARTIAL_REQUEST_PARAM,true,f);PrimeFaces.ajax.Request.addFormData(c,PrimeFaces.PARTIAL_SOURCE_PARAM,b,f);if(d){PrimeFaces.ajax.Request.addFormData(c,PrimeFaces.PARTIAL_PROCESS_PARAM,d,f)}if(e){PrimeFaces.ajax.Request.addFormData(c,PrimeFaces.PARTIAL_UPDATE_PARAM,e,f)}PrimeFaces.ajax.Request.addFormDataFromInput(c,PrimeFaces.VIEW_STATE,a,f);PrimeFaces.ajax.Request.addFormDataFromInput(c,PrimeFaces.CLIENT_WINDOW,a,f);PrimeFaces.ajax.Request.addFormDataFromInput(c,PrimeFaces.csp.NONCE_INPUT,a,f);PrimeFaces.ajax.Request.addFormDataFromInput(c,"dsPostWindowId",a,f);PrimeFaces.ajax.Request.addFormDataFromInput(c,"dspwid",a,f);return c}},Response:{handle:function(h,e,m,b){if(h===undefined||h===null){return}var n=h.getElementsByTagName("partial-response")[0];for(var g=0;g<n.childNodes.length;g++){var a=n.childNodes[g];switch(a.nodeName){case"redirect":PrimeFaces.ajax.ResponseProcessor.doRedirect(a);break;case"changes":var c=$(document.activeElement);var k=c.attr("id");var f;if(c.length>0&&c.is("input")&&typeof $.fn.getSelection==="function"){f=c.getSelection()}for(var d=0;d<a.childNodes.length;d++){var l=a.childNodes[d];switch(l.nodeName){case"update":PrimeFaces.ajax.ResponseProcessor.doUpdate(l,m,b);break;case"delete":PrimeFaces.ajax.ResponseProcessor.doDelete(l);break;case"insert":PrimeFaces.ajax.ResponseProcessor.doInsert(l);break;case"attributes":PrimeFaces.ajax.ResponseProcessor.doAttributes(l);break;case"eval":PrimeFaces.ajax.ResponseProcessor.doEval(l,m);break;case"extension":PrimeFaces.ajax.ResponseProcessor.doExtension(l,m);break}}PrimeFaces.ajax.Response.handleReFocus(k,f);PrimeFaces.ajax.Response.destroyDetachedWidgets();break;case"eval":PrimeFaces.ajax.ResponseProcessor.doEval(a);break;case"extension":PrimeFaces.ajax.ResponseProcessor.doExtension(a,m);break;case"error":PrimeFaces.ajax.ResponseProcessor.doError(a,m);break}}},handleReFocus:function(d,b){if(PrimeFaces.customFocus===true){PrimeFaces.customFocus=false;return}if(!d){return}var c=$(PrimeFaces.escapeClientId(d));if(c.length>0){var a=function(){if(d!==$(document.activeElement).attr("id")){c.trigger("focus");if(b){c.setSelection(b.start,b.end)}}};a();if(PrimeFaces.env.isIE()){setTimeout(function(){a()},50)}}},destroyDetachedWidgets:function(){for(var a=0;a<PrimeFaces.detachedWidgets.length;a++){var d=PrimeFaces.detachedWidgets[a];var b=PF(d);if(b){if(b.isDetached()===true){PrimeFaces.widgets[d]=null;b.destroy();try{delete b}catch(c){}}}}PrimeFaces.detachedWidgets=[]}},ResponseProcessor:{doRedirect:function(b){try{window.location.assign(b.getAttribute("url"))}catch(a){PrimeFaces.warn("Error redirecting to URL: "+b.getAttribute("url"))}},doUpdate:function(c,d,a){var e=c.getAttribute("id"),b=PrimeFaces.ajax.Utils.getContent(c);if(a&&a.widget&&a.widget.id===e){a.handle.call(a.widget,b)}else{PrimeFaces.ajax.Utils.updateElement(e,b,d)}},doEval:function(node,xhr){var textContent=node.textContent||node.innerText||node.text;var nonce;if(xhr&&xhr.pfSettings&&xhr.pfSettings.nonce){nonce=xhr.pfSettings.nonce}PrimeFaces.csp.eval(textContent,nonce)},doExtension:function(d,e){if(e){if(d.getAttribute("ln")==="primefaces"&&d.getAttribute("type")==="args"){var c=d.textContent||d.innerText||d.text;if(e.pfArgs){var b=JSON.parse(c);for(var a in b){e.pfArgs[a]=b[a]}}else{e.pfArgs=JSON.parse(c)}}}},doError:function(a,b){},doDelete:function(a){var b=a.getAttribute("id");$(PrimeFaces.escapeClientId(b)).remove()},doInsert:function(d){if(!d.childNodes){return false}for(var b=0;b<d.childNodes.length;b++){var a=d.childNodes[b];var f=a.getAttribute("id");var e=$(PrimeFaces.escapeClientId(f));var c=PrimeFaces.ajax.Utils.getContent(a);if(a.nodeName==="after"){$(c).insertAfter(e)}else{if(a.nodeName==="before"){$(c).insertBefore(e)}}}},doAttributes:function(c){if(!c.childNodes){return false}var g=c.getAttribute("id");var f=$(PrimeFaces.escapeClientId(g));for(var b=0;b<c.childNodes.length;b++){var d=c.childNodes[b];var a=d.getAttribute("name");var e=d.getAttribute("value");if(!a){return}if(!e||e===null){e=""}f.attr(a,e)}}},AjaxRequest:function(a,b){return PrimeFaces.ajax.Request.handle(a,b)}};$(window).on("unload",function(){PrimeFaces.ajax.Queue.abortAll()})};
if(!PrimeFaces.csp){PrimeFaces.csp={NONCE_INPUT:"primefaces.nonce",NONCE_VALUE:"",EVENT_REGISTRY:new Map(),init:function(d){PrimeFaces.csp.NONCE_VALUE=d;var b=document.getElementsByTagName("form");for(var c=0;c<b.length;c++){var e=b[c];var a=e.elements[PrimeFaces.csp.NONCE_INPUT];if(!a){a=document.createElement("input");a.setAttribute("name",PrimeFaces.csp.NONCE_INPUT);a.setAttribute("type","hidden");e.appendChild(a)}a.setAttribute("value",d)}},register:function(c,a,d){if(a){var e=a.substring(2,a.length),f=document.getElementById(c),b=e+"."+c;var i=function(j){var k=d.call(f,j);if(k===false&&j.cancelable){j.preventDefault()}};$(f).off(b).on(b,i);if(!PrimeFaces.isProductionProjectStage()){if(!PrimeFaces.csp.EVENT_REGISTRY.has(c)){PrimeFaces.csp.EVENT_REGISTRY.set(c,new Map())}var g=d.toString();var h=(g.indexOf("PrimeFaces.ab(")>=0)||(g.indexOf("pf.ab(")>=0)||(g.indexOf("mojarra.ab(")>=0)||(g.indexOf("jsf.ajax.request")>=0);PrimeFaces.csp.EVENT_REGISTRY.get(c).set(b,h)}}},hasRegisteredAjaxifiedEvent:function(d,c){if(PrimeFaces.isProductionProjectStage()){console.error("PrimeFaces CSP registry may not be used in JSF Production mode.");return false}if(PrimeFaces.csp.EVENT_REGISTRY.has(d)){var b=c.substring(2,c.length),a=b+"."+d;return PrimeFaces.csp.EVENT_REGISTRY.get(d).get(a)}return false},eval:function(c,a){var b={};if(a){b={nonce:a}}else{if(PrimeFaces.csp.NONCE_VALUE){b={nonce:PrimeFaces.csp.NONCE_VALUE}}}$.globalEval(c,b)},evalResult:function(js){var executeJs="var cspResult = "+js;PrimeFaces.csp.eval(executeJs);return cspResult},executeEvent:function(id,js,e){var scriptEval="var cspFunction = function(event){"+js+"}";PrimeFaces.csp.eval(scriptEval,PrimeFaces.csp.NONCE_VALUE);cspFunction.call(id,e)},clickEvent:function(){var a=$.Event("click");if(PrimeFaces.csp.NONCE_VALUE){a.preventDefault()}return a}}};
if(!PrimeFaces.expressions){PrimeFaces.expressions={};PrimeFaces.expressions.SearchExpressionFacade={resolveComponentsAsSelector:function(c){if(c instanceof $){return c}if(c instanceof HTMLElement){return $(c)}var a=PrimeFaces.expressions.SearchExpressionFacade.splitExpressions(c);var e=$();if(a){for(var b=0;b<a.length;++b){var g=PrimeFaces.trim(a[b]);if(g.length>0){if(g=="@none"||g=="@all"||g.indexOf("@obs(")==0){continue}if(g.indexOf("@")==-1){e=e.add($(document.getElementById(g)))}else{if(g.indexOf("@widgetVar(")==0){var f=g.substring(11,g.length-1);var d=PrimeFaces.widgets[f];if(d){e=e.add($(document.getElementById(d.id)))}else{PrimeFaces.widgetNotAvailable(f)}}else{if(g.indexOf("@(")==0){e=e.add($(g.substring(2,g.length-1)))}}}}}}return e},resolveComponents:function(l){var k=PrimeFaces.expressions.SearchExpressionFacade.splitExpressions(l),c=[];if(k){for(var g=0;g<k.length;++g){var m=PrimeFaces.trim(k[g]);if(m.length>0){if(m.indexOf("@")==-1||m=="@none"||m=="@all"||m.indexOf("@obs(")==0){if(!PrimeFaces.inArray(c,m)){c.push(m)}}else{if(m.indexOf("@widgetVar(")==0){var d=m.substring(11,m.length-1),h=PrimeFaces.widgets[d];if(h){if(!PrimeFaces.inArray(c,h.id)){c.push(h.id)}}else{PrimeFaces.widgetNotAvailable(d)}}else{if(m.indexOf("@(")==0){var b=$(m.substring(2,m.length-1));for(var e=0;e<b.length;e++){var f=$(b[e]),a=f.data(PrimeFaces.CLIENT_ID_DATA)||f.attr("id");if(a&&!PrimeFaces.inArray(c,a)){c.push(a)}}}}}}}}return c},splitExpressions:function(f){var e=[];var b="";var a=0;for(var d=0;d<f.length;d++){var g=f[d];if(g==="("){a++}if(g===")"){a--}if((g===" "||g===",")&&a===0){e.push(b);b=""}else{b+=g}}e.push(b);return e}}};
if(!PrimeFaces.utils){PrimeFaces.utils={resolveAppendTo:function(d,a){if(d&&d.jq[0]){var b=d.jq[0].closest(".ui-dialog");if(b&&a&&a.length){var c=$(b);if(c.css("position")==="fixed"){a.css("position","fixed")}if(!a.parent().is(document.body)){d.cfg.appendTo="@(body)";return d.cfg.appendTo}}return d.cfg.appendTo}return null},resolveDynamicOverlayContainer:function(a){return a.cfg.appendTo?PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector(a.cfg.appendTo):$(document.body)},cleanupDynamicOverlay:function(e,b,c,a){if(e.cfg.appendTo){var d=$("[id='"+c+"']");if(d.length>1){a.children("[id='"+c+"']").remove()}}},removeDynamicOverlay:function(d,b,c,a){a.children("[id='"+c+"']").not(b).remove()},appendDynamicOverlay:function(d,b,c,a){var e=b.parent();if(!e.is(a)&&!a.is(b)){PrimeFaces.utils.removeDynamicOverlay(d,b,c,a);b.appendTo(a)}},addModal:function(e,c,d){var h=e.id,g=c.css("z-index")-1;var f=e instanceof PrimeFaces.widget.ConfirmDialog?"alertdialog":"dialog";c.attr({role:f,"aria-hidden":false,"aria-modal":true,"aria-live":"polite"});PrimeFaces.utils.preventTabbing(h,g,d);if(e.cfg.blockScroll){PrimeFaces.utils.preventScrolling()}var a=h+"_modal";var b=$('<div id="'+a+'" class="ui-widget-overlay ui-dialog-mask"></div>');b.appendTo($(document.body));b.css("z-index",String(g));return b},preventTabbing:function(d,c,a){var b=$(document);b.on("focus."+d+" mousedown."+d+" mouseup."+d,function(e){if($(e.target).zIndex()<c){e.preventDefault()}});b.on("keydown."+d,function(g){var h=$(g.target);if(g.which===$.ui.keyCode.TAB){var f=a();if(f.length){var i=f.filter(":first"),e=f.filter(":last"),j=null;if(i.is(":radio")){j=f.filter('[name="'+$.escapeSelector(i.attr("name"))+'"]').filter(":checked");if(j.length>0){i=j}}if(e.is(":radio")){j=f.filter('[name="'+$.escapeSelector(e.attr("name"))+'"]').filter(":checked");if(j.length>0){e=j}}if(h.is(document.body)){i.focus(1);g.preventDefault()}else{if(g.target===e[0]&&!g.shiftKey){i.focus(1);g.preventDefault()}else{if(g.target===i[0]&&g.shiftKey){e.focus(1);g.preventDefault()}}}}}else{if(!h.is(document.body)&&(h.zIndex()<c)){g.preventDefault()}}})},removeModal:function(c,b){var d=c.id;var a=d+"_modal";if(b){b.attr({"aria-hidden":true,"aria-modal":false,"aria-live":"off"})}$(PrimeFaces.escapeClientId(a)).remove();$(document.body).children("[id='"+a+"']").remove();if(c.cfg.blockScroll){PrimeFaces.utils.enableScrolling()}PrimeFaces.utils.enableTabbing(d)},enableTabbing:function(a){$(document).off("focus."+a+" mousedown."+a+" mouseup."+a+" keydown."+a)},isModalActive:function(b){var a=b+"_modal";return $(PrimeFaces.escapeClientId(a)).length===1||$(document.body).children("[id='"+a+"']").length===1},registerHideOverlayHandler:function(e,c,d,b,a){e.addDestroyListener(function(){$(document).off(c)});$(document).off(c).on(c,function(h){if(d.is(":hidden")||d.css("visibility")==="hidden"){return}var f=$(h.target);if(b){var g=b(h);if(g){if(g.is(f)||g.has(f).length>0){return}}}a(h,f)});return{unbind:function(){$(document).off(c)}}},registerResizeHandler:function(d,a,b,c,e){d.addDestroyListener(function(){$(window).off(a)});$(window).off(a).on(a,e||null,function(f){if(b&&(b.is(":hidden")||b.css("visibility")==="hidden")){return}c(f)});return{unbind:function(){$(window).off(a)}}},registerDynamicOverlay:function(d,b,c){if(d.cfg.appendTo){var a=PrimeFaces.utils.resolveDynamicOverlayContainer(d);PrimeFaces.utils.appendDynamicOverlay(d,b,c,a);d.addDestroyListener(function(){var e=PrimeFaces.utils.resolveDynamicOverlayContainer(d);PrimeFaces.utils.removeDynamicOverlay(d,null,c,e)});d.addRefreshListener(function(){var e=PrimeFaces.utils.resolveDynamicOverlayContainer(d);PrimeFaces.utils.cleanupDynamicOverlay(d,b,c,e)})}return b},registerScrollHandler:function(c,b,a){var d=c.getJQ().scrollParent();if(d.is("body")||d.is("html")||d[0].nodeType===9){d=$(window)}c.addDestroyListener(function(){d.off(b)});d.off(b).on(b,function(f){a(f)});return{unbind:function(){d.off(b)}}},registerConnectedOverlayScrollHandler:function(f,e,c,a){var d=PrimeFaces.utils.getScrollableParents((c||f.getJQ()).get(0));for(var b=0;b<d.length;b++){var g=$(d[b]);f.addDestroyListener(function(){g.off(e)});g.off(e).on(e,function(h){a(h)})}return{unbind:function(){for(var h=0;h<d.length;h++){$(d[h]).off(e)}}}},getScrollableParents:function(g){var k=[];var l=function(j,i){return j.parentNode==null?i:l(j.parentNode,i.concat([j.parentNode]))};if(g){var m=l(g,[]);var a=/(auto|scroll)/;var f=function(j){var i=window.getComputedStyle(j,null);return a.test(i.getPropertyValue("overflow"))||a.test(i.getPropertyValue("overflowX"))||a.test(i.getPropertyValue("overflowY"))};for(var h=0;h<m.length;h++){var n=m[h];var c=n.nodeType===1&&n.dataset.scrollselectors;if(c){var o=c.split(",");for(var e=0;e<o.length;e++){var d=o[e];var b=n.querySelector(d);if(b&&f(b)){k.push(b)}}}if(n.nodeType!==9&&f(n)){k.push(n)}}}return k},unbindScrollHandler:function(b,a){var c=b.getJQ().scrollParent();if(c.is("body")||c.is("html")||c[0].nodeType===9){c=$(window)}c.off(a)},preventScrolling:function(){$(document.body).addClass("ui-overflow-hidden")},enableScrolling:function(){$(document.body).removeClass("ui-overflow-hidden")},calculateRelativeOffset:function(b){var a={left:0,top:0};var e=b.offset();var c=$(window).scrollTop();var d=$(window).scrollLeft();a.top=e.top-c;a.left=e.left-d;return a},blockEnterKey:function(c){var a=c.which,b=$.ui.keyCode;if((a===b.ENTER)){c.preventDefault()}},ignoreFilterKey:function(c){var a=c.which,b=$.ui.keyCode,d=[b.END,b.HOME,b.LEFT,b.RIGHT,b.UP,b.DOWN,b.TAB,16,17,18,91,92,93,b.ESCAPE,b.PAGE_UP,b.PAGE_DOWN,19,20,44,144,145];if(d.indexOf(a)>-1){return true}return false},excludedSwipeElements:function(){return":button:enabled, :input:enabled, a, [role='combobox'], .noSwipe"},openLink:function(c,b){var a=b.attr("href");var e;if(a&&a!=="#"){if(c.ctrlKey){e=window.open(a,"_blank")}else{var d=b.attr("target")||"_self";e=window.open(a,d)}if(e){e.focus()}}c.preventDefault()},enableInputWidget:function(b,a){if(!a){a=b}if(a.is(":disabled")){a.prop("disabled",false);b.removeClass("ui-state-disabled")}},disableInputWidget:function(b,a){if(!a){a=b}if(!a.is(":disabled")){a.prop("disabled",true);b.addClass("ui-state-disabled")}},enableButton:function(a){if(a){a.removeClass("ui-state-disabled").removeAttr("disabled")}},disableButton:function(a){if(a){a.removeClass("ui-state-hover ui-state-focus ui-state-active").addClass("ui-state-disabled").attr("disabled","disabled")}},enableAnimations:function(){$.fx.off=false;PrimeFaces.animationEnabled=true},disableAnimations:function(){$.fx.off=true;PrimeFaces.animationEnabled=false},registerCSSTransition:function(b,c){if(b&&c!=null){var a={enter:c+"-enter",enterActive:c+"-enter-active",enterDone:c+"-enter-done",exit:c+"-exit",exitActive:c+"-exit-active",exitDone:c+"-exit-done"};var d=function(f,e,g){if(f!=null&&f[e]!=null){f[e].call(g)}};return{show:function(e){b.removeClass([a.exit,a.exitActive,a.exitDone]);if(b.is(":hidden")){if(PrimeFaces.animationEnabled){PrimeFaces.animationActive=true;b.css("display","block").addClass(a.enter);d(e,"onEnter");requestAnimationFrame(function(){setTimeout(function(){b.addClass(a.enterActive)},0);b.one("transitionrun.css-transition-show",function(f){d(e,"onEntering",f)}).one("transitioncancel.css-transition-show",function(){b.removeClass([a.enter,a.enterActive,a.enterDone]);PrimeFaces.animationActive=false}).one("transitionend.css-transition-show",function(f){b.removeClass([a.enterActive,a.enter]).addClass(a.enterDone);d(e,"onEntered",f);PrimeFaces.animationActive=false})})}else{b.css("display","block");d(e,"onEnter");d(e,"onEntering");d(e,"onEntered")}}},hide:function(e){b.removeClass([a.enter,a.enterActive,a.enterDone]);if(b.is(":visible")){if(PrimeFaces.animationEnabled){PrimeFaces.animationActive=true;b.addClass(a.exit);d(e,"onExit");setTimeout(function(){b.addClass(a.exitActive)},0);b.one("transitionrun.css-transition-hide",function(f){d(e,"onExiting",f)}).one("transitioncancel.css-transition-hide",function(){b.removeClass([a.exit,a.exitActive,a.exitDone]);PrimeFaces.animationActive=false}).one("transitionend.css-transition-hide",function(f){b.css("display","none").removeClass([a.exitActive,a.exit]).addClass(a.exitDone);d(e,"onExited",f);PrimeFaces.animationActive=false})}else{d(e,"onExit");d(e,"onExiting");d(e,"onExited");b.css("display","none")}}}}}return null},countBytes:function(e){var c=0,a=e.length,b;e=String(e||"");for(b=0;b<a;b++){var d=encodeURI(e[b]).split("%").length;c+=d===1?1:d-1}return c},styleClass:function(){var b=Array.prototype.slice.call(arguments);if(b){var d=[];for(var c=0;c<b.length;c++){var f=b[c];if(!f){continue}var e=typeof f;if(e==="string"||e==="number"){d.push(f)}else{if(e==="object"){var a=Array.isArray(f)?f:Object.keys(f).map(function(g){return !!f[g]?g:null});d=a.length?d.concat(a.filter(function(g){return !!g})):d}}}return d.join(" ")}return undefined}}};
(function(){var a=false,b=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(g){var f=this.prototype;a=true;var e=new this();a=false;for(var d in g){e[d]=typeof g[d]=="function"&&typeof f[d]=="function"&&b.test(g[d])?(function(h,i){return function(){var k=this._super;this._super=f[h];var j=i.apply(this,arguments);this._super=k;return j}})(d,g[d]):g[d]}function c(){if(!a&&this.init){this.init.apply(this,arguments)}}c.prototype=e;c.prototype.constructor=c;c.extend=arguments.callee;return c}})();if(!PrimeFaces.widget){PrimeFaces.widget={};PrimeFaces.widget.BaseWidget=Class.extend({init:function(a){this.cfg=a;this.id=a.id;if(Array.isArray(this.id)){this.jqId=$.map(this.id,function(c){return PrimeFaces.escapeClientId(c)}).join(",")}else{this.jqId=PrimeFaces.escapeClientId(this.id)}this.jq=$(this.jqId);this.widgetVar=a.widgetVar;this.destroyListeners=[];this.refreshListeners=[];this.removeScriptElement(this.id);if(this.widgetVar){var b=this;this.jq.on("remove",function(){PrimeFaces.detachedWidgets.push(b.widgetVar)})}if(this.cfg.postConstruct){this.cfg.postConstruct.call(this,this)}},refresh:function(a){this.destroyListeners=[];if(this.refreshListeners){for(var b=0;b<this.refreshListeners.length;b++){var d=this.refreshListeners[b];d.call(this,this)}}this.refreshListeners=[];var c=this.init(a);if(this.cfg.postRefresh){this.cfg.postRefresh.call(this,this)}return c},destroy:function(){if(this.cfg.preDestroy){this.cfg.preDestroy.call(this,this)}PrimeFaces.debug("Destroyed detached widget: "+this.widgetVar);if(this.destroyListeners){for(var a=0;a<this.destroyListeners.length;a++){var b=this.destroyListeners[a];b.call(this,this)}}this.destroyListeners=[]},isDetached:function(){var a=document.getElementById(this.id);if(typeof(a)!=="undefined"&&a!==null){return false}return true},getJQ:function(){return this.jq},removeScriptElement:function(a){if(Array.isArray(a)){$.each(a,function(b,c){$(PrimeFaces.escapeClientId(c)+"_s").remove()})}else{$(PrimeFaces.escapeClientId(a)+"_s").remove()}},hasBehavior:function(a){if(this.cfg.behaviors){return this.cfg.behaviors[a]!=undefined}return false},callBehavior:function(b,a){if(this.hasBehavior(b)){this.cfg.behaviors[b].call(this,a)}},getBehavior:function(a){return this.cfg.behaviors?this.cfg.behaviors[a]:null},addDestroyListener:function(a){if(!this.destroyListeners){this.destroyListeners=[]}this.destroyListeners.push(a)},addRefreshListener:function(a){if(!this.refreshListeners){this.refreshListeners=[]}this.refreshListeners.push(a)},getParentForm:function(){return this.jq.closest("form")},getParentFormId:function(){if(this.cfg.formId){return this.cfg.formId}var a=this.getParentForm();if(a.length>0){this.cfg.formId=a.attr("id")}return this.cfg.formId}});PrimeFaces.widget.DynamicOverlayWidget=PrimeFaces.widget.BaseWidget.extend({init:function(a){this._super(a);PrimeFaces.utils.registerDynamicOverlay(this,this.jq,this.id)},refresh:function(a){PrimeFaces.utils.removeModal(this,this.modalOverlay);this.appendTo=null;this.modalOverlay=null;this._super(a)},destroy:function(){this._super();PrimeFaces.utils.removeModal(this);this.appendTo=null;this.modalOverlay=null},enableModality:function(a){var b=a||this.jq;this.modalOverlay=PrimeFaces.utils.addModal(this,b,$.proxy(function(){return this.getModalTabbables()},this))},disableModality:function(a){var b=a||this.jq;PrimeFaces.utils.removeModal(this,b);this.modalOverlay=null},getModalTabbables:function(){return null}});PrimeFaces.widget.DeferredWidget=PrimeFaces.widget.BaseWidget.extend({renderDeferred:function(){if(this.jq.is(":visible")){this._render();this.postRender()}else{if(this.jq[0]){var a=this.jq[0].closest(".ui-hidden-container");if(a){var c=$(a);if(c.length){var b=this;this.addDeferredRender(this.id,c,function(){return b.render()})}}}}},render:function(){if(this.jq.is(":visible")){this._render();this.postRender();return true}else{return false}},_render:function(){throw"Unsupported Operation"},postRender:function(){},destroy:function(){this._super();PrimeFaces.removeDeferredRenders(this.id)},addDeferredRender:function(b,a,d){PrimeFaces.addDeferredRender(b,a.attr("id"),d);if(a.is(":hidden")){var c=this.jq.closest(".ui-hidden-container");if(c.length){this.addDeferredRender(b,a.parent().closest(".ui-hidden-container"),d)}}}})};
if(!PrimeFaces.resources){PrimeFaces.resources={getFacesResource:function(a,i,g){if(a.indexOf("/")===0){a=a.substring(1,a.length)}var k=PrimeFaces.resources.getResourceScriptURI();var b=PrimeFaces.resources.getResourceScriptName(k);k=k.replace(b,a);var j=new RegExp("[?&]([^&=]*)ln=(.*?)(&|$)");var h="ln="+j.exec(k)[2];var d="";var f=!(k.indexOf("?"+h)>-1||k.indexOf("&"+h)>-1);if(f){d=new RegExp("[?&]([^&=]+)"+h+"($|&)").exec(k)[1]}k=k.replace(d+h,d+"ln="+i);if(g){var c=new RegExp("[?&]"+d+"v=([^&]*)").exec(k)[1];k=k.replace(d+"v="+c,d+"v="+g)}var e=window.location.protocol+"//"+window.location.host;return k.indexOf(e)>=0?k:e+k},isExtensionMapping:function(){if(!PrimeFaces.resources.IS_EXTENSION_MAPPING){var a=PrimeFaces.resources.getResourceScriptURI();var b=PrimeFaces.resources.getResourceScriptName(a);PrimeFaces.resources.IS_EXTENSION_MAPPING=a.charAt(a.indexOf(b)+b.length)==="."}return PrimeFaces.IS_EXTENSION_MAPPING},getResourceUrlExtension:function(){if(!PrimeFaces.resources.RESOURCE_URL_EXTENSION){var a=PrimeFaces.resources.getResourceScriptURI();var b=PrimeFaces.resources.getResourceScriptName(a);PrimeFaces.resources.RESOURCE_URL_EXTENSION=RegExp(b+".([^?]*)").exec(a)[1]}return PrimeFaces.resources.RESOURCE_URL_EXTENSION},getResourceScriptName:function(a){var b=new RegExp("\\/?"+PrimeFaces.RESOURCE_IDENTIFIER+"(\\/|=)(.*?)\\.js");return b.exec(a)[2]+".js"},getResourceScriptURI:function(){if(!PrimeFaces.resources.SCRIPT_URI){PrimeFaces.resources.SCRIPT_URI=$('script[src*="/'+PrimeFaces.RESOURCE_IDENTIFIER+'/"]').first().attr("src");if(!PrimeFaces.resources.SCRIPT_URI){PrimeFaces.resources.SCRIPT_URI=$('script[src*="'+PrimeFaces.RESOURCE_IDENTIFIER+'="]').first().attr("src")}}return PrimeFaces.resources.SCRIPT_URI}}};
if(!PrimeFaces.clientwindow){PrimeFaces.clientwindow={CLIENT_WINDOW_URL_PARAM:"jfwid",CLIENT_WINDOW_SESSION_STORAGE:"pf.windowId",TEMP_CLIENT_WINDOW_ID:"temp",LENGTH_CLIENT_WINDOW_ID:5,initialized:false,clientWindowId:null,initialRedirect:false,init:function(b,a){if(PrimeFaces.clientwindow.initialized===true){return}this.initialized=true;this.clientWindowId=b;this.initialRedirect=a;this.cleanupCookies();this.assertClientWindowId()},cleanupCookies:function(){var a=this.getUrlParameter(window.location.href,this.CLIENT_WINDOW_URL_PARAM);if(a){this.expireCookie("pf.initialredirect-"+a)}},assertClientWindowId:function(){var b=this.getUrlParameter(window.location.href,this.CLIENT_WINDOW_URL_PARAM);var a=sessionStorage.getItem(this.CLIENT_WINDOW_SESSION_STORAGE);if(a===null){if(this.initialRedirect&&b===this.clientWindowId){sessionStorage.setItem(this.CLIENT_WINDOW_SESSION_STORAGE,this.clientWindowId)}else{this.requestNewClientWindowId()}}else{if(a===this.TEMP_CLIENT_WINDOW_ID){sessionStorage.setItem(this.CLIENT_WINDOW_SESSION_STORAGE,this.clientWindowId)}else{if(a.length!==this.LENGTH_CLIENT_WINDOW_ID){this.requestNewClientWindowId()}else{if(a!==b||a!==this.clientWindowId){window.location=this.replaceUrlParam(window.location.href,this.CLIENT_WINDOW_URL_PARAM,a)}}}}},requestNewClientWindowId:function(){sessionStorage.setItem(this.CLIENT_WINDOW_SESSION_STORAGE,this.TEMP_CLIENT_WINDOW_ID);window.location=this.replaceUrlParam(window.location.href,this.CLIENT_WINDOW_URL_PARAM,null)},getUrlParameter:function(f,d){var b=document.createElement("a");b.href=f;var h=b.search;if(h&&h.length>0){var c=h.substring(1).split("&");for(var e=0;e<c.length;e++){var g=c[e].split("=");if(g[0]===d){return g.length>1?decodeURIComponent(g[1]):""}}}return null},replaceUrlParam:function(d,l,e){var k=document.createElement("a");k.href=d;if(!e||e.replace(/^\s+|\s+$/g,"").length===0){e=""}if(e.length===0){if(k.search.length===0||k.search.indexOf(l+"=")===-1){return k.href}}if(k.search.length===0){k.search="?"+encodeURIComponent(l)+"="+encodeURIComponent(e);return k.href}var c=k.search.substring(1).split("&");var h=[];h.push(l+"="+encodeURIComponent(e));for(var g=0;g<c.length;g++){var f=c[g];if(f.length>0){var b=f.split("=")[0];var j=f.split("=")[1];if(j&&j.replace(/^\s+|\s+$/g,"").length>0){if(b!==l){h.push(b+"="+j)}}}}k.search="?"+h.join("&");return k.href},expireCookie:function(a){PrimeFaces.setCookie(a,"true",{path:"/",expires:-10,"max-age":"0"})}}};
if(!Element.prototype.matches){Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector}if(!Element.prototype.closest){Element.prototype.closest=function(b){var a=this;do{if(a.matches(b)){return a}a=a.parentElement||a.parentNode}while(a!==null&&a.nodeType===1);return null}}if(!String.prototype.includes){String.prototype.includes=function(a,b){if(a instanceof RegExp){throw TypeError("first argument must not be a RegExp")}if(b===undefined){b=0}return this.indexOf(a,b)!==-1}}if(!String.prototype.endsWith){String.prototype.endsWith=function(b,a){if(a===undefined||a>this.length){a=this.length}return this.substring(a-b.length,a)===b}}if(!Array.prototype.includes){Object.defineProperty(Array.prototype,"includes",{value:function(c,d){if(this==null){throw new TypeError('"this" is null or not defined')}var e=Object(this);var a=e.length>>>0;if(a===0){return false}var f=d|0;var b=Math.max(f>=0?f:a-Math.abs(f),0);while(b<a){if(e[b]===c){return true}b++}return false}})}if(!("remove" in Element.prototype)){Element.prototype.remove=function(){if(this.parentNode){this.parentNode.removeChild(this)}}};
!function(){return function a(f,d,h){function g(i,m){if(!d[i]){if(!f[i]){var k="function"==typeof require&&require;if(!m&&k){return k(i,!0)}if(c){return c(i,!0)}var j=new Error("Cannot find module '"+i+"'");throw j.code="MODULE_NOT_FOUND",j}var e=d[i]={exports:{}};f[i][0].call(e.exports,function(l){return g(f[i][1][l]||l)},e,e.exports,a,f,d,h)}return d[i].exports}for(var c="function"==typeof require&&require,b=0;b<h.length;b++){g(h[b])}return g}}()({1:[function(a,c,b){a("string.prototype.replaceall").shim()},{"string.prototype.replaceall":40}],2:[function(a,c,b){},{}],3:[function(b,d,c){var g=b("get-intrinsic"),f=b("./"),a=f(g("String.prototype.indexOf"));d.exports=function(h,j){var i=g(h,!!j);return"function"==typeof i&&a(h,".prototype.")>-1?f(i):i}},{"./":4,"get-intrinsic":29}],4:[function(x,q,b){var h=x("function-bind"),g=x("get-intrinsic"),k=g("%Function.prototype.apply%"),v=g("%Function.prototype.call%"),s=g("%Reflect.apply%",!0)||h.call(v,k),d=g("%Object.getOwnPropertyDescriptor%",!0),w=g("%Object.defineProperty%",!0),j=g("%Math.max%");if(w){try{w({},"a",{value:1})}catch(x){w=null}}q.exports=function(a){var c=s(h,v,arguments);d&&w&&(d(c,"length").configurable&&w(c,"length",{value:1+j(0,a.length-(arguments.length-1))}));return c};var m=function(){return s(h,k,arguments)};w?w(q.exports,"apply",{value:m}):q.exports.apply=m},{"function-bind":28,"get-intrinsic":29}],5:[function(v,k,b){var g=v("object-keys"),f="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),j=Object.prototype.toString,q=Array.prototype.concat,m=Object.defineProperty,d=m&&function(){var a={};try{for(var c in m(a,"x",{enumerable:!1,value:a}),a){return !1}return a.x===a}catch(a){return !1}}(),s=function(a,i,c,p){var l;i in a&&("function"!=typeof(l=p)||"[object Function]"!==j.call(l)||!p())||(d?m(a,i,{configurable:!0,enumerable:!1,value:c,writable:!0}):a[i]=c)},h=function(l,o){var n=arguments.length>2?arguments[2]:{},a=g(o);f&&(a=q.call(a,Object.getOwnPropertySymbols(o)));for(var p=0;p<a.length;p+=1){s(l,a[p],o[a[p]],n[a[p]])}};h.supportsDescriptors=!!d,k.exports=h},{"object-keys":37}],6:[function(f,h,g){var l=f("get-intrinsic"),j=f("call-bind/callBound"),d=l("%TypeError%"),b=f("./IsArray"),k=l("%Reflect.apply%",!0)||j("%Function.prototype.apply%");h.exports=function(a,i){var c=arguments.length>2?arguments[2]:[];if(!b(c)){throw new d("Assertion failed: optional `argumentsList`, if provided, must be a List")}return k(a,i,c)}},{"./IsArray":11,"call-bind/callBound":3,"get-intrinsic":29}],7:[function(d,g,f){var j=d("get-intrinsic")("%TypeError%"),h=d("object-inspect"),c=d("./IsPropertyKey"),b=d("./Type");g.exports=function(a,i){if("Object"!==b(a)){throw new j("Assertion failed: Type(O) is not Object")}if(!c(i)){throw new j("Assertion failed: IsPropertyKey(P) is not true, got "+h(i))}return a[i]}},{"./IsPropertyKey":14,"./Type":18,"get-intrinsic":29,"object-inspect":35}],8:[function(d,g,f){var j=d("get-intrinsic")("%TypeError%"),h=d("./GetV"),c=d("./IsCallable"),b=d("./IsPropertyKey");g.exports=function(a,k){if(!b(k)){throw new j("Assertion failed: IsPropertyKey(P) is not true")}var i=h(a,k);if(null!=i){if(!c(i)){throw new j(k+"is not a function")}return i}}},{"./GetV":10,"./IsCallable":12,"./IsPropertyKey":14,"get-intrinsic":29}],9:[function(x,K,A){var D=x("get-intrinsic")("%TypeError%"),C=x("call-bind/callBound"),G=x("../helpers/regexTester"),O=x("../helpers/every"),M=C("String.prototype.charAt"),B=C("String.prototype.slice"),w=C("String.prototype.indexOf"),F=parseInt,J=G(/^[0-9]$/),k=x("object-inspect"),z=x("./Get"),N=x("./IsArray"),I=x("./IsInteger"),L=x("./ToObject"),H=x("./ToString"),q=x("./Type"),E=0 in [void 0],j=function(a,c,b){return"String"===q(a)||(E?!(c in b):"Undefined"===q(a))};K.exports=function(y,ab,Q,W,aa,X){if("String"!==q(y)){throw new D("Assertion failed: `matched` must be a String")}var Z=y.length;if("String"!==q(ab)){throw new D("Assertion failed: `str` must be a String")}var V=ab.length;if(!I(Q)||Q<0||Q>V){throw new D("Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got "+k(Q))}if(!N(W)||!O(W,j)){throw new D("Assertion failed: `captures` must be a List of Strings, got "+k(W))}if("String"!==q(X)){throw new D("Assertion failed: `replacement` must be a String")}var g=Q+Z,s=W.length;"Undefined"!==q(aa)&&(aa=L(aa));for(var f="",p=0;p<X.length;p+=1){var n=M(X,p),v=p+1>=X.length,u=p+2>=X.length;if("$"!==n||v){f+=M(X,p)}else{var d=M(X,p+1);if("$"===d){f+="$",p+=1}else{if("&"===d){f+=y,p+=1}else{if("`"===d){f+=0===Q?"":B(ab,0,Q-1),p+=1}else{if("'"===d){f+=g>=V?"":B(ab,g),p+=1}else{var b=u?null:M(X,p+2);if(!J(d)||"0"===d||!u&&J(b)){if(J(d)&&(u||J(b))){var Y=d+b,a=F(Y,10)-1;f+=Y<=s&&"Undefined"===q(W[a])?"":W[a],p+=2}else{if("<"===d){if("Undefined"===q(aa)){f+="$<",p+=2}else{var h=w(X,">",p);if(h>-1){var c=B(X,p+"$<".length,h),l=z(aa,c);"Undefined"!==q(l)&&(f+=H(l)),p+=("<"+c+">").length}}}else{f+="$"}}}else{var S=F(d,10);f+=S<=s&&"Undefined"===q(W[S-1])?"":W[S-1],p+=1}}}}}}}return f}},{"../helpers/every":23,"../helpers/regexTester":26,"./Get":7,"./IsArray":11,"./IsInteger":13,"./ToObject":16,"./ToString":17,"./Type":18,"call-bind/callBound":3,"get-intrinsic":29,"object-inspect":35}],10:[function(b,d,c){var g=b("get-intrinsic")("%TypeError%"),f=b("./IsPropertyKey"),a=b("./ToObject");d.exports=function(h,i){if(!f(i)){throw new g("Assertion failed: IsPropertyKey(P) is not true")}return a(h)[i]}},{"./IsPropertyKey":14,"./ToObject":16,"get-intrinsic":29}],11:[function(a,c,b){var f=a("get-intrinsic")("%Array%"),d=!f.isArray&&a("call-bind/callBound")("Object.prototype.toString");c.exports=f.isArray||function(e){return"[object Array]"===d(e)}},{"call-bind/callBound":3,"get-intrinsic":29}],12:[function(a,c,b){c.exports=a("is-callable")},{"is-callable":33}],13:[function(d,g,f){var j=d("./abs"),h=d("./floor"),c=d("../helpers/isNaN"),b=d("../helpers/isFinite");g.exports=function(a){if("number"!=typeof a||c(a)||!b(a)){return !1}var i=j(a);return h(i)===i}},{"../helpers/isFinite":24,"../helpers/isNaN":25,"./abs":19,"./floor":20}],14:[function(a,c,b){c.exports=function(d){return"string"==typeof d||"symbol"==typeof d}},{}],15:[function(a,c,b){c.exports=a("../5/CheckObjectCoercible")},{"../5/CheckObjectCoercible":21}],16:[function(a,c,b){var f=a("get-intrinsic")("%Object%"),d=a("./RequireObjectCoercible");c.exports=function(e){return d(e),f(e)}},{"./RequireObjectCoercible":15,"get-intrinsic":29}],17:[function(b,d,c){var g=b("get-intrinsic"),f=g("%String%"),a=g("%TypeError%");d.exports=function(e){if("symbol"==typeof e){throw new a("Cannot convert a Symbol value to a string")}return f(e)}},{"get-intrinsic":29}],18:[function(a,c,b){var d=a("../5/Type");c.exports=function(e){return"symbol"==typeof e?"Symbol":"bigint"==typeof e?"BigInt":d(e)}},{"../5/Type":22}],19:[function(a,c,b){var d=a("get-intrinsic")("%Math.abs%");c.exports=function(e){return d(e)}},{"get-intrinsic":29}],20:[function(a,c,b){var d=Math.floor;c.exports=function(e){return d(e)}},{}],21:[function(a,c,b){var d=a("get-intrinsic")("%TypeError%");c.exports=function(f,g){if(null==f){throw new d(g||"Cannot call method on "+f)}return f}},{"get-intrinsic":29}],22:[function(a,c,b){c.exports=function(d){return null===d?"Null":void 0===d?"Undefined":"function"==typeof d||"object"==typeof d?"Object":"number"==typeof d?"Number":"boolean"==typeof d?"Boolean":"string"==typeof d?"String":void 0}},{}],23:[function(a,c,b){c.exports=function(d,g){for(var f=0;f<d.length;f+=1){if(!g(d[f],f,d)){return !1}}return !0}},{}],24:[function(a,c,b){var d=Number.isNaN||function(e){return e!=e};c.exports=Number.isFinite||function(e){return"number"==typeof e&&!d(e)&&e!==1/0&&e!==-1/0}},{}],25:[function(a,c,b){c.exports=Number.isNaN||function(d){return d!=d}},{}],26:[function(a,c,b){var f=a("get-intrinsic")("RegExp.prototype.test"),d=a("call-bind");c.exports=function(e){return d(f,e)}},{"call-bind":4,"get-intrinsic":29}],27:[function(a,c,b){var f=Array.prototype.slice,d=Object.prototype.toString;c.exports=function(k){var n=this;if("function"!=typeof n||"[object Function]"!==d.call(n)){throw new TypeError("Function.prototype.bind called on incompatible "+n)}for(var l,j=f.call(arguments,1),g=Math.max(0,n.length-j.length),o=[],m=0;m<g;m++){o.push("$"+m)}if(l=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof l){var e=n.apply(this,j.concat(f.call(arguments)));return Object(e)===e?e:this}return n.apply(k,j.concat(f.call(arguments)))}),n.prototype){var h=function(){};h.prototype=n.prototype,l.prototype=new h,h.prototype=null}return l}},{}],28:[function(a,c,b){var d=a("./implementation");c.exports=Function.prototype.bind||d},{"./implementation":27}],29:[function(t,e,r){var n=SyntaxError,o=Function,i=TypeError,a=function(t){try{return o('"use strict"; return ('+t+").constructor;")()}catch(t){}},c=Object.getOwnPropertyDescriptor;if(c){try{c({},"")}catch(t){c=null}}var p=function(){throw new i},u=c?function(){try{return arguments.callee,p}catch(t){try{return c(arguments,"callee").get}catch(t){return p}}}():p,l=t("has-symbols")(),f=Object.getPrototypeOf||function(t){return t.__proto__},y={},s="undefined"==typeof Uint8Array?void 0:f(Uint8Array),b={"%AggregateError%":"undefined"==typeof AggregateError?void 0:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayIteratorPrototype%":l?f([][Symbol.iterator]()):void 0,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%BigInt%":"undefined"==typeof BigInt?void 0:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":y,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":l?f(f([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&l?f((new Map)[Symbol.iterator]()):void 0,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&l?f((new Set)[Symbol.iterator]()):void 0,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":l?f(""[Symbol.iterator]()):void 0,"%Symbol%":l?Symbol:void 0,"%SyntaxError%":n,"%ThrowTypeError%":u,"%TypedArray%":s,"%TypeError%":i,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?void 0:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet},g={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},d=t("function-bind"),h=t("has"),v=d.call(Function.call,Array.prototype.concat),m=d.call(Function.apply,Array.prototype.splice),S=d.call(Function.call,String.prototype.replace),j=d.call(Function.call,String.prototype.slice),A=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,O=/\\(\\)?/g,w=function(t,e){var r,o=t;if(h(g,o)&&(o="%"+(r=g[o])[0]+"%"),h(b,o)){var c=b[o];if(c===y&&(c=function t(e){var r;if("%AsyncFunction%"===e){r=a("async function () {}")}else{if("%GeneratorFunction%"===e){r=a("function* () {}")}else{if("%AsyncGeneratorFunction%"===e){r=a("async function* () {}")}else{if("%AsyncGenerator%"===e){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else{if("%AsyncIteratorPrototype%"===e){var o=t("%AsyncGenerator%");o&&(r=f(o.prototype))}}}}}return b[e]=r,r}(o)),void 0===c&&!e){throw new i("intrinsic "+t+" exists, but is not available. Please file an issue!")}return{alias:r,name:o,value:c}}throw new n("intrinsic "+t+" does not exist!")};e.exports=function(t,e){if("string"!=typeof t||0===t.length){throw new i("intrinsic name must be a non-empty string")}if(arguments.length>1&&"boolean"!=typeof e){throw new i('"allowMissing" argument must be a boolean')}var r=function(t){var e=j(t,0,1),r=j(t,-1);if("%"===e&&"%"!==r){throw new n("invalid intrinsic syntax, expected closing `%`")}if("%"===r&&"%"!==e){throw new n("invalid intrinsic syntax, expected opening `%`")}var o=[];return S(t,A,function(t,e,r,n){o[o.length]=r?S(n,O,"$1"):e||t}),o}(t),o=r.length>0?r[0]:"",a=w("%"+o+"%",e),p=a.name,u=a.value,l=!1,f=a.alias;f&&(o=f[0],m(r,v([0,1],f)));for(var y=1,s=!0;y<r.length;y+=1){var g=r[y],d=j(g,0,1),P=j(g,-1);if(('"'===d||"'"===d||"`"===d||'"'===P||"'"===P||"`"===P)&&d!==P){throw new n("property names with quotes must have matching quotes")}if("constructor"!==g&&s||(l=!0),h(b,p="%"+(o+="."+g)+"%")){u=b[p]}else{if(null!=u){if(!(g in u)){if(!e){throw new i("base intrinsic for "+t+" exists, but the property is not available.")}return}if(c&&y+1>=r.length){var x=c(u,g);u=(s=!!x)&&"get" in x&&!("originalValue" in x.get)?x.get:u[g]}else{s=h(u,g),u=u[g]}s&&!l&&(b[p]=u)}}}return u}},{"function-bind":28,has:32,"has-symbols":30}],30:[function(a,c,b){var f="undefined"!=typeof Symbol&&Symbol,d=a("./shams");c.exports=function(){return"function"==typeof f&&("function"==typeof Symbol&&("symbol"==typeof f("foo")&&("symbol"==typeof Symbol("bar")&&d())))}},{"./shams":31}],31:[function(a,c,b){c.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols){return !1}if("symbol"==typeof Symbol.iterator){return !0}var d={},g=Symbol("test"),f=Object(g);if("string"==typeof g){return !1}if("[object Symbol]"!==Object.prototype.toString.call(g)){return !1}if("[object Symbol]"!==Object.prototype.toString.call(f)){return !1}for(g in d[g]=42,d){return !1}if("function"==typeof Object.keys&&0!==Object.keys(d).length){return !1}if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(d).length){return !1}var i=Object.getOwnPropertySymbols(d);if(1!==i.length||i[0]!==g){return !1}if(!Object.prototype.propertyIsEnumerable.call(d,g)){return !1}if("function"==typeof Object.getOwnPropertyDescriptor){var h=Object.getOwnPropertyDescriptor(d,g);if(42!==h.value||!0!==h.enumerable){return !1}}return !0}},{}],32:[function(a,c,b){var d=a("function-bind");c.exports=d.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":28}],33:[function(x,q,b){var h,g,k=Function.prototype.toString,v="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof v&&"function"==typeof Object.defineProperty){try{h=Object.defineProperty({},"length",{get:function(){throw g}}),g={},v(function(){throw 42},null,h)}catch(x){x!==g&&(v=null)}}else{v=null}var s=/^\s*class\b/,d=function(a){try{var c=k.call(a);return s.test(c)}catch(a){return !1}},w=Object.prototype.toString,j="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,m="object"==typeof document&&void 0===document.all&&void 0!==document.all?document.all:{};q.exports=v?function(a){if(a===m){return !0}if(!a){return !1}if("function"!=typeof a&&"object"!=typeof a){return !1}if("function"==typeof a&&!a.prototype){return !0}try{v(a,null,h)}catch(a){if(a!==g){return !1}}return !d(a)}:function(a){if(a===m){return !0}if(!a){return !1}if("function"!=typeof a&&"object"!=typeof a){return !1}if("function"==typeof a&&!a.prototype){return !0}if(j){return function(e){try{return !d(e)&&(k.call(e),!0)}catch(e){return !1}}(a)}if(d(a)){return !1}var c=w.call(a);return"[object Function]"===c||"[object GeneratorFunction]"===c}},{}],34:[function(x,q,b){var h,g,k,v,s=x("call-bind/callBound"),d=x("has-symbols/shams")()&&!!Symbol.toStringTag;if(d){h=s("Object.prototype.hasOwnProperty"),g=s("RegExp.prototype.exec"),k={};var w=function(){throw k};v={toString:w,valueOf:w},"symbol"==typeof Symbol.toPrimitive&&(v[Symbol.toPrimitive]=w)}var j=s("Object.prototype.toString"),m=Object.getOwnPropertyDescriptor;q.exports=d?function(a){if(!a||"object"!=typeof a){return !1}var c=m(a,"lastIndex");if(!(c&&h(c,"value"))){return !1}try{g(a,v)}catch(a){return a===k}}:function(a){return !(!a||"object"!=typeof a&&"function"!=typeof a)&&"[object RegExp]"===j(a)}},{"call-bind/callBound":3,"has-symbols/shams":31}],35:[function(ak,az,am){var ap="function"==typeof Map&&Map.prototype,ao=Object.getOwnPropertyDescriptor&&ap?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,av=ap&&ao&&"function"==typeof ao.get?ao.get:null,aD=ap&&Map.prototype.forEach,aB="function"==typeof Set&&Set.prototype,an=Object.getOwnPropertyDescriptor&&aB?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,aj=aB&&an&&"function"==typeof an.get?an.get:null,ar=aB&&Set.prototype.forEach,ay="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,af="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,al="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,aC=Boolean.prototype.valueOf,ax=Object.prototype.toString,aA=Function.prototype.toString,aw=String.prototype.match,ai="function"==typeof BigInt?BigInt.prototype.valueOf:null,aq=Object.getOwnPropertySymbols,H="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,au="function"==typeof Symbol&&"object"==typeof Symbol.iterator,ad=Object.prototype.propertyIsEnumerable,L=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(a){return a.__proto__}:null),ah=ak("./util.inspect").custom,K=ah&&J(ah)?ah:null,ag="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function X(a,c,b){var d="double"===(b.quoteStyle||c)?'"':"'";return d+a+d}function aa(a){return String(a).replace(/"/g,"&quot;")}function Z(a){return !("[object Array]"!==z(a)||ag&&"object"==typeof a&&ag in a)}function J(a){if(au){return a&&"object"==typeof a&&a instanceof Symbol}if("symbol"==typeof a){return !0}if(!a||"object"!=typeof a||!H){return !1}try{return H.call(a),!0}catch(a){}return !1}az.exports=function ak(O,B,I,G){var P=B||{};if(at(P,"quoteStyle")&&"single"!==P.quoteStyle&&"double"!==P.quoteStyle){throw new TypeError('option "quoteStyle" must be "single" or "double"')}if(at(P,"maxStringLength")&&("number"==typeof P.maxStringLength?P.maxStringLength<0&&P.maxStringLength!==1/0:null!==P.maxStringLength)){throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`')}var F=!at(P,"customInspect")||P.customInspect;if("boolean"!=typeof F){throw new TypeError('option "customInspect", if provided, must be `true` or `false`')}if(at(P,"indent")&&null!==P.indent&&"\t"!==P.indent&&!(parseInt(P.indent,10)===P.indent&&P.indent>0)){throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`')}if(void 0===O){return"undefined"}if(null===O){return"null"}if("boolean"==typeof O){return O?"true":"false"}if("string"==typeof O){return function x(m,g){if(m.length>g.maxStringLength){var t=m.length-g.maxStringLength,p="... "+t+" more character"+(t>1?"s":"");return x(m.slice(0,g.maxStringLength),g)+p}var c=m.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,ae);return X(c,"single",g)}(O,P)}if("number"==typeof O){return 0===O?1/0/O>0?"0":"-0":String(O)}if("bigint"==typeof O){return String(O)+"n"}var N=void 0===P.depth?5:P.depth;if(void 0===I&&(I=0),I>=N&&N>0&&"object"==typeof O){return Z(O)?"[Array]":"[Object]"}var M=function(c,m){var g;if("\t"===c.indent){g="\t"}else{if(!("number"==typeof c.indent&&c.indent>0)){return null}g=Array(c.indent+1).join(" ")}return{base:g,prev:Array(m+1).join(g)}}(P,I);if(void 0===G){G=[]}else{if(Q(G,O)>=0){return"[Circular]"}}function E(n,m,g){if(m&&(G=G.slice()).push(m),g){var c={depth:P.depth};return at(P,"quoteStyle")&&(c.quoteStyle=P.quoteStyle),x(n,c,I+1,G)}return x(n,P,I+1,G)}if("function"==typeof O){var v=function(c){if(c.name){return c.name}var g=aw.call(aA.call(c),/^function\s*([\w$]+)/);if(g){return g[1]}return null}(O),h=Y(O,E);return"[Function"+(v?": "+v:" (anonymous)")+"]"+(h.length>0?" { "+h.join(", ")+" }":"")}if(J(O)){var R=au?String(O).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):H.call(O);return"object"!=typeof O||au?R:V(R)}if(function(c){if(!c||"object"!=typeof c){return !1}if("undefined"!=typeof HTMLElement&&c instanceof HTMLElement){return !0}return"string"==typeof c.nodeName&&"function"==typeof c.getAttribute}(O)){for(var y="<"+String(O.nodeName).toLowerCase(),C=O.attributes||[],j=0;j<C.length;j++){y+=" "+C[j].name+"="+X(aa(C[j].value),"double",P)}return y+=">",O.childNodes&&O.childNodes.length&&(y+="..."),y+="</"+String(O.nodeName).toLowerCase()+">"}if(Z(O)){if(0===O.length){return"[]"}var f=Y(O,E);return M&&!function(c){for(var g=0;g<c.length;g++){if(Q(c[g],"\n")>=0){return !1}}return !0}(f)?"["+q(f,M)+"]":"[ "+f.join(", ")+" ]"}if(function(c){return !("[object Error]"!==z(c)||ag&&"object"==typeof c&&ag in c)}(O)){var l=Y(O,E);return 0===l.length?"["+String(O)+"]":"{ ["+String(O)+"] "+l.join(", ")+" }"}if("object"==typeof O&&F){if(K&&"function"==typeof O[K]){return O[K]()}if("function"==typeof O.inspect){return O.inspect()}}if(function(c){if(!av||!c||"object"!=typeof c){return !1}try{av.call(c);try{aj.call(c)}catch(c){return !0}return c instanceof Map}catch(c){}return !1}(O)){var k=[];return aD.call(O,function(c,e){k.push(E(e,O,!0)+" => "+E(c,O))}),ab("Map",av.call(O),k,M)}if(function(c){if(!aj||!c||"object"!=typeof c){return !1}try{aj.call(c);try{av.call(c)}catch(c){return !0}return c instanceof Set}catch(c){}return !1}(O)){var s=[];return ar.call(O,function(c){s.push(E(c,O))}),ab("Set",aj.call(O),s,M)}if(function(c){if(!ay||!c||"object"!=typeof c){return !1}try{ay.call(c,ay);try{af.call(c,af)}catch(c){return !0}return c instanceof WeakMap}catch(c){}return !1}(O)){return ac("WeakMap")}if(function(c){if(!af||!c||"object"!=typeof c){return !1}try{af.call(c,af);try{ay.call(c,ay)}catch(c){return !0}return c instanceof WeakSet}catch(c){}return !1}(O)){return ac("WeakSet")}if(function(c){if(!al||!c||"object"!=typeof c){return !1}try{return al.call(c),!0}catch(c){}return !1}(O)){return ac("WeakRef")}if(function(c){return !("[object Number]"!==z(c)||ag&&"object"==typeof c&&ag in c)}(O)){return V(E(Number(O)))}if(function(c){if(!c||"object"!=typeof c||!ai){return !1}try{return ai.call(c),!0}catch(c){}return !1}(O)){return V(E(ai.call(O)))}if(function(c){return !("[object Boolean]"!==z(c)||ag&&"object"==typeof c&&ag in c)}(O)){return V(aC.call(O))}if(function(c){return !("[object String]"!==z(c)||ag&&"object"==typeof c&&ag in c)}(O)){return V(E(String(O)))}if(!function(c){return !("[object Date]"!==z(c)||ag&&"object"==typeof c&&ag in c)}(O)&&!function(c){return !("[object RegExp]"!==z(c)||ag&&"object"==typeof c&&ag in c)}(O)){var u=Y(O,E),d=L?L(O)===Object.prototype:O instanceof Object||O.constructor===Object,b=O instanceof Object?"":"null prototype",i=!d&&ag&&Object(O)===O&&ag in O?z(O).slice(8,-1):b?"Object":"",a=(d||"function"!=typeof O.constructor?"":O.constructor.name?O.constructor.name+" ":"")+(i||b?"["+[].concat(i||[],b||[]).join(": ")+"] ":"");return 0===u.length?a+"{}":M?a+"{"+q(u,M)+"}":a+"{ "+u.join(", ")+" }"}return String(O)};var D=Object.prototype.hasOwnProperty||function(a){return a in this};function at(a,b){return D.call(a,b)}function z(a){return ax.call(a)}function Q(a,c){if(a.indexOf){return a.indexOf(c)}for(var b=0,d=a.length;b<d;b++){if(a[b]===c){return b}}return -1}function ae(a){var c=a.charCodeAt(0),b={8:"b",9:"t",10:"n",12:"f",13:"r"}[c];return b?"\\"+b:"\\x"+(c<16?"0":"")+c.toString(16).toUpperCase()}function V(a){return"Object("+a+")"}function ac(a){return a+" { ? }"}function ab(a,c,b,d){return a+" ("+c+") {"+(d?q(b,d):b.join(", "))+"}"}function q(a,c){if(0===a.length){return""}var b="\n"+c.prev+c.base;return b+a.join(","+b)+"\n"+c.prev}function Y(s,j){var b=Z(s),g=[];if(b){g.length=s.length;for(var f=0;f<s.length;f++){g[f]=at(s,f)?j(s[f],s):""}}var h,l="function"==typeof aq?aq(s):[];if(au){h={};for(var k=0;k<l.length;k++){h["$"+l[k]]=l[k]}}for(var d in s){at(s,d)&&(b&&String(Number(d))===d&&d<s.length||au&&h["$"+d] instanceof Symbol||(/[^\w$]/.test(d)?g.push(j(d,s)+": "+j(s[d],s)):g.push(d+": "+j(s[d],s))))}if("function"==typeof aq){for(var m=0;m<l.length;m++){ad.call(s,l[m])&&g.push("["+j(l[m])+"]: "+j(s[l[m]],s))}}return g}},{"./util.inspect":2}],36:[function(A,q,b){var h;if(!Object.keys){var g=Object.prototype.hasOwnProperty,k=Object.prototype.toString,x=A("./isArguments"),v=Object.prototype.propertyIsEnumerable,d=!v.call({toString:null},"toString"),z=v.call(function(){},"prototype"),j=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],m=function(a){var c=a.constructor;return c&&c.prototype===a},w={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},B=function(){if("undefined"==typeof window){return !1}for(var a in window){try{if(!w["$"+a]&&g.call(window,a)&&null!==window[a]&&"object"==typeof window[a]){try{m(window[a])}catch(a){return !0}}}catch(a){return !0}}return !1}();h=function(F){var p=null!==F&&"object"==typeof F,a="[object Function]"===k.call(F),f=x(F),u=p&&"[object String]"===k.call(F),C=[];if(!p&&!a&&!f){throw new TypeError("Object.keys called on a non-object")}var D=z&&a;if(u&&F.length>0&&!g.call(F,0)){for(var o=0;o<F.length;++o){C.push(String(o))}}if(f&&F.length>0){for(var s=0;s<F.length;++s){C.push(String(s))}}else{for(var l in F){D&&"prototype"===l||!g.call(F,l)||C.push(String(l))}}if(d){for(var E=function(c){if("undefined"==typeof window||!B){return m(c)}try{return m(c)}catch(c){return !1}}(F),i=0;i<j.length;++i){E&&"constructor"===j[i]||!g.call(F,j[i])||C.push(j[i])}}return C}}q.exports=h},{"./isArguments":38}],37:[function(f,h,g){var l=Array.prototype.slice,j=f("./isArguments"),d=Object.keys,b=d?function(a){return d(a)}:f("./implementation"),k=Object.keys;b.shim=function(){Object.keys?function(){var a=Object.keys(arguments);return a&&a.length===arguments.length}(1,2)||(Object.keys=function(a){return j(a)?k(l.call(a)):k(a)}):Object.keys=b;return Object.keys||b},h.exports=b},{"./implementation":36,"./isArguments":38}],38:[function(a,c,b){var d=Object.prototype.toString;c.exports=function(f){var h=d.call(f),g="[object Arguments]"===h;return g||(g="[object Array]"!==h&&null!==f&&"object"==typeof f&&"number"==typeof f.length&&f.length>=0&&"[object Function]"===d.call(f.callee)),g}},{}],39:[function(z,M,B){var E=z("es-abstract/2020/Call"),D=z("es-abstract/2020/GetMethod"),I=z("es-abstract/2020/GetSubstitution"),Q=z("es-abstract/2020/IsCallable"),O=z("es-abstract/2020/IsInteger"),C=z("es-abstract/2020/RequireObjectCoercible"),x=z("es-abstract/2020/ToString"),G=z("es-abstract/2020/Type"),L=z("get-intrinsic"),q=z("call-bind/callBound"),A=z("has-symbols")(),P=z("is-regex"),K=L("%Math.max%"),N=L("%TypeError%"),J=q("Array.prototype.push"),w=q("String.prototype.slice"),F=q("String.prototype.indexOf"),k=q("String.prototype.replace");function H(b,d,c){if("String"!==G(b)||"String"!==G(d)){throw new N("Assertion failed: string and searchValue must both be Strings")}if(!O(c)||c<0){throw new N("Assertion failed: fromIndex must be a nonnegative integer")}var g=b.length;if(""===d&&c<=g){return c}var f=d.length;if(c>g){return -1}for(var a=c;a<g;a+=1){if(""===d||w(b,a,a+f)===d){return a}}return -1}M.exports=function(v,l){var a=C(this),m=P(v);if(m&&-1===F(w(v,v.source.length+2),"g")){throw new TypeError("use .replace for a non-global regex. NOTE: this may be allowed in the future.")}if(A&&Symbol.replace){if(null!=v){var j=D(v,Symbol.replace);if(void 0!==j){return E(j,v,[a,l])}}}else{if(m){return k(a,v,l)}}var n=x(a),b=x(v),i=Q(l);i||(l=x(l));for(var s=b.length,h=K(1,s),o=[],p=H(n,b,0);-1!==p;){J(o,p),p=H(n,b,p+h)}for(var S=0,u="",g=0;g<o.length;g+=1){var d;if(i){d=x(E(l,void 0,[b,o[g],n]))}else{if("String"!==G(l)){throw new N("Assertion failed: `replaceValue` should be a string at this point")}d=I(b,n,o[g],[],void 0,l)}u+=w(n,S,o[g])+d,S=o[g]+s}return S<n.length&&(u+=w(n,S)),u}},{"call-bind/callBound":3,"es-abstract/2020/Call":6,"es-abstract/2020/GetMethod":8,"es-abstract/2020/GetSubstitution":9,"es-abstract/2020/IsCallable":12,"es-abstract/2020/IsInteger":13,"es-abstract/2020/RequireObjectCoercible":15,"es-abstract/2020/ToString":17,"es-abstract/2020/Type":18,"get-intrinsic":29,"has-symbols":30,"is-regex":34}],40:[function(m,j,b){var g=m("call-bind"),f=m("define-properties"),h=m("./implementation"),l=m("./polyfill"),k=m("./shim"),d=g(h);f(d,{getPolyfill:l,implementation:h,shim:k}),j.exports=d},{"./implementation":39,"./polyfill":41,"./shim":42,"call-bind":4,"define-properties":5}],41:[function(a,c,b){var d=a("./implementation");c.exports=function(){return String.prototype.replaceAll||d}},{"./implementation":39}],42:[function(a,c,b){var f=a("define-properties"),d=a("./polyfill");c.exports=function(){var e=d();return f(String.prototype,{replaceAll:e},{replaceAll:function(){return String.prototype.replaceAll!==e}}),e}},{"./polyfill":41,"define-properties":5}]},{},[1]);
PrimeFaces.widget.AjaxStatus=PrimeFaces.widget.BaseWidget.extend({init:function(a){this._super(a);this.bind()},bind:function(){var b=$(document),a=this;b.on("pfAjaxStart",function(){var c=a.cfg.delay;if(c>0){a.timeout=setTimeout(function(){a.trigger("start",arguments)},c)}else{a.trigger("start",arguments)}}).on("pfAjaxError",function(){a.trigger("error",arguments)}).on("pfAjaxSuccess",function(){a.trigger("success",arguments)}).on("pfAjaxComplete",function(){if(a.timeout){a.deleteTimeout()}a.trigger("complete",arguments)});if(window.jsf&&jsf.ajax){jsf.ajax.addOnEvent(function(d){if(d.status==="begin"){var c=a.cfg.delay;if(c>0){a.timeout=setTimeout(function(){a.trigger("start",arguments)},c)}else{a.trigger("start",arguments)}}else{if(d.status==="complete"){}else{if(d.status==="success"){if(a.timeout){a.deleteTimeout()}a.trigger("success",arguments);a.trigger("complete",arguments)}}}});jsf.ajax.addOnError(function(c){if(a.timeout){a.deleteTimeout()}a.trigger("error",arguments);a.trigger("complete",arguments)})}},trigger:function(b,a){var c=this.cfg[b];if(c){c.apply(document,a)}if(b!=="complete"||this.jq.children().filter(this.toFacetId("complete")).length){this.jq.children().hide().filter(this.toFacetId(b)).show()}},toFacetId:function(a){return this.jqId+"_"+a},deleteTimeout:function(){clearTimeout(this.timeout);this.timeout=null}});
PrimeFaces.widget.Poll=PrimeFaces.widget.BaseWidget.extend({init:function(a){this._super(a);this.active=false;if(this.cfg.autoStart){this.start()}},refresh:function(a){this.stop();this._super(a)},destroy:function(){this._super();this.stop()},start:function(){if(!this.active){var a=this.cfg.intervalType=="millisecond"?this.cfg.frequency:(this.cfg.frequency*1000);this.timer=setInterval(this.cfg.fn,a);this.active=true}},stop:function(){if(this.active){clearInterval(this.timer);this.active=false}},isActive:function(){return this.active}});
window.org=window.org||{};org.apache=org.apache||{};org.apache.myfaces=org.apache.myfaces||{};if(!org.apache.myfaces.InputTextHelp){org.apache.myfaces.InputTextHelp=function(){};org.apache.myfaces.InputTextHelp.resetHelpValue=function(B,C){var A=document.getElementById(C);if(A.value==B){A.value="";}};org.apache.myfaces.InputTextHelp.selectText=function(B,C){var A=document.getElementById(C);if(A.value==B){A.select();}};}window.org=window.org||{};org.apache=org.apache||{};org.apache.myfaces=org.apache.myfaces||{};org.apache.myfaces.dateformat=org.apache.myfaces.dateformat||{};if(!org.apache.myfaces.dateformat.DateFormatSymbols){org.apache.myfaces.dateformat.DateFormatSymbols=function(){this.eras=new Array("BC","AD");this.months=new Array("January","February","March","April","May","June","July","August","September","October","November","December","Undecimber");this.shortMonths=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Und");this.weekdays=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");this.shortWeekdays=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");this.ampms=new Array("AM","PM");this.zoneStrings=new Array(new Array(0,"long-name","short-name"));var A=new Date();A.setYear(A.getYear()-80);this.twoDigitYearStart=A;};org.apache.myfaces.dateformat.ParserContext=function(A){this.newIndex=0;this.invalid=false;this.firstDayOfWeek=A;this.ambigousYear=false;this.ambigousWeekYear=false;this.year=0;this.month=0;this.day=1;this.dayOfWeek=0;this.hour=0;this.hourAmpm;this.min=0;this.sec=0;this.ampm=0;this.weekYear=0;this.weekOfWeekYear=0;};org.apache.myfaces.dateformat.WeekDate=function(B,A){this.year=B;this.week=A;};org.apache.myfaces.dateformat.StringBuffer=function(A){if(A==null){this.str="";}else{this.str=A;}var B=org.apache.myfaces.dateformat.StringBuffer.prototype;B.append=function(C){this.str=this.str+C;};B.toString=function(){return this.str;};};org.apache.myfaces.dateformat.SimpleDateFormatter=function(C,B,A){this._construct(C,B,A);};var proto=org.apache.myfaces.dateformat.SimpleDateFormatter.prototype;proto.MSECS_PER_SEC=1000;proto.MSECS_PER_MIN=60*proto.MSECS_PER_SEC;proto.MSECS_PER_HOUR=60*proto.MSECS_PER_MIN;proto.MSECS_PER_DAY=24*proto.MSECS_PER_HOUR;proto.MSECS_PER_WEEK=7*proto.MSECS_PER_DAY;proto.MONTH_LEN=[0,31,59,90,120,151,181,212,243,273,304,334];proto._getIsoWeekDate=function(B){var I=B.getFullYear();var F=B.getMonth()+1;var J=B.getDate();var L,K,H,G,E,D,C,N,A;if(F<=2){L=I-1;K=Math.floor(L/4)-Math.floor(L/100)+Math.floor(L/400);H=Math.floor((L-1)/4)-Math.floor((L-1)/100)+Math.floor((L-1)/400);N=K-H;E=0;D=J-1+31*(F-1);}else{L=I;K=Math.floor(L/4)-Math.floor(L/100)+Math.floor(L/400);H=Math.floor((L-1)/4)-Math.floor((L-1)/100)+Math.floor((L-1)/400);N=K-H;E=N+1;D=J+Math.floor((153*(F-3)+2)/5)+58+N;}C=(L+K)%7;G=(D+C-E)%7;A=D+3-G;if(A<0){var M=53-Math.floor((C-N)/5);return new org.apache.myfaces.dateformat.WeekDate(I-1,M);}else{if(A>(364+N)){var M=1;return new org.apache.myfaces.dateformat.WeekDate(I+1,M);}else{var M=Math.floor(A/7)+1;return new org.apache.myfaces.dateformat.WeekDate(I,M);}}};proto._isLeapYear=function(A){return((A%4==0)&&(A%100!=0))||(A%400==0);};proto._dayOfWeek=function(B,E,A){E-=2;if(E<1){E+=12;--B;}var D=Math.floor(B/100);B%=100;var C=Math.floor((26*E-2)/10)+A+B+Math.floor(B/4)+Math.floor(D/4)+(5*D);var F=C%7;return F;};proto._getWeekDate=function(D,B){var I=D.getFullYear();var G=D.getMonth()+1;var J=D.getDate();var E=this._isLeapYear(I);var K=J+this.MONTH_LEN[G-1];if(E&&(G>2)){++K;}var M=this._dayOfWeek(I,1,1);var F=B-M;if(F>3){F-=7;}else{if(F<-3){F+=7;}}var L=K-1;if(L<F){var H=this._isLeapYear(I-1);if((F==3)||((F==2)&&H)){return new org.apache.myfaces.dateformat.WeekDate(I-1,53);}return new org.apache.myfaces.dateformat.WeekDate(I-1,52);}var C=(K-1-F);var A=Math.floor(C/7)+1;if((A<53)||(F==-3)||(F==-2&&E)){return new org.apache.myfaces.dateformat.WeekDate(I,A);}else{return new org.apache.myfaces.dateformat.WeekDate(I+1,1);}};proto._getStartOfWeekYear=function(E,A){var F=new Date(E,0,1,0,0,0);var C=F.getDay();var D=A-C;var B;if(D>=4){B=7-B;}else{if(D>=0){B=D;}else{if(D>=-3){B=D;}else{B=7+D;}}}var G=F.getTime()+(B*this.MSECS_PER_DAY);return G;};proto._getDateForWeekDate=function(H,C,I,D,E,F,A){var B=this._getStartOfWeekYear(H,A);var G=(C-1)*this.MSECS_PER_WEEK;G+=(I-1)*this.MSECS_PER_DAY;G+=D*this.MSECS_PER_HOUR;G+=E*this.MSECS_PER_MIN;G+=F*this.MSECS_PER_SEC;var J=new Date();J.setTime(B+G);return J;};proto._fullYearFromDate=function(A){if(A<1900){return A+1900;}else{return A;}};proto._createDateFromContext=function(B){var A;if(B.weekOfWeekYear!=0){A=this._getDateForWeekDate(B.weekYear,B.weekOfWeekYear,B.day,B.hour,B.min,B.sec,B.firstDayOfWeek);}else{A=new Date(B.year,B.month,B.day,B.hour,B.min,B.sec);}return A;};proto._substr=function(C,D,A){var B=C.substring(D);if(B.length<=A){return B;}else{return B.substring(0,A);}};proto._parseOps=function(C,J,A,D,E){var B=new org.apache.myfaces.dateformat.ParserContext(A);var N=0;var F=E.length;for(var H=0;(H<D.length)&&(N<F);++H){var I=D[H];var M=I.substring(0,2);var G=I.substring(2);if(M=="f:"){this._parsePattern(C,J,B,G,E,N);if((B.newIndex<0)||B.invalid){break;}N=B.newIndex;}else{if(M=="q:"||M=="l:"){var K=G.length;var L=this._substr(E,N,K);if(G!=L){B.invalid=true;break;}N+=K;}}}return B;};proto._parsePattern=function(B,H,A,E,D,K){var J=E.charAt(0);var C=E.length;if(J=="y"){var I=this._parseNum(A,D,4,K);if((A.newIndex-K)<4){A.year=I;A.ambiguousYear=true;}else{A.year=I;A.ambiguousYear=false;}if(H){A.weekYear=A.year;A.ambiguousWeekYear=A.ambiguousYear;}}else{if(J=="x"){var I=this._parseNum(A,D,4,K);if((A.newIndex-K)<4){A.weekYear=I;A.ambiguousWeekYear=true;}else{A.weekYear=I;A.ambiguousWeekYear=false;}}else{if(J=="M"){if(C==3){var G=this._substr(D,K,3);var F=this._parseIndexOf(A,B.shortMonths,G);if(F!=-1){A.month=F;}}else{if(C>=4){var G=D.substring(K);var F=this._parsePrefixOf(A,B.months,G);if(F!=-1){A.month=F;}}else{A.month=this._parseNum(A,D,2,K)-1;}}}else{if(J=="d"){A.day=this._parseNum(A,D,2,K);}else{if(J=="E"){if(C<=3){var G=D.substring(K,K+3);var F=this._parseIndexOf(A,B.shortWeekdays,G);if(F!=-1){A.dayOfWeek=F;}}else{var G=D.substring(K);var F=this._parsePrefixOf(A,B.weekdays,G);if(F!=-1){A.dayOfWeek=F;}}}else{if(J=="H"){A.hour=this._parseNum(A,D,2,K);}else{if(J=="h"){A.hourAmpm=this._parseNum(A,D,2,K);}else{if(J=="m"){A.min=this._parseNum(A,D,2,K);}else{if(J=="s"){A.sec=this._parseNum(A,D,2,K);}else{if(J=="a"){A.ampm=this._parseString(A,D,K,B.ampms);}else{if(J=="w"){A.weekOfWeekYear=this._parseNum(A,D,2,K);}else{A.invalid=true;}}}}}}}}}}}};proto._parseInt=function(C){var B=0;for(var A=0;A<C.length;A++){var D=C.charAt(A);if(D<"0"||D>"9"){return -1;}B=B*10+(D-"0");}return B;};proto._parseNum=function(F,B,D,A){var C=Math.min(D,B.length-A);for(var E=C;E>0;E--){var H=B.substring(A,A+E);var G=this._parseInt(H);if(G==-1){continue;}F.newIndex=A+E;return G;}F.newIndex=-1;F.invalid=true;return -1;};proto._parseIndexOf=function(B,E,D){for(var A=0;A<E.length;++A){var C=E[A];if(D==C){B.newIndex+=C.length;return A;}}B.invalid=true;B.newIndex=-1;return -1;};proto._parsePrefixOf=function(B,E,D){for(var A=0;A<E.length;++A){var C=E[A];if(D.indexOf(C)==0){B.newIndex+=C.length;return A;}}B.invalid=true;B.newIndex=-1;return -1;};proto._parseString=function(E,C,B,A){var D=C.substr(B);return this._parsePrefixOf(E,A,D);};proto._parsePostProcess=function(C,D){if(D.ambiguousYear){D.year+=1900;var B=this._createDateFromContext(D);var A=C.twoDigitYearStart;if(B.getTime()<A.getTime()){D.year+=100;}}if(D.year<=0){D.year=new Date().getFullYear();}if(D.hourAmpm>0){if(D.ampm==1){D.hour=D.hourAmpm+12;if(D.hour==24){D.hour=0;}}else{D.hour=D.hourAmpm;}}};proto._formatOps=function(C,I,A,D,E){var B=new org.apache.myfaces.dateformat.ParserContext(A);B.year=E.getFullYear();B.month=E.getMonth();B.day=E.getDate();B.dayOfWeek=E.getDay();B.hour=E.getHours();B.min=E.getMinutes();B.sec=E.getSeconds();B.ampm=(B.hour<12)?0:1;var J=this._getWeekDate(E,A);B.weekYear=J.year;B.weekOfWeekYear=J.week;var K=new org.apache.myfaces.dateformat.StringBuffer();for(var G=0;G<D.length;++G){var H=D[G];var L=H.substring(0,2);var F=H.substring(2);if(L=="f:"){this._formatPattern(C,B,F,I,K);if(B.invalid){break;}}else{if(L=="l:"){K.append(F);}else{if(L=="q:"){K.append(F);}}}}if(B.invalid){return null;}else{return K.toString();}};proto._formatPattern=function(E,G,F,B,D){var H=F.charAt(0);var C=F.length;if(H=="y"){if(!B){this._formatNum(G.year,C<=3?2:4,true,D);}else{this._formatNum(G.weekYear,C<=3?2:4,true,D);}}else{if(H=="x"){this._formatNum(G.weekYear,C<=3?2:4,true,D);}else{if(H=="M"){if(C==3){D.append(E.shortMonths[G.month]);}else{if(C>=4){D.append(E.months[G.month]);}else{this._formatNum(G.month+1,C,false,D);}}}else{if(H=="d"){this._formatNum(G.day,C,false,D);}else{if(H=="E"){if(C<=3){D.append(E.shortWeekdays[G.dayOfWeek]);}else{D.append(E.weekdays[G.dayOfWeek]);}}else{if(H=="H"){this._formatNum(G.hour,C,false,D);}else{if(H=="h"){var A=G.hour;if(A==0){A=12;}else{if(A>12){A=A-12;}}this._formatNum(A,C,false,D);}else{if(H=="m"){this._formatNum(G.min,C,false,D);}else{if(H=="s"){this._formatNum(G.sec,C,false,D);}else{if(H=="a"){D.append(E.ampms[G.ampm]);}else{if(H=="w"){this._formatNum(G.weekOfWeekYear,C,false,D);}else{G.invalid=true;}}}}}}}}}}}};proto._formatNum=function(B,C,E,A){var D=""+B;while(D.length<C){D="0"+D;}if(E&&D.length>C){D=D.substr(D.length-C);}A.append(D);};proto._appendToArray=function(B,A){B[B.length]=A;};proto._isLetter=function(A){if((A>="a")&&(A<="z")){return true;}if((A>="A")&&(A<="Z")){return true;}return false;};proto._analysePattern=function(F){var D=0;var A=F.length;var H=0;var E=null;var G=false;var C=new Array();while(D<A){var I=F.charAt(D);var B;if(D<A-1){B=F.charAt(D+1);}else{B=0;}if(I=="'"&&H!="\\"){if(E!=null){this._appendToArray(C,E.toString());E=null;}G=!G;}else{if(G){if(E==null){E=new org.apache.myfaces.dateformat.StringBuffer("q:");}E.append(I);}else{if(I=="\\"&&H!="\\"){}else{if(E==null){if(this._isLetter(I)){E=new org.apache.myfaces.dateformat.StringBuffer("f:");}else{E=new org.apache.myfaces.dateformat.StringBuffer("l:");}}E.append(I);if(I!=B){this._appendToArray(C,E.toString());E=null;}}}}D++;H=I;}if(E!=null){this._appendToArray(C,E.toString());}return C;};proto._hasWeekPattern=function(E){var C=false;var A=false;for(var B=0;B<E.length;++B){var D=E[B];C=C||(D.indexOf("f:ww")==0);A=A||(D.indexOf("f:xx")==0);}return C&&!A;};proto._construct=function(C,B,A){if(B==null){this.symbols=new org.apache.myfaces.dateformat.DateFormatSymbols();}else{this.symbols=B;}this.ops=this._analysePattern(C);this.yearIsWeekYear=this._hasWeekPattern(this.ops);if(A!=null){this.firstDayOfWeek=A;}else{this.firstDayOfWeek=1;}};proto.setFirstDayOfWeek=function(A){this.firstDayOfWeek=A;};proto.parse=function(A){if((A==null)||(A.length==0)){return null;}var B=this._parseOps(this.symbols,this.yearIsWeekYear,this.firstDayOfWeek,this.ops,A);if(B.invalid){return null;}this._parsePostProcess(this.symbols,B);return this._createDateFromContext(B);};proto.format=function(A){return this._formatOps(this.symbols,this.yearIsWeekYear,this.firstDayOfWeek,this.ops,A);};proto.getWeekDate=function(A){return this._getWeekDate(A,this.firstDayOfWeek);};proto.getDateForWeekDate=function(A){return this._getDateForWeekDate(A.year,A.week,1,0,0,0,this.firstDayOfWeek);};}(!window.myfaces)?window.myfaces={}:null;if(!myfaces.oam){myfaces.oam=new function(){this.setHiddenInput=function(E,B,D){var C=document.forms[E];if(typeof C=="undefined"){C=document.getElementById(E);}if(typeof C.elements[B]!="undefined"&&(C.elements[B].nodeName=="INPUT"||C.elements[B].nodeName=="input")){C.elements[B].value=D;}else{var A=document.createElement("input");A.setAttribute("type","hidden");A.setAttribute("id",B);A.setAttribute("name",B);A.setAttribute("value",D);C.appendChild(A);}};this.clearHiddenInput=function(E,A,D){var C=document.forms[E];if(typeof C=="undefined"){C=document.getElementById(E);}var B=C.elements[A];if(typeof B!="undefined"){C.removeChild(B);}};this.submitForm=function(L,K,I,C){var F="clearFormHiddenParams_"+L.replace(/-/g,"$:").replace(/:/g,"_");if(typeof window[F]=="function"){window[F](L);}var A=document.forms[L];if(typeof A=="undefined"){A=document.getElementById(L);}if(myfaces.core.config.autoScroll&&typeof window.getScrolling!="undefined"){myfaces.oam.setHiddenInput(L,"autoScroll",getScrolling());}if(myfaces.core.config.ieAutoSave){var E=navigator.userAgent.toLowerCase();var J=navigator.appVersion;if(E.indexOf("msie")!=-1){if(!(E.indexOf("ppc")!=-1&&E.indexOf("windows ce")!=-1&&J>=4)){window.external.AutoCompleteSaveForm(A);}}}var H=A.target;if(I!=null){A.target=I;}if((typeof C!="undefined")&&C!=null){for(var D=0,B;(B=C[D]);D++){myfaces.oam.setHiddenInput(L,B[0],B[1]);}}myfaces.oam.setHiddenInput(L,L+":"+"_idcl",K);if(A.onsubmit){var M=A.onsubmit();if((typeof M=="undefined")||M){try{A.submit();}catch(G){}}}else{try{A.submit();}catch(G){}}A.target=H;if((typeof C!="undefined")&&C!=null){for(var D=0,B;(B=C[D]);D++){myfaces.oam.clearHiddenInput(L,B[0],B[1]);}}myfaces.oam.clearHiddenInput(L,L+":"+"_idcl",K);return false;};};}(!myfaces.core)?myfaces.core={}:null;(!myfaces.core.config)?myfaces.core.config={}:null;
/**
 * Helper to 'declare' packages.
 * @param packageName
 */
function use_package(packageName) {
	if (typeof (packageName) != "string") {
		throw new Error("Can only declare packages in string format!")
	}
	var packageParts = packageName.split(".")
	    currentPackage = window,
	    i = 0,
	    len = packageParts.length;
	for (; i < len; i++) {
		if (!currentPackage[packageParts[i]]) {
			currentPackage[packageParts[i]] = {};
		}
		currentPackage = currentPackage[packageParts[i]];
	}
}
use_package("de.his.common");

/**
 * Some common utils.
 */
de.his.common.Util = new function() {
    /**
     * Translates exceptions to a string.
     */
    this.toExceptionMessage = function(e) {
        if (typeof e === "string") {
            return e;
        }
        return e.message;
    };

    /**
     * Converts the given JSF client id so that it could be used within jQuery selectors.
     */
    this.toJQueryId = function(jsfClientId) {
    	return jsfClientId.replace(/:/g, '\\:');
    };
    
    this.escapeHtml = function (text) {
        return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
    };
    
    this.getQueryParam = function(param) {
        var found,
            items = window.location.search.substr(1).split("&"),
            it;
        //http://jsperf.com/url-query-search
        for(var i = 0, l = items.length; i<l; i++){
            it = items[i].split( "=" );
            if (param === it[0]) {
                found = it[1];
                break;
            }
        }
        
        return found;
    };



    /**
     * Erzeugt ein neues Popup-Fenster für die URL
     * @param url
     */
    this.openPopupWindow = function(url) {
        var left = (screen.width/2)-(screen.width/3);
        var top = (screen.height/2)-(screen.height/3);
        var params = 'width=' + (screen.width*2/3) + ', height=' + (screen.height*2/3) + ', resizeable, scrollbars, top=' + top + ', left=' + left;
        if (typeof(popupWindowRef) == 'undefined' || popupWindowRef.closed) {
            popupWindowRef = window.open(url, 'popupWindowRef', params); // neues Popup
        } else {
            popupWindowRef.location.href = url; // Erneuere die URL und hole Popup in Focus
            popupWindowRef.focus();
        }
    };
    
    var alreadyLoadedFiles = {};
    /**
	 * Filepath of js files to load. String or an Array of Strings
	 */
	this.loadFile = function (filepath, callback, async){
		
		if(filepath){
			
			//if filepath is just a string - then convert to array with 1 entry
			if(!jQuery.isArray(filepath)){
				filepath = [filepath];
			}
			
			var filesLoaded = 0, //fileloaded counter
				file,
				callbackFunction = function(){
					//if all the files have loaded
					if(filesLoaded === filepath.length){
						//check to see if there is a callback function to call
						if(jQuery.isFunction(callback)){
							callback.call();
						}
					}
				};
				
			for(var i = 0, l = filepath.length; i<l; i++){
				file = filepath[i];
				if(!alreadyLoadedFiles[file]){
					//file hasn't been loaded before - so load it now
					jQuery.ajax({
						async:typeof async === "boolean" ? async : true,
						dataType:'script',
					 	url:file,
					    success:function(){
					    	filesLoaded++;	//increment counter
					    	alreadyLoadedFiles[file] = true; //mark file as loaded
					    	callbackFunction();
					    },
					    error:function(){
					    	console.error("error whilst loading file:", file);
					    }
				    });
				}else{
					filesLoaded++;	//increment counter
					callbackFunction();
				}
				
			}
			
		}else{
			console.error("no filepath defined, nothing is loaded");
		}
	}
	
	this.sleep = function (milliseconds) {
		console.log("Sleeping for "+milliseconds+" ms. DO NOT USE IN PRODUCTION!")
		var start = new Date().getTime();
		for (var i = 0; i < 1e7; i++) {
			if ((new Date().getTime() - start) > milliseconds){
				break;
			}
		}
	}
    
};

/**
 * Context information / metadata of the server / from JSF to be used in Javascript.
 * The metadata is stored with a DOM-element rendered by '<his:globalJavascriptContextInformation />'.
 * This compoent must be included in every layout where global metadata is used in javascript.
 *
 * Additional metadata have to be declared in the xhtml-file named above.
 *
 * TODO: Automatisch durch PreRenderListener von JSF inkludieren lassen?
 *
 */
de.his.common.ContextInformation = new function() {

    var context;

    this.get = function(property) {
    	context = jQuery("#contextInformation");
    	return context.data(property);
    };

    this.set = function(property, value) {
    	context = jQuery("#contextInformation");
    	return context.data(property, value);
    };

    this.isEditUITexts = function() {
        return this.get('is-edit-ui-texts') == true;
    };
};

/**
 * Ermittelt die aktuelle System-Sprache
 */
de.his.common.LanguageHelper = new function() {
    var language;

    this.currentLanguage = function() {
        if (!language) {
            language = jQuery('html').attr('lang');
            if (!language) {
                language = 'de';
            }
        }
        return language;
    };
};

de.his.common.browser = new function(){
	
	var checkForString =  function(name){
		return navigator.userAgent.toLowerCase().indexOf(name.toLowerCase()) > -1 ? true : false;
	}
	
	this.isChrome = function(){
		return checkForString("chrome") && !checkForString("opr");
	}
	
	this.isFirefox = function(){
		return checkForString("firefox");
	}
	
	this.isIE = function(){
		return checkForString("msie") || checkForString("trident");
	}
	
	
/**
 * Add Class for IE
 */
	var ua = navigator.userAgent,
	doc = document.documentElement;
	if ((ua.match(/MSIE 10.0/i))) {
		doc.className = doc.className + " ie_old";
	} else if((ua.match(/rv:11.0/i))){
		doc.className = doc.className + " ie_old";
	}
	
}

/**
 * @param cursor - string (css value) - optional - defaults to "auto" 
 */
de.his.common.chromeCursorFix = function(cursor){
	var wkch = document.createElement("div");
    wkch.style.overflow = "hidden";
    wkch.style.position = "absolute";
    wkch.style.left = "0px";
    wkch.style.top = "0px";
    wkch.style.width = "100%";
    wkch.style.height = "100%";
    var wkch2 = document.createElement("div");
    wkch2.style.width = "200%";
    wkch2.style.height = "200%";
    wkch.appendChild(wkch2);
    document.body.appendChild(wkch);
    document.body.style.cursor = cursor || "auto";
    wkch.scrollLeft = 1;
    wkch.scrollLeft = 0;
    document.body.removeChild(wkch);
}

/**
 * IE bug fix - no contains method
 */
if ( !String.prototype.contains ) {
    String.prototype.contains = function() {
        return String.prototype.indexOf.apply( this, arguments ) !== -1;
    };
}

de.his.common.langSelected = function(select){
	var select = jQuery(select),
		option = select.find(":selected");
	//fire language change
	window.location = option.attr("data-value");
}


de.his.common.getAlreadyLoadedResources = function() {
	var list = performance.getEntriesByType("resource");
	if (list === undefined) {
		return[];
	}

  	var names = [];

  	for (var i=0; i < list.length; i++) {
		names.push(list[i].name);
	}

   	return names;	
}/**
 * Auf Cookies zugreifen
 */
de.his.common.Cookie = new function() {
	
	this.areCookiesEnabled = function (){
	    // Quick test if browser has cookieEnabled host property
	    if (navigator.cookieEnabled) return true;
	    // Create cookie
	    document.cookie = "cookietest=1; SameSite=Lax; Secure";
	    var ret = document.cookie.indexOf("cookietest=") != -1;
	    // Delete cookie
	    document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	    return ret;
	}

    this.create = function(name, value) {
        this.createWithPath(name, value, de.his.common.ContextInformation.get('context-path'));
    };

    this.createWithPath = function(name, value, path) {
    	var cookie = name + '=' + value + '; path=' + path +"; SameSite=Lax;Secure";  
    	
    	// Der Path soll immer nur den Servernamen enthalten.
    	if (name == "lastRefresh" && (path.lastIndexOf("/") > path.indexOf("/"))) {
	    	alert("Setting cookie with bad path. Report to SYS (JOL): " + cookie);
    	}
        document.cookie = cookie;
    };

    this.read = function(name) {
        var nameEQ = name + '=',
            ca = document.cookie.split(';'),
            i = 0;
        for (; i < ca.length; i++) {
            var c = ca[i];
            while (c && c.charAt(0) == ' ') {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) == 0) {
                return c.substring(nameEQ.length, c.length);
            }
        }
        return null;
    };
    
    this.erase = function(name) {
        this.eraseWithPath(name, de.his.common.ContextInformation.get('context-path'));
    };

    this.eraseWithPath = function(name, path) {
    	var cookie = name + '=0; path=' + path +"; SameSite=Lax; expires=Thu, 01-Jan-1970 00:00:01 GMT";  
    	document.cookie = cookie;
    };
    
    // common function aliases
    this.get = this.read;
	this.set = this.create;
	this.del = this.erase;
};/**
 * Initializes some HISinOne JS functionality.
 * 
 * Modules to be initialized need a method 'init'. Modules to be refreshed after AJAX requests need a 'refresh' method.
 */

/**
 * sets console loglevel
 */
jQuery("#contextInformation").ready(function(){
	
	// # LOG, DEBUG, INFO, WARN, ERROR
var jsLoglevel = de.his.common.ContextInformation.get('jsconsoleLoglevel');
	window = window['hisJsLoglevel'] = jsLoglevel;
	
	// disables console functions
	var setLogLevel = function( methods ) {
		for (var i = 0; methods.length > i; i++) {
    		window.console[ methods[ i ] ] = function() {};
        }
    };
    
    // debug a single page without JS debugging enabled globally.
    if(window.location.href.endsWith("jsdebug")){
    	jsLoglevel = 'LOG';
    	console.info("JS-Console loglevel set to '", jsLoglevel, "' for one request.");
    } else {
    	console.info("JS-Console loglevel set to '", jsLoglevel, "'. Set loglevel in DispatcherProperties with HIS_JS_CONSOLE_LOGLEVEL=LOG/DEBUG/INFO/WARN/ERROR.");
    }
	
    if(jsLoglevel === "LOG"){
		// enable better serviceworker debugging
		if(de.his.serviceworker.registration.isServiceWorkerRegistered()){
			navigator.serviceWorker.addEventListener('message', (event) => {
			  	console.log('Message from Service Worker:', event.data.msg, event.data.event);
			});
		}
		
	}else if(jsLoglevel === "DEBUG"){
		setLogLevel( ["log"] );
		
	}else if(jsLoglevel === "INFO"){
	    setLogLevel( ["log", "debug"] );
	}else if(jsLoglevel === "WARN"){
	    setLogLevel( ["log", "debug", "info"] );
	}else if(jsLoglevel === "ERROR"){
	    setLogLevel( ["log", "debug", "info", "warn", "group", "groupEnd"] );
	}
	
});


/**
 * initializes all modules by calling init() on document.ready
 */
jQuery(document).ready(function() {
    de.his.modules.ModuleRegistry.initializeAll();
	window.allHISinOneModulesInitialized = true;
});

use_package("de.his.modules");

de.his.modules.eventRegistry = new function(){
	var eventReg = {};
	var eventCounter = 0;	// increased with each event registered
	
	/**
	 * @param eventName - string
	 * @param func - function to be called when eventName is fired
	 * @param scope - object - optional
	 * @param destoryWhenFired - boolean - optional - default false : when the listener is fired once then it is destroyed
	 */
	this.addListener = function(eventName, func, scope, destoryWhenFired){
		if(!eventReg[eventName]){
			eventReg[eventName] = [];
		}
		
		if(func){
			console.log("registering event: ", eventName);
			func.eventId = eventCounter++;	// give the function an eventId
			func.eventName = eventName;	// register eventName too
			console.log("listener registered for event", func.eventName, "with Id", func.eventId);
			eventReg[eventName].push({
						func:func, 
						scope:scope,
						destoryWhenFired:destoryWhenFired
					});
		}else{
			console.warn("no function defined when adding a listener", eventName);
		}
	};

	// fire events by name across the application
	this.fireEvent = function(eventName){
		console.log("fired event: ", eventName);
		var events = eventReg[eventName] || [], 
			value;
		for(var i = 0, l = events.length; i<l; i++){
			value = events[i];
			if(value && value.func){
				if(value.scope){
					value.func.apply(value.scope);
				}else{
					value.func.call();
				}
				
				if(value.destoryWhenFired === true){
					this.destroyListener(value.func);
				}
			}
			
		}
	};
	
	/**
	 * @param func = function itself
	 */
	this.destroyListener = function(func){
		// TODO: allow func to be an array of listeners
		if(func){
			var eventName = func.eventName, 
			events = eventReg[eventName],	//array of objects {} see addListener for more details
			eventId = func.eventId;
			console.log("destroy listener registered for event", eventName, "with Id", eventId);
			// iterate all events for given eventName;
			for(var i = 0, l = events.length; i<l; i++){
				//check to see if the iterated event has the same eventId as the parameter func
				if(events[i].func.eventId == eventId){
					eventReg[eventName].splice(i, 1);
					break;
				}
			}
		}
	};
	
	/**
	 * @param - eventName (string), destroys all listeners for the given eventName
	 * beware! this could destroy system based events - use destroyListener() instead and destroy each listener at a time
	 */
	this.destroyEvent = function(eventName){
		delete eventReg[eventName];
	};
	
	
	
};

/**
 * Registry of modules that want to be initialized on startup and / or refreshed after ajax requests.
 */
de.his.modules.ModuleRegistry = new function() {
    var initModules = [];
    var ajaxRefreshModules = [];
    var ajaxStartModules = [];
    var asyncScripts = [];
    /**
	 * check if initialized, see bug:109744
	 */
    var hasModuleIntialized = function(module){
    	return module.moduleIntialized;
    };
    
    this.registerModule = function(module) {
        initModules.push(module);
        return this;
    };
    
    this.registerAjaxRefreshModule = function(module) {
        ajaxRefreshModules.push(module);
        return this;
    };

    this.registerAjaxStartModule = function(module) {
        ajaxStartModules.push(module);
        return this;
    };

    this.initializeAll = function() {
    	
        callModules(initModules, 'init', "Error initialising HISinOne-JS-Module!");
    };
    
    this.refreshAll = function(data) {
    	// check if initialised, see bug:109744
    	
    	if(initModules.length == 0){
    		console.warn("attempting refresh when no modules where initalized.... initalizing all modules");
    		this.initializeAll();
    	}
    	
    	de.his.modules.ModuleRegistry.loadScriptsFromSpan();
    	
    	if(ajaxRefreshModules.length > 0){
    		// double check to see if any module hasn't loaded yet
    		for(var i = 0, l = ajaxRefreshModules.length; i<l; i++){
    			if(!hasModuleIntialized(ajaxRefreshModules[i])){
    				console.warn("trying to refresh un-initialized module... init attempt first", ajaxRefreshModules[i]);
    				callModules([ajaxRefreshModules[i]], 'init', "Error initialising HISinOne-JS-Module!");
    			}
    		}
    	}
    	
    	callModules(ajaxRefreshModules, 'refresh', "Error refreshing HISinOne-JS-Module after AJAX request!", data);
    };

    this.indicateAjaxRequestStart = function() {
        callModules(ajaxStartModules, 'indicateAjaxRequestStart', "Error indicating ajax start to HISinOne-JS-Module!");
    };
    
    var executeFunctionByName = function(functionName, context /*, args */) {
		console.log("execute function: "+functionName+ " on: ",context);
	    var args = Array.prototype.slice.call(arguments, 2);
	    var namespaces = functionName.split(".");
	    var func = namespaces.pop();
	    try{
	    	for (var i = 0; i < namespaces.length; i++) {
		        context = context[namespaces[i]];
		    }
		    return context[func].apply(context, args);
	    } catch (e){
	    	console.log("Could not init script. This might be ok. ", e);
	    	return false;
	    }
	}
    
	var getCallbackFunction = function(callbackObject){
		var callback = function(response){
			executeFunctionByName(callbackObject+".init", window);
		};
		return callback;
	}
    
    this.loadScript = function (url, callbackObject) {
    	if(asyncScripts.indexOf(url) > -1){
			// do not load script if it already has been loaded dynamically
			console.log("%s already loaded ", src);
			return;
		}
		loadScript(url,getCallbackFunction(callbackObject));
		asyncScripts.push(url);
	};
	
	var loadScript = function (url, callback) {
		console.log("Async loading Script: "+ url);
		 jQuery.ajax({
			 url: url,
			 dataType: 'script',
			 success: callback,
			 async: true
		 });
	};
    /**
	 * DOES: 
	 * - searches for span.loadScript [data-library] [data-script] [data-callback-object]
	 * - load them damn scripts dynamically into the site 
	 * - initialize them damn scripts on successful load by calling [data-callback-object].init()
	 * - refresh and ajaxStart functions are working magically, those register automatically when the Module gets initialized.
	 */
	this.loadScriptsFromSpan = function(){
		jQuery("span.loadScript[data-library][data-script][data-callback-object]").each(function(index, elem){
			//console.log("initModules",initModules);
			
			var library = jQuery(elem).data('library');
			var script = jQuery(elem).data('script');
			var refresh = jQuery(elem).data('refresh');
			var callbackObject = jQuery(elem).data('callback-object');
			var qisserverUrl = de.his.common.ContextInformation.get('context-path');
			var url = qisserverUrl+"/javax.faces.resource/"+script+".xhtml?ln="+library;
			
			var initModulesContain = function(moduleName){
				// check if any loaded JS has the given module name
				var val = false;
				 for ( var i = 0, length = initModules.length; i < length; i++) {
					 if(initModules[i].moduleName === moduleName){
						 val = true;
					 }
				 }
				 console.log("initModulesContain: "+ moduleName+" ? "+val);
				 return val;
			}
			//console.log("trying to load script dynamically: "+ script, callbackObject);
			
			if(asyncScripts.indexOf(script) > -1){
				// do not load script if it already has been loaded dynamically
				//console.log("script already loaded "+ script);
				return;
			}
			asyncScripts.push(script);
			
			if(initModulesContain(callbackObject)){
				// Do not load module if JSF already included it
				console.log("script already loaded by JSF: "+ script);
				return;
			}
			
			loadScript(url,getCallbackFunction(callbackObject));
		});
	};
	class ModuleRegistryError extends Error {
		constructor(message, e){
	        super(message);
	        this.name = this.constructor.name;
	    	this.stack = e.stack;
	    }
	};
    var callModules = function(modules, method, errorBaseMessage, data) {   
        var errorList = [];	
		console.group('🧩 HIS-Modules', method);
        for ( var i = 0, length = modules.length; i < length; i++) {
            console.group('🗨' , modules[i].moduleName);
            try {
                modules[i][method](data);
                if(method == "init"){
                	modules[i].moduleIntialized = true;
                }
            } catch (e) {
				let errmsg = errorBaseMessage + " Src: "+modules[i].moduleName+"."+method+" (" + de.his.common.Util.toExceptionMessage(e) + ")";
            	console.error(errmsg, e);
				errorList.push( new ModuleRegistryError(errmsg, e));
            }
            console.groupEnd();
        }
        console.groupEnd();
        if(errorList.length > 0){
            console.group('❗ Errors in HIS-Modules:', method);
            for ( var i = 0, length = errorList.length; i < length; i++) {
                console.error(errorList[i].message, errorList[i].stack);
            }
            console.groupEnd();
        }
        
    };
    
};
//Current workaround to warn users using android browser or other (not chrome) on a mobile device, that the browser is not supported
// Eventually to be removed
de.his.modules.mobile = new function(){
	var me = this;
	de.his.modules.ModuleRegistry.registerModule(this);
	
	this.moduleName = "de.his.modules.mobile";
	
	this.mobile = {
			/**
			 * @property warnDelay
			 * @type {Integer} days
			 * @default 30
			 */
			warnDelay: 30,
			/**
			 * @property _cacheKey
			 * @private
			 * @type {String}
			 * @default "_his.mobile.browser.warning"
			 */
			_cacheKey: "_his.mobile.browser.warning",
			/**
			 * check whether the user has been warned
			 * @method hasBeenWarned
			 * @return {Boolean}
			 */
			hasBeenWarned: function(){
				var me = this;
				return !!me.getCacheValue( me._cacheKey );	//convert to boolean
			},
			/**
			 * @method getCacheValue
			 * @returns
			 */
			getCacheValue: function(){
				var me = this;
				if(typeof window.localStorage !== 'undefined'){
					return window.localStorage.getItem( me._cacheKey );
				} else {
				    return 0;
				}
				
			},
			/**
			 * checks whether the warn message is due to show itself again
			 * @method hasWarningExpired
			 * @return {Boolean}
			 */
			hasWarningExpired: function(){
				var me = this,
					currentTime = new Date().getTime();
				if(!me.hasBeenWarned() || (currentTime > me.getCacheValue()) ){
					return true;
				}
				return false;
			},
			/**
			 * sets the cache key that the user has been warned
			 * @method setWarning
			 */
			setWarning: function(){
				var me = this,
					timestamp = new Date().getTime() + (me.warnDelay * 24 * 60 * 60 * 1000);	//30 days from now
				return window.localStorage.setItem( me._cacheKey,  timestamp );
			},
			/**
			 * @method init
			 */
			init: function(){
				var me = this,
		       		device = window.device;

				if(typeof localStorage !== "undefined" && device){
					var storage = window.localStorage;
					if(device.android() && !de.his.common.browser.isChrome()){
						if( me.hasWarningExpired() ){
							me.setWarning();
		   					alert("Bitte verwenden Sie Google Chrome als Standardbrowser für diese Webseite. <br /> Please use Google Chrome as standard browser for this webpage.");
	    	   			}
					}
				}
			}
	};
	
	this.init = function(){
		return me.mobile.init();
	};
	
};/**
 * @Author: masala, wahrendorff
 * This is for non-module specific fixes/features etc
 * TODO: 
 */
use_package("de.his.modules");
de.his.modules.GeneralFixes = new function() {
	de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
	
    this.moduleName = "de.his.modules.GeneralFixes";
    
    this.init = function() {
    	de.his.modules.GeneralFixes.fixTablePagerMaxValidation();
    	//de.his.modules.GeneralFixes.fixCheckboxesWithLeftLabels();
        //de.his.modules.GeneralFixes.showCheckboxesWithoutLabelsWorkaround();
    	fixTomahawkJSPopupPosition();
    	handleInfoboxHide();
    	handleUserQueryFocusTrap();
    }
    this.refresh = function() {
    	de.his.modules.GeneralFixes.init();
    }
    
    var handleUserQueryFocusTrap = function() {
		var overlay = jQuery(".overlay.modal:visible").last();
		
		// Legacy Accessibility workaround for old callbacks
		// focus old callback, when there is no overlay.
		
		//Lagacy handling with overlays is in de.his.component.overlay.js
		var callBackContainer = jQuery('div[data-infobox-type="Query"]:visible');
		if (callBackContainer.length > 0 && overlay.length == 0) {
			var okButton = callBackContainer.find('.ok-button-behavior');
			var cancelButton = callBackContainer.find('.cancel-button-behavior');
			console.log("Overlay: Callback exists, focus callback");
			callBackContainer.find('h2').focus();
			callBackContainer.find(':focusable').first().attr("firstmodalfield", true);
			callBackContainer.find(':focusable').last().attr("lastmodalfield", true);
			/** set inert #299063 */
			//document.querySelectorAll("[tabindex], input:not([type=hidden]), button, a, textarea, label").forEach( function(element,key,parent) {
			//	/** erkenne ob element parent von .overlayContainer oder anders herum und spare aus. */
			//	/** ignoriere elemente ohne offset (versteckt oder hidden oder anderweitig nicht interagierbar) */
	        //    
	        //    if (!element.contains(callBackContainer[0]) && !callBackContainer[0].contains(element) && element.offsetParent !== null ) {
	        //        element.setAttribute('inert','inert');
	        //        console.log('set inert',key, element);
	        //    }
			//});
			var removeFocusTrap = function(){
				console.log("Overlay: Remove focus Trap");
				jQuery("[firstfocusableelement='true']").off("focus");
				jQuery("[lastfocusableelement='true']").off("focus");
				/** remove inert #299063 */
				//document.querySelectorAll("*[inert]").forEach( function(element,key,parent) {
				//	    element.removeAttribute('inert');
				//});
			}
			okButton.on('click', removeFocusTrap);
			cancelButton.on('click', removeFocusTrap);
			// handle Tab Key in userQuery
			jQuery('div[data-infobox-type="Query"]:visible').last().bind('keydown',	function(e) {
				console.log("bind userQuery Tab key.");
				if (e.keyCode == 9) {
					// 9 is tab key
					if (e.shiftKey) {
						// tab and Shift pressed... do anything here...
						if (jQuery(document.activeElement).attr("firstmodalfield") == "true") {
							e.preventDefault();
							jQuery(this).find("[lastmodalfield=true]").focus();
						}
						return;
					}
					// tab without shift is pressed
					if (jQuery(document.activeElement).attr("lastmodalfield") == "true") {
						e.preventDefault();
						jQuery(this).find("[tabindex='0']").first().focus();
					}
				}
			});
		} 
	
	};
    
    var handleInfoboxHide = function () {
	    var handleClicksAndPropagation = function(e,infoboxCloseBtn){
	    	// stop bubbling and propagation, cause burgermenu would close again when infobox is opened and automatically closed upon menu call.
	    	infoboxCloseBtn.on('click', function(){
	    		e.stopPropagation();
	    		return false;
	    	});
	    	infoboxCloseBtn.click();
	    	infoboxCloseBtn.off('click');
	    }
        // hide infobox when user clicks somewhere else in the page
        // caveeat: does not work when user clicks on iframes.
        // does not propagade click events on closing infoboxes (due to problems with burgermenu)
        //jQuery(document).off('click');
        if(jQuery("html").data('infoboxHandlerInitialized') === 'true'){
        	return;
        }
        jQuery(document).on("click", function (e) {
        	jQuery("html").data('infoboxHandlerInitialized','true');
            
            // fix for #322099, check if selectonemenu item triggered
			if(jQuery(e.target).hasClass("loadContent-behavior") || jQuery(e.target).hasClass("ui-selectonemenu-item")){
                // do not close Infobox on automated loading Button clicks or selectbox change.
				return;
			}
			//console.log("clicked somewhere, target is: ", jQuery(e.target));
			//console.log("clicked somewhere, find collapsibleHeaderActionFrom: ", jQuery(e.target).closest('#collapsibleHeaderActionFrom'));
			// close all visible portalinfoboxes of service Header on elsewhere click            
            if (!jQuery(e.target).closest("[id$='collapsibleHeaderActionFrom']").length && !jQuery(e.target).closest('.confirm_infobox').length) {
            	//[id$='txtTitle']
            	if (jQuery('#infoboxElement') && jQuery('#infoboxElement').find(".infoboxContainer").html()) {
	            	//console.log("close infoboxElement:visible");
	            	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:infobox\\:close']"));
	            }
                if (jQuery('#userInformationCenterElement') && jQuery('#userInformationCenterElement').find(".infoboxContainer").html()) {
	            	//console.log("close userInformationCenterElement:visible");
	            	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:userInformationCenter\\:close']"));
	            }
	            if (jQuery('#systemInformationCenterElement') && jQuery('#systemInformationCenterElement').find(".infoboxContainer").html()) {
	            	//console.log("close systemInformationCenterElement:visible");
	            	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:systemInformationCenter\\:close']"));
	            }
	            if (jQuery('#myJobs') && jQuery('#myJobs').find(".infoboxContainer").html()) {
	            	//console.log("close myJobs:visible");
	            	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:myJobsInfobox\\:myJobsInfoBox\\:close']"));
	            }
            }
            
            var clickedLink = jQuery(e.target).closest('a');
            //close all other portalinfoboxes on portalinfobox open click
            if(clickedLink && typeof jQuery(clickedLink).attr("id") !== 'undefined' && jQuery(clickedLink).attr("id").endsWith("open") && jQuery(clickedLink).attr("id").startsWith("collapsibleHeaderActionFrom")){
            	console.log("click portalinfobox open", clickedLink);
            	if (jQuery('#infoboxElement') && jQuery('#infoboxElement').find(".infoboxContainer").html() && !jQuery(clickedLink).attr("id").includes("infobox")) {
	            	//console.log("close infoboxElement:visible");
                	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:infobox\\:close']"));
	            }
                if (jQuery('#userInformationCenterElement') && jQuery('#userInformationCenterElement').find(".infoboxContainer").html() && !jQuery(clickedLink).attr("id").includes("userInformationCenter")) {
	            	//console.log("close userInformationCenterElement:visible");
	            	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:userInformationCenter\\:close']"));
	            }
	            if (jQuery('#systemInformationCenterElement') && jQuery('#systemInformationCenterElement').find(".infoboxContainer").html() && !jQuery(clickedLink).attr("id").includes("systemInformationCenter")) {
	            	//console.log("close systemInformationCenterElement:visible");
	            	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:systemInformationCenter\\:close']"));
	            }
	            if (jQuery('#myJobs') && jQuery('#myJobs').find(".infoboxContainer").html() && !jQuery(clickedLink).attr("id").includes("myJobsInfobox")) {
	            	//console.log("close myJobs:visible");
	            	handleClicksAndPropagation(e,jQuery("[id$='collapsibleHeaderActionFrom\\:myJobsInfobox\\:myJobsInfoBox\\:close']"));
	            }
            }
        });
    };
    
    var fixTomahawkJSPopupPosition = function(){
    	// we do not want to fix the tomahawk directly
    	// so we do it here
    	var popupElems = jQuery('.metadata_popup');
    	if(popupElems.length>0){
    		var observer = new MutationObserver(function(mutations) {
    			
        	    mutations.forEach(function(mutationRecord) {
        	        var popupElem = mutationRecord.target;
        	        var x = popupElem.style.left.replace('px','');
        	        // correct outer document limits.
        	        if (Number(popupElem.offsetWidth) + Number(x) > document.body.clientWidth){
        	        	console.log("Correct position of datdaDictPopup");
        	        	x = document.body.clientWidth - popupElem.offsetWidth;
        	        	popupElem.style.left = "" + x + "px";
        	        }
        	    });    
        	});
        	
        	popupElems.each(function(index, elem){
        		observer.observe(elem, { attributes : true, attributeFilter : ['style'] });
        	});
    	}
    }
    
    /**
     * TODO:
     * - should be removed when Umstellung is finished
     * Otherwise combine loops from here and fixCheckboxesWithLeftLabels for better performance
     */
    /*this.showCheckboxesWithoutLabelsWorkaround = function(){
    	jQuery('input[type="checkbox"]').each(function(){
    		if(typeof jQuery(this).attr('id') === 'undefined'){
    			return;
    		}
    		var checkboxId = de.his.common.Util.toJQueryId(jQuery(this).attr('id'));
    		if(!jQuery('label[for="'+checkboxId+'"]').length && jQuery(this).is(":visible")){
    			jQuery(this).css('opacity','1');
    			jQuery(this).wrap("<div class='thisCheckboxHasNoLabelError' title='Checkbox muss per id/for mit einem Label verknüpft sein. Bei Bedarf an einem unsichtbaren Label bitte barrierefreie Lösung aus dem Styleguide unter Checkboxen verwenden.'></div>");
    		}
    		
    		jQuery(this).on('focus',function(e){
				jQuery(this).addClass("checkbox-focus");
			});
    		jQuery(this).on('blur',function(e){
				jQuery(this).removeClass("checkbox-focus");
			});
    		
    	});
    };*/
    
    /*
     * DONE:
     * select checkboxes with prev label and id = for
     * apply style
     * add change handler
     */
    /*this.fixCheckboxesWithLeftLabels = function(){
    	
    	// select checkboxes
    	jQuery('input[type="checkbox"]').each(function(){
    		if(jQuery(this).data('checkboxified') == 'true'){
    			return true;
    		} else{
    			jQuery(this).data('checkboxified', 'true');
    		}
    		
    		// check if previous element is a label and belongs to the checkbox
    		var checkboxId = jQuery(this).attr('id');
    		var labelElem = jQuery(this).prev();
    		if(labelElem.hasClass("labelrequired")){
    			labelElem = labelElem.find('label');
    		}
    		//console.log("labelElem:", labelElem)
    		if(labelElem.is('label') && labelElem.attr('for') == checkboxId){
    			// apply magic
    			if(typeof jQuery(this).attr('checked') === 'undefined'){
    				labelElem.addClass("checkbox-unchecked");
    			}else{
    				labelElem.addClass("checkbox-checked");
    			}
    			if(typeof jQuery(this).attr('disabled') !== 'undefined'){
    				labelElem.addClass("checkbox-disabled");
    			}
    			
    			jQuery(this).on('focus',function(e){
    				labelElem.addClass("checkbox-focus");
    			});
        		jQuery(this).on('blur',function(e){
        			labelElem.removeClass("checkbox-focus");
    			});
    			
    			// add changehandler to update checkbox image
    			jQuery(this).on('change',function(e){
    				if(e.target.checked){
    					labelElem.removeClass("checkbox-unchecked").addClass("checkbox-checked");
        			}else{
        				labelElem.removeClass("checkbox-checked").addClass("checkbox-unchecked");
        			}
    			});
    		}
    		
    	});
    };*/
    
    this.fixTablePagerMaxValidation = function(){
    	//Temp Fix for: #114282
    	//Stop the user from entering a number higher than 300 in the pager (tables)
    	jQuery("input.pagerInput_behaviour").keyup(function(){
    		var input = jQuery(this),
    			val = parseInt(input.val()),
    			maxInt = 300; //TODO: make 300 variable/configurable
    		
    			console.log("val:"+val);
    		var err = function(){
    			//TODO: get the text from messages (i18n texts)
    			//console.log("set input to 300");
    			//alert("Max: 0-300"); // creates Problems on second execution (alert box is out of pageview, Background curtain cannot be removed)
    			input.val(maxInt);
    		};
    		
    		if(val != NaN){
    			if(val > maxInt || val < 0){
    				//console.log("if call err");
    				err();
    			}
    		}else{
    			//console.log("else call err");
    			err();
    		}
    	});
    }
    
};use_package("de.his.portal");

/**
 * injects userinformation for autologin login
 */
de.his.portal.AutoLogin = new function() {
	de.his.modules.ModuleRegistry.registerModule(this); //	.registerAjaxRefreshModule(this);
		
	this.moduleName = "de.his.portal.AutoLogin";

	this.init = function() {
		console.log("autologinAllowed: " + de.his.common.ContextInformation.get('autologinAllowed'));
		console.log("userLoggedIn: " + de.his.common.ContextInformation.get('userLoggedIn'));
		
		if(de.his.common.ContextInformation.get('autologinAllowed') && !de.his.common.ContextInformation.get('userLoggedIn')){
			injectUserInfoIntoLoginForm();
		}
	};
	
	var injectUserInfoIntoLoginForm = function (){
		console.log("injectUserInfoIntoLoginForm start");
		jQuery("input[name='userInfo']").val(JSON.stringify(getUserInformations()));
	}
	
	var getTimeZone = function(){
		
		var d = new Date();
		return d.getTimezoneOffset();
	}

	var getScreenInfos = function() {
		//Unter FF kann das Screen-Objekt nicht direkt weiter gegeben werden
		var screen = {};
		screen["height"] = window.screen.height;
		screen["width"] = window.screen.width;
		screen["pixelDepth"] = window.screen.pixelDepth;
		return screen;
	};
	
	var getClientInformation = function() {
		var clientInformation = {};
		if (window) {
			if (window.clientInformation) {
				if (window.clientInformation.appCodeName) {
					clientInformation["appCodeName"] = window.clientInformation.appCodeName;
				}
				if (window.clientInformation.appName) {
					clientInformation["appName"] = window.clientInformation.appName;
				}
				if (window.clientInformation.cpuClass) {
					clientInformation["cpuClass"] = window.clientInformation.cpuClass;
				}
				if (window.clientInformation.platform) {
					clientInformation["platform"] = window.clientInformation.platform;
				}
			}
			if (window.navigator) {
				if (window.navigator.oscpu) {
					clientInformation["oscpu"] = window.navigator.oscpu;
				}
			}
		}
		return clientInformation;

	}

	var getUserInformations = function() {
		var userInfo = {};
		userInfo["test"] = "test";
		userInfo["screen"] = getScreenInfos();
		userInfo["timeZone"] = getTimeZone();
		userInfo["clientInformation"] = getClientInformation();
		return userInfo;

	};

//	this.refresh = function() {
//		this.init();
//	};
};
use_package("de.his.serviceworker");
/**
 * Handles ServiceWorker registration
 */
de.his.serviceworker.registration = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this);
    this.moduleName = "de.his.serviceworker.registration";
    
    this.serviceWorkerRegistered = false;
    this.swRegistration = null;
    
    
    // map class instance to self, since the context of "this" can change.
    var self = this;
    
    this.init = function() {
    	// disable Buttons if push is not configured or serviceWorkers are not supported
    	if(!('serviceWorker' in navigator)){
    		if(!('serviceWorker' in navigator)){
    			console.error('Service workers aren\'t supported in this browser.');  
    		}
    		return;
    	}
    	
    	// check if the service worker is registered
    	self.serviceWorkerRegistered = self.isServiceWorkerRegistered();
    	
    	//console.log("sw: ", navigator);
    	if(self.serviceWorkerRegistered){
//     		console.log("sw: ", navigator.serviceWorker);
//         	console.log("sw: ", navigator.serviceWorker.controller);
    	} else {
    		self.registerServiceWorker();
    	}
    };
    
	this.registerServiceWorker = function(){
		if(self.serviceWorkerRegistered && self.swRegistration != null){
    		console.log('ServiceWorker already registered');
    		de.his.modules.eventRegistry.fireEvent("serviceWorkerRegistered");
    		return self.swRegistration;
    	}
    	
		return navigator.serviceWorker.register(de.his.common.ContextInformation.get('context-path') + "/serviceworker.js",
		 { scope: de.his.common.ContextInformation.get('context-path') + "/", updateViaCache: 'all'})
		.then(function(registration) {
			self.swRegistration = registration;
			de.his.modules.eventRegistry.fireEvent("serviceWorkerRegistered");
			console.log('Service worker successfully registered.');
			return registration;
		}, function(err) {
				// registration failed :(
				console.log('ServiceWorker registration failed: ', err);
		}).catch(function(err) {
			console.error('Unable to register service worker.', err);
		});
    };
    
    this.unregisterServiceWorker = function(){
		navigator.serviceWorker.getRegistrations().then(function(r) {
			console.log('Removing ServiceWorker.');
			self.swRegistration = null;
			return Promise.all(r.map(function(reg){reg.unregister()}));
		}).catch(function(err){
			console.log('Removing ServiceWorker failed with error: ', err);
		});
    };
    
    this.isServiceWorkerRegistered = function(){
	    if ('serviceWorker' in navigator && navigator.serviceWorker !== null && typeof navigator.serviceWorker !== 'undefined') {
	    	if('controller' in navigator.serviceWorker && navigator.serviceWorker.controller !== null && typeof navigator.serviceWorker.controller !== 'undefined'){
	    		if( navigator.serviceWorker.controller.state === 'activated'){
	    			return true;
	    		}
	    	}else{
	    		return false;
	    	}
		} else{
			return false;
		}
    };
};
use_package("de.his.pwa");
/**
 * Handles ServiceWorker registration
 */
de.his.pwa.install = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this);
        
    this.moduleName = "de.his.pwa.install";
    
    // map class instance to self, since the context of "this" can change.
    var self = this;
    var deferredPrompt;
    var btnContainer = jQuery("#pwaInstallContainer");
    var installBtn = jQuery("#pwaInstallBtn");
    var dismissBtn = jQuery("#dismissPwaInstallBtn");
    
    this.init = function() {
		window.addEventListener('beforeinstallprompt', (e) => {
			console.log("beforeinstallprompt event triggered");
			// Prevent Chrome 67 and earlier from automatically showing the prompt
			e.preventDefault();
			
			if(typeof localStorage.getItem("pwa_install_dismissed") === 'undefined'
				|| localStorage.getItem("pwa_install_dismissed") === null
				|| (Date.now() - localStorage.getItem("pwa_install_dismissed")) > 2592000000 ){ // 30 Tage
				console.log("show install prompt");
				// Stash the event so it can be triggered later.
				deferredPrompt = e;
				// show the install button Container
				btnContainer.css("display","");
			} else {
				// day in ms: 86400000
				var time2NextInstall = (2592000000 - (Date.now() - localStorage.getItem("pwa_install_dismissed")))/86400000;
				console.log("time to new install prompt: "+time2NextInstall +" days.");
			}
			
		});
		
		installBtn.on('click', (e) => {
			// hide user interface that shows install button
			btnContainer.css("display","none");
			// Show the prompt
			deferredPrompt.prompt();
			deferredPrompt.userChoice.then((choiceResult) => {
				if (choiceResult.outcome === 'accepted') {
				  console.log('User accepted the A2HS prompt');
				} else {
				  console.log('User dismissed the A2HS prompt');
				}
				deferredPrompt = null;
			});
		});
		dismissBtn.on('click', (e) => {
			// hide user interface that shows install button
			btnContainer.css("display","none");
			
			deferredPrompt = null;
			
			// Set curretn timestamp to show dialog again in 30 days
			localStorage.setItem("pwa_install_dismissed", Date.now());
			
		});


    };
    
    
    
};
/**
 * Setzt den Focus auf das erste Element im content frame, das mit der Style-Klasse 'autofocus-behavior' gekennzeichnet ist.
 */
de.his.modules.Autofocus = new function() {
    de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.modules.Autofocus";

    this.init = function() {
    	console.log("autofocus start");
    	manageFocus();
    	leftMenuClickHandler();
		manageFormStepFocus();
    };
    this.refresh = function() {
		// Nur neu initialisiren, wenn es sich um eine User-Query handelt.
		if( jQuery('.messages-infobox').data('infobox-type') == 'Query') {
	        this.init();		
		}
    };
    
	this.ajaxCallback = function(data) {
		console.log("AjaxCallback: " + data.status); //while ,data.status can be 1)"begin" 2)"complete" 3)"success"
		if (data.status === 'success') {
			manageFocus();
		}
    	
	};
    
    var leftMenuClickHandler = function(){
    	// Werden Untermenüpunkte im linken Navigationsmenü geklickt, soll auf der neuen Seite die Überschrift fokussiert werden.
        jQuery('a.linkNavigationSecond').click(function(e) {
        	if (window.localStorage) {
        		localStorage.setItem("leftMenuActivePageElementId", this.id);
        	}
        });

        // Wenn ein SubMenu Link geklickt wurde, soll der Link nach dem Öffnen wieder fokussiert werden.
        jQuery('a.linkNavigationFirst').click(function(e) {
        	if (window.localStorage) {
        		localStorage.setItem("leftSubMenuActivePageElementId", this.id);
        	}
        });
    };
    
    var manageFocus = function(){
    	var parentSelector = "#contentFrame";
    	// wenn messages-infobox angezeigt wird, setze den Fokus auf jeden Fall im in die Meldung
    	if(jQuery(".messages_infobox_header").length > 0 && !jQuery(".messages-infobox").hasClass("hideWhenClosed")){
			//de.his.modules.messagesInfobox manage focus by itself
			return;
		}
		// wenn overlay offen setze den focus auf jeden Fall im overlay
    	if(jQuery("div.overlay.modal").length > 0){
    		console.log("overlay found, *overlay.js calls setFocusAutomatically...")
    		parentSelector = "div.overlay.modal";
    		
    		// no left menu with overlay
    		//manageLeftMenuFocus();
    		return;
    	}

    	if (jQuery(parentSelector+" .autofocus-behavior").filter(':visible').length || jQuery(parentSelector+" .autofocus-behavior-focused").filter(':visible').length) {
    		de.his.modules.Autofocus.setFocusAutomatically(parentSelector);
    		
    	} else {
    		manageLeftMenuFocus();
    	}
    };
    
    /**
     * Set focus on first element with autofocus-behavior or first focusable element in container element
     */
    this.setFocusAutomatically = function(containerElementSelector){
    	
    		var element = jQuery(containerElementSelector);
		
    		if (jQuery(containerElementSelector+" .autofocus-behavior").filter(':visible').length) {
				if(!jQuery(containerElementSelector+" .autofocus-behavior").filter(':visible').first()[0].classList.contains('wizard-step__title')){
					element = jQuery(containerElementSelector+" .autofocus-behavior").filter(':visible').first();
				}
			}
			
			// wenn klasse autofocus-behavior-focused gesetzt
			if (jQuery(containerElementSelector+" .autofocus-behavior-focused").filter(':visible').length) {
				// Zum fokussierbaren Element scrollen
				element = jQuery(containerElementSelector+" .autofocus-behavior-focused");
				// letzte geänderte Element wenn vorhanden und localstorage gesetzt ist
				if (localStorage.lastChangedField !== undefined && jQuery('*[id="'+localStorage.getItem('lastChangedField')+'"]').length !== 0 ) {
					element = jQuery('*[id="'+localStorage.getItem('lastChangedField')+'"]').filter(':visible');
				} else if(localStorage.lastChangedField) {
		 			localStorage.removeItem('lastChangedField');
				}
			}

    		console.log("autofocus found autofocus-behavior class. Element:",element);
    		
    		// Styleklasse könnte auf einem Div liegen, deshalb suchen wir in diesem nach relevanten Elementen. Das ist bspw. bei selectOneMenu der Fall!
	    	var getFocusableElement = function(element){
                //beachten, dass fokussierbare elemente einen noAutofocus parent haben können.
                var focusableElements = jQuery(element).find('a[href], area[href], input, select, textarea, button, iframe, object, embed, *[tabindex], *[contenteditable], .iconfont-error_mono').not('[tabindex=-1], [disabled], :hidden, .titleCollapseArea,.fieldsetHeadlineCollapseButton,.collapsableFieldsetHelpButton,.noAutofocus');
                console.log("focusableElements",focusableElements);
                var elemntToFocus;
                focusableElements.each(function(index,elem){
                    
                    if(!jQuery(elem).parents('.noAutofocus').length){
                        elemntToFocus = jQuery(elem);
                        return false;
                    }
                });
                console.log("elemntToFocus",elemntToFocus);
                return elemntToFocus;
            };
            var focusableElement = getFocusableElement(element);
            
	    	//var focusableElement = jQuery(element).find('a[href], area[href], input, select, textarea, button, iframe, object, embed, *[tabindex], *[contenteditable]').not('[tabindex=-1], [disabled], :hidden, .titleCollapseArea,.fieldsetHeadlineCollapseButton,.collapsableFieldsetHelpButton,.noAutofocus');
	    	
	    	if (focusableElement && focusableElement.length) {
	    		console.log("autofocus for focusable "+focusableElement.attr('id'));
	    		
	    		/**
	    		 * PRIMEFACES PATCH START
	    		 */
	    		// element is correct for this, its a div which has the autofocus behaviour class, focus is getting set to included input.
	    		if(element.hasClass("ui-selectonemenu") || focusableElement.parent().hasClass("ui-helper-hidden-accessible")){
	    			setTimeout(function(){
	    				focusableElement.focus();
					},100);
	    		} else {
	    			focusableElement.focus();
	    		}
	    		/**
	    		 * PRIMEFACES PATCH ENDE
	    		 */
	    		jQuery('input[name="activePageElementId"]').attr('value', focusableElement.first().attr('id'));
	            de.his.common.ContextInformation.set("active-page-element-id", focusableElement.first().attr('id'));
	    	} else {
	    		console.log("autofocus for "+element.attr('id'));
	    		/**
	    		 * PRIMEFACES PATCH START
	    		 */
	    		if(element.hasClass("ui-selectonemenu") || element.hasClass("callBackButton")){
	    			setTimeout(function(){
						element.focus();
					},100);
	    		} else {
	    			element.focus();
	    		}
	    		/**
	    		 * PRIMEFACES PATCH ENDE
	    		 */
				
	    		jQuery('input[name="activePageElementId"]').attr('value', element.attr('id'));
	            de.his.common.ContextInformation.set("active-page-element-id", element.attr('id'));
	    	}	    	
	    	// scroll to autofocus object if needed
	    	var scrollTop = jQuery(document).scrollTop();
	    	var windowHeight = jQuery(window).height();
	    	var elementOffset = element.offset().top;
            
	    	if ((scrollTop == 0 && elementOffset < windowHeight) || jQuery("div.overlay.modal").length || element.hasClass("callBackButton")) {
	    		// Element ist sehr weit oben und daher sichtbar oder overlay. scrollen nicht notwendig
	    		return;
	    	}	    	

	    	// Beim scrollen einen evtl. vorhandenen ScrollWithMe Container beachten.
	    	var scrollWithMe = jQuery('.scrollWithMe');
			if (scrollWithMe.length > 0) {
				var newOffsetTop = elementOffset - scrollWithMe.offset().top;
				if (newOffsetTop < 0) {
					newOffsetTop = 0;
				}
				elementOffset = newOffsetTop;
			}
	    	
	    	//Scrollen mit einer Animation zum Element.
	        jQuery('html, body').animate({
	        	scrollTop: elementOffset
	        }, 1000);

    };
    
    /**
     * Wird im linken Navigationsmenü ein Link geklickt, wird dessen Id in die LocalStorage geschrieben. Nach dem öffnen des Links
     * wird diese id wieder ausgelesen und der Fokus entsprechend gesetzt.
     * Wenn ein SubMenu Link geklickt wurde, soll der Fokus auf dem geklickten Link bleiben.
     * Wenn ein Untermenü Link geklickt wurde, soll der Fokus auf die Überschrift der Seite gesetzt werden.
     * 
     */
    var manageLeftMenuFocus = function() {
    	console.log("autofocus manage left menu.");
    	if (window.localStorage) {
    		var leftMenuActivePageElementId = localStorage.getItem("leftMenuActivePageElementId");
    		var leftSubMenuActivePageElementId = localStorage.getItem("leftSubMenuActivePageElementId");
//    		console.log("leftMenuActivePageElementId "+leftMenuActivePageElementId );
//    		console.log("leftSubMenuActivePageElementId "+leftSubMenuActivePageElementId );
    		if (leftSubMenuActivePageElementId) {
    			var subMenuLink = document.getElementById(leftSubMenuActivePageElementId);
    			if (subMenuLink) {
    				subMenuLink.focus();
    			}
    		}

    		if (leftMenuActivePageElementId) {
    			jQuery("#hisinoneTitle").attr("tabindex", "0").focus();
    		}

    		localStorage.removeItem("leftMenuActivePageElementId");
    		localStorage.removeItem("leftSubMenuActivePageElementId");
    	}
    };
    
    /**
	 * PRIMEFACES PATCH START
	 */
	var manageFormStepFocus = function() {
		// id von letzte geänderte Element in localStorage speichern
		jQuery('.autofocus-behavior-focused').on('click', '.ui-selectonemenu-item', function(e) {
			$this = jQuery(this).closest('.autofocus-behavior-focused');
			if(window.localStorage) {
				localStorage.setItem('lastChangedField', $this.attr('id'));
			}
		});
		// Tabnavigation bestätigung mit Enter
		jQuery('.autofocus-behavior-focused').on('keyup', function(e) {
			// bei enter
			if(e.which == 13) {
				$this = jQuery(this);
				if(window.localStorage) {
					localStorage.setItem('lastChangedField', $this.attr('id'));
				}
			}
		});
		
		// Für mobile Android-Geräte, diese setzen sonst den Focus auf die Startseite des Browsers.
		jQuery('.ui-selectonemenu').on('click', '.ui-selectonemenu-item', function(){
			if( jQuery('html').hasClass('android mobile') ) {
				$this = jQuery(this);
				$this.closest('.ui-selectonemenu').find('input').blur();
				setTimeout(function(){
					$this.closest('.ui-selectonemenu').find('input').focus();
				}, 100);
			}
		});
		
	};
	/**
	 * PRIMEFACES PATCH EDNE
	 */
};
/**
 * Hilfsobjekt zur Behandlung der Default-Buttons.
 * Author: Hoersch, Wahrendorff
 */
de.his.modules.DefaultButton = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.modules.DefaultButton";

    var buttonClicked = false;
    var registeredButtons = [];
    var registeredForms = [];

    this.init = function() {
    	console.log("default Button init");

        jQuery('form').each(function() {
            var form = jQuery(this);
            handleSelfDeclaredDefaultButton(form);
        });
        buttonClicked = false;
    };

    this.refresh = function() {
    	console.log("default Button refresh");
    	resetRegistry();
        this.init();
    };
    
    var resetRegistry = function(){
    	console.log("reset defaultButton Registry");
    	registeredButtons = [];
        registeredForms = [];
    }
    
    var handleSelfDeclaredDefaultButton = function(form){
    	/**
         * Button declares itself as default via JSF default=true
         * 
         * in this case a button is written as first element into the form to act as default when no js is active.
         */
        form.children("button[class='defaultbutton']").each(function(){
        	if(jQuery(this).is(":visible") === true){
        		var id = jQuery(this).attr('name');
                
            	console.log("add "+id+" to default-button-behavior (JSF)");
                register(form, id);
        	}
    	});
        /**
         * or styleClass
         */
        form.find('.default-button-behavior').each(function() {
        	if(jQuery(this).is(":visible") === true){
        		var id = jQuery(this).attr('id');
                
            	console.log("add "+id+" to default-button-behavior");
                register(form, id);
        	}
        	
        });
    };
    
    var register = function(form, buttonId) {
        if (alreadyRegistered(buttonId)) {
            return;
        }
        console.log("register button:"+buttonId);
        registeredButtons.push(buttonId);
        
        if (alreadyRegisteredForm(form.attr('id'))) {
            return;
        } else {
        	console.log("register form:"+form.attr('id'));
            registeredForms.push(form.attr('id'));
            handleFormSubmit(form);
        }
        
    };
    
    var handleFormSubmit = function(form){
    	form.off('keydown');
    	form.keydown(function(event) {
        	var keycode = event.keyCode;
        	if(keycode != 13){
        		return;
        	}
        	//console.log("Enter target: " , jQuery(event.target));
            // Für selects geht das nicht, denn hier verhalten sich die Browser unterschiedlich:
            // Firefox: nix bei Enter
            // Chrome: menü aufklappen bei Enter
            // Keiner schickt hierbei das Formular ab
            if (jQuery(event.target).is('select')) {
            	console.log("item selected, no form submit on enter.");
                return false;
            }
            
            if (jQuery(event.target).parent().hasClass('ui-selectonemenu-items-wrapper')) {
            	//maybe unnecessary, Prime fetches event from items. 
            	console.log("PrimeSelect item selected, no form submit on enter.");
                return false;
            }
            
            /** Elemente die kein input sind, sollen keine default form submit on Enter auslösen können */
            if (!jQuery(event.target).is('input')) {
            	console.log(jQuery(event.target)+" no default form submit on enter allowed.");
                return true;
            }
             
            if(keycode == 13 && jQuery(event.target).is('input') && jQuery(event.target).is('[defaultbutton]')){
            	console.log("input has declared default submit button");
				var defaultButtonId = jQuery(event.target).attr('defaultbutton');
				if(jQuery("button[id$='"+de.his.common.Util.toJQueryId(defaultButtonId)+"']").length > 0){
					jQuery("button[id$='"+de.his.common.Util.toJQueryId(defaultButtonId)+"']").click();
                    return false;
				} else {
					console.warn("DefaultButton with id ending '"+defaultButtonId+"' does not exist. It has been ignored.");
				}
            }
            
            if (keycode == 13 ) {
            	// Suche letztes overlay
            	var overlay = jQuery('div.overlay.modal').filter(':visible').last();
            	if (overlay && overlay.length) {
            		console.log("search for generic Search with defaultbutton in overlay");
            		
            		// Ausnahme: Generische Untersuchmaske zur Auswahl im Overlay
            		/**
            		 * Schauen ob suchmaske vorhanden, wenn ja , clicke ersten defaultbutton
            		 */
            		 if(overlay.find("#genericSearchMask").length > 0){
            			var gsFirstDefaultBtn = jQuery(event.target).parents("#genericSearchMask").first().parent().find(".default-button-behavior").first();
                 		
						if(gsFirstDefaultBtn.length > 0){
							console.log("found generic search in overlay");
							gsFirstDefaultBtn.addClass("noAutofocus").click();
							return false;
						}
						
            		 } else {
            			 // JS defaultbutton behavior ist wegen Anfrage 199654 in overlays abgeschaltet. 
            			 // ^^ Vermutlich wegen unsichtbarer overlays die das Verhalten gestört haben, optimierter selektor sollte das Problem beheben.
            		 	
            			var defaultBtn = jQuery(event.target).parents(".overlayContainer").first().find(".default-button-behavior").first();
						var refreshBtn = jQuery(event.target).parents().children('label').parent().children('.refreshButtonNoDisplay');

            		 	if(defaultBtn.length > 0 && refreshBtn.length == 0){
							console.log("found defaultButton in overlay");
							defaultBtn.click();
							return false;
						}
            		 }
            		
            		console.log("nothing found");
            		return true;
            	}
            }
            
            
            console.log("nothing happened for defaultbutton from JS");
            
            return true;
        });
    };

    var alreadyRegistered = function(buttonId) {
    	console.log(buttonId + " indexOf: " + registeredButtons.indexOf(buttonId));
        return registeredButtons.indexOf(buttonId) > -1;
    };
    var alreadyRegisteredForm = function(formId) {
    	console.log(formId + " indexOf: " + registeredButtons.indexOf(formId));
        return registeredForms.indexOf(formId) > -1;
    };

    this.submitEnter = function (buttonId, e) {
        var keycode;
        if (window.event) {
            keycode = window.event.keyCode;
        } else if (e) {
            keycode = e.which;
        } else {
            return true;
        }
        if (keycode == 13) {
            clickButton(buttonId);
            return false;
        }
        return true;
    };

    var clickButton = function(buttonId) {
        if (buttonClicked) {
            return;
        }
        console.log("try to click:"+buttonId);
        if (document.getElementById(buttonId) != null) {
        	document.getElementById(buttonId).click();
        }
		if (document.getElementById(buttonId+':add_button') != null) {
        	document.getElementById(buttonId+':add_button').click();
        }
        buttonClicked = true;
    };
};/**
 * HISinOne HTML-Textfeld (hier mit CK-Editor).
 */

var CKEDITOR_BASEPATH;

de.his.modules.HtmlEditor = new function() {
    de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this).registerAjaxStartModule(this);

    this.moduleName = "de.his.modules.HtmlEditor";
    
    var textareaSelector = 'textarea.fckEditor,textarea.fckeditor'; // ,textarea.ckeditor<-- class ckeditor is recognised by ckeditor.js and replaces textareas with default ckeditor
    var contextPath = de.his.common.ContextInformation.get('context-path');
    var getParam = function(key){
    	
    	return jQuery('span#ckeditorParams').data(key);
    }

    this.init = function() {
    	// DONE: new approach: each editor can be configured individually
    	// so we begin with iterating potential textareas 
    	// and look out for data attributes for configuration
    	// before falling back to global configuration for legacy reasons
    	
    	var textareas = jQuery(textareaSelector);
    	if(textareas.length==0){
    		// return if no textareas match.
    		return;
    	}
    	
    	if (typeof CKEDITOR!=='undefined') {
        	textareas.each(function(e, i){
        		
        		var ta = jQuery(this);
        		//console.log("editor:",ta);
        		if(ta.data("loadonstart")){
        			// new approach
        			createCkeditors(ta);
        		} else {
        			// legacy
        			if (getParam("loadonstart")) {
        				if (!jQuery.fn.ckeditor) {
        		            return;
        		        }
        				ta.data(toolbar)
        				createCkeditors(ta);
        			}
        		}
        		
        	});
    	} else {
    		// we need to set CKEDITOR_BASEPATH when loading ckeditor dynamically or ckeditor thinks the current url is it's actual path
        	CKEDITOR_BASEPATH = de.his.common.ContextInformation.get('context-path')+'/pub/ckeditor/';
    		console.log("init ckeditor Basepath: %s",CKEDITOR_BASEPATH);
			de.his.modules.ModuleRegistry.loadScript(CKEDITOR_BASEPATH+"ckeditor.js", "de.his.modules.HtmlEditor");
    	}
    	
    };

    this.indicateAjaxRequestStart = function(){
        /**
         * Updating Textarea for potential ajax submit
         */
        if (typeof CKEDITOR!=='undefined') {
        	
            // update all instances of CKEDITOR that are not disabled
        	var textareas = jQuery(textareaSelector);
        	textareas.each(function() {
    			var instanceKey = this.name;
				var $instance = jQuery(this);
				 
				if(!$instance.is(':disabled')){
					try{
						CKEDITOR.instances[instanceKey].updateElement();
					} catch(e){
						// log error
				 		console.log(e);
				 	}
				}
        	});
        } 

    };

    this.debugSettings = function() {
    	//TODO: needs something else all these params are deprecated and unused in new approach
        //alert("loadOnStart = " + loadOnStart + "\r\n" + "replaceNewlines = " + replaceNewlines + "\r\n" + "customConfigFile = " + customConfigFile);
    };

    this.triggerElementUpdate = function() {
    	for ( var instance in CKEDITOR.instances ) {
    	    if( CKEDITOR.instances.hasOwnProperty( instance ) ){
    	        CKEDITOR.instances[instance].updateElement();    
    	    }
    	}
    }
    
    this.replace = function(){
    	this.init();
    };
    
    this.toggle = function(selector){
    	if(typeof selector === 'undefined'){
    		selector = textareaSelector;
    	}
    	
    	var textareas = jQuery(selector);
    	if(textareas.length == 0){
    		return;
    	}
    	
    	if(textareas[0].classList.contains("suneditor")){
			// also toggles quill for easy migration
			de.his.component.SunEditor.toggle(selector);
			return;
		}
    	
    	//console.log("CKEDITOR.instances: "+selector ,CKEDITOR.instances);
    	
    	// we replace all findings or nothing, so simply check if the first selected textarea is ckeditorfied
    	if(!CKEDITOR.instances[textareas[0].id]){
    		createCkeditors(textareas);
    	} else{
    		destroyCkeditors(textareas);
    	}
    };
    
    var destroyCkeditors = function(textareas){
    	for (var i = 0; textareas.length > i; i++){
    		jQuery("#"+de.his.common.Util.toJQueryId(textareas[i].id)).data('already-ckeditorified', false);
        	CKEDITOR.instances[textareas[i].id].destroy();
    	}
    }
    
    var createCkeditors = function(textareas){
    	if (textareas.length == 0) {
            return;
        }
        
        var customConfigFile = contextPath+'/pub/ckeditor_his/hisconfiguration.js?20240124';

        textareas.ckeditor(customConfigFile);
    }
    
    this.refresh = function() {
    	if (!jQuery.fn.ckeditor) {
            console.log("no juery ckeditor function available.");
            return;
        }
    	
    	this.init();
    };

	this.getAllowedContent = function(mode, allowedHtmlTags, allowedHtmlAttributes){
        var allowedContent;
        switch (mode){
        case 'extendedHtml':
            allowedContent = {
                $1: {
                    // Use the ability to specify elements as an object.
                    elements: allowedHtmlTags,
                    attributes: allowedHtmlAttributes,
                    styles: true,
                    classes: true
                }
            }        
		break;
		case 'tagsOnly':
			allowedContent = {
		    	$1: {
			        // Use the ability to specify elements as an object.
					// Tags only
			        elements: { h1: false, h2: true, h3: true, h4: true, h5: true, h6: true, a: true, abbr: true, b: true, i: true, u: true, sub: true, sup: true, ul: true, ol: true, li: true, dl: true, dt: true, dd: true, p: true, span: true, em: true, s: true, strike: true, strong: true, table: true, tbody: true, thead: true, tfoot: true, tr: true, th: true, td: true, colgroup: true, col: true, caption: true, div: true, small: true, pre: true, code: true,br: true, hr: true, img: true, col: true, style: true},
			        attributes: false,
					styles: false,
			        classes: false
			    }
			};
		break;
		default:
			allowedContent = {
			    $1: {
			        // Use the ability to specify elements as an object.
					// allowed tags, attributes and styles, from HTMLUtil.java, keep in sync!
					// font and font-family is allowed in HTMLUtil.java, but ' and " in style attribute aren't.
					// therefore filter font and font-family, since there is no value in getting the font-family from a Word Document, because the texts are always within a font-family setting context (Portal, FOP-Report, LO-Report) 
			        elements: { h1: false, h2: true, h3: true, h4: true, h5: true, h6: true, a: true, abbr: true, b: true, i: true, u: true, sub: true, sup: true, ul: true, ol: true, li: true, dl: true, dt: true, dd: true, p: true, span: true, em: true, s: true, strike: true, strong: true, table: true, tbody: true, thead: true, tfoot: true, tr: true, th: true, td: true, colgroup: true, col: true, caption: true, div: true, small: true, pre: true, code: true,br: true, hr: true, img: true, col: true, style: true},
			        attributes: [ 'aria-label','aria-labelledby','aria-describedby','title', 'alt', 'src', 'target', 'style', 'class', 'align', 'valign', 'bgcolor', 'colspan', 'rowspan', 'height', 'nowrap', 'width', 'cellpadding', 'cellspacing', 'border', 'id', 'scope', 'summary', 'href', 'lang', 'data-delayedsrc' ],
					styles: ['width', 'height', 'direction', 'line-height', 'vertical-align', 'list-style-type', 'list-style-position', 'color', 'background-color', 'background-repeat', 'font-style', 'font-variant', 'font-weight', 'font-size', 'text-indent', 'text-align', 'text-decoration', 'letter-spacing', 'word-spacing', 'text-transform', 'white-space', 'border', 'border-top', 'border-right', 'border-bottom', 'border-left', 'border-width', 'border-style', 'border-color', 'border-collapse'],
	        		classes: true
			    }
			};
		}
		return allowedContent;
	}
    
    /**
     * return array with toolbarGroups and removeButtons
     */
    this.getToolbarConfig = function(toolbar){
    	var array = []
    	switch (toolbar){
    	case 'full':
    		array['toolbarGroups'] = [
    			{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
    			{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
    			{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
    			{ name: 'links', groups: [ 'links' ] },
    			{ name: 'insert', groups: [ 'insert' ] },
    			{ name: 'forms', groups: [ 'forms' ] },
    			{ name: 'others', groups: [ 'others' ] },
    			{ name: 'tools', groups: [ 'tools' ] },
    			'/',
    			{ name: 'styles', groups: [ 'styles' ] },
    			{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
    			{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
    			{ name: 'colors', groups: [ 'colors' ] },
    			
    			{ name: 'about', groups: [ 'about' ] }
    			
    		];
    		array['removeButtons'] = 'About,Format,AutoComplete,UncommentSelectedRange,CommentSelectedRange,autoFormat,searchCode,Indent,Outdent,codemirrorAbout';

    	break;
    	case 'basic':
    		array['toolbarGroups'] = [
    			{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
    			{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
    			{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
    			{ name: 'colors', groups: [ 'colors' ] },
    			{ name: 'links', groups: [ 'links' ] },
    			{ name: 'others', groups: [ 'others' ] },
    			{ name: 'tools', groups: [ 'tools' ] },
    			{ name: 'about', groups: [ 'about' ] }
    			
    		];
    		
    		array['removeButtons'] = 'About,Format,AutoComplete,UncommentSelectedRange,CommentSelectedRange,autoFormat,searchCode,Indent,Outdent,Blockquote,codemirrorAbout';

    	break;
    	case 'slim':
    		array['toolbarGroups'] = [
    			{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
    			{ name: 'colors', groups: [ 'colors' ] },
    			{ name: 'links', groups: [ 'links' ] },
    			{ name: 'others', groups: [ 'others' ] },
    			{ name: 'about', groups: [ 'about' ] }
    		];
    		
    		array['removeButtons'] = 'About,Format,AutoComplete,UncommentSelectedRange,CommentSelectedRange,autoFormat,searchCode,Indent,Outdent,Blockquote,Subscript,Superscript,codemirrorAbout';

    	break;
    	default:
    		array['toolbarGroups'] = [
    			{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
    			{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
    			{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
    			{ name: 'links', groups: [ 'links' ] },
    			{ name: 'insert', groups: [ 'insert' ] },
    			{ name: 'forms', groups: [ 'forms' ] },
    			{ name: 'others', groups: [ 'others' ] },
    			{ name: 'tools', groups: [ 'tools' ] },
    			'/',
    			{ name: 'styles', groups: [ 'styles' ] },
    			{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
    			{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
    			{ name: 'colors', groups: [ 'colors' ] },
    			
    			{ name: 'about', groups: [ 'about' ] }
    			
    		];
    		array['removeButtons'] = 'About,Format,AutoComplete,UncommentSelectedRange,CommentSelectedRange,autoFormat,searchCode,Indent,Outdent,codemirrorAbout';
    		
    	
    	}
    	
    	return array;
    }
};/**
 * Kapselt Methoden, die für den Refresh-Button in Kombination mit Eingabefeldern benötigt werden.
 *
 * NOTE: in situations where focusing the next input element is undesireable the focus behavior
 *       can be disabled via the style class "disable-input-focus-behavior". 
 */
de.his.modules.InputRefresh = new function() {
    de.his.modules.ModuleRegistry
    	.registerModule(this)
    	.registerAjaxRefreshModule(this);

    this.moduleName = "de.his.modules.InputRefresh";
    var self = this;
    
    var lastActiveElements = [];
    
    this.init = function() {
	
        /**
         * jQuery-Funktion, welche den Focus in das nächste Eingabefeld setzt.
         * reverse - boolean - optional - set to true to focus previous input field
         */
        jQuery.fn.focusNextInputField = function(reverse) {
        	// durch select:not(.langSelector) wird die Auswahlliste der Sprachumsschaltung nicht betrachtet.
            var fields = jQuery("body").find('input[type!="submit"][type!="image"][type!="hidden"][type!="file"][data-exclude!="true"][tabindex!="-1"]:not(.ui-selectonemenu-filter),textarea,select[tabindex!="-1"]:not(.langSelector),button:not(.helpButton)');
            
            var index = fields.index(this);
            
            if(jQuery(this).hasClass("refreshButtonNoDisplay") && reverse){
            	console.log("refresh Button did it!");
            	index = index-1;
            }
           
            console.log("activeElementIndex: "+index);
            
            // ein bischen Magie zum bestimmen des Focus.
            if (index > -1 && (index + 1) < fields.length) {
            	var i = reverse === true ? index - 1 : index + 1;
            	
            	// search for the next input that is NOT disabled nor a refresh, a hidden or a help -button.
            	for(var n=i;i<=fields.length; n++){
            		var jQueryField = jQuery(fields.eq(i));
            		
            		if(!jQueryField.is(":disabled") 
        				//&& !jQueryField.is("[readonly]") 
        				&& !jQueryField.hasClass("refreshButtonNoDisplay") 
        				&& !jQueryField.hasClass("unsichtbar") 
        				//&& !jQueryField.hasClass("submit_image") 
						//&& !jQueryField.hasClass("helpButton")
						){
            			console.log("Set Focus on : "+jQueryField.attr('id'));
            			jQueryField.focus().select();
            			break;
            		}
            		i = reverse === true ? i - 1 : i + 1;
            	}
            }
            
            // Falls es keine Tabelle gibt, kann es vorkommen, dass es nach dem letzten Input noch einen Button gibt 
            // (um bspws. das Formular abzusenden siehe #166658). Ohne isTablePresent würde der viewPort aber wieder 
            // nach oben gesetzt werden. In Tabellen ist genau das aber gewünscht, deshalb an dieser Stelle die Prüfung. 
            var isTablePresent = jQuery(".datascroller");
            if (index > -1 && (index + 1) == fields.length && isTablePresent[0]) {
            	console.log("Set Focus on : "+ fields.eq(0));
                fields.eq(0).focus();
                window.scrollTo(0,0);
            }
            return this;
        };
        
        initIntern();
    };

    this.refresh = function() {
        initIntern();
    };

    var initIntern = function() {
    	// reset flag for radiobutton Patch
    	if(typeof window.sessionStorage !== 'undefined'){
    		sessionStorage.removeItem("his_refreshButtonClicked");
    	}
    	
    	// Focus Behaviour beim klicken mit Maus für einen Refresh abschalten. 
        jQuery('input[type!="submit"][type!="image"][type!="hidden"][type!="file"],textarea,select').click(function(){
        	if(!jQuery(this).hasClass('noAutofocus')){
        		var id = jQuery(this).attr('id');
            	console.log("click focus set on: "+id);
            	sessionStorage.setItem("his_lastClickedPageElementId",id);
            	setActivePageElement(id);
        	}
        });
    	
        jQuery('input[type!="submit"][type!="image"][type!="hidden"][type!="file"],textarea,select,a').focus(function() {
        	if(!jQuery(this).hasClass('noAutofocus')){
        		var id = jQuery(this).attr('id');
            	setActivePageElement(id);
        	}
        });

        //Buttons sollen Fokus nach Bedienung behalten
        jQuery('button[type=submit]').click(function() {
        	var activePageElementFocusId = jQuery(this).data('focusid');
        	if(typeof activePageElementFocusId !== 'undefined'){
        		sessionStorage.setItem("his_manualFocusByDataFocusId", activePageElementFocusId);
        	}
        	if(!jQuery(this).hasClass('noAutofocus') && !jQuery(this).hasClass('refreshButtonNoDisplay')){
        		setActivePageElement(this.id);
        	}
        	if(jQuery(this).hasClass('tabButton')){ 
        		sessionStorage.setItem("his_lastClickedTab", this.id);
        	}
        	
        	// add tooltip to rerendered button element in CollapsibleFieldset ajax/java
            if(jQuery(this).hasClass("fieldsetHeadlineCollapseButton") || jQuery(this).hasClass("collapsableFieldsetHelpButton")){
                de.his.modules.eventRegistry.addListener('refresherSuccess', function(){
                    var focused = document.activeElement;
                    de.his.component.customtooltip.removeTooltip(focused);
                    de.his.component.customtooltip.setTooltip(focused);
                });
            }
        });
        
        // Shift key pressed on tab Erkennung für Primefaces Select.
        jQuery('.ui-selectonemenu-filter,ui-selectonemenu-label').keydown(function(event){
        	var keyCode;
            if (event) {
            	var input = jQuery(this);
            	keyCode = event.keyCode || event.which;
            	if(keyCode === 9 || (jQuery(this).hasClass("_refreshOnEnter") && keyCode === 13)){
            		if(event.shiftKey){
            			console.log("shiftKEy pressed!");
                		//TODO: don't use globals!
                		de.his.common.ContextInformation.set("refresh-shift-key", true);
                	}else{
                		// reset if tab without shift is pressed
                		de.his.common.ContextInformation.set("refresh-shift-key", false);
                	}
            	}else{
            		// reset on any other key
            		de.his.common.ContextInformation.set("refresh-shift-key", false);
            	}
            }
        });
        
        jQuery('button[class="refreshButtonNoDisplay"]').click(function() {
            var id = jQuery(this).attr('id');
            refreshBtnClicked(id);
        });

        var activePageElementId = de.his.common.ContextInformation.get("active-page-element-id");
        
        if (activePageElementId) {
            
            var pollButtonClicked = de.his.common.ContextInformation.get("poll-button-clicked");
            var refreshButtonClicked = de.his.common.ContextInformation.get("refresh-button-clicked");
            var activePageElement = jQuery('#' + de.his.common.Util.toJQueryId(activePageElementId));

            var hasActivePageElementDisabledFocusBehavior = activePageElement.hasClass("disable-input-focus-behavior");
            var hasParentWithDisabledFocusBehavior = activePageElement.parents(".disable-input-focus-behavior").length > 0;
            var focusInputBehaviorEnabled = ! hasActivePageElementDisabledFocusBehavior && ! hasParentWithDisabledFocusBehavior;
            
            var fieldsetHelpButtonClicked = false;
            var popupButtonClicked = false;
            var tableFilterButtonClicked = false;
            var captchaRefreshButtonClicked = false;
            var tableConfigButtonClicked = false;
            var portalInfoBoxLinkClicked = false;
            
            //Es kann vorkommen, dass das ursprüngliche Element nicht mehr da ist, obwohl die Id noch gesetzt ist. Deshalb prüfen...
        	if (document.getElementById(activePageElementId)) {
            	fieldsetHelpButtonClicked = document.getElementById(activePageElementId).parentElement.classList.contains('fieldsetHelpButton');
            	popupButtonClicked = document.getElementById(activePageElementId).dataset.popupbutton;
            	tableFilterButtonClicked = document.getElementById(activePageElementId).dataset.tablefilterbutton;
            	captchaRefreshButtonClicked =  document.getElementById(activePageElementId).classList.contains('refreshCaptcha');
            	tableConfigButtonClicked = document.getElementById(activePageElementId).classList.contains('configTableButton');
            	portalInfoBoxLinkClicked = document.getElementById(activePageElementId).classList.contains('portalInfoBoxLink');
        	}
        	
        	// keep focus manually with data-attribute on active element, used in ui repeats to keep focus on moving element
        	var manualFocusByDataFocusId = sessionStorage.getItem("his_manualFocusByDataFocusId");
        	if(manualFocusByDataFocusId !== null){
        		manualFocusByDataFocusId = de.his.common.Util.toJQueryId(manualFocusByDataFocusId);
        		if(jQuery('[data-focusid="' + manualFocusByDataFocusId + '"]').length>0){
        			jQuery('[data-focusid="' + manualFocusByDataFocusId + '"]').focus().select();
        		} else{
        			if(manualFocusByDataFocusId.indexOf('up')>-1){
        				manualFocusByDataFocusId = manualFocusByDataFocusId.replace('up','down');
        			} else {
        				manualFocusByDataFocusId = manualFocusByDataFocusId.replace('down','up');
        			}
        			jQuery('[data-focusid="' + manualFocusByDataFocusId + '"]').focus().select();
        		}
        		console.log("focus set manually, data-focusId: %s",manualFocusByDataFocusId);
        		sessionStorage.removeItem("his_manualFocusByDataFocusId");
        		return;
        	}

            // disable focus on refresh after mouse click select
            var radioButtonClickedId = sessionStorage.getItem("his_radioButtonClickedId");
            var lastClickedPageElementId = sessionStorage.getItem("his_lastClickedPageElementId");
            console.log("lastClickedPageElementId: %s",lastClickedPageElementId);
            console.log("activePageElement: %s",activePageElementId);
            
            // check if is lastClickedPageElementId a checkbox and if yes, set focus to label and remove lastClicked
            if(lastClickedPageElementId != null && jQuery("#"+de.his.common.Util.toJQueryId(lastClickedPageElementId)).is(':checkbox') ){
				jQuery("label[for='"+de.his.common.Util.toJQueryId(lastClickedPageElementId)+"']").focus();
				sessionStorage.removeItem("his_lastClickedPageElementId");
				return;
			}
           
            console.log("radioButtonClickedId: %s",radioButtonClickedId);
            
            // Wenn eine Nutzer Rückfrage (IssueQuery) eingeblendet wird, soll die Überschrift bzw. der Text fokussiert werden
        	var query = jQuery('.infobox.confirm_infobox.messages-infobox');
        	if (query && query.length) {
        		query.find('h2').attr("tabindex", "0").focus();
        		return;
        	}
            
            if(lastClickedPageElementId === activePageElementId || (radioButtonClickedId === lastClickedPageElementId && lastClickedPageElementId !== null && radioButtonClickedId!== null)) {
            	console.log("disabled Focus behaviour cause a radio button or input was clicked.. ");
            	focusInputBehaviorEnabled = false;
            	if(!jQuery(this).hasClass('noAutofocus')){
                    // TODO:
                    // - wenn geklicktes Element hat noAutofocus, behalte id des vorherigen Elements als geklicktes Element
                    sessionStorage.removeItem("his_lastClickedPageElementId");
                }
            	sessionStorage.removeItem("his_radioButtonClickedId");
            	jQuery("#"+de.his.common.Util.toJQueryId(lastClickedPageElementId)).focus();
                return;
                
            }
             
            if (focusInputBehaviorEnabled) {
            	
            	if(pollButtonClicked) {
	            	de.his.common.ContextInformation.set("poll-button-clicked", false);
	            	return;
	            }
            	
            	//Wenn ein Popup geöffnet wird, soll hier nichts mehr gemacht werden, weil das popup Skript den Fokus selbst setzt.
            	if (popupButtonClicked) {
            		return;
            	}

            	// Wenn der Filter Button in einer Tabelle geklickt wird, soll der Fokus auf das erste Filter Input gesetzt werdenn.
            	if (tableFilterButtonClicked == "false") {
            		// erst den Container indem die Tabelle enthalten ist holen
            		var tableParent = document.getElementById(activePageElementId).parentElement.parentElement;
            		var tableInputs = jQuery(tableParent).find('table').find('input');
            		tableInputs[0].focus();
            		return;
            	}

            	//Tabellen Konfiguration wurde geöffnet
            	if (tableConfigButtonClicked) {
            		var tableConfigH2 = jQuery('.curtainTableConfig').find('h2').first();
            		if (tableConfigH2.length > 0) {
            			tableConfigH2.attr("tabindex", "0");
            			tableConfigH2.focus();
            		}
            		return;
            	}
            	
            	//Portal Infobox soll nach dem Öffnen den Fokus erhatlen
            	if (portalInfoBoxLinkClicked) {
            		jQuery('.infoboxContainer').find("h2").first().focus();
            		bindFocus(jQuery('.infoboxContainer'));
            		return;
            	}

            	// Bei Captcha Eingaben soll der Fokus nach dem Klick auf den RefreshButton auf das Captcha Input gesetzt werden
            	if (captchaRefreshButtonClicked && activePageElement) {
            		var previousSibling = jQuery('.refreshCaptcha').get()[0].previousSibling;
            		if (previousSibling) {
            			previousSibling.focus();
            			return;
            		}
            	}
            	
            	// Wenn auf der Seite ein Fehler aufgetreten ist, soll der Fokus in das erste fehlerhafte Eingabeelement gesetzt werden
            	var firstErrorText = jQuery('.error').first();
            	if (firstErrorText.length) {
            		if (firstErrorText.find("input[type!=hidden]").length) {
            			firstErrorText.find("input[type!=hidden]").focus().select();
                		return;
            		}
            	}

	            if (refreshButtonClicked) {
                    // fix for #299994 and #300348
	            	activePageElement.focus().select();
	            	/*if(!de.his.common.ContextInformation.get("refresh-shift-key")) {
	            		//normal tab
	            		console.log("Focus next input: ",activePageElement);
	            		activePageElement.focusNextInputField();
	            	}else{
	            		//backwards - shift-tab
	            		console.log("Focus prev input: ",activePageElement);
	            		de.his.common.ContextInformation.set("refresh-shift-key", false);
	            		activePageElement.focusNextInputField(true);
	            	}*/
	            } else{
	            	console.log("Focus input: ",activePageElement);	            	
					if(activePageElement.length){
                        if(activePageElement.hasClass('his-autocomplete-select-input')){
                            // do not select input on autocomplete, or user will erase input accedentilly upon ajax update.
                            activePageElement.focus();
                        } else {
                            activePageElement.focus().select();
                        }
					} else {
                        console.log("lastActive Element vanished.. :( ");
                        const lastActiveElementId = lastActiveElements.find(id => jQuery('#' + de.his.common.Util.toJQueryId(id)).length>0);
                        if (lastActiveElementId) {
	                        const previousActiveElem = jQuery('#' + de.his.common.Util.toJQueryId(lastActiveElementId));
                            console.log("Focus previousActiveElem: ",previousActiveElem);
                            if(previousActiveElem.hasClass('his-autocomplete-select-input')){
                                // do not select input on autocomplete, or user will erase input accedentilly upon ajax update.
                                previousActiveElem.focus();
                            } else {
                                previousActiveElem.focus().select();
                            }
                        }
                    }
	            }
            }else{
            	// keep selection when input focus behaviour is disabled.
            	if(activePageElement.is(':disabled')){
            		console.log("Focus next input 2: "+activePageElement.attr('id'));
            		activePageElement.focusNextInputField();
            	}else{
            		console.log("Focus input 2: "+activePageElement.attr('id'));
            		//Das soll nur für Inputs relevant sein. KEINE Buttons.
            		if(activePageElement.length && jQuery(activePageElement).is('input')){
						activePageElement.focus().select();
					}
            	}
            	
            }
            
        }
        // Wenn ein Tabbutton geklick wurde diesen wieder fokussiern
        if( sessionStorage.getItem("his_lastClickedTab") ) {
            jQuery('#' + de.his.common.Util.toJQueryId(sessionStorage.getItem("his_lastClickedTab"))).focus();
            sessionStorage.removeItem("his_lastClickedTab");
        }
    };
    
    this.pollButtonClicked = function(event){
    	de.his.common.ContextInformation.set("poll-button-clicked", true);
    }

    this.refreshSelectedValues = function (event, element, hiddenFieldCliendId, hiddenInputClientId) {
        var hiddenField = document.getElementById(hiddenFieldCliendId);
        var hiddenInput = document.getElementById(hiddenInputClientId);
        if (hiddenField && hiddenInput) {
//        	if (element) {
//        		beforeAjax(element);
//        	}
        	console.log("selectManyPicklist changed: "+hiddenField.value);
        	hiddenInput.value = hiddenField.value;
        	hiddenInput.change();
        }
    };

    this.refreshBtnClick = function(event, element, btnId) {
        var btn = document.getElementById(btnId);
        if (btn) {
        	beforeAjax(element);
            refreshBtnClicked(btnId);
            // set flag for radiobutton
            sessionStorage.setItem("his_refreshButtonClicked", "true");
            btn.click();
        }
    };
    
    this.radioBtnClick = function(event, element, btnId) {
    	
        sessionStorage.setItem("his_radioButtonClickedId", jQuery(element).attr('id'));
        console.log("radioButtonClickedId: "+jQuery(element).attr('id'));
    };

    var setActivePageElement = function(activePageElementId) {
        if (activePageElementId) {
            jQuery('input[name="activePageElementId"]').attr('value', activePageElementId);
            de.his.common.ContextInformation.set("active-page-element-id", activePageElementId);
            //console.log("lastActiveElements", lastActiveElements);
            lastActiveElements.unshift(activePageElementId);
            if(lastActiveElements.length >10){
                lastActiveElements.pop();
                //console.log("lastActiveElements popped", lastActiveElements);
            }
        }
    };
    

    var refreshBtnClicked = function(btnId) {
        if (btnId) {
        	setActivePageElement(btnId);
            de.his.common.ContextInformation.set("refresh-button-clicked-id", btnId);
            de.his.common.ContextInformation.set("refresh-button-clicked", true);
            de.his.common.ContextInformation.set("refresh-button-clicked-for-tree", true);
        }
    };

    var beforeAjax = function(input){
    	var claz = "waitingAnimation";
    	input = jQuery(input);
    	if(input.length > 0){

    		var p = input.parent();
    		if(p.find("." +claz).length <= 0){
    			//show mask
        		//p.append(de.his.modules.Waiting.getWaitingAnimationHtml(2));
        		//de.his.modules.Waiting.executeNormalWaiting();
            	de.his.modules.eventRegistry.addListener("refresherComplete", function(){
            		//hide mask
            		//de.his.modules.Waiting.refresh();
            		//jQuery("." + claz).remove();
            		//de.his.modules.Waiting.removeWaitingAnimationHtml();
            	}, this, true);
    		}

    	}
    };

    this.inputBlur = function(event, element, btnId) {
        if (element._changed) {
        	//beforeAjax(element);
            this.refreshBtnClick(event, element, btnId);
            var btn = document.getElementById(btnId);
            if (btn) {
                btn.alreadyClicked = true;
            }
        }
    };

    this.inputKeydown = function(event, element, btnId) {
    	var keyCode;
        if (event) {
        	keyCode = event.keyCode || event.which;
        	console.log("keycode: "+keyCode);
        	if(keyCode === 9 || (jQuery(element).hasClass("_refreshOnEnter") && keyCode === 13)){
        		sessionStorage.removeItem("his_lastClickedPageElementId");
        		if(event.shiftKey){
            		//TODO: don't use globals!
            		de.his.common.ContextInformation.set("refresh-shift-key", true);
            	} else {
            		de.his.common.ContextInformation.set("refresh-shift-key", false);
            	}
        		// only refresh if element has changed
        		if (element._changed) {
        			console.log("element changed! REFRESH!");
	            	//beforeAjax(event.originalTarget);
	                this.refreshBtnClick(event, element, btnId);
	                var btn = document.getElementById(btnId);
	                if (btn) {
	                    btn.alreadyClicked = true;
	                }
	                return false;
        		}
        	}else{
        		// do not mark element as changed if only shift is pressed, it might be Shift+Tab action
        		if(keyCode!==16){
        			console.log("element changed!");
        			element._changed = true;
        		}
        		// reset on any other key
        		de.his.common.ContextInformation.set("refresh-shift-key", false);
        	}
        	// workaround für ajax Fehler in Datumsfeldern bei Return siehe #166480
        	if(jQuery(element).hasClass("input_date") || jQuery(element).hasClass('input_standard')){
        		if(keyCode === 13){
        			// refresh vor dem Absenden des Formulars
        			event.preventDefault();
        			this.refreshBtnClick(event, element, btnId);
	                var btn = document.getElementById(btnId);
	                if (btn) {
	                    btn.alreadyClicked = true;
	                }
	                if(!jQuery(element).hasClass("_refreshOnEnter")){
	                	jQuery(element).parent("form").submit();
	                }
        		}
        	}
        }
        return true;
    },
    
    this.inputRadioKeydown = function(event,element,btnId){
    	if (sessionStorage.getItem("his_refreshButtonClicked") === "true") {
    		event.preventDefault();
     		console.log("preventDefault while AJAX refreshing");
     		
     		return false;
    	}
    }

    this.inputChange = function(event, element, btnId) {
    	console.log("element changed!");
        element._changed = true;
    };

    this.checkBtnAlreadyClicked = function(event, element, btnId) {
        if (element.alreadyClicked) {
            return false;
        }
        refreshBtnClicked(element.id);
        return true;
    };
    
    var bindFocus = function(infoboxcontainer){
		jQuery("[class='focusTrapFirst']").on("focus", function(){
			console.log("FocusTrap");
			infoboxcontainer.find("[id$='close1']").focus();
		})
		jQuery("[class='focusTrapEnd']").on("focus", function(){
			console.log("FocusTrap");
			infoboxcontainer.find("h2").focus();
		})
	}
};
/**
 * Whenever the session runs out the logged-in User will see a Popup window with
 * the possibility to re-login. Pressing the ESC-Button will close this window
 * 
 * For Mobile Users the site is reloaded, what causes an autologin and leads to the startpage in any case. 
 */
de.his.modules.SessionTimeout = new function() {
	de.his.modules.ModuleRegistry.registerModule(this);
    this.moduleName = "de.his.modules.SessionTimeout";
	this.init = function() {
		window.onkeydown = function(e) {
			var key = e.keyCode ? e.keyCode : e.which;
			if (key == 27) {
				de.his.modules.SessionTimeout.closeLoginForm();
			}
		}
	};

	this.showLoginForm = function() {
		this.closeAlertMessage();
		
		var loginDiv = document.getElementById("sessionTimeoutLoginDiv");
		this.bindFocus(loginDiv);
		if (loginDiv) {
			loginDiv.className = "curtainBoxCallBackBackground";
			//cas logout fix ticket #122889
			var cas = jQuery("#casLogouts img[data-value]");
			if(cas.length){
				var a;
				jQuery.each(cas, function(i,v){
					a = jQuery(v);
					a.attr("src", a.attr("data-value"));
				});
			}
		}
		// set inert for sessionTimeoutLoginDiv
		de.his.component.overlay.setInert();
		jQuery('#wrapper_no_background').addClass('blurFilter');
		jQuery("[class='sessionTimeoutAccessibilityTitle']").focus();
	};
	
	this.closeAlertMessage = function() {
		var alertElement = document.getElementById("alert")
		if (alertElement) {
			alertElement.parentNode.removeChild(alertElement);
			
			var alertModal = document.getElementById("alert-modal");
			alertModal.parentNode.removeChild(alertModal);
		}
	};

	this.closeLoginForm = function() {
		var loginDiv = document.getElementById('sessionTimeoutLoginDiv');
		if (loginDiv && jQuery('#sessionTimeoutLoginDiv.sessionTimeoutLogin').length == 0) {
			loginDiv.className = "noDisplay";
			//cas logout fix ticket #122889
			var cas = jQuery("#casLogouts img[data-value]");
			if(cas.length){
				jQuery.each(cas, function(i,v){
					jQuery(v).removeAttr("src");
				});
			}
			window.location.reload();
		}
	};
	
	this.submitLoginForm = function() {
		var loginDiv = document.getElementById('sessionTimeoutLoginDiv');
		if (loginDiv) {
			loginDiv.className = "noDisplay";
			//cas logout fix ticket #122889
			var cas = jQuery("#casLogouts img[data-value]");
			if(cas.length){
				jQuery.each(cas, function(i,v){
					jQuery(v).removeAttr("src");
				});
			}
		}
	}
	
	this.bindFocus = function (sessionTimeoutContainer){
		jQuery("[id='focusTrapEnde']", sessionTimeoutContainer).on("focus", function(){
			jQuery("[class='sessionTimeoutAccessibilityTitle']").focus();
		});
		
		jQuery("[id='focusTrapStart']", sessionTimeoutContainer).on("focus", function(){
			jQuery("[class='reset']").focus();
		});
	};
	
};/**
 * Das ablaufen der Nutzer-Session verhindern, in dem Requests an den Server
 * geschickt werden
 * 
 * 
 */
// alert(navigator.userAgent);
de.his.modules.SessionRefresh = new function() {
	de.his.modules.ModuleRegistry.registerModule(this)
			.registerAjaxRefreshModule(this);

	var refreshSec = undefined;
	var refreshActive = false;
	var lastRefresh = new Date().getTime();
	var resfreshTimer = undefined;
	var resfreshViewTimer = undefined;
	var timedOut = false;
	var loginFormShown = false;
	var autoLoginEnabled = false;
	this.moduleName = "de.his.modules.SessionRefresh";
	var self = this;
	this.init = function() {
		autoLoginEnabled = de.his.common.Cookie.get('cs.sys.hisinoneAutoLoginEnabled') == 'true' ? true : false;
		var globalSessionRefreshAllowed = de.his.common.ContextInformation.get("global-session-refresh-allowed");
		var isLoggedIn = de.his.common.ContextInformation.get("user-logged-in");
		
		console.log("loggedIN",isLoggedIn);
		if(!isLoggedIn){
			// behebt Probleme
			timedOut = true;
			de.his.common.Cookie.erase('lastRefresh');
			de.his.common.Cookie.erase('sessionRefresh');
		}
		console.log("timedOut",timedOut);
		//console.log("refresh Counter isLoggedIn",isLoggedIn);
		// Ist immer erlaubt, nur wenn das Setup aktiv ist nicht
		if (typeof globalSessionRefreshAllowed != 'undefined'
				&& globalSessionRefreshAllowed 
				&& isLoggedIn) {
			var globalSessionTimeout = de.his.common.ContextInformation.get("global-session-timeout");
			var globalRefreshSession = de.his.common.ContextInformation.get("global-refresh-session");
// 			console.log('always refresh Session? ' + globalRefreshSession);
// 			console.log('session timeout ' + globalSessionTimeout);
			de.his.common.Cookie.create('lastRefresh', lastRefresh);
			refreshSec = Math.max(globalSessionTimeout - 120,
					globalSessionTimeout / 2); // 2 Min. vor Ablauf
												// aktualisieren
// 			console.log("globalRefreshSession:",globalRefreshSession);

			// activate refresh for autologin
			if (globalRefreshSession || autoLoginEnabled) {
				this.activateRefresh();
			} else {
				this.deactivateRefresh();
			}
			resfreshViewTimer = window.setInterval(function(){de.his.modules.SessionRefresh.refreshCounter()}, 1000);
			
		};
		if(isLoggedIn){
			// run on focus, fixes sleepy problems of session timeouts on mobiles 
			jQuery(window).add(document.body);  //necessary for mobile browsers
			jQuery(window).focus(function(){
				console.log("window gained focus.");
				de.his.modules.SessionRefresh.refreshCounter();
			});
		}
	};

	this.refresh = function() {
		lastRefresh = new Date().getTime();
	};

	this.activateRefresh = function() {
		if (!timedOut) {
			de.his.common.Cookie.create('sessionRefresh', '1');
			refreshActive = true;
			this.setRefreshServerSessionTimeout( false );
			jQuery('.sessionTimeout').hide();
			jQuery('#sessionNoTimeoutText').show();
		}
	};

	this.deactivateRefresh = function() {
		if (!timedOut) {
			de.his.common.Cookie.create('sessionRefresh', '0');
			refreshActive = false;
			if (resfreshTimer) {
				window.clearTimeout(resfreshTimer);
			}
			jQuery('.sessionTimeout').show();
			jQuery('#sessionNoTimeoutText').hide();
		}
	};

	this.refreshCounter = function() {
		if(document.getElementsByTagName('body')[0].getAttribute('class').contains('embedded')){
			//do not show login warning or login form in portlets
			return;
		}
		if (!timedOut) {
			var tmp = de.his.common.Cookie.read('lastRefresh');
			if (tmp) {
				lastRefresh = tmp;
			}
			tmp = de.his.common.Cookie.read('sessionRefresh');
			if (tmp === '1' && !refreshActive) {
				jQuery('#refreshSession').attr("checked", true);
				return this.activateRefresh();
			} else if (tmp === '0' && refreshActive) {
				jQuery('#refreshSession').attr("checked", false);
				return this.deactivateRefresh();
			}
			// tmp = null: Keine Cookies im Browser aktiviert..

			if (refreshActive) {
				return;
			}
		}

		var diff = (new Date().getTime() - lastRefresh) / 1000;
		var globalSessionTimeout = de.his.common.ContextInformation
				.get("global-session-timeout");
		var diffSeconds = (globalSessionTimeout - diff);
		if (diffSeconds > 0) {
			var min = Math.floor(diffSeconds / 60);
			var sec = Math.floor(diffSeconds % 60);
			if (min > 0) {
				jQuery('#sessionCounter').html(min + 1);
			} else {
				jQuery('#sessionCounter').html('00:' + (sec < 10 ? '0' + sec : sec));
			}

			// Prüfen ob Nutzer eingeloggt ist.
			// Klicken auf "OK" ruft eine Funktion auf, welche die Session
			// zurücksetzen und verlängern kann.
			var loginForm = document.getElementById("sessionTimeoutLoginForm");
			
			//console.log("Cookie cs.sys.hisinoneAutoLoginEnabled: ", autoLoginEnabled);
			if (min == 5	 && (sec >= 0 && sec < 2) && !autoLoginEnabled) {
				
				// Prüfen ob bereits Alert Meldungen ausgegeben wurde
				var alertMessage = document.getElementById("alert");
				if (!alertMessage) {
					var language = de.his.common.LanguageHelper.currentLanguage();
					var alertTitle = null;
					var alertText = null;
					var alertButton = null;
					if (language == "de") {
						// Deutsche Meldung
						var text1 = "Zu Ihrer eigenen Sicherheit werden Sie in 5 Minuten automatisch vom System abgemeldet.";
						var text2 = "Bitte klicken Sie auf \"Anmeldung verlängern\", um Ihre Sitzung zu verlängern.";
						alertTitle = "<div id='focusTrapStart' tabindex='0'></div><div class='alertWarningTitle'><span class='iconfont-time'></span><h1>Warnung</h1></div>";
						alertText = "<div class='alertWarningBody' aria-label='Warnung. "+ text1 + text2 +"' tabindex='0'><p>"+ text1 +"<br />" + text2 + "</p></div>";
						alertButton = "Anmeldung verlängern";
					} else {
						// Englische Meldung
						var text1eng = "You will be automatically logged out in 5 minutes  for security reasons.";
						var text2eng = "Please choose \"Stay logged in\" to renew your session.";
						alertTitle = "<div id='focusTrapStart' tabindex='0'></div><div class='alertWarningTitle'><span class='iconfont-time'></span><h1>Warning</h1></div>";
						alertText = "<div class='alertWarningBody' aria-label='Warning. "+ text1eng + text2eng +"' tabindex='0'><p>" + text1eng + "<br />" + text2eng + "</p></div>";
						alertButton = "Stay logged in";
					}
					alert(alertTitle, alertText, {
						button_title : alertButton,
						callback : function() {
							de.his.modules.SessionRefresh.refreshSession();
						}
					});
					
					var alertElem = document.getElementById("alert");
					
					var focusTrap = document.createElement("div");
					focusTrap.tabIndex = "0";
					focusTrap.id = "focusTrapEnde";
					alertElem.appendChild(focusTrap);
					
					this.bindFocus(alertElem);
					jQuery("[class='alertWarningBody']").focus();
				}
			}
		} else {
			jQuery('#sessionCounter').html('--');
			timedOut = true;
			if (resfreshViewTimer) {
				window.clearInterval(resfreshViewTimer);
			}

			if (!loginFormShown) {
				de.his.modules.SessionTimeout.showLoginForm();
				loginFormShown = true;
			}
		}
	};
	
	this.bindFocus = function (alert) {
		jQuery("[id='focusTrapEnde']", alert).on("focus", function(){
			jQuery("[class='alertWarningBody']").focus();
		});
		
		jQuery("[id='focusTrapStart']", alert).on("focus", function(){
			jQuery("a",alert).focus();
		});
	};

	// Wenn nur noch 0 bis 5 Minuten der Sessionzeit eines eingeloggten
	// Benutzers übrig sind, kann dieser die Session mit klicken auf "ok"
	// zurücksetzen und verlängern.
	this.refreshSession = function() {
		if (!timedOut) {
			this.refreshServerSession();
			this.refresh();
			this.init();
		}
	};
	
	this.lastRefresh = function() {
	    lastRefresh = new Date().getTime();
        de.his.common.Cookie.create('lastRefresh', lastRefresh);
	}
	
	this.setRefreshServerSessionTimeout = function( ajax ){
		if (!timedOut) {
			console.log("Running refresh Session Timeout.")
		    this.refreshServerSession( ajax );
			resfreshTimer = window.setTimeout( function() {
		        de.his.modules.SessionRefresh.setRefreshServerSessionTimeout();
		    }, refreshSec*1000);
		}
	}

	/**
	 * refreshes the session one time
	 */
	this.refreshServerSession = function( ajax ) {
	    var me = this;
		console.log("refreshing Server Session");
		if( ajax !== false ){ //ajax can be undefined, null or boolean - only interesting if its false
		    jQuery.ajax({
		    	global: false,
	            url : de.his.common.ContextInformation.get('context-path') + '/pages/common/setSessionTimeout.faces',
	            success : function() {
	                me.lastRefresh();
	            },
	            error :  function() {
	            	de.his.ajax.Refresher.onError('Fehler beim aktuallisieren der Server Session.');
	            },
	            complete : function(){
	            	self.refresh();
	            }
	        });
		}else{
		    me.lastRefresh();
		}
		
	};

	/**
	 * sets global refresh flag on server session
	 */
	this.setRefresh = function(value) {
		console.log("set Server Refresh Session Cookie to "+value);
		jQuery.ajax({
			global: false,
			url : de.his.common.ContextInformation.get('context-path')
					+ '/pages/common/setSessionTimeout.faces?refreshSession='
					+ value,
			success : function() {
				lastRefresh = new Date().getTime();
				de.his.common.Cookie.create('lastRefresh', lastRefresh);
				de.his.common.ContextInformation.set("global-refresh-session", value);
			},
			 error :  function() {
				 de.his.ajax.Refresher.onError('Fehler beim setzen des globalen Refresh flags.');
			 },
            complete : function(){
            	self.refresh();
            }
		});
	};
};/**
 * Definiert einige Tastenkombinationen, die Funktionen in HISinOne ausführen
 * Insbesondere ESC zum schließen von modalen Overlays, Message-Infoboxen, Popups und Callbacks
 * Schließen Buttons werden mit der styleClass .simple-close-button-behavior deklariert
 * Sind keine Buttons mit .simple-close-button-behavior deklariert, wird versucht den ersten Button mit .cancel-button-behavior aus zu lösen, die in einem Overlay vorkommen können.
 */
de.his.modules.Shortcuts = new function() {
    de.his.modules.ModuleRegistry
	    .registerModule(this);
    this.moduleName = "de.his.modules.Shortcuts";
    this.init = function() {
	
        /** bei Nachfragen (callBack.xhtml) kann der Abbrechen/Nein-Button per Escape-Taste bedient werden. */
        jQuery(document).keyup(function(e) {
            if (e.keyCode == 13) { // enter
                jQuery('.ok-button-behavior:visible').first().click();
            }
            if (e.keyCode == 27) { // esc
            
            	// wenn UserQuery callback vorhanden
            	// ist immer am Anfang der Seite
            	var callBackContainer = jQuery('div[data-infobox-type="Query"]');
            	if (callBackContainer.length > 0) {
					var callBackCancelButton = callBackContainer.find('.cancel-button-behavior');
					if (callBackCancelButton.length > 0) {
						console.log("ESC click legacy callback cancel:", callBackCancelButton);
                    	callBackCancelButton.click();
					}
                    return false;
                }
                // Wenn ein infoboxCloseButton vorhanden ist, dann soll nur dieser ausgelöst werden
                // ist immer am Anfang der Seite, daher eine Ausnahme von anderen simpleCloseButtons
                var infoboxClose = jQuery('.simple-close-button-behavior.infobox_close:visible').first();
                if (infoboxClose.length > 0) {
					console.log("ESC click infoboxClose:", infoboxClose);
                    infoboxClose.click();
                    return false;
                }
                // Wenn ein simpleCloseButton vorhanden ist, dann soll dieser ausgelöst werden
                // sind verschachtelt am Anfang der modalen Overlay Komponente, daher immer letzten nehmen
				var simpleCloseButton = jQuery('.simple-close-button-behavior:visible').last();
                if (simpleCloseButton.length > 0) {
					console.log("ESC click simpleCloseButton:", simpleCloseButton);
                    simpleCloseButton.click();
                    return false;
                } 
                
                // sind verschachtelt am Ende der modalen Overlay Komponente, daher immer ersten nehmen
				var cancelButton = jQuery('.cancel-button-behavior:visible').first();
            	if (cancelButton.length > 0) {
					console.log("ESC click cancelButton:", cancelButton);
                    cancelButton.click();
                    return false;
                }
            } 
        });
    };
};/**
 * Objekt das Funktionalitäten zum 'Warten' bereitstellt.
 * - Graut den Bildschirm (kurz) aus, wenn
 *   - eine Form submitted wird
 *   - markierte Links geklickt werden
 *     - markierung erfolgt mit der Styleklasse 'waiting-behavior'
 *     - mit der Styleklasse 'short-waiting-behavior' markierte Links bewirken nur einen "warten"-Cursor
 *   - links, buttons und inputs innerhalb
 * - Verhindert bspw. auch Doppelklicks.
 *
 * Bei Downloads:
 * Die Download-Ausgabe-Komponente muss ein Cookie 'download-complete=true' mitschicken, damit das JS erkennt, das der Doownload fertig ist.
 */
de.his.modules.Waiting = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
    this.moduleName = "de.his.modules.Waiting";
    this.init = function() {
    	console.log('[.waiting] init');
        initIntern(this, false);
        jQuery(window).on("unload", function() {    	
            // dummy unload, forces Firefox to re-run the on-ready code if the user pressed the back button. 
        });
        
        jQuery(window).on("beforeunload", function() {
            console.log("[.waiting] beforeunload");            
            jsf.ajax.cancel(); // Laufende und ausstehende Ajax-Requests entfernen
            // PrimeFaces.ajax.Queue.abortAll(); // wird vielleicht mal interessant
        });
        
    };

    this.refresh = function(data) {
    	console.log('[.waiting] refresh');    
    	var doResetWaiting = (data == null) || hasWaitingBehavior(data); 
		initIntern(this, doResetWaiting);
    };

    var initIntern = function(self, doResetWaiting) {
    	if (doResetWaiting) {
    		resetNormalWaiting();    		
    	}
        console.log("waiting start");
        /** bei jedem submit den Screen ausgrauen. */
        jQuery( "form:not(.no-waiting-behavior, .full-screen-waiting-behavior)" ).each( function(index, elem) {
        	if( typeof jQuery(elem).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(elem).data("waitingBehaviorSet", true);
        	// schaltet das Script bei Angular o.ä. eingebetteten Anwendungen aus.
        	if(jQuery(".noHisJsModule").length > 0 && jQuery(elem).closest(".noHisJsModule").length > 0){
        		// Angular Formulare ausnehmen.
        		console.log(".noHisJsModule found on parent... Do not register waiting handlers.");
        		return;
        	}
        	
            // JSF führt direkt form.submit aus, wenn kein form.onsubmit gesetzt ist.
            // Und wider erwarten schreibt sich jQuery hier nicht rein, wenn man .submit(function(){}) benutzt
            var prevOnsubmit = this.onsubmit;
            this.onsubmit = function( event ) {
            	
                var $form = jQuery( this );
                if ( $form.attr("target") !== "_blank" && $form[0].tagName && this.id != ''){
                	console.log("form: "+this.id);
                    self.executeNormalWaiting(this.id);
                }
                if (prevOnsubmit) {
                    prevOnsubmit(event);
                }
            };
        } );
        
        /** bei speziell ausgezeichneten Buttons ein 'full screen waiting' durchführen. */
        jQuery('form.full-screen-waiting-behavior').submit(function(e) {
			if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
            if (de.his.common.ContextInformation.isEditUITexts()) {
                return;
            }
            

            // den eigentlichen Text über data-Attribut holen
            // TODO JSF2 Dazu muss die JSF-Komponenten diese Attribute rendern
            // TODO JSF2 Für die Anmeldemaske ginge es schon so, da hier eh html-Input-Tags benutzt werden
            // SOLUTION: <f:passThroughAttribute name="data-waiting-text" value="Bitte warten..." />
            var text = jQuery(this).data('waiting-text') || "";
            self.executeFullScreenWaiting(text);
            
        });
        
        jQuery('input.full-screen-waiting-behavior, a.full-screen-waiting-behavior, button.full-screen-waiting-behavior').not(".no-waiting-behavior").click(function(e) {
			if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
        	if (this.tagName == 'a' && (e.ctrlKey || e.shiftKey)) {
        		return;
        	}
        	console.log("execute Full Screen Waiting");
        	var text = jQuery(this).data('waiting-text') || "";
            self.executeFullScreenWaiting(text);
            setWaitingBehaviorMarker(this);
            
        });

        
        /**
         * only allow interactive elements (input, a, button) to have an waiting behaviour. Otherwise non active elements can block the UI upon accidental clicks
         */
        jQuery('input.waiting-behavior, a.waiting-behavior, button.waiting-behavior, .waiting-behavior input, .waiting-behavior a, .waiting-behavior button').click(function(e) {
			if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
        	if ((this.tagName.toLowerCase() === 'a' && (e.ctrlKey || e.shiftKey))
        			|| (this.tagName.toLowerCase() === 'a' && jQuery(this).attr("target") === "_blank")){
        		return;
        	}
        	console.log("tagName:" + this.tagName == 'a');
        	console.log("execute Normal Waiting");
            self.executeNormalWaiting(this.id);
            setWaitingBehaviorMarker(this);            
        });
        
        jQuery('input.short-waiting-behavior:not(.rf-sel, [onchange]), a.short-waiting-behavior:not(.rf-sel), button.short-waiting-behavior:not(.rf-sel), .short-waiting-behavior:not(.rf-sel, .radio-buttons, .ui-selectonemenu) input:not([onchange]), .short-waiting-behavior:not(.rf-sel) button, .short-waiting-behavior:not(.rf-sel) a, .scroller a').not(".waiting-behavior, .no-waiting-behavior, .full-screen-waiting-behavior").click(function(e) {
        	if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
			if ((this.tagName.toLowerCase() === 'a' && (e.ctrlKey || e.shiftKey))
        			|| (this.tagName.toLowerCase() === 'a' && jQuery(this).attr("target") === "_blank")) {
        		return;
        	}
        	console.log("execute Short Waiting (not .rd-sel)");
            self.executeShortWaiting(this.id);
            setWaitingBehaviorMarker(this);
        });

        
        // Radiobuttons benötigen 'change'-Event
        jQuery('.short-waiting-behavior.radio-buttons:not(.no-waiting-behavior, .full-screen-waiting-behavior)').on("change", function(e){
        	if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
			console.log("execute Short Waiting (radio-buttons)");
            self.executeShortWaiting(this.id);
            setWaitingBehaviorMarker(this);            
        });       

        // Sonstige Inputs mit 'change'-Event
        jQuery('input.short-waiting-behavior[onchange]:not(.no-waiting-behavior)').on("change", function(e){
			if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
        	console.log("execute Short Waiting (input with 'onchange' e.g. checkboxes)");
            self.executeShortWaiting(this.id);
            setWaitingBehaviorMarker(this);            
        });

		// Inputs mit 'change'-Event innerhalb einer Tabelle - z.B. selectManyCheckbox -
        jQuery('table.short-waiting-behavior:not(.no-waiting-behavior)').on("change", 'input[onchange]', function(e){
			if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
			console.log("execute Short Waiting (input with 'onchange' e.g. checkboxes in selectManyCheckbox component)");
			jQuery(this).addClass('short-waiting-behavior');
            self.executeShortWaiting(this.id);
            setWaitingBehaviorMarker(this);            
        });    
        
        // Primefaces SelectOneMenu benötigt 'selectitem'-Event
        jQuery('.short-waiting-behavior.ui-selectonemenu').on("selectitem", function(e){
			if( typeof jQuery(this).data("waitingBehaviorSet") !== 'undefined'){
				return;
			}
			jQuery(this).data("waitingBehaviorSet", true);
        	console.log("execute Short Waiting (.ui-selectonemenu)");
            self.executeShortWaiting(this.id);
            setWaitingBehaviorMarker(this);            
        });
        
    };   
    
    var setWaitingBehaviorMarker = function(source) {
        source.setAttribute("data-startsWaiting", "true");        	
    }
    
    var hasWaitingBehavior = function(data) {
    	
    	// Workaround für manipulierte checkboxes ('checkboxified')
    	if (data.source.type == "checkbox") {
    		return data.source.classList.contains("short-waiting-behavior");
    	}
    	
    	return data.source.getAttribute("data-startsWaiting") == "true";
    }
    
    this.executeFullScreenWaiting = function(waitingText){
		if (jQuery("#full-screen-waiting").length > 0) {
        	console.log('[.waiting] full-screen-waiting already exists');
            return;
        }  
        // normal waitings are needed by automated tests. 
    	executeWaiting('curtainBackgroundTransparent', this.id
    	);
    	
	 	jQuery('body').append(''+
                 '<div id="full-screen-waiting" class="curtainBoxCallBackBackground waitingCursor">'+
                 '    <center><div class="curtainBoxCallBack">'+
                 '        <div class="infobox confirm_infobox" style="background-color: rgba(255, 255, 255, 0.9) !important;">'+
                 '            <center>'+
                 '                <div class="imageContainer imageContainerWaitingPadding">'+
                 
                 // Variant 1
             	'<div class="floatBarsGContainer" >'+
	         	'	<div id="" class="floatBarsG floatBarsG_1"></div>'+
	         	'	<div id="" class="floatBarsG floatBarsG_2"></div>'+
	         	'	<div id="" class="floatBarsG floatBarsG_3"></div>'+
	         	'	<div id="" class="floatBarsG floatBarsG_4"></div>'+
	         	'	<div id="" class="floatBarsG floatBarsG_5"></div>'+
	         	'	<div id="" class="floatBarsG floatBarsG_6"></div>'+
	         	'	<div id="" class="floatBarsG floatBarsG_7"></div>'+
	         	'	<div id="" class="floatBarsG floatBarsG_8"></div>'+
         		'</div>'+
                 
					// original
                 //'                    <img src="/HISinOne/images/loader/loader_33.gif" title=" " alt=" " />'+
                 '                </div>'+
                 '                ' + waitingText + ''+
                 '            </center>'+
                 '        </div>'+
                 '        <div class="clearer"></div>'+
                 '    </div></center>'+
                 '</div>');
    }
        
    this.executeShortWaiting = function(sourceId) {
        executeWaiting('curtainBackgroundTransparent loadingTopAnimation', sourceId);
    };

    this.executeNormalWaiting = function(sourceId) {
        executeWaiting('curtainBoxCallBackBackground loadingTopAnimation', sourceId);
    };

    var executeWaiting = function(styleClass, sourceId) {
        if (de.his.common.ContextInformation.isEditUITexts()) {
            return;
        }
        if (jQuery("#global-waiting").length > 0) {
        	console.log('[.waiting] global-waiting already exists - skipping: %s from %s', styleClass, sourceId);
            return;
        }        
        
    	console.log('[.waiting] setting global-waiting with style: %s from %s', styleClass, sourceId);        
        jQuery('body').append(''+
        		'    <div id="global-waiting" class="' + styleClass + ' waitingCursor">'+
                '        <div></div>'+ // do not remove. is used for the "flicker" effekt on waiting click
                '    </div>');
        
        // Warn when user tries to click while waiting to complete the request
        jQuery("#global-waiting").click(function() {
            var childs = jQuery(this).children();
            childs.fadeIn(50, function() {
                childs.fadeOut(30);
            });
        });
        
        // Bei Download-Links wird die Seite nicht neugerendert.
        // Deswegen wird wird hier ein Cookie ausgelesen, dass durch die Download-Ausgabe-Komponente gesetzt werden muss.
        resetOnComplete('global-waiting', sourceId);
    };

    var resetOnComplete = function(elementId, sourceId) {
        setTimeout(function () {
            reset(elementId, sourceId);
        }, 100);
    };

    var reset = function(elementId, sourceId) {
        if (de.his.common.Cookie.read("download-complete") == 'true') {
			//de.his.component.MessagesInfobox.showMessagesInfobox('Download Complete remove waiting-behaviour','success');
        	de.his.common.Cookie.erase("download-complete");
			console.log('[.waiting] download-complete; resetting: %s from %s', elementId, sourceId);
			
        	jQuery('#'+elementId).css("animation", "fadeout 0.5s");
 			setTimeout(function () {
                jQuery('#' + elementId).remove();
            }, 500);
            
           // if (de.his.common.Cookie.read('job-started') == 'true') {
                de.his.component.Poll.downloadComplete();
           // }
            
        } else {
            setTimeout(function () {
            	// console.log('[.waiting] reset step: %s from %s', elementId, sourceId);            	
                    reset(elementId, sourceId);
                }, 100);
        }
    };

    var resetNormalWaiting = function() {
		jQuery('#global-waiting').css("animation", "fadeout 0.5s");
    	jQuery('#global-waiting').css("cursor", "initial");
        setTimeout(function(){
        	if(de.his.common.browser.isChrome()){
        		de.his.common.chromeCursorFix();
        	}
        	console.log('[.waiting] resetting global-waiting');        	
        	jQuery('#global-waiting').remove();
        }, 500);
        
		if (jQuery("#full-screen-waiting").length > 0) {
        	jQuery('#full-screen-waiting').css("animation", "fadeout 0.5s");
	        setTimeout(function(){
	        	if(de.his.common.browser.isChrome()){
	        		de.his.common.chromeCursorFix();
	        	}
	        	console.log('[.waiting] resetting global-waiting');        	
	        	jQuery('#full-screen-waiting').remove();
	        }, 500);
        }
		de.his.common.Cookie.erase("download-complete");
    };
    
    this.resetWaitingBehaviour = function(){
    	resetNormalWaiting();
    }
    /**
     * small or big
     * 2 or 1
     */
    this.getWaitingAnimationHtml = function (variant){
    	if(variant === 'big' || variant === 1){
    		var html = '<div class="floatBarsGContainer waitingAnimation">'+
				'<div class="floatBarsG floatBarsG_1"></div>'+
				'<div class="floatBarsG floatBarsG_2"></div>'+
				'<div class="floatBarsG floatBarsG_3"></div>'+
				'<div class="floatBarsG floatBarsG_4"></div>'+
				'<div class="floatBarsG floatBarsG_5"></div>'+
				'<div class="floatBarsG floatBarsG_6"></div>'+
				'<div class="floatBarsG floatBarsG_7"></div>'+
				'<div class="floatBarsG floatBarsG_8"></div>'+
			'</div>';
    	}
    	if(variant === 'small' || variant === 2){
    		var html = '<div class="theySeeMeLoading" >'+
		    '<div class="cssload-loader waitingAnimation" >'+
				'<div class="cssload-flipper">'+
					'<div class="cssload-front"></div>'+
					'<div class="cssload-back"></div>'+
				'</div>'+
			'</div>'+
		'</div>';
    	}
    	return html;
    };
    /**
     * removes all objects with .waitingAnimation
     */
    this.removeWaitingAnimationHtml = function (){
    	console.log('[.waiting] removing waitingAnimation');        	    	
    	jQuery(".waitingAnimation").remove();
    };
    

    this.isShortWaitingActive = function () {
    	var globalWaiting = jQuery('#global-waiting.curtainBackgroundTransparent');
		return globalWaiting.length > 0;
    }
    
    this.isFullWaitingActive = function () {
    	var globalWaiting = jQuery('#global-waiting.curtainBoxCallBackBackground');
    	if (globalWaiting.length > 0) {
    		return true;
    	}
    	
    	var fullScreenWaiting = jQuery('#full-screen-waiting');
    	if (fullScreenWaiting.length > 0) {
    		return true;
    	}
    	
    	return false;
    }
};/**
 * fügt Links mit der Klasse js_outputLink_newWindow eine popup funktionalität hinzu und zentriert das popup automatisch.
 */
de.his.modules.Window = new function() {
    de.his.modules.ModuleRegistry.registerModule(this);
    this.moduleName = "de.his.modules.Window";
    this.init = function() {
        jQuery(".outputLink-newWindow-behavior").click(function(event) {
            var width,
                height;
            
            event.preventDefault();
            
            // get Width and Height, otherwise use default
            if (jQuery(this).attr('data-popupWidth') !== undefined) {
                width = jQuery(this).attr('data-popupWidth');
            } else {
                width = 800; // default Width
            }
            if (jQuery(this).attr('data-popupHeight') !== undefined) {
                height = jQuery(this).attr('data-popupHeight');
            } else {
                height = 400; // default Height
            }
            // center popup window automatically
            var top = (document.body.clientHeight / 2) - (height / 2);
            var left = (document.body.clientWidth / 2) - (width / 2);

            window.open(jQuery(this).attr("href"), 'newwindow', 'menubar=no,resizable=yes,scrollbars=yes,status=no,width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + '');
        });
    };
};/**
 * Zweck:
 * - linkes Menü per JS ein-/ausklappen. Der Zustand wird per f:ajax an den Server übertragen.
 * - mobiles menü im mobile modus
 * - Änderungen am menü für desktop ansicht auf mobilen Geräten
 */

de.his.modules.NavigationMenu = new function() {

	de.his.modules.ModuleRegistry.registerModule(this);
    this.moduleName = "de.his.modules.NavigationMenu";
	var navigation = {
			/**
			 * used to determine whether the navigation is currently open - only for mobile
			 * @property navOpen
			 * @private
			 * @type {Boolean}
			 * @default false
			 */
			navOpen: false,
			/**
			 * @property topNav
			 * @type {jQuery Object}
			 * @private
			 * @default null
			 */
			topNav: null,
			/**
			 * @property leftMenu
			 * @type {jQuery Object}
			 * @private
			 * @default null
			 */
			leftMenu: null,
			/**
			 * @property minNav
			 * @type {jQuery Object}
			 * @private
			 * @default null
			 */
			minNav: null,
			/**
			 * @property touchMoved
			 * @type {Boolean}
			 * @private
			 * @default null
			 */
			touchMoved: null,
			/**
			 * @property childULClass
			 * @type String}
			 * @default "smartphoneNavigation"
			 */
			childULClass: "smartphoneNavigation",
			/**
			 * stop the height resize event being set more than once - memory leak
			 * @property winheightResize
			 * @private
			 * @type {Boolean}
			 * @default false
			 */
			winheightResize: false,
			/**
			 * used on smartphones for showing menus on top of each other
			 * @property globalZindex
			 * @type {Integer}
			 * @default 10
			 */
			globalZindex: 10,
			/**
			 * attached to the body element to indicate that the navigation is open and apply certain styles
			 * @property navigationOpenClass
			 * @type {String}
			 * @private
			 * @default "navigationOpen"
			 */
			navigationOpenClass: "navigationOpen",
			/**
			 * @property mobileNav
			 * @private
			 * @type {jQuery Object}
			 * @default null
			 */
			mobileNav: null,
			/**
			 * @property mobileNavSelector
			 * @private
			 * @type {String}
			 * @default ".topMenuContainer"
			 */
			mobileNavSelector: ".topMenuContainer",
			/**
			 * 
			 */
			getNavForMobile: function(){
				var me = this;
				if(!me.mobileNav){
					me.mobileNav = jQuery( me.mobileNavSelector );
				}
				
				return me.mobileNav;
			},
			/**
			 * @method getTopNav
			 * @return {jQuery Object}
			 */
			getTopNav: function(){
				var me = this;
				if(!me.topNav){
					me.topNav = jQuery(".topMenuContainer");
				}
				return me.topNav;
			},
			/**
			 * @method getLeftMenu
			 * @return {jQuery Object}
			 */
			getLeftMenu: function(){
				var me = this;
				if(!me.leftMenu){
					me.leftMenu = jQuery("#leftMenu");
				}
				return me.leftMenu;
			},
			/**
			 * @method getMinNav
			 * @return {jQuery Object}
			 */
			getMinNav: function(){
				var me = this;
				if(!me.minNav){
					me.minNav = jQuery("#min_navigation");
				}
				return me.minNav;
			},
			/**
			 * @method removeMenu
			 */
			removeMenu:  function() {
		    	var me = this,
		    		leftMenu = me.getLeftMenu();
		    	if(!leftMenu.hasClass("_ignoreForTablet")){
		    		leftMenu.hide();
		    		me.getMinNav().show();
		            
		            // CSS Klassen ersetzen
		            jQuery(".content_navi_on").removeClass('content_navi_on').addClass('content_max_navi_off');
		            jQuery("#wrapper").attr("id", "wrapper_no_navigation");  
		    	}
		              
		    },
		    /**
		     * redirect to removeMenu
		     * @method hideMenu
		     */
		    hideMenu: function(){
		    	var me = this;
		    	return me.removeMenu.apply(me, arguments)
		    },
		    /**
			 * @method showMenu
			 */
		    showMenu: function() {
		    	var me = this,
	    			leftMenu = me.getLeftMenu();
		    	
		    	if(!leftMenu.hasClass("_ignoreForTablet")){
		    		leftMenu.show();
		    		me.getMinNav().hide();
			        
			        jQuery('.content_max_navi_off').removeClass('content_max_navi_off').addClass('content_navi_on');
			        jQuery('#wrapper_no_navigation').attr('id', 'wrapper');       
		    	}
		    },
		    /**
		     * override the behaviour of the current top navigation for smartphones - i.e the submenus in particular
			 * @method overrideNavigationForMenu
			 */
		    overrideNavigationForMenu: function(doParentLinkClick){
		    	var me = this,
		    		top = me.getTopNav(),
		    		nav = jQuery("> ul.nav", top),
		    		links;
		    	console.log('overrideNavigationForMenu');
		    	if(nav.length){
		    		links = jQuery("li.parentListItem > a", nav);
		    		console.log('we have links in nav.');
		    		if(links.length){
		    			links.click(function(event){
		    				console.log('navlink Clicked');
		    				if(jQuery(this).hasClass('subMenuLink')){
		    					// another submenu in desktop view
		    					// leave the link clickable, do nothing.
		    					console.log('subMenuLink Clicked');
		    				}else{
		    					console.log('try parentLinkClick');
		    					
		    					event.preventDefault();
		    					if(doParentLinkClick){
		    						// indicates mobile menu on mobile
		    						me.parentLinkClickMobile(this);
		    					}else{
		    						// indicates desktop menu on mobile
		    						me.parentLinkClickDesktop(this);
		    					}
		    				}
		    			});
		    		}
		    	}
		    },
		    /**
		     * called by link.click in overrideNavigationForMenu
		     * @method parentLinkClick
		     * @private
		     * @param el {HTMLElement} click events "this" property
		     */
			parentLinkClickDesktop : function(el) {
				window.console.log('parentLinkClick');
				var me = this, $this = jQuery(el), child = $this.siblings("ul"), $window = jQuery(window), orientationchange;
	
				if (child.length) {
					console.log('childs are there..');
					orientationchange = function() {
						var $thisOffset = $this.parent().offset();
	
						if ($thisOffset.left + child.width() > $window.width()) {
							child.css("left", $window.innerWidth() - child.width());
						} else {
							child.css("left", $thisOffset.left);
						}
						child.css("margin", 0); // disable margin on orientation change, easier than to compute them and take them into account
						// child.css("top", $thisOffset.top + ($this.outerHeight()));
						console.log('orientation computed!');
					};
					child.addClass(me.childULClass);
					// orientation change event
					$window.on("orientationchange, resize", orientationchange);
	
					document.ontouchend = function(e) {
						if (!$(e.target).closest('.smartphoneNavigation')) {
							jQuery(child).css('display', 'none');
							document.activeElement.blur();
						}
					};
				}
			},
		    parentLinkClickMobile: function(el){
				var me = this,
					$this = jQuery(el),
					child = $this.siblings("ul"),
					top = me.getTopNav(),
					topOffset = top.offset(),
					$window = jQuery(window),
					$document = jQuery(document),
		    		windowHeight = $document.height(),
					zIndex = $this.css("z-index"),
					orientationchange,
					backButton;
				
				if(typeof zIndex === "number"){
					zIndex += 1;
				}else{
					me.globalZindex += 1;
					zIndex = me.globalZindex
				}
				
				if(child.length){
					
					orientationchange = function(){
						
						if( jQuery('body').hasClass('navigationOpen') ){
							jQuery('.navbar-toggle').trigger('click');
						}
						
						var _top = top.offset().top,
							_windowHeight = $window.height();
						child.css("top", _top);
						child.css("bottom", "0px");
						child.css("height", jQuery('.topMenuContainer').height());	
						console.log("orientation/resize computed.")
					};
					
					child.addClass(me.childULClass);
					child.css({
						top: topOffset.top,
						bottom: "0px",
						height: jQuery('.topMenuContainer').height(),
						zIndex: zIndex
					});
					
					//orientation change
					$window.on("orientationchange", orientationchange);
					
					backButton = jQuery("> li.mobileOnly > a.backButton", child);
					if(backButton.length){
						backButton.on("click", function(){
							me.globalZindex -= 1;
							child.removeClass(me.childULClass);
							$window.off("orientationchange", orientationchange);
						});
					}
					
				}
				
	    },
		    /**
		     * this method sets the height of target to that of the (device height - it's y position)
			 * @method resizeHeight
			 * @param target {jQuery Object}
			 */
		    resizeHeight: function(target){
		    	var height = window.innerHeight ? window.innerHeight : $(window).height();
		    	target.css({
					height: (height - target.offset().top),
					overflow: "auto"
				});
		    },
		    
		    /**
		     * @method toggle
		     */
		    toggle: function(data){
		    	var me = this;
		    	return de.his.ajax.Helper.callHandlerIfPhase(data, "begin", me.toggleMenu, me);
			},
			/**
			  * used to toggle the left navigation
		     * @method toggleMenu
		     */
			toggleMenu: function(){
				var me = this,
					leftMenu = me.getLeftMenu(), 
					minNav = me.getMinNav();
				
				if(leftMenu.length && minNav.length){
					if(leftMenu.is(":visible")){
						me.removeMenu(); 
					}else{
						me.showMenu();
					}
				}
				
			},
			/**
		     * @method remove
		     */
			remove: function(data) {
				var me = this;
		        return de.his.ajax.Helper.callHandlerIfPhase(data, "begin", mw.removeMenu, me);
		    },
		    /**
		     * @method show
		     */
		    show: function(data) {
		    	var me = this;
		        return de.his.ajax.Helper.callHandlerIfPhase(data, "begin", me.showMenu, me);
		    },
		    
		    /**
		     * @method initDesktop
		     */
		    initDesktop: function() {
		        jQuery( document ).on( "click", ".topMenuLink, .subMenuLink, .bookmarkPopupMenuLink", function(e) {
		        	// Kein waiting behaviour auslösen, wenn auf einen Eintrag mit Strg+Click oder Shift+Click geklickt wird.
		        	if (e.ctrlKey || e.shiftKey) {
		        		return;
		        	}
		        	if ( jQuery(this).attr("target") !== "_blank" ){
		        		de.his.modules.Waiting.executeNormalWaiting();
		        	}
		        } );
		    },
		    
		    /**
		     * set up an initial conditions when viewed on a tablet
		     * @method initTablet
		     */
		    initTablet: function(){
		    	var me = this;
		    	
		    	jQuery(document).bind("touchstart", function(e){
	    			me.touchMoved = false;
	    		});
	    		
	    		jQuery(document).bind("touchmove", function(e){
	    			me.touchMoved = true;
	    		});
	    		
		    	jQuery(document).bind("touchend", function(e){
					var nav = me.getLeftMenu();
					
					if(nav.is(":visible")){
						
						//check if the coordinates are the same -- i.e if the use is not scrolling
						if(!me.touchMoved){
							
							if(!nav.is(e.target) && nav.has(e.target).length == 0){
								me.hideMenu();
							}	
							
						}
						
									
					}
					
				});
		    },
		    /**
		     * set up an initial conditions when viewed on a mobile
		     * @method initMobile
		     */
		    initMobile: function(){
		    	var me = this;
		    	
		    	me.overrideNavigationForMenu(true);
		    	me.initMobileNavToggle();
		    	
		    },
		    /**
		     * call the widgetPanelIconClick outside of this scope if calling this function from JSF
		     * - de.his.modules.NavigationMenu.widgetPanelIconClick
		     * @method widgetPanelIconClick
		     * this function is called by JSF in 
		     */
		    widgetPanelIconClick: function(data){
		    	var me = this,
		    		body = jQuery("body"),
		    		css = navigation.navigationOpenClass;
		    		
		    	//only for mobile
		    	if(window.device && window.device.mobile()){
		    		body.addClass( navigation.navigationOpenClass );
			    	
			    	if(me.navOpen){
		    			me.mobileHideNavigation();
		    		}else{
		    			//if the icon was clicked again to close it - if the container has no longer
		    			//any content and is no longer visible
		    			if( !jQuery(".infoboxContainer").children().length ){
		    				//remove class
		    				body.removeClass( navigation.navigationOpenClass );
		    			}
		    		}
		    	}	
		    	if (window.localStorage) {
					localStorage.setItem('wpanellsource', jQuery(data.source).attr('id'));
				}
		    },
			widgetPanelClose: function(){
				if (window.localStorage) {
					jQuery(document.getElementById(localStorage.getItem('wpanellsource'))).focus();
				}
			},
		    /**
		     * registers the events when using the ||| toggle menu button found on the mobile version of the site
		     * - imitate that of Bootstrap navigation when browser is scaled.
		     * @method initMobileNavToggle
		     */
		    initMobileNavToggle: function(){
		    	var me = this;
		    	
		    	if ( jQuery(".infoboxContainer > *").length ) {
		    	    //has children means a widget it currently open
		    	    jQuery("body").addClass( navigation.navigationOpenClass );
		    	}
		    	
		    	jQuery(".navbar-toggle").on("click", function(event){
		    		return me.toggleMobileNavigation();
		    	});
		    },
		    /**
		     * @method toggleMobileNavigation
		     */
		    toggleMobileNavigation: function(){
		    	var me = this,
		    		target = me.getNavForMobile(),
		    		widget = jQuery(".closeWidgetPanelButtonLayout > a");

	    		if(target.length){
	    			if(target.is(":visible")){
	    				me.mobileHideNavigation();
	    			}else{
	    				me.mobileShowNavigation();
	    				if(widget.length){
	        				//TODO: is there has to be a better way of closing the infoboxes!?
	    		    		//TODO: ajax request?
	        				//mimic click event
	        				widget[0].click();
	        			}
	    			}
	    		}
		    },
		    /**
		     * @method mobileHideNavigation
		     */
		    mobileHideNavigation: function(target){
		    	var me = this,
		    		target = me.getNavForMobile();
		    	
		    	jQuery("li.parentListItem > ul", target).scrollTop(0).removeClass(me.childULClass);
				jQuery("body").removeClass( me.navigationOpenClass );
				
		    	target.scrollTop(0);
				target.hide();
		    	me.navOpen = false;
		    },
		    /**
		     * @method mobileHideNavigation
		     */
		    mobileShowNavigation: function(){
		    	var me = this,
		    		target = me.getNavForMobile();
		    	
		    	jQuery("body").addClass( me.navigationOpenClass );
		    	
		    	if(!me.winheightResize){
		    		me.winheightResize = true;
		    		jQuery(window).on("resize", function(){
		    			if(me.navOpen){
		    				return me.resizeHeight(target);
		    			}
		    		});
		    	}
				
		    	target.show();
		    	me.resizeHeight(target);
				me.navOpen = true;
		    },
		    
		    /**
		     * set up event listeners etc to toggle the top navigation (usually desktop mode) by clicking on the collapse/expand button 
		     * @method initToggleTopNav
		     */
		    initToggleTopNav: function(){
		    	var me = this,
		    		closeNav,
		    		navigation,
		    		toggleBtn,
		    		closeTheNav,
		    		showTheNav;
		    	
		    	if(navigator.cookieEnabled){
	    			closeNav = window.localStorage.getItem("his_topnavigation_closed") === "true";
			    	navigation = me.getTopNav();
			    	toggleBtn = jQuery("#hisinoneHeader .toggleNavigation");
			    	closeTheNav = function () {
				    		navigation.addClass("topNavClosed");
				    		navigation.hide();
				    		toggleBtn.addClass("iconfont-arrow_right_v");
				    		toggleBtn.removeClass("iconfont-arrow_up_v");
				    };
				    showTheNav = function () {
			    		navigation.removeClass("topNavClosed");
			    		navigation.show();
			    		toggleBtn.removeClass("iconfont-arrow_right_v");
			    		toggleBtn.addClass("iconfont-arrow_up_v");
			    	};
			    	
			    	if(closeNav){
			    		closeTheNav();
			    	}
			    	
			    	toggleBtn.click(function(event, element){
			    		closeNav = !closeNav;
			    		window.localStorage.setItem("his_topnavigation_closed", closeNav);
			    		if(closeNav){
			    			closeTheNav();
			        	}else{
			        		showTheNav();
			        	}
			    		//his global function
			    		window.resizeHeader();
			    		//window.resizeIframesIfAvailable();
			    	});
		    	}
		    },
		    /**
		     * general init method, this is called when the module is loaded
		     * @method init
		     */
		    init: function(){
		    	var me = this,
		    		device = window.device,	//stop any errors if global doesn't exist
		    		minNav = me.getMinNav();

		    	if ( device && jQuery(".notBurgernavigation").length ){
		    	    if ( !jQuery("._isDesktopMode").length && !jQuery(".currentDevice_desktop").length) { //todo with left menu on tablet/mobile
		    	        if(device.tablet()){
	                        me.initTablet();
	                    }else if(device.mobile()){
	                        me.initMobile();
	                    }
		    	    }
		    	    
		    	    if(jQuery(".currentDevice_desktop").length && jQuery(".originDevice_mobile").length){
		    	    	me.overrideNavigationForMenu(false);
		    	    }
		    	    
		    	    if ( device.desktop() ) {
		    	        me.initDesktop();
		    	    }
		    	    
		    		
		    	}
		    	
		    	if(jQuery("form.hide_navigation_onready").length > 0  || (device && device.tablet())){
		    		minNav.hide();
		    		me.hideMenu();
		    	}

		    	// me.initDesktop();
				if ( jQuery(".notBurgernavigation").length ){
		    		me.initToggleTopNav();
				} else {
					me.initDesktop();
				}
		    	
		    }
			
	};
	
	this.navigation = navigation;
	
	//map old functions in case they are used elsewhere
	//TODO: remove and change any calls to these functions and not .navigation
    this.toggle = function(){
    	// this scope in this context is changed at some point and cannot see this.navigation 
    	// hence the navigation variable
    	return navigation.toggle.apply(navigation, arguments);
    };
    this.toggleMenu = function(){
    	return navigation.toggleMenu.apply(navigation, arguments);
    };
    this.hideMenu = function(){
    	return navigation.hideMenu.apply(navigation, arguments);
    };
    this.remove = function(){
    	return navigation.remove.apply(navigation, arguments);
    };
    this.show = function(){
    	return navigation.show.apply(navigation, arguments);
    };
    // ********** //
    
    this.init = function(){
    	return navigation.init.apply(navigation, arguments);
    };
    this.widgetPanelIconClick = function(){
    	return navigation.widgetPanelIconClick.apply(navigation, arguments);
    };
this.widgetPanelClose = function(){
    	return navigation.widgetPanelClose.apply(navigation, arguments);
    };
 
    
};

/**
 * Author: Daniel Dziegielewski
 * 
 */

de.his.modules.sys = new function() {
    de.his.modules.ModuleRegistry.registerModule(this)
    .registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.modules.sys";

    this.init = function() {
    	this.stopHoverWhenScrolling();
    };
    
    this.initWithAjax = function() {
    };
    
    // Stoppt jegliche Hover-Effekte wenn der User scrollt. (#170492)
    this.stopHoverWhenScrolling = function(){    	
    	
    	if(jQuery(".originDevice_mobile")[0]){
    		// do not do this on mobile devices, it is very annoying
    		return;
    	}
    	
    	var body = document.body,
        timer;
	
	    window.addEventListener('scroll', function() {
	      clearTimeout(timer);
	      if(!body.classList.contains('disable-hover')) {
	        body.classList.add('disable-hover');
	      }
	      
	      timer = setTimeout(function(){
	        body.classList.remove('disable-hover');
	      },200);
	    }, false);
	    
	    jQuery(".rf-sel-lst-scrl").on('scroll', function() {
		      clearTimeout(timer);
		      if(!body.classList.contains('disable-hover')) {
		        body.classList.add('disable-hover');
		      }
		      
		      timer = setTimeout(function(){
		        body.classList.remove('disable-hover');
		      },50);
		    });
    };
    
    this.refresh = function() {
        this.initWithAjax();
    };
};/* Placeholders.js v3.0.2 */
/*!
 * The MIT License
 *
 * Copyright (c) 2012 James Allardice
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
!function(a){"use strict";function b(){}function c(){try{return document.activeElement}catch(a){}}function d(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return!0;return!1}function e(a,b,c){return a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent?a.attachEvent("on"+b,c):void 0}function f(a,b){var c;a.createTextRange?(c=a.createTextRange(),c.move("character",b),c.select()):a.selectionStart&&(a.focus(),a.setSelectionRange(b,b))}function g(a,b){try{return a.type=b,!0}catch(c){return!1}}function h(a,b){if(a&&a.getAttribute(B))b(a);else for(var c,d=a?a.getElementsByTagName("input"):N,e=a?a.getElementsByTagName("textarea"):O,f=d?d.length:0,g=e?e.length:0,h=f+g,i=0;h>i;i++)c=f>i?d[i]:e[i-f],b(c)}function i(a){h(a,k)}function j(a){h(a,l)}function k(a,b){var c=!!b&&a.value!==b,d=a.value===a.getAttribute(B);if((c||d)&&"true"===a.getAttribute(C)){a.removeAttribute(C),a.value=a.value.replace(a.getAttribute(B),""),a.className=a.className.replace(A,"");var e=a.getAttribute(I);parseInt(e,10)>=0&&(a.setAttribute("maxLength",e),a.removeAttribute(I));var f=a.getAttribute(D);return f&&(a.type=f),!0}return!1}function l(a){var b=a.getAttribute(B);if(""===a.value&&b){a.setAttribute(C,"true"),a.value=b,a.className+=" "+z;var c=a.getAttribute(I);c||(a.setAttribute(I,a.maxLength),a.removeAttribute("maxLength"));var d=a.getAttribute(D);return d?a.type="text":"password"===a.type&&g(a,"text")&&a.setAttribute(D,"password"),!0}return!1}function m(a){return function(){P&&a.value===a.getAttribute(B)&&"true"===a.getAttribute(C)?f(a,0):k(a)}}function n(a){return function(){l(a)}}function o(a){return function(){i(a)}}function p(a){return function(b){return v=a.value,"true"===a.getAttribute(C)&&v===a.getAttribute(B)&&d(x,b.keyCode)?(b.preventDefault&&b.preventDefault(),!1):void 0}}function q(a){return function(){k(a,v),""===a.value&&(a.blur(),f(a,0))}}function r(a){return function(){a===c()&&a.value===a.getAttribute(B)&&"true"===a.getAttribute(C)&&f(a,0)}}function s(a){var b=a.form;b&&"string"==typeof b&&(b=document.getElementById(b),b.getAttribute(E)||(e(b,"submit",o(b)),b.setAttribute(E,"true"))),e(a,"focus",m(a)),e(a,"blur",n(a)),P&&(e(a,"keydown",p(a)),e(a,"keyup",q(a)),e(a,"click",r(a))),a.setAttribute(F,"true"),a.setAttribute(B,T),(P||a!==c())&&l(a)}var t=document.createElement("input"),u=void 0!==t.placeholder;if(a.Placeholders={nativeSupport:u,disable:u?b:i,enable:u?b:j},!u){var v,w=["text","search","url","tel","email","password","number","textarea"],x=[27,33,34,35,36,37,38,39,40,8,46],y="#ccc",z="placeholdersjs",A=new RegExp("(?:^|\\s)"+z+"(?!\\S)"),B="data-placeholder-value",C="data-placeholder-active",D="data-placeholder-type",E="data-placeholder-submit",F="data-placeholder-bound",G="data-placeholder-focus",H="data-placeholder-live",I="data-placeholder-maxlength",J=100,K=document.getElementsByTagName("head")[0],L=document.documentElement,M=a.Placeholders,N=document.getElementsByTagName("input"),O=document.getElementsByTagName("textarea"),P="false"===L.getAttribute(G),Q="false"!==L.getAttribute(H),R=document.createElement("style");R.type="text/css";var S=document.createTextNode("."+z+" {color:"+y+";}");R.styleSheet?R.styleSheet.cssText=S.nodeValue:R.appendChild(S),K.insertBefore(R,K.firstChild);for(var T,U,V=0,W=N.length+O.length;W>V;V++)U=V<N.length?N[V]:O[V-N.length],T=U.attributes.placeholder,T&&(T=T.nodeValue,T&&d(w,U.type)&&s(U));var X=setInterval(function(){for(var a=0,b=N.length+O.length;b>a;a++)U=a<N.length?N[a]:O[a-N.length],T=U.attributes.placeholder,T?(T=T.nodeValue,T&&d(w,U.type)&&(U.getAttribute(F)||s(U),(T!==U.getAttribute(B)||"password"===U.type&&!U.getAttribute(D))&&("password"===U.type&&!U.getAttribute(D)&&g(U,"text")&&U.setAttribute(D,"password"),U.value===U.getAttribute(B)&&(U.value=T),U.setAttribute(B,T)))):U.getAttribute(C)&&(k(U),U.removeAttribute(B));Q||clearInterval(X)},J);e(a,"beforeunload",function(){M.disable()})}}(this),function(a,b){"use strict";var c=a.fn.val,d=a.fn.prop;b.Placeholders.nativeSupport||(a.fn.val=function(a){var b=c.apply(this,arguments),d=this.eq(0).data("placeholder-value");return void 0===a&&this.eq(0).data("placeholder-active")&&b===d?"":b},a.fn.prop=function(a,b){return void 0===b&&this.eq(0).data("placeholder-active")&&"value"===a?"":d.apply(this,arguments)})}(jQuery,this);de.his.modules.CustomizePortalNotification = new function() {
	de.his.modules.ModuleRegistry.registerModule(this);
	
    this.moduleName = "de.his.modules.CustomizePortalNotification";
    
	this.init = function() {
    }

	this.closeCustomizePortalNotification = function() {
		var loginDiv = document.getElementById('portalCustomizationNotification');
		if (loginDiv) {
			loginDiv.className = "noDisplay";
		}
		return false;
	};
	
};use_package( "de.his.modules" );

de.his.modules.ScrollWithMe = new function() {
    var cssSelector = ".scrollWithMe",
        cssClassKeepSize = "scrollWithMe-keepSize",
        cssClass = "scrollWithMe-active";

    de.his.modules.ModuleRegistry.registerModule( this ).registerAjaxRefreshModule( this );
    this.moduleName = "de.his.modules.ScrollWithMe";
    
    this.init = function(containers) {
    	var containers = jQuery( cssSelector );
        for ( var i = 0; i < containers.length; i++ ) {
        	scrollWithMe(containers[i]);
        }
    };
    
    this.refresh = function() {
        de.his.modules.ScrollWithMe.init();
    };

    this.refresSingleContainer = function(selector) {
		let single_element = jQuery(selector);
		scrollWithMe(single_element);
	};

    var scrollWithMe = function( element ) {
    	//console.log("scroll : ", element);
        var container = jQuery( element ),
            containerLeft,
            ovContainerTop,
            containerWidth,
            cssConfig,
            scrollFunction,
            limitInt;
	        //console.log("container scroll : ", container);
	        if ( container.length > 0 ) {
	            // containerLeft = container.offset().left;
	            // containerWidth = container.width();
				if( jQuery('.scrollWithMe-active').length ) {
					jQuery('.scrollWithMe-active').removeClass('scrollWithMe-active');
					ovContainerTop = parseInt( container.offset().top );  
					jQuery('.scrollWithMe').addClass('scrollWithMe-active');
				} 
				else {
	            ovContainerTop = parseInt( container.offset().top );  //parseInt to get whole number
				}
	            
	            scrollFunction = function(){
	            	var win = jQuery( window ),
	                scrollTop = win.scrollTop(),
	                scrollLeft = win.scrollLeft(),
	                containerTop = parseInt( container.offset().top ),
	                newContainerLeft;  //parseInt to get whole number
	            	
	            	if ( de.his.component.overlay && de.his.component.overlay.modalMode ) {
	                	//do nothing when overlay is open
	                	return;
	           		}
	
	            if ( !container.hasClass( cssClass ) ) {
	                //scroller not active

					if ( scrollTop > containerTop && !checkZoom(300) ) {
						// set var if container on top of window
						containerWidth = container.width();
						containerLeft = container.offset().left;
	                	container.parent().css("padding-top", container.outerHeight(true)+2+"px");
	                    container.addClass( cssClass );
	                
	
		                //calculate the left PX when scrolling right in the browser
		                newContainerLeft = containerLeft - scrollLeft
		                newContainerLeft = newContainerLeft < 0 ? 0 : newContainerLeft; //don't let it go below 0
		
		                cssConfig = {
		                    left: newContainerLeft + "px"   //apply new calculation
		                };
						
		                if ( container.hasClass( cssClassKeepSize ) ) {
		                    cssConfig.maxWidth = containerWidth;
		                }
						container.css( cssConfig );
					}
					
	            } else {
	                //scroller is active
	                if ( window.device && window.device.mobile() ) {
	                    //smartphone
	                    limitInt = ovContainerTop + 0;
	                } else {
	                    limitInt = ovContainerTop - 20; //-20 to stop jumping when the browser size hits the boundary of the scroll trigger
	                }
	                //console.log("ovContainerTop scrollTop "+ovContainerTop+":"+scrollTop);
	                limitInt = limitInt >= 0 ? limitInt : 0; //can be minus so set to 0
	                if ( scrollTop <= ovContainerTop ) {
	                    container.removeClass( cssClass );
	                    container.parent().css("padding-top", "");

						// Reset container values
						cssConfig = {
		                    left: '',
							maxWidth: ''
		                };
 						container.css(cssConfig);
	                }
	            }			
            };
            
            //find any containers with the selector
            var containers = jQuery( cssSelector );
            //console.log("scrollWithMe: ", containers);

            de.his.modules.eventRegistry.addListener( "overlayOpen", function() {
                jQuery( containers ).each( function() {
                    //jQuery( this ).removeClass( cssClass );
                	jQuery( this ).css('z-index','998');
                } );
            } );

            de.his.modules.eventRegistry.addListener( "overlayClose", function() {
            	jQuery( containers ).each( function() {
                    //jQuery( this ).removeClass( cssClass );
            		jQuery( this ).css('z-index','999');
                } );
            	
            } );

            //listener for scroll event
            jQuery( window ).off('scroll');
            jQuery( window ).scroll( scrollFunction );
            //listener for zoom event
            jQuery( window ).resize(handleScrollWithMeOnZoom); // prevent search overlay from hiding page content when zoom >= 300%

        }
    };

    var checkZoom = function (zoomLevel) {
      	var browserZoom = window.devicePixelRatio * 100;
      	return browserZoom >= zoomLevel ? true : false;
    }

    var handleScrollWithMeOnZoom = function () {
      	var scrollWithMe = document.querySelector('.scrollWithMe');
      	var hisInOneTitle = document.getElementById('hisinoneTitle');

      	if (scrollWithMe) {
      	  if (checkZoom(300)) { // Zoomlevel in %
      	    scrollWithMe.classList.remove("scrollWithMe-active")
      	  } else {
			// Do not apply style on on top of page, this would cause buttons to disappear above table
      	    if (!isElementInViewport(hisInOneTitle)) {
      	    	scrollWithMe.classList.add("scrollWithMe-active")
			}
      	  }
      	} 
    }
    
    var isElementInViewport = function (el) {
		var rect = el.getBoundingClientRect();

    	return (
    	    rect.top >= 0 &&
    	    rect.left >= 0 &&
    	    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    	    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    	);
	}
};/**
 * RF Picklist
 */
de.his.modules.HisinoneSelectBox = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
    this.moduleName = "de.his.modules.HisinoneSelectBox";
    this.init = function() {
    	//#113538 bugfix
        jQuery(".picklistShuttle, .picklistShuttleButtons").show();
    };

    this.refresh = function() {
        this.init();
    };
	
	// #308501 Barrierefreiheit: Ist das Listenfeld leer und wird dieses mit der Tastatur fokussiert, kann die Seite nicht mehr gescrollt werden
	jQuery(".picklistShuttle > select").on("focus", function(){
		var selectionBox = this;
		selectionBox.addEventListener('keydown', (event) => {
			if(selectionBox.length === 0){
				if (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
				    event.preventDefault();
				    event.stopPropagation();
				}
				return;
			}
		});
	});
	
};use_package("de.his.modules.iFrameCommunication");

/**
 * Author: wahrendorff Date: 08.06.2015 Zweck: ermöglicht der im iframe
 * eingebetteten untrusted Domain der HISinOne Hauptanwendung zu antworten.
 * 
 */

de.his.modules.iFrameCommunication = new function() {
	de.his.modules.ModuleRegistry.registerModule(this)
			.registerAjaxRefreshModule(this);
	
    this.moduleName = "de.his.modules.iFrameCommunication";

	var currentHost;
	var untrustedHost;
	
	if (typeof String.prototype.startsWith !== "function") {
        // see below for better implementation!
        String.prototype.startsWith = function(str) {
            return this.indexOf(str) === 0;
        };
    }
	
	
	var getMessages = function(type) {
		var messages = [];

		jQuery("." + type + "_infobox ul.listMessages > li:not([postedtoparent])").each(function(index, elem) {
			var message = new Object();
			message.text = jQuery(elem).text();
			message.type = type;
			if (message.text !== "") {
				messages.push(message);
			}
			jQuery(elem).attr('postedtoparent', 'true');
		});
		
		var title = "";
		jQuery("." + type + "_infobox h2.messages_infobox_header:not([postedtoparent])").each(function(index, elem) {
			title = jQuery(elem).text();
			jQuery(elem).attr('postedtoparent', 'true');
		});
		
		title = title.trim();
		if(title.charAt(title.length - 1) === ':'){
			title = title.slice(0, -1);
		}
		
		for(var message of messages){
			message.title = title;
		}
		
		console.log("getting " + type + " in iFrame: ", messages);
		return JSON.stringify(messages);
	};
	
	var receiveMessageInIframe = function(event) {
        // check is not needed because H1 can only be iframed by H1
        // also a check is not possible,
        // because there is no possibility to determine on which domain H1 is running

        // if (event.origin !== "https://localhost:8443") {
        // return;
        // }
        if(typeof event.data !== 'string'){
			// unerwartet. 
			// Angular dev tools senden unentwegt ein Object als message, wenn kein Angular Kontext gefunden wird.
			// alles ablehnen, was kein String ist.
			return;
		}
		
		console.log("receiving messages in iFrame: " + event.data);	
		
        if (event.data === "Hello") {
            event.source.postMessage("Hi, there!", event.origin);
        }
        if (event.data === "showMessages") {
			for(var type of ["error", "success", "info", "warning"]){
				var messages = getMessages(type);
            	if(typeof messages !== 'undefined' && messages.trim() !== "[]"){
               		event.source.postMessage(messages, event.origin);
            	}
			}
			event.source.postMessage("resizeMe");
        }
    };
    
    var receiveMessageInParent = function(event) {

        if (event.origin !== currentHost && event.origin !== untrustedHost
                || typeof event.data !== 'string' || event.data.trim() === "") {
            // do not receive Messages if IFrame is neither untrusted domain nor
            // current host
            // this is an important security measure!
            // Do never remove!
            // console.log(event.origin+" !== "+ currentHost, event);
            // console.log("typeof "+event.data+" !== 'string' it is", typeof event.data);
            return;
        }

        console.log("receiving messages in Parent: '" + event.data + "' type: "+(typeof event.data), event);

		if(event.data == "resizeMe"){
			de.his.modules.IframePortletResize.handleResizeWithPortalHelper();
			return;
		}
        
        if(event.data.startsWith("[") && event.data.endsWith("]")){
            var messages = JSON.parse(event.data);
            messages.forEach(function(message, index) {
              console.log(message, index);
            });
            
            var messageTexts = [];
            if(messages.length > 0){
				messages.forEach(message => messageTexts.push(message.text));
            	de.his.component.MessagesInfobox.showMessagesInfoboxWithTitle(messageTexts, messages[0].type, messages[0].title);
            }
            return;
        }
        
		// do not show messages that do not comply with what we expect.
        console.log("message was not from this file and therefore ignored...");
        return;
       
    };
    
    var requestMessagesFromIframe = function(iFrameElement, iFrameHost) {
        console.log("request message from iframe: ",iFrameHost);
        iFrameElement.prop("contentWindow").postMessage("showMessages", iFrameHost);
    };

	this.init = function() {
        
		if (self != top && jQuery("#hisinoneHeader").length == 0) {
			// Site is loaded in an iFrame
			console.log("init postMessages on iFrame...");
			window.addEventListener("message", receiveMessageInIframe, false);
		} else {
			// Site is NOT loaded in an iFrame
			currentHost = window.location.origin;//de.his.common.ContextInformation.get("host");
			untrustedHost = de.his.common.ContextInformation.get("untrustedHost");
            console.log("currentHost: %s",currentHost);
            console.log("untrustedHost: %s",untrustedHost);
			jQuery("iframe").each(
					function() {
						if(jQuery(this).data('initialized') == 'true') return;
						jQuery(this).data('initialized','true');
						var iFrameElement = jQuery(this);
						iFrameElement.on("load", function() {
							// check if an iFrame is loaded with Host or
							// UntrustedHost content
							var url = iFrameElement.attr("src");
							if (typeof url == 'undefined' || url == "") {
                                console.log("iframe url is not valid: ",url);
								return;
							} else if(url.startsWith("http")){
								console.log("iFrame URL: %s", url);
								var urlArray = url.split("://");
								var iFrameHostArray = urlArray[1].split("/");
								// enthält den Port, wenn auch die url den Port enthält
	                            // Das Script im iFrame check die event.origin, in dieser werden Defaultports entfernt,
	                            // daher müssen wir die Defaultports beim message request auch entfernen
	                            // bei "Custom" Ports wie 8080, 8008 oder 8443 müssen die Ports beibehalten werden!
	                            var iFrameHost = urlArray[0];
								var iFrameOriginPortArray = iFrameHostArray[0].split(":");
	                            if(iFrameOriginPortArray[1] == "443" || iFrameOriginPortArray[1] == "80"){
	                                console.log("remove default port(443||80) for iFrame Communication.");
	                                iFrameHost += "://" +  iFrameOriginPortArray[0];
	                            } else {
	                                // keep Port
	                                iFrameHost += "://" + iFrameHostArray[0]; 
	                            }
                            } else{ //in case "url" is a relative url
								iFrameHost = currentHost;
							}
                            console.log("iFrameHost %s",iFrameHost);
							if (iFrameHost == currentHost
									|| iFrameHost == untrustedHost) {

								console.log("init iFrame postMessages on parent...");
								window.addEventListener("message", receiveMessageInParent, false);
								setTimeout(function(){
									requestMessagesFromIframe(iFrameElement, iFrameHost);
								});
							}
							de.his.modules.eventRegistry.fireEvent( "iframe_loaded_" + iFrameElement.attr( "id" ) );
						});
					});
		}
	}

	this.refresh = function() {
		this.init();
		this.resizeInParent();
	}
	
	this.resizeInParent = function(){
		if(typeof parent !== "undefined"){
			console.log("init resize in iframe on parent...");
			try{
				parent.de.his.modules.IframePortletResize.init();
			} catch (e){
				console.error(e);
			}
			
		}
	}

};
/**
 * Author: Daniel Dziegielewski
 * Removes css class singleblock from divs with css classes roomconflict or personconflict
 */
de.his.modules.removeSingleblock = new function() {
    de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.modules.removeSingleblock";

    this.init = function() {
    	jQuery(".singleblock.roomconflict").removeClass("singleblock");
    	jQuery(".singleblock.personconflict").removeClass("singleblock");
    	jQuery(".terminStyleClass.roomconflict").removeClass("roomconflict");
    	jQuery(".terminStyleClass.personconflict").removeClass("personconflict");
    }
    
    this.refresh = function() {
        this.init();
    }
};/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    var special = $.event.special.mousewheel = {
        version: '3.1.12',

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
            // Store the line height and page height for this particular element
            $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
            $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
            // Clean up the data we added to the element
            $.removeData(this, 'mousewheel-line-height');
            $.removeData(this, 'mousewheel-page-height');
        },

        getLineHeight: function(elem) {
            var $elem = $(elem),
                $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
            if (!$parent.length) {
                $parent = $('body');
            }
            return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
        },

        getPageHeight: function(elem) {
            return $(elem).height();
        },

        settings: {
            adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
            normalizeOffset: true  // calls getBoundingClientRect for each event
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0,
            offsetX    = 0,
            offsetY    = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) { return; }

        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data(this, 'mousewheel-line-height');
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data(this, 'mousewheel-page-height');
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );

        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;

            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
                lowestDelta /= 40;
            }
        }

        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);

        // Normalise offsetX and offsetY properties
        if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
            var boundingRect = this.getBoundingClientRect();
            offsetX = event.clientX - boundingRect.left;
            offsetY = event.clientY - boundingRect.top;
        }

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;
        event.offsetX = offsetX;
        event.offsetY = offsetY;
        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

    function shouldAdjustOldDeltas(orgEvent, absDelta) {
        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
    }

}));
use_package("de.his.component");

de.his.component.Swipegesture = new function() {
    de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
    this.moduleName = "de.his.component.Swipegesture";
    this.init = function() { this.swipe(); };

	this.swipe = function(e) {
		let touchstartX = 0;
		let touchstartY = 0;
		let touchendX = 0;
		let touchendY = 0;
		let gestureZone = document.querySelectorAll('.menuItem');
		let deleteStatus = false;

		for (let i = 0; i < gestureZone.length; i++) {
						
			gestureZone[i].addEventListener('touchstart', function(event) {
			    touchstartX = event.changedTouches[0].screenX;
			    touchstartY = event.changedTouches[0].screenY;
			}, false);
			
			gestureZone[i].addEventListener('touchend', function(event) {
			    touchendX = event.changedTouches[0].screenX;
			    touchendY = event.changedTouches[0].screenY;
			    handleGesture(this.querySelector('.menuWrap'));
			}, false); 

			gestureZone[i].addEventListener('touchmove', function(event) {
				if( deleteStatus == true ) {
					return false;
				}
				let touchMoveX = event.changedTouches[0].screenX;
				let newPosX = touchstartX - touchMoveX;
				if(newPosX <= 500 && newPosX >= 0) {
					jQuery(this).children('.menuWrap').css({transform: 'translateX('+-newPosX+'px)', opacity: 1-(newPosX/200)});
				} else if ( newPosX <= 0 )  {
					jQuery(this).children('.menuWrap').css({transform: 'translateX(0px)', opacity: 1});
				}
			}, false);

		}
	
		function handleGesture(item) {

		    if (touchendX < touchstartX && deleteStatus == false) {
				if(touchendX - touchstartX <= -100) {
					deleteStatus = true; 
					jQuery(item).css({transform: '', opacity: ''});
					item.classList.add('deleted');
					jQuery(item).parent().animate({opacity: 0}, 1000);
					item.deleteTimer = setTimeout(function(){
						deleteStatus = false;
						item.querySelector('.iconfont-delete').click();
					}, 1000);	
				}
				else {
					jQuery(item).css({transform: '', opacity: ''});
					deleteStatus = false; 
					item.classList.remove('deleted');
				}
		    }
					    
		    if (touchendX > touchstartX || touchendY === touchstartY) {
				deleteStatus = false; 
				jQuery(item).parent().stop().css({opacity: ''});
				jQuery(item).css({transform: '', opacity: ''});
				item.classList.remove('deleted');
				clearTimeout(item.deleteTimer);
		    }
		    
		    /*if (touchendY <= touchstartY) {
		        console.log('Swiped up');
		    }
		    
		    if (touchendY >= touchstartY) {
		        console.log('Swiped down');
		    }
		    
		    if (touchendY === touchstartY) {
		        console.log('Tap');
		    }*/
		}
	}


    this.refresh = function() {
        this.init();
    };
};use_package( "de.his.common" );

de.his.common.mainnavigation = new function() {

    de.his.modules.ModuleRegistry.registerModule( this ).registerAjaxRefreshModule( this );
    this.moduleName = "de.his.common.mainnavigation";
    
    this.init = function() {
		mainnavigation();
    };

	this.refresh = function() {
		if(!jQuery('.js-opennavoverlay').length){
			de.his.common.mainnavigation.init();
		}
    };
    
	/**  
	* Höhe des Headers erst nach window.load berechenbar
	*/
	jQuery(window).on('load', function(){
		jQuery('#hisinoneHeader').addClass('js-fixed').parent().css({paddingTop:jQuery('#hisinoneHeader').outerHeight()});
	});

    var mainnavigation = function() {	
		var position = 0;
		var resizeTimer;
		
		clickEvent = "click";
		/*if($html.hasClass('touch')) {
			clickEvent = 'touchstart';
		}*/
		
		var $header = jQuery('#hisinoneHeader');
		var $navToggle = jQuery('.navbar-toggle');
		var $body = jQuery('body');
		var $html = jQuery('html');
		var $nav = jQuery('.topMenuContainer .nav');
		var $window = jQuery(window);
		var $navLink = jQuery('.topMenuContainer .parentListItem > a');
		var $navContainer = jQuery('.topMenuContainer');
		var $closeBtn = jQuery('.closeButtonNavigationESC');
		var innerScrollElement = '';
		
		$window.on('resize', function() {
		  clearTimeout(resizeTimer);
		  resizeTimer = setTimeout(function() {
			
			checkScrollnav();
			
		    if( $navToggle.css('display') == 'none' ) {
				position = 0;
				$nav.css('transform', '');
				jQuery('.js-opennavoverlay').remove();
				$body.removeClass('js-navOpen js-navOpenFooter');
				$nav.find('.js-visible').removeClass('js-visible');
				$nav.find('.js-hidden').removeClass('js-hidden');
				$navContainer.css({minHeight:'', height:'', display:''});
				$header.removeClass('js-fixed').parent().css({paddingTop:''});
			} else {
				$header.addClass('js-fixed').parent().css({paddingTop:$header.outerHeight()});
			}
			if( jQuery('#loginLinkElement').css('display') == 'none' && jQuery('#hisinoneHeader .loginStartPage').css('display') == 'none' ) {
				jQuery('#hisinoneHeader .loginStartPage').css({display:''});				
			}
		  }, 250);
		});

		let navigationShown = true;
		let scrollPosition = 0;
		this.defaultTitle = $navToggle.attr('title'); //needs to be set outside of click event handler because title attr is temporarily removed on mouseenter in customtooltip	
		
		function showNavigation() {
		    scrollPosition = window.pageYOffset;
		  	$body.css({top:-scrollPosition + 'px'});
	
			if( $navToggle.parents('#hisinoneFooter').length ) {
				$html.addClass('js-navOpen js-navOpenFooter');
			} else {
				$html.addClass('js-navOpen');	
			}		  	
			jQuery('<div class="js-opennavoverlay" />').appendTo('body');
			
			var newTitle = $navToggle.data('titletoggle');
			$navToggle.attr('title', newTitle).attr('aria-label', newTitle).attr('id', 'mobileOnlyNavBar_open').attr('aria-expanded', 'true');
			$navToggle.data('titletoggle');
			outerClicksCloseMenuHandler();
		}
		
		function removeNavigation() {
			$html.removeClass('js-navOpen js-navOpenFooter');
		  	window.scrollTo(0, scrollPosition);
		    $body.css({top:''});
			jQuery('.js-opennavoverlay').remove();
			$navToggle.attr('title', this.defaultTitle).attr('aria-label', this.defaultTitle).attr('id', 'mobileOnlyNavBar').attr('aria-expanded', 'false');
			position = 0;
			$nav.css('transform', 'translateX(0%)').find('li').removeClass('js-visible js-active js-hidden');
			setTimeout(function(){
				$header.removeClass('js-hide');
				if( jQuery('.scrollWithMe').length || jQuery('[appscrollwithme]').length ) {
					var $scrollWithMe = jQuery('.scrollWithMe, [appscrollwithme]');
					if( $scrollWithMe.hasClass('scrollWithMe-active') ) {
						var headerHeight = $header.outerHeight();
						$scrollWithMe.css({top:headerHeight});			
					}
				}
			});
		}
		
		function outerClicksCloseMenuHandler(){
	    	// hide slidedown menues when user clicks somewhere else in the page
			jQuery('.js-opennavoverlay,#hisinoneHeader,#hisinoneFooter').off(clickEvent).on(clickEvent, function (e) {
//				console.log('clicked somewhere..', jQuery(e.target));
				
				if ( jQuery('html').hasClass('js-navOpen') && jQuery(e.target).closest('#topMenuContainerId').length == 0
				    && !jQuery(e.target).hasClass("navbar-toggle")
            		&& !jQuery(e.target).hasClass("burger_navigation")
            		&& jQuery(e.target).is(':visible') ) {
		            		
	            	$navToggle.trigger(clickEvent);
	            	
	            }
	        });
	    }
		
		$navToggle.off(clickEvent).on(clickEvent, function(){
			navInit();
			checkScrollbar();
			var $this = jQuery(this);
			$navContainer.toggle('slide', 200);
			$this.toggleClass('js-open');
			if (navigationShown) {
				showNavigation();
			} else {
				removeNavigation();
			}
			$this.trigger("updateTooltip");
			closeNavigationButton();
			navigationShown = !navigationShown;
		});
		
		$navLink.off(clickEvent).on(clickEvent, function(){
			if( $navToggle.css('display') == 'block' ) {
				var $this = jQuery(this);
				$navContainer.find('.js-active').removeClass('js-active');
				$this.closest('li').addClass('js-visible js-active');
				$this.closest('li').parent().children('li:not(.js-visible)').addClass('js-hidden');
				var activeHeight = $this.closest('li').children('ul').height();
				if( jQuery('#searchMenuExtContainer_inNav').css('display') == 'block' ) {
					var mobileNavSearchHeight = jQuery('#searchMenuExtContainer_inNav').outerHeight();
					activeHeight= activeHeight+mobileNavSearchHeight;
				}
				$closeBtn.css('top', activeHeight);
				$navContainer.scrollTop(0);
				position = position-100;
				$nav.css('transform', 'translateX('+position+'%)');
				setTimeout(function(){
					jQuery($this.next('ul').children('.navitem-headline').children()).focus();
				},100);
				return false;
			}
		});
		jQuery('.backButton').off(clickEvent).on(clickEvent, function(){ 
			var $this = jQuery(this);
			$this.closest('.js-visible').parent().children('.js-hidden').removeClass('js-hidden');
			$this.closest('.js-visible').removeClass('js-visible js-active');
			$this.closest('.js-visible').addClass('js-active');
			position = position+100;
			$nav.css('transform', 'translateX('+position+'%)');
			if( $this.closest('.parentListItem').closest('ul').children('.navitem-headline').children().length ) {
				$this.closest('.parentListItem').closest('ul').children('.navitem-headline').children().focus();
				var activeHeight = $this.closest('.js-visible').children('ul').height();
			}
			else {				
				$this.closest('.parentListItem').children('a').focus();
				var activeHeight = $nav.height();
			}
			if( jQuery('#searchMenuExtContainer_inNav').css('display') == 'block' ) {
					var mobileNavSearchHeight = jQuery('#searchMenuExtContainer_inNav').outerHeight();
					activeHeight= activeHeight+mobileNavSearchHeight;
				}
			$closeBtn.css('top', activeHeight);
			return false;	
		});
//		$body.off(clickEvent).on(clickEvent, '.js-opennavoverlay', function(){
//			$navToggle.trigger(clickEvent);
//		});
						
		function navInit() {
			$navContainer.css({minHeight: '', height: ''});
			var headerHeight = $header.outerHeight();
			var footerHeight = jQuery('#hisinoneFooter').outerHeight();
			var winHeight = window.innerHeight;
			
			if( $navToggle.parents('#hisinoneFooter').length ) {
				var newNavHeight = winHeight - headerHeight-footerHeight;	
			} else {
				var newNavHeight = winHeight - headerHeight;
			}			
			$navContainer.css({height: newNavHeight + 'px', top:headerHeight});
		}
		function checkScrollbar(){
		    var $body = jQuery("body");
		    var previousWidth = null;
		    var currentWidth = $body.width();
		    if (currentWidth != previousWidth) {
		        previousWidth = currentWidth;        
		        $body.css("overflow", "hidden");
		        var scrollBarWidth = $body.width() - currentWidth;
		        $body.css("overflow", "auto");
		        $body.css("padding-right", scrollBarWidth + "px");     
				jQuery('#logoAndServicesHeader').css("padding-right", scrollBarWidth + "px");
		        $body.css("overflow", "");
		    }
		
		};
		
		var old_scroll_top = 0, delta = 5;
		$window.on('scroll', function(e){
			
			var current_scroll_top = jQuery(document).scrollTop();
			if( current_scroll_top == 0 ) {
				$header.removeClass('js-hide');
			}
			if(Math.abs(old_scroll_top - current_scroll_top) <= delta) {
	        	return;
			}
			if( $navToggle.css('display') == 'block' ) {
				var scroll_delta = current_scroll_top - old_scroll_top;
				if( !$html.hasClass('js-navOpen') ){
					if( scroll_delta <=0 ){						
						$header.removeClass('js-hide');
						var headerHeight = $header.outerHeight();
						if( jQuery('.scrollWithMe').length || jQuery('[appscrollwithme]').length ) {
							var $scrollWithMe = jQuery('.scrollWithMe, [appscrollwithme]');
							if( $scrollWithMe.hasClass('scrollWithMe-active') ) {
								$scrollWithMe.css({top:headerHeight});
							} else {
								$scrollWithMe.css({top:''});
							}
						}
						// Wenn der sticky Tabellenheader voranden ist, dann die Höhe vom SeitenHeader um den Tabellenheader runterschieben beim Hochscrollen, außer der feste Tabellenheader befindet sich in einem festen Seitenbereich innerhalb welchem nochmal gescrollt werden kann (zwei vertikale Scrollbalken auf der Seite)
                        if( jQuery('.tableStickyHeader').length) {
                            jQuery('.tableStickyHeader').find('th').css({top:headerHeight});

                            if(  jQuery('.scrollwithmeWrapper').length ) {
                                var scrollHeight = jQuery('.scrollwithmeWrapper').children('.scrollWithMe-active').outerHeight();
                                jQuery('.tableStickyHeader').find('th').css({top:scrollHeight+headerHeight});
                            }
                            if(  jQuery('.scrollWithMe').length ) {
                                var scrollHeight = jQuery('.scrollWithMe').outerHeight();
                                jQuery('.tableStickyHeader').find('th').css({top:scrollHeight+headerHeight});
                            }
                            $(innerScrollElement).find('th').css({top:0});

                        }
					}
					else { 
						if( navigator.webdriver != true && current_scroll_top > 100  && !$header.find('.widgetPanelDiv').length && $header.find('.popoverContainer').css('display') != 'block' ) {
							$header.addClass('js-hide');
						}
						if( jQuery('.scrollWithMe-active').length ) {
							if( navigator.webdriver == true ) {
								var headerHeight = $header.outerHeight();
								jQuery('.scrollWithMe-active').css({top:headerHeight});
							} else {
								jQuery('.scrollWithMe-active').css({top:''});
							}
						}
						if( jQuery('.tableStickyHeader').length ) {
                            jQuery('.tableStickyHeader').find('th').css({top:''});
                            
                            if(  jQuery('.scrollwithmeWrapper').length ) {
                                var scrollHeight = jQuery('.scrollwithmeWrapper').children('.scrollWithMe-active').outerHeight();
                                jQuery('.tableStickyHeader').find('th').css({top:scrollHeight});
                            }
                            if(  jQuery('.scrollWithMe').length ) {
                                var scrollHeight = jQuery('.scrollWithMe').outerHeight();
                                jQuery('.tableStickyHeader').find('th').css({top:scrollHeight});
                            }
                            
                        }
					}					
				}
								
				old_scroll_top = current_scroll_top;
			}
		});
		
		$('.tableStickyHeader').parent().on('scroll', function(e){
            jQuery('.tableStickyHeader').find('th').css({top:0});
            innerScrollElement = this;
		});
		
		window.addEventListener("orientationchange", function(){
			if($navToggle.hasClass('js-open')) {
				setTimeout(function(){
					navInit();
				}, 100);
			}
		});
		
		
		// LOGIN TOGGLE HEADER
		jQuery('.loginToggle').off(clickEvent).on(clickEvent, function(e){
			e.preventDefault();
			jQuery('.loginStartPage').slideToggle();
			if(jQuery('.loginToggle').attr("aria-pressed") == "true"){
				jQuery('.loginToggle').attr("aria-pressed", "false");
			} else {
				jQuery('.loginToggle').attr("aria-pressed", "true");
			}
		});
				
		function checkScrollnav() {
			if( jQuery('.navband').length != 0 ) {
				var initContainerWidth = jQuery('.navband')[0].scrollWidth;
				var initWrapWidth = jQuery('.navbandWrap').outerWidth()+10;
				if( initContainerWidth < initWrapWidth ) {
					jQuery('.navbandArrow').hide();
				} else {
					jQuery('.navbandRight').show();
				}
			}
		}checkScrollnav();
		num = 1;
		jQuery('.navbandArrow').off('mouseenter').on('mouseenter', function(){
			var $this = jQuery(this);
			incInterval= setInterval(function(){
				if( $this.hasClass('navbandRight') ) {
    				var pos = jQuery('.navband').scrollLeft() + num;
				} else {
					var pos = jQuery('.navband').scrollLeft() - num;
				}
    			jQuery('.navband').scrollLeft(pos);
				var curPos = jQuery('.navband').scrollLeft();
				var containerWidth = jQuery('.navband')[0].scrollWidth;
				var wrapWidth = jQuery('.navbandWrap').outerWidth();
				var scrollWidth = containerWidth - wrapWidth;
				if( curPos > 0 ) {
					jQuery('.navbandLeft').show();
				} 
				if( curPos == 0 ) {
					jQuery('.navbandLeft').hide();
				} 
				if( curPos+5 >= scrollWidth ) {
					jQuery('.navbandRight').hide();
				}
				if( curPos+5 < scrollWidth ) {
					jQuery('.navbandRight').show();
				}
		      	num++;	
			},50);
		}).mouseleave( function(){ 
			clearInterval(incInterval); 
		});
		
		function closeNavigationButton(){
			if( navigationShown ) {								
				var activeHeight = $nav.height();
				if( jQuery('#searchMenuExtContainer_inNav').css('display') == 'block' ) {
					var mobileNavSearchHeight = jQuery('#searchMenuExtContainer_inNav').outerHeight();
					activeHeight= activeHeight+mobileNavSearchHeight;
				}
				$closeBtn.css('top', activeHeight);
				$closeBtn.addClass('simple-close-button-behavior');
			} else {
				$closeBtn.removeClass('simple-close-button-behavior');
				$navToggle.focus();
			}
			$closeBtn.off('click').on('click', function(e){
				e.preventDefault();
				$navToggle.trigger('click');
			});
		}
		
		function navigationLoopEvent(){
			$closeBtn.off('keydown').on('keydown', function(e) {
				if (e.key === 'Tab' || e.keyCode === 9) {
					if( !$navContainer.find('.topMenuList').hasClass('js-hidden') ) {					
						var $firstVisibleLink = $navContainer.find('.topMenuList a').first();
					} else {
						var $firstVisibleLink = $navContainer.find('li.js-active').children('ul').find('a').first();
					}
					$firstVisibleLink.focus();
					e.preventDefault();
				}
			});
		}navigationLoopEvent();
		
	}
	

};



/*****************************************************************************/
// Provides a jQuery plugin for a simple sticky component.
// The component scolls with the window until a given margin to the op is reached, then it is fixed.
// Author: Dennis Hörsch
//
// The component must have an Id!
// OPTIONS (required):
//  - start: The distance from the top the effect should start
//  - margin: The distance to the top in case the effect is 'on'
/** *************************************************************************** */
(function(jQuery) {
	var stickyScrollables = [];
    
    jQuery.fn.stickyScrollable = function(options) {
        var component = jQuery(this),

            componentId = component.attr('id'),
        
            // Store initial values
            top = component.css('top'),
            left = component.css('left'),
            right = component.css('right'),

            scrollingBase = jQuery(options.scrollingBase ? options.scrollingBase : window),

            componentScrollingCss = {
	            position : 'absolute',
	            top : options.start,
	            left : left,
	            right : right
            },
            componentFixedCss = {
	            position : 'fixed',
	            top : options.margin,
	            left : left,
	            right : right
           	},
           	
            scrollingHandler = function() {
                var scroll = scrollingBase.scrollTop() + options.margin;

                // Wenn das Scrolling kleiner als die gewünschte Abstand zum top, dann ist die component fixiert.
                // Ansonsten ist sie absolut positioniert, so dass sie mitscrollt.
                if (scroll < options.start) {
                    component.css(componentScrollingCss);
                } else {
                    component.css(componentFixedCss);
                }
            };

        unStickyScrollable(component, componentId, scrollingBase);
            
        // First call to initialize position
        scrollingHandler();

        scrollingBase.scroll(scrollingHandler);

        stickyScrollables[componentId] = {
        	handler: scrollingHandler
        };
        
        return component;
    };

    var unStickyScrollable = function(component, componentId, scrollingBase) {
        var stickyScrollableData = stickyScrollables[componentId]; 
        
        if (stickyScrollableData) {
        	scrollingBase.unbind('scroll', stickyScrollableData.handler);
	        delete stickyScrollables[componentId];
    	}
    };
}(jQuery));/*****************************************************************************/
// Provides a jQuery plugin to 'auto close' a component.
// After a timeout the component fades out. If the mouse enters the component the fadings stops and the component is shown. On leaving the timeout starts again.
// Author: Dennis Hörsch
//
// The component must have an Id!
// OPTIONS (optiona):
//  - timeout: default is 4000 ms
//  - fadeOutTime: default is 2500 ms
//  - fadeInTime: default is 500 ms
//  - callbackOnHidden: no default
/** *************************************************************************** */
(function(jQuery) {
    var defaultOptions = {
            timeout:          4000,
            fadeOutTime:      2500,
            fadeInTime:       500,
            callbackOnHidden: undefined
    };

    jQuery.fn.autoClosing = function(params) {
    	if(jQuery('.messages-infobox-behavior.occassionalUser').length == 0){
	        var component = jQuery(this),
	            options = jQuery.extend({}, defaultOptions, params),
	
	            createTimeout = function() {
	                return setTimeout(function() {
	//                    component.fadeOut(options.fadeOutTime, fadeOutComplete);
	                    component.css({
	                    	marginRight: "-300px",
	                    	opacity: 0,
	                    	transition: "all 1s ease-in"
	                    }).addClass('hideWhenClosed');
	                    setTimeout(fadeOutComplete, 1000);
	                }, options.timeout)
	            },
	            
	            fadeOutComplete = function() {
	                component.unbind('mouseenter', mouseEnterHandler);
	                component.unbind('mouseleave', mouseLeaveHandler);
	            	options.callbackOnHidden();
	            },
	            resetAutoClosing = function() {
	                clearTimeout(autoClosingHandle);
	                component.unbind('mouseenter', mouseEnterHandler);
	                component.unbind('mouseleave', mouseLeaveHandler);  
	                
	                component.data('__autoClosing', null);
	                component.data('__resetAutoClosing', null);
	            },
	            
	            mouseEnterHandler = function() {
	                clearTimeout(autoClosingHandle);
	                component.stop().show().animate({'opacity': '1.0'}, options.fadeInTime);
	            },
	            mouseLeaveHandler = function() {
	                autoClosingHandle = createTimeout();
	            },
	            autoClosingHandle = createTimeout();
	            
			options.timeout /= 2.0;
			options.fadeOutTime /= 2.0;    
	
	        component.mouseenter(mouseEnterHandler);
	        component.mouseleave(mouseLeaveHandler);
	
	        component.data('__autoClosing', true);
	        component.data('__resetAutoClosing', resetAutoClosing);
	        
	        return component;
    	}
    };

    jQuery.fn.unAutoClosing = function() {
        var component = jQuery(this);
        if (component.data('__autoClosing')) {
        	component.data('__resetAutoClosing')();
        }
    	return component;
    };
}(jQuery));use_package("de.his.ajax");

/**
 * Re-initializes some modules after an AJAX request.
 * Usage: f:ajax onevent="de.his.ajax.Refresher.onEvent" onerror="de.his.ajax.Refresher.onError"
 * Is added automatically to all ajax-Behaviors, manually created or automatically, i.e. for refresh buttons.
 *
 * Modules to be refreshed need a method 'refresh'.
 *
 */
de.his.ajax.Refresher = new function() {

    this.onEvent = function(data) {   	
        switch (data.status) {
            /* status (JSF 2.1 spec, 14.4.1):
             * begin     Occurs immediately before the request is sent.
             * complete  Occurs immediately after the request has completed.
             *           For successful requests, this is immediately before javax.faces.response is called.
             *           For unsuccessful requests, this is immediately before the error handling callback is invoked.
             * success   Occurs immediately after jsf.ajax.response has completed.
             */
            case "begin":
            	console.log("[.ajax] begin: %s", data.source.id);            	
                ajaxBegin();
                break;
            case "complete":
               	console.log("[.ajax] complete: %s", data.source.id);
            	de.his.modules.eventRegistry.fireEvent("refresherComplete");
            	// hiermit werden fertige AJAX Calls global "sichtbar", sodass auf dieses Event reagiert werden kann
            	// Dies ist beispielsweise beim messen der clientseitigen Performanz notwendig.
            	jQuery(document).trigger('ajaxComplete');
                break;
            case "success":
            	if (isAjaxRedirect(data)) {
                	console.log("[.ajax] success redirect: %s", data.source.id);
            		break;
            	}
            	
            	console.log("[.ajax] success: %s", data.source.id);
	            ajaxEnd(data);
	            de.his.modules.eventRegistry.fireEvent("refresherSuccess");        		
               	break;
        }
    };

    var ajaxBegin = function() {
		de.his.modules.ModuleRegistry.indicateAjaxRequestStart();
    };

    var ajaxEnd = function(data) {
    	if (data.responseCode == 403) { // Access denied: force redirect, as a result the access-denied page is shown
    		window.location = window.location;
        }
        de.his.modules.ModuleRegistry.refreshAll(data);
    };

    this.onError = function(data) {
        /* status (JSF 2.1 spec, 14.4.2):
         * httpError     request status==null or request.status==undefined or request.status<200 or request.status >=300
         * serverError   The Ajax response contains an “error” element.
         * malformedXML  The Ajax response does not follow the proper format. See Section 1.4 "XML Schema Definition for Partial Responses"
         * emptyResponse There was no Ajax response from the server.
         */

        // TODO: Refresh, ansonsten ist die Oberfläche / Serverzustand evtl. inkonsistent.
        //
        // Die JavaScript-Fehlermeldung wird per AJAX verschickt und serverseitig protokolliert.
        // Weil die Fehlermeldung sehr lang werden kann (z. B. kann ajax.responseText enthalten
        // sein), muss POST verwendet werden.
        
        
        // Fehler, die beim Verlassen der Seite auftreten unterdrücken
		if (isPageUnloading == true) {
			return;
		}
	
    	console.log("[.ajax] error: %s", data.source.id);
    	var url = de.his.common.ContextInformation.get('context-path') + '/pages/cs/sys/error/error.faces?code=500&ajax=true';
        var form = new FormData();
        form.append('ajaxerror', JSON.stringify(data));
        jQuery.ajax({
            type : "POST",
            url : url,
            cache : false,
            contentType : false,
            processData : false,
            data : form,
            async : true,
            success : function(html) {
        	// alert(JSON.stringify(data));
            }
        });       
        disableWaitingBahaviour();
        showErrorToUser(data);
    };
    
    this.onErrorIgnore = function(data) {
    	console.log("[.ajax] errorignore: %s", data.source.id);    
    	disableWaitingBahaviour();
    };

    this.wrapOnEvent = function(onevent) {
        return wrapInternal(this.onEvent, onevent);
    };

    this.wrapOnError = function(onevent) {
        return wrapInternal(this.onError, onevent);
    };
    
    var disableWaitingBahaviour = function(){
    	de.his.modules.Waiting.resetWaitingBehaviour();
    }
    
    var showErrorToUser = function(data){
    	var errorMessage = getErrorText(data.status);
    	
    	if(data.status === "serverError"){
    		errorMessage += data.serverErrorMessage + " " + data.serverErrorMessage;
    	}
    	
    	de.his.component.MessagesInfobox.showMessagesInfobox(errorMessage,'error');
    }

    var wrapInternal = function(handler, onevent) {
        return function(data) {
            onevent(data);
            handler(data);
        };
    };
    
    
    var isAjaxRedirect = function(data) {
    	return (data.responseCode == 200) && (data.responseText.contains("<redirect url="));
    }
    
    var errorTexts = {
        de:{
            _title: "AJAX-Fehler:",
            malformedXML: "Das zurückgelieferte XML-Response-Objekt ist fehlerhaft aufgebaut.",
            serverError: "Auf dem Server ist ein Fehler aufgetreten.",
            clientError: "Das Javascript ist fehlerhaft.",
            httpError: "Ein unerwarteter Netzwerkfehler ist aufgetreten.",
            emptyResponse: "Die Antwort des Servers war leer.",
            _error: "Der Server antwortet nicht.",
            offline: "<div class='offlineContainer'>Ihre Internetverbindung ist unterbrochen, die Anwendung kann möglicherweise nicht vollständig genutzt werden.</div>"
        },
        en: {
            _title: "AJAX-Error:",
            malformedXML: "XML response is malformed.",
            serverError: "Server returned an error.",
            clientError: "The Javascript has errors.",
            httpError: "An unexpected network failure occured.",
            emptyResponse: "Server response was empty.",
            _error: "The Server does not answer requests.",
            offline: "<div class='offlineContainer'>Your internet connection seems to be down, this application may not respond properly if no connection is established.</div>"
        }
    };
    
    var getErrorText = function(status){
    	var lang = de.his.common.LanguageHelper.currentLanguage();
    	
    	if( !errorTexts[lang] ){
    	    //default language
    	    lang = "de";
    	}
    	
    	return (errorTexts[lang][status] || errorTexts[lang]._error);
    };

    window.addEventListener("offline", function(e) {
            alert( getErrorText( "offline" ) );
    }, false);
};

/**
 * Used i.e. in HIS_DEVELOPMENT-Modus to show a detailed error message.
 * @param data
 */
de.his.ajax.Helper = new function() {
    this.callHandlerIfPhase = function(data, phase, handler, scope) {
        console.log("AJAX status: " + data.status);
        if (data.status === phase) {
        	if(scope){
        		handler.apply(scope, data);
        	}else{
        		handler(data);	
        	}
        }
    };

    this.debugAjaxRequest = function(data) {
        if (data.responseCode == 403) { // Access denied: Handled in refresh above
            return;
        }
        var debugText = "";
        debugText += "<b>source.id:</b> " + data.source.id + "<br/>";
        debugText += "<b>responseCode:</b> " + data.responseCode + "<br/>";
        debugText += "<b>status:</b> " + data.status + "<br/>";
        debugText += "<b>serverErrorName:</b> " + data.serverErrorName + "<br/>";
        debugText += "<b>serverErrorMessage:</b> " + data.serverErrorMessage + "<br/>";

        debugText += "<b>responseText:</b><br/>" + data.responseText + "<br/>";
        
        alert("<h1>AJAX Error occured</h1>","Server is in HIS_DEVELOPMENT Mode and AJAX Error occured.<br/>You can ignore this message if you are not developing new AJAX features and just clicked any navigation link.<br/><br/>Here is your AJAX Error object:<br/><br/> "+debugText);
    };
};


/*
Die Möglichkeit schaffen, Verarbeitung zu unterdrücken, wenn die Seite gerade verlassen wird.
*/

var isPageUnloading = false;

jQuery(window).on("beforeunload",
	function() {
		isPageUnloading = true;
	}
);

use_package("de.his.ajax");

/**
 * JS-Funktionen zur Ajax-Funktion: Header einklappen
 */
de.his.ajax.ToggleHeader = new function() {
	
	var newValue, oldValue;
	
	//Wenn das togglen des Header abgeschlossen ist
    this.processEvent = function(data) {
    	
    	if (data.status == "success") {
    		jQuery('#wrapper_no_background').toggleClass('reducedHeader');
    		
    		//This ugly hack is required as styleClass is not always refreshed when using an #{} EL to define the value
    		//also: when it does change the value using the #{} EL it only does it once!
    		//TODO: is this needed in versions > JSF 2.0
    		var btn = jQuery('li.plusIconElement input.toggleIcon');
    		if(btn.length > 0 ){
    			if(!newValue && !oldValue){
    				if(btn.hasClass("minusIcon")){
    					oldValue = "minusIcon";
        				newValue = "plusIcon";
        				btn.removeClass(oldValue);
        				btn.addClass(newValue);
        			}else if(btn.hasClass("plusIcon")){
        				oldValue = "plusIcon";
        				newValue = "minusIcon";
        				btn.removeClass(oldValue);
        				btn.addClass(newValue);
        			}
    			}else{
    				btn.removeClass(newValue);
    				btn.addClass(oldValue);
    				var a = oldValue;
    				oldValue = newValue;
    				newValue = a;
    			}
    			
    		}
			
			setTimeout(function(){
				jQuery('#hisinoneHeader').parent().css({paddingTop:jQuery('#hisinoneHeader').outerHeight()});
			});			
			
    	}
    	try {
    		var fix = jQuery(".content_portal_hisinone_fixed");
    		if (fix && fix.length > 0) {
    			resizeHeader();
    		}
    	} catch (e) {
    		//Nur bei fixem Layout vorhanden
    	}
    };
};
use_package("de.his.common");

de.his.common.embedded = new function() {
	de.his.modules.ModuleRegistry.registerModule(this)
	.registerAjaxRefreshModule(this);
	this.moduleName = "de.his.common.embedded";
	
	this.init = function() {
		this.setCssClassIfHisinoneIsEmbedded();
	};
	
	this.refresh = function() {
		this.setCssClassIfHisinoneIsEmbedded();
	};
	
	/**
	 * Setzt eine CSS-Klasse, wenn HISinOne in einem IFrame läuft
	 */
	this.setCssClassIfHisinoneIsEmbedded = function() {
		var body = jQuery("body");
	    try {
	        if (window.self !== window.top) {
	        	body.addClass("embedded");
	        }
	    } catch (e) {
	    	//Auch im Fehlerfall läuft HISinOne in einem IFrame
	    	body.addClass("embedded");
	    }
	};
};use_package("de.his.common");

de.his.common.linkTargetAsOverlay = new function() {
	de.his.modules.ModuleRegistry.registerModule(this)
	.registerAjaxRefreshModule(this);
	this.moduleName = "de.his.common.linkTargetAsOverlay";
	
	this.init = function() {
		this.setLinkTargetAsOverlayOnClick();
	};
	
	this.refresh = function() {
		this.setLinkTargetAsOverlayOnClick();
	};
	
	/**
	 * Setzt eine CSS-Klasse, wenn HISinOne in einem IFrame lÃ¤uft
	 */
	this.setLinkTargetAsOverlayOnClick = function() {
		 try {
			jQuery('a.targetAsPopup').off('click');
			jQuery('a.targetAsPopup').on('click',function(){
				console.log("targetAsPopup klick!");
				var url =  jQuery(this).attr('href');
				var left = (screen.width/2)-(screen.width/4);
				var top = (screen.height/2)-(screen.height/4);
				var css = 'width=' + (screen.width/2) + ', height=' + (screen.height/2) + ', resizeable, scrollbars, top=' + top + ', left=' + left + '';
				if(typeof(winRef) == 'undefined' || winRef.closed){
					// neues Popup
					winRef = window.open(url, 'targetAsPopup', css);
				} else {
					// Erneuere die URL und hole Popup in Focus
					winRef.location.href = url;
					winRef.focus();
				}
				return false;
			});
			 
			jQuery('a.targetBrowserBack').off('click');
			jQuery('a.targetBrowserBack').on('click', function(){
				console.log("klick!");
				window.history.back();
			});
			 
			jQuery('a.targetAsOverlay').off('click');
			jQuery('a.targetAsOverlay').on('click', function(){
				console.log("linkAsOverlay: Klick");
				var iframeSrc = jQuery(this).attr('href');
				var iframeTitle = jQuery(this).text();
				console.log("iframeSrc: " + iframeSrc);
				console.log("iframeTitle: " + iframeTitle);
				
				jQuery('#linkTargetAsOverlayForm').append('<input type="hidden" id="overlayTitle" name="overlayTitle" value="' + iframeTitle + '" />');
				
				jQuery('#linkTargetAsOverlaySrc').attr('value',iframeSrc)
				jQuery('#linkTargetAsOverlayForm').show();
				jQuery('#linkTargetAsOverlayForm\\:linkTargetAsOverlayPlaceholder\\:overlayShowButton').hide();
			    jQuery('#linkTargetAsOverlayForm\\:linkTargetAsOverlayPlaceholder\\:overlayShowButton').click();
			    return false;
			});
			
			//Wurde das Overlay aktiviert?
			if (jQuery('#iframePlaceholder').length) {
				//Nur weiter machen, wenn es noch kein Iframe im Overlay gibt
				if (!jQuery('#linkTargetAsOverlayPlaceholderIframe').length) {
					//Title setzen
					var overlayTitle = jQuery('#overlayTitle').attr('value');
					console.log("overlayTitle: " + overlayTitle);
					jQuery('#linkTargetAsOverlayForm\\:linkTargetAsOverlayPlaceholder\\:overlayPlaceholder .box_title h2').text(overlayTitle);
					
					//Ziel-URL extrahieren
					var iframeSrc = jQuery('#linkTargetAsOverlaySrc').attr('value');
					console.log("linkTargetAsOverlaySrc: " + iframeSrc);
					
					//Höhe für Inhalt holen
					var overlayContentHeight = Math.floor(window.innerHeight * 0.80) - 181;
					console.log("overlayContentHeight: " + overlayContentHeight);
					
					//IFrame hinzufügen
					var iframePlaceholder = jQuery('#iframePlaceholder');
					iframePlaceholder.append('<iframe style="border:0px;width:100%;height:'+overlayContentHeight+'px" class="frame" id="linkTargetAsOverlayPlaceholderIframe" src="#" title="Overlay">Iframe</iframe>');
					
					//URL setzten
					jQuery('iframe#linkTargetAsOverlayPlaceholderIframe').attr('src', iframeSrc);
					
					//Laden
					jQuery('iframe#linkTargetAsOverlayPlaceholderIframe').ready(function() {
				    	console.log("resizeIt");
				    	//resizeIt(jQuery("#linkTargetAsOverlayPlaceholderIframe"));
				    });
				} 
			}
	   
	    } catch (e) {
	    	console.log(e)
	    }
	};
};use_package("de.his.common");

de.his.common.embedded = new function() {
	de.his.modules.ModuleRegistry.registerModule(this)
	.registerAjaxRefreshModule(this);
	this.moduleName = "de.his.common.portalUtil";
	
	this.init = function() {
		this.execFunctions();
	};
	this.refresh = function() {
		this.execFunctions();
	};
	
	/**
	 * Setzt eine CSS-Klasse, wenn HISinOne in einem IFrame lÃ¤uft
	 */
	this.execFunctions = function() {
		 try {
			//In HTML-Portlets eine Zurückfunktion ermöglichen - nur bei Mehrfachverwendung einer Portletverlinkung (Deeplink) nutzen 
			jQuery(document).ready(function () {
				jQuery('a.targetBrowserBack').click(function(){
					console.log("klick!");
					window.history.back();
				});
			});   
	    } catch (e) {
	    	console.log(e)
	    }
	};
};/**
 * Author: Evelyn Elsner
 * 
 */
de.his.modules.Menutabs = new function() {
    de.his.modules.ModuleRegistry
		.registerModule(this)
		.registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.modules.Menutabs";

    this.init = function() {
		this.activeTabHandling();
		jQuery('.tabButton.active').css('cursor','pointer');
    };
    
    this.refresh = function() {	
		this.activeTabHandling();
    };
	
	this.activeTabHandling = function(){
		if(!jQuery('.responsive_tab.mikronavi_submit > ul > li:first-child button.tabButton').hasClass('active') && jQuery(window).width() <= 768 || window.localStorage.getItem("firstLinkActivationCount") == 1){
			window.localStorage.setItem("firstLinkActivationCount", 0);
			jQuery('.responsive_tab.mikronavi_submit ~ div, .responsive_tab.mikronavi_submit + h2').css('display', 'block');
			jQuery('.responsive_tab.mikronavi_submit').css('display', 'none');
			
			jQuery('.backButtonTabSmallView').css('display', 'inline');
			//jQuery('button.backButtonResponsive:not(.backButtonTabSmallView)').attr('onclick', "return false");
			
			if(jQuery('.backButtonTabSmallView').is(":visible")){
			   jQuery('.backButtonResponsive.submit.immediate').css('display', 'none');
			} 
		}
		if(window.localStorage.getItem("firstLinkActivationCount") == 0 && jQuery(window).width() > 768){
			jQuery('.responsive_tab.mikronavi_submit').css('display', 'block');
			jQuery('.backButtonTabSmallView').css('display', 'none');
			jQuery('.backButtonResponsive.submit.immediate').css('display', 'inline-block');
		}
		if (jQuery(window).width() <= 768 && jQuery('.responsive_tab.mikronavi_submit').css('display') == 'block') {
			jQuery('.responsive_tab.mikronavi_submit ~ div, .responsive_tab.mikronavi_submit + h2').css('display', 'none');
		}
		
	}
	
	// Klick auf den ersten Tab, der standardmäßig aktiv ist -> Nach Request soll noch bekannt sein, dass dieser geklickt wurde, deshalb Klick im Storage speichern
	jQuery('.responsive_tab.mikronavi_submit > ul > li:first-child button.tabButton').on("click", function(){
		var firstLinkActivationCount = parseInt(window.localStorage.getItem("firstLinkActivationCount")) + 1;
	  	window.localStorage.setItem("firstLinkActivationCount", firstLinkActivationCount);
	});
		
	this.disableBackButton = function(){
		if(jQuery('.responsive_tab.mikronavi_submit').is(":visible")){
			jQuery('.backButtonTabSmallView').css('display', 'none');
		}
	}
};

jQuery(window).resize(function() {
	if(jQuery(window).width() > 768){
		jQuery('.responsive_tab.mikronavi_submit ~ div, .responsive_tab.mikronavi_submit + h2').css('display', 'block');
		jQuery('.responsive_tab.mikronavi_submit').css('display', 'block');
		jQuery('.backButtonResponsive.submit.immediate').css('display', 'inline-block');
		
		jQuery('.backButtonTabSmallView').css('display', 'none');
	}
	else if(jQuery(window).width() <= 768 && jQuery('.responsive_tab.mikronavi_submit').css('display') == 'none'){

		jQuery('.responsive_tab.mikronavi_submit ~ div, .responsive_tab.mikronavi_submit + h2').css('display', 'block');
	
	}
	else{
		jQuery('.responsive_tab.mikronavi_submit ~ div, .responsive_tab.mikronavi_submit + h2').css('display', 'none');
	}
});/**
 * Author: Evelyn Elsner
 * 
 */
de.his.modules.LoginPassword = new function() {
    de.his.modules.ModuleRegistry.registerModule(this)
		.registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.modules.LoginPassword";

	var showPasswordBtn = "";
	var showPasswordBtnImg = "";
	var lang = "de";
	var newTitleDe = "Passwort verbergen";	
	var newTitleEn = "Hide password"
	var oldTitle = "";
	
	// Login-Portlet
	var pShowPasswordBtn = "";
	var pShowPasswordBtnImg = "";
	var pNewTitleDe = "Passwort verbergen";	
	var pNewTitleEn = "Hide password"
	var pOldTitle = "";
	
	// Access Denied Form
	var dShowPasswordBtn = "";
	var dShowPasswordBtnImg = "";
	var dNewTitleDe = "Passwort verbergen";	
	var dNewTitleEn = "Hide password"
	var dOldTitle = "";
	
	// Self Registration first Password
	var s1ShowPasswordBtn = "";
	var s1ShowPasswordBtnImg = "";
	var s1NewTitleDe = "Passwort verbergen";	
	var s1NewTitleEn = "Hide password"
	var s1OldTitle = "";
	
	// Self Registration second/repeated Password
	var s2ShowPasswordBtn = "";
	var s2ShowPasswordBtnImg = "";
	var s2NewTitleDe = "Passwort verbergen";	
	var s2NewTitleEn = "Hide password"
	var s2OldTitle = "";
	
	
    this.init = function() {
		showPasswordBtn = jQuery('button[id$="showPassword"]');
		showPasswordBtnImg = jQuery('button[id$="showPassword"].iconfont-eye');
		oldTitle = jQuery('button[id$="showPassword"]').attr("title");
		
		pShowPasswordBtn = jQuery('button[id$="showPasswordPortlet"]');
		pShowPasswordBtnImg = jQuery('button[id$="showPasswordPortlet"] > img');
		pOldTitle = jQuery('button[id$="showPasswordPortlet"]').attr("title");
		
		dShowPasswordBtn = jQuery('button[id$="showPasswordAccessDenied"]');
		dShowPasswordBtnImg = jQuery('button[id$="showPasswordAccessDenied"].iconfont-eye');
		dOldTitle = jQuery('button[id$="showPasswordAccessDenied"]').attr("title");
		
		s1ShowPasswordBtn = jQuery('button[id$="showPassword1SelfRegistration"]');
		s1ShowPasswordBtnImg = jQuery('button[id$="showPassword1SelfRegistration"] > img');
		s1OldTitle = jQuery('button[id$="showPassword1SelfRegistration"]').attr("title");
		
		s2ShowPasswordBtn = jQuery('button[id$="showPassword2SelfRegistration"]');
		s2ShowPasswordBtnImg = jQuery('button[id$="showPassword2SelfRegistration"] > img');
		s2OldTitle = jQuery('button[id$="showPassword2SelfRegistration"]').attr("title");
		
		if(jQuery('select[id$=langselectbox]').attr("class") === "langSelector language_en"){
			lang = "en";
		}
    };

    this.refresh = function() {
        this.init();
    };
  		
	function getPassword(passwordId){
		var password = document.querySelector(passwordId);
		return password;
	}
	
	// toggle the type attribute
	function setType(password){
		var type = password.getAttribute("type") === "password" ? "text" : "password";
		password.setAttribute('type', type);
		return type;
	}
	
	// toggle title and alt attributes
	function setBtnImgAttributes(button, buttonImg, titleDe, titleEn){
		if(lang === "de"){
			button.attr("title", titleDe);
			button.attr("aria-label", titleDe);
			if(buttonImg.toString().includes("iconfont")){
				buttonImg.attr("alt", titleDe);
			}
		}
		else if(lang === "en"){
			button.attr("title", titleEn);
			button.attr("aria-label", titleEn);
			if(buttonImg.toString().includes("iconfont")){
				buttonImg.attr("alt", titleEn);
			}
		}
		button.trigger("updateTooltip");
	}
	
	function setOldAttributes(button, buttonImg, oldAttribute){
		if(buttonImg.toString().includes("iconfont") === false){
			button.attr("title", oldAttribute);
			button.attr("aria-label", oldAttribute);
			buttonImg.attr("alt", oldAttribute);
			buttonImg.attr("src", "/HISinOne/images/icons/eye.svg");
		}
		else{
			button.attr("title", oldAttribute);
			button.attr("aria-label", oldAttribute);
			button.attr("class", buttonImg);
		}
		button.trigger("updateTooltip");
	}
	
	jQuery('button[id$="showPassword"]').on("click", function(){
		var password = getPassword('#fdsa');
	  	var type = setType(password);

		if(type === "text"){
			showPasswordBtnImg.attr("class", "iconfont_2023_06-eye_blocked submit_image showPasswordElement");
			setBtnImgAttributes(showPasswordBtn, showPasswordBtnImg, newTitleDe, newTitleEn);
		}
		else{
			setOldAttributes(showPasswordBtn, "iconfont-eye submit_image showPasswordElement", oldTitle);
		}
	});
	
	// Eye in Login-Portlet (mobile-login-form.xhtml)
	jQuery('button[id$="showPasswordPortlet"]').on("click", function(){
		var password = getPassword('input[id$="mobileLoginSubForm:fdsa"]');
		var type = setType(password);

		if(type === "text"){
			pShowPasswordBtnImg.attr("src", "/HISinOne/images/icons/eye_blocked.svg");
			setBtnImgAttributes(pShowPasswordBtn, pShowPasswordBtnImg, pNewTitleDe, pNewTitleEn);
		}
		else{
			setOldAttributes(pShowPasswordBtn, pShowPasswordBtnImg, pOldTitle);
		}
	});
	
	// Eye in Access Denied (login-form.xhtml)
	jQuery('button[id$="showPasswordAccessDenied"]').on("click", function(){
		var password = getPassword('#accessDeniedForm > div > div > input[id$="fdsa"]');
		var type = setType(password);

		if(type === "text"){
			dShowPasswordBtnImg.attr("class", "iconfont_2023_06-eye_blocked submit_image showPasswordAccessDenied");
			setBtnImgAttributes(dShowPasswordBtn, dShowPasswordBtnImg, dNewTitleDe, dNewTitleEn);		}
		else{
			setOldAttributes(dShowPasswordBtn, "iconfont-eye submit_image showPasswordAccessDenied", dOldTitle);
		}
	});
	
	// Eye in self Registration Form (selfRegistrationForm.xhtml)
	jQuery('button[id$="showPassword1SelfRegistration"]').on("click", function(){
		var password = getPassword('#selbstregistrierung > div > div > div > fieldset > div > div > input[id$="passwort1"]');
		var type = setType(password);

		if(type === "text"){
			s1ShowPasswordBtnImg.attr("src", "/HISinOne/images/icons/eye_blocked.svg");
			setBtnImgAttributes(s1ShowPasswordBtn, s1ShowPasswordBtnImg, s1NewTitleDe, s1NewTitleEn);		}
		else{
			setOldAttributes(s1ShowPasswordBtn, s1ShowPasswordBtnImg, s1OldTitle);
		}
	});
	
	// Second eye in self Registration Form (selfRegistrationForm.xhtml)
	jQuery('button[id$="showPassword2SelfRegistration"]').on("click", function(){
		var password = getPassword('#selbstregistrierung > div > div > div > fieldset > div > div > input[id$="passwort2"]');
		var type = setType(password);

		if(type === "text"){
			s2ShowPasswordBtnImg.attr("src", "/HISinOne/images/icons/eye_blocked.svg");
			setBtnImgAttributes(s2ShowPasswordBtn, s2ShowPasswordBtnImg, s2NewTitleDe, s2NewTitleEn);		}
		else{
			setOldAttributes(s2ShowPasswordBtn, s2ShowPasswordBtnImg, s2OldTitle);
		}
	});
};//	based on code written by Tan Ling Wee on 2 Dec 2001
//	last updated 20 June 2003
//	email :	fuushikaden@yahoo.com
//
// Modified to be completely object-oriented, CSS based and using proper DOM-access functions
// @author Martin Marinschek
// @author Sylvain Vieujot

//we reserve the namespace correctly
window.org = window.org || {};
org.apache = org.apache || {};
org.apache.myfaces = org.apache.myfaces || {};

if (!org.apache.myfaces.PopupCalendar) {
    org.apache.myfaces.CalendarInitData = function () {
        // x position (-1 if to appear below control)
        this.fixedX = -1;

        // y position (-1 if to appear below control)
        this.fixedY = -1;

        // 0 - sunday ; 1 - monday (aka firstDayOfWeek)
        this.startAt = 1;

        // 0 - don't show; 1 - show
        this.showWeekNumber = 1;

        // 0 - don't show; 1 - show
        this.showToday = 1;

        // directory for images ... e.g. this.imgDir="/img/"
        this.imgDir = "images/";

        this.imgDirSuffix = "";

        this.themePrefix = "jscalendar-DB";

        this.gotoString = "Go To Current Month";
        this.todayString = "Today is";
        this.todayDateFormat = null;
        this.weekString = "Wk";
        this.scrollLeftMessage = "Click to scroll to previous month. Hold mouse button to scroll automatically.";
        this.scrollRightMessage = "Click to scroll to next month. Hold mouse button to scroll automatically.";
        this.selectMonthMessage = "Click to select a month.";
        this.selectYearMessage = "Click to select a year.";
        this.selectDateMessage = "Select [date] as date."; // do not replace [date], it will be replaced by date.

        this.popupLeft = false;

        this.monthName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
        this.dayName = this.startAt == 0 ? new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") : new Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

        this.selectMode = "day";

    };

    org.apache.myfaces.DateParts = function (sec, min, hour, date, month, year) {
        this.sec = sec;
        this.min = min;
        this.hour = hour;
        this.date = date;
        this.month = month;
        this.year = year;
    };

    org.apache.myfaces.HolidayRec = function (d, m, y, desc) {
        this.d = d;
        this.m = m;
        this.y = y;
        this.desc = desc;
    };

    org.apache.myfaces.PopupCalendar = function () {
        this.idPrefix = "org.apache.myfaces.PopupCalendar";

        this.selectedDate = new org.apache.myfaces.DateParts(0, 0, 0, 0, 0, 0);
        this.saveSelectedDate = new org.apache.myfaces.DateParts(0, 0, 0, 0, 0, 0);

        this.monthConstructed = false;
        this.yearConstructed = false;
        this.intervalID1 = null;
        this.intervalID2 = null;
        this.timeoutID1 = null;
        this.timeoutID2 = null;
        this.ctlToPlaceValue = null;
        this.ctlNow = null;
        this.containerCtl = null;
        this.dateFormat = "MM/dd/yyyy";
        this.nStartingYear = null;
        this.bPageLoaded = false;

        // Detect whether the browser is Microsoft Internet Explorer.
        // Testing for the presence of document.all is not sufficient, as Opera provides that.
        // However hopefully nothing but IE implements ActiveX..
        // it is only needed to test for ie6 and before ie7 and quirks mode
        // do not expose the bleed through bug anymore
        this.ieVersion = this.getInternetExplorerVersion();
        this.ie6 = this.ieVersion != -1 && this.ieVersion < 7;

        this.dom = document.getElementById;
        this.ns4 = document.layers;
        this.dateFormatSymbols = new org.apache.myfaces.dateformat.DateFormatSymbols();
        this.initData = new org.apache.myfaces.CalendarInitData();
        this.today = new Date();
        this.dateNow = this.today.getDate();
        this.monthNow = this.today.getMonth();
        this.yearNow = this.today.getFullYear();

        // list of images to be preloaded from the server
        this.imgSrc = new Array("drop1.gif", "drop2.gif", "left1.gif", "left2.gif", "right1.gif", "right2.gif");
        this.img = new Array();

        //elements which need to change their dynamical
        //representation over time
        this.calendarDiv;
        this.selectMonthDiv;
        this.selectYearDiv;
        this.todaySpan = null;
        this.captionSpan = null;
        this.contentSpan = null;
        this.acceptMonthSpan = null;
        this.closeCalendarSpan = null;
        this.monthSpan = null;
        this.yearSpan = null
        this.changeMonthImg = null;
        this.changeYearImg = null;

        this.holidaysCounter = 0;
        this.holidays = new Array();

        this.bClickOnCalendar = false;
        this.bCalendarHidden = true;

        this.myFacesCtlType = "x:inputCalendar";
        this.inputDateClientId;
    };

//http://msdn.microsoft.com/en-us/library/ms537509%28v=vs.85%29.aspx
    org.apache.myfaces.PopupCalendar.prototype.getInternetExplorerVersion = function ()
        // Returns the version of Internet Explorer or a -1
        // (indicating the use of another browser).
    {
        var rv = -1; // Return value assumes failure.
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var ua = navigator.userAgent;
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null)
                rv = parseFloat(RegExp.$1);
        }
        return rv;
    };

    org.apache.myfaces.PopupCalendar.prototype._MSECS_PER_DAY = 24 * 60 * 60 * 1000;

    /**
     popups always have to be
     at the dom level nowhere else
     */
    org.apache.myfaces.PopupCalendar.prototype._fixPopupDomOrder = function (overDiv) {
        if (document.body != overDiv.parentNode) {
            overDiv.parentNode.removeChild(overDiv);
            document.body.appendChild(overDiv);
        }
    };

// IE bug workaround: hide background controls under the specified div.
    org.apache.myfaces.PopupCalendar.prototype._showPopupPostProcess = function (overDiv) {

        //ie6 detection over object inspections
        if (this.ie6) {
            // The iframe created here is a hack to work around an IE bug. In IE,
            // "windowed controls" (esp selectboxes) do not respect the z-index
            // setting of "non-windowed controls", meaning they will be drawn on
            // top of components that they should theoretically be underneath.
            // However a selectbox will NOT be drawn on top of an iframe, so the
            // workaround is to create an iframe with no content, then in function
            // _recalculateElement position the iframe under the "popup" div to
            // "mask out" the unwanted elements. 
            var iframe = document.getElementById(overDiv.id + "_IFRAME");

            if (iframe == null) {
                // the source attribute is to avoid a IE error message about non secure content on https connections
                iframe = document.createElement("iframe");
                iframe.setAttribute("id", overDiv.id + "_IFRAME");
                iframe.setAttribute("src", "javascript:false;");
                
                //HIS_FIX_BEGIN
                jQuery(iframe).css({
                	"visibility": "hidden",
                	"position": "absolute",
                	"top": "0px",
                	"left": "0px"
                });
//                Element.setStyle(iframe, "visibility:hidden; position: absolute; top:0px;left:0px;");

                //we can append it lazily since we are late here anyway and everything is rendered
                document.body.appendChild(iframe);
            }

            // now put the iframe at the appropriate location, and make it visible.
            this._recalculateElement(overDiv);
        }
    };

// IE bug workaround: hide background controls under the specified div; see _showPopupPostProcess.
// This should be called whenever a popup div is moved.
    org.apache.myfaces.PopupCalendar.prototype._recalculateElement = function (overDiv) {
        if (this.ie6) {
            var iframe = document.getElementById(overDiv.id + "_IFRAME");

            if (iframe) {
                // ok, there is a "masking iframe" associated with this div, so make its
                // size and position match the div exactly, and set its z-index to just
                // below the div. This hack blocks IE selectboxes from being drawn on top
                // of the div. 

                overDiv.style.zIndex = 98;

                iframe.style.zIndex = overDiv.style.zIndex - 1;
                iframe.style.width = overDiv.offsetWidth;
                iframe.style.height = overDiv.offsetHeight;
                iframe.style.top = overDiv.style.top;
                iframe.style.left = overDiv.style.left;
                iframe.style.display = "block";
                iframe.style.visibility = "visible";
                /*we have to set an explicit visible otherwise it wont work*/
            }
        }
    };

// IE bug workaround: unhide background controls that are beneath the specified div; see _showPopupPostProcess.
// Note that although this is called _showeElement, it is called when the popup is being *hidden*,
// in order to *show* the underlying controls again.
// we also reallign the floating div 
    org.apache.myfaces.PopupCalendar.prototype._hidePopupPostProcess = function (overDiv) {

        if (this.ie6) {
            var iframe = document.getElementById(overDiv.id + "_IFRAME");
            if (iframe) iframe.style.display = "none";
        }
    };

    org.apache.myfaces.PopupCalendar.prototype.addHoliday = function (d, m, y, desc) {
        this.holidays[this.holidaysCounter++] = new org.apache.myfaces.HolidayRec(d, m, y, desc);
    };

    org.apache.myfaces.PopupCalendar.prototype._swapImage = function (srcImg, destImg) {

        if (srcImg)
            srcImg.setAttribute("src", this.initData.imgDir + destImg + this.initData.imgDirSuffix);
    };

    org.apache.myfaces.PopupCalendar.prototype._keypresshandler = function () {
        // This method is intended for use on IE browsers only; they are the only
        // browsers that define window.event and window.event.keyCode.
        // Q: Why is this done only for IE?
        if (window["event"] && window.event["keyCode"] && (window.event.keyCode == 27)) {
            this._hideCalendar();
        }
    };

    org.apache.myfaces.PopupCalendar.prototype._clickhandler = function () {
        if (!this.bClickOnCalendar) {
            this._hideCalendar();
        }

        this.bClickOnCalendar = false;
    };

    org.apache.myfaces.PopupCalendar.prototype._isDaySelectable = function () {
        return (this.initData.selectMode == "day");
    };

    org.apache.myfaces.PopupCalendar.prototype._isWeekSelectable = function () {
        return (this.initData.selectMode == "week");
    };

    org.apache.myfaces.PopupCalendar.prototype._isMonthSelectable = function () {
        return (this.initData.selectMode == "month");
    };

    org.apache.myfaces.PopupCalendar.prototype.init = function (containerCtl) {
        if (this.dom) {
			//HIS_FIX_BEGIN #306351
			if(containerCtl===null){
				console.warn("Container is null. Cannot initiate popcalendar!");
				return;	
			}
			//HIS_FIX_END #306351
            if (!this.calendarDiv) {
                for (var i = 0; i < this.imgSrc.length; i++) {
                    // force preload of all images, so that when DOM nodes have their src set to
                    // the name of this image, it has already been loaded from the server.
                    this.img[i] = new Image;
                    this.img[i].src = this.initData.imgDir + this.imgSrc[i] + this.initData.imgDirSuffix;
                }

                this.containerCtl = containerCtl;

                this.calendarDiv = document.createElement("div");
                this.calendarDiv.id = containerCtl.id + "_calendarDiv";
                this.calendarDiv.className = this.initData.themePrefix + "-div-style";

                //HIS_FIX_BEGIN
                var that = this;
                jQuery(this.calendarDiv).on("click", function() {
                	that.bClickOnCalendar = true;
                });
//                Event.observe(this.calendarDiv, "click", function () {
//                    this.bClickOnCalendar = true;
//                }.bind(this), false);
                //HIS_FIX_END

                this.containerCtl.appendChild(this.calendarDiv);

                var mainTable = document.createElement("table");
                
                //HIS_FIX_BEGIN
                jQuery(mainTable).css({
                	"width": ((that.initData.showWeekNumber == 1) ? 250 : 220) + "px"
                });
//                Element.setStyle(mainTable, "width:" + ((this.initData.showWeekNumber == 1) ? 250 : 220) + "px;");
                mainTable.className = this.initData.themePrefix + "-table-style";
                //HIS_FIX_END

                this.calendarDiv.appendChild(mainTable);

                //This is necessary for IE. If you don't create a tbody element, the table will never show up!
                var mainBody = document.createElement("tbody");
                mainTable.appendChild(mainBody);

                var mainRow = document.createElement("tr");
                mainRow.className = this.initData.themePrefix + "-title-background-style";

                mainBody.appendChild(mainRow);

                var mainCell = document.createElement("td");

                mainRow.appendChild(mainCell);

                var contentTable = document.createElement("table");
                
                //HIS_FIX_BEGIN
                jQuery(contentTable).css({
                	"width": ((that.initData.showWeekNumber == 1) ? 248 : 218) + "px"
                });
//                Element.setStyle(contentTable, "width:" + ((this.initData.showWeekNumber == 1) ? 248 : 218) + "px;");
                //HIS_FIX_END
                
                var contentBody = document.createElement("tbody");
                contentTable.appendChild(contentBody);

                mainCell.appendChild(contentTable);

                var headerRow = document.createElement("tr");
                contentBody.appendChild(headerRow);

                var captionCell = document.createElement("td");
                captionCell.className = this.initData.themePrefix + "-title-style";
                headerRow.appendChild(captionCell);

                this.captionSpan = document.createElement("span");
                captionCell.appendChild(this.captionSpan);

                if (this._isMonthSelectable()) {
                    var acceptMonthCell = document.createElement("td");
                    
                    //HIS_FIX_BEGIN
                    jQuery(acceptMonthCell).css("text-align", "right");
//                    Element.setStyle(acceptMonthCell, "text-align:right;");
                    //HIS_FIX_END
                    headerRow.appendChild(acceptMonthCell);

                    var acceptMonthLink = document.createElement("a");
                    acceptMonthLink.setAttribute("href", "#");
                    
                    //HIS_FIX_BEGIN
                    jQuery(acceptMonthLink).on("click", function(event){
                    	that.selectedDate.date = 1; // force first of the selected month
                    	that._closeCalendar();
                    	event.preventDefault();
                    	event.stopPropagation()
                    });
//                    Event.observe(acceptMonthLink, "click", function (event) {
//                        this.selectedDate.date = 1; // force first of the selected month
//                        this._closeCalendar();
//                        Event.stop(event);
//                    }.bindAsEventListener(this), false);
                    //HIS_FIX_END

                    acceptMonthCell.appendChild(acceptMonthLink);
                    this.acceptMonthSpan = document.createElement("span");
                    this.acceptMonthSpan.appendChild(document.createTextNode("Y"));

                    acceptMonthLink.appendChild(this.acceptMonthSpan);
                }

                var closeButtonCell = document.createElement("td");
                //HIS_FIX_BEGIN
                jQuery(closeButtonCell).css("text-align", "right");
//                Element.setStyle(closeButtonCell, "text-align:right;");
                //HIS_FIX_END
                headerRow.appendChild(closeButtonCell);

                var closeCalendarLink = document.createElement("a");
                closeCalendarLink.setAttribute("href", "#");
                
                //HIS_FIX_BEGIN
                jQuery(closeCalendarLink).on("click", function(event){
                	that._hideCalendar();
                	event.preventDefault();
                    event.stopPropagation();
                });
//                Event.observe(closeCalendarLink, "click", function (event) {
//                    this._hideCalendar();
//                    Event.stop(event);
//                }.bindAsEventListener(this), false);
                //HIS_FIX_END

                closeButtonCell.appendChild(closeCalendarLink);

                this.closeCalendarSpan = document.createElement("span");

                closeCalendarLink.appendChild(this.closeCalendarSpan);

                var contentRow = document.createElement("tr");
                mainBody.appendChild(contentRow);

                var contentCell = document.createElement("td");
                contentCell.className = this.initData.themePrefix + "-body-style";
                contentRow.appendChild(contentCell);

                this.contentSpan = document.createElement("span");
                contentCell.appendChild(this.contentSpan);

                if (this.initData.showToday == 1) {
                    var todayRow = document.createElement("tr");
                    todayRow.className = this.initData.themePrefix + "-today-style";
                    mainBody.appendChild(todayRow);

                    var todayCell = document.createElement("td");
                    todayCell.className = this.initData.themePrefix + "-today-lbl-style";
                    todayRow.appendChild(todayCell);

                    this.todaySpan = document.createElement("span");
                    todayCell.appendChild(this.todaySpan);
                }

                this.selectMonthDiv = document.createElement("div");
                this.selectMonthDiv.id = this.containerCtl.id + "_selectMonthDiv";
                this.selectMonthDiv.className = this.initData.themePrefix + "-div-style";

                this.containerCtl.appendChild(this.selectMonthDiv);

                this.selectYearDiv = document.createElement("div");
                this.selectYearDiv.id = this.containerCtl.id + "_selectYearDiv";
                this.selectYearDiv.className = this.initData.themePrefix + "-div-style";

                this.containerCtl.appendChild(this.selectYearDiv);

                // Catch global keypresses and clicks, so that entering data into any field
                // outside the calendar, or clicking anywhere outside the calendar, will
                // close it.
                //
                // This is ugly, as it's quite a load on the client to check this for every
                // keystroke/click. It would be nice to find an alternative...maybe register
                // these listeners only when a calendar is open?
                
                //HIS_FIX_BEGIN
                jQuery(document).on("keypress", function(){
                	that._keypresshandler();
                });
//                Event.observe(document, "keypress", this._keypresshandler.bind(this), false);
                jQuery(document).on("click", function(){
                	that._clickhandler();
                });
//                Event.observe(document, "click", this._clickhandler.bind(this), false);
                //HIS_FIX_END
            }
        }

        if (!this.ns4) {
            /* Instead use getFullYear() */
            /*if (!this.ie6)
             this.yearNow += 1900;*/

            this._hideCalendar();

            this.monthConstructed = false;
            this.yearConstructed = false;

            if (this.initData.showToday == 1) {
                // TODO this.dateFormatSymbols is probably never set at this point.
                this.todayDateFormatter = new org.apache.myfaces.dateformat.SimpleDateFormatter(
                        this.initData.todayDateFormat ? this.initData.todayDateFormat : this.dateFormat,
                        this.dateFormatSymbols,
                        this.initData.startAt);

                this.todaySpan.appendChild(document.createTextNode(this.initData.todayString + " "))

                var todayLink = document.createElement("a");
                todayLink.className = this.initData.themePrefix + "-today-style";
                todayLink.setAttribute("title", this.initData.gotoString);
                todayLink.setAttribute("href", "#");
                todayLink.appendChild(document.createTextNode(this._todayIsDate()));
                
                //HIS_FIX_BEGIN
                jQuery(todayLink).on("click", function(event){
                	that.selectedDate.month = that.monthNow;
                	that.selectedDate.year = that.yearNow;
                	that._constructCalendar();
                	event.preventDefault();
                    event.stopPropagation();
                });
//                Event.observe(todayLink, "click", function (event) {
//                    this.selectedDate.month = this.monthNow;
//                    this.selectedDate.year = this.yearNow;
//                    this._constructCalendar();
//                    Event.stop(event);
//                }.bindAsEventListener(this), false);
                
                jQuery(todayLink).on("mousemove", function(event){
                	window.status = that.initData.gotoString;
                });
//                Event.observe(todayLink, "mousemove", function () {
//                    window.status = this.initData.gotoString;
//                }.bind(this), false);
                
                jQuery(todayLink).on("mouseout", function(event){
                	 window.status = "";
                });
//                Event.observe(todayLink, "mouseout", function () {
//                    window.status = "";
//                }.bind(this), false);
                //HIS_FIX_END

                this.todaySpan.appendChild(todayLink);
            }

            this._appendNavToCaption("left");
            this._appendNavToCaption("right");

            this.monthSpan = document.createElement("span");
            this.monthSpan.className = this.initData.themePrefix + "-title-control-normal-style";

            //HIS_FIX_BEGIN
            jQuery(that.monthSpan).on("mouseover", function(event){
            	that._swapImage(that.changeMonthImg, "drop2.gif");
            	that.monthSpan.className = that.initData.themePrefix + "-title-control-select-style";
            	window.status = that.selectMonthMessage;
            });
//            Event.observe(this.monthSpan, "mouseover", function (event) {
//                this._swapImage(this.changeMonthImg, "drop2.gif");
//                this.monthSpan.className = this.initData.themePrefix + "-title-control-select-style";
//                window.status = this.selectMonthMessage;
//            }.bindAsEventListener(this), false);

            jQuery(that.monthSpan).on("mouseout", function(event){
            	that._swapImage(that.changeMonthImg, "drop1.gif");
            	that.monthSpan.className = that.initData.themePrefix + "-title-control-normal-style";
                window.status = "";
            });
//            Event.observe(this.monthSpan, "mouseout", function (event) {
//                this._swapImage(this.changeMonthImg, "drop1.gif");
//                this.monthSpan.className = this.initData.themePrefix + "-title-control-normal-style";
//                window.status = "";
//            }.bindAsEventListener(this), false);

            jQuery(that.monthSpan).on("click", function(event){
            	that._popUpMonth();
            	event.preventDefault();
                event.stopPropagation();
            });
//            Event.observe(this.monthSpan, "click", function (event) {
//                this._popUpMonth();
//                Event.stop(event);
//            }.bind(this), false);
            //HIS_FIX_END

            this.captionSpan.appendChild(this.monthSpan);
            this._appendNbsp(this.captionSpan);

            this.yearSpan = document.createElement("span");
            this.yearSpan.className = this.initData.themePrefix + "-title-control-normal-style";

            //HIS_FIX_BEGIN
            jQuery(that.yearSpan).on("mouseover", function(event){
            	that._swapImage(that.changeYearImg, "drop2.gif");
            	that.yearSpan.className = that.initData.themePrefix + "-title-control-select-style";
                 window.status = that.selectYearMessage;
            });
//            Event.observe(this.yearSpan, "mouseover", function (event) {
//                this._swapImage(this.changeYearImg, "drop2.gif");
//                this.yearSpan.className = this.initData.themePrefix + "-title-control-select-style";
//                window.status = this.selectYearMessage;
//            }.bindAsEventListener(this), false);

            jQuery(that.yearSpan).on("mouseout", function(event){
            	that._swapImage(that.changeYearImg, "drop1.gif");
            	that.yearSpan.className = that.initData.themePrefix + "-title-control-normal-style";
            	window.status = "";
            });
//            Event.observe(this.yearSpan, "mouseout", function (event) {
//                this._swapImage(this.changeYearImg, "drop1.gif");
//                this.yearSpan.className = this.initData.themePrefix + "-title-control-normal-style";
//                window.status = "";
//            }.bindAsEventListener(this), false);

            jQuery(that.yearSpan).on("click", function(event){
            	that._popUpYear();
            	event.preventDefault();
            	event.stopPropagation();
            });
//            Event.observe(this.yearSpan, "click", function (event) {
//                this._popUpYear();
//                Event.stop(event);
//            }.bind(this), false);
            //HIS_FIX_END

            this.captionSpan.appendChild(this.yearSpan);
            this._appendNbsp(this.captionSpan);

            this.bPageLoaded = true;

        }
    };

    org.apache.myfaces.PopupCalendar.prototype._appendNavToCaption = function (direction) {
        var imgLeft = document.createElement("img");
        imgLeft.setAttribute("src", this.initData.imgDir + direction + "1.gif" + this.initData.imgDirSuffix);
        imgLeft.setAttribute("width", "10px");
        imgLeft.setAttribute("height", "11px");
        //HIS_FIX_BEGIN
        jQuery(imgLeft).css("border", "0px");
//        Element.setStyle(imgLeft, "border:0px;");
        //HIS_FIX_END
        
        var spanLeft = document.createElement("span");

        this._createControl(direction, spanLeft, imgLeft);

        this._appendNbsp(spanLeft);
        spanLeft.appendChild(imgLeft);
        this._appendNbsp(spanLeft);
        this.captionSpan.appendChild(spanLeft);
        this._appendNbsp(spanLeft);
    };

    org.apache.myfaces.PopupCalendar.prototype._createControl = function (direction, spanLeft, imgLeft) {
        spanLeft.className = this.initData.themePrefix + "-title-control-normal-style";
        
        //HIS_FIX_BEGIN
        var that = this;
        jQuery(spanLeft).on("mouseover", function(event){
        	that._swapImage(imgLeft, direction + "2.gif");
             spanLeft.className = that.initData.themePrefix + "-title-control-select-style";
             if (direction == "left") {
                 window.status = that.scrollLeftMessage;
             }
             else {
                 window.status = that.scrollRightMessage;
             }
        });
//        Event.observe(spanLeft, "mouseover", function (event) {
//            this._swapImage(imgLeft, direction + "2.gif");
//            spanLeft.className = this.initData.themePrefix + "-title-control-select-style";
//            if (direction == "left") {
//                window.status = this.scrollLeftMessage;
//            }
//            else {
//                window.status = this.scrollRightMessage;
//            }
//        }.bindAsEventListener(this), false);
        
        jQuery(spanLeft).on("click", function(){
        	 if (direction == "left") {
        		 that._decMonth();
             }
             else {
            	 that._incMonth();
             }
        });
//        Event.observe(spanLeft, "click", function () {
//            if (direction == "left") {
//                this._decMonth();
//            }
//            else {
//                this._incMonth();
//            }
//        }.bind(this), false);
        
        
        jQuery(spanLeft).on("mouseout", function(){
        	 clearInterval(that.intervalID1);
        	 that._swapImage(imgLeft, direction + "1.gif");
             spanLeft.className = "" + that.initData.themePrefix + "-title-control-normal-style";
             window.status = "";
        });
//        Event.observe(spanLeft, "mouseout", function (event) {
//            clearInterval(this.intervalID1);
//            this._swapImage(imgLeft, direction + "1.gif");
//            spanLeft.className = "" + this.initData.themePrefix + "-title-control-normal-style";
//            window.status = "";
//        }.bindAsEventListener(this), false);
        
        jQuery(spanLeft).on("mousedown", function(){
        	 clearTimeout(that.timeoutID1);
        	 that.timeoutID1 = setTimeout((function () {
                 if (direction == "left") {
                	 that._startDecMonth();
                 }
                 else {
                	 that._startIncMonth();
                 }
             }).bind(this), 500)
        });
//        Event.observe(spanLeft, "mousedown", function () {
//            clearTimeout(this.timeoutID1);
//            this.timeoutID1 = setTimeout((function () {
//                if (direction == "left") {
//                    this._startDecMonth();
//                }
//                else {
//                    this._startIncMonth();
//                }
//            }).bind(this), 500)
//        }.bind(this), false);
        
        jQuery(spanLeft).on("mouseup", function(){
        	 clearTimeout(that.timeoutID1);
             clearInterval(that.intervalID1);
        });
//        Event.observe(spanLeft, "mouseup", function () {
//            clearTimeout(this.timeoutID1);
//            clearInterval(this.intervalID1);
//        }.bind(this), false);
        //HIS_FIX_END
    };

    org.apache.myfaces.PopupCalendar.prototype._appendNbsp = function (element) {
        if (element)
            element.appendChild(document.createTextNode(String.fromCharCode(160)));
    };

    org.apache.myfaces.PopupCalendar.prototype._todayIsDate = function () {
        return this.todayDateFormatter.format(this.today);
    };

    org.apache.myfaces.PopupCalendar.prototype._hideCalendar = function () {
        this.calendarDiv.classList.add("jscalendar-hidden");
        this.calendarDiv.classList.remove("jscalendar-visible");
        this.bCalendarHidden = true;
        if (this.selectMonthDiv.style != null) {
        	this.selectMonthDiv.classList.add("jscalendar-hidden");
        	this.selectMonthDiv.classList.remove("calendar-visible");
        }
        if (this.selectYearDiv.style != null) {
        	this.selectYearDiv.classList.add("jscalendar-hidden");
        	this.selectYearDiv.classList.remove("jscalendar-visible");
        }

        this._hidePopupPostProcess(this.selectMonthDiv);
        this._hidePopupPostProcess(this.selectYearDiv);
        this._hidePopupPostProcess(this.calendarDiv);
    };

    org.apache.myfaces.PopupCalendar.prototype._padZero = function (num) {
        return (num < 10) ? '0' + num : num;
    };

    org.apache.myfaces.PopupCalendar.prototype._constructDate = function (d, m, y) {
        var date = new Date(y, m, d, this.selectedDate.hour, this.selectedDate.min, this.selectedDate.sec);
        return this.stdDateFormatter.format(date);
    };

    org.apache.myfaces.PopupCalendar.prototype._closeCalendar = function () {
        this._hideCalendar();

        if (this.myFacesCtlType != "x:inputDate") {
            this.ctlToPlaceValue.value = this._constructDate(this.selectedDate.date, this.selectedDate.month, this.selectedDate.year)
            var onchange = this.ctlToPlaceValue.getAttribute("onchange");
            if (onchange) {
                this.ctlToPlaceValue.onchange();
            }
        }
        else {
            document.getElementById(this.myFacesInputDateClientId + ".day").value = this.selectedDate.date;
            document.getElementById(this.myFacesInputDateClientId + ".month").value = this.selectedDate.month + 1;
            document.getElementById(this.myFacesInputDateClientId + ".year").value = this.selectedDate.year;
        }
    };

    /*** Month Pulldown ***/

    org.apache.myfaces.PopupCalendar.prototype._startDecMonth = function () {
        this.intervalID1 = setInterval((function () {
            this._decMonth();
        }).bind(this), 80);
    };

    org.apache.myfaces.PopupCalendar.prototype._startIncMonth = function () {
        this.intervalID1 = setInterval((function () {
            this._incMonth();
        }).bind(this), 80);
    };

    org.apache.myfaces.PopupCalendar.prototype._incMonth = function () {
        this.selectedDate.month = this.selectedDate.month + 1;
        if (this.selectedDate.month > 11) {
            this.selectedDate.month = 0;
            this.selectedDate.year++;
        }
        this._constructCalendar();
    };

    org.apache.myfaces.PopupCalendar.prototype._decMonth = function () {
        this.selectedDate.month = this.selectedDate.month - 1;
        if (this.selectedDate.month < 0) {
            this.selectedDate.month = 11;
            this.selectedDate.year--;
        }
        this._constructCalendar()
    };

    org.apache.myfaces.PopupCalendar.prototype._removeAllChildren = function (element) {
        while (element && element.hasChildNodes())
            element.removeChild(element.lastChild);
    };

    org.apache.myfaces.PopupCalendar.prototype._constructMonth = function () {
        this._popDownYear();
        if (!this.monthConstructed) {

            var selectMonthTable = document.createElement("table");
            //HIS_FIX_BEGIN
            jQuery(selectMonthTable).css({
            	"width": "70px",
            	"border-collapse": "collapse"
            });
//            Element.setStyle(selectMonthTable, "width:70px;border-collapse:collapse;");
            //HIS_FIX_END
            selectMonthTable.className = this.initData.themePrefix + "-dropdown-style";

            this._removeAllChildren(this.selectMonthDiv);

            this.selectMonthDiv.appendChild(selectMonthTable);

            //HIS_FIX_BEGIN
            var that = this;
            jQuery(selectMonthTable).on("mouseover", function(){
            	clearTimeout(that.timeoutID1);
            });
//            Event.observe(selectMonthTable, "mouseover", function () {
//            	clearTimeout(this.timeoutID1);
//            }.bind(this), false);
            
            jQuery(selectMonthTable).on("mouseout", function(event){
            	clearTimeout(that.timeoutID1);
            	that.timeoutID1 = setTimeout((function () {
            		that._popDownMonth()
                }).bind(this), 100);
            	event.preventDefault();
                event.stopPropagation();
            });
//            Event.observe(selectMonthTable, "mouseout", function (event) {
//                clearTimeout(this.timeoutID1);
//                this.timeoutID1 = setTimeout((function () {
//                    this._popDownMonth()
//                }).bind(this), 100);
//                Event.stop(event);
//            }.bindAsEventListener(this), false);
            //HIS_FIX_END

            var selectMonthTableBody = document.createElement("tbody");
            selectMonthTable.appendChild(selectMonthTableBody);

            for (i = 0; i < 12; i++) {
                var sName = this.initData.monthName[i];

                var sNameNode = null;

                if (i == this.selectedDate.month) {
                    sNameNode = document.createElement("span");
                    //HIS_FIX_BEGIN
                    jQuery(sNameNode).css("font-weight", "bold");
//                    Element.setStyle(sNameNode, "font-weight:bold;");
                    //HIS_FIX_END
                    sNameNode.appendChild(document.createTextNode(sName));
                    sNameNode.setAttribute("userData", i);
                }
                else {
                    sNameNode = document.createTextNode(sName);
                }

                var monthRow = document.createElement("tr");
                selectMonthTableBody.appendChild(monthRow);

                var monthCell = document.createElement("td");
                monthCell.setAttribute("userData", i);
                monthRow.appendChild(monthCell);
                
                //HIS_FIX_BEGIN
                jQuery(monthCell).on("mouseover", function(event){
                	event.target.className = that.initData.themePrefix + "-dropdown-select-style";
                });
//                Event.observe(monthCell, "mouseover", function (event) {
//                    Event.element(event).className = this.initData.themePrefix + "-dropdown-select-style";
//                }.bind(this), false);

                jQuery(monthCell).on("mouseout", function(event){
                	event.target.className = that.initData.themePrefix + "-dropdown-normal-style";
                });
//                Event.observe(monthCell, "mouseout", function (event) {
//                    Event.element(event).className = this.initData.themePrefix + "-dropdown-normal-style";
//                }.bind(this), false);

                jQuery(monthCell).on("click", function(event){
                	that.monthConstructed = false;
                	that.selectedDate.month = parseInt(event.target.getAttribute("userData"), 10);
                	that._constructCalendar();
                    that._popDownMonth();
                	event.preventDefault();
                    event.stopPropagation();
                });
//                Event.observe(monthCell, "click", function (event) {
//                    this.monthConstructed = false;
//                    this.selectedDate.month = parseInt(Event.element(event).getAttribute("userData"), 10);
//                    this._constructCalendar();
//                    this._popDownMonth();
//                    Event.stop(event);
//                }.bindAsEventListener(this), false);
                //HIS_FIX_END

                this._appendNbsp(monthCell);
                monthCell.appendChild(sNameNode);
                this._appendNbsp(monthCell);
            }

            this.monthConstructed = true;
        }
    };

    org.apache.myfaces.PopupCalendar.prototype._popUpMonth = function () {
        this._constructMonth()
        this._fixPopupDomOrder(this.selectMonthDiv);
        if (this.dom || this.ie6) {
    		this.selectMonthDiv.classList.remove("jscalendar-hidden");
    		this.selectMonthDiv.classList.add("jscalendar-visible");
		} else {
    		this.selectMonthDiv.classList.remove("jscalendar-hidden");
    		this.selectMonthDiv.classList.add("jscalendar-visible");
    	}
        this.selectMonthDiv.style.left = parseInt(this._formatInt(this.calendarDiv.style.left), 10) + 50 + "px";
        this.selectMonthDiv.style.top = parseInt(this._formatInt(this.calendarDiv.style.top), 10) + 26 + "px";

        this._showPopupPostProcess(this.selectMonthDiv);
    };

    org.apache.myfaces.PopupCalendar.prototype._popDownMonth = function () {
		this.selectMonthDiv.classList.add("jscalendar-hidden");
		this.selectMonthDiv.classList.remove("jscalendar-visible");
        this._hidePopupPostProcess(this.selectMonthDiv);
    };

    /*** Year Pulldown ***/

    org.apache.myfaces.PopupCalendar.prototype._incYear = function () {
        for (var i = 0; i < 7; i++) {
            var newYear = (i + this.nStartingYear) + 1;

            this._createAndAddYear(newYear, i);
        }
        this.nStartingYear++;
        this.bClickOnCalendar = true;
    };

    org.apache.myfaces.PopupCalendar.prototype._createAndAddYear = function (newYear, i) {
        var parentNode = document.getElementById(this.containerCtl.getAttribute("id") + "y" + i);

        this._removeAllChildren(parentNode);

        if (newYear == this.selectedDate.year) {
            this._appendNbsp(parentNode);
            var newYearSpan = document.createElement("span");
            newYearSpan.setAttribute("userData", newYear);
            newYearSpan.appendChild(document.createTextNode(newYear));
            parentNode.appendChild(newYearSpan);
            this._appendNbsp(parentNode);
        }
        else {
            this._appendNbsp(parentNode);
            parentNode.appendChild(document.createTextNode(newYear));
            this._appendNbsp(parentNode);
        }

        parentNode.setAttribute("userData", newYear);
    };

    org.apache.myfaces.PopupCalendar.prototype._decYear = function () {
        for (i = 0; i < 7; i++) {
            var newYear = (i + this.nStartingYear) - 1;

            this._createAndAddYear(newYear, i);
        }
        this.nStartingYear--;
        this.bClickOnCalendar = true;
    };

    org.apache.myfaces.PopupCalendar.prototype._constructYear = function () {
        this._popDownMonth();
        var sHTML = "";
        if (!this.yearConstructed) {

            var selectYearTable = document.createElement("table");
            //HIS_FIX_BEGIN
            jQuery(selectYearTable).css({
            	"width": "44px",
            	"border-collapse": "collapse"
            });
//            Element.setStyle(selectYearTable, "width:44px;border-collapse:collapse;");
            //HIS_FIX_END
            selectYearTable.className = this.initData.themePrefix + "-dropdown-style";

            this._removeAllChildren(this.selectYearDiv);

            this.selectYearDiv.appendChild(selectYearTable);
            
            //HIS_FIX_BEGIN
            var that = this;
            jQuery(selectYearTable).on("mouseover", function(event){
                clearTimeout(that.timeoutID2);
            });
//            Event.observe(selectYearTable, "mouseover", function (event) {
//                clearTimeout(this.timeoutID2);
//            }.bind(this), false);
            
            jQuery(selectYearTable).on("mouseout", function(event){
            	clearTimeout(that.timeoutID2);
            	that.timeoutID2 = setTimeout((function () {
            		that._popDownYear()
            	}).bind(this), 100);
            	event.preventDefault();
                event.stopPropagation();
            });
//            Event.observe(selectYearTable, "mouseout", function (event) {
//                clearTimeout(this.timeoutID2);
//                this.timeoutID2 = setTimeout((function () {
//                    this._popDownYear()
//                }).bind(this), 100);
//                Event.stop(event);
//            }.bindAsEventListener(this), false);
            //HIS_FIX_END

            var selectYearTableBody = document.createElement("tbody");
            selectYearTable.appendChild(selectYearTableBody);

            var selectYearRowMinus = document.createElement("tr");
            selectYearTableBody.appendChild(selectYearRowMinus);

            var selectYearCellMinus = document.createElement("td");
            selectYearCellMinus.setAttribute("align", "center");

            selectYearCellMinus.appendChild(document.createTextNode("-"));

            selectYearRowMinus.appendChild(selectYearCellMinus);

            //HIS_FIX_BEGIN
            jQuery(selectYearCellMinus).on("mouseover", function(event){
            	event.target.className = that.initData.themePrefix + "-dropdown-select-style";
            });
//            Event.observe(selectYearCellMinus, "mouseover", function (event) {
//                Event.element(event).className = this.initData.themePrefix + "-dropdown-select-style";
//            }.bindAsEventListener(this), false);

            jQuery(selectYearCellMinus).on("mouseout", function(event){
            	 clearInterval(that.intervalID1);
            	 event.target.className = that.initData.themePrefix + "-dropdown-normal-style";            
            });
//            Event.observe(selectYearCellMinus, "mouseout", function (event) {
//                clearInterval(this.intervalID1);
//                Event.element(event).className = this.initData.themePrefix + "-dropdown-normal-style";
//            }.bindAsEventListener(this), false);

            
            jQuery(selectYearCellMinus).on("mousedown touchstart", function(event){
            	clearInterval(that.intervalID1);
            	that.intervalID1 = setInterval((function () {
            		that._decYear();
                }).bind(this), 30);
            	event.preventDefault();
                event.stopPropagation();
            });
//            Event.observe(selectYearCellMinus, "mousedown", function (event) {
//                clearInterval(this.intervalID1);
//                this.intervalID1 = setInterval((function () {
//                    this._decYear();
//                }).bind(this), 30);
//                Event.stop(event);
//            }.bindAsEventListener(this), false);
            
            jQuery(selectYearCellMinus).on("mouseup touchend", function(event){
            	clearInterval(that.intervalID1);
            	event.preventDefault();
                event.stopPropagation();
            });
//            Event.observe(selectYearCellMinus, "mouseup", function (event) {
//                clearInterval(this.intervalID1);
//                Event.stop(event);
//            }.bindAsEventListener(this), false);
            //HIS_FIX_END

            //sHTML = "<tr><td align='center' onmouseover='this.className=\""+this.initData.themePrefix+"-dropdown-select-style\"' onmouseout='clearInterval(this.intervalID1); this.className=\""+this.initData.themePrefix+"-dropdown-normal-style\"' onmousedown='clearInterval(this.intervalID1);this.intervalID1=setInterval(\"_decYear()\",30)' onmouseup='clearInterval(this.intervalID1)'>-</td></tr>";

            this.nStartingYear = this.selectedDate.year - 3;
            var j = 0;
            for (i = this.selectedDate.year - 3; i <= (this.selectedDate.year + 3); i++) {
                var sName = i;

                var sNameNode = null;

                if (i == this.selectedDate.year) {
                    sNameNode = document.createElement("span");
                    //HIS_FIX_BEGIN
                    jQuery(sNameNode).css("font-weight", "bold");
//                    Element.setStyle(sNameNode, "font-weight:bold;");
                    //HIS_FIX_END
                    sNameNode.appendChild(document.createTextNode(sName));
                    sNameNode.setAttribute("userData", sName);
                }
                else {
                    sNameNode = document.createTextNode(sName);
                }

                var yearRow = document.createElement("tr");
                selectYearTableBody.appendChild(yearRow);

                var yearCell = document.createElement("td");
                yearCell.setAttribute("userData", sName);
                yearCell.setAttribute("id", this.containerCtl.getAttribute("id") + "y" + j);
                yearRow.appendChild(yearCell);

                //HIS_FIX_BEGIN
                jQuery(yearCell).on("mouseover", function(event){
                	event.target.className = that.initData.themePrefix + "-dropdown-select-style";
                });
//                Event.observe(yearCell, "mouseover", function (event) {
//                    Event.element(event).className = this.initData.themePrefix + "-dropdown-select-style";
//                }.bind(this), false);

                jQuery(yearCell).on("mouseout", function(event){
                	event.target.className = that.initData.themePrefix + "-dropdown-normal-style";
                });
//                Event.observe(yearCell, "mouseout", function (event) {
//                    Event.element(event).className = this.initData.themePrefix + "-dropdown-normal-style";
//                }.bind(this), false);

                jQuery(yearCell).on("click", function(event){
                	var elem = event.target;
                	var sYear = null;
                	that.selectedDate.year = parseInt(that._formatInt(elem.getAttribute("userData"), 10));
                	that.yearConstructed = false;
                	that._popDownYear();
                	that._constructCalendar();
                	event.preventDefault();
                	event.stopPropagation();
                });
//                Event.observe(yearCell, "click", function (event) {
//                    var elem = Event.element(event);
//                    var sYear = null;
//                    this.selectedDate.year = parseInt(this._formatInt(elem.getAttribute("userData"), 10));
//                    this.yearConstructed = false;
//                    this._popDownYear();
//                    this._constructCalendar();
//                    Event.stop(event);
//                }.bindAsEventListener(this), false);
                //HIS_FIX_END

                this._appendNbsp(yearCell);
                yearCell.appendChild(sNameNode);
                this._appendNbsp(yearCell);
                j++;
            }

            var selectYearRowPlus = document.createElement("tr");
            selectYearTableBody.appendChild(selectYearRowPlus);

            var selectYearCellPlus = document.createElement("td");
            selectYearCellPlus.setAttribute("align", "center");

            selectYearCellPlus.appendChild(document.createTextNode("+"));

            selectYearRowPlus.appendChild(selectYearCellPlus);
            
            //HIS_FIX_BEGIN
            jQuery(selectYearCellPlus).on("mouseover", function(event){
            	event.target.className = that.initData.themePrefix + "-dropdown-select-style";
            });
//            Event.observe(selectYearCellPlus, "mouseover", function (event) {
//                Event.element(event).className = this.initData.themePrefix + "-dropdown-select-style";
//            }.bindAsEventListener(this), false);

            jQuery(selectYearCellPlus).on("mouseout", function(event){
            	 clearInterval(that.intervalID2);
            	 event.target.className = that.initData.themePrefix + "-dropdown-normal-style";
            });
//            Event.observe(selectYearCellPlus, "mouseout", function (event) {
//                clearInterval(this.intervalID2);
//                Event.element(event).className = this.initData.themePrefix + "-dropdown-normal-style";
//            }.bindAsEventListener(this), false);

            jQuery(selectYearCellPlus).on("mousedown touchstart", function(event){
            	 clearInterval(that.intervalID2);
            	 that.intervalID2 = setInterval((function () {
            		 that._incYear();
                 }).bind(this), 30);
            });
//            Event.observe(selectYearCellPlus, "mousedown", function (event) {
//                clearInterval(this.intervalID2);
//                this.intervalID2 = setInterval((function () {
//                    this._incYear();
//                }).bind(this), 30);
//            }.bindAsEventListener(this), false);

            jQuery(selectYearCellPlus).on("mouseup touchend", function(event){
                clearInterval(that.intervalID2);
            });
//            Event.observe(selectYearCellPlus, "mouseup", function (event) {
//                clearInterval(this.intervalID2);
//            }.bindAsEventListener(this), false);
            //HIS_FIX_END

            this.yearConstructed = true;
        }
    };

    org.apache.myfaces.PopupCalendar.prototype._popDownYear = function () {
        clearInterval(this.intervalID1);
        clearTimeout(this.timeoutID1);
        clearInterval(this.intervalID2);
        clearTimeout(this.timeoutID2);
        this.selectYearDiv.classList.add("jscalendar-hidden"); 
        this.selectYearDiv.classList.remove("jscalendar-visible"); 
        this._hidePopupPostProcess(this.selectYearDiv);
    };

    org.apache.myfaces.PopupCalendar.prototype._popUpYear = function () {
        var leftOffset;
        this._fixPopupDomOrder(this.selectYearDiv);
        this._constructYear();
        if (this.dom || this.ie6) {
    		this.selectYearDiv.classList.remove("jscalendar-hidden");
    		this.selectYearDiv.classList.add("jscalendar-visible");
		} else {
    		this.selectYearDiv.classList.remove("jscalendar-hidden");
    		this.selectYearDiv.classList.add("jscalendar-visible");
		}
        leftOffset = parseInt(this._formatInt(this.calendarDiv.style.left), 10) + this.yearSpan.offsetLeft;
        if (this.ie6)
            leftOffset += 6;
        this.selectYearDiv.style.left = leftOffset + "px";
        this.selectYearDiv.style.top = parseInt(this._formatInt(this.calendarDiv.style.top), 10) + 26 + "px";

        this._showPopupPostProcess(this.selectYearDiv);
    };

    org.apache.myfaces.PopupCalendar.prototype._appendCell = function (parentElement, value) {
        var cell = document.createElement("td");
        //HIS_FIX_BEGIN
        jQuery(cell).css("text-align", "right");
//        Element.setStyle(cell, "text-align:right;");
        //HIS_FIX_END

        if (value && value != "") {
            cell.appendChild(document.createTextNode(value));
        }
        else {
            this._appendNbsp(cell);
        }

        parentElement.appendChild(cell);
    };

    org.apache.myfaces.PopupCalendar.prototype._getDateStyle = function (datePointer) {
        var sStyle = this.initData.themePrefix + "-normal-day-style";
        //regular day

        if ((datePointer == this.dateNow) &&
                (this.selectedDate.month == this.monthNow) && (this.selectedDate.year == this.yearNow)) //today
        {
            sStyle = this.initData.themePrefix + "-current-day-style";
        }
        else if (this.dayPointer % 7 == (this.initData.startAt * -1) + 1) //end-of-the-week day
        {
            sStyle = this.initData.themePrefix + "-end-of-weekday-style";
        }

        //selected day
        if ((datePointer == this.saveSelectedDate.date) &&
                (this.selectedDate.month == this.saveSelectedDate.month) &&
                (this.selectedDate.year == this.saveSelectedDate.year)) {
            sStyle += " " + this.initData.themePrefix + "-selected-day-style";
        }

        for (k = 0; k < this.holidaysCounter; k++) {
            if ((parseInt(this._formatInt(this.holidays[k].d), 10) == datePointer) && (parseInt(this._formatInt(this.holidays[k].m), 10) == (this.selectedDate.month + 1))) {
                if ((parseInt(this._formatInt(this.holidays[k].y), 10) == 0) || ((parseInt(this._formatInt(this.holidays[k].y), 10) == this.selectedDate.year) && (parseInt(this._formatInt(this.holidays[k].y), 10) != 0))) {
                    sStyle += " " + this.initData.themePrefix + "-holiday-style";
                }
            }
        }

        return sStyle;
    };

    org.apache.myfaces.PopupCalendar.prototype._getHolidayHint = function (datePointer) {
        var sHint = "";
        for (k = 0; k < this.holidaysCounter; k++) {
            if ((parseInt(this._formatInt(this.holidays[k].d), 10) == datePointer) && (parseInt(this._formatInt(this.holidays[k].m), 10) == (this.selectedDate.month + 1))) {
                if ((parseInt(this._formatInt(this.holidays[k].y), 10) == 0) || ((parseInt(this._formatInt(this.holidays[k].y), 10) == this.selectedDate.year) && (parseInt(this._formatInt(this.holidays[k].y), 10) != 0))) {
                    sHint += sHint == "" ? this.holidays[k].desc : "\n" + this.holidays[k].desc;
                }
            }
        }

        return sHint;
    };

    org.apache.myfaces.PopupCalendar.prototype._addWeekCell = function (currentRow, startDate, weekSelectable, sNormalStyle, sSelectStyle) {
        var cell = document.createElement("td");
        //HIS_FIX_BEGIN
        jQuery(cell).css("text-align", "right");
//        Element.setStyle(cell, "text-align:right;");
        //HIS_FIX_END
        
        var weekDate = this.stdDateFormatter.getWeekDate(startDate);
        if (weekSelectable) {
            var link = document.createElement("a");
            link.className = sNormalStyle;
            link.sNormalStyle = sNormalStyle;
            link.sSelectStyle = sSelectStyle;
            link.setAttribute("href", "#");
            link.appendChild(document.createTextNode(weekDate.week + " "));

            link.dateObj = this.stdDateFormatter.getDateForWeekDate(weekDate);

            cell.appendChild(link);

            //HIS_FIX_BEGIN
            var that = this;
            jQuery(link).on("mousemove", function(event){
            	 window.status = that.initData.selectDateMessage.replace(
                         "[date]",
                         that._constructDate(link.dateObj));
            });
//            Event.observe(link, "mousemove", function (event) {
//                window.status = this.initData.selectDateMessage.replace(
//                        "[date]",
//                        this._constructDate(link.dateObj));
//            }.bindAsEventListener(this), false);

            jQuery(link).on("mouseout", function(event){
            	   var elem = event.target;
                   elem.className = elem.sNormalStyle;
                   window.status = "";
            });
//            Event.observe(link, "mouseout", function (event) {
//                var elem = Event.element(event);
//                elem.className = elem.sNormalStyle;
//                window.status = "";
//            }.bindAsEventListener(this), false);

            jQuery(link).on("click", function(event){
            	var elem = event.target;
            	that.selectedDate.year = elem.dateObj.getFullYear();
            	that.selectedDate.month = elem.dateObj.getMonth();
            	that.selectedDate.date = elem.dateObj.getDate();
            	that._closeCalendar();
            	event.preventDefault();
            	event.stopPropagation();
            });
//            Event.observe(link, "click", function (event) {
//                var elem = Event.element(event);
//                this.selectedDate.year = elem.dateObj.getFullYear();
//                this.selectedDate.month = elem.dateObj.getMonth();
//                this.selectedDate.date = elem.dateObj.getDate();
//                this._closeCalendar();
//                Event.stop(event);
//            }.bindAsEventListener(this), false);

            jQuery(link).on("mouseover", function(event){
	           	var elem = event.target;
	            elem.className = elem.sSelectStyle;
            });
//            Event.observe(link, "mouseover", function (event) {
//                var elem = Event.element(event);
//                elem.className = elem.sSelectStyle;
//            }.bindAsEventListener(this), false);
            //HIS_FIX_END
        }
        else {
            var span = document.createElement("span");
            span.className = sNormalStyle;
            span.appendChild(document.createTextNode(weekDate.week + " "));
            cell.appendChild(span);
        }

        currentRow.appendChild(cell);
    };

    org.apache.myfaces.PopupCalendar.prototype._constructCalendar = function () {
        var aNumDays = Array(31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

        var dateMessage;
        var startDate = new Date(this.selectedDate.year, this.selectedDate.month, 1);
        var numDaysInMonth = null;

        if (this.selectedDate.month == 1) {
            // to compute the number of days in february, select first day of march,
            // subtract 24 hours then query the day-of-the-month.
            var msecs = new Date(this.selectedDate.year, this.selectedDate.month + 1, 1).getTime();
            var endDate = new Date(msecs - this._MSECS_PER_DAY);
            numDaysInMonth = endDate.getDate();
        }
        else {
            numDaysInMonth = aNumDays[this.selectedDate.month];
        }

        this.datePointer = 0;
        this.dayPointer = startDate.getDay() - this.initData.startAt;

        if (this.dayPointer < 0)
            this.dayPointer = 6;

        this._removeAllChildren(this.contentSpan);

        var contentTable = document.createElement("table");
        //HIS_FIX_BEGIN
        jQuery(contentTable).css("border", "0px");
//        Element.setStyle(contentTable, "border:0px;");
        //HIS_FIX_END
        contentTable.className = this.initData.themePrefix + "-body-style";

        this.contentSpan.appendChild(contentTable);

        var contentBody = document.createElement("tbody");
        contentTable.appendChild(contentBody);

        var contentRow = document.createElement("tr");
        contentBody.appendChild(contentRow);

        if (this.initData.showWeekNumber == 1) {
            var showWeekNumberCell = document.createElement("td");
            //HIS_FIX_BEGIN
            jQuery(showWeekNumberCell).css({
            	"width": "27px",
            	"font-weight": "bold"
            });
//            Element.setStyle(showWeekNumberCell, "width:27px;font-weight:bold;");
            //HIS_FIX_END

            contentRow.appendChild(showWeekNumberCell);

            showWeekNumberCell.appendChild(document.createTextNode(this.initData.weekString));

            var dividerCell = document.createElement("td");
            //HIS_FIX_BEGIN
            jQuery(dividerCell).css("width", "1px");
//            Element.setStyle(dividerCell, "width:1px;");
            //HIS_FIX_END
            if (this.ie6) //fix for https://issues.apache.org/jira/browse/TOMAHAWK-1184
                dividerCell.setAttribute("rowSpan", "7");
            else
                dividerCell.setAttribute("rowspan", "7");
            dividerCell.className = this.initData.themePrefix + "-weeknumber-div-style";

            contentRow.appendChild(dividerCell);

            var dividerImg = document.createElement("img");
            dividerImg.setAttribute("src", this.initData.imgDir + "divider.gif" + this.initData.imgDirSuffix);
            //HIS_FIX_BEGIN
            jQuery(dividerImg).css("width", "1px");
//            Element.setStyle(dividerImg, "width:1px;");
            //HIS_FIX_END
            dividerCell.appendChild(dividerImg);
        }

        for (i = 0; i < 7; i++) {
            var dayNameCell = document.createElement("td");
            //HIS_FIX_BEGIN
            jQuery(dayNameCell).css({
            	"width": "27px",
            	"text-align": "right",
            	"font-weight": "bold"
            });
//            Element.setStyle(dayNameCell, "width:27px;text-align:right;font-weight:bold;");
            //HIS_FIX_END
            contentRow.appendChild(dayNameCell);

            dayNameCell.appendChild(document.createTextNode(this.initData.dayName[i]));
        }

        var currentRow = document.createElement("tr");
        contentBody.appendChild(currentRow);

        var weekSelectable = this._isWeekSelectable();
        var sWeekNormalStyle = this.initData.themePrefix + "-normal-week-style";
        var sWeekSelectStyle = sWeekNormalStyle + " " + this.initData.themePrefix + "-would-be-selected-week-style";

        if (this.initData.showWeekNumber == 1) {
            this._addWeekCell(currentRow, startDate, weekSelectable, sWeekNormalStyle, sWeekSelectStyle);
        }

        for (var i = 1; i <= this.dayPointer; i++) {
            this._appendCell(currentRow);
        }

        for (this.datePointer = 1; this.datePointer <= numDaysInMonth; this.datePointer++) {
            this.dayPointer++;
            var dateCell = document.createElement("td");
            //HIS_FIX_BEGIN
            jQuery(dateCell).css("text-align", "right");
//            Element.setStyle(dateCell, "text-align:right;");
            //HIS_FIX_END
            
            currentRow.appendChild(dateCell);

            var sStyle = this._getDateStyle(this.datePointer);
            var sHint = this._getHolidayHint(this.datePointer);

            var sSelectStyle = sStyle + " " + this.initData.themePrefix + "-would-be-selected-day-style";
            var sNormalStyle = sStyle;

            if (this._isDaySelectable()) {

                var dateLink = document.createElement("a");
                dateLink.className = sStyle;
                dateLink.setAttribute("href", "#");
                dateLink.setAttribute("title", sHint);

                dateLink.sNormalStyle = sNormalStyle;
                dateLink.sSelectStyle = sSelectStyle;
                dateLink.datePointer = this.datePointer;

                dateCell.appendChild(dateLink);
                
                //HIS_FIX_BEGIN
                var that = this;
                jQuery(dateLink).on("mousemove", function(event){
                    window.status = that.initData.selectDateMessage.replace("[date]", that._constructDate(this.datePointer, that.selectedDate.month, that.selectedDate.year));
                });
//                Event.observe(dateLink, "mousemove", function (event) {
//                    window.status = this.initData.selectDateMessage.replace("[date]", this._constructDate(this.datePointer, this.selectedDate.month, this.selectedDate.year));
//                }.bindAsEventListener(this), false);
                
                jQuery(dateLink).on("mouseout", function(event){
                	var elem = event.target;
                    elem.className = elem.sNormalStyle;
                    window.status = "";
                });
//                Event.observe(dateLink, "mouseout", function (event) {
//                    var elem = Event.element(event);
//                    elem.className = elem.sNormalStyle;
//                    window.status = "";
//                }.bindAsEventListener(this), false);
                
                jQuery(dateLink).on("click", function(event){
                	var elem = event.target;
                	that.selectedDate.date = elem.datePointer;
                	that._closeCalendar();
                	event.preventDefault();
                	event.stopPropagation();
                });
//                Event.observe(dateLink, "click", function (event) {
//                    var elem = Event.element(event);
//                    this.selectedDate.date = elem.datePointer;
//                    this._closeCalendar();
//                    Event.stop(event);
//                }.bindAsEventListener(this), false);
                
                jQuery(dateLink).on("mouseover", function(event){
                	var elem = event.target;
                    elem.className = elem.sSelectStyle;
                });
//                Event.observe(dateLink, "mouseover", function (event) {
//                    var elem = Event.element(event);
//                    elem.className = elem.sSelectStyle;
//                }.bindAsEventListener(this), false);
                //HIS_FIX_END

                this._appendNbsp(dateLink);
                dateLink.appendChild(document.createTextNode(this.datePointer));
                this._appendNbsp(dateLink);
            }
            else {
                var dateSpan = document.createElement("span");
                dateCell.appendChild(dateSpan);

                dateSpan.appendChild(document.createTextNode(this.datePointer));
                dateSpan.className = sStyle;
                dateSpan.setAttribute("title", sHint);
            }

            if ((this.dayPointer + this.initData.startAt) % 7 == this.initData.startAt) {
                currentRow = document.createElement("tr");
                contentBody.appendChild(currentRow);

                if ((this.initData.showWeekNumber == 1) && (this.datePointer < numDaysInMonth)) {
                    var startDate = new Date(this.selectedDate.year, this.selectedDate.month, this.datePointer + 1);
                    this._addWeekCell(currentRow, startDate, weekSelectable, sWeekNormalStyle, sWeekSelectStyle);
                }
            }
        }

        this._removeAllChildren(this.monthSpan);

        this._appendNbsp(this.monthSpan);
        this.monthSpan.appendChild(document.createTextNode(this.initData.monthName[this.selectedDate.month]));
        this._appendNbsp(this.monthSpan);

        this.changeMonthImg = document.createElement("img");
        this.changeMonthImg.setAttribute("src", this.initData.imgDir + "drop1.gif" + this.initData.imgDirSuffix);
        this.changeMonthImg.setAttribute("width", "12px");
        this.changeMonthImg.setAttribute("height", "10px");
        //HIS_FIX_BEGIN
        jQuery(that.changeMonthImg).css("border", "0px");
//        Element.setStyle(this.changeMonthImg, "border:0px;");
        //HIS_FIX_END

        this.monthSpan.appendChild(this.changeMonthImg);

        // Year dropdown list (YYYY plus dropdown icon)
        this._removeAllChildren(this.yearSpan);
        this._appendNbsp(this.yearSpan);
        this.yearSpan.appendChild(document.createTextNode(this.selectedDate.year));
        this._appendNbsp(this.yearSpan);
        this.changeYearImg = document.createElement("img");
        this.changeYearImg.setAttribute("src", this.initData.imgDir + "drop1.gif" + this.initData.imgDirSuffix);
        this.changeYearImg.setAttribute("width", "12px");
        this.changeYearImg.setAttribute("height", "10px");
        //HIS_FIX_BEGIN
        jQuery(that.changeYearImg).css("border", "0px");
//        Element.setStyle(this.changeYearImg, "border:0px;");
        //HIS_FIX_END
        this.yearSpan.appendChild(this.changeYearImg);

        // Accept Month icon
        if (this.acceptMonthSpan) {
            this._removeAllChildren(this.acceptMonthSpan);
            var acceptMonthImg = document.createElement("img");
            acceptMonthImg.setAttribute("src", this.initData.imgDir + "accept.gif" + this.initData.imgDirSuffix);
            acceptMonthImg.setAttribute("width", "15px");
            acceptMonthImg.setAttribute("height", "13px");
            //HIS_FIX_BEGIN
            jQuery(acceptMonthImg).css("border", "0px");
//            Element.setStyle(acceptMonthImg, "border:0px;");
            //HIS_FIX_END
            acceptMonthImg.setAttribute("alt", "Accept the current month selection");
            this.acceptMonthSpan.appendChild(acceptMonthImg);
        }

        // Close Popup icon
        this._removeAllChildren(this.closeCalendarSpan);
        var closeButtonImg = document.createElement("img");
        closeButtonImg.setAttribute("src", this.initData.imgDir + "close.gif" + this.initData.imgDirSuffix);
        closeButtonImg.setAttribute("width", "15px");
        closeButtonImg.setAttribute("height", "13px");
        //HIS_FIX_BEGIN
        jQuery(closeButtonImg).css("border", "0px");
//        Element.setStyle(closeButtonImg, "border:0px;");
        //HIS_FIX_END
        closeButtonImg.setAttribute("alt", "Close the calendar");
        this.closeCalendarSpan.appendChild(closeButtonImg);

        this._recalculateElement(this.calendarDiv);
    };

    org.apache.myfaces.PopupCalendar.prototype._popUpCalendar = function (ctl, ctl2, format) {
        if (!this.bPageLoaded) {
            // The user has clicked a button before the initialisation of this
            // class has completed. Just ignore the click.. 
            return;
        }

        if (!this.calendarDiv.classList.contains("calendar-visible")) {
            this.ctlToPlaceValue = ctl2;
            this.dateFormat = format;

            this.stdDateFormatter = new org.apache.myfaces.dateformat.SimpleDateFormatter(
                    this.dateFormat, this.dateFormatSymbols, this.initData.startAt);
            var dateSelected = this.stdDateFormatter.parse(ctl2.value);

            if (dateSelected) {
                this.selectedDate.sec = dateSelected.getSeconds();
                this.selectedDate.min = dateSelected.getMinutes();
                this.selectedDate.hour = dateSelected.getHours();
                this.selectedDate.date = dateSelected.getDate();
                this.selectedDate.month = dateSelected.getMonth();

                //https://issues.apache.org/jira/browse/TOMAHAWK-1595
                //http://de.selfhtml.org/javascript/objekte/date.htm#get_year
                var fullYear = dateSelected.getFullYear;
                var yearDetermined = parseInt(((fullYear) ? dateSelected.getFullYear() : dateSelected.getYear()), 10);

                if (!fullYear && yearDetermined < 1000) {
                    yearDetermined = yearDetermined + 1900;
                }

                this.selectedDate.year = yearDetermined;
            }
            else {
                this.selectedDate.date = this.dateNow;
                this.selectedDate.month = this.monthNow;
                this.selectedDate.year = this.yearNow;
            }

            this._popUpCalendar_Show(ctl);
        }
        else {
            this._hideCalendar();
            if (this.ctlNow != ctl) {
                this._popUpCalendar(ctl, ctl2, format);
            }
        }
        this.ctlNow = ctl;
    };

    org.apache.myfaces.PopupCalendar.prototype._popUpCalendarForInputDate = function (clientId, format) {
        if (this.bPageLoaded) {
            this.myFacesCtlType = "x:inputDate";
            this.myFacesInputDateClientId = clientId;
            this.dateFormat = format;

            //Init stdDateFormatter
            this.stdDateFormatter = new org.apache.myfaces.dateformat.SimpleDateFormatter(
                    this.dateFormat, this.dateFormatSymbols, this.initData.startAt);

            this.selectedDate.date = document.getElementById(clientId + ".day").value != "" ? parseInt(this._formatInt(document.getElementById(clientId + ".day").value), 10) : this.dateNow;
            this.selectedDate.month = document.getElementById(clientId + ".month").value != "-1" ? parseInt(this._formatInt(document.getElementById(clientId + ".month").value), 10) - 1 : this.monthNow;
            this.selectedDate.year = document.getElementById(clientId + ".year").value != "" ? parseInt(this._formatInt(document.getElementById(clientId + ".year").value), 10) : this.yearNow;
            this.ctlNow = document.getElementById(clientId + ".day");
            this._popUpCalendar_Show(document.getElementById(clientId + ".day"));
        }
    };

    org.apache.myfaces.PopupCalendar.prototype._getStyle = function (ctl, property) {
        var value = null;

        // local style
        if (ctl.style[property]) {
            value = ctl.style[property];
        }
        // IE syntax
        else if (ctl.currentStyle && ctl.currentStyle[property]) {
            value = ctl.currentStyle[property];
        }
        // DOM syntax
        else if (document.defaultView && document.defaultView.getComputedStyle) {
            var computed = document.defaultView.getComputedStyle(ctl, '');

            if (computed && computed.getPropertyValue(property)) {
                value = computed.getPropertyValue(property);
            }
        }
        return value;
    };

    org.apache.myfaces.PopupCalendar.prototype._popUpCalendar_Show = function (ctl) {
        this.saveSelectedDate.date = this.selectedDate.date;
        this.saveSelectedDate.month = this.selectedDate.month;
        this.saveSelectedDate.year = this.selectedDate.year;

        var leftpos = 0;
        var toppos = 0;

        var aTag = ctl;
        var aCSSPosition = null;
        var aTagPositioningisAbsolute = false;
        // Added try-catch to the next loop (MYFACES-870)
        try {

            do {
                aTag = aTag.offsetParent;
                leftpos += aTag.offsetLeft;
                toppos += aTag.offsetTop;
            }
            while ((null != aTag.offsetParent ) && ('undefined' != aTag.offsetParent ));
        }
        catch (ex) {
            // ignore
        }

        var leftScrollOffset = 0;
        var topScrollOffset = 0;

        aTag = ctl;
        // Added try-catch (MYFACES-870)
        try {
            do {
                if ('undefined' != typeof(aTag.scrollLeft) && null != aTag.scrollLeft)
                    leftScrollOffset += parseInt(aTag.scrollLeft);
                if ('undefined' != typeof(aTag.scrollTop) && null != aTag.scrollTop)
                    topScrollOffset += parseInt(aTag.scrollTop);

                aTag = aTag.parentNode;
            }
            while ((aTag.tagName.toUpperCase() != "BODY") && (aTag.tagName.toUpperCase() != "HTML"));
            //while ('undefined' != typeof(aTag) && null != aTag);
        }
        catch (ex) {
            // ignore
        }
        
        // needs to be called before positioning, otherwise the width won't be correct
        this._constructCalendar(1, this.selectedDate.month, this.selectedDate.year);
        
        var bodyRect = this._getVisibleBodyRectangle();
        var cal = this.calendarDiv;

        var top = 0;
        var left = 0

        top = ctl.offsetTop + toppos - topScrollOffset + ctl.offsetHeight + 2;
        left = ctl.offsetLeft + leftpos - leftScrollOffset;

        if (this.initData.popupLeft) {
            left -= cal.offsetWidth;
        }
        // use document.body.offsetWidth to get width without any scrollbar
        if (left + cal.offsetWidth > document.body.offsetWidth) {
            left = document.body.offsetWidth - cal.offsetWidth;
        }
        if (top + cal.offsetHeight > bodyRect.bottom) {
            top = bodyRect.bottom - cal.offsetHeight;
        }
        if (left < bodyRect.left) {
            left = bodyRect.left;
        }
        if (top < bodyRect.top) {
            top = bodyRect.top;
        }

        /*we have to remap the popup so that we can handle the positioning in a neutral way*/
        if (this.calendarDiv.parentNode != document.body) {
            this.calendarDiv.parentNode.removeChild(this.calendarDiv);
            document.body.appendChild(this.calendarDiv);
        }

        this.calendarDiv.style.left = this.initData.fixedX == -1 ? left + "px" : this.initData.fixedX;
        this.calendarDiv.style.top = this.initData.fixedY == -1 ? top + "px" : this.initData.fixedY;
        
        if (this.dom || this.ie6) {
    		this.calendarDiv.classList.remove("jscalendar-hidden");
    		this.calendarDiv.classList.add("jscalendar-visible");
		} else {
    		this.calendarDiv.classList.remove("jscalendar-hidden");
    		this.calendarDiv.classList.add("jscalendar-visible");
		}
        this.bCalendarHidden = false;

        setTimeout((function () {
            this._showPopupPostProcess(this.calendarDiv);
        }).bind(this), 200);

        this._showPopupPostProcess(this.calendarDiv);

        this.bClickOnCalendar = true;
    };

    org.apache.myfaces.PopupCalendar.prototype._getVisibleBodyRectangle = function () {
        var visibleRect = new org.apache.myfaces.Rectangle();

        if (typeof window.pageYOffset != "undefined") {
            //Most non IE
            visibleRect.top = window.pageYOffset;
            visibleRect.left = window.pageXOffset;
        }
        else if (document.body && document.body.scrollTop) {
            //IE 6 strict mode
            visibleRect.top = document.body.scrollTop;
            visibleRect.left = document.body.scrollLeft;
        }
        else if (document.documentElement && document.documentElement.scrollTop) {
            //Older IE
            visibleRect.top = document.documentElement.scrollTop;
            visibleRect.left = document.documentElement.scrollLeft;
        }

        if (window.innerWidth != undefined) {
            //Most non-IE
            visibleRect.right = visibleRect.left + window.innerWidth;
            visibleRect.bottom = visibleRect.top + window.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight) {
            //IE 6 strict mode
            visibleRect.right = visibleRect.left + document.documentElement.clientWidth;
            visibleRect.bottom = visibleRect.top + document.documentElement.clientHeight;
        }
        else if (document.body && document.body.clientHeight) {
            //IE 4 compatible
            visibleRect.right = visibleRect.left + document.body.clientWidth;
            visibleRect.bottom = visibleRect.top + document.body.clientHeight;
        }
        return visibleRect;
    };

    org.apache.myfaces.PopupCalendar.prototype._formatInt = function (str) {

        if (typeof str == 'string') {

            //truncate 0 for number less than 10
            if (str.charAt && str.charAt(0) == "0") { // <----- Change, added str.charAt for method availability detection (MYFACES)
                return str.charAt(1);
            }

        }
        return str;

    };

    org.apache.myfaces.Rectangle = function() {
        this.top = 0;
        this.left = 0;
        this.bottom = 0;
        this.right = 0;
    };

}    
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * @author Bruno Aranda (latest modification by $Author: dziegielewski#his.de $)
 * @version $Revision: 1.3 $ $Date: 2016/04/18 11:50:34 $
 */

window.org = window.org || {};
org.apache = org.apache || {};
org.apache.myfaces = org.apache.myfaces || {};

if (!org.apache.myfaces.Picklist) {
    org.apache.myfaces.Picklist = {};

// moves all the items to the selected list
    org.apache.myfaces.Picklist.addAllToSelected = function (availableListId, selectedListId, hiddenId) {
        var availableList = document.getElementById(availableListId);
        var selectedList = document.getElementById(selectedListId);

        org.apache.myfaces.Picklist.moveAll(availableList, selectedList, hiddenId);
        org.apache.myfaces.Picklist.updateHidden(selectedList, hiddenId);
    };

// removes all the items from the selected list
    org.apache.myfaces.Picklist.removeAllFromSelected = function (availableListId, selectedListId, hiddenId) {
        var availableList = document.getElementById(availableListId);
        var selectedList = document.getElementById(selectedListId);

        org.apache.myfaces.Picklist.moveAll(selectedList, availableList, hiddenId);
        org.apache.myfaces.Picklist.updateHidden(selectedList, hiddenId);
    };

// moves an item to the selected list
    org.apache.myfaces.Picklist.addToSelected = function (availableListId, selectedListId, hiddenId) {
        var availableList = document.getElementById(availableListId);
        var selectedList = document.getElementById(selectedListId);

        org.apache.myfaces.Picklist.move(availableList, selectedList, hiddenId);
        org.apache.myfaces.Picklist.updateHidden(selectedList, hiddenId);
    };

// removes an item from the selected list
    org.apache.myfaces.Picklist.removeFromSelected = function (availableListId, selectedListId, hiddenId) {
        var availableList = document.getElementById(availableListId);
        var selectedList = document.getElementById(selectedListId);

        org.apache.myfaces.Picklist.move(selectedList, availableList, hiddenId);
        org.apache.myfaces.Picklist.updateHidden(selectedList, hiddenId);
    };

    org.apache.myfaces.Picklist.move = function (fromList, toList, hiddenId) {
        // Return, if no items selected
        var selectedIndex = fromList.selectedIndex;
        if (selectedIndex < 0) {
            return;
        }

        var tLen = toList.options.length;
        // Decremental loop, so the index is not affected in the moves
        for (var i = fromList.options.length - 1; i >= 0; i--) {
            if (fromList.options[i].selected) {
                toList.options.add(new Option(fromList.options[i].text),tLen);
                toList.options[tLen].value = fromList.options[i].value;
                fromList.options[i] = null;
            }
        }
        
        updateAriaDescribedBy(fromList, toList);
    };

    org.apache.myfaces.Picklist.moveAll = function (fromList, toList, hiddenId) {

    	var tLen = toList.options.length;
        // Decremental loop, so the index is not affected in the moves
        for (var i = fromList.options.length - 1; i >= 0; i--) {
            toList.options.add(new Option(fromList.options[i].text),tLen);
            toList.options[tLen].value = fromList.options[i].value;
            fromList.options[i] = null;
        }
    };

// Selection - invoked on submit
    org.apache.myfaces.Picklist.updateHidden = function(selectedList, hiddenId) {
        var hiddenField = document.getElementById(hiddenId);

        var arrValues = new Array(selectedList.options.length);
        for (var i = 0; i < selectedList.options.length; i++) {
            arrValues[i] = selectedList.options[i].value;
        }
        //https://issues.apache.org/jira/browse/TOMAHAWK-1653
        //we set a neutral divider string, which allows
        //comma and other dividiers to be used
        hiddenField.value = arrValues.join("|MFVAL_DIV|");
    };
    
    updateAriaDescribedBy = function (fromList, toList) {
		var ariaDescribedTextFromList = document.getElementById(fromList.id);
        var ariaDescribedTextToList = document.getElementById(toList.id);
        if(ariaDescribedTextFromList.children.length > 0){
			ariaDescribedTextFromList.removeAttribute("aria-describedby");
		}
		else{
			ariaDescribedTextFromList.setAttribute("aria-describedby",fromList.id + "_emptyDescription");
		}
		if(ariaDescribedTextToList.children.length > 0){
			ariaDescribedTextToList.removeAttribute("aria-describedby");
		}
		else{
			ariaDescribedTextToList.setAttribute("aria-describedby", toList.id + "_emptyDescription");
			
		}
	}
}use_package('de.his.component');
/**
* Iframe sichtbar machen, wenn der Inhalt fertig ist.
* Bis dahin wird ein Warte-Icon angezeigt
* 
* @autor wassmann@his.de, wahrendorff@his.de
*/


/**
 * Funktionen ausführen, wenn die Seite fertig geladen ist
 */
de.his.modules.IframeVisibility = new function() {
    de.his.modules.ModuleRegistry
    	.registerModule(this)
    	.registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.modules.IframeVisibility";

    this.init = function() {
    
		jQuery('.frameWrapper-behavior > iframe').each(function(){
    		var iFrame = jQuery(this);
    		if(!iFrame.data('initialized')){
    			
        		iFrame.data('initialized','true');
        		//console.log("iFrame initialized.. ", iFrame);
        		
        		iFrame.on("load", function() {
        			//console.log("iFrame remove loadingAnimation event.. ", id);
        			iFrame.siblings(".loadingAnimationContainer").remove();
        			iFrame.siblings(".frameloaderBackground").remove();
        		
        			// reload portlet periodically
	        		var iframeWrapper = iFrame.parent();
	        		var reload = iframeWrapper.data("portlet-reload");
	        		if(reload !== false){
	        			setReloadTimer(reload, iFrame);
	        		}
        		});
    		} else {
    			console.log("iFrame already initialized.. ",iFrame.attr("id"));
    			
    			iFrame.on("load", function() {
    				// might need to be removed again when sitting in a lazy loaded collapesible Filedset
    				iFrame.siblings(".loadingAnimationContainer").remove();
        			iFrame.siblings(".frameloaderBackground").remove();
    			});
    		}
    		try {
	    		// Check if loading was complete before we set the load event 
				var iframeDoc = iFrame[0].contentDocument || iFrame[0].contentWindow.document;
					
			    if (iframeDoc && iframeDoc.readyState  == 'complete') {
			    	iFrame.siblings(".loadingAnimationContainer").remove();
	    			iFrame.siblings(".frameloaderBackground").remove();
			    }
		    } catch (error) {
   				console.log("Fehler beim Zugriff auf das Dokument ", error);
			}
    	});
    	
    };
    
    var setReloadTimer = function(reload, iFrame){
    	setTimeout(function() {
    		console.log("refreshing iFrame "+iFrame.attr('id'));
    		iFrame.attr('src', iFrame.parent().data('src'));
    		setReloadTimer(reload,iFrame);
        }, reload);
    }

    this.refresh = function() {
        this.init();
    };

};
use_package('de.his.modules');
/**
* Portlets die in einem IFrame laufen sollen sich automatisch in der
* Höhe anpassen
* 
* @author wassmann@his.de
* @author wahrendorff@his.de
*/

/**
 * Funktionen ausführen, wenn die Seite fertig geladen ist
 */
de.his.modules.IframePortletResize = new function() {
	de.his.modules.ModuleRegistry
		.registerModule(this)
		.registerAjaxRefreshModule(this);
	
	this.moduleName = "de.his.modules.IframePortletResize";
	
	var self = this;
	
	this.init = function() {
		console.log("IframePortletResize init");
		this.handleEvents();
    };
    
    this.refresh = function() {
    	self.handleResizeWithPortalHelper();
    };
    
    this.handleEvents = function (){
//    	console.log("IframePortletResize handleEvents");
    	
    	this.handleResizeWithPortalHelper();
    	this.handleWindowResizeEvent();
    	
    	//this.handleAjaxLoading(); // perfect!
    	    	
    }
    
    this.handleWindowResizeEvent = function(){
		var timer = 0;
		var delay = function(fn, ms) {
            return function(...args) {
                clearTimeout(timer);
                timer = setTimeout(fn.bind(this, ...args), ms || 0);
            }
        };
    	jQuery(window).resize(delay(function(evt){
			self.handleResizeWithPortalHelper();
		}, 400));
    }
    
    this.handleResizeWithPortalHelper = function(){
    	console.log("handleResizeWithPortalHelper");
    	jQuery("iframe").each(function(index){
    		var $iframe = jQuery(this);
    		var autoResize = $iframe.parent().data("portlet-auto-resize");
    		console.log("handleResizeWithPortalHelper Autoresize? " + autoResize);
    		
    		if($iframe.parent().hasClass('frameWrapper') && autoResize){
    			
    			
    			// keine iFramePortlets von fremden Seiten resizen
    			try{
    				var host = de.his.common.ContextInformation.get("host");
    				var urlParts = host.split(":");
    				var serverUrl = urlParts[0]+":"+urlParts[1];
    				console.log("host is: "+serverUrl);
    				if($iframe.attr('src').startsWith(serverUrl)){
    					console.log(serverUrl+" is local url...");
    					local = true;
    				}else{
    					// keine iFramePortlets von fremden Seiten resizen
    					if(!$iframe.hasClass('fullIframePage')){
    						local = false;
    						console.log("IframePortletResize "+$iframe.attr( "id" )+" wird nicht resized.");
    						return;
    					}
    				}
    			}catch(e){
    				// IE < 12
    				var host = de.his.common.ContextInformation.get("host");
    				if($iframe.attr('src').substr(0,host.length) === host){
    					local = true;
    				}else{
    					if(!$iframe.hasClass('fullIframePage')){
							local = false;
							return;
						}
    				}
    				
    			}
    			
    			console.log("IframePortletResize resize "+$iframe.attr( "id" ));
    			
    			if( $iframe.data( "his-iframe-loaded" ) ) {
    				if(autoResize){
        				$iframe.css("height","");
        			}
    				//portaHelper.js function
     	            resizeIt( $iframe );
     	        } else {
     	        	de.his.modules.eventRegistry.destroyEvent( "iframe_loaded_" + $iframe.attr( "id" ));
     	            de.his.modules.eventRegistry.addListener( "iframe_loaded_" + $iframe.attr( "id" ), function() {
     	            	if(autoResize){
     	    				$iframe.css("height","");
     	    			}
     	            	//portaHelper.js function
     	                resizeIt( $iframe );
     	                $iframe.data( "his-iframe-loaded", true );
     	            } );
			try {
     	            		// Check if loading was complete before we set the load event
				var iframeDoc = $iframe[0].contentDocument || $iframe[0].contentWindow.document;
				if ( iframeDoc.readyState  == 'complete' ) {
					if ( autoResize ) {
     	    					$iframe.css("height","");
     	    				}

     	            			//portaHelper.js function
     	                		resizeIt( $iframe );
     	                		$iframe.data( "his-iframe-loaded", true );
			 	}
			} catch (error) {
				console.log("Fehler beim Zugriff auf das Dokument ", error);
			}
     	        }
    		}
    	});
    };
    
    /**
     * START EXPERIMENTAL AJAX LOADING OF PORTLETS (WORKING!)
     */
    
//    this.handleAjaxLoading = function(){
//    	console.log("load iframe with ajax...");
//    	// load iFrame via AJAX.
//    	jQuery(".frameWrapper").each(function(index){
//    		
//    		var elem = jQuery(this);
//    		var autoResize = elem.data("portlet-auto-resize");
//    		var portletReload = elem.data("portlet-reload"); // data-portlet-reload="900000"
//    		
//    		if(!autoResize || typeof autoResize === 'undefined'){
//    			elem.css('height','460px');
//    			elem.css('overflow-x','auto');
//    		}
//    		self.loadPortlet(elem);
//    		
//    		// TODO: reload mechanism
//    		
//    	});
//    };
//    
//    this.loadPortlet = function(wrapperElement){
//    	var url = wrapperElement.data("src");
//    	jQuery.ajax({
//			type: 'GET',
//			url: url,
//			success : function(response){
//				// only use body content
//				var data = response.replace('<body', '<body><div id="fakebody"').replace('</body>','</div></body>');
//				var body = jQuery(data).filter('#fakebody');
//				wrapperElement.html(body);
//				console.log("Successful loaded portlet.");
//			}, 
//			error : function(response,b,c){
//				console.error("Error loading Portlet with ID "+wrapperElement.attr('id')+": " + c);
//			}
//		}); 
//    }
    
    /**
     * END EXPERIMENTAL AJAX LOADING OF PORTLETS (WORKING!)
     */
};
window.org=window.org||{};org.apache=org.apache||{};org.apache.myfaces=org.apache.myfaces||{};if(!org.apache.myfaces.Tree){org.apache.myfaces.Tree=function(){};org.apache.myfaces.Tree.treeNavClick=function(F,L,H,G,K,I,C,J,D){var E=document.getElementById(F);var M=E.style.display;if(M=="none"){M="block";org.apache.myfaces.CookieLib.setCookieAttrib(J,D,"x");}else{M="none";org.apache.myfaces.CookieLib.setCookieAttrib(J,D,"c");}E.style.display=M;if(L!=""){var B=document.getElementById(L);if(B.src.indexOf(H)>=0){B.src=G;}else{B.src=H;}}if(K!=""){var A=document.getElementById(K);if(A.src.indexOf(I)>=0){A.src=C;}else{A.src=I;}}};}window.org=window.org||{};org.apache=org.apache||{};org.apache.myfaces=org.apache.myfaces||{};if(!org.apache.myfaces.CookieLib){org.apache.myfaces.CookieLib=function(){};org.apache.myfaces.CookieLib.COOKIE_DELIM=";";org.apache.myfaces.CookieLib.COOKIE_KEYVAL="=";org.apache.myfaces.CookieLib.ATTRIB_DELIM=";";org.apache.myfaces.CookieLib.ATTRIB_KEYVAL="=";org.apache.myfaces.CookieLib.getRawCookie=function(C){var B=org.apache.myfaces.CookieLib;var D=C+B.COOKIE_KEYVAL;if(document.cookie){if(document.cookie.length>0){var E=document.cookie.indexOf(D);if(E!=-1){E+=D.length;var A=document.cookie.indexOf(B.COOKIE_DELIM,E);if(A==-1){A=document.cookie.length;}return unescape(document.cookie.substring(E,A));}}}return null;};org.apache.myfaces.CookieLib.setCookieAttrib=function(E,C,A){var B=org.apache.myfaces.CookieLib;var D=B.getCookie(E);D[C]=A;B.setCookie(E,D);};org.apache.myfaces.CookieLib.getCookieAttrib=function(D,B){var A=org.apache.myfaces.CookieLib;var C=A.getCookie(D);return C[B];};org.apache.myfaces.CookieLib.getCookie=function(H){var E=org.apache.myfaces.CookieLib;var G=new Array();var B=E.getRawCookie(H);if(typeof (B)!="undefined"&&B!=null){var C=B.split(E.ATTRIB_DELIM);for(var D=0;D<C.length;D++){var F=C[D].indexOf(E.ATTRIB_KEYVAL);var A=C[D].substring(0,F);var I=C[D].substring(F+1);G[A]=I;}}return G;};org.apache.myfaces.CookieLib.setCookie=function(F,E){var B=org.apache.myfaces.CookieLib;var D="";for(var A in E){var C=E[A];if(typeof (C)!="undefined"&&C!=null&&C!=""&&typeof (C)!="function"){if(A.indexOf(B.ATTRIB_KEYVAL)<0&&C.indexOf(B.ATTRIB_KEYVAL)<0&&A.indexOf(B.ATTRIB_DELIM)<0&&C.indexOf(B.ATTRIB_DELIM)<0){D+=((D=="")?"":B.ATTRIB_DELIM);D+=(A+B.ATTRIB_KEYVAL+C);}else{alert("Cookie attribute name and/or value contains a delimeter ("+B.ATTRIB_KEYVAL+" or "+B.ATTRIB_DELIM+").");}}}document.cookie=F+B.COOKIE_KEYVAL+escape(D);};}use_package("de.his.validation");

/**
 * Initialisiert die clientseitige Validierung via Parsley.js
 * Zu validierende Felder werden durch .parsleyValidation erkannt. Zusätzlich ist eine CSS Klasse am Feld gesetzt, welche den Namen
 * des entsprechenden Validators enthält. Dieser Name wird geparst und via dat- Attribut an das Feld geschrieben.
 * FIXME Ein setzen der data- Attribute via ApplyMetaData wäre schöner, jedoch hat das nicht überall funktioniert 
 * (wie zB klenke/klenke!, rolle: gebührenadmin, navigation Begründete Antragstypen bearbeiten, beliebiges Element bearbeiten, Auf der 
 * Detailseite in der unteren Tabelle "Absoluter Betrag, Minimal, Maximal" werden eigentlich validiert)
 * 
 * Hier werden auch die Klassen bei Fehler/Erfolg gesetzt:
 * Fehler, am Input: validation-failed inputError
 * Fehler, am Label: labelError
 * Erfolg, am Input: validation-passed
 * Erolg, am Label: keine!
 * 
 */

de.his.validation.initParsleyValidation = new function() {
    de.his.modules.ModuleRegistry
    	.registerModule(this)
    	.registerAjaxRefreshModule(this);

    this.moduleName = "de.his.validation.initParsleyValidation";

    var self = this;

    this.init = function() {
    	this.initValidation();
    	this.setParsleyLocale();
    }

    //Am refresh Modul regestrieren, damit auch Felder validiert werden, welche durch AJAX hinzukommen!
    this.refresh = function() {
    	this.init();
    }

    this.initValidation = function () {
		jQuery('.parsleyValidation').each(function() {
			var field = jQuery(this);
			var validatorId = self.getValidationIdentifier(field);
			field.attr("data-parsley-" + validatorId, "");
			var form = field.closest("form")

			if (form && form.attr('data-validataion-enabled') && !form.attr('data-initialized-parsley')) {
				// die tatsächliche technische Initialisierung des Formulars erfolgt hier. Hier kann auch die Konfiguration 
				// der Validierung erfolgen (wann soll Validierung ausgelöst werden, welche Klassen sollen gesetzt werden usw...)
				form.parsley({
					trigger: "focusout",
					triggerAfterFailure: "input",
					errorsMessagesDisabled: true,
					successClass:	"validation-passed",
					errorClass:	"validation-failed inputError",
					errorsWrapper: '<div></div>',
					errorTemplate: '<div class="errortext"></div>',
					errorsContainer: function (field) {
						//Damit sagen wir parsley, dass die Fehlermeldung an das Elternelement des Felds gehängt werden soll.
						// Sonst wird es direkt hinter das Feld gehängt, wodurch Hilfe/Info Buttons sich verschieben!
						return self.findCorrectParent(field.$element);
					}
				});
				
				// Wenn eine Validierung fehlschlägt, soll das label des Feldes eine entsprechende Klasse erhalten
				// FIXME Aktuell hat parsley.js hier noch keine Möglichkeit das direkt zu stylen, vielleicht in Zukunft?
				jQuery(form).parsley().on('field:error', function (fieldInstance) {
					var fieldId = fieldInstance.$element.attr("id");
					var label = document.getElementById(fieldId + "Label");
					if (label && !label.classList.contains('labelError')) {
						label.classList.add('labelError');
					}

					/*
					 * Fehlermeldungen werden hier manuell angezeigt. Dadurch ist es uns möglich den Namen des Labels
					 * vor die Fehlermeldung zu schreiben.
					 */
					var parent = self.findCorrectParent(fieldInstance.$element);
					var fieldErrorElement = jQuery(parent).find('.errortext');
					if (!fieldErrorElement.length) {
						var fieldMessages = fieldInstance.getErrorsMessages();
						if (fieldMessages) {
							var labelText = "";
							if (label) {
								labelText = label.innerText + ": ";
							}
							var msg = labelText + fieldMessages;
							fieldInstance.addError('fieldError', {message: msg, assert: true, updateClass: true});
						}
					}
				});
				
				// Wird ein Fehler vom Nutzer korrigiert, soll das Label keine Fehler Klasse mehr haben.
				jQuery(form).parsley().on('field:success', function (fieldInstance) {
					var fieldId = fieldInstance.$element.attr("id");
					var label = document.getElementById(fieldId + "Label");
					if (label && label.classList.contains('labelError')) {
						label.classList.remove('labelError');
					}
					// weil wir die Fehlermeldungen manuell anzeigen, müssen diese auch manuell wieder entfernt werden!
					fieldInstance.removeError("fieldError", {updateClass: true});
				});
				
				// Formular als initialisiert markieren.
				form.attr("data-initialized-parsley", "true");
			}
		});
    }

    /**
     *   Suche die in den Eltern Elementen nach einen übegreifenden Container, welcher auch Hilfe Buttons usw enthält. 
     *   Dieser wird dann genutzt um die Fehlermeldung anzuhängen. Sonst werden Hilfe Buttons usw. verschoben!
     */
    this.findCorrectParent = function(fieldInstance) {
    	var parent;
		var parentTagName;

		// Suche die in den Eltern Elementen nach einen übegreifenden Container, welcher auch 
		// Hilfe Buttons usw enthält. Dieser wird dann genutzt um die Fehlermeldung anzuhängen. Sonst
		// werden Hilfe Buttons usw. verschoben!
		for (var i = 0; i < 3; i++) {
			parent = fieldInstance.parent();
			parentTagName = parent[0].tagName;
			if (parentTagName.toLowerCase() == "div" || parentTagName.toLowerCase() == "td") {
				return parent;
			}

			fieldInstance = parent;
		}
    }

    /**
     * Parst aus den CSS Klassen des Feldes den Namen des Validators für dieses Feld. Die entsprechende CSS Klasse wurde
     * zuvor von ApplyMetadata auf dem Server gesetzt.
     */
    this.getValidationIdentifier = function(field) {
    	var classes = field.attr("class");
		var classArr = classes.split(" ");
		var arrayLength = classArr.length;
		//FIXME aktuell wird eine CSS Klasse .parsleyValidation_VALIDATORIDENTIFIER gesetzt. Mit String Operationen wird hier der 
		//Identifier bestimmt. Geht das evtl. eleganter?
		for (var i = 0; i < arrayLength; i++) {
			var currentStr = classArr[i];
			if (currentStr && currentStr.startsWith("parsleyValidation_")) {
				var currentStrArr = currentStr.split("_", 2);
				if (currentStrArr.length > 1) {
					return currentStrArr[1];
				}
			}
		}
    };

    /**
     * Setzt das aktuelle locale in Parsley. Dadurch werden dann später die korrekten Fehlermeldungen der Validierung 
     * angezeigt.
     */
    this.setParsleyLocale = function() {
    	var lang = de.his.common.LanguageHelper.currentLanguage();
    	if (lang == "de") {
    		Parsley.setLocale("de");
    	} else {
    		Parsley.setLocale("en");
    	}
    };
};
// Validation errors messages for Parsley
// Load this after Parsley

Parsley.addMessages('de', {
  defaultMessage: "Die Eingabe scheint nicht korrekt zu sein.",
  type: {
    email:        "Die Eingabe muss eine gültige E-Mail-Adresse sein.",
    url:          "Die Eingabe muss eine gültige URL sein.",
    number:       "Die Eingabe muss eine Zahl sein.",
    integer:      "Die Eingabe muss eine Zahl sein.",
    digits:       "Die Eingabe darf nur Ziffern enthalten.",
    alphanum:     "Die Eingabe muss alphanumerisch sein."
  },
  notblank:       "Die Eingabe darf nicht leer sein.",
  required:       "Dies ist ein Pflichtfeld.",
  pattern:        "Die Eingabe scheint ungültig zu sein.",
  min:            "Die Eingabe muss größer oder gleich %s sein.",
  max:            "Die Eingabe muss kleiner oder gleich %s sein.",
  range:          "Die Eingabe muss zwischen %s und %s liegen.",
  minlength:      "Die Eingabe ist zu kurz. Es müssen mindestens %s Zeichen eingegeben werden.",
  maxlength:      "Die Eingabe ist zu lang. Es dürfen höchstens %s Zeichen eingegeben werden.",
  length:         "Die Länge der Eingabe ist ungültig. Es müssen zwischen %s und %s Zeichen eingegeben werden.",
  mincheck:       "Wählen Sie mindestens %s Angaben aus.",
  maxcheck:       "Wählen Sie maximal %s Angaben aus.",
  check:          "Wählen Sie zwischen %s und %s Angaben.",
  equalto:        "Dieses Feld muss dem anderen entsprechen."
});

//FIXME das setLocale sollte wahrscheinlich eher in die initParsleyValidation.js und auch variable sein, abhängig vom aktuellem locale.
//Parsley.setLocale('de');
/**
 * Author: masala@his.de
 * 
 * device.js (below) must be included before this file
 * https://github.com/matthewhudson/device.js
 * 
 * note: 
 * 	add ?deviceDetails=true to URL in order to print device height and width
 * 
 */


(function(){
	
	if(!navigator.cookieEnabled){
		console.info("cookies must be enabled");
		return false;
	}
	
	var forceDeviceSessionName = "hisforcedevice";
	var actualDeviceSessionName = "hisactualdevice";
	
	//output the device height and width if the URL contains ?deviceDetails=true
	var urlParam = de.his.common.Util.getQueryParam("deviceDetails"),
		actualDevice = window.sessionStorage.getItem(actualDeviceSessionName),
		forcedDevice = window.sessionStorage.getItem(forceDeviceSessionName);
	
	if(urlParam == "true"){
		//print the width and height of device
		alert(window.innerWidth + " x " + window.innerHeight);
	}
	
	if(forcedDevice){
		//TODO: following replaces all classes with {mobile|tablet|desktop|etc} - what about "ios mobile portrait" etc
		jQuery("html").attr("class", forcedDevice);
	}
	
	if(!device.desktop() && forcedDevice != "desktop"){
		jQuery("a.forceDeviceLink[device-data='desktop']").css("display", "block");
	}else if(actualDevice){
		//if actual device has been set in the sessionStorage - then allow a return back to the actual device
		jQuery("a.forceDeviceLink[device-data=" + actualDevice + "]").css("display", "block");
	}
	

	//function used to disable responsive design when user clicks the desired link
	jQuery("a.forceDeviceLink").on("click", function(){
		
		//device.js
		var ad, //actual device
			url = window.location.href,
			forceDevice = jQuery(this).attr("device-data"),
			forceDeviceUrl = "wantDevice=" + forceDevice,
			currentParam = de.his.common.Util.getQueryParam( "wantDevice" );
		
		if(device.desktop()){
			ad = "desktop";
		}else if(device.mobile()){
			ad = "mobile";
		}else if(device.tablet()){
			ad = "tablet";
		}
		
		//save the device to force to - i.e. desktop
		window.sessionStorage.setItem(forceDeviceSessionName, forceDevice);
		//save the actual device - i.e mobile
		window.sessionStorage.setItem(actualDeviceSessionName, ad);
		
		
		if(currentParam){
			//replace anyting in url already
			url = url.replace("wantDevice="+currentParam, forceDeviceUrl);
		}else{
			url = url + (url.indexOf("?") >= 0 ? "&" + forceDeviceUrl : "?" + forceDeviceUrl);
			//url = url + "&device=desktop";
		}
		
		window.location = url;
	});

	
})();/**
* masala@his.de
* by setting custom or predefined (img-xs, img-l) media queries this plugin with change the image to fit the current viewport in a responsive manner.
*  
* usage: 	<img data-sizes="img-xs, img-s, img-m, img-l, img-xl" 
*				 data-srcset="http://placehold.it/60%26text=xs,
*							  http://placehold.it/60%26text=s,
*							  http://placehold.it/60%26text=m,
*							  http://placehold.it/60%26text=l,
*							  http://placehold.it/60%26text=xl" />
*
* note: if two sizes are a match then the first wins.
* 
* possible sizes:
* 	
* 	"img-xs": "(max-width:767px)",
*	"img-s": "(max-width:991px)",
*	"img-m": "(max-width:1199px)",
*	"img-l": "(max-width:1920px)",
*	"img-xl": "(min-width : 1921px)"
*
* 
*/

(function(){
	
	var presets = {
			"img-xs": "(max-width:767px)",
			"img-s": "(max-width:991px)",
			"img-m": "(max-width:1199px)",
			"img-l": "(max-width:1920px)",
			"img-xl": "(min-width : 1921px)"
	}
	
	var imgs = jQuery("img[data-srcset]");
	
	var reponsiveImages = function(){
		imgs.hide();	//hide all images
		var sizes = [], img = {}, src = [], media, size;
		//first iterate through all the image tags that were found
		for(var i = 0, l = imgs.length; i<l; i++){
			img = jQuery(imgs[i]);
			sizes = img.attr("data-sizes").split(",");
			src = img.attr("data-srcset").split(",");
			//per image tag, iterate through the sizes defined in each tag
			for(var ii = 0, ll = sizes.length;ii<ll; ii++){
				size = sizes[ii].trim();
				//if the size is defined using a preset such as img-xs or img-l - convert it to the corresponding media query
				if(size.indexOf("img-") >= 0){
					media = presets[size];
				}else{
					//preset wasn't used but a direct media query
					media = size;
				}
				console.info(media, window.matchMedia(media));
				if(window.matchMedia(media).matches){
					//set the correct src url and show the correct image
					img.attr("src", src[ii].trim());
					img.show();	
					return;
				}
			}
		}
		
	}
	
	//auto recall when windows changes size
	jQuery(window).resize(reponsiveImages);
	
	//initial call
	reponsiveImages();
	
})();/*!
 * @author Steven Masala [me@smasala.com]
 * Github: https://github.com/smasala/responsive-tables-js
 * @license MIT https://tldrlegal.com/license/mit-license
 * Responsive Tables
 * @version 0.1.5
 *
 * usage: give any table you want to work responsively, the CSS class "responsive".
 */

( function( root, factory ) {
    "use strict";
    
    if ( typeof define === "function" && define.amd ) {
        define( [ "jquery" ], function( $ ) {
            return factory( root, root.document, $ );
        } );
    } else {
        return factory( root, root.document, root.jQuery );
    }

} )( this, function( window, document, $ ) {
    "use strict";
    
    if ( window.responsiveTables ) {
        console.error( "window.responsiveTables is already defined globally", window.responsiveTables );
        return;
    }

    var responsiveTables = {

        version: "0.1.5",

        titleTpl: function( data ) {
            return "<span data-type='responsive'>" + data + "</span>";
        },

        /**
         * @method init
         * @param selector {String} optional - pass if you wish to update tables that do not meet the selector: table.responsive
         * @param force {Boolean} [default=false] - optional - set true to reiterate over previous converted tables
         */
        init: function( selector, force ) {
            var me = this,
                tables = $( selector ? selector : "table.responsive" ),
                table, ths, th, trs, tds, td, text, it; //for later

            if ( tables.length > 0 ) {

                for ( var i = 0, l = tables.length; i < l; i++ ) {
                    //iterate over each table
                    table = $( tables[ i ] );
                    if ( table.attr( "data-type" ) && !force ) {
                        //ignore this table
                        continue;
                    }
                    table.attr( "data-type", "responsive" );
                    //get all the table header for the give table
                    ths = table.find( "th" );
                    trs = table.find( "tr" );
                    //iterate over all trs
                    for ( var ii = 0, ll = trs.length; ii < ll; ii++ ) {
                        //find tds and iterate
                        tds = $( trs[ ii ] ).find( "td" );
                        for ( var iii = 0, lll = tds.length; iii < lll; iii++ ) {
                            //for each td - find the correct heading
                            th = ths[ iii ];
                            it = $( tds[ iii ] );
                            //get the text content
                            text = th.textContent || text.innerText || "";
                            if ( force ) {
                                it.find( "span[data-type='responsive']" ).remove();
                            }
                            //prepend td with the correct template
                            td = it.prepend( me.titleTpl( text ) );
                        }
                    }
                }
            }
        }

    };
    
    //define globally
    window.responsiveTables = responsiveTables;
    return responsiveTables;
} );use_package("de.his.component.ResponsiveTables");
/**
* Author:masala@his.de
* Plugin/helper for tables to make them more responsive
*/
//overlayOpen

de.his.component.ResponsiveTables = new function() {
	
    de.his.modules.ModuleRegistry
    .registerModule(this)
    .registerAjaxRefreshModule(this);
    
	this.moduleName = "de.his.component.ResponsiveTables";
 
    this.init = function(){
    	var tables = jQuery("table.table:not(.disableResponsiveLabels):not([data-responsive=true])");

    	var table, ths, trs;
    	for(var x = 0, xl = tables.length; x<xl; x++){
    		table = jQuery(tables[x]);
    		table.attr("data-responsive", true);
    		//find tableHeaders
    		ths = table.find("> thead > tr > th"); //.css("display", "none");
    		//table rows in the body of the table
    		trs = table.find("> tbody > tr");
    		
    		var tds = [], 
    			label,
    			th, td;
    		
    		for(var i = 0, l = trs.length; i<l; i++){
    			tds = jQuery(trs[i]).find("> td");
    			for(var ii = 0, ll = tds.length; ii<ll; ii++){
    				td = tds[ii];
    				th = ths[ii];
    				if(th){
    					// innerHTML damit auch HTML Elemente, wie Popup Buttons angezeigt werden können!
    					label = th.innerHTML;
    					
    					var ariaHide ="";
    					if(jQuery(window).width() > 768) {
						ariaHide ="aria-hidden='true'"
    					}    		
    					jQuery(td).prepend("<span data-type='responsive'" + ariaHide + ">" + label + "</span>").find('[id*="filterSelectOneMenu"], [id*="filterInput"], [id*="resetFilter"], [id*="filterRefresh"], [class*="headerExtSelectOneMenu"]').remove();
    						/** inline-table requires content of the td will collapse (used for responsive tables) **/ 
    				
    					if(!jQuery(td).html()){
    						jQuery(td).html("&nbsp;");
    					}
    					
    					
    					
    				}
    				
    			}
    		}
    	}

    jQuery(window).resize(function() {
	
		setTimeout(function(){
			if(jQuery(window).width() <= 768){	
					$("span[data-type='responsive']").removeAttr('aria-hidden');						
			}	
			else{
					$("span[data-type='responsive']").attr('aria-hidden', 'true');	
			}
		},800);									
	});

    	setTimeout(function(){
        	jQuery('.frozenCol_2').each(function(){
                var $this = jQuery(this);
                var thWidth = $this.find('th:nth-child(1)').outerWidth();
                 $this.find('td:nth-child(2), th:nth-child(2)').css({left: thWidth}); 
            });
            jQuery('.frozenCol_3').each(function(){
				var $this2 = jQuery(this);
                var thWidth2 = $this2.find('th:nth-child(1)').outerWidth();
                 $this2.find('td:nth-child(2), th:nth-child(2)').css({left: thWidth2}); 
                var $this3 = jQuery(this);
                var thWidth3 = $this3.find('th:nth-child(1)').outerWidth() + $this3.find('th:nth-child(2)').outerWidth();
                 $this3.find('td:nth-child(3), th:nth-child(3)').css({left: thWidth3}); 
            });
    	 },200);
    	 
    	 jQuery('.frozenCol_3, .frozenCol_2, .frozenCol').each(function(){
            var $this = jQuery(this);
            if( $this.find('.overflowAuto').length && $this.find('.virtualTableScroll').length == 0 ) {
                $this.append(' <div class="virtualTableScrollWrap"><div class="virtualTableScroll"><div class="virtualTableScroll-handler"></div></div></div> '); 
                
                var $table = $this.find('.overflowAuto').find('table');
                var overflowWidth = $this.find('.overflowAuto').width();
                var tableWidth = $table.width();
                var scrollWidth = tableWidth-overflowWidth
                $this.find( ".virtualTableScroll" ).slider({
                  create: function() {
                      if( overflowWidth >=  tableWidth || $this.hasClass('tableStickyHeader') ) {
                          $this.find( ".virtualTableScroll" ).slider( "destroy" );
                          $this.find('.virtualTableScrollWrap').remove();
                      }  
                  },
                  slide: function( event, ui ) {
                    virtualScroller = (scrollWidth/100)*ui.value;
                    $this.find('.overflowAuto').scrollLeft(virtualScroller);
                  }
                });
                
                var $handle = $this.find( ".ui-slider-handle" );
                $this.find('.overflowAuto').scroll(function(e){
                    scroller = (jQuery(this).scrollLeft()/scrollWidth)*100;
                    $handle.css({left:scroller+'%'});
                });
                
                // Virtual Scrollbar ausblenden wenn der horizontale Browserscrollbalken sichtbar ist
                var tableHeight = $table.outerHeight();
                var tableTop = $table.offset().top;
                var windowHeight = jQuery(window).height();
                var old_scroll_top = 0;
                jQuery(window).scroll(function(){
                    var current_scroll_top = $(document).scrollTop();
                    var scroll_delta = current_scroll_top - old_scroll_top;
                    var scrollbarInView = (tableHeight +tableTop )- windowHeight >=  current_scroll_top;                    
                        if( scroll_delta <=0 ){
                            if( scrollbarInView ) {
                                $this.find( ".virtualTableScrollWrap" ).removeClass('js-hidden');
                                }
                        }
                        else {
                            if( current_scroll_top >= 200 ){
                                if( !scrollbarInView ) {
                                    $this.find( ".virtualTableScrollWrap" ).addClass('js-hidden');
                                }
                            }
                        }
                    
                    old_scroll_top = current_scroll_top;
                });
                
            }
            
            
         });
    	
    };
    
    this.refresh = this.init;
    
};

/*
 * alert.js - javascript alert replacement v2.4
 *
 * (c) 2009-2011 Naden Badalgogtapeh - http://www.naden.de/blog/javascript-alert
 *
 */

// Datei wurde angepasst, um den Top wert nicht zu setzen, da er die Alert-box ausßerhalb des sichtbaren Bereichs anzeigt.
// Alert box wird nun anhand unseres CSS's positioniert. Zum Finden des auskommentieren Codes Suche in der Datei nach: A.style.top

window.alert=function(){var H=2.4;var D={button_title:"OK",callback:function(){},left:-1,top:-1,width:-1,height:-1,modal:true,timeout:0};if(arguments.length==2&&typeof arguments[1]=="object"){D=J(arguments[1],D)}else{if(arguments.length==3){D=J(arguments[2],D)}}window.alert_callback=D.callback;if(arguments.length==1||(arguments.length==2&&typeof arguments[1]!="string")){arguments=["",arguments[0]]}var A=document.getElementById("alert");if(A){document.body.removeChild(A)}if(D.modal){var F=document.createElement("DIV");F.id="alert-modal";F.className="alert-modal";document.body.appendChild(F)}A=document.createElement("DIV");A.id=A.className="alert";document.body.appendChild(A);A.innerHTML=(arguments[0]==""?"":'<div class="title">'+arguments[0]+"</div>")+'<div class="body">'+arguments[1]+'</div><div class="button"><a href="" onclick="var _m3423=document.getElementById(\'alert-modal\');if(_m3423)document.body.removeChild(_m3423);document.body.removeChild(document.getElementById(\'alert\'));alert_callback();return false;">'+D.button_title+"</a></div>";var B=G(),K=Math.max(I(arguments[0]),I(arguments[1]))*6,C=0,E=0;if(D.width==-1){D.width=K}else{C=D.width;K=0}if(D.left==-1){D.left=parseInt((B[0]+B[2]-K-C)/2)}A.style.display="block";if(D.top==-1){D.top=parseInt(((B[1]+B[3]-(D.height==-1?0:(D.height/2)))/2)-(A.pixelHeight||A.offsetHeight))}A.style.width=D.width+"px";if(D.height>0){A.style.height=D.height+"px"}/*A.style.left=D.left+"px";A.style.top=D.top+50+"px";*/function J(M,L){for(var N in L){if(N in M){continue}M[N]=L[N]}return M}function I(O){var P=O.split("<br />");if(P.length<=1){P=O.split("<br>")}if(P.length<=1){return O.replace(/<(?:.|\s)*?>/g,"").length}var L=0;for(var N=0;N<P.length;N++){var M=P[N].replace(/<(?:.|\s)*?>/g,"");if(M.length>L){L=M.length}}return L}function G(){var M=0,N=0,L=0,O=0;if(typeof window.innerWidth=="number"){M=window.innerWidth;N=window.innerHeight}else{if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){M=document.documentElement.clientWidth;N=document.documentElement.clientHeight}else{if(document.body&&(document.body.clientWidth||document.body.clientHeight)){M=document.body.clientWidth;N=document.body.clientHeight}}}if(typeof window.pageYOffset=="number"){O=window.pageYOffset;L=window.pageXOffset}else{if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){O=document.body.scrollTop;L=document.body.scrollLeft}else{if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){O=document.documentElement.scrollTop;L=document.documentElement.scrollLeft}}}return[L,O,M,N]}}; 'use strict';

use_package("de.his.component");

de.his.component.PrimeFacesSelectOneMenu = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
	this.moduleName = "de.his.component.PrimeFacesSelectOneMenu";
	const setAriaActivedescendant = true;
	const setAriaOwns = true;
	
    this.init = function() {
    	if (window.PrimeFaces) {
    	    PrimeFaces.widget.SelectOneMenu();
			PrimeFaces.animationEnabled = false;
    	}
    }
    this.refresh = function() {
        this.init();
    };
    	
    if (window.PrimeFaces) {
    	/// START PrimeFaces-Komponente ///    	
		PrimeFaces.widget.SelectOneMenu = PrimeFaces.widget.DeferredWidget.extend({
		
			/**
			 * @override
			 * @inheritdoc
		     * @param {PrimeFaces.PartialWidgetCfg<TCfg>} cfg
			 */
		    init: function(cfg) {
		        this._super(cfg);
		
		        this.panelId = this.jqId + '_panel';
		        this.input = $(this.jqId + '_input');
		        this.focusInput = $(this.jqId + '_focus');
		        this.label = this.jq.find('.ui-selectonemenu-label');
		
		        this.panel = $(this.panelId);
		        this.disabled = this.jq.hasClass('ui-state-disabled');
		        this.itemsWrapper = this.panel.children('.ui-selectonemenu-items-wrapper');
		        this.options = this.input.find('option');
		        this.cfg.effect = this.cfg.effect||'fade';
		
		        this.cfg.effectSpeed = this.cfg.effectSpeed||'normal';
		        this.cfg.autoWidth = this.cfg.autoWidth === false ? false : true;
		        this.cfg.dynamic = this.cfg.dynamic === true ? true : false;
		        this.cfg.appendTo = PrimeFaces.utils.resolveAppendTo(this, this.panel);
		        this.cfg.renderPanelContentOnClient = this.cfg.renderPanelContentOnClient === true;
		        this.isDynamicLoaded = false;
		        this.isOpenedByKeydown = false;
		        this.defaultTooltip = this.jq.attr('title');
		
		        if(this.cfg.dynamic || (this.itemsWrapper.children().length === 0)) {
		            var selectedOption = this.options.filter(':selected'),
		            labelVal = this.cfg.editable ? this.label.val() : selectedOption.text();
		
		            this.setLabel(labelVal);
		        }
		        else {
		            this.initContents();
		            this.bindItemEvents();
		        }
		
		        //triggers
    	        this.triggers = this.jq.find(".ui-selectonemenu-label");
		
		        //mark trigger and descandants of trigger as a trigger for a primefaces overlay
		        this.triggers.data('primefaces-overlay-target', true).find('*').data('primefaces-overlay-target', true);
		
		        if(!this.disabled) {
		           this.bindEvents();

		           this.transition = PrimeFaces.utils.registerCSSTransition(this.panel, 'ui-connected-overlay');
		        }
		
		        // see #7602
		        if (PrimeFaces.env.isTouchable(this.cfg)) {
		            this.focusInput.attr('readonly', true);
		        }
		
		       //this.renderDeferred();
		       //this._render(); // this.renderDeferred ist eine Performancebremse (durch den Zugriff auf :visible) und bei uns scheinbar unnötig
		    },
		
		    /**
		     * Finds and initializes the DOM elements that make up this widget.
		     * @private
		     */
		    initContents: function() {
		        this.itemsContainer = this.itemsWrapper.children('.ui-selectonemenu-items');
		        this.items = this.itemsContainer.find('.ui-selectonemenu-item');
		        this.optGroupsSize = this.itemsContainer.children('li.ui-selectonemenu-item-group').length;
				this.itemsWithGroup = this.itemsContainer.find(".ui-selectonemenu-item, .ui-selectonemenu-item-group");
				
		        var $this = this,
		        selectedOption = this.options.filter(':selected'),
		        highlightedItem = this.items.eq(this.options.index(selectedOption));
		
		        //disable options
		        this.options.filter(':disabled').each(function() {
		            $this.items.eq($(this).index()).addClass('ui-state-disabled');
		        });
		
		        //activate selected
		        if(this.cfg.editable) {
		            var customInputVal = this.label.val();
		
		            //predefined input
		            if(customInputVal === selectedOption.text()) {
		                this.highlightItem(highlightedItem);
		            }
		            //custom input
		            else {
		                this.items.eq(0).addClass('ui-state-highlight');
		                this.customInput = true;
		                this.customInputVal = customInputVal;
		            }
		        }
		        else {
		            this.highlightItem(highlightedItem);
		        }
		
		        if(this.cfg.syncTooltip) {
		            this.syncTitle(selectedOption);
		        }
		
		        //pfs metadata
		        this.input.data(PrimeFaces.CLIENT_ID_DATA, this.id);
		
		        //for Screen Readers
		        for(var i = 0; i < this.items.length; i++) {
		            this.items.eq(i).attr('id', this.id + '_' + i);
		        }
		
		        var highlightedItemId = highlightedItem.attr('id');
		        this.jq.attr('aria-owns', this.itemsContainer.attr('id'));
		        this.focusInput.attr('aria-autocomplete', 'list')
		            .attr('aria-activedescendant', highlightedItemId)
		            .attr('aria-describedby', highlightedItemId)
		            .attr('aria-disabled', this.disabled);
		        this.itemsContainer.attr('aria-activedescendant', highlightedItemId);
		    },
		
		    /**
		     * @include
		     * @override
		     * @protected
		     * @inheritdoc
		     */
		    _render: function() {
		        var contentStyle = this.jq.attr('style'),
		        hasWidth = contentStyle && contentStyle.indexOf('width') != -1;
		
		        if(this.cfg.autoWidth && !hasWidth) {
		            this.jq.css('width', this.input.outerWidth() + 'px');
		        }
		    },
		
		    /**
		     * @override
		     * @inheritdoc
		     * @param {PrimeFaces.PartialWidgetCfg<TCfg>} cfg
		     */
		    refresh: function(cfg) {
		        this.panelWidthAdjusted = false;
		        this.items = null;
		
		        this._super(cfg);
		    },
		
		    /**
		     * Adjust the width of the overlay panel.
		     * @private
		     */
		    alignPanelWidth: function() {
		        //align panel and container
		        if(!this.panelWidthAdjusted) {
		            var jqWidth = this.jq.outerWidth();
		            if(this.panel.outerWidth() < jqWidth) {
		                this.panel.width(jqWidth);
		            }
		            else {
		                this.panel.width(this.panel.width());
		            }
		
		            this.panelWidthAdjusted = true;
		        }
		    },
		
		    /**
		     * Sets up all event listeners required by this widget.
		     * @private
		     */
		    bindEvents: function() {
		        var $this = this;
		
		        // Screen Reader(JAWS) hack on Chrome
		        if(PrimeFaces.env.browser.webkit) {
		            this.input.on('focus', function(){
		                setTimeout(function(){
		                    $this.focusInput.trigger('focus.ui-selectonemenu');
		                },2);
		            });
		        }
		
		        //Triggers
		        this.triggers.on("mouseenter", function() {
		            if(!$this.jq.hasClass('ui-state-focus')) {
		                $this.jq.addClass('ui-state-hover');
		            }
		        })
		        .on("mouseleave", function() {
		            $this.jq.removeClass('ui-state-hover');
		        })
		        .on("click", function(e) {
		            if($this.panel.is(":hidden")) {
		                $this.show();
		            }
		            else {
		                $this.hide();
		
		                $this.revert();
		                $this.changeAriaValue($this.getActiveItem());
		            }
		
		            $this.jq.removeClass('ui-state-hover');
		            $this.focusInput.trigger('focus.ui-selectonemenu');
		            e.preventDefault();
		        });
		
		        this.focusInput.on('focus.ui-selectonemenu', function(e) {
		            $this.jq.addClass('ui-state-focus');
		            if(!$this.cfg.dynamic && !$this.items) {
		                $this.callHandleMethod($this.handleTabKey(), e);
		            }
		            var item = Array.from($this.items).filter(elem => {
                        return elem.classList.contains('ui-state-highlight');
                    });
		        })
		        .on('blur.ui-selectonemenu', function(){
		            $this.jq.removeClass('ui-state-focus');
		            $this.callBehavior('blur');
		        });
		
		        //onchange handler for editable input
		        if(this.cfg.editable) {
		            this.label.on('change', function(e) {
		                $this.triggerChange(true);
		                $this.callHandleMethod($this.handleLabelChange, e);
		            });
		        }
		
    	        // fixes missing label after Chrome autofills selects or Screenreader Selection from HTML-Select
		    	this.input.off('change').on("change",function(e){
					var  value = $this.cfg.editable ? $this.label.val() : $this.getSelectedLabel(); 
	 	            $this.setLabel(value); 
	 	            
				    if($this.panel.is(":visible")){
				    	$this.hide();
				    }
				});
				
		        //key bindings
		        this.bindKeyEvents();
		    },
		
		    /**
		     * Sets up the event listeners for the selectable items.
		     * @private
		     */
		    bindItemEvents: function() {
		        var $this = this;
		        if(!this.items) {
		            return;
		        }
		
		        //Items
		        this.items.filter(':not(.ui-state-disabled)').on('mouseover.selectonemenu', function() {
		            var el = $(this);
		
		            if(!el.hasClass('ui-state-highlight'))
		                $(this).addClass('ui-state-hover');
		        })
		        .on('mouseout.selectonemenu', function() {
		            $(this).removeClass('ui-state-hover');
		        })
		        .on('click.selectonemenu', function() {
		            $this.revert();
		            $this.selectItem($(this));
		            $this.changeAriaValue($(this));
		        });
		    },
		
		    /**
		     * Sets up all panel event listeners
		     * @private
		     */
		    bindPanelEvents: function() {
		        var $this = this;
		
		        this.hideOverlayHandler = PrimeFaces.utils.registerHideOverlayHandler(this, 'mousedown.' + this.id + '_hide', this.panel,
		            function() { return  $this.label; },
		            function(e, eventTarget) {		
	    	            if(e.target.nodeName === "HTML") {
	    	            	// verhindert das einklappen bei Betätigung der Scrollbars.
	    	                return;
	    	            }     	            
		                if(!($this.panel.is(eventTarget) || $this.panel.has(eventTarget).length > 0)) {
		                    $this.panel.hide();
		                    setTimeout(function() {
		                        $this.revert();
		                        $this.changeAriaValue($this.getActiveItem());
		                    }, 2);
		                }
		            });
		
		        this.resizeHandler = PrimeFaces.utils.registerResizeHandler(this, 'resize.' + this.id + '_hide', this.panel, function() {
		            $this.handleViewportChange();
		        });
		
		        // GitHub #1173/#4609 keep panel with select while scrolling
		        this.scrollHandler = PrimeFaces.utils.registerConnectedOverlayScrollHandler(this, 'scroll.' + this.id + '_hide', this.jq, function() {
		            $this.handleViewportChange();
		        });
		    },
		
		    /**
		     * Fired when the browser viewport is resized or scrolled.  In Mobile environment we don't want to hider the overlay
		     * we want to re-align it.  This is because on some mobile browser the popup may force the browser to trigger a
		     * resize immediately and close the overlay. See GitHub #7075.
		     * @private
		     */
		    handleViewportChange: function() {
		        if (PrimeFaces.env.mobile) {
		            this.alignPanel();
		        } else {
		            this.hide();
		        }
		    },
		
		    /**
		     * Unbind all panel event listeners
		     * @private
		     */
		    unbindPanelEvents: function() {
		        if (this.hideOverlayHandler) {
		            this.hideOverlayHandler.unbind();
		        }
		
		        if (this.resizeHandler) {
		            this.resizeHandler.unbind();
		        }
		
		        if (this.scrollHandler) {
		            this.scrollHandler.unbind();
		        }
		    },
		
		    /**
		     * Removes some event listeners when this widget was disabled.
		     * @private
		     */
		    unbindEvents: function() {
		        if (this.items) {
		            this.items.off();
		        }
		        this.triggers.off();
		        this.input.off();
		        this.focusInput.off();
		        this.label.off();
		    },
		
		    /**
		     * Unselect the selected item, if any, and select the `please select` option.
		     */
		    revert: function() {
		        if(this.cfg.editable && this.customInput) {
		            this.setLabel(this.customInputVal);
		            this.items.filter('.ui-state-active').removeClass('ui-state-active');
		            this.items.eq(0).addClass('ui-state-active');
		        }
		        else {
		            this.highlightItem(this.items.eq(this.options.index(this.preShowValue)));
		        }
		    },
		
		    /**
		     * Highlight the given selectable option.
		     * @private
		     * @param {JQuery} item Option to highlight.
		     */
		    highlightItem: function(item) {
		        this.items.attr('aria-selected', false);
		        this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
		
		        if(item.length > 0) {
		            item.addClass('ui-state-highlight');
		            item.attr('aria-selected', true);
		            this.setLabel(item.data('label'));
		            var _this = this;
		            setTimeout(function() {
    		            if( _this.isOpenedByKeydown ) {                        
    		              _this.focusTooltip();
                        }
                    },100)
		        }
		    },
		    
		    focusTooltip: function()  {
                if (/Edg/.test(navigator.userAgent)) {
                    console.log("no focus tooltip for edge");
                    return;
                }
                // Fokus-Tooltips auch bei der Auswahlliste anzeigen
                var item = this.getActiveItem();
                var athis = this;
                setTimeout(function(){                  
                    var title = item.attr('title');
                    item.attr('data-title',title);
                    if (title !== undefined && title.trim() !== ''   ) {
                        jQuery('.focusTooltip').remove();
                        jQuery('body').append('<span class="focusTooltip"></span>');
                        jQuery('.focusTooltip').text(title);
                        
                        if( jQuery('.ui-selectonemenu-filter-container').is(':visible') ) {
                            var rect = item[0].getBoundingClientRect();
                            var thisHeight = item.outerHeight();
                        } else {
                            var rect = athis.jq[0].getBoundingClientRect();
                            var thisHeight = jQuery(athis.jq[0]).outerHeight();
                        }
                        jQuery('.focusTooltip').css({
                            left: rect.left + 'px',
                            top: rect.top + thisHeight + 'px'
                        });
        
                        var ftWidth = jQuery('.focusTooltip').outerWidth();
                        var rightPosition = ftWidth + rect.left;
                        var winWidth = jQuery(window).width();
                        var newLeftPosition = rect.left - (rightPosition - winWidth);
        
                        if (rightPosition >= winWidth) {
                            jQuery('.focusTooltip').css({
                                left: newLeftPosition + 'px'
                            });
                        }
                    }
                },200);
            },
		
		    /**
		     * Triggers the event listeners when the value of this widget changed.
		     * @private
		     * @param {boolean} edited Whether the value was edited by the user. If it was, checks which option is now selected.
		     */
		    triggerChange: function(edited) {
		        this.changed = false;
		
		        this.input.trigger('change');
		
		        if(!edited) {
		            this.value = this.options.filter(':selected').val();
		        }
		    },
		
		    /**
		     * Callback for when the user selects an item with the mouse.
		     * @private
		     * @param {JQuery} item The option to select.
		     * @param {boolean} silent `true` to suppress triggering event listeners, or `false` otherwise.
		     */
		    selectItem: function(item, silent) {
				// HIS-Patch
				//index nach neuer Sortierung finden
				var newIndex;
				this.items.each(function(i, el ){
					if( item.attr('data-itemValue') == jQuery(el).attr('data-itemValue') ) {
						newIndex = i;	
					}
				});
		        var selectedOption = this.options.eq(newIndex),
		        currentOption = this.options.filter(':selected'),
		        sameOption = selectedOption.val() == currentOption.val(),
		        shouldChange = null;
		
		        if(this.cfg.editable) {
		            shouldChange = (!sameOption)||(selectedOption.text() != this.label.val());
		        }
		        else {
		            shouldChange = !sameOption;
		        }
		
		        if(shouldChange) {
		            this.highlightItem(item);
		            this.input.val(selectedOption.val());
		
		            if(!silent) {
		                this.triggerChange();
		            }
		            		
		            if(this.cfg.editable) {
		                this.customInput = false;
		            }
		
		            if(this.cfg.syncTooltip) {
		                this.syncTitle(selectedOption);
		            }
		        }
		        
		        if(!silent) {
                    // HIS-Patch um ajax auch bei Auswahl des gleichen Elements aus zu lösen.
                    // behebt Probleme mit Suchsets, Auswahl gleiches Suchset resetet Änderungen
                    this.input.trigger("selectitem");        
                    this.callBehavior('itemSelect');
                    this.focusInput.trigger('focus');                   
                    // update tooltip after selection change with keyboard too
                    this.focusTooltip();
                }
		
		        if(this.panel.is(':visible')) {
		            this.hide();
		        }
				
				// wenn SOM in Tableheader als Filter refresh button triggern
				if( this.id.contains('filterSelectOneMenu') && this.input.attr('onkeydown') ) {
					var refreshBtnId = this.input.attr('onkeydown').split("'")[1];
					refreshBtnId = refreshBtnId.replace( /(:|\.|\[|\]|,|=|@)/g, "\\$1" );
					jQuery('#'+refreshBtnId).trigger('click');
				}
				
		    },
		
		    /**
		     * Adjust the value of the title attribute to match selected option.
		     * @private
		     * @param {JQuery} option The option that was selected.
		     */
		    syncTitle: function(option) {
                var optionTitle = this.items.eq(option.index()).attr('data-title') || this.items.eq(option.index()).attr('title');
		        if(optionTitle && optionTitle.trim().length > 0) {
		            this.jq.attr('title', optionTitle);
				}
    	        else {
		            this.jq.attr('title', this.defaultTooltip);
				}
		    },
		
		    /**
		     * Finds the index of the given selectable option.
		     * @param {JQuery} item One of the available selectable options.
		     * @return {number} The index of the given item.
		     */
		    resolveItemIndex: function(item) {
		        if(this.optGroupsSize === 0)
		            return item.index();
		        else
		            return item.index() - item.prevAll('li.ui-selectonemenu-item-group').length;
		    },
		
		    /**
		     * Sets up the event listeners for all keyboard related events other than the overlay panel, such as pressing space
		     * to bring up the overlay panel.
		     * @private
		     */
		    bindKeyEvents: function() {
		        var $this = this;
		
		        this.focusInput.on('keydown.ui-selectonemenu', function(e) {
		            var keyCode = $.ui.keyCode,
		            key = e.which;
		
		            switch(key) {
		                case keyCode.UP:
		                case keyCode.LEFT:
							if (e.altKey) {
								$this.handleEscapeKey(e);
							} else  {
								$this.callHandleMethod($this.highlightPrev, e);
							}
		                break;
		
		                case keyCode.DOWN:
							// Pfeiltaste nach unten soll Auswahlfeld öffnen
							if ($this.panel.is(":hidden")) {
								$this.show();
								$this.isOpenedByKeydown = true;
								$this.focusTooltip();
							} else {
								$this.callHandleMethod($this.highlightNext, e);
							}
						break;
						
						case keyCode.RIGHT:
							$this.callHandleMethod($this.highlightNext, e);
						break;
		
		                case keyCode.ENTER:
		                    $this.handleEnterKey(e);
		                break;
		
		                case keyCode.TAB:
		                    $this.handleTabKey();
		                break;
		
		                case keyCode.ESCAPE:
		                    $this.handleEscapeKey(e);
		                break;
		
		                case keyCode.SPACE:
		                    $this.handleSpaceKey(e);
		                break;

						case keyCode.BACKSPACE: 
							 $this.handleDelete(e);
							break;
						case keyCode.DELETE: 
							 $this.handleDelete(e);
							break;
		            }
		        })
		        .on('keyup.ui-selectonemenu', function(e) {
		            var keyCode = $.ui.keyCode,
		            key = e.which;
		
		            switch(key) {
		                case keyCode.UP:
		                case keyCode.LEFT:
		                case keyCode.DOWN:
		                case keyCode.RIGHT:
		                case keyCode.ENTER:
		                case keyCode.TAB:
		                case keyCode.ESCAPE:
		                case keyCode.SPACE:
		                case keyCode.HOME:
		                case keyCode.PAGE_DOWN:
		                case keyCode.PAGE_UP:
		                case keyCode.END:
		                case keyCode.DELETE:
		                case 16: //shift
		                case 17: //keyCode.CONTROL:
		                case 18: //keyCode.ALT:
		                case 19: //Pause/Break:
		                case 20: //capslock:
		                case 44: //Print Screen:
		                case 45: //Insert:
		                case 91: //left window or cmd:
		                case 92: //right window:
		                case 93: //right cmd:
		                case 144: //num lock:
		                case 145: //scroll lock:
		                break;
		
		                default:
		                    //function keys (F1,F2 etc.)
		                    if(key >= 112 && key <= 123) {
		                        break;
		                    }
		
		                    var matchedOptions = null,
		                    metaKey = e.metaKey||e.ctrlKey||e.altKey;
		
		                    if(!metaKey) {
		                        clearTimeout($this.searchTimer);
		
		                        // #4682: check for word match
		                        var text = $(this).val();
		                        matchedOptions = $this.matchOptions(text);
		                        if(matchedOptions.length) {
		                            var matchIndex = matchedOptions[0].index;
		                            var highlightItem = $this.items.eq(matchIndex);
		                            if($this.panel.is(':hidden')) {
		                                $this.selectItem(highlightItem);
		                            }
		                            else {
		                                $this.highlightItem(highlightItem);
		                                PrimeFaces.scrollInView($this.itemsWrapper, highlightItem);
		                            }
		                        } else {
		                            // #4682: check for first letter match
		                            text = String.fromCharCode(key).toLowerCase();
		                            // find all options with the same first letter
		                            matchedOptions = $this.matchOptions(text);
		                            if(matchedOptions.length) {
		                                var selectedIndex = -1;
		
		                                // is current selection one of our matches?
		                                matchedOptions.each(function() {
		                                   var option = $(this);
		                                   var currentIndex = option[0].index;
		                                   var currentItem = $this.items.eq(currentIndex);
		                                   if (currentItem.hasClass('ui-state-highlight')) {
		                                       selectedIndex = currentIndex;
		                                       return false;
		                                   }
		                                });
		
		                                matchedOptions.each(function() {
		                                    var option = $(this);
		                                    var currentIndex = option[0].index;
		                                    var currentItem = $this.items.eq(currentIndex);
		
		                                    // select next item after the current selection
		                                    if (currentIndex > selectedIndex) {
		                                         if($this.panel.is(':hidden')) {
		                                             $this.selectItem(currentItem);
		                                         }
		                                         else {
		                                             $this.highlightItem(currentItem);
		                                             PrimeFaces.scrollInView($this.itemsWrapper, currentItem);
		                                         }
		                                         return false;
		                                     }
		                                });
		                            }
		                        }
		
		                        $this.searchTimer = setTimeout(function(){
		                            $this.focusInput.val('');
		                        }, 1000);
		                    }
		                break;
		            }
		        });
		    },
		
		    /**
		     * Finds all options that match the given search string.
		     * @private
		     * @param {string} text The search string against which to match the options.
		     * @return {JQuery} All selectable options that match (contain) the given search string.
		     */
		    matchOptions: function(text) {
		        if(!text) {
		            return false;
		        }
		        return this.options.filter(function() {
		            var option = $(this);
		            if(option.is(':disabled')) {
		                return false;
		            }
		            if(option.text().toLowerCase().indexOf(text.toLowerCase()) !== 0) {
		                return false;
		            }
		            return true;
		        });
		    },
		
		    /**
		     * Sets up the event listeners for the filter input in the overlay panel.
		     * @private
		     */
		    bindFilterEvents: function() {
		        var $this = this;
		
		        this.filterInput.on('keyup.ui-selectonemenu', function(e) {
		            var keyCode = $.ui.keyCode,
		            key = e.which;
		
		            switch(key) {
		                case keyCode.UP:
		                case keyCode.LEFT:
		                case keyCode.DOWN:
		                case keyCode.RIGHT:
		                case keyCode.ENTER:
		                case keyCode.TAB:
		                case keyCode.ESCAPE:
		                case keyCode.SPACE:
		                case keyCode.HOME:
		                case keyCode.PAGE_DOWN:
		                case keyCode.PAGE_UP:
		                case keyCode.END:
		                case 16: //shift
		                case 17: //keyCode.CONTROL:
		                case 18: //keyCode.ALT:
		                case 91: //left window or cmd:
		                case 92: //right window:
		                case 93: //right cmd:
		                case 20: //capslock:
		                break;
		
		                default:
		                    //function keys (F1,F2 etc.)
		                    if(key >= 112 && key <= 123) {
		                        break;
		                    }
		
		                    var metaKey = e.metaKey||e.ctrlKey;
		
		                    if(!metaKey) {
		                        $this.filter($(this).val());
		                    }
		                break;
		            }
		        })
		        .on('keydown.ui-selectonemenu',function(e) {
		            var keyCode = $.ui.keyCode,
		            key = e.which;
		
		            switch(key) {
		                case keyCode.UP:
		                    $this.highlightPrev(e);
		                break;
		
		                case keyCode.DOWN:
								$this.highlightNext(e);
		                break;
		
		                case keyCode.ENTER:
		                    $this.handleEnterKey(e);
		                break;
		
		                case keyCode.TAB:
		                    $this.handleTabKey();
		                break;
			
		                case keyCode.ESCAPE:
		                    $this.handleEscapeKey(e);
		                break;
		
		                case keyCode.SPACE:
		                    $this.handleSpaceKey(e);
		                break;

						case keyCode.HOME:
							$this.handleHomeKey();
						break;
						case keyCode.END:
							$this.handleEndKey();
						break;
						case keyCode.PAGE_DOWN:
							$this.handlePageDownKey(e);
						break;
    	                case keyCode.PAGE_UP:
							$this.handlePageUpKey(e);
						break;
		
		                default:
		                break;
		            }
		        }).on('paste.ui-selectonemenu', function() {
		            setTimeout(function(){
		                $this.filter($this.filterInput.val());
		            },2);
				});
		    },
		
		    /**
		     * Highlights the next option after the currently highlighted option in the overlay panel.
		     * @private
		     * @param {JQuery.TriggeredEvent} event The event of the keypress.
		     */
		    highlightNext: function(event) {
		        var activeItem = this.getActiveItem(),
		        next = this.panel.is(':hidden') ? activeItem.nextAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first')
		                                : activeItem.nextAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):visible:first');
		
		        if(event.altKey) {
		            this.show();
		        }
		        else {
		            if(next.length === 1) {
		                if(this.panel.is(':hidden')) {
		                    this.selectItem(next);
		                }
		                else {
		                    this.highlightItem(next);
		                    PrimeFaces.scrollInView(this.itemsWrapper, next);
		                    this.focusInput.focus();
		                }
		                this.changeAriaValue(next);
		            }
					else {
						this.focusInput.focus();
					}
		        }
		
		        event.preventDefault();
		    },
		
		    /**
		     * Highlights the previous option before the currently highlighted option in the overlay panel.
		     * @private
		     * @param {JQuery.TriggeredEvent} event The event of the keypress.
		     */
		    highlightPrev: function(event) {
		        var activeItem = this.getActiveItem(),
		        prev = this.panel.is(':hidden') ? activeItem.prevAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first')
		                                : activeItem.prevAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):visible:first');
		
		        if(prev.length === 1) {
		            if(this.panel.is(':hidden')) {
		                this.selectItem(prev);
		            }
		            else {
		                this.highlightItem(prev);
		                PrimeFaces.scrollInView(this.itemsWrapper, prev);
						this.focusInput.focus();
		            }
					this.changeAriaValue(prev);
		        }
				else {
					this.filterInput.focus();
				}
		
		        event.preventDefault();
		    },
		
		    /**
		     * Callback for when the enter key was pressed. Brings up the overlay panel or accepts the highlighted option.
		     * @private
		     * @param {JQuery.TriggeredEvent} event The event of the keypress.
		     */
		    handleEnterKey: function(event) {
		        if(this.panel.is(':visible')) {
		            this.selectItem(this.getActiveItem());
			        event.preventDefault();
			        event.stopPropagation();
    	        } else {
    	        	return true;
    	        }			
		    },
		
		    /**
		     * Callback for when the space key was pressed. Brings up or hides the overlay panel.
		     * @private
		     * @param {JQuery.TriggeredEvent} event The event of the keypress.
		     */
		    handleSpaceKey: function(event) {
		        var target = $(event.target);
		
		        if(target.is('input') && target.hasClass('ui-selectonemenu-filter')) {
		            return;
		        }
		
		        if(this.panel.is(":hidden")) {
		            this.show();
		        }
		        else {
		            this.hide();
		
		            this.revert();
		            this.changeAriaValue(this.getActiveItem());
		        }
		
		        event.preventDefault();
		    },
		
		    /**
		     * Callback for when the escape key was pressed. Hides the overlay panel.
		     * @private
		     * @param {JQuery.TriggeredEvent} event The event of the keypress.
		     */
		    handleEscapeKey: function(event) {
		        if(this.panel.is(':visible')) {
		            this.revert();
		            this.hide();
		        }
		
		        event.preventDefault();
		    },
		
		    /**
		     * Callback for when the tab key was pressed. Selects the next option.
		     * @private
		     */
		    handleTabKey: function() {
		        if(this.panel.is(':visible')) {
		            this.selectItem(this.getActiveItem());
		        }
		    },
		
		    /**
		     * Callback that adjusts the label, invoked when the selected option has changed.
		     * @private
		     * @param {JQuery.TriggeredEvent} event The event that triggered the change.
		     */
		    handleLabelChange: function(event) {
		        this.customInput = true;
		        this.customInputVal = $(event.target).val();
		        this.items.filter('.ui-state-active').removeClass('ui-state-active');
		        this.items.eq(0).addClass('ui-state-active');
		    },

			handleEndKey:function() {
				var item = this.items.last();
				this.highlightItem(item); 
    	        PrimeFaces.scrollInView(this.itemsWrapper, item); 
			},
			handleHomeKey:function() {
				var item = this.items.first();
				this.highlightItem(item); 
    	        PrimeFaces.scrollInView(this.itemsWrapper, item); 
			},
			handlePageUpKey:function(b) {
				var item = this.items.filter('.ui-state-highlight').prevAll().eq(2);
				if(item.length != 1) {
					item =  this.items.first();
				}
				this.highlightItem(item); 
    	        PrimeFaces.scrollInView(this.itemsWrapper, item); 
				b.preventDefault(); 
			},
			handlePageDownKey:function(b) {
				var item = this.items.filter('.ui-state-highlight').nextAll().eq(2);
				if(item.length != 1) {
					item =  this.items.last();
				}
				this.highlightItem(item); 
    	        PrimeFaces.scrollInView(this.itemsWrapper, item);
				b.preventDefault(); 
			},
			// Event für Rück und Entf Taste bei fokus
			handleDelete:function (b) {
				this.show();
				this.setLabel('&nbsp;');
				this.filterInput.val('');
    	        b.preventDefault(); 
    	    },

		    /**
		     * Brings up the overlay panel with the available selectable options.
		     */
		    show: function() {
		        this.callHandleMethod(this._show, null);
		    },
		
		    /**
		     * Brings up the overlay panel with the available selectable options. Compared this `show`, this does not ensure
		     * the the overlay panel is loaded already (when dynamic loading is enabled).
		     * @private
		     */
		    _show: function() {
		        var $this = this;
		
		        if (this.transition) {
		            this.transition.show({
		                onEnter: function() {
		                    $this.panel.css('z-index', 100 + PrimeFaces.nextZindex());
		                    $this.alignPanel();
		                    de.his.component.customtooltip.initHovertooltip();
		                },
		                onEntered: function() {
		                    $this.bindPanelEvents();
		
		                    //value before panel is shown
		                    $this.preShowValue = $this.options.filter(':selected');
		                    $this.jq.attr('aria-expanded', true);
		
		                    PrimeFaces.scrollInView($this.itemsWrapper, $this.getActiveItem());
		
		                    if ($this.cfg.filter) {
		                        $this.focusFilter(10);
		                    }
		                }
		            });
		        }
		    },
		
		    /**
		     * Hides the overlay panel with the available selectable options.
		     */
		    hide: function() {
		        if (this.panel.is(':visible') && this.transition) {
		            var $this = this;
		            $this.isOpenedByKeydown = false;
		            this.transition.hide({
		                onExit: function() {
		                    $this.unbindPanelEvents();
		                },
		                onExited: function() {
		                    $this.panel.css('z-index', '');
		                    $this.jq.attr('aria-expanded', false);
                            jQuery('.focusTooltip').remove();
		                }
		            });
		        }
		    },
		
		    /**
		     * Puts focus on this widget.
		     */
		    focus: function() {
		        this.focusInput.trigger('focus');
		    },
		
		    /**
		     * Puts focus on the filter input in the overlay panel.
		     * @param {number} [timeout] Amount of time in milliseconds to wait before attempting to focus the input.
		     */
		    focusFilter: function(timeout) {
		        if(timeout) {
		            var $this = this;
		            setTimeout(function() {
		                $this.focusFilter();
		            }, timeout);
		        }
		        else {
		            this.filterInput.trigger('focus');
		        }
		    },
		
		    /**
		     * Removes focus from this widget.
		     */
		    blur: function() {
		        this.focusInput.trigger("blur");
		
		        this.callBehavior('blur');
		    },
		
		    /**
		     * Disables this widget so that the user cannot select any option.
		     */
		    disable: function() {
		    	if (!this.disabled) {
			        this.disabled = true;
			        this.jq.addClass('ui-state-disabled');
			        this.input.attr('disabled', 'disabled');
			        if(this.cfg.editable) {
			            this.label.attr('disabled', 'disabled');
			        }
			        this.unbindEvents();
		    	}
		    },
		
		    /**
		     * Enables this widget so that the user can select an option.
		     */
		    enable: function() {
		    	if (this.disabled) {
			        this.disabled = false;
			        this.jq.removeClass('ui-state-disabled');
			        this.input.removeAttr('disabled');
			        if(this.cfg.editable) {
			            this.label.removeAttr('disabled');
			        }
		
		            this.bindEvents();
		            this.bindItemEvents();
		    	}
		    },
		
		    /**
		     * Align the overlay panel with the available selectable options so that is is positioned next to the the button.
		     */
		    alignPanel: function() {
		        this.alignPanelWidth();
		
		        if(this.panel.parent().is(this.jq)) {
		            this.panel.css({
		                left: '0px',
		                top: this.jq.innerHeight() + 'px',
		                'transform-origin': 'center top'
		            });
		        }
		        else {
		            this.panel.css({left:'0px', top:'0px', 'transform-origin': 'center top'}).position({
		                my: 'left top'
		                ,at: 'left bottom'
		                ,of: this.jq
		                ,collision: 'flipfit'
		                ,using: function(pos, directions) {
		                    $(this).css('transform-origin', 'center ' + directions.vertical).css(pos);
		                }
		            });
		        }
		    },
		
		    /**
		     * Sets the label text that indicates the currently selected item to the item with the given value.
		     * @private
		     * @param {string} value Value of the item that was selected.
		     */
		    setLabel: function(value) {
		        var displayedLabel = this.getLabelToDisplay(value);
		
		        if (this.cfg.editable) {
		            if (value === '&nbsp;')
		                this.label.val('');
		            else
		                this.label.val(displayedLabel);
		
		            var hasPlaceholder = this.label[0].hasAttribute('placeholder');
		            this.updatePlaceholderClass((hasPlaceholder && value === '&nbsp;'));
		        }
		        else if (this.cfg.alwaysDisplayLabel && this.cfg.label) {
		            this.label.text(this.cfg.label);
		        }
		        else {
		            var labelText = this.label.data('placeholder');
		            if (labelText == null || labelText == "") {
		                labelText = '&nbsp;';
		            }
		
		            this.updatePlaceholderClass((value === '&nbsp;' && labelText !== '&nbsp;'));
		
		            if (value === '&nbsp;') {
		                if (labelText != '&nbsp;') {
		                   this.label.text(labelText);
		                } else {
		                    this.label.html(labelText);
		                }
		            }
		            else {
		                this.label.removeClass('ui-state-disabled');
		
		                var option = null;
		                if(this.items) {
		                    var selectedItem = this.items.filter('[data-label="' + $.escapeSelector(value) + '"]');
		                    option = this.options.eq(this.resolveItemIndex(selectedItem));
		                }
		                else {
		                    option = this.options.filter(':selected');
		                }
		
		                if (option && option.data('escape') === false) {
		                    this.label.html(displayedLabel);
		                } else {
		                    this.label.text(displayedLabel);
		                }
		            }
		        }
		    },
		
		    /**
		     * Selects the option with the given value.
		     * @param {string} value Value of the option to select.
		     */
		    selectValue: function(value) {
		        if(!this.items || this.items.length === 0) {
		           this.callHandleMethod(null, null);
		        }
		
		        var option = this.options.filter('[value="' + $.escapeSelector(value) + '"]');
		
		        this.selectItem(this.items.eq(option.index()), true);
		    },
		
		    /**
		     * Resets the input.
		     * @param {boolean} silent `true` to suppress triggering event listeners, or `false` otherwise.
		     */
		    resetValue: function(silent) {
		        if(!this.items || this.items.length === 0) {
		           this.callHandleMethod(null, null);
		        }
		
		        var option = this.options.filter('[value=""]');
		        if (option.length === 0) {
		            // if no empty value option found, fallback to first in list like JSF default
		            option = this.options.eq(0);
		        }
		        this.selectItem(this.items.eq(option.index()), silent);
		    },
		
		    /**
		     * Finds the element for the currently select option of this select one menu.
		     * @return {JQuery} The DOM element that represents the currently selected option.
		     */
		    getActiveItem: function() {
		        return this.items.filter('.ui-state-highlight');
		    },
		
		    /**
		     * Finds and stores the filter function which is to be used for filtering the options of this select one menu.
		     * @private
		     */
		    setupFilterMatcher: function() {
		        this.cfg.filterMatchMode = this.cfg.filterMatchMode||'startsWith';
		        this.filterMatchers = {
		            'startsWith': this.startsWithFilter
		            ,'contains': this.containsFilter
		            ,'endsWith': this.endsWithFilter
		            ,'custom': this.cfg.filterFunction
		        };
		
		        this.filterMatcher = this.filterMatchers[this.cfg.filterMatchMode];
		    },
		
		    /**
		     * Implementation of a `PrimeFaces.widget.SelectOneMenu.FilterFunction` that matches the given option when it starts
		     * with the given search text.
		     * @param {string} value Text of an option.
		     * @param {string} filter Value of the filter.
		     * @return {boolean} `true` when the text of the options starts with the filter value, or `false` otherwise.
		     */
		    startsWithFilter: function(value, filter) {
		        return value.indexOf(filter) === 0;
		    },
		
		    /**
		     * Implementation of a `PrimeFaces.widget.SelectOneMenu.FilterFunction` that matches the given option when it
		     * contains the given search text.
		     * @param {string} value Text of an option.
		     * @param {string} filter Value of the filter.
		     * @return {boolean} `true` when the text of the contains the filter value, or `false` otherwise.
		     */
		    containsFilter: function(value, filter) {
		        return value.indexOf(filter) !== -1;
		    },
		
		    /**
		     * Implementation of a `PrimeFaces.widget.SelectOneMenu.FilterFunction` that matches the given option when it ends
		     * with the given search text.
		     * @param {string} value Text of an option.
		     * @param {string} filter Value of the filter.
		     * @return {boolean} `true` when the text of the options ends with the filter value, or `false` otherwise.
		     */
		    endsWithFilter: function(value, filter) {
		        return value.indexOf(filter, value.length - filter.length) !== -1;
		    },
		
		    /**
		     * Filters the available options in the overlay panel by the given search value. Note that this does not bring up
		     * the overlay panel, use `show` for that.
		     * @param {string} value A value against which the available options are matched.
		     */
		    filter: function(value) {
			
				var filterListStart = [];
				var filterListRest = [];
				var filtered = false;
				var filterGroupResult = [];
			
		        this.cfg.initialHeight = this.cfg.initialHeight||this.itemsWrapper.height();
		        var filterValue = this.cfg.caseSensitive ? PrimeFaces.trim(value) : PrimeFaces.trim(value).toLowerCase();
		
		        if(filterValue === '') {
					
					// HIS-Patch
					// Alle Listeneinträge in vorheriger Reihenfolge ausgeben
					//Array.from(this.items).forEach(li => this.itemsContainer.append(li));
					var items = this.optGroupsSize == 0 ?  this.items : this.itemsWithGroup;
					Array.from(items).forEach(li => this.itemsContainer.append(li));

			
		            this.items.filter(':hidden').show();
		            this.itemsContainer.children('.ui-selectonemenu-item-group').show();
		        }
		        else {
		            var hide = [];
		            var show = [];
		
		            /*for(var i = 0; i < this.options.length; i++) {
		                var option = this.options.eq(i),*/
					var itemLength = this.optGroupsSize == 0 ?  this.options.length : this.itemsWithGroup.length;	
    	            for (var i = 0; i < itemLength; i++ ) {
    	                var option = this.optGroupsSize == 0 ?  this.options.eq(i) : this.itemsWithGroup.eq(i),						
		                itemLabel = this.cfg.caseSensitive ? option.text() : option.text().toLowerCase(),
		                //item = this.items.eq(i);
						item = this.optGroupsSize == 0 ?  this.items.eq(i) : this.itemsWithGroup.eq(i);
		
		                if(item.hasClass('ui-noselection-option')) {
		                    hide.push(item);
		                }
		                else {
		                    /*if(this.filterMatcher(itemLabel, filterValue)) {
								// HIS-Patch
								// Gefilterte Einträge in Arrays aufteilen, "startsWith"  und "contains"
								if(itemLabel.indexOf(filterValue) === 0) {								
									filterListStart.push(item);
								} else {
									filterListRest.push(item);
								}*/
								if(this.optGroupsSize == 0) {
			                    if (this.filterMatcher(itemLabel, filterValue)) {
									// HIS-Patch
									// Gefilterte Einträge in Arrays aufteilen, erst "startsWith" und dann "contains"
									if(itemLabel.indexOf(filterValue) === 0) {	
										filterListStart.push(item);
									} else {
										filterListRest.push(item);
								}								
										
		                        show.push(item);
							//}
		                                }
			                    else {
			                        hide.push(item); 
			                    }
							}
							else {
								// Items den Gruppen zuordnen
								if( item.hasClass('ui-selectonemenu-item-group') ) {
									var _this = this;
									
									// Wenn keiner Gruppe zugeordnet
									if( !item.prevAll().hasClass('ui-selectonemenu-item-group') ) {
										item.prevAll().each(function(){
											var $this = jQuery(this);
											var ing = _this.cfg.caseSensitive ? $this.text() : $this.text().toLowerCase();
											if (_this.filterMatcher(ing, filterValue)) {
												$this.show(); 
						                    }
						                    else {
						                    	$this.hide(); 
											}						
										});												
									}
									
									// innerhalb der Gruppen Filtern
									var itemsByGroup = item.nextUntil('.ui-selectonemenu-item-group');
									var groupResult = {group: null,items: null}; 
									var filterGroupStart = [];
									var filterGroupRest = [];
									itemsByGroup.each(function(){
										var $this = jQuery(this);
										var ibg = _this.cfg.caseSensitive ? $this.text() : $this.text().toLowerCase();
										if (_this.filterMatcher(ibg, filterValue)) {
							
											if( groupResult.group != itemLabel ) {
												groupResult = {group:itemLabel};
											}
											if(ibg.indexOf(filterValue) === 0) {
												filterGroupStart.push($this);
											} else {
												filterGroupRest.push($this);
											}
											$this.show();
							            } else {
											$this.hide();
										}
									});		
									
									if( groupResult.group == itemLabel ) {
										groupResult = {group:itemLabel, items:filterGroupStart.concat(filterGroupRest)};
										groupResult.items.unshift(item);
										filterGroupResult.push(groupResult);
									}
									
									
									if ( this.cfg.caseSensitive ? item.text() : item.text().toLowerCase() == groupResult.group ) {
										item.show();
									} else {
										item.hide();
									}
								}

							}

		                }
		            }
		
		            $.each(hide, function(i, o) { o.hide(); });
		            $.each(show, function(i, o) { o.show(); });
		            hide = [];
		            show = [];
					
					
					// HIS-Patch
					if(this.optGroupsSize == 0) {						
						var filterResult = filterListStart.concat(filterListRest);
						if( filterResult.length > 0 ) {							    
							filtered = true;					
							filterResult.forEach(li => this.itemsContainer.append(li));
							this.highlightItem(filterResult[0]);
						    PrimeFaces.scrollInView(this.itemsWrapper, filterResult[0]);
						}
					} else {
						if( filterGroupResult.length > 0 ) {
							filtered = true;
							filterGroupResult.forEach(fgr => fgr.items.forEach(li => this.itemsContainer.append(li)) );
							this.highlightItem(filterGroupResult[0].items[1]);
						    PrimeFaces.scrollInView(this.itemsWrapper, filterGroupResult[0].items[0]);
						}

					}

					
					
		            //Toggle groups
		            var groups = this.itemsContainer.children('.ui-selectonemenu-item-group');
		            for(var g = 0; g < groups.length; g++) {
		                var group = groups.eq(g);
		
		                if(g === (groups.length - 1)) {
		                    if(group.nextAll().filter(':visible').length === 0)
		                        hide.push(group);
		                    else
		                        show.push(group);
		                }
		                else {
		                    if(group.nextUntil('.ui-selectonemenu-item-group').filter(':visible').length === 0)
		                        hide.push(group);
		                    else
		                        show.push(group);
		                }
		            }
		
		            $.each(hide, function(i, o) { o.hide(); });
		            $.each(show, function(i, o) { o.show(); });
		        }
		
		        var firstVisibleItem = this.items.filter(':visible:not(.ui-state-disabled):first');
		        if(firstVisibleItem.length && !filtered) {
		            this.highlightItem(firstVisibleItem);
		        }
				filtered = false;
		        if(this.itemsContainer.height() < this.cfg.initialHeight) {
		            this.itemsWrapper.css('height', 'auto');
		        }
		        else {
		            this.itemsWrapper.height(this.cfg.initialHeight);
		        }
		
		        this.alignPanel();
		    },
		
		    /**
		     * Finds the value of the currently selected item, if any.
		     * @return {string} The value of the currently selected item. Empty string if none is selected.
		     */
		    getSelectedValue: function() {
		        return this.input.val();
		    },
		
		    /**
		     * Finds the label of the currently selected item, if any.
		     * @return {string} The label of the currently selected item. Empty string if none is selected.
		     */
		    getSelectedLabel: function() {
		        return this.options.filter(':selected').text();
		    },
		
		    /**
		     * Finds the label of the option with the given value.
		     * @private
		     * @param {string} value The value of a selectable option.
		     * @return {string} The label of the option with the given value.
		     */
		    getLabelToDisplay: function(value) {
		        if(this.cfg.labelTemplate && value !== '&nbsp;') {
		            return this.cfg.labelTemplate.replace('{0}', value);
		        }
		        return String(value);
		    },
		
		    /**
		     * Adjusts the value of the aria attributes for the given selectable option.
		     * @private
		     * @param {JQuery} item An option for which to set the aria attributes.
		     */
		    changeAriaValue: function (item) {
		        var itemId = item.attr('id');
		
		        this.focusInput.attr('aria-activedescendant', itemId)
		                .attr('aria-describedby', itemId);
		        this.itemsContainer.attr('aria-activedescendant', itemId);
		    },
		
		    /**
		     * Loads the overlay panel with the selectable options, if dynamic mode is enabled.
		     * @private
		     */
		    dynamicPanelLoad: function() {
		        var $this = this,
		        options = {
		            source: this.id,
		            process: this.id,
		            update: this.id,
		            global: false,
		            params: [{name: this.id + '_dynamicload', value: true}],
		            onsuccess: function(responseXML, status, xhr) {
		                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
		                    widget: $this,
		                    handle: function(content) {
		                        var $content = $($.parseHTML(content));
		
		                        var $ul = $content.filter('ul');
		                        $this.itemsWrapper.empty();
		                        $this.itemsWrapper.append($ul);
		
		                        var $select = $content.filter('select');
		                        $this.input.replaceWith($select);
		                    }
		                });
		
		                return true;
		            },
		            oncomplete: function(xhr, status, args, data) {
		                $this.isDynamicLoaded = true;
		                $this.input = $($this.jqId + '_input');
		                $this.options = $this.input.children('option');
		
		                $this.renderPanelContentFromHiddenSelect(false);
		
		                $this.initContents();
		                $this.bindItemEvents();
		            }
		        };
		
		        PrimeFaces.ajax.Request.handle(options);
		    },
		
		    /**
		     * Invokes the given method after making sure that the overlay panel was loaded (in case dynamic mode is enabled).
		     * @private
		     * @param {(this: PrimeFaces.widget.SelectOneMenu, event: JQuery.TriggeredEvent) => void} handleMethod Callback method to
		     * invoke after the dynamic overlay panel was loaded.
		     * @param {JQuery.TriggeredEvent} event An event that is passed to the callback.
		     */
		    callHandleMethod: function(handleMethod, event) {
		        var $this = this;
		        if(this.cfg.dynamic && !this.isDynamicLoaded) {
		            this.dynamicPanelLoad();
		
		            var interval = setInterval(function() {
		                if($this.isDynamicLoaded) {
		                    if (handleMethod) {
		                        handleMethod.call($this, event);
		                    }
		
		                    clearInterval(interval);
		                }
		            }, 10);
		        }
		        else {
		            this.renderPanelContentFromHiddenSelect(true);
		
		            if (handleMethod) {
		                handleMethod.call(this, event);
		            }
		        }
		    },
		
		    /**
		     * Renders panel content based on hidden select.
		     * @private
		     * @param {boolean} initContentsAndBindItemEvents `true` to call {@link initContents} and {@link bindItemEvents}
		     * after rendering, `false` otherwise.
		     */
		    renderPanelContentFromHiddenSelect: function(initContentsAndBindItemEvents) {
		         if (this.cfg.renderPanelContentOnClient && this.itemsWrapper.children().length === 0) {
			
					 //filter
					 if (this.cfg.filter) {
						 this.cfg.initialHeight = this.itemsWrapper.height();
						 this.setupFilterMatcher();
						 this.filterInput = this.panel.find('> div.ui-selectonemenu-filter-container > input.ui-selectonemenu-filter');
						 PrimeFaces.skinInput(this.filterInput);

						 this.bindFilterEvents();
					 }
					 
					 PrimeFaces.utils.registerDynamicOverlay(this, this.panel, this.id + '_panel');
					 
                     var panelContent = jQuery('<ul/>').attr('id', this.id + '_items').addClass('ui-selectonemenu-items ui-selectonemenu-list ui-widget-content ui-widget ui-corner-all ui-helper-reset').attr('role', 'listbox');
                     panelContent.append(this.renderSelectItems(this.input)).html();
		             		
		             this.itemsWrapper.append(panelContent);
		
		             if (initContentsAndBindItemEvents) {
		                 this.initContents();
		                 this.bindItemEvents();
		             }
		         }
		    },
		
		    /**
		     * Renders panel HTML-code for all select items.
		     * @private
		     * @param {JQuery} parentItem A parent item (select, optgroup) for which to render HTML code.
		     * @param {boolean} [isGrouped] Indicated whether the elements of the parent item should be marked as grouped.
		     * @return {string} The rendered HTML string.
		     */
		    renderSelectItems: function(parentItem, isGrouped) {
		        var $this = this;
		        var content = new Array();
		        isGrouped = isGrouped || false;
		
		        var opts = parentItem.children("option, optgroup");
		        opts.each(function(index, element) {
		            content.push($this.renderSelectItem(element, isGrouped));
		        });
		        return content;
		    },
		
		    /**
		     * Renders panel HTML code for one select item (group).
		     * @private
		     * @param {JQuery} item An option (group) for which to render HTML code.
		     * @param {boolean} [isGrouped] Indicates whether the item is part of a group.
		     * @return {string} The rendered HTML string.
		     */
		    renderSelectItem: function(item, isGrouped) {
		        var content = "";
		        var $item = $(item);
		        var label;
		        var title = $item.data("title");
		        var escape = $item.data("escape");
		        var cssClass;
		
		        if (item.tagName === "OPTGROUP") {
		            label = $item.attr("label");
		            if (escape) {
		                label = $("<div>").text(label).html();
		            }
		            cssClass = "ui-selectonemenu-item-group ui-corner-all";
		        }
		        else { //OPTION
		            if (escape) {
		                label = $item.html();
		                if ($item.text() === "&nbsp;") {
		                    label = $item.text();
		                }
		            }
		            else {
		                label = $item.text();
		            }
		            cssClass = "ui-selectonemenu-item ui-selectonemenu-list-item ui-corner-all";
		            if (isGrouped) {
		                cssClass += " ui-selectonemenu-item-group-children";
		            }
		        }
		
		        var dataLabel = label.replace(/(<([^>]+)>)/gi, "").replaceAll('"', '&quot;');
				var dataValue = $item[0].value;
		        if ($item.data("noselection-option")) {
		            cssClass += " ui-noselection-option";
		        }
		
                var $li = jQuery('<li data-label="'+dataLabel+'">'+label+'</li>');
                $li.addClass(cssClass).attr('tabindex', '-1').attr('role', 'option').attr('title', title).attr('data-itemValue', dataValue);
                
                if ($item.is(':disabled')) {
                    $li.attr('disabled','disabled');
                }
                if (item.tagName === "OPTGROUP") {
                    var arr;
                    var li;                    
                    this.renderSelectItems($item, true).forEach(function(el){
                        arr += el.prop('outerHTML');
                    });
                    li = $li.prop('outerHTML');
                    li += arr;
                    $li = jQuery(li).filter(function(){ return this.nodeValue != 'undefined'; });
                }
                return $li;

		    },
		
		
		    /**
		     * Updates the style class of the label that indicates the currently selected item.
		     * @param {boolean} add `true` if a placeholder should be displayed, or `false` otherwise.
		     */
		    updatePlaceholderClass: function(add) {
		        if (add) {
		            this.label.addClass('ui-selectonemenu-label-placeholder');
		        }
		        else {
		            this.label.removeClass('ui-selectonemenu-label-placeholder');
		        }
		    }
		
		});
    }
};
 'use strict';

use_package("de.his.component");

de.his.component.PrimeTreetable = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
	this.moduleName = "de.his.component.PrimeTreetable";
	const setAriaActivedescendant = true;
	const setAriaOwns = true;
	
	var defaultAriaLabel = '';
	var initialized = false;
	
	var zoomedToTiles = false;
		
    this.init = function() {
    	if (window.PrimeFaces) {
			PrimeFaces.widget.TreeTable();
			updateClasses();
    	}
    }
	
    this.refresh = function() {
        this.init();
    };
    	
    if (window.PrimeFaces) {
    	/// START PrimeFaces-Komponente ///    	
		PrimeFaces.widget.TreeTable = PrimeFaces.widget.DeferredWidget.extend({

    /**
     * Map between the sort order names and the multiplier for the comparator.
     * @protected
     * @type {Record<PrimeFaces.widget.DataTable.SortOrder, -1 | 0 | 1>}
     */
    SORT_ORDER: {
        ASCENDING: 1,
        DESCENDING: -1,
        UNSORTED: 0
    },

    /**
     * @override
     * @inheritdoc
     * @param {PrimeFaces.PartialWidgetCfg<TCfg>} cfg
     */
    init: function(cfg) {
        this._super(cfg);
        this.thead = $(this.jqId + '_head');
        this.tbody = $(this.jqId + '_data');
        this.cfg.expandMode = this.cfg.expandMode||"children";
    
        this.resize();
        this.actionButtons();
        this.renderDeferred();
        let isTile = checkIfTile();
        if((screen.availWidth <= 768 && !initialized) || (isTile && !initialized)){
			if(screen.availWidth > 768){
				zoomedToTiles = true;
			}
			this.collapsAllNodes();
			initialized = true;
		}
    },

    /**
     * @include
     * @override
     * @protected
     * @inheritdoc
     */
    _render: function() {
        if(this.cfg.scrollable) {
            this.setupScrolling();
        }

        if(this.cfg.filter) {
            this.setupFiltering();
        }

        if(this.cfg.resizableColumns) {
            this.resizableStateHolder = $(this.jqId + '_resizableColumnState');
            this.resizableState = [];

            if(this.resizableStateHolder.attr('value')) {
                this.resizableState = this.resizableStateHolder.val().split(',');
            }

            this.setupResizableColumns();
        }

        if(this.cfg.stickyHeader) {
            this.setupStickyHeader();
        }

        if(this.cfg.editable) {
            this.bindEditEvents();
        }

        this.bindEvents();
        
    },

    /**
     * @override
     * @inheritdoc
     * @param {PrimeFaces.PartialWidgetCfg<TCfg>} cfg
     */
    refresh: function(cfg) {
        this.columnWidthsFixed = false;
        this.scrollStateVal = this.scrollStateHolder ? this.scrollStateHolder.val() : null;

        this._super(cfg);
    },

    /**
     * Sets up all event listeners that are required by this widget.
     * @private
     */
    bindEvents: function() {
        var $this = this,
        treeTogglerSelector = '> tr > td > .ui-treetable-toggler.treeToggler',
        tileTogglerSelector = '> tr > td > .ui-treetable-toggler.tileToggler';
			
        // Brotkrumenpfad
        this.jq.closest('.ui-treetable').children('.treetableBreadcrumb-element').prependTo( this.jq.find('.treetableBreadcrumb') );
      
		jQuery('.treetableBreadcrumb').off('click', '.treetableBreadcrumb-node:not(.previous):not(:last)').on('click', '.treetableBreadcrumb-node:not(.previous):not(:last)', function(){
			var $this = jQuery(this);
			var dataRk = $this.attr('data-rk');
			
			$this.closest('.ui-treetable').find('.ui-widget-content[data-rk="' + dataRk + '"]').find('.ui-treetable-toggler.tileToggler').trigger('click');
		});
		
		// Ein Klick auf den zurück-Button entspricht gleich dem Klick auf den vorletzten Krümel
		jQuery('.breadcrumb-container').off('click', '.breadcrumbBack').on('click', '.breadcrumbBack', function(){
			var $this = jQuery(this);
			if($this.next('ul')[0].children.length > 2){
				var penultimateChildRk = $this[0].nextSibling.children[$this[0].nextSibling.children.length - 2].dataset.rk;
				$this.closest('.ui-treetable').find('.ui-widget-content[data-rk="' + penultimateChildRk + '"]').find('.ui-treetable-toggler.tileToggler').trigger('click');			
			}
			else{
				var dataRk = $this[0].nextSibling.children[1].dataset.rk;
				$this.closest('.ui-treetable').find('.ui-widget-content[data-rk="' + dataRk + '"]').find('.ui-treetable-toggler.tileToggler').trigger('click', true);			
			}
		});
		
		jQuery('.breadcrumb-container').off('focus', '.breadcrumbBack').on('focus', '.breadcrumbBack', function(){
			var $this = jQuery(this);
			var language = de.his.common.LanguageHelper.currentLanguage();
			if (language == "de") {
				this.defaultAriaLabel = 'Zurück zu';
				if(jQuery('ul.treetableBreadcrumb')[0].children.length > 2){
					var goBackToBreadcrumb = $this.closest('.ui-treetable').find('ul.treetableBreadcrumb')[0]?.children[jQuery('ul.treetableBreadcrumb')[0].children.length - 2];
					$this.attr('aria-label', this.defaultAriaLabel + ' ' + goBackToBreadcrumb.children[0]?.innerHTML);
					$this.attr('title', this.defaultAriaLabel + ' ' + goBackToBreadcrumb.children[0]?.innerHTML);
				}
				else{
					$this.attr('aria-label', 'Zurück');
					$this.attr('title', 'Zurück');
				}
			}
			else{
				this.defaultAriaLabel = 'Back to';
				if(jQuery('ul.treetableBreadcrumb')[0].children.length > 2){
					var goBackToBreadcrumb = $this.closest('.ui-treetable').find('ul.treetableBreadcrumb')[0]?.children[jQuery('ul.treetableBreadcrumb')[0].children.length - 2];
					$this.attr('aria-label', this.defaultAriaLabel + ' ' + goBackToBreadcrumb.children[0]?.innerHTML);
					$this.attr('title', this.defaultAriaLabel + ' ' + goBackToBreadcrumb.children[0]?.innerHTML);
				}
				else{
					$this.attr('aria-label', 'Back');
					$this.attr('title', 'Back');
				}
			}
		});
		
		jQuery('.breadcrumb-container').off('focusout', '.breadcrumbBack').on('focusout', '.breadcrumbBack', function(){
			var $this = jQuery(this);
			$this.removeAttr('aria-label');
			$this.removeAttr('title');
		});
		
		screen.orientation.addEventListener("change", (event) => {
			if(screen.availWidth <= 768){
				$this.collapsAllNodes();
			}
			else{
				updateClasses();
			}
		});
		
		window.addEventListener("keyup", (event) => {
			// Zoomevent for STRG+, STRG-, STRG + Mousewheel
			if (event.key == 'Control') {
				let isTile = checkIfTile();
				if(isTile){
					zoomedToTiles = true;
					$this.collapsAllNodes();
				}
				else{
					zoomedToTiles = false;
					updateClasses();
				}
			}
		});
		
        // Tree: expand and collapse
        this.tbody.off('click.treeTable-toggle', treeTogglerSelector)
                    .on('click.treeTable-toggle', treeTogglerSelector, null, function(e) {
                        var toggler = $(this),
                        node = toggler.closest('tr');
                        
                        if(!node.data('processing')) {
                            node.data('processing', true);
                            $this.refreshBreadcrumb(node);
                            if(toggler.hasClass('ui-icon-triangle-1-e')) {
                                $this.expandNode(node);
                                }
                            else{
                                $this.collapseNode(node);
                                }

							var statetitle = toggler.attr('data-statetitle'),
							// toggler.attr('title') is empty onclick because on mousenter/focus it will be replaced by data-title in customtooltips.
							title = toggler.attr('title') || toggler.attr('data-title');
							toggler.attr('title', statetitle).attr('aria-label', statetitle).attr('data-statetitle', title);
							toggler.trigger("updateTooltip");
							
                        }
                    });
        
        // Tile: expand and collapse
        this.tbody.off('click.treeTable-toggle', tileTogglerSelector)
                    .on('click.treeTable-toggle', tileTogglerSelector, null, function(e, collapseAll = false) {
                        $this.closeDroplistMenu();
                        var toggler = $(this),
                        node = toggler.closest('tr');
                        
                        jQuery('.treeTableSmallAnimation')[0].classList.remove('noDisplay');
                        
                        var tiles = jQuery('.ui-treetable table[data-istreeexpanded="true"] tr.ui-widget-content[data-isParentExpanded="true"]');
                        var treeTable = this.closest('.ui-treetable.ui-widget').id;
                        for(let tile of tiles){
							if(parseInt(tile.dataset.level) <= parseInt(node[0].dataset.level) && tile.id?.contains(treeTable)){
								tile.classList.add('noDisplay');
							}
							else{
								tile.classList.remove('noDisplay');
							}
						}
						
                        if(!node.data('processing')) {
							document.getElementsByClassName('ui-treetable ui-widget')[0].style.display = 'none';
                            node.data('processing', true);
                            $this.refreshBreadcrumb(node);
                            if(toggler.hasClass('ui-icon-triangle-1-e')) {
                                $this.expandNode(node);
                                hiddenChange('.breadcrumb-container', 'false');
                                $this.setupStickyBreadcrumb();
                            }
                            else{
								if(collapseAll === true){
									$this.collapseExpandedChildren($this, node);
									$this.collapseNode(node);
									hiddenChange('.breadcrumb-container', 'true');
								}
								else{
									var sibling = node.next('tr');
									while(sibling[0]?.innerHTML.contains('iconfont-bullet_mono') || sibling[0]?.ariaExpanded == 'false'){
										sibling = sibling.next('tr');
									}
											
									$this.collapseExpandedChildren($this, node);
			                                
			                        $this.collapseNode(sibling);
			                        // Processing fü den Hauptnode setzen
			                        node.data('processing', false);
			                        $this.setupStickyBreadcrumb();
		                        }
		                        
                            }

							var statetitle = toggler.attr('data-statetitle'),
							title = toggler.attr('title');
							toggler.attr('title', statetitle).attr('aria-label', statetitle).attr('data-statetitle', title);
                        }
                    });

        //selection
        if(this.cfg.selectionMode) {
            this.jqSelection = $(this.jqId + '_selection');
            var selectionValue = this.jqSelection.val();
            this.selections = selectionValue === "" ? [] : selectionValue.split(',');
            this.cfg.disabledTextSelection = this.cfg.disabledTextSelection === false ? false : true;

            this.bindSelectionEvents();
        }

        if(this.cfg.sorting) {
            this.bindSortEvents();
        }

        if(this.cfg.paginator) {
            this.cfg.paginator.paginate = function(newState) {
                $this.handlePagination(newState);
            };

            this.paginator = new PrimeFaces.widget.Paginator(this.cfg.paginator);
            this.paginator.bindSwipeEvents(this.jq, this.cfg);
        }
    },
    
    setFrozenColumns: function(node){
		var treetable = node.closest('div.ui-treetable');
        if( treetable.parents('.frozenCol_2').length > 0 ) {
        	var thWidth = treetable.find('th:nth-child(1)').outerWidth();
            treetable.find('td:nth-child(2), th:nth-child(2)').css({left: thWidth});
        }
        if( treetable.parents('.frozenCol_3').length > 0 ) {
			var thWidth2 = treetable.find('th:nth-child(1)').outerWidth();
            treetable.find('td:nth-child(2), th:nth-child(2)').css({left: thWidth2});
            var thWidth3 = treetable.find('th:nth-child(1)').outerWidth() + treetable.find('th:nth-child(2)').outerWidth();
            treetable.find('td:nth-child(3), th:nth-child(3)').css({left: thWidth3});
        }
	},
    
    // Beim Klick auf einen Krümel, bzw. beim initialen Schließen alle noch geöffneten tieferen Knoten schließen
    collapseExpandedChildren: function(jQThis, node) {
		for(let closedNode of node.nextAll('tr[aria-expanded="true"]')){
			if(closedNode.ariaExpanded == 'true'){
				jQThis.collapseNode($(closedNode));
			}				
		}
		if(parseInt(node[0].dataset.level) == 1){
			node[0].classList.remove('noDisplay');
		}	
	},

    /**
     * Sets up all event listeners required for the standard filters. Also skins the filter inputs.
     * @private
     */
    setupFiltering: function() {
        var $this = this,
        filterColumns = this.thead.find('> tr > th.ui-filter-column');
        this.cfg.filterEvent = this.cfg.filterEvent||'keyup';
        this.cfg.filterDelay = this.cfg.filterDelay||300;

        filterColumns.children('.ui-column-filter').each(function() {
            var filter = $(this);

            if(filter.is('input:text')) {
                PrimeFaces.skinInput(filter);
                $this.bindTextFilter(filter);
            }
            else {
                PrimeFaces.skinSelect(filter);
                $this.bindChangeFilter(filter);
            }
        });
    },

    /**
     * Clear the filter input of this tree table and shows all rows again.
     */
    clearFilters: function() {
        this.thead.find('> tr > th.ui-filter-column > .ui-column-filter').val('');
        this.thead.find('> tr > th.ui-filter-column > .ui-column-customfilter').each(function() {
            var widgetElement = $(this).find('.ui-widget');
            if (widgetElement.length > 0) {
                var widget = PrimeFaces.getWidgetById(widgetElement.attr('id'));
                if (widget && typeof widget.resetValue === 'function') {
                    widget.resetValue(true);
                }
                else {
                    $(this).find(':input').val('');
                }
            }
            else {
                $(this).find(':input').val('');
            }
        });

        $(this.jqId + '\\:globalFilter').val('');
        this.filter();
    },

    /**
     * Sets up the event listeners required for filtering this tree table, filtering either when enter is pressed or
     * when the {@link TreeTableCfg.filterEvent|configured event} occurs.
     * @private
     * @param {JQuery} filter The filter input field.
     */
    bindTextFilter: function(filter) {
        if(this.cfg.filterEvent === 'enter')
            this.bindEnterKeyFilter(filter);
        else
            this.bindFilterEvent(filter);

        // #7562 draggable columns cannot be filtered with touch
        if (PrimeFaces.env.isTouchable(this.cfg)) {
            filter.on('touchstart', function(e) {
                e.stopPropagation();
            });
        }
    },

    /**
     * Sets up the event listeners required for filtering this tree table when the filter input has changed.
     * @private
     * @param {JQuery} filter The filter input field.
     */
    bindChangeFilter: function(filter) {
        var $this = this;

        filter.on('change', function() {
            $this.filter();
        });
    },

    /**
     * Sets up the event listeners required for filtering this tree table when the enter key is pressed.
     * @private
     * @param {JQuery} filter The filter input field.
     */
    bindEnterKeyFilter: function(filter) {
        var $this = this;

        filter.on('keydown', PrimeFaces.utils.blockEnterKey)
        .on('keyup', function(e) {
            var key = e.which,
            keyCode = $.ui.keyCode;

            if(key === keyCode.ENTER) {
                $this.filter();

                e.preventDefault();
            }
        });
    },

    /**
     * Sets up the event listeners required for filtering this tree table.
     * @private
     * @param {JQuery} filter The filter input field.
     */
    bindFilterEvent: function(filter) {
        var $this = this;

        //prevent form submit on enter key
        filter.on('keydown.treeTable-blockenter', PrimeFaces.utils.blockEnterKey)
        .on(this.cfg.filterEvent + '.treeTable', function(e) {
            if($this.filterTimeout) {
                clearTimeout($this.filterTimeout);
            }

            $this.filterTimeout = setTimeout(function() {
                $this.filter();
                $this.filterTimeout = null;
            },
            $this.cfg.filterDelay);
        });
    },

    /**
     * Reads the current value of the filter input and performs a filtering operation. Sends an AJAX requests to the
     * server and updates this tree table with the result. Also invokes the appropriate behaviors.
     */
    filter: function() {
        var $this = this,
        options = {
            source: this.id,
            update: this.id,
            process: this.id,
            formId: this.getParentFormId(),
            params: [{name: this.id + '_filtering', value: true},
                     {name: this.id + '_encodeFeature', value: true}],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            this.tbody.html(content);
                        }
                    });

                return true;
            },
            oncomplete: function(xhr, status, args, data) {
                var paginator = $this.getPaginator();
                if(args && args.totalRecords) {
                    if(paginator) {
                        paginator.setTotalRecords(args.totalRecords);
                    }
                }
            }
        };

        if(this.hasBehavior('filter')) {
            this.callBehavior('filter', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * Handles a pagination event by updating this tree table and invoking the appropriate behaviors.
     * @private
     * @param {PrimeFaces.widget.Paginator.PaginationState} newState The new pagination state to apply.
     */
    handlePagination: function(newState) {
        var $this = this,
        options = {
            source: this.id,
            update: this.id,
            process: this.id,
            params: [
                {name: this.id + '_pagination', value: true},
                {name: this.id + '_first', value: newState.first},
                {name: this.id + '_rows', value: newState.rows}
            ],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            this.tbody.html(content);
                        }
                    });

                return true;
            },
            oncomplete: function() {
                $this.paginator.cfg.page = newState.page;
                $this.paginator.updateUI();
                
                jQuery(jQuery("ul.short-waiting-behavior a").removeData('waitingBehaviorSet'));
                jQuery("ul.short-waiting-behavior a").removeAttr('data-startswaiting');
                de.his.modules.Waiting.refresh();
            }
        };

        if(this.hasBehavior('page')) {
            this.callBehavior('page', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * Returns the paginator instance if any is exists.
     * @return {PrimeFaces.widget.Paginator | undefined} The paginator instance for this widget, or `undefined` if
     * paging is not enabled.
     */
    getPaginator: function() {
        return this.paginator;
    },

    /**
     * Sets up all events listeners required for selecting one or multiple rows of this tree table.
     * @private
     */
    bindSelectionEvents: function() {
        var $this = this,
        rowSelector = '> tr.ui-treetable-selectable-node';
		
        this.tbody.off('mouseenter.treeTable mouseleave.treeTable click.treeTable', rowSelector)
                    .on('mouseenter.treeTable', rowSelector, null, function(e) {
                        $(this).addClass('ui-state-hover');
                    })
                    .on('mouseleave.treeTable', rowSelector, null, function(e) {
                        $(this).removeClass('ui-state-hover');
                    })
                    .on('click.treeTable', rowSelector, null, function(e) {
                        $this.onRowClick(e, $(this));
                    });

        if(this.isCheckboxSelection()) {
           var checkboxSelector =  this.cfg.nativeElements ? '> tr.ui-treetable-selectable-node > td:first-child :checkbox':
                    '> tr.ui-treetable-selectable-node > td:first-child div.ui-chkbox-box';

                this.tbody.off('click.treeTable-checkbox mouseenter.treeTable-checkbox mouseleave.treeTable-checkbox', checkboxSelector)
                        .on('mouseenter.treeTable-checkbox', checkboxSelector, null, function(e) {
                            $(this).addClass('ui-state-hover');
                        })
                        .on('mouseleave.treeTable-checkbox', checkboxSelector, null, function(e) {
                            $(this).removeClass('ui-state-hover');
                        })
                        .on('click.treeTable-checkbox', checkboxSelector, null, function(e) {
                            var node = $(this).closest('tr.ui-treetable-selectable-node');
                            $this.toggleCheckboxNode(node);
                        });


                //initial partial selected visuals
                if(this.cfg.nativeElements) {
                    this.indeterminateNodes(this.tbody.children('tr.ui-treetable-partialselected'));
                }
        }
    },

    /**
     * Sets up all events listeners required for sorting the rows of this tree table.
     * @private
     */
    bindSortEvents: function() {
        var $this = this,
            hasAriaSort = false;

        this.cfg.multiSort = this.cfg.multiSort||false;
        this.cfg.allowUnsorting = this.cfg.allowUnsorting||false;
        this.sortMeta = [];

        //aria messages
        this.ascMessage = "Aufsteigend sortiert";
        this.descMessage = "Absteigend sortiert";
        if (this.cfg.allowUnsorting) {
            this.otherMessage = "Unsortiert";
        }
        else {
            this.otherMessage = "Aufsteigend";
        }

        this.sortableColumns = this.thead.find('> tr > th.ui-sortable-column');

        this.sortableColumns.each(function() {
            var columnHeader = $(this),
            columnHeaderId = columnHeader.attr('id'),
            sortIcon = columnHeader.children('span.ui-sortable-column-icon'),
            sortOrder = null,
            ariaLabel = columnHeader.attr('aria-label');

            if (sortIcon.hasClass('ui-icon-triangle-1-n')) {
                sortOrder = $this.SORT_ORDER.ASCENDING;
                columnHeader.attr('aria-label', $this.getSortMessage(this.descMessage));
                if (!hasAriaSort) {
                    columnHeader.attr('aria-sort', 'ascending');
                    hasAriaSort = true;
                }
            }
            else if (sortIcon.hasClass('ui-icon-triangle-1-s')) {
                sortOrder = $this.SORT_ORDER.DESCENDING;
                columnHeader.attr('aria-label', $this.getSortMessage(this.otherMessage));
                if (!hasAriaSort) {
                    columnHeader.attr('aria-sort', 'descending');
                    hasAriaSort = true;
                }
            }
            else {
                sortOrder = $this.SORT_ORDER.UNSORTED;
                columnHeader.attr('aria-label', $this.getSortMessage(this.ascMessage));
                if (!hasAriaSort) {
                    columnHeader.attr('aria-sort', 'other');
                    hasAriaSort = true;
                }
            }

            columnHeader.data('sortorder', sortOrder);

            if ($this.cfg.multiSort && $this.cfg.sortMetaOrder) {
                var resolvedSortMetaIndex = $.inArray(columnHeaderId, $this.cfg.sortMetaOrder);

                $this.sortMeta[resolvedSortMetaIndex] = {
                    col: columnHeaderId,
                    order: sortOrder
                };
            }
        });

        this.sortableColumns.on('mouseenter.treeTable', function() {
            $(this).addClass('ui-state-hover');
        })
        .on('mouseleave.treeTable', function() {
            $(this).removeClass('ui-state-hover');
        })
        .on('click.treeTable', function(e, metaKeyOn){
            if(!$this.shouldSort(e, this)) {
                return;
            }

            PrimeFaces.clearSelection();

            var columnHeader = $(this),
                sortOrderData = columnHeader.data('sortorder'),
                sortOrder = (sortOrderData === $this.SORT_ORDER.UNSORTED) ? $this.SORT_ORDER.ASCENDING :
                    (sortOrderData === $this.SORT_ORDER.ASCENDING) ? $this.SORT_ORDER.DESCENDING :
                        $this.cfg.allowUnsorting ? $this.SORT_ORDER.UNSORTED : $this.SORT_ORDER.ASCENDING,
                metaKey = e.metaKey || e.ctrlKey || metaKeyOn;

            if (!$this.cfg.multiSort || !metaKey) {
                $this.sortMeta = [];
            }

            $this.addSortMeta({
                col: columnHeader.attr('id'),
                order: sortOrder
            });
            
            $this.sort(columnHeader, sortOrder, $this.cfg.multiSort && metaKey);
        })
        .on('keydown.treeTable', function(e, metaKeyOn){
            // Enter-Event
            if(e.keyCode === 13){
                if(!$this.shouldSort(e, this)) {
                    return;
                }
    
                PrimeFaces.clearSelection();
    
                var columnHeader = $(this),
                    sortOrderData = columnHeader.data('sortorder'),
                    sortOrder = (sortOrderData === $this.SORT_ORDER.UNSORTED) ? $this.SORT_ORDER.ASCENDING :
                        (sortOrderData === $this.SORT_ORDER.ASCENDING) ? $this.SORT_ORDER.DESCENDING :
                            $this.cfg.allowUnsorting ? $this.SORT_ORDER.UNSORTED : $this.SORT_ORDER.ASCENDING,
                    metaKey = e.metaKey || e.ctrlKey || metaKeyOn;
    
                if (!$this.cfg.multiSort || !metaKey) {
                    $this.sortMeta = [];
                }
    
                $this.addSortMeta({
                    col: columnHeader.attr('id'),
                    order: sortOrder
                });
                $this.sort(columnHeader, sortOrder, $this.cfg.multiSort && metaKey);

            }
        });

        $this.updateSortPriorityIndicators();
    },

    /**
     * @override
     * @inheritdoc
     * @param {PrimeFaces.widget.ContextMenu} menuWidget
     * @param {PrimeFaces.widget.TreeTable} targetWidget
     * @param {string} targetId
     * @param {PrimeFaces.widget.ContextMenuCfg} cfg
     */
    bindContextMenu : function(menuWidget, targetWidget, targetId, cfg) {
        var targetSelector = targetId + ' .ui-treetable-data > ' + (cfg.nodeType ? 'tr.ui-treetable-selectable-node.' + cfg.nodeType : 'tr.ui-treetable-selectable-node');
        var targetEvent = cfg.event + '.treetable';

        $(document).off(targetEvent, targetSelector).on(targetEvent, targetSelector, null, function(e) {
            targetWidget.onRowRightClick(e, $(this));
            menuWidget.show(e);
        });
    },
    
    setupStickyBreadcrumb: function() {
        const $hisinoneHeader = jQuery('#hisinoneHeader');
        const hisinoneHeaderHeight = $hisinoneHeader.outerHeight();
        
        jQuery(window).on('scroll', function(e){
            /*
             * Get parent element of breadcrumb container (studyPlannerTree) to get position of the breadcrumb. 
             * Can't use breadcrumb position because it will move and is initially 0, because it's display non.
             * Needs to be updated because the height of page changes on usage of collapsible panel and helptexts
             */
            const studyPlannerTreePos = jQuery('.breadcrumb-container').parent().offset().top;
            const current_scroll_top = jQuery(document).scrollTop();
            
            if(current_scroll_top <= studyPlannerTreePos) {
                // scrolling above the container
                jQuery('.breadcrumb-container').css({
                   'top': 0,
                   'border-radius': '7px'
                });
                
            } else if ($hisinoneHeader.hasClass('js-hide')) {
                //scrolling with header hidden
                jQuery('.breadcrumb-container').css({
                   'top': 0,
                   'border-radius': '0 0 7px 7px'
                });
            } else {
                //scrolling with header visible
                jQuery('.breadcrumb-container').css({
                   'top': hisinoneHeaderHeight + 'px',
                   'border-radius': '0 0 7px 7px'
                });
            }
        });
    },

    /**
     * Sets up the CSS and event listeners for the sticky header feature, if it is enabled.
     * @private
     */
    setupStickyHeader: function() {
        var table = this.thead.parent(),
        offset = table.offset(),
        win = $(window),
        $this = this;

        this.stickyContainer = $('<div class="ui-treetable ui-treetable-sticky ui-widget"><table></table></div>');
        this.clone = this.thead.clone(false);
        this.stickyContainer.children('table').append(this.thead);
        table.append(this.clone);

        this.stickyContainer.css({
            position: 'absolute',
            width: table.outerWidth() + 'px',
            top: offset.top + 'px',
            left: offset.left + 'px',
            'z-index': PrimeFaces.nextZindex()
        });

        this.jq.prepend(this.stickyContainer);

        if(this.cfg.resizableColumns) {
            this.relativeHeight = 0;
        }

        PrimeFaces.utils.registerScrollHandler(this, 'scroll.' + this.id + '_align', function() {
            var scrollTop = win.scrollTop(),
            tableOffset = table.offset();

            if(scrollTop > tableOffset.top) {
                $this.stickyContainer.css({
                                        'position': 'fixed',
                                        'top': '0px'
                                    })
                                    .addClass('ui-shadow ui-sticky');

                if($this.cfg.resizableColumns) {
                    $this.relativeHeight = scrollTop - tableOffset.top;
                }

                if(scrollTop >= (tableOffset.top + $this.tbody.height()))
                    $this.stickyContainer.hide();
                else
                    $this.stickyContainer.show();
            }
            else {
                $this.stickyContainer.css({
                                        'position': 'absolute',
                                        'top': tableOffset.top + 'px'
                                    })
                                    .removeClass('ui-shadow ui-sticky');

                if($this.stickyContainer.is(':hidden')) {
                    $this.stickyContainer.show();
                }

                if($this.cfg.resizableColumns) {
                    $this.relativeHeight = 0;
                }
            }
        });

        PrimeFaces.utils.registerResizeHandler(this, 'resize.sticky-' + this.id, null, function(e) {
            var _delay = e.data.delay || 0;

            if (_delay !== null && typeof _delay === 'number' && _delay > -1) {
                if ($this.resizeTimeout) {
                    clearTimeout($this.resizeTimeout);
                }

                $this.stickyContainer.hide();
                $this.resizeTimeout = setTimeout(function() {
//                    $this.stickyContainer.css('left', orginTableContent.offset().left + 'px');
                    $this.stickyContainer.width(table.outerWidth());
                    $this.stickyContainer.show();
                }, _delay);
            }
            else {
                $this.stickyContainer.width(table.outerWidth());
            }
        }, { delay: null });

        //filter support
        this.clone.find('.ui-column-filter').prop('disabled', true);
    },

    /**
     * Sets up all events listeners required for editing entire rows or individual cells.
     * @private
     */
    bindEditEvents: function() {
        var $this = this;
        this.cfg.cellSeparator = this.cfg.cellSeparator||' ',
        this.cfg.saveOnCellBlur = (this.cfg.saveOnCellBlur === false) ? false : true;

        if(this.cfg.editMode === 'row') {
            var rowEditorSelector = '> tr > td > div.ui-row-editor';
            this.tbody.off('click.treetable', rowEditorSelector)
                        .on('click.treetable', rowEditorSelector, null, function(e) {
                            var element = $(e.target),
                            row = element.closest('tr');

                            if(element.hasClass('ui-icon-pencil')) {
                                $this.switchToRowEdit(row);
                                element.hide().siblings().show();
                            }
                            else if(element.hasClass('ui-icon-check')) {
                                $this.saveRowEdit(row);
                            }
                            else if(element.hasClass('ui-icon-close')) {
                                $this.cancelRowEdit(row);
                            }

                            e.preventDefault();
                        });
        }
        else if(this.cfg.editMode === 'cell') {
            var cellSelector = '> tr > td.ui-editable-column';
            var editEvent = (this.cfg.editInitEvent !== 'click') ? this.cfg.editInitEvent + '.treetable-cell click.treetable-cell' : 'click.treetable-cell';

            this.tbody.off(editEvent, cellSelector)
                .on(editEvent, cellSelector, null, function(e) {
                    if(!$(e.target).is('span.ui-treetable-toggler.ui-c')) {
                        var item = $(this);
                        var cell = item.hasClass('ui-editable-column') ? item : item.closest('.ui-editable-column');

                        if(!cell.hasClass('ui-cell-editing') && e.type === $this.cfg.editInitEvent) {
                            $this.showCellEditor($(this));
                        }
                     }
                });

            // save/cancel on mouseup to queue the event request before whatever was clicked reacts
            $(document).off('mouseup.treetable-cell-blur' + this.id)
                .on('mouseup.treetable-cell-blur' + this.id, function(e) {
                    // ignore if not editing
                    if(!$this.currentCell)
                        return;

                    var currentCell = $($this.currentCell);
                    var target = $(e.target);

                    // ignore clicks inside edited cell
                    if(currentCell.is(target) || currentCell.has(target).length)
                        return;

                    // ignore clicks inside input overlays like calendar popups etc
                    var ignoredOverlay = '.ui-input-overlay, .ui-editor-popup, #keypad-div, .ui-colorpicker-container';
                    // and menus - in case smth like menubutton is inside the table
                    ignoredOverlay += ', .ui-datepicker-buttonpane, .ui-menuitem, .ui-menuitem-link';
                    // and blockers
                    ignoredOverlay += ', .ui-blockui, .blockUI';
                    if(target.is(ignoredOverlay) || target.closest(ignoredOverlay).length)
                        return;

                    if($.datepicker._datepickerShowing || $('.p-datepicker-panel:visible').length)
                        return;

                    if($this.cfg.saveOnCellBlur)
                        $this.saveCell($this.currentCell);
                    else
                        $this.doCellEditCancelRequest($this.currentCell);
                });
        }
    },

    /**
     * Sort this tree table by the given column, either in ascending or descending order.
     * @param {JQuery} columnHeader A column to sort by, must be a TH element of the THEAD.
     * @param {PrimeFaces.widget.TreeTable.SortOrder} order Whether to sort the rows in ascending or descending order.
     * @param {boolean} multi `true` if sorting by multiple columns is enabled, or `false` otherwise.
     */
    sort: function(columnHeader, order, multi) {
        var $this = this,
        options = {
            source: this.id,
            update: this.id,
            process: this.id,
            formId: this.getParentFormId(),
            params: [
                {name: this.id + '_sorting', value: true}
            ],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            this.tbody.html(content);

                            if(!multi) {
                                columnHeader.siblings().filter('.ui-state-active').removeData('sortorder').removeClass('ui-state-active')
                                                .find('.ui-sortable-column-icon').removeClass('ui-icon-triangle-1-n ui-icon-triangle-1-s');
                                columnHeader.siblings().attr('aria-label', $this.getSortMessage($this.otherMessage));
                            }

                            columnHeader.addClass('ui-state-active').data('sortorder', order);
                            var sortIcon = columnHeader.find('.ui-sortable-column-icon');
                            if (order === $this.SORT_ORDER.DESCENDING) {
                                sortIcon.removeClass('ui-icon-triangle-1-n').addClass('ui-icon-triangle-1-s');
                                columnHeader.attr('aria-sort', 'none').attr('aria-label', $this.getSortMessage($this.descMessage) + '. Sortierung aufheben');
                                $(PrimeFaces.escapeClientId(columnHeader.attr('id') + '_clone')).attr('aria-sort', 'other')
                                    .attr('aria-label', $this.getSortMessage($this.descMessage));
                            } else if (order === $this.SORT_ORDER.ASCENDING) {
                                sortIcon.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-n');
                                columnHeader.attr('aria-sort', 'descending').attr('aria-label', $this.getSortMessage($this.ascMessage));
                                $(PrimeFaces.escapeClientId(columnHeader.attr('id') + '_clone')).attr('aria-sort', 'descending')
                                    .attr('aria-label', $this.getSortMessage($this.ascMessage));
                            } else {
                                sortIcon.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-carat-2-n-s');
                                columnHeader.removeClass('ui-state-active ').attr('aria-sort', 'ascending')
                                    .attr('aria-label', $this.getSortMessage($this.otherMessage));
                                $(PrimeFaces.escapeClientId(columnHeader.attr('id') + '_clone')).attr('aria-sort', 'ascending')
                                    .attr('aria-label', $this.getSortMessage($this.otherMessage));
                            }

                            $this.updateSortPriorityIndicators();
                        }
                    });

                return true;
            },
            oncomplete: function(xhr, status, args, data) {
                if($this.cfg.selectionMode && args.selection) {
                    $this.selections = args.selection.split(',');
                    $this.writeSelections();
                }
            }
        };

        options.params.push({name: this.id + '_sortKey', value: $this.joinSortMetaOption('col')});
        options.params.push({name: this.id + '_sortDir', value: $this.joinSortMetaOption('order')});

        if(this.hasBehavior('sort')) {
            this.callBehavior('sort', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * Expands the given row of this tree table.
     * @param {JQuery} node A node to expand, must be a TR element.
     */
    expandNode: function(node) {
        var $this = this,
        nodeKey = node.attr('data-rk'),
        options = {
            source: this.id,
            process: this.id,
            update: this.id,
            params: [
                {name: this.id + '_expand', value: nodeKey}
            ],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            if($this.cfg.expandMode === "self")
                                node.replaceWith(content);
                            else
                                node.after(content);

                            node.find('.ui-treetable-toggler:first').addClass('ui-icon-triangle-1-s').removeClass('ui-icon-triangle-1-e');
                            node.attr('aria-expanded', true);
                            $this.indeterminateNodes($this.tbody.children('tr.ui-treetable-partialselected'));

                            if(this.cfg.scrollable) {
                                this.alignScrollBody();
                            }
                        }
                    });
                return true;
            },
            oncomplete: function() {
                node.data('processing', false);
                $this.updateVerticalScroll();
                $this.setFrozenColumns(node);
                updateClasses();
                
				jQuery(jQuery(".short-waiting-behavior[data-startswaiting='true'")[0]).removeData('waitingBehaviorSet');
                jQuery(".short-waiting-behavior[data-startswaiting='true'").removeAttr('data-startswaiting');
                jQuery('.treeTableSmallAnimation')[0].classList.add('noDisplay');
                de.his.modules.Waiting.refresh();
                
                de.his.component.customtooltip.init();
                de.his.component.popup.refresh();
            }
        };
        if(this.hasBehavior('expand')) {
            this.callBehavior('expand', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },
    
    refreshBreadcrumb: function(node) {	
		var $this = this; 
		var form = $this.jq.closest('form');
	    var actionUrl = form.attr('action');
	
		$.ajax({
	        type: "POST",
	        url: actionUrl,
	        data: form.serialize(),
	        success: function(data){	
				var thisTable = $($.parseHTML(data)).find($this.jqId);
				$this.jq.find('.treetableBreadcrumb').html( thisTable.children('.treetableBreadcrumb-element') );
				
				if( $this.jq.find('tr[aria-expanded="true"]').length > 0 ) {
					$this.jq.children('table').attr('data-isTreeExpanded', true);
					
					var expandLevel = $this.jq.find('.treetableBreadcrumb').find('.treetableBreadcrumb-node:last').data('rk');
					expandLevel = String(expandLevel).split("_").length;
					$this.jq.children('table').attr('data-expandedLevel', expandLevel);
				} else {
					$this.jq.children('table').attr('data-isTreeExpanded', false);
					$this.jq.children('table').attr('data-expandedLevel', 0);
				}
			},
			complete: function(){
				if(screen.availWidth <= 768 || zoomedToTiles == true){
					updateBreadcrumbStyle(node);
					document.getElementsByClassName('ui-treetable ui-widget')[0].style.display = 'block';
				}
			}
	    });
	},

    /**
     * Collapses the given row of this tree table.
     * @param {JQuery} node A node to collapse, must be a TR element.
     */
    collapseNode: function(node) {
        var $this = this,
        nodeKey = node.attr('data-rk'),
        nextNodes = node.nextAll();

        for(var i = 0; i < nextNodes.length; i++) {
            var nextNode = nextNodes.eq(i),
            nextNodeRowKey = nextNode.attr('data-rk');

            if(nextNodeRowKey.indexOf(nodeKey) !== -1) {
               nextNode.remove();
            }
            else {
                break;
            }
        }

        node.attr('aria-expanded', false).find('.ui-treetable-toggler:first').addClass('ui-icon-triangle-1-e').removeClass('ui-icon-triangle-1-s');
        node.data('processing', false);

        if(this.cfg.scrollable) {
            this.alignScrollBody();
        }

        var options = {
            source: this.id,
            process: this.id,
            update: this.id,
            params: [
                {name: this.id + '_collapse', value: nodeKey}
            ],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            // do nothing
                        }
                    });
                return true;
            },
            oncomplete: function() {
                $this.updateVerticalScroll();
                $this.setFrozenColumns(node);
                
				jQuery(jQuery(".short-waiting-behavior[data-startswaiting='true'")[0]).removeData('waitingBehaviorSet');
				jQuery(".short-waiting-behavior[data-startswaiting='true'").removeAttr('data-startswaiting');
				jQuery('.treeTableSmallAnimation')[0].classList.add('noDisplay');
                de.his.modules.Waiting.refresh();
            }
        };

        if(this.hasBehavior('collapse')) {
            this.callBehavior('collapse', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * Callback for when a row was clicked. Selects or unselects the row, if that feature is enabled.
     * @private
     * @param {JQuery.TriggeredEvent} event The click event that occurred.
     * @param {JQuery} node The node that was clicked.
     */
    onRowClick: function(event, node) {
        if($(event.target).is('td,span:not(.ui-c)')) {
            var selected = node.hasClass('ui-state-highlight'),
            metaKey = event.metaKey||event.ctrlKey,
            shiftKey = event.shiftKey;

            if(this.isCheckboxSelection()) {
                this.toggleCheckboxNode(node);
            }
            else {
                if(selected && metaKey) {
                    this.unselectNode(node);
                }
                else {
                    if(this.isSingleSelection()||(this.isMultipleSelection() && !metaKey)) {
                        this.unselectAllNodes();
                    }

                    if(this.isMultipleSelection() && shiftKey) {
                        this.selectNodesInRange(node);
                    }
                    else {
                        this.selectNode(node);
                        this.cursorNode = node;
                    }
                }
            }

            if(this.cfg.disabledTextSelection) {
                PrimeFaces.clearSelection();
            }
        }
    },

    /**
     * Callback for when a right click was performed on a node. Selects or unselects the row, if that feature is
     * enabled.
     * @private
     * @param {JQuery.TriggeredEvent} event The click event that occurred.
     * @param {JQuery} node The node that was clicked.
     */
    onRowRightClick: function(event, node) {
        var selected = node.hasClass('ui-state-highlight'),
            nodeKey = node.attr('data-rk');

        if(this.isCheckboxSelection()) {
            if(!selected) {
                this.toggleCheckboxNode(node);
            }
        }
        else {
            if(this.isSingleSelection() || !selected ) {
                this.unselectAllNodes();
            }
            this.selectNode(node);
        }

        this.fireSelectEvent(nodeKey, 'contextMenu');

        if(this.cfg.disabledTextSelection) {
            PrimeFaces.clearSelection();
        }
    },

    /**
     * Sends a select event on server side to invoke a select listener if defined.
     * @private
     * @param {string} nodeKey The key of the node that was selected.
     * @param {string} behaviorEvent Name of the event to fire.
     */
    fireSelectEvent: function(nodeKey, behaviorEvent) {
        if(this.hasBehavior(behaviorEvent)) {
            var ext = {
                    params: [{name: this.id + '_instantSelection', value: nodeKey}
                ]
            };

            this.callBehavior(behaviorEvent, ext);
        }
    },

    /**
     * Selects the given row. The {@link TreeTableCfg.selectionMode} must not be set to `checkbox`.
     * @param {JQuery} node A row to select, must be a TR element.
     * @param {boolean} [silent] If set to `true`, does not trigger event listeners.
     */
    selectNode: function(node, silent) {
        var nodeKey = node.attr('data-rk');

        node.removeClass('ui-treetable-partialselected').addClass('ui-state-highlight').attr('aria-selected', true);
        this.addToSelection(nodeKey);
        this.writeSelections();

        if(this.isCheckboxSelection()) {
            if(this.cfg.nativeElements)
                node.find('> td:first-child > :checkbox').prop('checked', true).prop('indeterminate', false).addClass('ui-state-active');
            else
                node.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box').addClass('ui-state-active').children('span.ui-chkbox-icon').removeClass('ui-icon-blank ui-icon-minus').addClass('ui-icon-check');
        }

        if(!silent) {
            this.fireSelectNodeEvent(nodeKey);
        }
    },

    /**
     * Unselects the given row. The {@link TreeTableCfg.selectionMode} must not be set to `checkbox`.
     * @param {JQuery} node A row to unselect, must be a TR element.
     * @param {boolean} [silent] If set to `true`, does not trigger event listeners.
     */
    unselectNode: function(node, silent) {
        var nodeKey = node.attr('data-rk');

        node.removeClass('ui-state-highlight ui-treetable-partialselected').attr('aria-selected', false);
        this.removeSelection(nodeKey);
        this.writeSelections();

        if(this.isCheckboxSelection()) {
            if(this.cfg.nativeElements)
                node.find('> td:first-child > :checkbox').prop('checked', false).prop('indeterminate', false).removeClass('ui-state-active');
            else
                node.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box').removeClass('ui-state-active').children('span.ui-chkbox-icon').addClass('ui-icon-blank').removeClass('ui-icon-check ui-icon-minus');
        }

        if(!silent) {
            this.fireUnselectNodeEvent(nodeKey);
        }
    },

    /**
     * Unselects all selected rows. The {@link TreeTableCfg.selectionMode} must not be set to `checkbox`.
     */
    unselectAllNodes: function() {
        var selectedNodes = this.tbody.children('tr.ui-state-highlight');
        for(var i = 0; i < selectedNodes.length; i++) {
            this.unselectNode(selectedNodes.eq(i), true);
        }

        this.selections = [];
        this.writeSelections();
    },

    /**
     * Selects all rows between the current row and the row that was just clicked. Used for multiple selections while
     * the shift key is pressed.
     * @private
     * @param {JQuery} node  A row that was just clicked.
     */
    selectNodesInRange: function(node) {
        if(this.cursorNode) {
            this.unselectAllNodes();

            var currentNodeIndex = node.index(),
            cursorNodeIndex = this.cursorNode.index(),
            startIndex = (currentNodeIndex > cursorNodeIndex) ? cursorNodeIndex : currentNodeIndex,
            endIndex = (currentNodeIndex > cursorNodeIndex) ? (currentNodeIndex + 1) : (cursorNodeIndex + 1),
            nodes = this.tbody.children();

            for(var i = startIndex ; i < endIndex; i++) {
                this.selectNode(nodes.eq(i), true);
            }
        }
        else {
            this.selectNode(node);
        }
    },

    /**
     * Sets the `indeterminate` attribute of the given rows to `true`.
     * @private
     * @param {JQuery} nodes List of rows to process.
     */
    indeterminateNodes: function(nodes) {
        for(var i = 0; i < nodes.length; i++) {
            nodes.eq(i).find('> td:first-child > :checkbox').prop('indeterminate', true);
        }
    },

    /**
     * When the {@link TreeTableCfg.selectionMode} is set to `checkbox`: select the given row if is is currently
     * unselected, or unselects it otherwise.
     * @param {JQuery} node A row to toggle, must be a TR element.
     */
    toggleCheckboxNode: function(node) {
        var selected = node.hasClass('ui-state-highlight'),
        rowKey = node.data('rk');

        //toggle itself
        if(selected)
            this.unselectNode(node, true);
        else
            this.selectNode(node, true);

        //propagate down
        var descendants = this.getDescendants(node);
        for(var i = 0; i < descendants.length; i++) {
            var descendant = descendants[i];
            if(selected)
                this.unselectNode(descendant, true);
            else
                this.selectNode(descendant, true);
        }

        if(selected) {
           this.removeDescendantsFromSelection(node.data('rk'));
        }

        //propagate up
        var parentNode = this.getParent(node);
        if(parentNode) {
            this.propagateUp(parentNode);
        }

        this.writeSelections();

        if(selected)
            this.fireUnselectNodeEvent(rowKey);
        else
            this.fireSelectNodeEvent(rowKey);
    },

    /**
     * Finds all descendants of the given row, i.e. all children, grandchildren etc.
     * @param {JQuery} node A node for which to get the descendants.
     * @return {JQuery} The descendants of the given row. An empty jQuery instance in case the row does not have
     * descendants.
     */
    getDescendants: function(node) {
        var nodeKey = node.attr('data-rk'),
        nextNodes = node.nextAll(),
        descendants = [];

        for(var i = 0; i < nextNodes.length; i++) {
            var nextNode = nextNodes.eq(i),
            nextNodeRowKey = nextNode.attr('data-rk');

            if(nextNodeRowKey.indexOf(nodeKey) != -1) {
                descendants.push(nextNode);
            }
            else {
                break;
            }
        }

        return descendants;
    },

    /**
     * Finds the children of the given row.
     * @param {JQuery} node A row for which to find the children.
     * @return {JQuery} The children of the given row. An empty jQuery instance in case the row does not have children.
     */
    getChildren: function(node) {
        var nodeKey = node.attr('data-rk'),
        nextNodes = node.nextAll(),
        children = [];

        for(var i = 0; i < nextNodes.length; i++) {
            var nextNode = nextNodes.eq(i),
            nextNodeParentKey = nextNode.attr('data-prk');

            if(nextNodeParentKey === nodeKey) {
                children.push(nextNode);
            }
        }

        return children;
    },

    /**
     * Propagates a select or unselect event up to the parents of the given row.
     * @private
     * @param {JQuery} node A node that was selected or unselected.
     */
    propagateUp: function(node) {
        var children = this.getChildren(node),
        allSelected = true,
        partialSelected = false,
        checkbox = this.cfg.nativeElements ? node.find('> td:first-child > :checkbox') :
                            node.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box > span.ui-chkbox-icon');

        for(var i = 0; i < children.length; i++) {
            var child = children[i],
            childSelected = child.hasClass('ui-state-highlight');

            allSelected = allSelected&&childSelected;
            partialSelected = partialSelected||childSelected||child.hasClass('ui-treetable-partialselected');
        }

        if(allSelected) {
            node.removeClass('ui-treetable-partialselected');
            this.selectNode(node, true);
        }
        else if(partialSelected) {
            node.removeClass('ui-state-highlight').addClass('ui-treetable-partialselected');

            if(this.cfg.nativeElements)
                checkbox.prop('indeterminate', true).removeClass('ui-state-active');
            else
                checkbox.removeClass('ui-icon-blank ui-icon-check').addClass('ui-icon-minus').closest('.ui-chkbox-box').removeClass('ui-state-active');

            this.removeSelection(node.attr('data-rk'));
        }
        else {
            node.removeClass('ui-state-highlight ui-treetable-partialselected');

            if(this.cfg.nativeElements)
                checkbox.prop('indeterminate', false).prop('checked', false).removeClass('ui-state-active');
            else
                checkbox.addClass('ui-icon-blank').removeClass('ui-icon-check ui-icon-minus').closest('.ui-chkbox-box').removeClass('ui-state-active');

            this.removeSelection(node.attr('data-rk'));
        }

        var parent = this.getParent(node);
        if(parent) {
            this.propagateUp(parent);
        }
    },

    /**
     * Finds the parent row of the given row of this tree table.
     * @param {JQuery} node A row for which to find the parent.
     * @return {JQuery | null} The parent of the given row, or `null` if it does not have a parent.
     */
    getParent: function(node) {
        var parent = $(this.jqId + '_node_' + node.attr('data-prk'));

        return parent.length === 1 ? parent : null;
    },

    /**
     * Removes all children of the given row from the list of currently selected rows.
     * @private
     * @param {string} rowKey A row with children that were unselected.
     */
    removeDescendantsFromSelection: function(rowKey) {
        this.selections = $.grep(this.selections, function(value) {
            return value.indexOf(rowKey + '_') !== 0;
        });
    },

    /**
     * Removes the given row from the list of currenlty selected rows.
     * @param {string} nodeKey A row that was unselected.
     */
    removeSelection: function(nodeKey) {
        this.selections = $.grep(this.selections, function(value) {
            return value !== nodeKey;
        });
    },

    /**
     * Adds the given row to the list of currently selected rows.
     * @private
     * @param {string} rowKey A row that was selected.
     */
    addToSelection: function(rowKey) {
        if(!this.isSelected(rowKey)) {
            this.selections.push(rowKey);
        }
    },

    /**
     * Checks whether the given row is currently selected.
     * @param {string} nodeKey Key of a row to check.
     * @return {boolean} Whether the given row is selected.
     */
    isSelected: function(nodeKey) {
        return PrimeFaces.inArray(this.selections, nodeKey);
    },

    /**
     * Checks whether only a single row of this tree table can be selected via clicking.
     * @return {boolean} `true` if the {@link TreeTableCfg.selectionMode} is set to `single`, or `false` otherwise.
     */
    isSingleSelection: function() {
        return this.cfg.selectionMode == 'single';
    },

    /**
     * Checks whether multiple rows of this tree table may be selected.
     * @return {boolean} `true` if the {@link TreeTableCfg.selectionMode} is set to `multiple`, or `false` otherwise.
     */
    isMultipleSelection: function() {
        return this.cfg.selectionMode == 'multiple';
    },

    /**
     * Checks whether rows of this tree table are selected via checkboxes.
     * @return {boolean} `true` if the {@link TreeTableCfg.selectionMode} is set to `checkbox`, or `false` otherwise.
     */
    isCheckboxSelection: function() {
        return this.cfg.selectionMode == 'checkbox';
    },

    /**
     * Saves the currently selected rows in the hidden input field.
     * @private
     */
    writeSelections: function() {
        this.jqSelection.val(this.selections.join(','));
    },

    /**
     * Callback for when a node was selected. Invokes the appropriate behaviors.
     * @private
     * @param {string} nodeKey Key of the row that was selected.
     */
    fireSelectNodeEvent: function(nodeKey) {
        if(this.isCheckboxSelection()) {
            var $this = this,
            options = {
                source: this.id,
                process: this.id
            };

            options.params = [
                {name: this.id + '_instantSelection', value: nodeKey}
            ];

            options.oncomplete = function(xhr, status, args, data) {
                if(args.descendantRowKeys && args.descendantRowKeys !== '') {
                    var rowKeys = args.descendantRowKeys.split(',');
                    for(var i = 0; i < rowKeys.length; i++) {
                        $this.addToSelection(rowKeys[i]);
                    }
                    $this.writeSelections();
                }
            }

            if(this.hasBehavior('select')) {
                this.callBehavior('select', options);
            }
            else {
                PrimeFaces.ajax.Request.handle(options);
            }
        }
        else {
            this.fireSelectEvent(nodeKey, 'select');
        }
    },

    /**
     * Callback for when a node was unselected. Invokes the appropriate behaviors.
     * @private
     * @param {string} nodeKey Key of the row that was unselected.
     */
    fireUnselectNodeEvent: function(nodeKey) {
        if(this.hasBehavior('unselect')) {
            var ext = {
                params: [
                    {name: this.id + '_instantUnselection', value: nodeKey}
                ]
            };

            this.callBehavior('unselect', ext);
        }
    },

    /**
     * Initializes scrolling and sets up the appropriate event handlers.
     * @private
     */
    setupScrolling: function() {
        this.scrollHeader = this.jq.children('div.ui-treetable-scrollable-header');
        this.scrollBody = this.jq.children('div.ui-treetable-scrollable-body');
        this.scrollFooter = this.jq.children('div.ui-treetable-scrollable-footer');
        this.scrollStateHolder = $(this.jqId + '_scrollState');
        this.scrollHeaderBox = this.scrollHeader.children('div.ui-treetable-scrollable-header-box');
        this.scrollFooterBox = this.scrollFooter.children('div.ui-treetable-scrollable-footer-box');
        this.headerTable = this.scrollHeaderBox.children('table');
        this.bodyTable = this.scrollBody.children('table');
        this.footerTable = this.scrollFooterBox.children('table');
        this.headerCols = this.headerTable.find('> thead > tr > th');
        this.footerCols = this.footerTable.find('> tfoot > tr > td');
        this.percentageScrollHeight = this.cfg.scrollHeight && (this.cfg.scrollHeight.indexOf('%') !== -1);
        this.percentageScrollWidth = this.cfg.scrollWidth && (this.cfg.scrollWidth.indexOf('%') !== -1);
        var $this = this;

        if(this.cfg.scrollHeight) {
            if(this.cfg.scrollHeight.indexOf('%') !== -1) {
                this.adjustScrollHeight();
            }

            if(this.cfg.scrollHeight.indexOf('vh') !== -1)  {
                this.applyViewPortScrollHeight();
            }

            this.marginRight = this.getScrollbarWidth() + 'px';
            this.scrollHeaderBox.css('margin-right', this.marginRight);
            this.scrollFooterBox.css('margin-right', this.marginRight);
            this.alignScrollBody();
        }

        this.fixColumnWidths();

        if(this.cfg.scrollWidth) {
            if(this.cfg.scrollWidth.indexOf('%') !== -1) {
                this.adjustScrollWidth();
            }
            else {
                this.setScrollWidth(parseInt(this.cfg.scrollWidth));
            }
        }

        this.cloneHead();

        this.restoreScrollState();

        this.updateVerticalScroll();

        this.scrollBody.on('scroll.treeTable', function() {
            var scrollLeft = $this.scrollBody.scrollLeft();
            $this.scrollHeaderBox.css('margin-left', -scrollLeft + 'px');
            $this.scrollFooterBox.css('margin-left', -scrollLeft + 'px');

            $this.saveScrollState();
        });

         this.scrollHeader.on('scroll.treeTable', function() {
            $this.scrollHeader.scrollLeft(0);
        });

        this.scrollFooter.on('scroll.treeTable', function() {
            $this.scrollFooter.scrollLeft(0);
        });

        PrimeFaces.utils.registerResizeHandler(this, 'resize.' + this.id + '_align', $this.jq, function() {
            if ($this.percentageScrollHeight) {
                $this.adjustScrollHeight();
            }
            if ($this.percentageScrollWidth) {
                $this.adjustScrollWidth();
            }
        });
    },
    
    /**
     * Clones a table header and removes duplicate IDs.
     * @private
     * @param {JQuery} thead The head (`THEAD`) of the table to clone.
     * @param {JQuery} table The table to which the head belongs.
     * @return {JQuery} The cloned table head.
     */
    cloneTableHeader: function(thead, table) {
        var clone = thead.clone();
        clone.find('th').each(function() {
            var header = $(this);
            header.attr('id', header.attr('id') + '_clone');
            header.children().not('.ui-column-title').remove();
            header.children('.ui-column-title').children().remove();
        });
        clone.removeAttr('id').addClass('ui-treetable-scrollable-theadclone').height(0).prependTo(table);

        return clone;
    },

    /**
     * Creates and stores a cloned copy of the table head(er), and sets up some event handlers.
     * @private
     */
    cloneHead: function() {
        if (this.theadClone) {
            this.theadClone.remove();
        }
        this.theadClone = this.cloneTableHeader(this.headerTable.children('thead'), this.bodyTable);
    },

    /**
     * Applies the desired width to all columns.
     * @private
     */
     fixColumnWidths: function() {
        var $this = this;

        if(!this.columnWidthsFixed) {
            if(this.cfg.scrollable) {
                this.headerCols.each(function() {
                    var headerCol = $(this),
                    colIndex = headerCol.index(),
                    width = headerCol.width();

                    if ($this.resizableState) {
                        width = $this.findColWidthInResizableState(headerCol.attr('id')) || width;
                    }

                    headerCol.width(width);

                    if($this.footerCols.length > 0) {
                        var footerCol = $this.footerCols.eq(colIndex);
                        footerCol.width(width);
                    }
                });
            }
            else {
                var columns = this.jq.find('> table > thead > tr > th'),
                    visibleColumns = columns.filter(':visible'),
                    hiddenColumns = columns.filter(':hidden');

                this.setColumnsWidth(visibleColumns);
                /* IE fixes */
                this.setColumnsWidth(hiddenColumns);
            }

            this.columnWidthsFixed = true;
        }
    },

    /**
     * Applies the appropriated width to all given column elements.
     * @param {JQuery} columns A list of column elements.
     * @private
     */
    setColumnsWidth: function(columns) {
        if(columns.length) {
            var $this = this;

            columns.each(function() {
                var col = $(this),
                colStyle = col[0].style,
                width = colStyle.width||col.width();

                if ($this.resizableState) {
                    width = $this.findColWidthInResizableState(col.attr('id')) || width;
                }

                col.width(width);
            });
        }
    },

    /**
     * Computes and saves the resizable state of this data table, ie. which columns have got which width. May be used
     * later to restore the current column width after an AJAX update.
     * @private
     * @param {JQuery} columnHeader Element of a column header of this data table.
     * @param {JQuery} nextColumnHeader Element of the column header next to the given column header.
     * @param {JQuery} table The element for this data table.
     * @param {number} newWidth New width to be applied.
     * @param {number | null} nextColumnWidth Width of the column next to the given column header.
     */
    updateResizableState: function(columnHeader, nextColumnHeader, table, newWidth, nextColumnWidth) {
        var expandMode = (this.cfg.resizeMode === 'expand'),
        currentColumnId = columnHeader.attr('id'),
        nextColumnId = nextColumnHeader.attr('id'),
        tableId = this.id + "_tableWidthState",
        currentColumnState = currentColumnId + '_' + newWidth,
        nextColumnState = nextColumnId + '_' + nextColumnWidth,
        tableState = tableId + '_' + parseInt(table.css('width')),
        currentColumnMatch = false,
        nextColumnMatch = false,
        tableMatch = false;

        for(var i = 0; i < this.resizableState.length; i++) {
            var state = this.resizableState[i];
            if(state.indexOf(currentColumnId) === 0) {
                this.resizableState[i] = currentColumnState;
                currentColumnMatch = true;
            }
            else if(!expandMode && state.indexOf(nextColumnId) === 0) {
                this.resizableState[i] = nextColumnState;
                nextColumnMatch = true;
            }
            else if(expandMode && state.indexOf(tableId) === 0) {
                this.resizableState[i] = tableState;
                tableMatch = true;
            }
        }

        if(!currentColumnMatch) {
            this.resizableState.push(currentColumnState);
        }

        if(!expandMode && !nextColumnMatch) {
            this.resizableState.push(nextColumnState);
        }

        if(expandMode && !tableMatch) {
            this.resizableState.push(tableState);
        }

        this.resizableStateHolder.val(this.resizableState.join(','));
    },

    /**
     * Finds the saved width of the given column. The width of resizable columns may be saved to restore it after an
     * AJAX update.
     * @private
     * @param {string} id ID of a column
     * @return {string | null} The saved width of the given column in pixels. `null` when the given column does not
     * exist.
     */
    findColWidthInResizableState: function(id) {
        for (var i = 0; i < this.resizableState.length; i++) {
            var state = this.resizableState[i];
            if (state.indexOf(id) === 0) {
                return state.substring(state.lastIndexOf('_') + 1, state.length);
            }
        }

        return null;
    },

    /**
     * Adjust the view and scrolling position for the current height of the table.
     * @private
     */
    adjustScrollHeight: function() {
        var relativeHeight = this.jq.parent().innerHeight() * (parseInt(this.cfg.scrollHeight) / 100),
        tableHeaderHeight = this.jq.children('.ui-treetable-header').outerHeight(true),
        tableFooterHeight = this.jq.children('.ui-treetable-footer').outerHeight(true),
        scrollersHeight = (this.scrollHeader.outerHeight(true) + this.scrollFooter.outerHeight(true)),
        height = (relativeHeight - (scrollersHeight + tableHeaderHeight + tableFooterHeight));

        this.scrollBody.height(height);
    },

    /**
     * Sets the height of the scroll body to the value of this widget's configuration.
     * @private
     */
    applyViewPortScrollHeight: function() {
        this.scrollBody.height(this.cfg.scrollHeight);
    },

    /**
     * Adjust the view and scrolling position for the current width of the table.
     * @private
     */
    adjustScrollWidth: function() {
        var width = parseInt((this.jq.parent().innerWidth() * (parseInt(this.cfg.scrollWidth) / 100)));
        this.setScrollWidth(width);
    },

    /**
     * Applies the given outer width to an element.
     * @private
     * @param {JQuery} element An element to modify.
     * @param {number} width The new (outer) width for the element.
     */
    setOuterWidth: function(element, width) {
        var diff = element.outerWidth() - element.width();
        element.width(width - diff);
    },

    /**
     * Checks if there is any vertical overflow present currently.
     * @private
     * @return {boolean} `true` if there is overflow in the vertical y direction, or `false` otherwise.
     */
    hasVerticalOverflow: function() {
        return (this.cfg.scrollHeight && this.bodyTable.outerHeight() > this.scrollBody.outerHeight());
    },

    /**
     * Adjust the view for the given scrollbar width.
     * @private
     * @param {number} width The width of the scrollbar.
     */
    setScrollWidth: function(width) {
        var $this = this;
        this.jq.children('.ui-widget-header').each(function() {
            $this.setOuterWidth($(this), width);
        });
        this.scrollHeader.width(width);
        this.scrollBody.css('padding-right', '0px').width(width);
        this.scrollFooter.width(width);
    },

    /**
     * Aligns the scroll body element, taking into account the width of the scrollbar.
     * @private
     */
    alignScrollBody: function() {
        if(!this.cfg.scrollWidth) {
            if(this.hasVerticalOverflow())
                this.scrollBody.css('padding-right', '0px');
            else
                this.scrollBody.css('padding-right', this.getScrollbarWidth() + 'px');
        }
    },

    /**
     * Attempts to find a width for the scrollbar of the browser.
     * @private
     * @return {number} An estimate in pixels for the width of the native scrollbar.
     */
    getScrollbarWidth: function() {
        return $.browser.webkit ? '15' : PrimeFaces.calculateScrollbarWidth();
    },

    /**
     * Reads the scroll position from the hidden input element and applies it.
     * @private
     */
    restoreScrollState: function() {
        var scrollState = this.scrollStateVal||this.scrollStateHolder.val(),
        scrollValues = scrollState.split(',');

        this.scrollBody.scrollLeft(scrollValues[0]);
        this.scrollBody.scrollTop(scrollValues[1]);
        this.scrollStateVal = null;
    },

    /**
     * Stores the current scroll position in a hidden input element.
     * @private
     */
    saveScrollState: function() {
        var scrollState = this.scrollBody.scrollLeft() + ',' + this.scrollBody.scrollTop();

        this.scrollStateHolder.val(scrollState);
    },

    /**
     * Sets up the JQuery UI draggable with the appropriate event listeners for resizing columns.
     * @private
     */
    setupResizableColumns: function() {
        this.fixColumnWidths();

        if(!this.cfg.liveResize) {
            this.resizerHelper = $('<div class="ui-column-resizer-helper ui-state-highlight"></div>').appendTo(this.jq);
        }

        this.thead.find('> tr > th.ui-resizable-column:not(:last-child)').prepend('<span class="ui-column-resizer">&nbsp;</span>');
        var resizers = this.thead.find('> tr > th > span.ui-column-resizer'),
        $this = this;

        resizers.draggable({
            axis: 'x',
            start: function() {
                if($this.cfg.liveResize) {
                    $this.jq.css('cursor', 'col-resize');
                }
                else {
                    var header = $this.cfg.stickyHeader ? $this.clone : $this.thead,
                        height = $this.cfg.scrollable ? $this.scrollBody.height() : header.parent().height() - header.height() - 1;

                    if($this.cfg.stickyHeader) {
                        height = height - $this.relativeHeight;
                    }

                    $this.resizerHelper.height(height);
                    $this.resizerHelper.show();
                }
            },
            drag: function(event, ui) {
                if($this.cfg.liveResize) {
                    $this.resize(event, ui);
                }
                else {
                    $this.resizerHelper.offset({
                        left: ui.helper.offset().left + ui.helper.width() / 2,
                        top: $this.thead.offset().top + $this.thead.height()
                    });
                }
            },
            stop: function(event, ui) {
                var columnHeader = ui.helper.parent();
                ui.helper.css('left','');

                if($this.cfg.liveResize) {
                    $this.jq.css('cursor', 'default');
                } else {
                    $this.resize(event, ui);
                    $this.resizerHelper.hide();
                }

                var options = {
                    source: $this.id,
                    process: $this.id,
                    params: [
                        {name: $this.id + '_colResize', value: true},
                        {name: $this.id + '_columnId', value: columnHeader.attr('id')},
                        {name: $this.id + '_width', value: parseInt(columnHeader.width())},
                        {name: $this.id + '_height', value: parseInt(columnHeader.height())}
                    ]
                };

                if($this.hasBehavior('colResize')) {
                    $this.callBehavior('colResize', options);
                }

                if($this.cfg.stickyHeader) {
                    $this.reclone();
                }
            },
            containment: this.jq
        });
    },

    /**
     * Callback for when a row was resized. Adjust the column widths.
     * @private
     * @param {JQuery.TriggeredEvent} event Event that triggered the resize.
     * @param {JQueryUI.DraggableEventUIParams} ui Details about the resize.
     */
    resize: function(event, ui) {
        var columnHeader = ui.helper.parent(),
            nextColumnHeader = columnHeader.next(),
            table = this.thead.parent(),
            change = null,
            newWidth = null,
            nextColumnWidth = null;

        if(this.cfg.liveResize) {
            change = columnHeader.outerWidth() - (event.pageX - columnHeader.offset().left),
            newWidth = (columnHeader.width() - change),
            nextColumnWidth = (nextColumnHeader.width() + change);
        }
        else {
            change = (ui.position.left - ui.originalPosition.left),
            newWidth = (columnHeader.width() + change),
            nextColumnWidth = (nextColumnHeader.width() - change);
        }

        if(newWidth > 15 && nextColumnWidth > 15) {
            columnHeader.width(newWidth);
            nextColumnHeader.width(nextColumnWidth);
            this.updateResizableState(columnHeader, nextColumnHeader, table, newWidth, nextColumnWidth);

            var colIndex = columnHeader.index();

            if(this.cfg.scrollable) {
                this.theadClone.find(PrimeFaces.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth);
                this.theadClone.find(PrimeFaces.escapeClientId(nextColumnHeader.attr('id') + '_clone')).width(nextColumnWidth);

                if(this.footerCols.length > 0) {
                    var footerCol = this.footerCols.eq(colIndex),
                    nextFooterCol = footerCol.next();

                    footerCol.width(newWidth);
                    nextFooterCol.width(nextColumnWidth);
                }
            }
        }
    },

    /**
     * Removes the cloned table header and create a new clone.
     * @private
     */
    reclone: function() {
        this.clone.remove();
        this.clone = this.thead.clone(false);
        this.jq.children('table').append(this.clone);
    },

    /**
     * Switches a row to edit mode and displays the editors for that row.
     * @param {JQuery} row A row for which to activate the editors. Must be a TR element.
     */
    switchToRowEdit: function(row) {
        this.showRowEditors(row);

        if(this.hasBehavior('rowEditInit')) {
            var rowKey = row.data('rk');

            var ext = {
                params: [{name: this.id + '_rowEditIndex', value: rowKey}]
            };

            this.callBehavior('rowEditInit', ext);
        }
    },

    /**
     * Hides the row and display the row editors.
     * @private
     * @param {JQuery} row A row for which to show the editors.
     */
    showRowEditors: function(row) {
        row.addClass('ui-state-highlight ui-row-editing').children('td.ui-editable-column').each(function() {
            var column = $(this);

            column.find('.ui-cell-editor-output').hide();
            column.find('.ui-cell-editor-input').show();
        });
    },

    /**
     * When a row is currently being edited: Saves the edited row and hides the editors.
     * @param {JQuery} rowEditor A row to save, must be a TR element.
     */
    saveRowEdit: function(rowEditor) {
        this.doRowEditRequest(rowEditor, 'save');
    },

    /**
     * When a row is currently being edited: cancels row editing and discards the entered data.
     * @param {JQuery} rowEditor A row for which to cancel editing, must be a TR element.
     */
    cancelRowEdit: function(rowEditor) {
        this.doRowEditRequest(rowEditor, 'cancel');
    },

    /**
     * Sends an AJAX request to the server to handle a row save or cancel event.
     * @private
     * @param {JQuery} rowEditor The inline editor with data that needs to be saved or discarded.
     * @param {string} action The action to perform, either `save` or `cancel`.
     */
    doRowEditRequest: function(rowEditor, action) {
        var row = rowEditor.closest('tr'),
        rowKey = row.data('rk'),
        expanded = row.hasClass('ui-expanded-row'),
        $this = this,
        options = {
            source: this.id,
            process: this.id,
            update: this.id,
            formId: this.getParentFormId(),
            params: [{name: this.id + '_rowEditIndex', value: rowKey},
                     {name: this.id + '_rowEditAction', value: action}],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            if(expanded) {
                                this.collapseRow(row);
                            }

                            this.updateRows(row, content);
                        }
                    });

                return true;
            },
            oncomplete: function(xhr, status, args, data) {
                if(args && args.validationFailed) {
                    $this.invalidateRow(rowKey);
                }
            }
        };

        if(action === 'save') {
            this.getRowEditors(row).each(function() {
                options.params.push({name: this.id, value: this.id});
            });
        }

        if(action === 'save' && this.hasBehavior('rowEdit')) {
            this.callBehavior('rowEdit', options);
        }
        else if(action === 'cancel' && this.hasBehavior('rowEditCancel')) {
            this.callBehavior('rowEditCancel', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * Updates a row with the given HTML content.
     * @private
     * @param {JQuery} row A row to update.
     * @param {string | HTMLElement | HTMLElement[] | JQuery} content The new HTML content of the row.
     */
    updateRows: function(row, content) {
        this.tbody.children('tr').filter('[data-prk^="'+ row.data('rk') +'"]').remove();
        row.replaceWith(content);
    },

    /**
     * Callback for when validation did not succeed. Switches all editors of the given row to the error state.
     * @private
     * @param {string} rowKey the rowKey.
     */
    invalidateRow: function(rowKey) {
        this.tbody.children('tr').filter('[data-rk="'+ rowKey +'"]').addClass('ui-widget-content ui-row-editing ui-state-error');
    },

    /**
     * Finds all editors of a row.
     * @private
     * @param {JQuery} row A row for which to find all cell editors.
     * @return {JQuery} All cell editors of the given row.
     */
    getRowEditors: function(row) {
        return row.find('div.ui-cell-editor');
    },

    /**
     * Collapses the given row of this tree table after saving the contents of an inline editor.
     * @private
     * @param {JQuery} row A row to collapse.
     */
    collapseRow: function(row) {
        row.removeClass('ui-expanded-row').next('.ui-expanded-row-content').remove();
    },

    /**
     * Activates the inline editor for the given cell.
     * @param {JQuery} c The cell TD element for which to activate the inline editor.
     */
    showCellEditor: function(c) {
        var cell = null;

        if(c) {
            cell = c;

            //remove contextmenu selection highlight
            if(this.contextMenuCell) {
                this.contextMenuCell.parent().removeClass('ui-state-highlight');
            }
        }
        else {
            cell = this.contextMenuCell;
        }

        var editorInput = cell.find('> .ui-cell-editor > .ui-cell-editor-input');
        if(editorInput.length !== 0 && editorInput.children().length === 0 && this.cfg.editMode === 'cell') {
            // for lazy cellEditMode
            this.cellEditInit(cell);
        }
        else {
            this.showCurrentCell(cell);

            if(this.hasBehavior('cellEditInit')) {
                var cellInfo = this.getCellMeta(cell);
                var ext = {
                    params: [{name: this.id + '_cellInfo', value: cellInfo}]
                };
                this.callBehavior('cellEditInit', ext);
            }
        }
    },

    /**
     * Makes the inline cell visible and sets up the appropriate event listeners.
     * @private
     * @param {JQuery} cell The cell TD element for which to activate inline editing mode.
     */
    showCurrentCell: function(cell) {
        var $this = this;

        if(this.currentCell) {
            if(this.cfg.saveOnCellBlur)
                this.saveCell(this.currentCell);
            else if(!this.currentCell.is(cell))
                this.doCellEditCancelRequest(this.currentCell);
        }

        this.currentCell = cell;

        var cellEditor = cell.children('div.ui-cell-editor'),
        displayContainer = cellEditor.children('div.ui-cell-editor-output'),
        inputContainer = cellEditor.children('div.ui-cell-editor-input'),
        inputs = inputContainer.find(':input:enabled'),
        multi = inputs.length > 1;

        cell.addClass('ui-state-highlight ui-cell-editing');
        displayContainer.hide();
        inputContainer.show();
        inputs.eq(0).trigger('focus').trigger('select');

        //metadata
        if(multi) {
            var oldValues = [];
            for(var i = 0; i < inputs.length; i++) {
                oldValues.push(inputs.eq(i).val());
            }

            cell.data('multi-edit', true);
            cell.data('old-value', oldValues);
        }
        else {
            cell.data('multi-edit', false);
            cell.data('old-value', inputs.eq(0).val());
        }

        //bind events on demand
        if(!cell.data('edit-events-bound')) {
            cell.data('edit-events-bound', true);

            inputs.on('keydown.treetable-cell', function(e) {
                    var keyCode = $.ui.keyCode,
                    shiftKey = e.shiftKey,
                    key = e.which,
                    input = $(this);

                    if(key === keyCode.ENTER) {
                        $this.saveCell(cell);

                        e.preventDefault();
                    }
                    else if(key === keyCode.TAB) {
                        if(multi) {
                            var focusIndex = shiftKey ? input.index() - 1 : input.index() + 1;

                            if(focusIndex < 0 || (focusIndex === inputs.length)) {
                                $this.tabCell(cell, !shiftKey);
                            } else {
                                inputs.eq(focusIndex).trigger('focus');
                            }
                        }
                        else {
                            $this.tabCell(cell, !shiftKey);
                        }

                        e.preventDefault();
                    }
                    else if(key === keyCode.ESCAPE) {
                        $this.doCellEditCancelRequest(cell);
                        e.preventDefault();
                    }
                })
                .on('focus.treetable-cell click.treetable-cell', function(e) {
                    $this.currentCell = cell;
                });
        }
    },

    /**
     * Callback for when the tab key is pressed, switches (focuses) to the next or previous cell editor.
     * @private
     * @param {JQuery} cell The currently focused cell.
     * @param {boolean} forward `true` to move to the next cell, or `false` to move to the previous cell.
     */
    tabCell: function(cell, forward) {
        var targetCell = forward ? cell.nextAll('td.ui-editable-column:first') : cell.prevAll('td.ui-editable-column:first');
        if(targetCell.length == 0) {
            var tabRow = forward ? cell.parent().next() : cell.parent().prev();
            targetCell = forward ? tabRow.children('td.ui-editable-column:first') : tabRow.children('td.ui-editable-column:last');
        }

        this.showCellEditor(targetCell);
    },

    /**
     * Saves the current data entered into a cell's inline editor. Checks whether the data has changed and if so, sends
     * it to the server.
     * @param {JQuery} cell A cell with an inline editor to save.
     */
    saveCell: function(cell) {
        var inputs = cell.find('div.ui-cell-editor-input :input:enabled'),
        changed = false,
        $this = this;

        if(cell.data('multi-edit')) {
            var oldValues = cell.data('old-value');
            for(var i = 0; i < inputs.length; i++) {
                if(inputs.eq(i).val() != oldValues[i]) {
                    changed = true;
                    break;
                }
            }
        }
        else {
            changed = (inputs.eq(0).val() != cell.data('old-value'));
        }

        if(changed)
            $this.doCellEditRequest(cell);
        else
            $this.viewMode(cell);

        if(this.cfg.saveOnCellBlur) {
            this.currentCell = null;
        }
    },

    /**
     * Switch from edit mode to view mode, Hides the inline editor and displays the data.
     * @private
     * @param {JQuery} cell The cell with an activate inline editor to hide.
     */
    viewMode: function(cell) {
        var cellEditor = cell.children('div.ui-cell-editor'),
        editableContainer = cellEditor.children('div.ui-cell-editor-input'),
        displayContainer = cellEditor.children('div.ui-cell-editor-output');

        cell.removeClass('ui-cell-editing ui-state-error ui-state-highlight');
        displayContainer.show();
        editableContainer.hide();
        cell.removeData('old-value').removeData('multi-edit');

        if(this.cfg.cellEditMode === "lazy") {
            editableContainer.children().remove();
        }
    },

    /**
     * When the inline editor a cell is active and the user wants to save the changes: send the newly entered data to
     * the server and hide the editor.
     * @private
     * @param {JQuery} cell The cell with an inline editor to be saved.
     */
    doCellEditRequest: function(cell) {
        var cellEditor = cell.children('.ui-cell-editor'),
        cellEditorId = cellEditor.attr('id'),
        cellInfo = this.getCellMeta(cell),
        $this = this;

        var options = {
            source: this.id,
            process: this.id,
            update: this.id,
            params: [{name: this.id + '_cellInfo', value: cellInfo},
                     {name: cellEditorId, value: cellEditorId}],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            cellEditor.children('.ui-cell-editor-output').html(content);
                        }
                    });

                return true;
            },
            oncomplete: function(xhr, status, args, data) {
                if(args.validationFailed)
                    cell.addClass('ui-state-error');
                else
                    $this.viewMode(cell);
            }
        };

        if(this.hasBehavior('cellEdit')) {
            this.callBehavior('cellEdit', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * When the inline editor a cell is active and the user requests a cancel: discards the data and loads the
     * original content of the cell.
     * @private
     * @param {JQuery} cell The cell for which editing should be canceled.
     */
    doCellEditCancelRequest: function(cell) {
        var cellEditor = cell.children('.ui-cell-editor'),
        cellIndex = cell.index(),
        cellInfo = cell.closest('tr').data('rk') + ',' + cellIndex,
        $this = this;

        this.currentCell = null;

        var options = {
            source: this.id,
            process: this.id,
            update: this.id,
            params: [{name: this.id + '_cellEditCancel', value: true},
                     {name: this.id + '_cellInfo', value: cellInfo}],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            cellEditor.children('.ui-cell-editor-input').html(content);
                        }
                    });

                return true;
            },
            oncomplete: function(xhr, status, args, data) {
                $this.viewMode(cell);
                cell.data('edit-events-bound', false);
            }
        };

        if(this.hasBehavior('cellEditCancel')) {
            this.callBehavior('cellEditCancel', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * When activating the inline editor of a cell, starts an AJAX request to fetch the editor's HTML. Also invokes
     * the appropriate behaviors.
     * @private
     * @param {JQuery} cell The cell for which inline editing should be activated.
     */
    cellEditInit: function(cell) {
        var cellEditor = cell.children('.ui-cell-editor'),
        cellInfo = this.getCellMeta(cell),
        $this = this;

        var options = {
            source: this.id,
            process: this.id,
            update: this.id,
            global: false,
            params: [{name: this.id + '_cellEditInit', value: true},
                     {name: this.id + '_cellInfo', value: cellInfo}],
            onsuccess: function(responseXML, status, xhr) {
                PrimeFaces.ajax.Response.handle(responseXML, status, xhr, {
                        widget: $this,
                        handle: function(content) {
                            cellEditor.children('.ui-cell-editor-input').html(content);
                        }
                    });

                return true;
            },
            oncomplete: function(xhr, status, args, data) {
                cell.data('edit-events-bound', false);
                $this.showCurrentCell(cell);
            }
        };

        if(this.hasBehavior('cellEditInit')) {
            this.callBehavior('cellEditInit', options);
        }
        else {
            PrimeFaces.ajax.Request.handle(options);
        }
    },

    /**
     * Retrieves the meta data of the given cell.
     * @private
     * @param {JQuery} cell A cell to inspect.
     * @return {string} The meta data for the given cell.
     */
    getCellMeta: function(cell) {
        var cellIndex = cell.index(),
            cellInfo = cell.closest('tr').data('rk') + ',' + cellIndex;
        return cellInfo;
    },

    /**
     * Updates the vertical scroll position and adjusts the margin.
     * @private
     */
    updateVerticalScroll: function() {
        if(this.cfg.scrollable && this.cfg.scrollHeight) {
            if(this.bodyTable.outerHeight() < this.scrollBody.outerHeight()) {
                this.scrollHeaderBox.css('margin-right', '0px');
                this.scrollFooterBox.css('margin-right', '0px');
            }
            else {
                this.scrollHeaderBox.css('margin-right', this.marginRight);
                this.scrollFooterBox.css('margin-right', this.marginRight);
            }
        }
    },

    /**
     * Checks whether the tree table should be sorted.
     * @private
     * @param {JQuery.TriggeredEvent} event Event that occurred.
     * @param {JQuery} column Column that was clicked.
     * @return {boolean} Whether the tree table should be sorted.
     */
    shouldSort: function(event, column) {
        if(this.isEmpty()) {
            return false;
        }

        var target = $(event.target);
        if(target.closest('.ui-column-customfilter', column).length) {
            return false;
        }

        return target.is('th,span');
    },

    /**
     * Checks whether any data is currently displayed.
     * @return {boolean} Whether there is any data displayed currently.
     */
    isEmpty: function() {
        return this.tbody.children('tr.ui-treetable-empty-message').length === 1;
    },

    /**
     * Adds the given sorting to the list of sortings. Each sorting describes a column by which to sort. This data table
     * may be sorted by multiple columns.
     * @param {PrimeFaces.widget.DataTable.SortMeta} meta Sorting to add.
     * @private
     */
    addSortMeta: function(meta) {
        this.sortMeta = $.grep(this.sortMeta, function(value) {
            return value.col !== meta.col;
        });

        this.sortMeta.push(meta);
    },

    /**
     * Serializes the option from the sort meta items.
     * @private
     * @param {keyof PrimeFaces.widget.DataTable.SortMeta} option Property of the sort meta to use.
     * @return {string} All values from the current sort meta list for the given option.
     */
    joinSortMetaOption: function(option) {
        var value = '';

        for(var i = 0; i < this.sortMeta.length; i++) {
            value += this.sortMeta[i][option];

            if(i !== (this.sortMeta.length - 1)) {
                value += ',';
            }
        }

        return value;
    },

    /**
     * Creates the sort order message shown to indicate what the current sort order is.
     * @private
     * @param {string | undefined} ariaLabel Optional label text from an aria attribute.
     * @param {string} sortOrderMessage Sort order message.
     * @return {string} The sort order message to use.
     */
    getSortMessage: function(sortOrderMessage) {
        if(sortOrderMessage) {
            return sortOrderMessage;
        }
        else{
            return 'Unsortiert';
        }
    },

    /**
     * In multi-sort mode this will add number indicators to let the user know the current 
     * sort order. If only one column is sorted then no indicator is displayed and will
     * only be displayed once more than one column is sorted.
     * @private
     */
    updateSortPriorityIndicators: function() {
        var $this = this;

        // remove all indicator numbers first
        $this.sortableColumns.find('.ui-sortable-column-badge').text('').addClass('ui-helper-hidden');

        // add 1,2,3 etc to columns if more than 1 column is sorted
        var sortMeta =  $this.sortMeta;
        if (sortMeta && sortMeta.length > 1) {
            $this.sortableColumns.each(function() {
                var id = $(this).attr("id");
                for (var i = 0; i < sortMeta.length; i++) {
                    if (sortMeta[i].col == id) {
                        $(this).find('.ui-sortable-column-badge').text(i + 1).removeClass('ui-helper-hidden');
                    }
                }
            });
        }
    },
	
    resize: function() {
        var resizeId = 0;
        jQuery(window).off('resize').on('resize', function() {
            clearTimeout(resizeId);
            resizeId = setTimeout(doneResizing, 500);

        });
        
        function doneResizing() {
            //var winWidth = jQuery(window).width(); 
            var winWidth = screen.availWidth;
            if( winWidth <= 768 ) {    
                //jQuery('.treeTableActions').find('button[id*="treeTableCollapseAll"]').trigger('click');
            }
        } 
    },
    
    collapsAllNodes: function() {
		updateClasses();
		var trElements = jQuery('.ui-treetable table tr.ui-widget-content[data-rk]');
		var firstTrs = [];
		for(let tr of trElements){
			if($(tr)[0].dataset.level == '1'){
				firstTrs.push(tr);
			}
		}
		for(let toggler of trElements){
			var togglerrr = $(toggler).find('.ui-treetable-toggler.tileToggler'),
            node = togglerrr.closest('tr');
			this.collapsingORexpanding(node, false);
		}
		var tables = jQuery('.ui-treetable table');
		for(let table of tables){
			$(table).attr('data-isTreeExpanded', false);
		}
		hiddenChange('.breadcrumb-container', 'true');
	},
	
	collapsingORexpanding: function(node, option){
		if(this.getChildren(node).length > 0) {
	        for(let child of this.getChildren(node)) {
	            this.collapsingORexpanding(child, option);
	        }
	        if(option == true){
				this.expandNode(node);
			}
			else{
				this.collapseNode(node);
			}
	    }
	},
	
	closeDroplistMenu: function(){
		var droplists = jQuery('ul.droplist-menu');
		for(let i = 0; i < droplists.length; i++){
			droplists[i].classList.add('noDisplay');
		}
	},
	
    actionButtons: function() { 
        /*jQuery('.treeTableActions').find('button').off('click').on('click', function(){
            var $this = jQuery(this);
            var $tableDiv = $this.closest('.ui-treetable');
            
                if( $this.attr('id').contains('treeTableCollapseAll')  ) {
                    $tableDiv.children('table').attr('data-isTreeExpanded', false);
                } else if($this.attr('id').contains('treeTableExpandAll') ) {
                    $tableDiv.children('table').attr('data-isTreeExpanded', true);
                }
      
        });
        */ 
    } 
});
    }
    
    function updateClasses(){
		if(screen.availWidth <= 768 || zoomedToTiles == true){
			jQuery('button.ui-treetable-toggler').removeClass('treeToggler').addClass('tileToggler');
		}
		else{
			jQuery('button.ui-treetable-toggler').removeClass('tileToggler').addClass('treeToggler');
			var tiles = jQuery('.ui-treetable table[data-istreeexpanded="true"] tr.ui-widget-content[data-isParentExpanded="true"]');
            for(let tile of tiles){
				tile.classList.remove('noDisplay');
			}
		}
	}
	
	function updateBreadcrumbStyle(node){
			var breadcrumbs = node.closest('div').find('.treetableBreadcrumb-node');
			if(breadcrumbs.length > 3){
				var droplistBreadcrumbs = breadcrumbs.slice(0,-3);
				var lastThreeBreadcrumbs = breadcrumbs.slice(-3);
				var alreadyIn = false;
				for(let droplistBreadcrumb of droplistBreadcrumbs){
					if(droplistBreadcrumb.childNodes.length > 1){
						alreadyIn = true
					}
				}
				var language = de.his.common.LanguageHelper.currentLanguage();
				if(droplistBreadcrumbs.length >= 1 && alreadyIn == false){
					if (language == "de") {
						lastThreeBreadcrumbs[0].insertAdjacentHTML('beforebegin', '<li class="previous treetableBreadcrumb-element treetableBreadcrumb-node  ui-node-level-1"><button type="button" aria-label="Vorausgehende Navigationspunkte">...</button></li>');
					}
					else {
						lastThreeBreadcrumbs[0].insertAdjacentHTML('beforebegin', '<li class="previous treetableBreadcrumb-element treetableBreadcrumb-node  ui-node-level-1"><button type="button" aria-label="Previous navigation points">...</button></li>');
					}
					var additionalPointsBreadcrumb = node.closest('div').find('.previous.treetableBreadcrumb-node');
					additionalPointsBreadcrumb[0].insertAdjacentHTML('beforeend', '<ul class="droplist-menu noDisplay"></ul>');
					var droplist = node.closest('div').find('ul.droplist-menu');
					for(let i = 0; i < droplistBreadcrumbs.length; i++){
						droplist[0].appendChild(droplistBreadcrumbs[i]);
					}
					additionalPointsBreadcrumb.on("click", function() {
						if(droplist[0].classList.contains('noDisplay')){
							droplist[0].classList.remove('noDisplay');
						}
						else{
							droplist[0].classList.add('noDisplay');
						}
					});
				}
			}
	}
	
	function hiddenChange(element, isHidden) {
		if(isHidden === 'true'){
			jQuery(element).addClass('noDisplay');
		}
		else{
			jQuery(element).removeClass('noDisplay');
		}
		jQuery(element)[0].ariaHidden = isHidden;
	}
	
	function checkIfTile(){
		// if togglerbutton style right = 0px, the tile view is visible
		let elementsRight = jQuery('.ui-treetable-data > .ui-widget-content .ui-treetable-toggler').css('right');
		if(elementsRight == '0px'){
			return true;
		}
		return false;
	}
};
'use strict';

use_package("de.his.component");

de.his.component.PrimePaginator = new function() {
	de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
	this.moduleName = "de.his.component.PrimePaginator";
		
    this.init = function() {
    	if (window.PrimeFaces) {
			PrimeFaces.widget.Paginator();
    	}
    }
	
    this.refresh = function() {
        this.init();
    };
    	
    if (window.PrimeFaces) {
    	/// START PrimeFaces-Komponente ///    	
		PrimeFaces.widget.Paginator = PrimeFaces.widget.DeferredWidget.extend({
			
			/**
		     * @override
		     * @inheritdoc
		     * @param {PrimeFaces.PartialWidgetCfg<PaginatorCfg>} cfg
		     */
			init: function (a) {
            this._super(a);
            this.pagesContainer = this.jq;
            this.pageLinks = this.pagesContainer.find(".ui-paginator-page");
            this.rppSelect = this.jq.children(".ui-paginator-rpp-options");
            this.jtpSelect = this.jq.children(".ui-paginator-jtp-select");
            this.jtpInput = this.jq.children(".ui-paginator-jtp-input");
            this.firstLink = this.jq.find("a.iconfont-resultset_first");
            this.prevLink = this.jq.find("a.iconfont-resultset_previous");
            this.nextLink = this.jq.find("a.iconfont-resultset_next");
            this.endLink = this.jq.find("a.iconfont-resultset_last");
            this.currentReport = this.jq.children(".ui-paginator-current");
            this.cfg.rows = this.cfg.rows == 0 ? this.cfg.rowCount : this.cfg.rows;
            this.cfg.prevRows = this.cfg.rows;
            this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows) || 1;
            this.cfg.pageLinks = this.cfg.pageLinks || 10;
            this.cfg.currentPageTemplate = this.cfg.currentPageTemplate || "({currentPage} of {totalPages})";
            //this.cfg.ariaPageLabel = PrimeFaces.getAriaLabel("paginator.PAGE");
            this.bindEvents()
        },
        bindEvents: function () {
            var a = this;
            this.jq.find("a").on("keydown.paginator", function (d) {
                var b = d.which,
                c = $.ui.keyCode;
                if ((b === c.ENTER)) {
                    $(this).trigger("click");
                    d.preventDefault()
                }
            });
            this.bindPageLinkEvents();
            this.firstLink.on("click", function (b) {
                PrimeFaces.clearSelection();
                if (!$(this).hasClass("disabled")) {
                    a.setPage(0)
                }
                b.preventDefault()
            });
            this.prevLink.on("click", function (b) {
                PrimeFaces.clearSelection();
                if (!$(this).hasClass("disabled")) {
                    a.setPage(a.cfg.page - 1)
                }
                b.preventDefault()
            });
            this.nextLink.on("click", function (b) {
                PrimeFaces.clearSelection();
                if (!$(this).hasClass("disabled")) {
                    a.setPage(a.cfg.page + 1)
                }
                b.preventDefault()
            });
            this.endLink.on("click", function (b) {
                PrimeFaces.clearSelection();
                if (!$(this).hasClass("disabled")) {
                    a.setPage(a.cfg.pageCount - 1)
                }
                b.preventDefault()
            })
        },
        bindPageLinkEvents: function () {
            var a = this,
            b = this.pagesContainer.find(".ui-paginator-page");
            b.on("click.paginator", function (f) {
                var d = $(this),
                c = parseInt(d.text());
                a.setPage(c-1)
                f.preventDefault()
            }).on("keydown.paginator", function (f) {
                var c = f.which,
                d = $.ui.keyCode;
                if ((c === d.ENTER)) {
                    $(this).trigger("click");
                    f.preventDefault()
                }
            })
        },
        bindSwipeEvents: function (a, b) {
            if (!PrimeFaces.env.isTouchable(b)) {
                return
            }
            var c = this;
            a.swipe({
                swipeLeft: function (d) {
                    c.prev()
                },
                swipeRight: function (d) {
                    c.next()
                },
                excludedElements: PrimeFaces.utils.excludedSwipeElements()
            })
        },
        unbindEvents: function () {
            var a = this.jq.children("a.ui-state-default");
            if (a.length > 0) {
                a.off()
            }
            var b = this.pagesContainer.find(".ui-paginator-page");
            if (b.length > 0) {
                b.off()
            }
        },
        updateUI: function () {
            if (this.cfg.page === 0) {
                this.disableElement(this.firstLink);
                this.disableElement(this.prevLink)
            } else {
                this.enableElement(this.firstLink);
                this.enableElement(this.prevLink)
            }
            if (this.cfg.page === (this.cfg.pageCount - 1)) {
                this.disableElement(this.nextLink);
                this.disableElement(this.endLink)
            } else {
                this.enableElement(this.nextLink);
                this.enableElement(this.endLink)
            }
            var a = (this.cfg.rowCount === 0) ? 0 : (this.cfg.page * this.cfg.rows) + 1,
            c = (this.cfg.page * this.cfg.rows) + this.cfg.rows;
            if (c > this.cfg.rowCount) {
                c = this.cfg.rowCount
            }
            /*var e = this.cfg.currentPageTemplate.replace("{currentPage}", this.cfg.page + 1)?.replace("{totalPages}", this.cfg.pageCount)?.replace("{totalRecords}", this.cfg.rowCount)?.replace("{startRecord}", a)?.replace("{endRecord}", c);
            this.currentReport.text(e);
            if (this.cfg.prevRows !== this.cfg.rows) {
                this.rppSelect.filter(":not(.ui-state-focus)").children("option").filter('option[value="' + $.escapeSelector(this.cfg.rows) + '"]').prop("selected", true);
                this.cfg.prevRows = this.cfg.rows
            }
            if (this.jtpSelect.length > 0) {
                if (this.jtpSelect[0].options.length != this.cfg.pageCount) {
                    var d = "";
                    for (var b = 0; b < this.cfg.pageCount; b++) {
                        d += '<option value="' + b + '">' + (b + 1) + "</option>"
                    }
                    this.jtpSelect[0].innerHTML = d
                }
                this.jtpSelect.children("option[value=" + (this.cfg.page) + "]").prop("selected", "selected")
            }
            if (this.jtpInput.length > 0) {
                this.jtpInput.val(this.cfg.page + 1)
            }*/
            this.updatePageLinks(this.cfg.page);
        },
        updatePageLinks: function (page) {
            var activePage = page + 1;
            var language = de.his.common.LanguageHelper.currentLanguage();
            for(let i = 0; i < this.pageLinks.length; i++){
				if(this.pageLinks[i].innerText == activePage){
					this.pageLinks[i].closest("li").classList.add("activePage");
					if (language == "de") {
						this.pageLinks[i].setAttribute("title", "Aktive Seite: " + activePage);
						this.pageLinks[i].setAttribute("aria-label", "Aktive Seite: " + activePage);
					}
					else{
						this.pageLinks[i].setAttribute("title", "Active Page: " + activePage);
						this.pageLinks[i].setAttribute("aria-label", "Active Page: " + activePage);
					}
				}
				else{
					this.pageLinks[i].closest("li").classList.remove("activePage");
					this.pageLinks[i].removeAttribute("title");
					this.pageLinks[i].removeAttribute("aria-label");
				}
			}
            this.bindPageLinkEvents()
        },
        setPage: function (c) {
            if (c >= 0 && c <= this.cfg.pageCount && this.cfg.page != c) {
                var b = {
                    first: this.cfg.rows * c,
                    rows: this.cfg.rows,
                    page: c
                };
                this.cfg.paginate.call(this, b)
            }
        },
        setRowsPerPage: function (b) {
            if (b === "*") {
                this.cfg.rows = this.cfg.rowCount;
                this.cfg.pageCount = 1;
                this.cfg.page = 0;
                var c = {
                    first: 0,
                    rows: b,
                    page: this.cfg.page
                };
                this.cfg.paginate.call(this, c)
            } else {
                var d = this.cfg.rows * this.cfg.page;
                this.cfg.rows = parseInt(b);
                var a = parseInt(d / this.cfg.rows);
                this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows);
                this.cfg.page = -1;
                this.setPage(a)
            }
        },
        setTotalRecords: function (a) {
            this.cfg.rowCount = a;
            this.cfg.pageCount = Math.ceil(a / this.cfg.rows) || 1;
            this.cfg.page = 0;
            this.updateUI()
        },
        updateTotalRecords: function (a) {
            this.cfg.rowCount = a;
            this.cfg.pageCount = Math.ceil(a / this.cfg.rows) || 1;
            this.updateUI()
        },
        getCurrentPage: function () {
            return this.cfg.page
        },
        getFirst: function () {
            return (this.cfg.rows * this.cfg.page)
        },
        getRows: function () {
            return this.cfg.rows
        },
        getContainerHeight: function (c) {
            var a = 0;
            for (var b = 0; b < this.jq.length; b++) {
                a += this.jq.eq(b).outerHeight(c)
            }
            return a
        },
        disableElement: function (a) {
            a.removeClass("ui-state-hover ui-state-focus ui-state-active").attr("tabindex", -1).addClass("disabled").attr('disabled', true);
            a.removeClass("ui-state-hover ui-state-focus ui-state-active").attr("tabindex", -1).addClass("disabled").attr('disabled', true)
        },
        enableElement: function (a) {
            a.removeClass("disabled").attr("tabindex", 0).removeAttr("disabled", true)
        },
        next: function () {
            this.setPage(this.cfg.page + 1)
        },
        prev: function () {
            this.setPage(this.cfg.page - 1)
        }
    });
}}/**
* @author masala@his.de, dziegielewski@his.de
* @usage
*  <{containerElement} 
*      class="quickmenu-container"    //must be declared
*      data-menu-taketext     //value optional, boolean, defaults to false, if true will insert text into the quickmenu items (if buttons) taken from the data-title or alt attribute
*      data-quickmenu-items   //optional, defaults to 2, specify if you wish to see more/less actions by default
*      data-quickmenu-selector //optional, defaults to "> *", value must be a valid css selector, use this to specify exactly which items within this container are quickmenu-items
*      data-quickmenu-alwaysMenu //optional, defaults to "false", specify if the menu will always be created, even if there would be only 1 element in the menu
*  >
*   <button />
*   <li></li>
*   <a></a>
*  </{containerElement}>
**/

use_package( "de.his.component" );

//IIF: $ === jQuery
( function( $ ) {
    de.his.component.Quickmenu = new function() {
        de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
        this.moduleName = "de.his.component.Quickmenu";

        var quickmenu = {

            /**
             * change with attribute "data-quickmenu-items"
             * @private
             * @property _defaultItemNumer
             * @type {Integer}
             * @default 2
             */
            _defaultItemNumer: 2,
            /**
             * change with attribute "data-quickmenu-selector"
             * @private
             * @property _defaultItemSelector
             * @type {String}
             * @default "> *"
             */
            _defaultItemSelector: "> *",
            /**
             * change with attribute "data-quickmenu-alwaysMenu"
             * @private
             * @property _defaultAlwaysMenu
             * @type {boolean}
             * @default "false"
             */
            _defaultAlwaysMenu: false,
            /**
             * @private
             * @method _dropdownButton
             * @return {jQuery Template Element}
             */
            _dropdownButton: function(menu) {
                //get local
            	//title wählen
            	var language = de.his.common.LanguageHelper.currentLanguage();
            	if (language == "de") {
            		title = "Menü aufklappen";
            	} else {
            		title = "Open menu";
            	}
            	// Shortcut für das Aufklappen des Quickmenus soll auch im Title angezeigt werden.
            	var hotkey = jQuery( "html" ).data( "hotkey" );
            	if (hotkey && !menu.closest('table').length) {
            		title = title + "[" + hotkey.toUpperCase() + "+W]";
            	}
            	
                return $( "<div aria-haspopup='true' tabindex='0' role='button' title='" + title + "' aria-label='" + title + "' class='quickmenu-action quickmenu-action-show iconfont-resultset_down' data-shortcut='w' aria-expanded='false'>" );
            },
            /**
             * @private
             * @method _text
             * @return {jQuery Template Element}
             */
            _text: function( $item ) {
                var text = $item.data( "title" ) || $item.attr( "title" ) || "";
                return $( "<span class='quickmenu-item-text' aria-hidden='true'>" ).text( text );
            },

            /**
             * @method init
             */
            init: function() {
                var me = this, $menus = $( ".quickmenu-container" ) 
                if ( $menus.length ) {
                    me.initMenus( $menus );
                }
            },

            /**
             * @method initMenus
             * @param $menus {jQuery Object}
             **/
            initMenus: function( $menus ) {
                var me = this, $menu;
                for ( var i = 0, l = $menus.length; i < l; i++ ) {
                	$menu = $( $menus[ i ] );
                	$menuAlreadyExist = $menu.find(".quickmenu-identifier");// Search for this css class to check if the quickmenu was already created
                	if(!$menuAlreadyExist.length){
						// Die Pipe '.spacerHyphenTable' vor dem Delete Icon sorgt dafür, dass die Zählung der Menü Items durcheinander geht
						// und muss gesondert behandelt werden. S. Ticket 326840
						if ($menu.children().length > 3 && $menu.find('.spacerHyphenTable').length) {
							$menu.find('.spacerHyphenTable').remove();	
						}
                		me.initQuickMenu( $menu );
                	}
                }
                $menus.removeClass("noDisplay");
            },

            /**
             * @initShowBtnAction
             * @param $menu {jQuery Object} container of $showBtn where ".quickmenu-container" is defined
             */
            initShowBtnAction: function( $menu ) {
                var me = this;

//                $menu.append( $showBtn );
                $menu.find("span").first().css("cursor", "pointer");
                $quickItems = $( ".quickmenu-identifier", $menu );
    			var buttons = $quickItems.children("button, a, input, span");
    			if (buttons.length) {
    				/* Wenn das letzte Elemente im Quickmenu via Tab erreicht wird und erneut Tab gedrückt wird, 
    				 * so wird ein blur Event ausgelöst. Dadurch wird das Quickmenu geschlossen und automatisch das nächste
    				 * fokussierbare Element erhält den Fokus. 
    				 * Problematisch ist hierbei, dass wenn bei fokussiertem letzten Element ein anderes Element im Quickmenu via
    				 * Maus angeklickt wird, das Menü geschlossen wird und die Aktion auf das Element nicht registriert wird. (sehr selten)
    				*/
//    				buttons.last().on("blur", function (event) {
//    					me.closeMenu($quickItems);
//    				});
    				
    				/*
    				 * Blur Variante dekativiert: wenn letztes Element im Menü ein overlay Button war. 
    				 * Wurde das Overlay geladen aber nicht angezeigt, weil dieses sich im Menü befindet 
    				 * und dieses durch das blur geschlossen wurde.
    				 */
    				buttons.last().on("keydown", function (event) {
    					if (event.keyCode == 9) {
    						if (!event.shiftKey) {
    							me.closeMenu($quickItems);
    						}
        				}
    				});
    				
    				// Beim ersten Element soll nach Shift-Tab das Menü auch geschlossen werden.
    				buttons.first().on("keydown", function (event) {
    					if (event.keyCode == 9 && event.shiftKey) {
							me.closeMenu($quickItems);
        				}
    				});
    			}

    			//ESC key will close menu.
    			$quickItems.on("keydown", function(event) {
    				if (event.keyCode == 27) {
    					me.closeMenu($quickItems);
    				}
    			});
				
    			buttons.on("keydown", function(event) {
					//Arrow DOWN
    				if (event.keyCode == 40) {
						event.preventDefault();
						if( $(this).next().hasClass('tabable-link') ) {
							$(this).next().children().focus();
						}
						else {
							$(this).next().focus();	
						}
						if( !$(this).next().length ) {
							me.closeMenu($quickItems);
						}
    				}
					//Arrow UP
					if (event.keyCode == 38) {
						event.preventDefault();
						if( $(this).prev().hasClass('tabable-link') ) {
							$(this).prev().children().focus();
						}
						else {
							$(this).prev().focus();	
						}
						if( !$(this).prev().length ) {
							me.closeMenu($quickItems);
						}
    				}
    			});
                $menu.find('.quickmenu-action, .quickmenuSpanUnderlined').on( "click keydown", function( event ) {	
                    if (event.type == "keydown" || event.type == "click") {
                    	//open menu with click, enter or space
                    	if (event.type == "click" || event.keyCode == 13 || event.keyCode == 32) {
                    		$quickItems = $( ".quickmenu-identifier", $menu ), $showBtn = $menu.find(".quickmenu-action");
                    		offset = $showBtn.position();
                    		$menu.closest("tr").addClass("rowHighlightedRose");
                    
                    		if ( $quickItems.length && $quickItems.hasClass("noDisplay")) {
                    			event.preventDefault();
                    			event.stopPropagation();
                    			me.closeAnyOpenMenus();
                    			var language = de.his.common.LanguageHelper.currentLanguage();
                            	if (language == "de") {
                            		$menu.find(".quickmenu-action").attr("title", "Menü schließen");
                            	} else {
                            		$menu.find(".quickmenu-action").attr("title", "Close menu");
                            	}
                    			$menu.find(".quickmenu-action").removeClass("iconfont-resultset_down");
                    			$menu.find(".quickmenu-action").addClass("iconfont-resultset_up");
                    			$menu.find(".quickmenu-action").attr("aria-expanded", "true"); 
                    			$quickItems.removeClass("noDisplay");
                    			$quickItems.addClass("quickmenu-show quickmenu-container-items");
                    			
                    			// Prüfe ob das Quickmenu am rechten Bildschirm Rand ist
                    			var minWidth = parseInt(jQuery('.quickmenu-container-items.quickmenu-show').css("min-width"));
                    			var quickmenuLeftPos;
                    			// Wenn es am Rand ist, positioniere es weiter links
                    			if ($showBtn.offset().left + minWidth > window.innerWidth) {
                    				quickmenuLeftPos = $showBtn.offset().left - minWidth;
                    			} else {
                    				quickmenuLeftPos = $showBtn.offset().left;
                    			}
                    			
                    			$menu.find(".quickmenu-identifier").css( {
                    				left: quickmenuLeftPos
                    			} );
                    			
                    			// Focus first Element in Quickmenu
                    			var Elements = $quickItems.children();
                    			if(Elements.length){
                    				Elements[0].focus();
                    			}
                    			
                    			
                    			// Add blurrEvent to quickItems
                    			me.addBlurEvent( $quickItems );
                                
                    		} else {
                    			me.closeMenu($quickItems);
                    		}
                    	}
                    }
                } );
				setTimeout(function(){
					$menu.find('.quickmenu-action').trigger('click');
				});		
            },

            /**
             * @method closeAnyOpenMenus
             */
            closeAnyOpenMenus: function() {
                var me = this, $menu = $( ".quickmenu-show" );
                if ( $menu.length ) {
                    me.closeMenu( $menu );
                }
            },

            /**
             * @method addBlurEvent
             * @param $menu {jQuery Object}
             **/
            addBlurEvent: function( $menu ) {
                var me = this, 
	                f = function( event ) {
	                    var $target = $( event.target );
	                    if ( !$menu.has( $target ).length ) {
	                        me.closeMenu( $menu );
	                        $( document ).off( "click touchstart" );
	                    }
	                };
	            $( document ).off( "click touchstart" );
                $( document ).on( "click touchstart", f );
                $menu.data( "quickmenu-global-click-function", f );
            },

            /**
             * @method closeMenu
             * @param $menu{jQuery Object}
             **/
            closeMenu: function( $menu ) {
                var me = this;
                var language = de.his.common.LanguageHelper.currentLanguage();
            	if (language == "de") {
            		$menu.prev(".quickmenu-action").attr("title", "Menü aufklappen");
            	} else {
            		$menu.prev(".quickmenu-action").attr("title", "Open menu");
            	}
                $menu.prev(".quickmenu-action").removeClass("iconfont-resultset_up");
                $menu.prev(".quickmenu-action").addClass("iconfont-resultset_down");
                $menu.prev(".quickmenu-action").attr("aria-expanded", "false");
                $menu.removeClass( "quickmenu-show quickmenu-container-items" );
                $menu.addClass("noDisplay");
                $menu.closest("tr").removeClass("rowHighlightedRose");
            },

            /**
            * @method initQuickMenu
            * @param $menu {jQuery Object}
            */
            initQuickMenu: function( $menu ) {
            	var me = this;
			
				//Quickmenu erst bei klick Initialisieren
				items = $menu.attr( "data-quickmenu-items" ) ? $menu.data( "quickmenu-items" ) : me._defaultItemNumer;
				if( $menu.children().not('.ui-tooltip').not('.spacerHyphenTable').length > items && !$menu.find('.quickmenu-action').length > 0 ) {
    	    		$showBtn = me._dropdownButton($menu);
    	    		$showBtn.appendTo( $menu );

					$firstElement = $menu.children(":first");
                    if($firstElement.is("span:not(.tabable-link)")) {
                    	$firstElement.addClass("quickmenuSpanUnderlined");
                    }
					$menu.find('.quickmenu-action, .quickmenuSpanUnderlined').on('click keydown', function(event){
						if (event.type == "click" || event.keyCode == 13 || event.keyCode == 32) {
							if (event.keyCode == 32) { event.preventDefault();}
							if( !$menu.find('.quickmenu-identifier').length > 0 ) {
								if(me.initItems( $menu ) ){
									jQuery(this).off('click keydown');
									jQuery(this).parent().find('.quickmenuSpanUnderlined').off('click keydown');
			                		me.initShowBtnAction( $menu );
			                	}
							}
						}
					});
					$menu.css("display", "");
				}
				
            },

            /**
             * @method initItems
             * @param $menu {jQuery Object}
             * @return {boolean} true if items exist, false if not
             **/
            initItems: function( $menu ) {
                var me = this, 
                    takeText = ( function( $m ) {
                        var d = $m.data( "menu-taketext" );
                        return d === true || d === "";
                    } )( $menu ),
                    $quickItems = $menu.attr( "data-quickmenu-selector" ) ? $( $menu.data( "quickmenu-selector" ), $menu ) : $( me._defaultItemSelector, $menu ),
                    items = $menu.attr( "data-quickmenu-items" ) ? $menu.data( "quickmenu-items" ) : me._defaultItemNumer, $item, $box = $( "<div role='application' class='noDisplay quickmenu-identifier'>" );
                    for ( var i = 0, l = $quickItems.length; i < l; i++ ) {
                        $item = $( $quickItems[ i ] );
                        /*
                         * excludeFromQuickmenu - ermöglicht es Elemente bei der Erstellung des Menus zu ignorieren.  
                         */
                        if($item.hasClass( "spacerImageTable" ) || $item.hasClass( "spacerHyphenTable" ) || $item.hasClass( "excludeFromQuickmenu" )){
                        	$item.remove();
                        	continue;
                        }
                        /*
                         * Abfrage für overlayShowButton, damit die generierten divs zu einem Overlay-Button nicht
                         * im Quickmenu angezeigt werden
                         */
						/* Lösung per CSS eingebunden #258647						
                        if($item.attr("id")){
                        	if($item.attr("id").search("overlayShowButton") != -1){
                        		// hole element des showOverlayButtons und suche das nächstgelegene Div.
                        		var nextDivItem = document.getElementById($item.attr("id")).next('div');
                        		nextDivItem.addClassName("quickmenuOverlayDiv");
                        	}
                        }
						*/
                    }
                    $quickItems = $menu.attr( "data-quickmenu-selector" ) ? $( $menu.data( "quickmenu-selector" ), $menu ) : $( me._defaultItemSelector, $menu );
                    itemSize = $quickItems.length;
                    for(var i = 0; i < itemSize; i++){
                    	$item = $( $quickItems[ i ] );
                    	if($item.attr('type') == "hidden" || $item.hasClass("noDisplay") || $item.hasClass("refreshButtonNoDisplay")){
                    		$quickItems.splice(i,1); 
                    		i--;
                    	}
                    }
                    var showAlwaysMenuString = $menu.attr( "data-quickmenu-alwaysMenu" ) ? $menu.attr( "data-quickmenu-alwaysMenu" ) : me._defaultAlwaysMenu;
                    var showAlwaysMenu = (showAlwaysMenuString == 'true');
                    // Check if more than 1 quickitem exist for bewerbung sichten to show status ( first element of quickItems ) but not the quickmenu
                    if($quickItems.length > 1)
                	{
                    	if($quickItems.length > (items+1) || showAlwaysMenu ){
    	                    for ( var i = items, l = $quickItems.length; i < l; i++ ) {
    	                    	$item = $( $quickItems[ i ] );
    	                    	if ( takeText ) {
                                    if ( $item.is( "button" ) ) {
                                        $item.append( me._text( $item ) );
                                    } else if ($item.is( "a" ) ) {
                                        $item.append( me._text( $item.find('img')));
                                    } else if ($item.is("input") && $item.attr("type") == "checkbox") {
                                    	if(!$item.hasClass("noDisplay") && !$item.attr('type') !== "hidden"){
                                    		$item.css("display", "inline-block")
                                    	}
                                    } else if ($item.is("label")) {
                                    	$item.css("display", "inline-block")
                                    }else if($item.find("button").length > 0 ){ 
                                    	// Sofern das item weder link noch button ist ( bspw span ) und taketext aktiviert ist, wird einfach der title des nächst sichtbaren Buttons oder Links genommen
                                    	var $foundButton = $item.find("button");
                                    	if(!$foundButton.hasClass("noDisplay") && !$foundButton.attr('type') !== "hidden"){
                                    		$foundButton.append( me._text( $foundButton ) ); 
                                    	}else if($item.find("a").length > 0){
                                        	var $foundLink = $item.find("a");
                                        	if(!$foundLink.hasClass("noDisplay") && !$foundLink.attr('type') !== "hidden")
                                        		$foundLink.append( "<span>" + $foundLink.attr( "title" ) + "</span>" );
                                        }
                                    }else if($item.find("a").length > 0){
                                    	var $foundLink = $item.find("a");
                                    	if(!$foundLink.hasClass("noDisplay") && !$foundLink.attr('type') !== "hidden"){
                                    		var text = $foundLink.data( "title" ) || $foundLink.attr( "title" ) || "";
                                    		$foundLink.append( me._text( text ) );
                                    	}
                                    }
    	                    	}
    	                    	if ( !$item.hasClass( "quickmenu-action" ) ) {
    	                    		$item.appendTo( $box );
    	                    	}
    	                    	/* Entfernt, siehe https://hiszilla.his.de/hiszilla/show_bug.cgi?id=283784
                                if ($item.is( "button") && $item.hasClass("submit") && !$item.hasClass("submit_linkLook")) {
    	                    		$item.addClass("submit_linkLook");
    	                    	}*/
    	                    }
    	                    if ( items < $quickItems.length || showAlwaysMenu) {
    	                    	/*//add the button here, so it has logical order in the parent div (better tab behaviour)
    	                    	$showBtn = me._dropdownButton($menu);
    	                    	$showBtn.appendTo( $menu );*/
    	                        $box.appendTo( $menu );
    	                        /*$firstElement = $menu.children(":first");
    	                        if($firstElement.is("span"))
    	                        {
    	                        	$firstElement.addClass("quickmenuSpanUnderlined");
    	                        }*/
    	                        $menu.css("display", "");
    	                        return true;
    	                    }
                        }
                	}

                    // wenn nur das "mehr..." enthalten ist, soll es nicht angezeigt werden
                    if ($quickItems.length == 1 && $menu.find('.quickMenuMoreElement').length > 0) {
                    	return false;
                    }

                    //$menu.css("display", "");
                return false;
            }

        };

        this.init = function() {
            //start
            quickmenu.init();          
        }
        
        this.refresh = function() {
            quickmenu.init();
            
        }
    };

} )( jQuery );
use_package("de.his.component");

de.his.component.SystemClipboard = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
    this.moduleName = "de.his.component.SystemClipboard";
   
    this.init = function() {
    	jQuery('.copyToSystemClipboard').click(function () {
            var clipboardContent = jQuery('#clipboardContent'); 
            var appendix=jQuery('<input>');
            jQuery('body').append(appendix);
            appendix.val(clipboardContent.text());
            appendix.select();
            document.execCommand('copy');
            appendix.remove();
        });
    	return false;
    };
    
    this.refresh = function() {
        this.init();
    };
};/* mousetrap v1.5.3 craig.is/killing/mice */
(function(C,r,g){function t(a,b,h){a.addEventListener?a.addEventListener(b,h,!1):a.attachEvent("on"+b,h)}function x(a){if("keypress"==a.type){var b=String.fromCharCode(a.which);a.shiftKey||(b=b.toLowerCase());return b}return l[a.which]?l[a.which]:p[a.which]?p[a.which]:String.fromCharCode(a.which).toLowerCase()}function D(a){var b=[];a.shiftKey&&b.push("shift");a.altKey&&b.push("alt");a.ctrlKey&&b.push("ctrl");a.metaKey&&b.push("meta");return b}function u(a){return"shift"==a||"ctrl"==a||"alt"==a||
"meta"==a}function y(a,b){var h,c,e,g=[];h=a;"+"===h?h=["+"]:(h=h.replace(/\+{2}/g,"+plus"),h=h.split("+"));for(e=0;e<h.length;++e)c=h[e],z[c]&&(c=z[c]),b&&"keypress"!=b&&A[c]&&(c=A[c],g.push("shift")),u(c)&&g.push(c);h=c;e=b;if(!e){if(!k){k={};for(var m in l)95<m&&112>m||l.hasOwnProperty(m)&&(k[l[m]]=m)}e=k[h]?"keydown":"keypress"}"keypress"==e&&g.length&&(e="keydown");return{key:c,modifiers:g,action:e}}function B(a,b){return null===a||a===r?!1:a===b?!0:B(a.parentNode,b)}function c(a){function b(a){a=
a||{};var b=!1,n;for(n in q)a[n]?b=!0:q[n]=0;b||(v=!1)}function h(a,b,n,f,c,h){var g,e,l=[],m=n.type;if(!d._callbacks[a])return[];"keyup"==m&&u(a)&&(b=[a]);for(g=0;g<d._callbacks[a].length;++g)if(e=d._callbacks[a][g],(f||!e.seq||q[e.seq]==e.level)&&m==e.action){var k;(k="keypress"==m&&!n.metaKey&&!n.ctrlKey)||(k=e.modifiers,k=b.sort().join(",")===k.sort().join(","));k&&(k=f&&e.seq==f&&e.level==h,(!f&&e.combo==c||k)&&d._callbacks[a].splice(g,1),l.push(e))}return l}function g(a,b,n,f){d.stopCallback(b,
b.target||b.srcElement,n,f)||!1!==a(b,n)||(b.preventDefault?b.preventDefault():b.returnValue=!1,b.stopPropagation?b.stopPropagation():b.cancelBubble=!0)}function e(a){"number"!==typeof a.which&&(a.which=a.keyCode);var b=x(a);b&&("keyup"==a.type&&w===b?w=!1:d.handleKey(b,D(a),a))}function l(a,c,n,f){function e(c){return function(){v=c;++q[a];clearTimeout(k);k=setTimeout(b,1E3)}}function h(c){g(n,c,a);"keyup"!==f&&(w=x(c));setTimeout(b,10)}for(var d=q[a]=0;d<c.length;++d){var p=d+1===c.length?h:e(f||
y(c[d+1]).action);m(c[d],p,f,a,d)}}function m(a,b,c,f,e){d._directMap[a+":"+c]=b;a=a.replace(/\s+/g," ");var g=a.split(" ");1<g.length?l(a,g,b,c):(c=y(a,c),d._callbacks[c.key]=d._callbacks[c.key]||[],h(c.key,c.modifiers,{type:c.action},f,a,e),d._callbacks[c.key][f?"unshift":"push"]({callback:b,modifiers:c.modifiers,action:c.action,seq:f,level:e,combo:a}))}var d=this;a=a||r;if(!(d instanceof c))return new c(a);d.target=a;d._callbacks={};d._directMap={};var q={},k,w=!1,p=!1,v=!1;d._handleKey=function(a,
c,e){var f=h(a,c,e),d;c={};var k=0,l=!1;for(d=0;d<f.length;++d)f[d].seq&&(k=Math.max(k,f[d].level));for(d=0;d<f.length;++d)f[d].seq?f[d].level==k&&(l=!0,c[f[d].seq]=1,g(f[d].callback,e,f[d].combo,f[d].seq)):l||g(f[d].callback,e,f[d].combo);f="keypress"==e.type&&p;e.type!=v||u(a)||f||b(c);p=l&&"keydown"==e.type};d._bindMultiple=function(a,b,c){for(var d=0;d<a.length;++d)m(a[d],b,c)};t(a,"keypress",e);t(a,"keydown",e);t(a,"keyup",e)}var l={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",
20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"ins",46:"del",91:"meta",93:"meta",224:"meta"},p={106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},A={"~":"`","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=",":":";",'"':"'","<":",",">":".","?":"/","|":"\\"},z={option:"alt",command:"meta","return":"enter",
escape:"esc",plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},k;for(g=1;20>g;++g)l[111+g]="f"+g;for(g=0;9>=g;++g)l[g+96]=g;c.prototype.bind=function(a,b,c){a=a instanceof Array?a:[a];this._bindMultiple.call(this,a,b,c);return this};c.prototype.unbind=function(a,b){return this.bind.call(this,a,function(){},b)};c.prototype.trigger=function(a,b){if(this._directMap[a+":"+b])this._directMap[a+":"+b]({},a);return this};c.prototype.reset=function(){this._callbacks={};this._directMap=
{};return this};c.prototype.stopCallback=function(a,b){return-1<(" "+b.className+" ").indexOf(" mousetrap ")||B(b,this.target)?!1:"INPUT"==b.tagName||"SELECT"==b.tagName||"TEXTAREA"==b.tagName||b.isContentEditable};c.prototype.handleKey=function(){return this._handleKey.apply(this,arguments)};c.init=function(){var a=c(r),b;for(b in a)"_"!==b.charAt(0)&&(c[b]=function(b){return function(){return a[b].apply(a,arguments)}}(b))};c.init();C.Mousetrap=c;"undefined"!==typeof module&&module.exports&&(module.exports=
c);"function"===typeof define&&define.amd&&define(function(){return c})})(window,document);
/**
 * @author masala@his.de used with mousetrap: https://craig.is/killing/mice
 */
use_package("de.his.component");

de.his.component.HisMousetrap = new function() {
	de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
	this.moduleName = "de.his.component.HisMousetrap";

	this.init = function() {
		initIntern(this, "[data-shortcut]")
	};
	
    this.refresh = function() {
		initIntern(this, ".bookmarkPopupMenuLink[data-shortcut]");  // Lesezeichen können per Ajax umdefiniert werden   	
    };
    
    var initIntern = function(self, shortcutSelector) {
		"use strict";
		if (!window.Mousetrap) {
			throw Error("Mousetrap js library not found");
		}

		var hotkeys = jQuery("html").data("hotkey"); 
		var shortcuts = jQuery(shortcutSelector); 
		var bindTrap;

		if (shortcuts.length) {

			bindTrap = function($el) {
				var sc = $el.data("shortcut");
				var element = $el[0];
				var hk = hotkeys ? hotkeys + "+" : ""; // if hotkeys are present add a "+"
				console.log("Mousetrap hotkeys: "+hotkeys);
				
				Mousetrap.bind(hk + sc, function(event) {
					event.preventDefault();
					
					var type = element.tagName;
					
					if (type.toUpperCase() !== 'INPUT') {   
                        // wenn Angular eingebunden Anker aus URL zusammenbauen, das Routing von Angular kommt sonst nicht mit Ankern aus JSF zurecht
                        if( jQuery('app-root' ).length ) {
                            var anchor = jQuery(element).attr('href');
                            if( anchor.startsWith('#') ) {
                                jQuery(element).attr('href',window.location.pathname+window.location.search+anchor);
                            }
                        }
						element.click();
					} else {
						element.focus();
					}
					return false;
				});
			};

			for (var i = 0; i < shortcuts.length; i++) {
				var e = jQuery(shortcuts[i]);
				if(e.data("shortcut") != ""){
					bindTrap(e);
					console.log("Bind Shortcut '"+hotkeys+"+"+e.data("shortcut")+"' to '"+e[0].type+"' with id '"+e[0].id+"'");
				}
			}
		}
  	};
};/*!
 *  Flex Level Drop Down Menu v1.1
 * Created: Jan 5th, 2010 by DynamicDrive.com. This notice must stay intact for usage 
 * Author: Dynamic Drive at http://www.dynamicdrive.com/
 * Visit http://www.dynamicdrive.com/ for full source code
 */


// Achtung: Diese Version ist eine angepasste Version!
// Nicht einfach durch eine Neue ersetzen!
use_package( "de.his.portal" );

de.his.portal.Flexdropdown = new function() {

    de.his.modules.ModuleRegistry.registerModule( this ).registerAjaxRefreshModule( this );
    this.moduleName = "de.his.portal.Flexdropdown";
    
    this.init = function() {
		var reinit = false;
		flexdropdownmenuInit(reinit);
    };

	this.refresh = function() {
		var reinit = true;
		flexdropdownmenuInit(reinit);
    };

var flexdropdownmenuInit = function(reinit) { 
var flexdropdownmenu={
//	arrowpath: 'arrow.gif', //full URL or path to arrow image
	animspeed: 0, //reveal animation speed (in milliseconds)
	showhidedelay: [400, 2000], //delay before menu appears and disappears when mouse rolls out of it, in milliseconds
	defaultOffsetX: -11,
	defaultOffsetY: 1, //jQuery.browser.mozilla? 1 : (jQuery.browser.msie && parseInt(jQuery.browser.version)==8)? 3 : 5,
	minSpaceToRightEdge: 20,
	minSpaceToBottomEdge: 20,

	//***** NO NEED TO EDIT BEYOND HERE
	startzindex:1000,
	builtflexmenuids: [], //ids of flex menus already built (to prevent repeated building of same flex menu)
	menuitemsToHide: [],
	debug: false,

	positionMenu:function($, $menu, e, $anchor){
		var istoplevel=$menu.hasClass('jqflexmenu') //Bool indicating whether $menu is top level flex menu DIV
		var docrightedge=$(document).scrollLeft()+$(window).width()-this.minSpaceToRightEdge 
		var docbottomedge=$(document).scrollTop()+$(window).height()-this.minSpaceToBottomEdge
		if (istoplevel){ //if main flex menu DIV		
			var offsets=$anchor.offset()
			var anchorsetting=$anchor.data('setting')
			var x=offsets.left+this.defaultOffsetX+anchorsetting.useroffsets[0]+(anchorsetting.dir=="h"? $anchor.outerWidth() : 0) //x pos of main flex menu UL
			var y=offsets.top+this.defaultOffsetY+anchorsetting.useroffsets[1]+(anchorsetting.dir=="h"? 0 : $anchor.outerHeight())
			var menuWidth = $anchor.outerWidth()
			var subMenuWidth = $menu.data('dimensions').w
			x=(x+subMenuWidth > docrightedge)? x-(anchorsetting.useroffsets[0]*2) - subMenuWidth + menuWidth + (anchorsetting.dir=="h"? -(menuWidth*2) : 0) : x //if not enough horizontal room to the ridge of the cursor
//			y=(y+$menu.data('dimensions').h > docbottomedge)? y-(anchorsetting.useroffsets[1]*2)-$menu.data('dimensions').h-$anchor.outerHeight()+(anchorsetting.dir=="h"? ($anchor.outerHeight()*2) : 0) : y

			// Wenn Menuliste zu hoch für viewport den Header nicht fixieren
			if ($menu.parents('.navband').length) {
				var winHeight = $(window).outerHeight();
				var menuHeight = $menu.outerHeight();
				var $header = $('#hisinoneHeader');
				if( winHeight <= menuHeight ) {
					var headerTop = $header.offset().top;
					$header.addClass('js-absolute').css({top:headerTop});
				}
			}

		}
		else{ //if sub level flex menu UL
			var $parentli=$menu.data('$parentliref')
			var parentlioffset=$parentli.offset()
			var x=$menu.data('dimensions').parentliw //x pos of sub UL
			var y=0
			x=(parentlioffset.left+x+$menu.data('dimensions').w > docrightedge)? x-$menu.data('dimensions').parentliw-$menu.data('dimensions').w : x //if not enough horizontal room to the ridge parent LI
//			y=(parentlioffset.top+$menu.data('dimensions').h > docbottomedge)? y-$menu.data('dimensions').h+$menu.data('dimensions').parentlih : y
		}
		$menu.css({left:x, top:y})
	},
	
	showMenu:function($, $menu, ev){
		if ($menu.data('timers').hidetimer) {
			clearTimeout($menu.data('timers').hidetimer)
			$menu.data('timers').hidetimer = null
			this.removeFromMenuitemsToHide($menu)
		}
		this.hideOldMenuImmediate()
		$menu.data('timers').showtimer=setTimeout(function(){$menu.show(flexdropdownmenu.animspeed)}, this.showhidedelay[0])
	},

	hideMenu:function($, $menu){
		if ($menu.data('timers').showtimer) clearTimeout($menu.data('timers').showtimer) 
		$menu.data('timers').hidetimer=setTimeout(function(){
			$menu.hide(flexdropdownmenu.animspeed)
			$('#hisinoneHeader').removeClass('js-absolute').css({top:''}); // Header wieder fixieren
			}, this.showhidedelay[1]) //hide flex menu plus all of its sub ULs
		this.menuitemsToHide.push($menu)
	},
	
	hideOldMenuImmediate:function() {
		if (this.menuitemsToHide.length > 0){
			for (var i = 0; i < this.menuitemsToHide.length; i++) {
				if (this.menuitemsToHide[i].data('timers').hidetimer) {
					clearTimeout(this.menuitemsToHide[i].data('timers').hidetimer)
					this.menuitemsToHide[i].data('timers').hidetimer = null
					this.menuitemsToHide[i].hide()
					if (this.debug)
					flexdropdownmenu.writeLog('Hide Submenu of: '+this.menuitemsToHide[i].parent().find('a:eq(0)').get(0).innerHTML)
				}
			}
			this.menuitemsToHide = new Array()
		}
	},
	
	removeFromMenuitemsToHide:function($menuToShow) {
		var length_ = $menuToShow.get().length
		if (length_ == 0) {
			return
		}
		if (length_ > 1) {
			if (this.debug) this.writeLog('Fehler: Mehr als ein UL als Parameter übergeben!')
			return
		}
		if (!$menuToShow.get(0).id) {
			if (this.debug) this.writeLog('Fehler: UL hat keine id')
			return
		}
		for (var i = 0; i < this.menuitemsToHide.length; i++) {
			if (this.menuitemsToHide[i].get(0).id == $menuToShow.get(0).id) {
				this.menuitemsToHide.splice(i,1) // Element löschen
				break
			}
		}
	},

	writeLog:function(text) {
		var xx = jQuery('#debug').get(0) 
		xx.innerHTML = text + '<br>' + xx.innerHTML
	},

	buildflexmenu:function($, $menu, $anchor){ // $anchor ist Button oder Link, $menu ist ein ul (auf gleicher Ebene wie der Button/Link)
		if( $menu.hasClass('jqflexmenu') ) {
			return;	
		}
		$menu.css({display:'block', visibility:'hidden', zIndex:++this.startzindex}).addClass('jqflexmenu')//.appendTo(document.body)
		if(typeof $menu.attr("data-flexmenuBuildMenu") === "undefined"){
    		$menu.on('mouseenter', function(){
    			clearTimeout($menu.data('timers').hidetimer)
    			$menu.data('timers').hidetimer = null
    			flexdropdownmenu.removeFromMenuitemsToHide($menu)
    		}).on('mouseleave', function(){ //hide menu when mouse moves out of it
    			flexdropdownmenu.hideMenu($, $menu)
    		})
    		$menu.attr("data-flexmenuBuildMenu", "true");
		}
		$menu.data('dimensions', {w:$menu.outerWidth(), h:$menu.outerHeight()}) //remember main menu's dimensions
		$menu.data('timers', {})
		var $lis=$menu.find("ul").parent() //find all LIs within menu with a sub UL
		$lis.each(function(i){
			var $li=$(this)
			var $subul=$li.find('ul:eq(0)').css({display:'block'}) //set sub UL to "block" so we can get dimensions
			$subul.data('dimensions', {w:$subul.outerWidth(), h:$subul.outerHeight(), parentliw:this.offsetWidth, parentlih:this.offsetHeight})
			$subul.data('$parentliref', $li) //cache parent LI of each sub UL
			$subul.data('timers', {})
			$li.data('$subulref', $subul) //cache sub UL of each parent LI
//			$li.children("input").addClass('link_next') //add arrow image
//			$li.children("a:eq(0)").append( //add arrow images
//				'<img src="'+flexdropdownmenu.arrowpath+'" class="rightarrowclass" style="border:0;" />'
//			)
			$subul.css({zIndex: ++flexdropdownmenu.startzindex})
			if(typeof $li.attr("data-flexmenuBuild") == "undefined"){
    			$li.on('mouseenter', function(ev){ //show sub UL when mouse moves over parent LI
    				var $li_ = $(this)
    				var $targetul=$li_.addClass("selected").data('$subulref')
    				if ($targetul.queue().length<=1) { //if 1 or less queued animations
    					if (flexdropdownmenu.debug)
    					flexdropdownmenu.writeLog('Mouseover: ' + $li_.find('a:eq(0)').get(0).innerHTML)
    					if ($targetul.data('timers').hidetimer) {
    						clearTimeout($targetul.data('timers').hidetimer)
    						$targetul.data('timers').hidetimer = null
    						flexdropdownmenu.removeFromMenuitemsToHide($targetul)
    					}
    					flexdropdownmenu.removeFromMenuitemsToHide($li_.parent('ul')) // parent ul
    					flexdropdownmenu.removeFromMenuitemsToHide($li_.parent('ul').parent('li').parent('ul')) // grand parent ul
    					flexdropdownmenu.hideOldMenuImmediate()
    					$targetul.data('timers').showtimer=setTimeout(function(){
    							flexdropdownmenu.positionMenu($, $targetul, ev)
    							$targetul.show(flexdropdownmenu.animspeed)
    						}, flexdropdownmenu.showhidedelay[0])
    				}
    			}).on('mouseleave', function(ev){ 
                    //hide sub UL when mouse moves out of parent LI
    				var $targetul=$(this).data('$subulref')
    				clearTimeout($targetul.data('timers').showtimer)
    				$targetul.data('timers').hidetimer=setTimeout(function(){$targetul.hide(flexdropdownmenu.animspeed).data('$parentliref').removeClass('selected')}, flexdropdownmenu.showhidedelay[1])
    				flexdropdownmenu.menuitemsToHide.push($targetul)
    				if (flexdropdownmenu.debug)
    				flexdropdownmenu.writeLog('Mouseout: ' + $targetul.parent().find('a:eq(0)').get(0).innerHTML)
    			})
    			$li.attr("data-flexmenuBuild","true");
			}
		})
		$menu.find('ul').addBack().css({display:'none', visibility:'visible'}) //collapse all ULs again
		this.builtflexmenuids.push($menu.get(0).id) //remember id of flex menu that was just built
	},


	init:function($, $anchor, $menu){ // $anchor ist Button oder Link, $menu ist ein ul, das sich in der gleichen xml-Ebene wie $anchor befindet
	
		// Nicht in Burgernavigation ausführen
		if ($menu.parents('.topMenuContainer').length) {
			return;
		}
		if (this.builtflexmenuids.length==0 && reinit == false){ //only bind click event to document once
			$(document).on("click", function(ev){
				if (ev.button==0){ //hide all flex menus (and their sub ULs) when left mouse button is clicked
					$('.jqflexmenu').find('ul').addBack().hide()
				}
			})
		}
		if (jQuery.inArray($menu.get(0).id, this.builtflexmenuids)==-1) //if this flex menu hasn't been built yet
			this.buildflexmenu($, $menu, $anchor)
		if ($anchor.parents().filter('ul.jqflexmenu').length>0) //if $anchor matches an element within the flex menu markup, don't bind onflexmenu to that element
			return
		var useroffsets=$anchor.attr('data-offsets')? $anchor.attr('data-offsets').split(',') : [0,0] //get additional user offsets of menu
		useroffsets=[parseInt(useroffsets[0]), parseInt(useroffsets[1])]
		$anchor.data('setting', {dir: $anchor.attr('data-dir'), useroffsets: useroffsets}) //store direction (drop right or down) of menu plus user offsets
		if(typeof $anchor.attr("data-flexmenuAnchorInit") === "undefined"){
    		$anchor.on("mouseenter", function(ev){
    			$menu.css('zIndex', ++flexdropdownmenu.startzindex)
    			flexdropdownmenu.positionMenu($, $menu, ev, $anchor)
    			flexdropdownmenu.showMenu($, $menu, ev)
    		}).on("mouseleave", function(ev){
    			flexdropdownmenu.hideMenu($, $menu)
    		})
    		$anchor.attr("data-flexmenuAnchorInit", "true");
		}
	}
}

jQuery.fn.addflexmenu=function(options){
	var $=jQuery
	return this.each(function(){ //return jQuery obj
		var $anchor=$(this)
		if (typeof options=="object"){ //if options parameter defined
			if (options.dir)
				$anchor.attr('data-dir', options.dir) //set/overwrite data-dir attr with defined value
			if (options.offsets)
				$anchor.attr('data-offsets', options.offsets) //set/overwrite data-offsets attr with defined value
		}
		var $subul = $anchor.parent().find('ul:eq(0)')
		
		if ($subul.length==1) //check flex menu is defined
			flexdropdownmenu.init($, $anchor, $subul)
	})
};


	var $anchors=$('.subMenuBtn.flexdropdownmenu, .topMenuLink.flexdropdownmenu ')
	$anchors.each(function(){
		$(this).addflexmenu()
	})
	if (flexdropdownmenu.debug) {
		jQuery('body').append('<div id="debug" style="position:absolute; z-index:10000; width:100%; height:300px; left:0; bottom:0; background-color:white; overflow:auto;" />')
	}
}
}
/**
* Extend the flexdropdown menu functionality to include arrow key navigation
* author: masala@his.de
*/

window.his_flexdropdown = window.his_flexdropdown || new function(){
	
	var topLevelElement = null, openElement, originalTimers, currentFocus;
	
	
	var setTopLevelElement = function(fe){
		topLevelElement = fe;
	}

	var getTopLevelElement = function(){
		var item = jQuery(".topMenuList a:focus");
		if(item.length > 0){
			if(!item.hasClass(".topMenuLink") && !item.hasClass(".topMenuLinkHighlighted")){
				item = item.closest(".topMenuList");
				item = item.find("> a");
			}
			return item;
		}
	};
	
	var setOpenElement = function(oe){
		openElement = oe;
	}

	var getOpenElement = function(){
		return openElement;
	};
	
	var setFlexTimers = function(a,b){
		originalTimers = flexdropdownmenu.showhidedelay;
		flexdropdownmenu.showhidedelay = [a, b];	//overwrite it. so the menu shows immediately
	}

	var resetFlexTimers = function(){
		flexdropdownmenu.showhidedelay = originalTimers;
	}
	
	var focusItem = function(element, silent){
		currentFocus = element;
		//without timeout it won't always focus because of keyup event 
		if(currentFocus && !silent){
			currentFocus.focus();
		}
	}
	
	var getFocusedItem = function(){
		return currentFocus;
	}
	
	var closeOpen = function(element){
		var oe = element || getOpenElement();
		//if any open menus - then close
		if(oe){
			setFlexTimers(0, 0);	//make it immediate
			flexdropdownmenu.hideMenu(jQuery, oe);
			if(!element){
				setOpenElement(null); //clear openElement
			}
			resetFlexTimers();
		}
	};
	
	var private_showMenu = function(menu, event){
		//position and show menu - this was take from flexdropdownmenu.init() -> bind("mouseenter")
		flexdropdownmenu.positionMenu(jQuery, menu, event, menu.parent().find("> a"));
		//override the showMenu function so that the focus() doesn't need to be called delayed
		var oldShow = flexdropdownmenu.showMenu;
			flexdropdownmenu.showMenu = function($, $menu, ev){
				if ($menu.data('timers').hidetimer) {
					$menu.data('timers').hidetimer = null
					this.removeFromMenuitemsToHide($menu)
				}
				this.hideOldMenuImmediate();
				$menu.show(flexdropdownmenu.animspeed);
			};
		flexdropdownmenu.showMenu(jQuery, menu, event);
		//reset it
		flexdropdownmenu.showMenu = oldShow;
		/////////
		setOpenElement(menu);
	};
	
	var openChildMenu = function(menu, event){
		private_showMenu(menu, event);
		
		//end - boolean start from back for array
		var findLink = function(lis, end){
			if(lis.length > 0){
				if(end){
					lis = lis.toArray().reverse();
				}
				
				var link, a;
				for(var i = 0, l = lis.length; i<l; i++){
					link = jQuery(lis[i]);
					a = link.find("> a");
					if(a.length > 0){
						return a;
					}
				}
				
			}
		};
		
		
		var lis = menu.find("> li");
		if(lis.length > 0){
			var firstItem = findLink(lis);
			focusItem(firstItem);	//focus the first item in the new menu shown
		
			//if tab shift is called on the first item of the menu - close the menu as the user is leaving the menu
			var tab = function(e){
				var keyCode = e.which || e.keyCode;
				if (keyCode == 9 && e.shiftKey) {
			        closeOpen(menu);
			        firstItem.keydown(tab);
			    }
			}
			firstItem.keydown(tab);
			
			//if the menu has more than 1 LI (entry) also close the menu when the user presses the tab item on the last menu item as the user is also leaving the menu
			if(lis.length > 1){
				var lastItem = findLink(lis, true);
				if(lastItem){
					var tabDown = function(e){
						var keyCode = e.which || e.keyCode;
						if (keyCode == 9 && !e.shiftKey) {
					        closeOpen(menu);
					        lastItem.unbind("keydown");
					    }
					}
					lastItem.keydown(tabDown);
				}
			}
		}
		
	};
	
	//dir == next or prev (jQuery function)
	var topLevelMove = function(dir){
		focusItem(getTopLevelElement().parent()[dir]().find("> a"));
	};
	
	var keyActions = {
			left: function(event){
				event.preventDefault();
				//find the drop down
				var child = getTopLevelElement().parent().find("> ul.jqflexmenu");
				
				//check if exists and 
				if(child.length > 0){
					//check visibility
					if(!child.is(":visible")){
						//top menu - move across one
						topLevelMove("prev");
					}else{
						//sub menu
						var current = getFocusedItem();
						if(current){
							//find its own menu - i.e. the UL where the current LI is present
							var menu = current.closest("ul.subMenu");
							//find the parent of that menu - i.e. the LI where the sub UL is in
							var parent = menu.parent("li").find("> a");
							if(menu.length > 0 && parent.length > 0){
								//close subMenu and focus on parent Link
								closeOpen(menu);
								focusItem(parent);
							}
						}
					}
				}else{
					topLevelMove("prev");	//has no children
				}
			}, 
			right: function(event){
				event.preventDefault();
				//find the drop down
				var child = getTopLevelElement().parent().find("> ul.jqflexmenu");
				
				//check if exists and 
				if(child.length > 0){
					//check visibility
					if(!child.is(":visible")){
						//top menu - move across one
						topLevelMove("next");
					}else{
						var current = getFocusedItem();
						if(current){
							var subMenu = current.next("ul.subMenu");
							if(subMenu.length > 0){
								//open the next level (subMenu) of a menu point
								openChildMenu(subMenu, event);
							}
						}
					}
				}else{
					topLevelMove("next");//has no children
				}
			},
			up: function(event){
				event.preventDefault();
				//find the drop down
				var child = getTopLevelElement().parent().find("> ul.jqflexmenu");
				//check if exists and 
				if(child && child.length > 0){
					//check visibility
					var current = getFocusedItem();
					var li = current.closest("li");
					var prev = li.prev().find("> a");
					
					if(child.is(":visible")){
						if(prev.length > 0){
							//focus on previous entry
							focusItem(prev);
						}else{
							//only if current focus item is not inside a submenu
							var subMenu = current.closest("ul.subMenu");
							if(subMenu.length <= 0){
								//no top item - hide menu and move a level up
								closeOpen(child);
								focusItem(getTopLevelElement());
							}
						}
					}
				}
			},
			down: function(event){
				event.preventDefault();
				//find the drop down
				var child = getTopLevelElement().parent().find("> ul.jqflexmenu");
				//check if exists and 
				if(child.length > 0){
					//check visibility
					var current = getFocusedItem();
					if(!child.is(":visible")){
						openChildMenu(child, event);
					}else{
						//is visible
						var next = current.closest("li").next().find("> a");
						//focus on next entry
						if(next.length > 0){
							focusItem(current.closest("li").next().find("> a"));
						}
					}
				}
			},
			tab_up: function(event){
				var newFocus = jQuery("ul.nav a:focus");
				if(newFocus.length > 0){
					focusItem(newFocus, true);
				}
			}
	};
	
	var keyMapper = {
			onKeyDown: function(e){
				if(getTopLevelElement()){
					var keyCode = e.keyCode || e.which,
				      arrow = {left: 37, up: 38, right: 39, down: 40 }, tab = 9;
					switch (keyCode) {
					    case arrow.left:
					    	keyActions.left(e);
					    	break;
					    case arrow.up:
					    	keyActions.up(e);
					    	break;
					    case arrow.right:
					    	keyActions.right(e);
					    	break;
					    case arrow.down:
					    	keyActions.down(e);
					    	break;
					}
				}
			},
			onKeyUp: function(e){
				if(getTopLevelElement()){
					var keyCode = e.keyCode || e.which,
						tab = 9;
					switch (keyCode) {
						case tab:
					    	keyActions.tab_up(e);
					    	break;
					}
				}
			}
	};	
	
	var registerEvents = function(){
		//register events on topmenu item
		jQuery(".topMenuLink, .topMenuLinkHighlighted").focus(function(){
			closeOpen();
		});
//		jQuery(document).on("focus mouseenter", ".topMenuLink, .topMenuLinkHighlighted", function(event){
//			closeOpen();
//		});
		
		//register keydown actions
		jQuery(document).keydown(keyMapper.onKeyDown).keyup(keyMapper.onKeyUp);
	};
	
	this.init = function(){
		registerEvents();
	};
	
};


jQuery(document).ready(function(){
	
	his_flexdropdown.init();
	
});/**
 * Actions to support angular.
 * Currently the only function is deleting HTML5 SessionStorage keys
 * when clicking certain buttons and links in the JSF frame,
 * like startpage, bookmarks, menu search, menu items.
 */
use_package("de.his.modules");
de.his.modules.angularHelper = new function() {
	
    this.moduleName = "de.his.modules.angularHelper";

    /**
     * Delete all Angular keys from HTML5 SessionStorage.
     */
    this.deleteAngularSessionStorageKeys = function() {
        console.log( 'Delete angular keys from HTML5 SessionStorage...' );
        sessionStorage.removeItem( 'his_cs_sys_last_menu_item' );
        sessionStorage.removeItem( 'his_cs_sys_last_search_url' );
        sessionStorage.removeItem( 'his_cs_sys_last_searchresult_url' );
        sessionStorage.removeItem( 'his_cs_sys_last_back_url' );
    }
};
use_package("de.his.component");

de.his.component.tabsAsDropdown = new function() {
    de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
	this.moduleName = "de.his.component.tabsAsDropdown";    
    this.refresh = function() {
        this.init();
    };

	this.init = function() {
		jQuery('.tabsAsDropdown').each(function(){
		    var $this = jQuery(this);
		    if( !$this.find('.mikronavi_submit-trigger').length ) {
		        var activeText = $this.find('button.active').html();
			    jQuery('<button class="mikronavi_submit-trigger">'+activeText+'</button>').insertBefore($this.children('ul'));
		    }
		});
		
		jQuery('.tabsAsDropdown').off('click').on('click', '.mikronavi_submit-trigger', function(e){
			e.preventDefault();
			var $this = jQuery(this);
			$this.toggleClass('open');
			$this.next('ul').slideToggle(100);
		});

    };
};use_package("de.his.portal");

/**
 * Portal Grid
 */
de.his.portal.grid = new function() {
	de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
		
	this.moduleName = "de.his.portal.grid";

	this.init = function(){		
		if( jQuery('body').hasClass('editNavigationframe') ) {
			drag();
			createGrid();
			configureGrid();
			initial = true;
			if( !jQuery('.gridWrapConfiguration').hasClass('visible') ) {
				jQuery('.gridDDZoneWrap').removeClass('gridDDZone-hide');
			}
		setTimeout(function(){	
				jQuery('#hisinoneHeader').addClass('js-fixed').parent().css({paddingTop:jQuery('#hisinoneHeader').outerHeight()})				
			}, 500);
		}
	}
		
	createGrid = function(){	
		grid = [];

	    jQuery('.gridElement').each(function() {
			$this = jQuery(this);
			
			var widgetPosition = $this.attr('id');
			widgetPosition = widgetPosition.split('_')[1];
			
			$this.find('.draggableEl').each(function(i){
				$this = jQuery(this);
				var widgetType = $this.attr('id');
				widgetType = widgetType.split('_')[0];
				widgetId = $this.data('id');
				item = {}
	        	item["widgetPosition"] = Number(widgetPosition);
	        	item["widgetType"] = widgetType;
				item["widgetId"] = Number(widgetId);
				
				item["widgetSortorder"] = i;
				//item["widgetSortInPos"] = {widgetPosition: Number(widgetPosition) , widgetSortorder: i};
				
				grid.push(item);	
			});
	    });
		// Elemente aus DropZone holen 
		ddzoneIndx = 0;
		jQuery('#gridDDZone').children().each(function(){
			ddzoneIndx++;
			$this = jQuery(this);
			var widgetType = $this.attr('id');
			widgetType = widgetType.split('_')[0];
			widgetId = $this.data('id');
			item = {}
			item["widgetPosition"] = 0;
			item["widgetType"] = widgetType;
			//item["widgetSortorder"] = 999+ddzoneIndx;
			item["widgetId"] = Number(widgetId);
			
			item["widgetSortorder"] = ddzoneIndx;
			//item["widgetSortInPos"] = {widgetPosition: 0 , widgetSortorder: ddzoneIndx};
			
			grid.push(item);
		});
		
		// Reihenfolge in Array schreiben
		/*for (i = 0; i < grid.length; i++){
			if( !grid[i].widgetSortorder ) {
				grid[i].widgetSortorder = i+1;
			}
		}*/
		
		gridString = JSON.stringify(grid);
		document.getElementById('gridForm:gridData').value = gridString;
		
		//console.log(gridString);
		
	}	
	initial = true;	
	var allGridAreasSelected;
	configureGrid = function(){

		var gridAreasString = jQuery('.gridSizeHeader').val(); 
		gridAreasString = gridAreasString.replace(/'/g, '');
		var gridAreas = gridAreasString.split(" ");
		
		var gridAreasStringFooter = jQuery('.gridSizeFooter').val(); 
		gridAreasStringFooter = gridAreasStringFooter.replace(/'/g, '');
		var gridAreasFooter = gridAreasStringFooter.split(" ");
		
				
		if( initial == true ) {			
			createConfigurationGrid(gridAreas, gridAreasFooter);
		}
		// Vorhandenes Grid anzeigen
		function createConfigurationGrid(gridAreas, gridAreasFooter){			

			if( jQuery('.gridWrapConfiguration').find('.gridElementSelected').length == 0 ) {
								
				//Header									
				var gridWithCount = 1;
				for (i = 0; i < gridAreas.length; i++){			
					var pos = i+1;
					var gridElementWidth = jQuery('.gridHeader').find('.gridWrapConfiguration').find('.gridElement').width();	
					if( gridAreas[i] != gridAreas[i-1] ) {
						//console.log(gridAreas[i], pos);
						if( !jQuery('.gridHeader').find('.gridWrapConfiguration').find('.gridElement:nth-child('+pos+')').attr('data-index', gridAreas[i]).find('.gridElementSelected').length ) {
							jQuery('.gridHeader').find('.gridWrapConfiguration').find('.gridElement:nth-child('+pos+')').attr('data-index', gridAreas[i])
							.append('<div class="gridElementSelected"><a class="gridElementSelectedClose iconfont-delete" title="Rasterelement löschen" href="#" ></a><div class="gridElementDragbar"></div></div>');
							gridWithCount = 1; 
						}									
						
					} else {
						gridWithCount++; 
						gridElementWidth = gridElementWidth*gridWithCount;
						jQuery('.gridHeader').find('.gridWrapConfiguration').find('.gridElement[data-index='+gridAreas[i]+']').children('.gridElementSelected').css({width:gridWithCount*100+'%'});
					}
				}
				
				//Footer
				var gridWithCountFooter = 1;			
				for (i = 0; i < gridAreasFooter.length; i++){							
					var pos = i+1;
					var gridElementWidth = jQuery('.gridFooter').find('.gridWrapConfiguration').find('.gridElement').width();
					if( gridAreasFooter[i] != gridAreasFooter[i-1] ) {
						// console.log(gridAreas[i], pos);
						if( !jQuery('.gridFooter').find('.gridWrapConfiguration').find('.gridElement:nth-child('+pos+')').attr('data-index', gridAreasFooter[i]).find('.gridElementSelected').length ) {
							jQuery('.gridFooter').find('.gridWrapConfiguration').find('.gridElement:nth-child('+pos+')').attr('data-index', gridAreasFooter[i])
							.append('<div class="gridElementSelected"><a class="gridElementSelectedClose iconfont-delete" title="Rasterelement löschen" href="#" ></a><div class="gridElementDragbar"></div></div>');
							gridWithCountFooter = 1; 				
						}									
						
					} else {
						gridWithCountFooter++;
						gridElementWidth = gridElementWidth*gridWithCountFooter;
						jQuery('.gridFooter').find('.gridWrapConfiguration').find('.gridElement[data-index='+gridAreasFooter[i]+']').children('.gridElementSelected').css({width:gridWithCountFooter*100+'%'});
				
					}
				}
			}

		}
		
		
		// Grid Konfiguration
		var selectedElements = [];
		var selectedElements2 = [];
		var savedElements = [];
		var savedElements2 = [];		
		
		// Grid Konfiguration ein und ausblenden		
		jQuery('.toggleGridConfig').off('click').on('click', function(){
			if( jQuery('.gridWrapConfiguration').hasClass('visible') ) {
				saveGridConfig();
				// Wenn nicht jedes Gridfeld gefüllt nicht weiter machen
				if( allGridAreasSelected == false ) {
					return false;
				}
				jQuery('#gridForm\\:submitGrid').attr('disabled', false);	
			} else {
				jQuery('#gridForm\\:submitGrid').attr('disabled', true);
			}
			jQuery('.gridWrapConfiguration').toggleClass('visible');
			jQuery('.gridDDZoneWrap').toggleClass('gridDDZone-hide');
			
		});
		// Grid anwenden bei klick auf speichern
		jQuery('.saveGridConfig').off('click').on('click', function(){ 
			saveGridConfig();
		});
		
		jQuery('.toggleLoggedinView').off('click').on('click', function(){ 
			if( !jQuery('.gridWrapConfiguration').hasClass('visible') ) {
				jQuery('body').toggleClass('editNavigationframe_loggedinView');
			}
		});

		// letzten geladene Konfiguratin zurückholen
		/*jQuery('.restoreGridConfig').on('click', function(){
			restoreGridConfig();
		});*/


		// Grid Konfigurieren per Drag
		function resizableGrid() {
			jQuery('.gridElementDragbar').parent().resizable({
					handles: 'e',
					// TODO:
					//Links und rechts dragbar
					//handles: 'e, w',
					containment: "document",
					/*grid: 207,*/
					start: function(event, ui){
						// Lücke für maximale Breite berechnen					
						var $this = jQuery(this);
						var $gridElement = $this.closest('.gridElement');
						var gridElementWidth = $gridElement.outerWidth();
						
						var nextElement = $gridElement.nextAll().find('.gridElementSelected')[0];	
						var prevElement = $gridElement.prevAll().find('.gridElementSelected')[0];				
						$this.resizable( "option", "maxWidth", 0 );
						$this.resizable( "option", "minWidth", gridElementWidth );
						
						var thisTop = $this.offset().top;
						var thisLeft = $this.offset().left;
						if( nextElement ) {
							var nextLeft = jQuery(nextElement).offset().left;
							var nextTop = jQuery(nextElement).offset().top;						
							var maxWidth = nextLeft-thisLeft;
							if( nextTop == thisTop ) {
								$this.resizable( "option", "maxWidth", maxWidth );
							}
						}
						/*if( prevElement && !event.toElement.classList.contains('ui-resizable-e') ) { 
							var prevLeft = jQuery(prevElement).offset().left;
							var prevWidth = jQuery(prevElement).outerWidth();
							var prevTop = jQuery(prevElement).offset().top;						
							var maxWidth = prevLeft+prevWidth-thisLeft;						
							if( prevTop == prevTop ) {
								$this.resizable( "option", "maxWidth", maxWidth );
							}
							console.log('prevElement', prevElement)	
						}*/
						
					},				
					stop: function(){
						// neue Größe berechnen
						var $this = jQuery(this);
						var $gridElement = $this.closest('.gridElement');
						var gridElementWidth = $gridElement.outerWidth();
						var thisWidth = $this.outerWidth();
						var newWidth = (thisWidth/gridElementWidth);
						newWidth = Math.round(newWidth); 
						$this.css({width: 100*newWidth+'%'});
					},
					resize: function(){
					},				
					 
			});
		} resizableGrid();
		// Grid Konfigurieren per Click
		jQuery('.gridWrapConfiguration').find('.gridElement').off('click').on('click', function(e){
			var $this = jQuery(this);
			if(e.target.classList.contains('gridElement')) {				
				// wenn nicht vorhanden element anlegen
				if( !$this.find('.gridElementSelected').length ) {
					$this.append('<div class="gridElementSelected"><a class="gridElementSelectedClose iconfont-delete" title="Rasterelement löschen" href="#" ></a><div class="gridElementDragbar"></div></div>')
					// wenn vorhanden auswahl erweitern
				} 
				resizableGrid();
				/*if( !jQuery('.gridElementSelectedActive').length ) {
					$this.append('<div class="gridElementSelected gridElementSelectedActive"><a class="gridElementSelectedSave iconfont-save_mono" href="#" ></a><a class="gridElementSelectedClose iconfont-delete" href="#" ></a><div class="gridElementDragbar"></div></div>')
					// wenn vorhanden auswahl erweitern
				} else {
					var selectedLeft = jQuery('.gridElementSelectedActive').offset().left;
					var thisLeft = $this.offset().left;
					
					// nur positive Clicks zulassen
					if( selectedLeft <= thisLeft ) {
						var thisWidth = $this.width();
						var newWidth = thisLeft-selectedLeft + thisWidth;
						jQuery('.gridElementSelectedActive').css({width:newWidth});
					}
				}	*/						
			}
		});
		
		// Element bearbeiten
		jQuery('.gridWrapConfiguration').find('.gridElement').on('click', '.gridElementSelectedEdit', function(){
			jQuery(this).closest('.gridElementSelected').addClass('gridElementSelectedActive');
		});
		
		// Element entfernen und array leeren
		jQuery('.gridWrapConfiguration').find('.gridElement').on('click', '.gridElementSelectedClose', function(){
			jQuery(this).closest('.gridElementSelected').remove();
			// selectedElements = [];
		});
				
		function collectAllItems() {			
			/*Header*/			
			var selectedCounter = 0;
			var selectedCounterArr = [];
			jQuery('.gridHeader').find('.gridWrapConfiguration').find('.gridElementSelected').each(function(){
				var $thisSelected = jQuery(this);
				var selectedLeft = $thisSelected.offset().left;
				var selectedWidth = $thisSelected.outerWidth();
				var selectedTop = $thisSelected.offset().top;
				var activeRange = selectedLeft+selectedWidth;
				// alle gridelemente finden die überlagert werden von der Auswahl und in Array legen
				$thisSelected.closest('.gridWrapConfiguration').find('.gridElement').each(function(){
					$this = jQuery(this);
					var gridElementLeft = $this.offset().left;
					var gridElementWidth = $this.outerWidth();
					var gridElementRange = gridElementLeft+gridElementWidth;
					var gridElementTop = $this.offset().top;					
					if(Math.round(gridElementLeft) >= Math.round(selectedLeft) && Math.round(activeRange) >= Math.round(gridElementRange) && selectedTop == gridElementTop ) {
						var id = $this.attr('id').split('_')[1];
						selectedElements.push(id);
						
						// Gridfelder sammeln um zu prüfen ob alle gefüllt sind
						selectedCounter++;
						selectedCounterArr.push(selectedCounter);						
					}
				});		
				var selectedId = $thisSelected.parent().attr('id').split('_')[1];				
				savedElements.push({selectedElements, selectedId});				
		 		selectedElements = [];
			
				// Elemente in nicht definierten Areas finden
				jQuery('.gridHeader.gridWrap:not(.gridWrapConfiguration)').children('#gridElement_'+selectedId).addClass('inuse');					
			});			
							
			/*Footer*/			
			jQuery('.gridFooter').find('.gridWrapConfiguration').find('.gridElementSelected').each(function(){
				var $thisSelected = jQuery(this);
				var selectedLeft = $thisSelected.offset().left;
				var selectedWidth = $thisSelected.outerWidth();
				var selectedTop = $thisSelected.offset().top;
				var activeRange = selectedLeft+selectedWidth;
				// alle gridelemente finden die überlagert werden von der Auswahl und in Array legen
				$thisSelected.closest('.gridWrapConfiguration').find('.gridElement').each(function(){
					$this = jQuery(this);
					var gridElementLeft = $this.offset().left;
					var gridElementWidth = $this.outerWidth();
					var gridElementRange = gridElementLeft+gridElementWidth;
					var gridElementTop = $this.offset().top;
					if(Math.round(gridElementLeft) >= Math.round(selectedLeft) && Math.round(activeRange) >= Math.round(gridElementRange) && selectedTop == gridElementTop ) {
						var id = $this.attr('id').split('_')[1];
						selectedElements2.push(id);
						
						// Gridfelder sammeln um zu prüfen ob alle gefüllt sind
						selectedCounter++;
						selectedCounterArr.push(selectedCounter);
					}					
				});				
				var selectedId = $thisSelected.parent().attr('id').split('_')[1];				
				savedElements2.push({selectedElements2, selectedId});	
		 		selectedElements2 = [];
			
				// Elemente in nicht definierten Areas finden
				jQuery('.gridFooter.gridWrap:not(.gridWrapConfiguration)').children('#gridElement_'+selectedId).addClass('inuse');					
			});
			
			// Püfen ob alle Gridfelder gefüllt sind
			if( selectedCounterArr.length != 20 ) {
				allGridAreasSelected = false;
			} else {
				allGridAreasSelected = true;
			}
			
			// Wenn nicht jedes Gridfeld gefüllt nicht weiter machen
			if( allGridAreasSelected == false ) {
				return false;	
			}
			// wenn LoginForm wegkonfigurtiert			
			if( jQuery('.gridWrap:not(.gridWrapConfiguration)').find('.gridElement:not(.inuse)').find('#loginForm_DragID.draggableEl').length ) {
				document.getElementById('gridForm:isLoginFormVisible').value = false;
				jQuery('#gridForm\\:isLoginFormVisible').trigger('change');	
			}  
			// nicht in Raster positionierte Widgets in Dropzone legen
			// Productlogo darf nicht entfernt werden und wird wieder in den Footer gelegt
			jQuery('.gridWrap:not(.gridWrapConfiguration)').find('.gridElement:not(.inuse)').find('.draggableEl:not(.productLogo)').prependTo('#gridDDZone');
			jQuery('.gridWrap:not(.gridWrapConfiguration)').find('.gridElement:not(.inuse)').find('.draggableEl.productLogo').appendTo('#gridElement_11');
			jQuery('.gridWrap').find('.gridElement.inuse').removeClass('inuse');
	
		}		

		this.saveGridConfig = function() {
			// Neue Auswahl in vorhandenem Array ändern		
			collectAllItems();			
			// Wenn nicht jedes Gridfeld gefüllt nicht weiter machen
			if( allGridAreasSelected == false ) {
				jQuery('.triggerAllGridAreasSelectedMessage').trigger('click');
				return false;	
			} else {
				if( jQuery('.error_infobox').length ) {
					jQuery('.infobox_close').trigger('click');
				}
			}
			
			//Header
			for (i = 0; i < savedElements.length; i++){
				gridElement = savedElements[i].selectedId;
				elements = savedElements[i].selectedElements;
				for (i2 = 0; i2 < elements.length; i2++){
					gridAreas[elements[i2]-1] = 'grid'+ gridElement;
				}
			}		
			// Ausgabe für css Aufbereiten
			var gridAreasCss1 = [];
			var gridAreasCss2 = [];			
			for (i = 0; i < gridAreas.length; i++){
				if(i < 5) {
					gridAreasCss1.push(gridAreas[i]);
				} else {
					gridAreasCss2.push(gridAreas[i]);
				}
			}
			var gridAreasCss = "'" + gridAreasCss1.join(' ') + "' '"+ gridAreasCss2.join(' ') + "'";
			//console.log('gridAreasCss', gridAreasCss);
			jQuery('.gridSizeHeader').val(gridAreasCss);
			jQuery('.gridHeader').css({gridTemplateAreas: gridAreasCss});
			savedElements = [];
			
			//Footer
			for (i = 0; i < savedElements2.length; i++){
				gridElement = savedElements2[i].selectedId;				
				elements = savedElements2[i].selectedElements2;
				for (i2 = 0; i2 < elements.length; i2++){
					gridAreasFooter[elements[i2]-11] = 'grid'+ gridElement;
				}
			}
			var gridAreasCss1_2 = [];
			var gridAreasCss2_2 = [];			
			for (i = 0; i < gridAreasFooter.length; i++){
				if(i < 5) {
					gridAreasCss1_2.push(gridAreasFooter[i]);
				} else {
					gridAreasCss2_2.push(gridAreasFooter[i]);
				}
			}
			var gridAreasCss_2 = "'" + gridAreasCss1_2.join(' ') + "' '"+ gridAreasCss2_2.join(' ') + "'";
			jQuery('.gridSizeFooter').val(gridAreasCss_2);
			jQuery('.gridFooter').css({gridTemplateAreas: gridAreasCss_2});
			savedElements2 = [];
		};
		
	}

	this.submitGrid = function() {
		jQuery('.saveGridConfig').trigger('click');
		createGrid();
		setTimeout(function(){
			configureGrid();
		},800);
		
		initial = false;
		// Wenn nicht jedes Gridfeld gefüllt nicht weiter machen
		if( allGridAreasSelected == false ) {
			de.his.modules.Waiting.resetWaitingBehaviour();
			return false;	
		} 
    }
	
	
	var drag = function(){
		
		/*jQuery('<button type="button" class="saveGrid">ShowArray</button>').insertAfter('#hisinoneHeader');
		jQuery('.saveGrid').off('click').on('click',function(){
			createGrid();
		});*/

		var $dropZone = jQuery('.gridElement, #gridDDZone'); 
		var $dragElement = jQuery(".draggableEl");
		 $dragElement.attr('draggable', 'true');
		
		
		var originalPosX;
  		var originalPosY;
		var currPosX;
		var currPosY;
		
		jQuery('body').on('dragover', function(e){
			currPosX = e.clientX;
			currPosY = e.clientY;
			jQuery('.js-dragClone').css({left: currPosX, top: currPosY});
		});
	
		$dragElement.on('dragstart', function(e){
			
			originalPosX = jQuery(this).offset().left;
  			originalPosY = jQuery(this).offset().top;
		  				
			$dropZone.addClass('dragactive');			
			jQuery(this).addClass('onthedrag');			
			if( !jQuery('.js-dragClone').length ) {
				jQuery(this).clone().addClass('js-dragClone').css({left: originalPosX, top: originalPosY}).appendTo('body');
			}
			
			var thisId = jQuery(e.target).closest("[draggable=true]").attr('id');
			localStorage.setItem('dataTransferObject', thisId);
			
			if( jQuery(this).hasClass('productLogo') ) {
				jQuery('.gridDDZoneWrap').addClass('gridDDZone-hide');						
			}
			
		}).on('dragend', function(e){
			if( e.originalEvent.dataTransfer.dropEffect == 'none' ) {
				jQuery('.js-dragClone').animate({'top':originalPosY, 'left':originalPosX},400);
			}
			
			$dragElement.removeClass('onthedrag');
			if( jQuery('.js-dragClone').length ) {
				setTimeout(function(){
					jQuery('.js-dragClone').remove();
					jQuery('.gridDDZoneWrap').removeClass('gridDDZone-hide');
				},400);
			}
		});
		
		$dropZone.off('drop').on('drop', function(e){
			e.preventDefault();
			var ev = e;
			var data = localStorage.getItem('dataTransferObject');
			setTimeout(function(){
				$dropZone.removeClass('dragactive dragover');
				if( ev.target.classList.contains('gridElement') || ev.target.id.contains('gridDDZone') ) {
					ev.target.appendChild(document.getElementById(data));
				} 
				else {					
					var $closestDragZone = jQuery(ev.target).closest("[draggable=true]");					
					$closestDragZone[0].before(document.getElementById(data));
				}					
				
				// wenn LoginForm wegkonfigurtiert
				if( data.contains('loginForm') ) {
					if( ev.currentTarget.id.contains('gridDDZone')  ) {
						document.getElementById('gridForm:isLoginFormVisible').value = false;
						jQuery('#gridForm\\:isLoginFormVisible').trigger('change');
					} else {
						document.getElementById('gridForm:isLoginFormVisible').value = true;
						jQuery('#gridForm\\:isLoginFormVisible').trigger('change');
					}
				}
				
				localStorage.removeItem('dataTransferObject');
				jQuery('#hisinoneHeader').addClass('js-fixed').parent().css({paddingTop:jQuery('#hisinoneHeader').outerHeight()});
			},400);
			jQuery('.js-dragClone').addClass('bye');
		});
		
		
		/*$dropZone.on('dragenter', function(e){
			e.preventDefault();			
			jQuery(this).addClass('dragover');
		});*/
		
		$dropZone.on('dragleave', function(e){
			e.preventDefault();
			jQuery(this).removeClass('dragover');
		});
		
		$dropZone.on('dragover', function(e){
			jQuery(this).addClass('dragover');
			e.preventDefault();
		});
	}
	
	
	
	this.refresh = function() {
		this.init();
	};
};
/**
 * Creates custom tooltips in Firefox, Safari and Chrome Browsers
 * does not work in Edge
 */
use_package("de.his.component");

de.his.component.customtooltip = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);

    this.moduleName = "de.his.component.customtooltip ";

    this.init = function() {
        initCustomTooltips();
        if(window.device.desktop()){
            focustooltip();
            if( navigator.webdriver != true ) {
               hovertooltip();
            }
        }
    };

    this.refresh = function() {
        de.his.component.customtooltip.init();
    };

    this.initHovertooltip = function() {
        hovertooltip();
    }
    
    this.setTooltip = function(element) {
        if(window.device.desktop()){
            setTooltip(element);
        }
    }
    
    this.removeTooltip = function(element) {
        removeTooltip(element);
    }
    
    var initCustomTooltips = function() {
        // remove all title attributes and write them to data-title
        $focusableElements = jQuery('input[required]');
        $focusableElements.each(function(index, element) {
            var $this = jQuery(element);
            
            if(typeof $this.attr('required') !== 'undefined'){
                
                $this.removeAttr('required');
                $this.attr('data-required', 'required');
                //console.log("data-required", $this);
                //console.log($this.closest('form'));
                if(typeof $this.closest('form').attr('data-required-listener-set') === 'undefined'){
                    
                    $this.closest('form').find('button[type="submit"]').on('click', function(e){
                        // onclick
                        $this.closest('form').find('input[data-required]').each(function(index, element){
                            //jQuery(element).attr('required','required');
                            if (element.value == '') {
                                 element.setCustomValidity('Fülle dieses Feld aus.');
                              } else {
                                 element.setCustomValidity('');
                              }
                        });
                    });
                };
            };
        });
    };

    var setTooltip = function(element, removeTitle = false) {
        var $this = jQuery(element);
        var title = $this.attr('title');
        $this.attr('data-title', title);
        var id = $this.attr('id');            
        
        jQuery('.focusTooltip').remove();
       
        if (title !== undefined && title.trim() !== ''   ) { 
            jQuery('body').append('<span class="focusTooltip"></span>');
            jQuery('.focusTooltip').attr('data-id', id);
            jQuery('.focusTooltip').text(title);
            // fix for selenium tests #312308
            if( removeTitle && navigator.webdriver != true ) {
                $this.removeAttr('title');
            }
            var rect = element.getBoundingClientRect();
            var thisHeight = $this.outerHeight();
            var highlightFocusOutlineWidth = 0;
            // check for outlines on button. If so, we need to add them to the height to possition the tooltip properly
            if(parseFloat($this.css('outline-width'))>0 && getComputedStyle(element).getPropertyValue('--highlightFocusOutline')) {
                // value of $this.css('outline-width') won't be correct on click and first focus. Probably because of transitions etc., so we are getting the correct outline value directly from the css variable
                // get outline with form css variable, works as long as highlightFocusOutline width is not set to double digit value
                highlightFocusOutlineWidth = parseFloat(getComputedStyle(element).getPropertyValue('--highlightFocusOutline').slice(0,1));
                // to reduce variations because of decimal number in outer height we round up
                thisHeight = Math.ceil(parseFloat(thisHeight)) + highlightFocusOutlineWidth;
            }
            
            jQuery('.focusTooltip').css({
                left: rect.left + 'px',
                top: rect.top + thisHeight + 'px'
            });
    
            if(rect.bottom + thisHeight > (window.innerHeight || document.documentElement.clientHeight)) {
                jQuery('.focusTooltip').css({
                    top: rect.top - jQuery('.focusTooltip').outerHeight() - highlightFocusOutlineWidth + 'px'
                });
            }
    
            var ftWidth = jQuery('.focusTooltip').outerWidth();
            var rightPosition = ftWidth + rect.left;
            var winWidth = jQuery(window).width();
            var newLeftPosition = rect.left - (rightPosition - winWidth);
    
            if (rightPosition >= winWidth) {
                jQuery('.focusTooltip').css({
                    left: newLeftPosition + 'px'
                });
            }
        }
    }
    
    var removeTooltip = function(element) {
        var $this = jQuery(element);
        var title = $this.attr('title');
        if (title === undefined) {
            $this.attr('title', $this.attr('data-title'));
        }
        $this.removeAttr('data-title');
        jQuery('.focusTooltip').remove();
    }
    
   
   
    var hovertooltip = function() {
        var $focusableElements = jQuery('a[title], button[title], li[title], div[title], input[title], img[title], span[title]');
        // :not([type="checkbox"])
      
        $focusableElements.each(function(index, element) {
            //var nestedFocusableElements = element.find('a[title], button[title], li[title], div[title], input[title], img[title], span[title]');
            
            if(element.getAttribute("data-customTooltipInitialized") == null){
                var $this = jQuery(element);
                $this.on('mouseenter', function(e) {
                    // "save" mouse is on element to be able to separate mouse click event from enter/space key while screen reader usage (does not work if mouse is on same element which is used enter or space on) 
                    $this.attr('data-hover', true);
                    setTooltip(element, true);
                }).on('mouseleave',  function(e) {
                    $this.removeAttr('data-hover');
                    removeTooltip(element);
                    //console.log("remove hovertooltip on mouseleave");
                }).on('updateTooltip', function(e) {
                    // check if is Edge and mouse is on same element. updateTooltip is triggered as well if screen reader is used and enter or space key is hit
                    if (/Edg/.test(navigator.userAgent) && !$this.attr('data-hover')) {
                        console.log("no focus tooltip for edge");
                        return;
                    }
                    // check if mouse is on same element and set removeTitle param in dependence on that. Needed because of issues with screen reader using 'click'-event on enter and space
                    setTooltip(element, !!$this.attr('data-hover'));
                });
                element.setAttribute("data-customTooltipInitialized","true");
            }
            
        });
    }
    
    var focustooltip = function() {
        // not for Edge #307939
        if (/Edg/.test(navigator.userAgent)) {
            console.log("no focus tooltip for edge");
            return;
        }
        var $focusableElements = jQuery('a[title], button[title], li[title], div[title], input[title], img[title], span[title]');
    
        $focusableElements.each(function(index, element) {
            if(element.getAttribute("data-customFocusTooltipInitialized") == null){
                var $this = jQuery(element);
                $this.on('keyup', function(e) {
                    var code = e.keyCode || e.which;
                    // menuSearch is also navigatable with up(40) and down(38) cursor keys.
                    if (code == '9' || code == '38' || code == '40') {
                        setTooltip(element);
                    } else if (code == 27) {
                        jQuery('.focusTooltip').remove();
                    }
                }).on('focusout', function(e) {
                    removeTooltip(element);
                });
                
                element.setAttribute("data-customFocusTooltipInitialized","true");
            }
        });

        jQuery(window).on('scroll', function() {
            jQuery('.focusTooltip').remove();
        });
    }
}/**
 * @Author: jgrimm
 */
use_package("de.his.modules");
de.his.modules.HISinOneGallery = new function() {
	de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
	
    this.moduleName = "de.his.modules.HISinOneGallery";
    var intervalId;
    
    this.init = function() {
		jQuery(".hisinone-gallery").each(function() {
			var currentGallery = jQuery(this);
			de.his.modules.HISinOneGallery.initGallery(currentGallery);
		});
    }
    
    this.refresh = function() {
    	de.his.modules.HISinOneGallery.init();
    }
    
    this.initGallery = function(gallery) {
		// init/compute image metadata
		gallery.data("imageCount", 0);
		gallery.children("img").each(function(index) {
			var galleryImage = jQuery(this);
			
			galleryImage.data("index", index);
			
			// set title to filename if not available
			var title = galleryImage.attr("title");
			if (!title) {
				var src = galleryImage.attr("src");
				var srcParts = src.split('/');
				var filename = srcParts[srcParts.length - 1];
				galleryImage.attr("title", filename);
			}
			
			// set alt to title if not available
			var alt = galleryImage.attr("alt");
			if (!alt) {
				galleryImage.attr("alt", galleryImage.attr("title"));
			}
			
			gallery.data("imageCount", gallery.data("imageCount") + 1);
		});
		
		if(!gallery.data("initialized")){
			// init gallery nav and captions
			gallery.append("<div class='hisinone-gallery-nav-caption'>" + de.his.modules.HISinOneGallery.galleryContentMarkup(null, '', null)+ "</div>");
			gallery.append("<div class='hisinone-gallery-nav'><a href='#' class='hisinone-gallery-nav-button hisinone-gallery-nav-last' title='Zurück' alt='Zurück'><span class='unsichtbar'>Zurück</span></a> <a href='#' class='hisinone-gallery-nav-button hisinone-gallery-nav-next' title='Weiter' alt='Weiter'><span class='unsichtbar'>Weiter</span></a></div>");
			
			// register click handlers for navigation
			gallery.find(".hisinone-gallery-nav-last").click(de.his.modules.HISinOneGallery.last);
			gallery.find(".hisinone-gallery-nav-next").click(de.his.modules.HISinOneGallery.next);
			
			// start with image 0
			gallery.data("currentImageIndex", 0);
			de.his.modules.HISinOneGallery.setGalleryImage(gallery, -1, 0);
			
			// start image interval
			var interval = gallery.data("interval");
			if (interval) {
				intervalId = setInterval(function() {
					de.his.modules.HISinOneGallery.changeImage(gallery, 1);
				}, interval);
			}
		}
		gallery.data("initialized", true);
	}
	
	/**
	 * show last image
	 */
	this.last = function() {
		var gallery = jQuery(this).closest(".hisinone-gallery");
		de.his.modules.HISinOneGallery.changeImage(gallery, -1);
		clearInterval(intervalId);
		return false;
	}
	
	/**
	 * show next image
	 */
	this.next = function() {
		var gallery = jQuery(this).closest(".hisinone-gallery");
		de.his.modules.HISinOneGallery.changeImage(gallery, 1);
		clearInterval(intervalId);
		return false;
	}
	
	/**
	 * change image by 'currentIndex + amount' where amount can be positive or negative
	 */
	this.changeImage = function(gallery, amount) {
		if (!amount || amount == 0) {
			return;
		}
		
		var galleryImageCount = gallery.data("imageCount");
		var currentImageIndex = gallery.data("currentImageIndex");
		var nextImageIndex = de.his.modules.HISinOneGallery.getNextImageIndex(galleryImageCount, currentImageIndex, amount);

		de.his.modules.HISinOneGallery.setGalleryImage(gallery, currentImageIndex, nextImageIndex);
	}
	
	/**
	 * compute next image index
	 * @param images number of images
	 * @param current index of current image
	 * @param change amount to change the current index 
	 */
	this.getNextImageIndex = function(images, current, change) {
		var next = current + change;
		while (next < 0) {
			next += images;
		}
		
		return next % images;
	}
	
	/**
	 * changes the image
	 */
	this.setGalleryImage = function(gallery, lastImageIndex, nextImageIndex) {
		// hide previous image
		if (lastImageIndex >= 0) {
			var lastImage = jQuery(gallery.children("img")[lastImageIndex]);
			lastImage.fadeOut();
		}
		
		// show next image
		var nextImage = jQuery(gallery.children("img")[nextImageIndex]);
		nextImage.fadeIn();
		gallery.data("currentImageIndex", nextImageIndex);
		
		// copy link from image to gallery
		var href = nextImage.data("href");
		var title = nextImage.attr("title");
		var alt = nextImage.attr("alt");
		var content = gallery.find(".hisinone-gallery-nav-content");
		content.replaceWith(de.his.modules.HISinOneGallery.galleryContentMarkup(href, title, alt));
		
		// copy image caption
		var caption = nextImage.data("caption");
		var text = gallery.find(".hisinone-gallery-nav-text");
		if (caption) {
			text.fadeIn();
			text.text(caption);
		} else {
			text.fadeOut();
			text.text("");
		}
	}
	
	this.galleryContentMarkup = function(href, title, alt) {
		if (!href) {
			return "<div title='" + title + "' class='hisinone-gallery-nav-content'><span class='hisinone-gallery-nav-text'></span></div>";
		}
		
		return "<a href='" + href + "' title='" + title + "' alt='" + alt + "' class='hisinone-gallery-nav-content' target='_blank'><span class='hisinone-gallery-nav-text'></span></a>";
	}
    
};use_package("de.his.component.sidebar");

de.his.component.sidebar = new function(){
    de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
    this.moduleName = "de.his.component.sidebar";
    var self = this;
    
    this.lastClickedOpenSidebarElementId = "";
    
    this.init = function(){
        handleOpenClick();
        handleCloseClick();
    }
    
    this.refresh = function(){
        self.init();    
    }
    
    var handleOpenClick = function(){
        jQuery("[id$='showSidebar']").click( function(event){
            if( jQuery(this).attr('id').length ) {                
                self.lastClickedOpenSidebarElementId = de.his.common.Util.toJQueryId( jQuery(this).attr('id') );
            } else {
              self.lastClickedOpenSidebarElementId = de.his.common.Util.toJQueryId(de.his.common.ContextInformation.get("active-page-element-id"));
            }
            localStorage.setItem("lastClickedOpenSidebarElementId", self.lastClickedOpenSidebarElementId);
			focusSidebar();
        });
        
    }
    
    var handleCloseClick = function(){
        jQuery("[id*='hideSidebar']").click(function(event){
            event.preventDefault();
            focusLastClickedOpenedElementOnHideSidebar();
        });
    }
    
    // Funktion wird zu oft aufgerufen, verhindern, dass nur einmal pro Klick
    var focusSidebar = function(){
		var sidebarContainers = jQuery(".ui-sidebar");
		// Wenn es mehrere Sidebars innerhalb einer Seite gibt
		if(sidebarContainers.length > 1){
			for(let i = 0; i < sidebarContainers.length; i++){
				var openingButton = localStorage.getItem("lastClickedOpenSidebarElementId");
				if(openingButton.toLocaleLowerCase().includes(sidebarContainers[i].getAttribute("name").toLowerCase())){
					$(sidebarContainers[i]).find('h2').focus();
					break;
				}
			}
		}
		else{
			sidebarContainers.find('h2').focus();
		}
    }
    
    var focusLastClickedOpenedElementOnHideSidebar = function(){
        var lastClickedElementId = localStorage.getItem("lastClickedOpenSidebarElementId");
        if(lastClickedElementId != null && lastClickedElementId != ""){
            jQuery('#' + de.his.common.Util.toJQueryId(lastClickedElementId.replaceAll('\\', ''))).focus();
        
            self.lastClickedOpenSidebarElementId = "";
            localStorage.setItem("lastClickedOpenSidebarElementId", self.lastClickedOpenSidebarElementId);  
        }   
    }
};
/*****************************************************************************
* Include in diesen Datei ändern: layoutHISinOne*.xhtml
*
* portalHelper: Funktionen die von unterschiedlichen Stellen aufgerufen werden
*****************************************************************************/


/**
 * Funktion um Text zu kürzen
 * TODO hier evtl noch ein wenig optimieren
 */
function resizeText(maxLength, str ) {
	if (str == null || maxLength == null || str == "" || maxLength == "" || str.length < 1) {
		return str;
	}
	
	var dummy = document.createElement("div");
	
	dummy.innerHTML = str;
	dummy.style.whiteSpace = "nowrap";
	dummy.style.position = "absolute";
	dummy.style.top = "-100px";
	document.body.appendChild(dummy);
	var breite = dummy.scrollWidth;
	if (breite == null || breite == "" || breite < 0) {
		return str;
	}	
	document.body.removeChild(dummy);
	maxLength -= 110;
	if (breite > maxLength) {
		var newbreite = breite;
		var sicherung = 0;
		while(newbreite > maxLength) {
			str = str.substr(0,str.length - 1)
			var dummy = document.createElement("div");
			dummy.innerHTML = str;
			dummy.style.whiteSpace = "nowrap";
			dummy.style.position = "absolute";
			dummy.style.top = "-100px";
			document.body.appendChild(dummy);
			newbreite = dummy.scrollWidth;
			document.body.removeChild(dummy);
			// Sicherheitsabfrage Schleife beenden
			if (sicherung > 50) {
				break;
			}
			sicherung++;
		}
		return (str + "...");
	} else {
		return	str;		
	}
};

/**
 * Entfernt ein Html-Element mit der übergeben ID aus dem DOM-Baum
 * @param clientId
 */
function removeHtmlElement(clientId) {
	if (clientId == null) {
		return;
	}
	if (document.getElementById(clientId) == null) {
		return;
	}
	document.getElementById(clientId).style.display  = 'none';
}

/**
 * Entfernt ein HTML-Element oder fügt wieder eines hinzu mit einer "coolen" Animation
 * @param clientId
 */
function toggleHtmlElementWithEffect(clientId) {
	if (clientId == null ||clientId == "") {
		return;
	}
	if (document.getElementById(clientId) == null) {
		return;
	}
	if (clientId.indexOf(':')>=0) {
		clientId = de.his.common.Util.toJQueryId(clientId);
	}
	jQuery("#"+clientId).fadeToggle("fast", "linear");
}

/**
 * Fügt ein Html-Element mit der übergeben ID wieder als Block-Element hinzu 
 * @param clientId
 */
function restoreHtmlElement(clientId) {
	if (clientId == null) {
		return;
	}
	if (document.getElementById(clientId) == null) {
		return;
	}
	document.getElementById(clientId).style.display  = 'block';
}

/**
 * Fügt ein Html-Element mit der übergeben ID wieder als Inline-Element hinzu 
 * @param clientId
 */
function restoreHtmlElementInline (clientId) {
	if (clientId == null) {
		return;
	}
	if (document.getElementById(clientId) == null) {
		return;
	}
	document.getElementById(clientId).style.display  = 'inline';
}

/**
 * Schließt die Sidebar/Infobox
 * 
 * @param contextPath
 * @param clientId
 * @param sidebarContentId
 */
function closeSidebar(contextPath, clientId, sidebarContentId) {
	toggleHtmlElementWithEffect(sidebarContentId);	
//	if (renderFixed != "true") {
//		document.getElementById('portalContent').style.width = '99%';
//	}
//	restoreHtmlElement(sidebarContentId);
	
	// Ajax ausführen
	var ajaxToken = getAjaxToken();
	jQuery.ajax( {
		type: 'POST',
		url : contextPath+'/pages/cs/sys/portal/sidebarAjaxReqest.faces',
		data: ({ 
			ajaxToken :ajaxToken, 
			clientId:clientId 
		}),
		error :  function() {
			de.his.ajax.Refresher.onError('Fehler beim Schließen der Sidebar');
		}
	}); 
}

/**
 * Öffnet die Sidebar/Infobox
 * @param contextPath
 * @param clientId
 * @param sidebarContentId
 */
function openSidebar(contextPath, clientId, sidebarContentId) {
//	removeHtmlElement('clipboardWhitoutContent');	
//	if (renderFixed != "true") {
//		document.getElementById('portalContent').style.width = '73%';
//	}
	toggleHtmlElementWithEffect(sidebarContentId);
	
	// Ajax ausführen
	var ajaxToken = getAjaxToken();
	jQuery.ajax( {
		type: 'POST',
		url : contextPath+'/pages/cs/sys/portal/sidebarAjaxReqest.faces',
		data: ({ 
			ajaxToken :ajaxToken, 
			clientId:clientId 
		}),
		error :  function() {
			de.his.ajax.Refresher.onError('Fehler beim Öffnen der Sidebar');
		}
	}); 
}

function resizeIt( $iframe ){
	/**
	 * TODO: refactor to iFramePortletResize.
	 */
	console.log("RESIZE IT "+ $iframe.attr( "id" ));
    var winHeight = jQuery( window ).height(),
        $body,
        $footer,
        top,
        $mainContent,
        height = 0,
        $header,
        $parent = $iframe.parent();

        /**
         * Fälle:
         * 
         * Jeweils für ganzseitige iFrames und iFrame Portlets. (duh!)
         * 
         * 1. Seite auf gleicher Domain, fixierte Header und Footer deaktiviert
         * 2. Seite auf gleicher Domain, fixierte H&F aktiv
         * 3. X-Domain, fixed H&F deaktiviert
         * 4. X-Domain, fixed H&F aktiv
         */
    var resizeFunction = function ($iframe){
		$parent = $iframe.parent();
		// Bei iFrames die Seiten mit der gleichen Domain einbinden, 
    	// die volle Höhe des iFrames ermitteln und als Höhe des parents setzen.
    	// margins und paddings der Kindelemente nicht mit einbeziehen.
		var $content = jQuery( $iframe[ 0 ].contentWindow.document.body );
        if ( $content.length ) {
        	/**
        	 * same-origin iframe
        	 */
        	var	contentHeight = $iframe[ 0 ].contentWindow.document.getElementById('contentFrame').offsetHeight;//getBoundingClientRect().height;//jQuery( $iframe[ 0 ].contentWindow.document).outerHeight(true);
        	
        	if(contentHeight !== $parent.innerHeight()){
        		console.log("content Height of IFrame: "+ contentHeight + " parent:" + $parent.innerHeight());
        		// +2 removes 1px microscrollbars in infobox on mobile
        		$parent.height( 2 + contentHeight );// + childPadding); 
        	}else{
        		console.log("(no resize) content Height of IFrame: "+ contentHeight + " parent:"+ $parent.innerHeight());
        	}
    	} else {
            //needed for safari - doesn't throw an error with cors
            throw new Error();
        }
	}
    try {
		var url = $iframe.attr("src");
		if( ! url.includes('/a/')){
			// JSF Portlets sind fertig gerendert wenn loaded und müssen einmal resized werden.
			resizeFunction($iframe);
		} else {
			// MutationObserver für Angular Portlets, weil Angular beim document.ready noch nicht fertig gerendert ist.
			// siehe auch: https://hiszilla.his.de/hiszilla/show_bug.cgi?id=309092
			//
			// Auch zur dynamischen Anpassung der Größe für JSF Portlets statt postMessage nach ajax-refresh möglich, aber unnötig.
			let lastMutationTimeout;
			
			// timeout Hack um bis zur letzten Mutation keinen resize durch zu führen.
			function handleMutations() {
		        clearTimeout(lastMutationTimeout);

		        lastMutationTimeout = setTimeout(() => {
			        resizeFunction($iframe);
		        }, 50); 
		    }

		    const observer = new MutationObserver(() => {
		        console.log("Mutation detected");
		        handleMutations(); 
		    });
			
			observer.observe($iframe[0].contentWindow.document.getElementById('contentFrame'), { attributes: true, childList: true, subtree:true });
		}
		
    } catch( e ) {
		console.warn('portlet resize error. This is expected only on Safari Browsers.');
    	/**
    	 * wenn fehler fliegt:  x-origin iframe
    	 */
        $footer = jQuery( "#hisinoneFooter" );
        $mainContent = jQuery( "#contentFrame" );
        $header = jQuery( "#hisinoneHeader" );
        $body = jQuery( "body" );
        $title = jQuery( "#hisinoneTitle" );
        $permissionQuery = jQuery( "#askForNotificationPermission" );
        	
        // childrens have paddings and margins that can change when the CSS is changed. 
        // Take them into account.
        childrenPadding = getChildrenPaddingAndMargin($mainContent);
        childrenPadding += getElementPaddingMarginAndBorder(jQuery( ".his_main_content" ));
        childrenPadding += getElementPaddingMarginAndBorder(jQuery( "#clearer" ));
        
    	if($permissionQuery.length && !$permissionQuery.hasClass("unsichtbar")){
    		// wenn Anfrage für push da ist und ganzseitig, höhe dazu nehmen.
    		childrenPadding += $permissionQuery.outerHeight(true)+3;
    	}
            
        childrenPadding += $title.outerHeight(true); // 
        
        bodyHeight = $body.outerHeight();
        
        headerHeight = $header.outerHeight(true);
        
        footerHeight = $footer.outerHeight(true);
        
        contentPaddingMargin = childrenPadding; 
        
        height = bodyHeight - footerHeight - headerHeight - childrenPadding;
        
        console.log("bodyHeight: "+ bodyHeight);
        console.log("headerHeight: "+ headerHeight);
        console.log("footerHeight: "+ footerHeight);
        console.log("contentPaddingMargin: "+ contentPaddingMargin);
        console.log("height: "+ height);
        
        if(height !== $parent.innerHeight()){
        	$parent.height( height );
        }
        
    }
    makeAppleScroll($iframe[ 0 ]);
}

//function resizeIframeOnXDomain(){
//	if( jQuery( "body.fixedLayout" ).length ){
//		
//	}else{
//		
//	}
//}
//
//function resizeIframeOnSameDomain(){
//	if( jQuery( "body.fixedLayout" ).length ){
//		
//	}else{
//		
//	}
//}

function getChildrenPaddingAndMargin(jQueryElement){
	 mainContentChildren = jQueryElement.find("*");
	 
	 // padding und margin vom content div mit einbeziehen.
	 childrenPadding = getElementPaddingMarginAndBorder(jQueryElement);
     mainContentChildren.each(function(){
         if(jQuery(this).is(":hidden") || jQuery(this).hasClass('unsichtbar') || jQuery(this).parents().hasClass('unsichtbar')){
             //do nothing
         }else{
             childrenPadding += getElementPaddingMarginAndBorder(jQuery(this));
         }
     });
     console.log("childrenPadding: "+ childrenPadding);
     return childrenPadding;
}

function getElementPaddingMarginAndBorder(jQueryElement){
	 var bordT = jQueryElement.outerHeight() - jQueryElement.innerHeight();
     var paddT = jQueryElement.innerHeight() - jQueryElement.height();
     var margT = jQueryElement.outerHeight(true) - jQueryElement.outerHeight();
     var paddMargBord = paddT+margT+bordT;
     
     //console.log("child id: #"+ jQueryElement.attr('id'));
//     console.log("child class: ."+ jQueryElement.attr('class'));
//     console.log("padd+marg+bord: "+ paddMargBord);
     
     return paddMargBord;
}

function makeAppleScroll(element){
	// Configure for scrolling peculiarities of iPad and iPhone

	if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1){
		var iFrame = jQuery(element);
		var iframeWrapper = iFrame.parent();
		var iframeWidth = iFrame.width();
		var bodyWidth = jQuery("body").width();
		console.log("makeAppleScroll");
		console.log("iframeWrapper "+iframeWrapper);
		console.log("iframeWidth "+iframeWidth);
		
		var iframeHeight = iFrame.height();
		var bodyHeight = jQuery("body").height();
		console.log("iframeHeight "+iframeHeight);
		
		var lang = de.his.common.LanguageHelper.currentLanguage();
		
		if(jQuery("#appleLinkToIframeSrc").length === 0){
			if(lang==='en'){
				var linkText = "Open embedded site in new window.";
			}
			if(lang==='de'){
				var linkText = "Eingebettete Seite in einem neuen Fenster öffnen.";
			}
			jQuery('#hisinoneIframePage').prepend('<a id="appleLinkToIframeSrc" href="'+iFrame.attr('src')+'" target="_blank">'+linkText+'</a>');
		}
		
		/**
		 * There are no margins and padding on wrapper or iframe that could be taken into account.
		 */
//		var paddWrapper = iframeWrapper.innerWidth() - iframeWrapper.width();
//		var margWrapper = iframeWrapper.outerWidth(true) - iframeWrapper.outerWidth();
//		
//		iframeWrapper.prepend("<div>Wrapper Padding: "+paddWrapper+"px ; Wrapper Margin: "+margWrapper+"px </div>")
//		
//		var paddiFrame = iFrame.innerWidth() - iFrame.width();
//		var margiFrame = iFrame.outerWidth(true) - iFrame.outerWidth();
//		
//		iframeWrapper.prepend("<div>Frame Padding: "+paddiFrame+"px ; Frame Margin: "+margiFrame+"px </div>")
		
		// workaround for fixed Header and Footer
		if( jQuery( "body.fixedLayout" ).length ){
			jQuery(".fixedElements").css('height','auto');
			jQuery(".fixedLayout").css('overflow','auto');
			iframeWrapper.css('overflow','auto');
		}
		// NO change of width... renders iframe portlets ugly... 
		// create a responsive CSS for the child site INSTEAD.
//		if (iframeWidth > bodyWidth){
//			// not quite sure, why these addings (+90 and +120) are needed in some cases, but them do no harm in other scenarios
//			iframeWrapper.css('width',90+iframeWidth + 'px');
//			jQuery("body").css('width',120+iframeWidth + 'px');
//		}
		
		if (iframeHeight > bodyHeight){
			iframeWrapper.css('height',iframeHeight + 'px');
		}
	}
};

/**
 * Berechnet die Höhe eines Elements
 * @param elem
 * @returns Höhe
 */
function getOffsetHeight(elem) {
	if (jQuery(elem) != null && jQuery(elem)[0] != null) {
		return jQuery(elem)[0].offsetHeight;
	}
	return 0;
}

/**
 * Bei fixem Header und Footer den Header berechnen, damit das Navigationsmenü vollständig hinein passt
 */
function resizeHeader() {
//	if(jQuery('#hisinoneHeader').hasClass("header_fixed")){
//		if(jQuery("html.tablet.ios").length){
//			jQuery('.content_portal_hisinone_fixed').css('margin-top', jQuery('#hisinoneHeader').height() + 5  + "px");	
//		}else{
//			jQuery('.content_portal_hisinone_fixed').css('top', jQuery('#hisinoneHeader').height() + "px");	
//		}
//	}
}

/**
 * Hole Ajax Token
 * @returns token
 */
function getAjaxToken() {
	var ajaxToken = document.getElementById("ajaxToken").value;
	return ajaxToken;
}

/**
 * Ein Icon toggeln, also abwechselend das eine und mal das andere anzeigen
 * @param clientId
 * @param img0
 * @param img1
 */
function toggleIcon(clientId, img0, img1) {
	var img = document.getElementById(clientId).src;
	if (img == null) {
		return;
	}
	if (img.endsWith(img0)) {
		document.getElementById(clientId).src = img1;
	} else {
		document.getElementById(clientId).src = img0;
	}
}

/**
 * Icon toggeln, wenn es das Kind-Element eines Links ist
 * @param a
 * @param img0
 * @param img1
 */
function toggleIconAsChild(a, img0, img1) {
	if (a == null) {
		return;
	}
	var clientId = jQuery(a).children('img').attr('id');
	toggleIcon(clientId, img0, img1);
}

/**
 * ??
 * @param elem
 */
function toggleCCDiff(elem) {
	if (elem == null) {
		return;
	}
	jQuery(elem).parent().find(".ccDiff").fadeToggle("fast", "linear");
}

/**
 * Das Navigationsmenü, Breadcrumb, usw. deaktiveren oder aktiveren
 * EXP, wird nicht verwendet
 */
function lockOrUnlockNavigation () {
	//Linkes Menü deaktivieren
	var isLock = false;
	//Topmenü
	var menu = jQuery('.topMenuContainer .flexdropdownmenu');
	if (menu != null) {
		isLock = jQuery('.topMenuContainer').attr('title') != null;
	} else {
		return;
	}
	lockMenu(menu, isLock);
	
	//linkes Menü
	menu = jQuery('#leftTopMenu .auflistung');
	lockMenu(menu, isLock);
	
	//Krümelpfad
	menu = jQuery('.divBreadcrumb a');
	lockMenu(menu, isLock);
	
	if (isLock) {
		//Entsperren 
		unFadeMenu('.topMenuContainer');
		unFadeMenu('#leftTopMenu');
		unFadeMenu('.divBreadcrumb');
	} else {
		//Sperren
		fadeMenu('#leftTopMenu');
		fadeMenu('.topMenuContainer');
		fadeMenu('.divBreadcrumb');
	}
	//Topmenü deaktiveren
	
	//Krümelpfad deaktivieren
}

/**
 * Menü sperren oder entsperren (EXP)
 */
function lockMenu(menu, isLock) {
	if (menu == null) {
		return;
	}
	jQuery.each(menu, function() {
		if (isLock) {
			//Entsperren
			jQuery(this).attr('onclick', '');
		} else {
			//Sperren
			jQuery(this).attr('onclick', 'return false;');
		}
	});
}

/**
 * ???
 * @param clientId
 */
function unFadeMenu(clientId) {
	jQuery(clientId).fadeTo(200,1);
	jQuery(clientId).attr('title',null);
}

/**
 * ???
 * @param clientId
 */
function fadeMenu(clientId) {
	jQuery(clientId).fadeTo(400,0.4);
	jQuery(clientId).attr('title','Dieses Menü wurde gesperrt. Zum entsperren klicken Sie bitte auf den Entsperren-Button oben rechts im Kopfbereich der Seite.');
}

/**
 * Spezielle Bildergalerie in der Infobox-Verwaltung
 */
function showImageOnmouseover() {
//	jQuery(this).css('cssText' , 'padding:5px;');
	jQuery(".picture").hover(function() {
		jQuery(this).css({'z-index' : '10'}); /*Add a higher z-index value so this image stays on top*/ 
		jQuery(this).addClass("hoverImg").stop() /* Add class of "hover", then stop animation queue buildup*/
			.animate({
				marginTop: '-30px', /* The next 4 lines will vertically align this image */ 
				marginLeft: '-30px',
//				top: '100%',
//				left: '100%',
				width: '60px', /* Set new width */
				height: '60px' /* Set new height */
			}, 0); /* this value of "200" is the speed of how fast/slow this hover animates */
		
		} , function() {
		jQuery(this).css({'z-index' : '0'}); /* Set z-index back to 0 */
		jQuery(this).removeClass("hoverImg").stop()  /* Remove the "hover" class , then stop animation queue buildup*/
			.animate({
				marginTop: '0', /* Set alignment back to default */
				marginLeft: '0',
//				top: '0',
//				left: '0',
				width: '23px', /* Set new width */
				height: '23px', /* Set new height */
				padding: '2px'
			}, 0);
		jQuery(this).removeAttr('style');
	});
}

/**
 * ???
 * @param frameId
 */
function xonload2(frameId)
{
	document.getElementById('frameWrapper_' + frameId).className = 'frameWrapper2';
	document.getElementById(frameId).style.visibility = 'visible';
}

/**
 * Alle Buttons quasi deaktieren in dem ihr onclick Event überschrieben wird
 */
function disableAllButtons() {
	jQuery(':submit').attr('onClick', 'return false;');
}
(function($){
    
    var capsLockActive = false;
	var fdsa = document.getElementById("fdsa");
	var text = document.getElementById("capsLockWarning");
	
	if(fdsa == null){
        // return if no login field exists #311009
        return;
    }
	
	var checkCapsLock = function(event) {
		let key = event.key;
		//console.log("key:", key);
		if(key=="Enter"){
			return;
		}
   		if(capsLockActive && key == "CapsLock"){
			// remove warning instantly if capsLock was active and capsLock is pressed
			capsLockActive = false;
		} else if ( typeof event.getModifierState !== 'undefined' && event.getModifierState("CapsLock")) {
            // #311778 getModifierState is undefined when password is filled by (webkit) autofill.
			capsLockActive = true;
		} else {
			capsLockActive = false;
		}
		
		if (capsLockActive) {
			var warningContainer = jQuery("#capsLockWarning");
			var popup = warningContainer.find('button');
			if (popup.length) {
				
				warningContainer.show();
				// setze Fokus zurück auf Passworteingabe wenn popup per click geschlossen wird
				// one (im gegensatz zu on()), löscht den Clickhandler wenn er einmal ausgelöst wurde
				popup.one('click',function(){
					jQuery("#fdsa").focus();
				});
				popup[0].click();
			}
		}else {
            $("#capsLockWarning").hide();
        }
	};
	        
	// keyup to recognize modifier State instantly when tabbing into the passwort field
	fdsa.addEventListener("keyup", checkCapsLock);
	// click to recognize modifier State instantly when mouse clicking into the passwort field
	fdsa.addEventListener("click", checkCapsLock);
	
})(jQuery);use_package("de.his.component.popup");

/**
 * Author: wahrendorff Date: 12.03.2013 Zweck: move popup
 * 
 * Popup:
 * - öffnen: via mouseover oder via click
 * - schließen: via mouseout oder via click auf schließen button.
 * - positionieren: beim öffnen, beim verschieben, bei resize des Fensters
 *
 * - fokussieren: nach dem Schließen den öffnenden Button fokussieren 
 */

de.his.component.popup = new function(){
	de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);
    this.moduleName = "de.his.component.popup";
    var mouseOverClass = "showOnMouseOver";
    var stayOpenProp = "stayOpen";
    
    var self = this;
    
    this.lastClickedOpenPopupElementId = "";
    
    
    this.init = function(){
    	handleOpenClick();
    	handleCloseClick();
    	handleMouseOver();
    }
    
    this.refresh = function(){
		self.init();	
    }
    
    var handleMouseOver = function(){
    	var popupButtons = jQuery("." + mouseOverClass + ":not([data-popup-event-registered=true])").find("> button, > a");
		
		popupButtons.each(function(){
			handleMouseEvents( jQuery( this ) );
		});
    }
    
    var handleOpenClick = function(){
    	jQuery("[id$='showPopup']").click( function(event){
    		// ID des geklickten Buttons holen und zwischenspeichern
    		if( jQuery(this).attr('id').length ) {                
                self.lastClickedOpenPopupElementId = de.his.common.Util.toJQueryId( jQuery(this).attr('id') );
            } else {
		      self.lastClickedOpenPopupElementId = de.his.common.Util.toJQueryId(de.his.common.ContextInformation.get("active-page-element-id"));
            }
			localStorage.setItem("lastClickedOpenPopupElementId", self.lastClickedOpenPopupElementId);		
			
       		event.preventDefault();
    		/*
    		var popup = jQuery(this).parent().parent();
    		var popupContainer = popup.find(".popoverContainer"); //Wenn mehrere Popups im Container sind, dann werden alle gefunden
    		*/ 
    		var popupContainer = jQuery(this).siblings(".popoverContainer");

			// Popup wieder schließen bei Klick auf das Icon
			if( jQuery('#bookmarkForm').find('.popoverContainer').css('display') != 'none' && jQuery(this).parents('#bookmarkForm').length > 0 ) {
				hidePopup(popupContainer);
				return false;
			}

			if( popupContainer.parents().hasClass('jobConfigurationSelector' ) ) {
				correctSize(popupContainer);
			}
    		showPopup(popupContainer);
    		handleDrag(popupContainer);
    		correctPosition(popupContainer, event);
			handleCloseClickBookmark();
			bindFocus(popupContainer);
    		return false;
    	});
     	
    }
    
    var handleCloseClick = function(){
    	//console.log("handleCloseClick");
    	jQuery("[id$='hidePopup'], [id$='backgroundClose']").click(function(event){
    		event.preventDefault();
			var popupContainer = jQuery(this).parents(".popoverContainer");
			//console.log(popupContainer);
			
    		hidePopup(popupContainer);
    		
    		return false;
    	});
    }

	var handleCloseClickBookmark = function(){
		jQuery('body').on('click', function(e){
			if( jQuery('#bookmarkForm').find('.popoverContainer').css('display') != 'none' && jQuery(e.target).parents('#bookmarkForm .popoverContainer').length == 0 ) {
				var popupBookmark = jQuery('#bookmarkForm').find('.popoverContainer');
    			hidePopup(popupBookmark);
			}
		});	
	}

    var handleDrag = function(popupContainer){
    	jQuery("[id$='movePopup']", popupContainer).mousedown(function() {
			jQuery('body').addClass('noMouseSelection');
			de.his.component.popup.Mover.startMove( jQuery(this) );	
		});
    	jQuery("[id$='movePopup']", popupContainer).mouseup(function(){
    		de.his.component.popup.Mover.stopMove();	
    	});
    }
    
    var showPopup = function(popupContainer){
    	popupContainer.show();//removeClass("unsichtbar");
    	//Fokus auf die Überschrift setzen. Funktioniert nur, wenn Überschrift nicht deaktiviert wurde.
    	popupContainer.find('h3').focus();
    	
    }
    
    var bindFocus = function(popupContainer){
		jQuery("[class='focusTrapEnd']", popupContainer).on("focus", function(){
			popupContainer.find('h3').focus();
		});
		
		jQuery("[class='focusTrapFirst']", popupContainer).on("focus", function(){
			popupContainer.find("[id$='hidePopup']").focus();
		});
		
	}
    
    var hidePopup = function(popupContainer){
    	popupContainer.hide();//addClass("unsichtbar");
    	popupContainer.removeProp( stayOpenProp );
    	popupContainer.css( {top: ''});
    	focusLastClickedOpenedElementOnHidePopup();
    }
    
    // Fokussiert den öffnenden Button des Popups nach dem Schließen dieses
    var focusLastClickedOpenedElementOnHidePopup = function(){
    	var lastClickedElementId = localStorage.getItem("lastClickedOpenPopupElementId");
		if(lastClickedElementId != null && lastClickedElementId != ""){
    		jQuery('#' + de.his.common.Util.toJQueryId(lastClickedElementId.replaceAll('\\', ''))).focus();
    	
    		self.lastClickedOpenPopupElementId = "";
    		localStorage.setItem("lastClickedOpenPopupElementId", self.lastClickedOpenPopupElementId);	
    	}	
    }
    
	var handleMouseEvents = function( $it ){
		//console.log("handleMouseEvents start");
		var $cont = $it.parent().find(".popoverContainer");
		//console.log($cont);
		if($cont && $cont.length){
			$it.attr("data-popup-event-registered", true);	//for any ajax requests with call init() again
			$it.on("mouseover", function(event){
				//console.log("mouseover start ", $cont);
				var clickFunc;
				if( $cont.is(":hidden") ){
					//console.log("$cont is hidden");
					clickFunc = function(){
						$cont.prop( stayOpenProp, true);
					};
					var $popCont = $cont.find(".popupContainer");
					showPopup($cont);
					correctPosition($cont,event);
					if( $cont.parent().hasClass("popupDismissable") ){
			    		handleDismissableEvents( $cont );
					}
					$popCont.on("click", clickFunc);
					$popCont.on("mouseleave", function(e){
						//stayOpen property is set if the user clicks anywhere inside the popup
						if(!$cont.prop( stayOpenProp )){
							hidePopup( $cont );
							$popCont.off("click");
							$popCont.off("mouseleave");
						}
					});
				}
			});	
		}
	};
	
	var handleDismissableEvents = function( $popup ){
		//console.log("Dismissable popup id:"+$popup.attr('id'));
		var func = function(event){
				var $target = jQuery( event.target );
				//console.log("click target: ",$target);
				if( !$target.closest(".popoverContainer").length && (typeof $target.attr('id') == 'undefined' || !$target.attr('id').endsWith("poll")) ){
					hidePopup( $popup );
					jQuery( document ).off("click", func);
				}
			};
		jQuery( document ).on("click", func);
	};
	
     var correctPosition = function( popupContainer, event ){
		var left, top;
		if(event.type === "mouseover"){
			left = event.pageX - 30;
			top = event.pageY - 30;
		}
		
		de.his.component.popup.Mover.positionHorizontal( popupContainer, left );
		de.his.component.popup.Mover.positionVertical( popupContainer, top );
	};
	
	var correctSize = function( popupContainer ){
		var newWidth, 
		windowWidth = jQuery(window).width(),
		windowHeight = jQuery(window).height(), 
		scrollPosition = window.pageYOffset;
		
		setTimeout(function(){
			var maxWidth = 0,
			popupLeftpos = popupContainer.position().left;
			
			jobConfigurationListItem = popupContainer.find('.jobConfigurationListItem');
		    jobConfigurationListItem.each(function() {      
				if(jQuery(this).width() > maxWidth) {
		            maxWidth = jQuery(this).width();
		        }
		    });
		    newWidth = maxWidth+30;
		    
		    if( newWidth+popupLeftpos <= windowWidth) {
		    	popupContainer.children('.popupContainer').css({'min-width':newWidth});
			} else { 
				popupContainer.find('.jobConfigurationListItem').children('.quickStartJob').addClass('whiteSpaceNormal'); 
			}
			
			var popupHeight = popupContainer.find('.popupContainer').outerHeight(),
			popupTopOffset = popupContainer.offset().top;
			popupToppos = popupTopOffset-scrollPosition;
			
			var popupPosHeight =  popupHeight+popupToppos;
			
			if( popupPosHeight > windowHeight) {
                var newPosition = scrollPosition -( (popupPosHeight - windowHeight) - popupToppos);
                popupContainer.css( {top: newPosition});
            }   
            if(popupHeight > windowHeight) {
                popupContainer.css( {top: scrollPosition});
            }
			
		},1);
		

		
	};
	
};

de.his.component.popup.Mover = new function() {
	de.his.modules.ModuleRegistry.registerModule(this)
	.registerAjaxRefreshModule(this);
	this.moduleName = "de.his.component.popup.Mover";
	// Globale Variablen:
	// Firebug debug
	var logConsole = false;
	// Mauskoordinaten
	var mouseX;
	var mouseY;
	// Distanz von Maus zum nullpunkt des Popup`s
	var distX;
	var distY;
	// Zu verschiebendes Popup
	var movePopup = null;

	// Bei jeder Mausbewegung werden die Koordinaten in die Globalen Variablen
	// geschrieben und die move() Funktion ausgeführt, wenn das Popup gehalten
	// wird.
	
	this.init = function(){
		
		// Falls kein Popup gehalten wird, muss auch nichts verschoben werden.
		jQuery(document).mouseup(function(e) {
			// reenable selection
			jQuery('body').removeClass('noMouseSelection');
			movePopup = null;
		});
		
		jQuery(document).mousemove(function(e) {
			mouseX = e.pageX;
			mouseY = e.pageY;
			// if(logConsole) console.log("mouseX: " + mouseX + " mouseY: " +
			// mouseY);
			if (movePopup != null){
				//console.log("movePopup",movePopup)
				de.his.component.popup.Mover.move();
			}
				
		});
	}
	
	this.refresh = function(){
		de.his.component.popup.Mover.init();
	}
	
	this.stopMove = function(){
		jQuery('body').removeClass('noMouseSelection');
		movePopup = null;
	}
	
	// brechnet die Distanz von mauszeiger zu popup
	this.startMove = function(element) {
		//console.log("startMOve");
		if (logConsole){
			console.log("MoveId: " + element.attr("id"));
		}
		movePopup = element.parents(".popupContainer");
		if (logConsole){
			console.log("PopupId: " + movePopup.attr("id"));			
		}
		var popupPos = movePopup.position();
		distX = mouseX - popupPos.left;
		distY = mouseY - popupPos.top;
		
	};

	// verschiebt das Popup
	this.move = function() {
		jQuery(movePopup).css("position", "absolute");
		jQuery(movePopup).css("top", mouseY - distY + "px");
		jQuery(movePopup).css("left", mouseX - distX + "px");
	};
	
	/**
	 * @param left {Integer} optional
	 */
	this.positionHorizontal = function(popupPlaceholder, left) {
		/**
		 * DONE: Horizontale Positionierung - get width of viewPort - get width
		 * of popup - get x position of popup - if (x + popupWidth >
		 * viewPortWidth) x = viewPortWidth - popupWidth
		 * 
		 */
		var windowWidth = jQuery(window).width(),
			element = popupPlaceholder.find(".popupContainer"),
			popupWidth = element.outerWidth() + 5,
			position = popupPlaceholder.position(),
			posX = position.left;
		
		if(left){
			posX = left;
		}else{
			left = posX;
		}
		
		console.log("eLEMENTiD=" + popupPlaceholder + " widths: WIN " + windowWidth + " : popW " + popupWidth + " :pos " + posX);
		if (posX + popupWidth > windowWidth) {
			//alert("yes!");
			element.parent().css("left", windowWidth - popupWidth + "px");
		} else{
			element.parent().css("left", left + "px");
		}
	};

	/**
	 * @param top {Integer} optional
	 */
	this.positionVertical = function(popupPlaceholder, top) {
		/**
		 * DONE: Vertikale Positionierung - get height of viewPort - get height
		 * of popup - get y position of popup - if (y + popupHeight >
		 * viewPortHeight) y = viewPortHeight - popupHeight
		 * 
		 */
		var windowHeight = jQuery(window).height(),
			scrollTop = jQuery(window).scrollTop(),
			documentHeight = jQuery(document).height(),
			element = popupPlaceholder.find(".popupContainer"),
			popupHeight = element.outerHeight() + 5, // 5px more corrects // some margin/border// problems
			position = popupPlaceholder.position(),
			posY = position.top;
		console.log("eLEMENTiD=" + popupPlaceholder + " height: WIN "
				+ windowHeight + " : DOC " + documentHeight
				+ " : scrollTop " + scrollTop + " : popH " + popupHeight
				+ " :posY " + posY
				+ "top: "+top);
		
		//element.parent().css("top", windowHeight - popupHeight + scrollTop + "px");
		
		// Wenn fixer Header/Footer aktiviert ist die Positionierung anhand des scrollenden Containers berechnen. 
		if ( element.parents().hasClass('content_portal_hisinone_fixed' ) ) {
			element.parent().css({ top: '' });			
			eltop = element.offset().top;
			containerTop = jQuery('.content_portal_hisinone_fixed').scrollTop();
			top = eltop-containerTop;
		}
		
		if(top){
			console.log("top is set");
			//element.parent().css("top", top + "px");
			if (top + popupHeight > windowHeight + scrollTop) {
				console.log("outer bla");
				element.parent().css("top", windowHeight - popupHeight + scrollTop + "px");
			} else{
				element.parent().css("top", top + "px");
			}
		}else{
			console.log("posY is set");
			if (posY + popupHeight > windowHeight + scrollTop) {
				 //alert("yes!");
				if( !element.parents().hasClass('jobConfigurationSelector' ) ) {
					element.parent().css("top", windowHeight - popupHeight + scrollTop + "px");	
				}
			}
		}
	};
};
use_package("de.his.component.overlay");

/**
 * @Author: wahrendorff Date: 16.01.2013 
 * Zweck: Changes some CSS behaviour of modal Dialogs 
 * - disables/reenables Scolling of body 
 * - corrects height of Dialog on window resize. 
 * - corrects height of content when help is shown
 * - catches Tab for modal function
 * - sets inert on other interative element parents
 * - moves overlay on drag and drop
 */

de.his.component.overlay = new function() {
	
    de.his.modules.ModuleRegistry
    .registerModule(this)
    .registerAjaxRefreshModule(this);
    
    this.moduleName = "de.his.component.overlay";
    
    this.lastOverlayIds = [];
    this.lastClickedOpenOverlayElementIds = [];
    
    var origMarginRight = "0px";
    
    var origMinButtonTitle = null;
    
    var self = this;
    
    this.init = function(){
    	// init wird beim laden der Seite aufgerufen, 
        // synonym für $(document).ready
    	console.log("init overlay");
    	
    	handleOverlayUse();
    	handleResize();
        handleTabKey();
		handleMinButton();
		/*handleTransparency();*/
    };
    
    this.refresh = function(){
    	// refresh wird nach ajaxRefresh Events aufgerufen
    	console.log("init overlay after refresh");
    	
    	unsetInert();
    	handleOverlayUse();
    	handleResize();
    	handleTabKey();
        handleMinButton();
        /*handleTransparency();*/
    };
    /*this.indicateAjaxRequestStart = function(){
		unsetInert();
	}*/
    
    /*var handleTransparency = function(){
		document.querySelectorAll(".overlayMinButton").forEach(function(elem){
			var overlay = elem.closest('.overlay');
			elem.addEventListener('mouseenter', function(){
				overlay.style.opacity = '0';
			}, false);
			elem.addEventListener('mouseleave', function(){
				overlay.style.opacity = '1';
			}, false);
			
		});
		
	}*/
    
    var handleMinButton = function(){
		
		var toggleMinFunc = function(event){
			event.preventDefault();
			
			//disable Tab key until overlay is minimized
			disableTabKey();
			
			let button = event.target;
			console.log('button.tagName:', button.tagName);
			if(button.tagName.toUpperCase() === 'SPAN'){
				button = button.closest('button');
			}
			
			if(origMinButtonTitle === null) {
				origMinButtonTitle = button.dataset.title;
			}
			
			let parentOverlay = button.closest('.overlay');
			//button.classList.toggle('image');
			var toggleReturn = parentOverlay.classList.toggle('minimizedOverlay');
			
			console.log('toggleReturn:', toggleReturn);
			console.log('button:', button);
			console.log('parentOverlay:', parentOverlay);
			
			if (toggleReturn){
				//wurde hinzugefügt
				
				parentOverlay.classList.remove('maximizedOverlay');
				button.title = button.dataset.maxTitle;
				console.log('button.firstChild', button.firstElementChild);
				button.firstElementChild.classList.toggle('iconfont-empty');
				button.firstElementChild.classList.toggle('iconfont-panel_open');
				
				// hide elements in overlay after animation is done.
				setTimeout(function(){
					parentOverlay.querySelectorAll('.overlayContent,.overlaySubTitle,.submit_information,.overlayFooter').forEach(function(elem){
						elem.classList.add('noDisplay');
						setModalFields(jQuery(parentOverlay));
						handleTabKey();
					});
				},500)
				enableScolling();
			} else {		
				// wurde entfernt
				parentOverlay.classList.add('maximizedOverlay');
				button.dataset.title = origMinButtonTitle;
				button.firstElementChild.classList.toggle('iconfont-empty');
				button.firstElementChild.classList.toggle('iconfont-panel_open');
				parentOverlay.querySelectorAll('.overlayContent,.overlaySubTitle,.submit_information,.overlayFooter').forEach(function(elem){
					elem.classList.remove('noDisplay');
					setModalFields(jQuery(parentOverlay));
					handleTabKey();
				})
				disableScolling();
			}
			
			
			return false;
		}
		
		document.querySelectorAll('.overlayMinButton').forEach(function(minButton) {
		    minButton.addEventListener('click', toggleMinFunc, false);
		});
	}
    
    
    var handleDrag = function(overlayElement){
		if(typeof overlayElement == 'undefined' || !overlayElement.draggable){
			// might be undefined when data-infobox-type="Query" is shown upon an overlay
			return;
		}
		var overlayContent = overlayElement.getElementsByClassName('overlayContent')[0];
		var dragStart = function(e) {
			//console.log("target", e.target);
			
			if(!document.getElementById("dragAndDrop_contentCurtain"+overlayElement.id)){
				// create a curtain for the content, because it might not be droppable (iframe, see #331409)
				let div = document.createElement("div");
				div.id = "dragAndDrop_contentCurtain"+overlayElement.id;
				div.style = "position:absolute;height:100%;width:100%;z-index:1100;";
				overlayContent.prepend(div);
			}
			
			
			if( typeof e.target.classList === 'undefined' || !e.target.classList.contains('overlay')){
				// if text selected and accidentally dragged, do not throw error.
				return;
			}
			var style = window.getComputedStyle(e.target, null);
    		e.dataTransfer.setData("text/plain",
    			(parseInt(style.getPropertyValue("left"),10) - e.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - e.clientY));
		}
		var drag = function(e) {
			e.preventDefault(); 
    		return false; 
		}
		var dragEnd = function(e) {
			//overlayContent.classList.remove('noDisplay');
			var offset = e.dataTransfer.getData("text/plain").split(',');
			//console.log("dragEnd offset:",offset,e);
		    overlayElement.style.left = (e.clientX + parseInt(offset[0],10)) + 'px';
		    overlayElement.style.top = (e.clientY + parseInt(offset[1],10)) + 'px';
		    e.preventDefault();
		    return false;
		}
		
		var dragFinal = function(e){
			//console.log("dragFInal!");
			
			// remove curtain when drag ends, even outsite of window
			if(document.getElementById("dragAndDrop_contentCurtain"+overlayElement.id)){
				document.getElementById("dragAndDrop_contentCurtain"+overlayElement.id).remove();
			}
		}
		
		overlayElement.addEventListener('dragstart', dragStart, false);
		document.body.addEventListener('dragover', drag, false);
		document.body.addEventListener('drop', dragEnd, false);
		overlayElement.addEventListener('dragend', dragFinal, false);
		
		// enable text selection in content
		overlayContent.addEventListener('mousedown' , function(e) {
			console.log('mousedown text selection')
			// can't use getElementsByClassName with forEach, because its not an array.
			// 
			let overlays = document.getElementsByClassName('overlay');
			for (var i = 0; i < overlays.length; i++) {
				overlays[i].setAttribute("draggable", "false");
			}
		  	//overlayElement.setAttribute("draggable", "false");
		});
		
		// let the item be draggable again after the text selection is done.
		overlayContent.addEventListener('mouseleave', function(e) {
			console.log('mouseleave text selection')
			let overlays = document.getElementsByClassName('overlay');
			for (var i = 0; i < overlays.length; i++) {
				overlays[i].setAttribute("draggable", "true");
			}
		  	//overlayElement.setAttribute("draggable", "true");
		});
	};
    
    /**
     * Handles Overlays that open via "openOnLoad" set by a flowScope variable or similar.
     * 
     * DONE: Should be able to handle all overlays now. 
     *  * Evaluate to remove direct calls to de.his.component.overlay.disableBodyScroll 
     *  and de.his.component.overlay.enableBodyScroll in overlay.xhtml
     */
    var handleOverlayUse = function(){
        // Button to open overlays shall regain focus after closing the overlay
        jQuery(".overlayShowButton").on('click', function(){
            //console.log("push lastClickedOpenOverlayElementIds",jQuery(this).attr('id'));
            self.lastClickedOpenOverlayElementIds.push(de.his.common.Util.toJQueryId(jQuery(this).attr('id')));
        });
    	if(jQuery('.overlayContainer').length > 0 || jQuery('div[data-infobox-type="Query"]:visible').length > 0){
			// overlay was not closed for any reason (failed validation, browser-refresh etc.) 
    		// or overlay was opened by some other button via openOnLoad
    		// hide scrollbar or it possibly doubles
			var onReady = function( $overlay ){
			    $overlay.ready(function() {
				
					/** Workaround for #290267 
					 FileUpload does not refresh JS*/
					de.his.modules.eventRegistry.addListener("fileUploaded", function(){
						de.his.component.overlay.refresh();
					}, document, true);
					
		            /**
		             * - schauen ob Kindkomponente iFrame, 
		             * - wenn ja, warten bis fertig geladen
		             * - wenn nein, einfach Höhe korrigieren
		             */
			    	disableScolling();
			    	
		            if($overlay.find("iframe").length > 0){
		                //iFrame vorhanden
		                var iFrame = $overlay.find("iframe");
		                jQuery("iframe").on("load", function(){
		                	self.startModalFunction();
		                	correctHeight();
		    		        correctBackgroundHeight();
		    		        correctPosition();
		    		        handleDrag($overlay[0]);
		                });
		            }else{
		            	self.startModalFunction();
		            	correctHeight();
				        correctBackgroundHeight();
				        correctPosition();
				        handleDrag($overlay[0]);
		            }
			    } );
			};
			onReady(jQuery(".overlay.modal:visible").last());
		} else {
			enableScolling();
			de.his.component.overlay.endModalFunction();
		}
    	
    };
    
    var disableScolling = function(){
    	if(isScrollBarActive()){
    		origMarginRight = jQuery("body").css("margin-right");
	    	console.log("margin-right: "+origMarginRight);
	    	
	    	jQuery("body").css("margin-right", getScrollbarWidth()+"px");
	    	jQuery(".overlayContainer").css("padding-right", getScrollbarWidth()+"px");
    	}
    	
    	jQuery("body").css("overflow", "hidden");
    };
    
    var enableScolling = function(){
    	// special case, with fixed header and footer overflow on body is always hidden
		if(!jQuery('body').hasClass('fixedLayout')){
			jQuery("body").css("overflow", "auto");
			jQuery("body").css("margin-right", origMarginRight);
			jQuery(".overlayContainer").css("padding-right","0px");
		}
    };
    
    var isScrollBarActive = function() {
    	return (jQuery("body").get(0).scrollHeight > jQuery("body").height());
    };
    
    var getScrollbarWidth = function() {
    	
		var div, width = getScrollbarWidth.width;
		if (width === undefined) {
			div = document.createElement('div');
			div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
			div = div.firstChild;
			document.body.appendChild(div);
			width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth;
			document.body.removeChild(div);
		}
		return width;
	};
    
    var handleResize = function(){
    	/**
    	 * on resize event
    	 */
    	jQuery(window).resize(function() {
    		correctHeight();
    		correctBackgroundHeight();
    	});
    };
	
	/**
	 * disables the Tab key 
	 */
	var disableTabKey = function(){
		jQuery('.overlay').last().unbind('keydown').bind('keydown',	function(e) {
			e.preventDefault();
		});
	};
    /**
	 * handles tab key trap for overlays and UserQuerys
	 */
	var handleTabKey = function(){
		jQuery('.overlay').last().unbind('keydown').bind	('keydown',	function(e) {
			if (e.keyCode == 9) {
				// 9 is tab key
				if (e.shiftKey) {
					// tab and Shift pressed... do anything here...
					if (jQuery(document.activeElement).attr("firstmodalfield") == "true") {
						e.preventDefault();
						jQuery(this).find("[lastmodalfield=true]").focus();
					}
					return;
				}
				// tab without shift is pressed
				if (jQuery(document.activeElement).attr("lastmodalfield") == "true") {
					e.preventDefault();
					jQuery(this).find("[tabindex='0']").first().focus();
				}
			}
		});
		jQuery('div[data-infobox-type="Query"]:visible').last().bind('keydown',	function(e) {
			//console.log("bind userQuery Tab key.");
			if (e.keyCode == 9) {
				// 9 is tab key
				if (e.shiftKey) {
					// tab and Shift pressed... do anything here...
					if (jQuery(document.activeElement).attr("firstmodalfield") == "true") {
						e.preventDefault();
						jQuery(this).find("[lastmodalfield=true]").focus();
					}
					return;
				}
				// tab without shift is pressed
				if (jQuery(document.activeElement).attr("lastmodalfield") == "true") {
					e.preventDefault();
					jQuery(this).find("[tabindex='0']").first().focus();
				}
			}
		});
	};
	
    /**
     * TODO: Remove from overlay.xhtml and EXA Descendants. Afterwards remove here. 
     * Need to be public, is called in overlay.xhtml
     */
	this.disableBodyScroll = function(data) {
		// Legacy
	};
	
	this.enableBodyScroll = function(data) {
		// Legacy
	};
	
	/**
	 * Setting inert on parents makes containing elements non-interactable.
	 */
	var setInert = this.setInert = function(){
		
		/** set inert für barrierefreie Focus Trap #299063 */
		var overlay = jQuery(".overlay.modal:visible").last();
		// visible messages infoboxes, exclude possible shown debug and log info boxes
		var messagesInfobox = jQuery(".messages-infobox:visible").not(".sys_warning");
		if(messagesInfobox.length > 1) {
            // multiple messages infoboxes are open, save parent container of the infoboxes to check against it later
            messagesInfobox = $(messagesInfobox[0]).parent();
        }
		var loginDiv = jQuery("#sessionTimeoutLoginDiv");
		
		// Legacy workaround for old callbacks
		// focus old callback, when in overlay
		var callBackContainer = jQuery('div[data-infobox-type="Query"]:visible');
		if (callBackContainer.length > 0) {
			overlay = callBackContainer;
			console.log("set inert for callBackContainer", overlay);
		} 
		
		if(loginDiv.is(":visible")){
			overlay = loginDiv;
			console.log("set inert for loginDiv", overlay);
		}
		
		console.log("set inert", overlay[0].id);
		
		/** divs auf oberster ebene die wir erstmal abklemmen können*/
		document.getElementById('hisinoneHeader')?.setAttribute('inert','inert');
		document.getElementById('hisinoneFooter')?.setAttribute('inert','inert');
		document.getElementById('sessionTimeoutLoginDiv')?.setAttribute('inert','inert');
		
		/** legacy userQuerys (und möglicherweise auch manche custom overlays im header) werden in vorher inert gesetzte Bereiche gerendert */
		let overlayInertParent = overlay[0].closest('[inert]');
		if(overlayInertParent !== null){
			console.log("Overlay in inert Parent!",overlayInertParent, overlay);
			overlayInertParent.removeAttribute('inert');
		}
		
		/** suche tabbare Elemente im contentFrame div und setze an deren parents inert */
		// .getElementById('contentFrame')
		document.querySelectorAll("[tabindex], input:not([type=hidden]), button, a, textarea, label, select, details").forEach( function(element,key,parent) {
			/** erkenne ob element parent vom sichtbaren Overlay oder anders herum und spare aus. */
			/** erkenne ob messages-infobox vorhanden und wenn ja, spare diese aus. */
			/** erkenne ob ein parent schon inert hat und spare aus. */
            
            if (!element.parentElement.contains(overlay[0]) && !overlay[0].contains(element) 
                && ( typeof messagesInfobox[0] === 'undefined' || (!element.parentElement.contains(messagesInfobox[0]) && !messagesInfobox[0].contains(element)))
                // inert wurde nicht bereits gesetzt
                && element.closest("[inert]") === null 
                // ist kein typeahead element das immer am Seitenende gerendert wird
                && !element.classList.contains('ui-menu-item-wrapper')
                && !element.classList.contains('ui-selectonemenu-item')
                && !element.classList.contains('ui-selectonemenu-filter')) {
					
				// wenn wir als parent eine form, ein fieldset, eine table, oder liste finden und diese nicht das overlay beinhaltet, 
				// können wir uns ein paar inerts sparen, weil es voraussichtlich interaktive Geschwister gibt.
				let form = element.closest('form');
				let fieldset = element.closest('fieldset');
				let table = element.closest('table');
				let uList = element.closest('ul');
				let oList = element.closest('ol');
				if(form !== null && !form.contains(overlay[0])){
					form.setAttribute('inert','inert');
				} else if(fieldset !== null && !fieldset.contains(overlay[0])){
					fieldset.setAttribute('inert','inert');
				} else if(table !== null && !table.contains(overlay[0])){
					table.setAttribute('inert','inert');
				} else if(uList !== null && !uList.contains(overlay[0])){
					uList.setAttribute('inert','inert');
				} else if(oList !== null && !oList.contains(overlay[0])){
					oList.setAttribute('inert','inert');
				} else{
					 element.parentElement.setAttribute('inert','inert');
				}
				//console.log('set inert',key, element.parentElement);
               
            }
		});
		
	};
	/**
	 * unset inert Attribute
	 */
	var unsetInert = function(){
		/** remove inert #299063 */
		var overlay = jQuery(".overlay.modal:visible").last();
		
		/**
		 * Wenn noch n Overlays vorhanden sind, nur im letzten Overlay inert entfernen
		 */
		if(overlay.length > 0){
			overlay[0].querySelectorAll("*[inert]").forEach( function(element,key,parent) {
				element.removeAttribute('inert');
			});
		} else {
			document.querySelectorAll("*[inert]").forEach( function(element,key,parent) {	   
				//console.log('remove inert '+key, element);
				element.removeAttribute('inert');
			});
		}
	};
	
	/**
	 * control focus in conjunction with de.his.modules.input-refresh.js
	 */
	this.startModalFunction = function(){
		var overlay = jQuery(".overlay.modal:visible").last(),
			inputs,
			last,
			first;
		
		console.log("START Overlay Modal Function",overlay);
		
		// Legacy workaround for old callbacks
		// focus old callback, when in overlay
		var callBackContainer = jQuery('div[data-infobox-type="Query"]:visible');
		if (callBackContainer.length > 0) {
			console.log("Overlay: Callback exists, focus callback");
			overlay = callBackContainer;
		} 
		
		//does modal pop exist
		if(overlay && overlay.length > 0){
			console.log("OVERLAY EXISTS.");			
			de.his.modules.eventRegistry.fireEvent("overlayOpen");
			var focusafterclose = overlay.data('focusafterclose');
			
			// mark first and last interactable element for tab focus trap
			setModalFields(overlay);
			// set Page Markers for Focus Management 
			setPageMarkers();
			
			// check status of overlay and do magic.
			if(self.lastOverlayIds.length > 0 && overlay.attr('id') === self.lastOverlayIds[self.lastOverlayIds.length-1]){
				// immernoch das gleiche Overlay nach ajaxRefresh, lasse input-refresh focus setzen.
				console.log("Overlay: Noch offen! Lasse input-refresh den Fokus setzen! id: ",overlay.attr('id'), self.lastOverlayIds);
				
				//  es gibt Fälle in EXA (die eigentlich nicht auftreten sollten) 
				// in denen ein Overlay durch drücken der Enter Taste mehrfach per ajax geöffnet werden kann. die nacheinander fiolgenden refreshes
				// bringen diese Logik zum straucheln.
				// in diesen Fällen ist der overlay button das aktive Element welches wieder den Fokus bekommt.
				// Lösung: setze den Fokus auf das erste Element im overlay, falls der fokus ausserhalb des sichtbaren overlays liegt
				
				if(jQuery(document.activeElement).closest(".overlayContainer").length==0){
					if(overlay && overlay.length > 0){
						overlay.find("[firstmodalfield='true']").focus();
					}
				}
				
			} else {
				/**
				 * Wenn ein overlay neu geöffnet wurde oder wenn ein ntes overlay geschlossen wird.
				 */
				//console.log("New overlay or nth overlay closed. overlayIDArray:",self.lastOverlayIds);
				if(jQuery('.overlayContainer').length > 0){
					//neues overlay
		    		var overlayId = overlay.closest('[id]').attr('id');

		    		if(self.lastOverlayIds.indexOf(overlayId) === -1){
		    			// neu geöffnetes Overlay
		    			console.log("Neues Overlay: Fokus setzen!", overlayId);
						
		    			// schau nach autofocus objekten, wenn keinne, dann header fokussieren
		    			de.his.modules.Autofocus.setFocusAutomatically('#' + de.his.common.Util.toJQueryId(overlayId));
						var activePageElementId = de.his.common.Util.toJQueryId(de.his.common.ContextInformation.get("active-page-element-id"));
						
						if(activePageElementId !== 'overlayTitleId'){
                            console.log("push lastClickedOpenOverlayElementIds",de.his.common.Util.toJQueryId(de.his.common.ContextInformation.get("active-page-element-id")));
                            self.lastClickedOpenOverlayElementIds.push(de.his.common.Util.toJQueryId(de.his.common.ContextInformation.get("active-page-element-id")));
                        }
						self.lastOverlayIds.push(overlayId);
						
						//console.log("lastClickedOpenOverlayElementIds: ",self.lastClickedOpenOverlayElementIds);
						//console.log("overlayIDArray: ",self.lastOverlayIds);
		    		} else {
		    			// altes, noch geöffnetes Overlay
		    			console.log("Overlay: Wiedererkannt, setze focus auf letzten aktiven Button in diesem Overlay.." )
		    			//console.log("lastClickedOpenOverlayElementIds: ",self.lastClickedOpenOverlayElementIds);
		    			
		    			//console.log("ID: #"+self.lastClickedOpenOverlayElementIds[self.lastClickedOpenOverlayElementIds.length-1]);
						var lastElement = overlay.find("#"+self.lastClickedOpenOverlayElementIds[self.lastClickedOpenOverlayElementIds.length-1]);
						
						if(lastElement){
							console.log("Overlay: Fokus auf letztes betätigtes Element.", lastElement);
							lastElement.focus();
							self.lastClickedOpenOverlayElementIds.pop();
							self.lastOverlayIds.pop();
						}
		    		}
		    		
		    	}
			}
			setInert();
		} 
	};
	
	this.endModalFunction = function(){
		unsetInert();
		// das letzte (bzw. erste von n) overlay wurde gerade geschlossen
		if(self.lastOverlayIds.length > 0){
			
			if(self.lastClickedOpenOverlayElementIds.length > 0){
				// setzt den Fokus auf den letzen öffnen Button beim schließen von verschachtelten Overlays
				console.log("End Overlay Modal Function",self.lastClickedOpenOverlayElementIds);
				// versuche Fokus von vor dem öffnen des ersten Overlays wieder her zu stellen.
				//console.log("lastClickedOpenOverlayElementIds: ",self.lastClickedOpenOverlayElementIds);
				var index = self.lastClickedOpenOverlayElementIds.length-1;
				console.log("End Overlay index",index);
				var lastElementId = self.lastClickedOpenOverlayElementIds[index];
				console.log("End Overlay lastElemntId: #",lastElementId);
				
				if(lastElementId !== ""){
				
					var lastElement = jQuery("#"+self.lastClickedOpenOverlayElementIds[self.lastClickedOpenOverlayElementIds.length-1]);
				
					if(lastElement){
						//console.log("Overlay closed: Fokus auf letztes betätigtes Element.",lastClickedOpenOverlayElementIds);
						lastElement.focus();
						self.lastClickedOpenOverlayElementIds.pop();
					}
				}
			}
			
			// Hilfsvariablen leeren.
			self.lastOverlayIds = [];
			self.lastClickedOpenOverlayElementIds = [];
			
			console.log("Overlay: finished focus handling.",self.lastClickedOpenOverlayElementIds);
			
			//console.log("overlayIDArray: "+self.lastOverlayIds);
			de.his.modules.eventRegistry.fireEvent("overlayClose");
		}
	};

	this.toggleHelp = function(data) {
		//jQuery(".overlayContent").css('top','0px');
		if (data.status != "success") {
			return;
		}
		if (jQuery(".overlayHelp").length == 0) {
            // help is hidden
            jQuery(".overlayContent").css('top','20px');
        } else {
            // help is shown
            jQuery(".overlayContent").css('top','10px');
        }
        correctHeight();
        correctBackgroundHeight();
	};
	
	/**
	 * Marks the first and last selectable element in the docuemtn for trapping the focus as long as an overlay is opened
	 */
	var setPageMarkers = function(){
		jQuery(document).find(':focusable').first().attr("firstfocusableelement", true);
		jQuery(document).find(':focusable').last().attr("lastfocusableelement", true);
	};
	/**
	 * Marks the first and last interactable element in overlay
	 */
	const setModalFields = function(overlay){
		// determine first and last element in modal dialog
		inputs = overlay.find("input:visible,button:visible");	//give all fields the attribute "modal"
		//remove first, needs to be set again when overlay is minimized
		inputs.each(function(index, elem){
			elem.removeAttribute("firstmodalfield");
			elem.removeAttribute("lastmodalfield");
		});
		last = inputs.last();
		if(last){
			last.attr("lastmodalfield", true);
		}
		first = overlay.find("h2[tabindex=0]");
		if(first){
			first.attr("firstmodalfield", true);
		}
	}
	
	/**
	 * @param el = jQuery select elem = jQuery(".myselector")
	 */
	var getTrueHeight = function(el){
		var h = 0;
		
		if(el){
			h = el.outerHeight();	//includes padding - not margins
			h += el.css("margin-top") ? parseInt(el.css("margin-top").replace("px", "")) : 0;
			h += el.css("margin-bottom") ? parseInt(el.css("margin-top").replace("px", "")) : 0;
		}
		
		return h;
	};
	
	var correctBackgroundHeight = function(data) {
		if(jQuery('.overlayContainer').length > 0){
			console.log("correctBackgroundHeight");
			
			jQuery(".overlayBackground").css("height", jQuery(".overlay").outerHeight()+30+"px");
		}
	};
	
	var correctHeight = function(data) {
		
		var overlay = jQuery(".overlay").last();
		//console.log("correctHeight");
		//console.log(overlay);
		if(overlay && overlay.length > 0){
			//console.log("correctHeight2");
			var maxHeight = overlay.css("max-height");
			//console.log("maxHeight: " + maxHeight);
			if(maxHeight){
				if(maxHeight.indexOf("px") >= 0){
					maxHeight = parseInt(maxHeight.replace("px", ""));
				}else if(maxHeight.indexOf("%") >= 0 ){
					//Chrome returns the actual css rather than the calculated value
					var perc = parseInt(maxHeight.replace("%", ""));	//example: 85% -> 85
					var decimal = perc / 100; //85 -> 0.85
					maxHeight = Math.floor(window.innerHeight * decimal);
				}
			}else{
				maxHeight = 300;	//default
			}
			//console.log("maxHeight2: " + maxHeight);
			var headingHeight = getTrueHeight(jQuery(".overlayHeading"));
			var footerHeight = getTrueHeight(jQuery(".overlayFooter"));
			var padding = overlay.css("padding") ? parseInt(overlay.css("padding").replace("px", "")) : 0;
			
			var maxContentHeight = maxHeight - padding - headingHeight - footerHeight;
			
			if(jQuery(".overlayContent > .box_content").height() < maxContentHeight){
				//console.log("height: 100%");
				jQuery(".overlayContent").css("height", "100%");
			}else{
				//console.log("maxContentHeight: " + maxContentHeight);
				jQuery(".overlayContent").css("height", maxContentHeight);
			}
		}
	};
	
	// When the overlay extends to much in both ways, it will be cut on top due to the transform css attribute.
	// In case this happens this method removes the transform
	var correctPosition = function(){
    	if(jQuery(".modal").length > 0){
    		overlayDiv = jQuery(".modal");
    		if(overlayDiv.offset().top < 0){
    			overlayDiv.css("transform","");
    			overlayDiv.css("top","");
    		}
    	}
    };
	
	this.debug = function() {
		var windowHeight = jQuery(window).height();
		var containerHeight = jQuery(".overlay").outerHeight();

		var headingHeight = jQuery(".overlayHeading").outerHeight();
		var footerHeight = jQuery(".overlayFooter").outerHeight();
		var helpHeight = jQuery(".overlayHelp").outerHeight();

		var contentHeight = jQuery(".overlayContent").outerHeight(true);
		var contentScrollHeight = jQuery(".overlayContent")
				.prop("scrollHeight");

		var paddings = containerHeight - contentHeight;

		var maxNewContentHeight = windowHeight - helpHeight - paddings;
        var minNewContentHeight = contentScrollHeight + paddings;
        
        var newContentHeight = windowHeight - helpHeight - paddings;
		//jQuery(".overlayContent").append
		if (jQuery(".debug").length > 0) {
			jQuery(".debug").html(
					"<span class='debug'>" + "windowHeight:" + windowHeight + "; "
							+ "help:" + helpHeight + "; " + "footer:"
							+ footerHeight + "; " + "heading:" + headingHeight
							+ ";<br/> " + "paddings:" + paddings + "; "
							+ "container:" + containerHeight + "; "
							+ "content:" + contentHeight + "; <br/>"
							+ "maxNewContentHeight:" + maxNewContentHeight + "; "
							+ "minNewContetnHeight:" + minNewContentHeight + "; "
							+ "newContentHeight:" + newContentHeight + "; "
							+ "contentScroll:" + contentScrollHeight + "; "
							+ "</span>");
		} else {
			jQuery(".overlayContent").find(".box_content").prepend(
					"<span class='debug'>" + "windowHeight:" + windowHeight + "; "
							+ "help:" + helpHeight + "; " + "footer:"
							+ footerHeight + "; " + "heading:" + headingHeight
							+ ";<br/> " + "paddings:" + paddings + "; "
							+ "container:" + containerHeight + "; "
							+ "content:" + contentHeight + "; <br/>"
							+ "maxNewContentHeight:" + maxNewContentHeight + "; "
                            + "minNewContetnHeight:" + minNewContentHeight + "; "
							+ "newContentHeight:" + newContentHeight + "; "
							+ "contentScroll:" + contentScrollHeight + "; "
							+ "</span>");
		}

	};

};

use_package("de.his.component");

/**
 * Wird durch die messages-infobox-Komponente eingebunden.
 *
 * Setzt die Nachrichten fix mit der Seite verbunden.
 * Sie werden mitgescrollt solange sie im sichtbaren Bereich sind,
 * ansonsten sind sie oben (links, durch austauschen der css-Anweisung
 * unten auch rechts möglich)fest angeordnet.
 *
 *
 */
de.his.component.MessagesInfobox = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
    this.moduleName = "de.his.component.MessagesInfobox";
    var isInitialized = false,
        isFixedHeaderLayout = false,
	    normalTop = 20,
        scrolledTop = 20,
        restoreTop = 20,

        right = 20,
        zIndex = 1300,

        scrollingBase = window;
    
    var body = jQuery('body');
    var mobileBody = jQuery('body.currentDevice_mobile');
    
    this.init = function() {
        initIntern();
        focusMessageInfobox();
    };

    this.refresh = function() {
        initIntern();
        focusMessageInfobox();
    };

	//de.his.component.MessagesInfobox.showMessagesInfoboxWithTitle(messageList, severity, title)
	this.showMessagesInfoboxWithTitle = function(messageList, severity, title){
    	/**
    	 * TODO: replace titles with js context information translated.
    	 */
	    var iconClass = "iconfont-tick"; // checkmark
	    var messageBoxStyleClass = "success";
	    var additionalStyleClass = "auto-closing-box-behavior"; // auto-closing-box-behavior
		
		if(severity == 'info'){
			iconClass = "iconfont-error_mono";
			messageBoxStyleClass = "info";
			additionalStyleClass="";
		}
		
		if(severity == 'warn' || severity == 'warning'){
			severity = 'warn';
			iconClass = "iconfont-warning_mono";
			messageBoxStyleClass = "warning";
			additionalStyleClass=""; 
		}
		
		if(severity == 'error'){
			iconClass = "iconfont-error_mono";
			additionalStyleClass = "";
			messageBoxStyleClass = "error";
			additionalStyleClass="";
		}
		
		var titleEnding = title.charAt(title.length - 1) === ')' ? '' : ':';
		var htmlPart1 = '<div id="messages-infobox:'+severity+'" class="infobox '+messageBoxStyleClass+'_infobox messages-infobox '+additionalStyleClass+'" style=" ">'
		+ '		<div class="messages-infobox-scroll-container">'
		+ '			<span class="messages_infobox_header">'
		+ '				<span title=" " class="'+iconClass+'"></span> '+title + titleEnding
		+ '			</span>'
		+ '			<button id="messages-infobox:'+severity+':button" name="messages-infobox:'+severity+':button" type="submit" onclick="jQuery(\'messages-infobox:'+severity+'\').attr(\'style\', \'transform: scale(0, 0); transition: all 2s ease 0s;\');" title="Schließen (Mit der Escape-Taste können Sie alle Meldungen zusammen schließen.)" style="" class="simple-close-button-behavior submit_image infobox_close">'
		+ '				<span class="iconfont-panel_close"></span>'
		+ '			</button>'
		+ '			<ul class="listMessages">';
		
		var htmlListOfMessages = ''; 
		for(message of messageList){
			htmlListOfMessages += "				<li>" +  de.his.common.Util.escapeHtml(message) + "</li>";
		}
		
		var htmlPart3 = '			</ul>'
		+ '		</div>'
		+ '		<div class="clearerSpaceAboveHalfEm"></div>'
		+ '			<button id="messages-infobox:'+severity+':buttonESC" name="messages-infobox:'+severity+':button" type="submit" onclick="jQuery(\'messages-infobox:'+severity+'\').attr(\'style\', \'transform: scale(0, 0); transition: all 2s ease 0s;\');" title="Schließen (Mit der Escape-Taste können Sie alle Meldungen zusammen schließen.)" style="" class="simple-close-button-behavior closeButtonMessagesESC">'
		+ '				<span>Schließen [ESC]</span>'
		+ '			</button>'
		+ '		</div>'
		+ '	</div>';
    	
    	var html = htmlPart1 + htmlListOfMessages + htmlPart3;
		var contentFrame = jQuery('div[id$="contentFrame"]');
		contentFrame.append("<div class='messages-infobox-behavior' data-maximum-severity='"+severity+"'>"+html+"</div>");
				
		initIntern();
	}

    this.showMessagesInfobox = function(message, severity){
		var titleTranslation = new Map([["success", "Bestätigung"], ["info", "Hinweis"], ["warn", "Warnung"], ["error","Fehler"]]);
		de.his.component.MessagesInfobox.showMessagesInfoboxWithTitle([message], severity, titleTranslation.get(severity));
    }

    var initDefaultValues = function() {
    	if (isInitialized) {
    		return;
    	}
    	isInitialized = true;

    };

    var initIntern = function() {
    	/**
    	 * TODO: Needs redesign maybe - Priority low.
    	 * 
    	 * Was designed to handle only one message-infobox per page.
    	 * Now global functions that create messages from javascript (see this.showMessagesInfobox) 
    	 * 
    	 * Each is a hack that makes it work with more than one message-infobox on one page, 
    	 * but it can lead to strange behaviour when used excessively without reloading the page. 
    	 * (Boxes overlap, instead of aligning beneath.
    	 * 
    	 */
    	
    	jQuery('.messages-infobox-behavior').each(function(){
    		
    	
	        var messagesInfobox = jQuery(this);
	        if (jQuery(messagesInfobox).hasClass('rendered-behavior')) {
	        	jQuery(messagesInfobox).removeClass('rendered-behavior');
	        	return;
	        }
	        
	        // only initialize if element has not been initialized before
	//    	if(messagesInfobox.data('initialized') == 'true'){
	//			//console.log('messagesInfobox already initialized...');
	//			return;
	//		}
	//    	// set element as initialized
	//    	messagesInfobox.data('initialized', 'true');
	        
	        // Sachen, welche immer initialisiert werden müssen
	        initAndResetClickedButtonMark();
	
	        if (messagesInfobox.children().length <= 0) {
	        	return;
	        }
	
	        // Sachen, welche nur benötigt sind, wenn Messages existieren
	        markClickedButton(messagesInfobox);
	
			//Meldungen in IFrames sollen per iFrameCommunication an das parent Fenster gegen werden und dort angezeigt werden. #251815
			/*// wenn Message in iFrame dann soll sie mitscrollen anhand der Scrollbar des Hauptfensters #264425
			if(jQuery('body').hasClass('embedded')) {
				var messageTop = messagesInfobox.offset().top;
				var messageHeight = messagesInfobox.outerHeight();
				messageTop = messageTop+messageHeight;	
				
				var frameId = window.frameElement.id;
				var iFrame = parent.window.document.getElementById(frameId).parentNode;
				var iFrameTop = iFrame.offsetTop;
				
				var scrollFromTop = jQuery(parent.window).scrollTop();
				var messagePos = Math.round(messageTop+iFrameTop);
				var newPos = scrollFromTop-messagePos+messageHeight+parent.window.document.getElementById('hisinoneHeader').clientHeight;
			
				if( messageTop+iFrameTop <= scrollFromTop ) {
					messagesInfobox.css({top:newPos});
					jQuery('.message-infobox-button-wrapper').css({top:newPos});
				}
				jQuery(parent.window).on('scroll', function(){
					scrollFromTop = jQuery(parent.window).scrollTop();			
					newPos = scrollFromTop-messagePos+messageHeight+parent.window.document.getElementById('hisinoneHeader').clientHeight;
					
					if( messagePos-messageHeight <= scrollFromTop ) {
						messagesInfobox.css({top:newPos});
						jQuery('.message-infobox-button-wrapper').css({top:newPos});
					} else {
						messagesInfobox.css({top:''});
						jQuery('.message-infobox-button-wrapper').css({top:''});
					}
				}); 
			} */
	
	        // um die Messages auch rechts anzuordnen hier statt left right setzen:
	        messagesInfobox.css({
	            position:  "fixed",
	            top:       jQuery('#hisinoneHeader').height(),
	            right: "50px",
	            "z-index": zIndex,
	        });
	
	        jQuery('.messages-infobox-behavior > .messages-infobox .simple-close-button-behavior')
	        	.click(function() {
	        		mobileBody.removeClass("bgBlock");
	                jQuery(this)
	                	.closest('.messages-infobox')
	                    .css({
		        			'marginRight': '-300px',
		        			'opacity' : '0',
		        			'transition': 'all 0.5s ease-in'
		        			})
		        			.addClass('hideWhenClosed');
	                
	                setTimeout(enableRestoreHiddenMessages, 800);
	                return false;
	        	}).show();
	
	        jQuery('.messages-infobox-restore-button-behavior').each(function(){
	        	var restoreMessages = jQuery(this);
	        	restoreMessages.parent()
		        .click(function() {
					focusMessageInfobox();
		        	jQuery('.messages-infobox-behavior > .messages-infobox').css({'display': 'block'});
		        	jQuery('.hideWhenClosed').removeClass('hideWhenClosed');
		        	setTimeout(function() {
		        	jQuery('.messages-infobox-behavior > .messages-infobox')
		        		.stop()
		        		.unAutoClosing()
		        		.css({
		        			'marginRight': 0,
		        			'opacity' : '1',
		        			'transition': 'all 0.5s ease-out'
		        			});
		        	}, 0);
		        	restoreMessages.hide();
		        	return false;
		        });
	        });
//	        var restoreMessages = jQuery('.messages-infobox-restore-button-behavior').first().parent()
//		        .click(function() {
//		        	jQuery('.messages-infobox-behavior > .messages-infobox').css({'display': 'block'});
//		        	jQuery('.hideWhenClosed').removeClass('hideWhenClosed');
//		        	setTimeout(function() {
//		        	jQuery('.messages-infobox-behavior > .messages-infobox:not(.info_infobox)')
//		        		.stop()
//		        		.unAutoClosing()
//		        		.css({
//		        			'marginRight': 0,
//		        			'opacity' : '1',
//		        			'transition': 'all 1s ease-out'
//		        			});
//		        	}, 0);
//		        	restoreMessages.hide();
//		        	return false;
//		        });
	        
	        /*
	         * Wenn sich die Seite in einem Iframe befindet und via AJAX (auf mobilem Gerät) Fehler generiert werden,
	         * sollen diese so formatiert werden, dass sie auch bei sehr kleinen Iframes noch lesbar sind. Behebt #160686
	         */
	        var isInIframe = (window.location != window.parent.location) ? true : false;
	        if (isInIframe && window.device.mobile()) {
	        	jQuery('.messages-infobox-behavior').addClass("messages-infobox-behavior-iframe");
	        	jQuery('.messages-infobox').addClass("messages-infobox-iframe");
	        }
	
	        messagesInfobox.fadeIn(1000);
	
	        if(jQuery('.auto-closing-box-behavior').length > 0){
	        	jQuery('.auto-closing-box-behavior').autoClosing({callbackOnHidden : enableRestoreHiddenMessages});
	        }
           
            // Wenn es schon eine Meldung gibt, die Folgende darunter positionieren um Überlappung zu vermeiden.
            if( messagesInfobox.prev('.messages-infobox-behavior').length || messagesInfobox.prev('.messages-infobox-behavior-scroll').length) {
                if( !jQuery('.messages-infobox-behavior-scroll').length ) {
                    messagesInfobox.prev('.messages-infobox-behavior').wrap('<div class="messages-infobox-behavior-scroll"></div>');
                }
                messagesInfobox.prependTo('.messages-infobox-behavior-scroll');
            }
            // Mouseenter von Autoclosing unbinden, es gibt sonst Darstellungsprobleme, wenn mehrere Meldungen sichtbar.
            if(messagesInfobox.parent('.messages-infobox-behavior-scroll').length != 0){
                jQuery('.messages-infobox-behavior > .messages-infobox').off('mouseenter');
            }
	        
    	});
    };

    var enableRestoreHiddenMessages = function() {
    	jQuery('.messages-infobox-behavior > .messages-infobox.hideWhenClosed').css("display", "none");
    	jQuery('.messages-infobox-restore-button-behavior').parent().show();
    	//Der Button selbst erhält ein element style mit display: none, wenn Meldungen via "Bullet" vom Nutzer eingeblendet werden. Dieser muss entfernt werden. 
    	jQuery('.messages-infobox-restore-button-behavior').css("display", "block");
        
        // Wenn mehrere Meldungen vorhanden, einen Counter einbinden.
        if(jQuery('.messages-infobox-behavior').parent('.messages-infobox-behavior-scroll').length != 0){
            var messagesInfoboxLength = jQuery('.messages-infobox-behavior-scroll').find('.messages-infobox.hideWhenClosed').length;
            if( !jQuery('.messages-infobox-counter').length ) {
                jQuery('<div class="messages-infobox-counter"><span>'+parseInt(messagesInfoboxLength)+'</span></div>').appendTo('.message-infobox-button-wrapper');
            } else {
                jQuery('.messages-infobox-counter').addClass('animated').text(parseInt(messagesInfoboxLength));
            }    
            setTimeout(function(){
                jQuery('.messages-infobox-counter').removeClass('animated');
            },500);
        }
        if(jQuery(".messages-infobox.auto-closing-box-behavior").css('display') != 'none'){
        	focusElementOnCloseMessagesInfobox();
        }
    };

    var initAndResetClickedButtonMark = function() {
        jQuery('input[type="submit"],input[type="image"]').not('.messages-infobox-restore-button-behavior').not('.simple-close-button-behavior').click(function() {
            de.his.common.Cookie.create('_clickedButtonId', jQuery(this).attr('id'));
        });

        if ((mobileBody).find(".messages-infobox[data-infobox-type='Error']").length > 0) {
        	mobileBody.addClass("bgBlock");

			var headerHeight = jQuery('#hisinoneHeader').height();
			var viewHeight = jQuery(window).height();
			var msgHeight = viewHeight-headerHeight-15;
        	jQuery(mobileBody).find(".messages-infobox[data-infobox-type='Error']").css({'maxHeight':msgHeight});
        }
        
        else {
        	body.removeClass("bgBlock");
        }
        
        if (!body.data("clickButtonMarkRemover")) {
            body
                .data("clickButtonMarkRemover", true)
                .click(function() {
                    removeClickedButtonMark();
                    // TODO: Auch die Messages bei click und oder keydown entfernen?:
                    //jQuery('.messages-infobox-behavior > .messages-infobox .simple-close-button-behavior').click();
                })
                .keydown(function() {
                    removeClickedButtonMark();
                });
        }

        removeClickedButtonMark();
    };

    var removeClickedButtonMark = function() {
        jQuery('input.highlighted-behavior').each(function() {
            var button = jQuery(this),
                severityStyleClass = button.data('severity-style-class');

            button
                .removeClass('highlighted-behavior')
                .removeClass(severityStyleClass)
                .removeData('severity-style-class');
        });
    };

    var markClickedButton = function(messagesInfobox) {
        var maximumSeverity = messagesInfobox.data('maximum-severity'),
            buttonStyleClass = severityToStyleClass(maximumSeverity),
            clickedButtonId = de.his.common.Cookie.read('_clickedButtonId');

        if (clickedButtonId) {
            var button = jQuery('#' + de.his.common.Util.toJQueryId(clickedButtonId)),
                oldCss = button.css('border');

            button
                .addClass('highlighted-behavior')
                .addClass(buttonStyleClass)
                .data('severity-style-class', buttonStyleClass);

            de.his.common.Cookie.erase('_clickedButtonId');
        }
    };

    var severityToStyleClass = function(severity) {
        switch(severity) {
            case 'error':
            	/* PRODUCTION_REMOVE_BEGIN */
//            	if (Audio) {
//	        		var snd = new Audio("http://dl.dropbox.com/u/25363220/his-test/Shadow_demon_laugh_05.ogg");
//	        		snd.load();
//	        		snd.play();
//            	}
            	/* PRODUCTION_REMOVE_END */
                return 'highlight-error-button';
            case 'warn':
            	/* PRODUCTION_REMOVE_BEGIN */
//            	if (Audio) {
//	        		var snd = new Audio("http://dl.dropbox.com/u/25363220/his-test/Female%20Scream-SoundBible.com-237334261.ogg");
//	        		snd.load();
//	        		snd.play();
//            	}
            	/* PRODUCTION_REMOVE_END */
                return 'highlight-warn-button';
            case 'info':
                return 'highlight-info-button';
            case 'success':
                return 'highlight-success-button';
            default:
                throw new Error("Undefined severity: " + severity);
        }
    };
    
    var focusMessageInfobox = function(){
		if(jQuery(".messages_infobox_header").length > 0){
			setTimeout(function() {
				var lastInfoboxClose = (document.querySelectorAll(".messages-infobox-container button.infobox_close"))[document.querySelectorAll(".messages-infobox-container button.infobox_close").length - 1];
				var lastInfoboxCloseDisplay = window.getComputedStyle(lastInfoboxClose)?.display;
				if((document.querySelectorAll(".messages-infobox-container button.infobox_close")[document.querySelectorAll(".messages-infobox-container button.infobox_close").length - 1]) && lastInfoboxCloseDisplay != "none"){
					(document.querySelectorAll(".messages-infobox-container button.infobox_close")[document.querySelectorAll(".messages-infobox-container button.infobox_close").length - 1]).focus();
				}
				else if((document.querySelectorAll(".messages-infobox-container button.closeButtonMessagesESC")[document.querySelectorAll(".messages-infobox-container button.closeButtonMessagesESC").length - 1])){
					(document.querySelectorAll(".messages-infobox-container button.closeButtonMessagesESC")[document.querySelectorAll(".messages-infobox-container button.closeButtonMessagesESC").length - 1]).focus();
				}
				bindFocus();
				openingInfoboxElement = localStorage.getItem("openingInfoboxElement");
				if(!document.getElementById(openingInfoboxElement)){
					localStorage.setItem("openingInfoboxElement", "");
				}
			}, 50);
		}
	}
	
	var bindFocus = function(){
		jQuery("[class='focusTrapEnd']", jQuery(".messages-infobox")[jQuery(".messages_infobox_header").length - 1]).on("focus", function(){
			jQuery(".messages-infobox .infobox_close")[jQuery(".messages-infobox .infobox_close").length - 1].focus();
		});
		
		jQuery("[class='focusTrapFirst']", jQuery(".messages-infobox")[jQuery(".messages_infobox_header").length - 1]).on("focus", function(){
			jQuery(".messages-infobox .closeButtonMessagesESC")[jQuery(".messages-infobox .closeButtonMessagesESC").length - 1].focus();
		});
	}
	
	var focusElementOnCloseMessagesInfobox = function(){
		// Wenn Fehler auf der Seite vorhanden sind, zuerst diese fokussieren
		var firstErrorField = jQuery(".error"); // .error ist nicht an jedem Eingabefeld vorhanden
		var firstErrortextField = jQuery(".errortext");
		var isErrorHigher = false;
		if(firstErrorField?.position()?.top <= firstErrortextField?.position()?.top){
			isErrorHigher = true;
		}
		if(isErrorHigher && firstErrorField.find(":tabbable").length > 0){
			firstErrorField.find(":tabbable")[0].focus();
			return;
		}	
		if(!isErrorHigher && firstErrortextField.is(":tabbable").length > 0){
			firstErrortextField[0].focus();
			return;
		}
		
		// Ist ein Overlay geöffnet, das Overlay selbst den Fokus setzen lassen
		if(jQuery(".overlay.modal").length > 0 && jQuery(".overlay.modal") != undefined){
			de.his.component.overlay.startModalFunction();
			return;
		}
		
		//  Fokus auf das zuletzt fokussierte Element auf der Seite setzen
		if(localStorage.getItem("openingInfoboxElement") && localStorage.getItem("openingInfoboxElement").length > 0){
			document.getElementById(localStorage.getItem("openingInfoboxElement"))?.focus();
			return;
		}
		de.his.modules.Autofocus.init();
	}
	
	jQuery(".messages-infobox button").click( function(event){
		focusElementOnCloseMessagesInfobox();
	});
	
	jQuery(".messages-infobox-restore-button").click( function(event){
		focusMessageInfobox();
	});

	jQuery("button:not(.infobox_close):not(.closeButtonMessagesESC):not([id$='toggleSearchShowAllCriteria'])").click( function(event){
		var openingInfoboxElement = event.currentTarget.id;
		localStorage.setItem("openingInfoboxElement", openingInfoboxElement);
	});
};
use_package("de.his.component");

/**
 * Wird durch die selectElement-Komponente eingebunden und aktiviert die Autocomplete-Liste.
 */
de.his.component.SelectElement = new function() {
    de.his.modules.ModuleRegistry
        .registerModule(this)
        .registerAjaxRefreshModule(this);
    this.moduleName = "de.his.component.SelectElement";
    
    // autocompleteList can be loaded via REST, but the used searchConfig needs an authority tag for this to work
    const REST_API_URL = de.his.common.ContextInformation.get('context-path') + '/api/v1/cs/sys/genericSearch/loadSearchResult';
    
    var currentInput = "";
    var lastRequestedInput = null;
    
    this.init = function() {
        
        jQuery.widget("ui.autocomplete", jQuery.ui.autocomplete, {
            _renderMenu: function(ul, items) {
                var self = this;
                jQuery.each(items.slice(0, self.options.maxResults), function(index, item) {
                    self._renderItemData(ul, item);
                });
                if (items.length > self.options.maxResults) {
                    var item = {
                        label: "... (" + (items.length - self.options.maxResults) + " " + self.options.moreResultsText + ")",
                        value: undefined
                    };
                    self._renderItemData(ul, item);
                }
            },
            _initSource: function() {
				
				var array;
				if ( $.isArray( this.options.source ) ) {
					
					array = this.options.source;
					this.source = function( request, response ) {
						//console.log("INIT SOURCE ", request.term, array);
						response( de.his.component.SelectElement.filter(array,request.term));
					};
				} else {
					//console.log("NOP INIT SOURCE");
					this.source = this.options.source;
				}
			}
			
        });
        
        $.extend( $.ui.autocomplete, {
			filter: function( array, term ) {
		      return de.his.component.SelectElement.filter(array,request.term);
			}
		} );

        prepareSelects();
            
    };
    
    this.filter = function( array, term ) {
		var values = term.split(' ');
        var searchString = '';
        for ( var i = 0; i < values.length; i++) {
            if (i == values.length - 1) {
                searchString += values[i].trim().replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
            } else {
                searchString += values[i].trim().replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ) + '.+';
            }
        }
		//console.log("AUTOCOMPLETE: "+searchString);
		var matcher = new RegExp( searchString , "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		} );
	}
	
    var prepareSelects = function (){
         jQuery("span.select-element-autocomplete-data-behavior").each(function() {
            var autocompleteData = jQuery(this);
            var inputClientSelector = "#" + de.his.common.Util.toJQueryId(autocompleteData.data('input-client-id')),
                //dataSpanId = autocompleteData.attr('id'),
                valueFromAutocompleteMarkerClientId = autocompleteData.data('value-from-autocomplete-marker-client-id'),
                triggerAfterSelectAction = autocompleteData.data('trigger-after-select-action'),
                afterSelectActionButtonClientId = autocompleteData.data('after-select-action-button-client-id'),
                minLengthOption = autocompleteData.data('autocomplete-min-length') || 3,
                loadViaRest = autocompleteData.data('load-via-rest') || false,
                moreResultsText = autocompleteData.data('autocomplete-more-results-text') || "weiter(e) Element(e)";
                
            /*if(jQuery(inputClientSelector).data('initialized')==='true'){
                console.log("nothing to do.");
                return;
            }*/
            
            // only initialize if element has not been initialized before
            if(autocompleteData.data("initialized") === "true"){
                console.log("autocompleteList already initialized");
            } else {
                var timer = 0;
                var delay = function(fn, ms) {
                    
                    return function(...args) {
                        clearTimeout(timer)
                        timer = setTimeout(fn.bind(this, ...args), ms || 0)
                    }
                };
                
                jQuery(inputClientSelector).keyup(delay(function(evt){
                    // keyup listener loads the autocomplete list after typing stopps for 300ms 
                    var keyCode = evt.key || evt.which ;
                    //console.log("keyup event from autocomplete:", keyCode);
                    //console.log("keyup event from autocomplete:", evt.key);
                    
                    // do not load autocomplete on Tabbing.
                    // && keyCode!=="Tab" && keyCode!="9"
                    // check if used key is ArrowDown or ArrowUp because they are needed to navigate through the options and should not refresh the list. Fix #301119
                    const navigationKeyIsUsed = ["ArrowDown","ArrowUp", 38, 40].includes(keyCode);
                    if(jQuery(inputClientSelector).val().length >= minLengthOption) { 
                        if(loadViaRest === 'true'){
                            loadAutocompleteListFromRest(autocompleteData);
                        }else{
                            // pass navigationKeyIsUsed to prevent from refreshing autocompleteList when using up and down arrow in open list. Fix #301119
                            loadAutocompleteFromJSF(autocompleteData, navigationKeyIsUsed);
                        }
                     }
                },300));
                
                var refreshAutocompleteList = function(){
                    var arrayList =  jQuery(inputClientSelector).siblings("div.autocompleteListAjax").data('autocomplete-list');
                    //console.log("autocomplete list after refresherSuccess", arrayList);
                    if(arrayList.length > 0){
                        initAutocomplete(autocompleteData,arrayList);
                    }
                };
                
                jQuery(inputClientSelector).on('focus', function(evt){
                    // add listener for refresh on focus
                    // listener will be revoked by input-refresh focus after refresherSuccess, so destroy autocatically after one hit.
                    de.his.modules.eventRegistry.addListener('refresherSuccess', refreshAutocompleteList, inputClientSelector, true);
                    if(typeof jQuery(inputClientSelector).autocomplete( "instance" ) !== 'undefined'){
                        // enable autocomplete list, it might got disabled after blur
                        jQuery(inputClientSelector).autocomplete( "enable" );
                    }
                    
                });
                
                jQuery(inputClientSelector).on('blur', function(evt){
                    //clear any pending keyup timeout
                    clearTimeout(timer);
                    // remove Listener on blur
                    de.his.modules.eventRegistry.destroyListener(refreshAutocompleteList);
                    // disable and close autocmomplete list on blur
                    if(typeof jQuery(inputClientSelector).autocomplete( "instance" ) !== 'undefined'){
                        jQuery(inputClientSelector).autocomplete( "disable" );
                        jQuery(inputClientSelector).autocomplete( "close" );
                    }
                    // remove list from dom on blur
                    destroyAutocompleteList(autocompleteData);
                });
                
                if(jQuery(inputClientSelector).is(":focus")){
                    // if select input has initial focus before the script loads
                    de.his.modules.eventRegistry.addListener('refresherSuccess', refreshAutocompleteList);
                }      
                
                autocompleteData.data("initialized","true");
            }

        });
    };
    
    var initAutocomplete = function(autocompleteData, autoCompleteList){
        var inputClientSelector = "#" + de.his.common.Util.toJQueryId(autocompleteData.data('input-client-id')),
            //dataSpanId = autocompleteData.attr('id'),
            valueFromAutocompleteMarkerClientId = autocompleteData.data('value-from-autocomplete-marker-client-id'),
            triggerAfterSelectAction = autocompleteData.data('trigger-after-select-action'),
            afterSelectActionButtonClientId = autocompleteData.data('after-select-action-button-client-id'),
            minLengthOption = autocompleteData.data('autocomplete-min-length') || 3,
            maxResultsOption = autocompleteData.data('autocomplete-max-results') || 100,
            moreResultsText = autocompleteData.data('autocomplete-more-results-text') || "weiter(e) Element(e)";
            
            /**
            *DONE:
                prüfe ob initialisiert, 
                - wenn ja, ändere option source
                - wenn nein, initialisiere und suche.       
            */
            //console.log("autoCompleteList", autoCompleteList);
        if(typeof jQuery(inputClientSelector).autocomplete( "instance" ) !== 'undefined'){
            jQuery(inputClientSelector).autocomplete( "option", "source", autoCompleteList ).autocomplete( "search" );
            //jQuery(inputClientSelector).autocomplete( "search" );
        }else{
            jQuery(inputClientSelector).autocomplete({
                minLength: 1, // minlength is controlled by loading mechanism 
                maxResults: maxResultsOption,
                moreResultsText: moreResultsText,
                source: autoCompleteList,
                select: function(event, ui) {
                    if (typeof ui.item !== 'undefined' && typeof ui.item.value !== 'undefined') {
                        if (valueFromAutocompleteMarkerClientId) {
                            document.getElementById(valueFromAutocompleteMarkerClientId).value = 'true';
                        }
                        if (triggerAfterSelectAction) {
                            setTimeout(function() {
                                document.getElementById(afterSelectActionButtonClientId).click();
                            }, 100);
                        }
                    }
                }
            }).autocomplete( "search" );
        }
        
        //jQuery(inputClientSelector).data('initialized','true');
        
    }
    
    var destroyAutocompleteList = function(autocompleteData){
        //console.log('destroy autocompleteList.');
        var inputClientSelector = "#" + de.his.common.Util.toJQueryId(autocompleteData.data('input-client-id'));
        jQuery(inputClientSelector).siblings("div.autocompleteListAjax").attr('data-autocomplete-list','[]');
        //jQuery(inputClientSelector).autocomplete( "destroy" );
        //autocompleteData.data('initialized','false');
    }

	var loadAutocompleteFromJSF = function(autocompleteData, navigationKeyIsUsed){
        var inputClientSelector = "#" + de.his.common.Util.toJQueryId(autocompleteData.data('input-client-id')),
            searchConfigFile = autocompleteData.data('search-config-file'),
            searchEntity = autocompleteData.data('search-entity'),
            searchFieldname = autocompleteData.data('search-fieldname');
            useUniquenameForAutocompleteList = autocompleteData.data('use-uniquename-for-autocomplete-list');
            
        let autocompleteList = jQuery(inputClientSelector).siblings("div.autocompleteListAjax").data('autocomplete-list');
        currentInput = jQuery(inputClientSelector).val();
        //console.log("refresh autocomplete List currentInput",currentInput);
        //console.log("refresh autocomplete List lastRequestedInput",lastRequestedInput);
        
        var navigatingInOpenList = false;
        if(navigationKeyIsUsed) {
            // Check if there is a list already open. Fix #301119
            var openAutocompleteLists = jQuery('.ui-autocomplete').not(function() { 
                return $(this).css('display') == 'none'; 
            }); 
            navigatingInOpenList = openAutocompleteLists.length > 0;
        }        
        // Prevent from refreshing while using up and down arrow while list is open. Fix #301119
        if( !navigatingInOpenList && ( 
            !currentInput.startsWith(lastRequestedInput) 
            || autocompleteList.length > 500 || autocompleteList.length == 0  
            || lastRequestedInput == null || (currentInput.startsWith(lastRequestedInput) && lastRequestedInput.length < 3) )) {
            console.log("DO refresh autocomplete List ");
            lastRequestedInput = currentInput;
            jQuery(inputClientSelector).siblings("button.loadAutocompleteListBtn").click();
        } else {
            console.log("no need to refresh autocompleteList");
        }
        
    }

    // is not implemented atm, but works in general, keep for reference
    var loadAutocompleteListFromRest = function(autocompleteData){
        
        var inputClientSelector = "#" + de.his.common.Util.toJQueryId(autocompleteData.data('input-client-id')),
            searchConfigFile = autocompleteData.data('search-config-file'),
            searchEntity = autocompleteData.data('search-entity'),
            searchFieldname = autocompleteData.data('search-fieldname');
            useUniquenameForAutocompleteList = autocompleteData.data('use-uniquename-for-autocomplete-list');
            
       /* if(jQuery(inputClientSelector).data('initialized')==='true'){
            return;
        }*/
        
        /**
     * DONE:
        build a REST Client for /cs/sys/genericSearch/loadSearchResult

        Hint: GenericSearch can not filter over concatinated hidden fields. It's not implemented. 
            So we set a limit to 10 000 for more than good measure.
     */
        if(searchFieldname == "searchfield" ){
            searchFieldname = "defaulttext";
        } else if( useUniquenameForAutocompleteList){
            searchFieldname = "uniquename";
        }
        
        var jsonData = {
            "search": {
                "groups": [
                    {
                        "criteria":[{"field":searchFieldname,"value":jQuery(inputClientSelector).val()}],
                        "criteriaGroups":[],
                        "groupLabel": ""
                    }
                ],
                "configFile": searchConfigFile
            },
            "offset":0,
            "limit":10000 // REST genericSearch does not filter, so we need to get all results.
        };
        //console.log("autocomplete search=", jsonData);
        
        jQuery.ajax({
            url: REST_API_URL,
            method: 'POST',
            dataType: 'json',
            data: JSON.stringify(jsonData),
            processData: false,
            contentType: 'application/json',
            async: true,
            success: function(json, textStatus, xhr) {
                //console.log("autocomplete searchFieldname", searchFieldname);
                //console.log("autocomplete json: ", json);
                
                let index = json.columns.findIndex( element => {
                    if (element.id === searchFieldname) {
                        return true;
                    }
                });
                
                //console.log("autocomplete index", index)
                var arrayList = [];
                json.data.forEach((item) => {
                    //console.log('autocomplete selectItem: ',item);
                    // RESTController does not respect name as id in the result set, 
                    // so searchfield is somethimes not in the result
                    // take last index in that case and hope for the best
                    if(index == -1){
                        arrayList.push(item[item.length-1]);
                    } else {
                        arrayList.push(item[index]);
                    }
                    
                });
                //console.log('autocomplete selectList: ', arrayList);
                
                initAutocomplete(autocompleteData,arrayList);
            },
            error: function(err) {
                // Zeige entsprechnde Fehlermeldung, wenn 403 auf missing authorities hinweist.
                console.error("autocomplete REST ERROR: ", err);
                if(err.status == 403) {
                    de.his.component.MessagesInfobox.showMessagesInfobox(err.status+" not authorized: "+searchConfigFile+" add authorities element with valid rights to search config.", "error");
                }
                
            }
        });

    }

    this.refresh = function() {
       prepareSelects();
    };
};use_package("de.his.component");
/**
 * Scrollt zum Anfang der Seite
 */
de.his.component.ScrollToLink = new function() {
    de.his.modules.ModuleRegistry.registerModule(this).registerAjaxRefreshModule(this);;
    this.moduleName = "de.his.components.ScrollToLink";
    this.init = function() {
        
            jQuery('a.scrollToLink').on('click', function(event){
                //console.log("targetid", jQuery(this).data('targetid'));
                scrollTo(jQuery(this).data('targetid'));
            });
            jQuery('a.scrollToLink').on('keydown', function(event){
               // console.log("targetid", jQuery(this).data('targetid'));
               // Enter and Space
               if(event.which === 13){
				   var targetId = jQuery(this).data('targetid');
				   scrollTo(targetId);
			   }
            });
    };
    this.refresh = function(){
        this.init();
    };
    
    var scrollTo = function(targetId){
		console.log("targetid", targetId);
		
		
		
		if(jQuery('.header_fixed').length){
			document.getElementsByClassName("his_main_content")[0].scroll(0,findPos(document.getElementById(targetId)));
		} else {
			document.getElementById(targetId).scrollIntoView();
		}
		// focus Element, set tabindex, since they dont know how browser native Anchors work and 
		// they want to scrollTo and focus any element, not just anchors, they also scrollTo spans and divs via id. 
		document.getElementById(targetId).setAttribute('tabindex','-1');
		document.getElementById(targetId).focus();
		
	}
    
    var findPos = function (obj) {
        var curtop = 0;
        if (obj.offsetParent) {
            do {
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
            return [curtop];
        };
    };
};