
/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:s,sort:n.sort,splice:n.splice},w.extend=w.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||g(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)n=a[t],a!==(r=e[t])&&(l&&r&&(w.isPlainObject(r)||(i=Array.isArray(r)))?(i?(i=!1,o=n&&Array.isArray(n)?n:[]):o=n&&w.isPlainObject(n)?n:{},a[t]=w.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},w.extend({expando:"jQuery"+("3.3.1"+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==c.call(e))&&(!(t=i(e))||"function"==typeof(n=f.call(t,"constructor")&&t.constructor)&&p.call(n)===d)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e){m(e)},each:function(e,t){var n,r=0;if(C(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(C(Object(e))?w.merge(n,"string"==typeof e?[e]:e):s.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:u.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;o<a;o++)(r=!t(e[o],o))!==s&&i.push(e[o]);return i},map:function(e,t,n){var r,i,o=0,s=[];if(C(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&s.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&s.push(i);return a.apply([],s)},guid:1,support:h}),"function"==typeof Symbol&&(w.fn[Symbol.iterator]=n[Symbol.iterator]),w.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function C(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!g(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",I="\\["+M+"*("+R+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+R+"))|)"+M+"*\\]",W=":("+R+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+I+")*)|.*)\\)|)",$=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),F=new RegExp("^"+M+"*,"+M+"*"),_=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},G=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){p()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{L.apply(A=H.call(w.childNodes),w.childNodes),A[w.childNodes.length].nodeType}catch(e){L={apply:A.length?function(e,t){q.apply(e,H.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,s,l,c,f,h,v,m=t&&t.ownerDocument,T=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==T&&9!==T&&11!==T)return r;if(!i&&((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,g)){if(11!==T&&(f=J.exec(e)))if(o=f[1]){if(9===T){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&x(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return L.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return L.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!y||!y.test(e))){if(1!==T)m=t,v=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=b),s=(h=a(e)).length;while(s--)h[s]="#"+c+" "+ve(h[s]);v=h.join(","),m=K.test(e)&&ge(t.parentNode)||t}if(v)try{return L.apply(r,m.querySelectorAll(v)),r}catch(e){}finally{c===b&&t.removeAttribute("id")}}}return u(e.replace(B,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function se(e){return e[b]=!0,e}function ue(e){var t=d.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return se(function(t){return t=+t,se(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},p=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==d&&9===a.nodeType&&a.documentElement?(d=a,h=d.documentElement,g=!o(d),w!==d&&(i=d.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=ue(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ue(function(e){return e.appendChild(d.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(d.getElementsByClassName),n.getById=ue(function(e){return h.appendChild(e).id=b,!d.getElementsByName||!d.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},v=[],y=[],(n.qsa=Q.test(d.querySelectorAll))&&(ue(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||y.push("~="),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||y.push(".#.+[+~]")}),ue(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=d.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(n.matchesSelector=Q.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ue(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),v.push("!=",W)}),y=y.length&&new RegExp(y.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),x=t||Q.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===d||e.ownerDocument===w&&x(w,e)?-1:t===d||t.ownerDocument===w&&x(w,t)?1:c?O(c,e)-O(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===d?-1:t===d?1:i?-1:o?1:c?O(c,e)-O(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?ce(a[r],s[r]):a[r]===w?-1:s[r]===w?1:0},d):d},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(z,"='$1']"),n.matchesSelector&&g&&!S[t+" "]&&(!v||!v.test(t))&&(!y||!y.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,d,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),x(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==d&&p(e);var i=r.attrHandle[t.toLowerCase()],o=i&&N.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(D),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:se,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace($," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",y=t.parentNode,v=s&&t.nodeName.toLowerCase(),m=!u&&!s,x=!1;if(y){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?y.firstChild:y.lastChild],a&&m){x=(d=(l=(c=(f=(p=y)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1])&&l[2],p=d&&y.childNodes[d];while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if(1===p.nodeType&&++x&&p===t){c[e]=[T,d,x];break}}else if(m&&(x=d=(l=(c=(f=(p=t)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1]),!1===x)while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++x&&(m&&((c=(f=p[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]=[T,x]),p===t))break;return(x-=i)===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?se(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=O(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:se(function(e){var t=[],n=[],r=s(e.replace(B,"$1"));return r[b]?se(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:se(function(e){return function(t){return oe(e,t).length>0}}),contains:se(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:se(function(e){return U.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=fe(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=pe(t);function ye(){}ye.prototype=r.filters=r.pseudos,r.setFilters=new ye,a=oe.tokenize=function(e,t){var n,i,o,a,s,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=r.preFilter;while(s){n&&!(i=F.exec(s))||(i&&(s=s.slice(i[0].length)||s),u.push(o=[])),n=!1,(i=_.exec(s))&&(n=i.shift(),o.push({value:n,type:i[0].replace(B," ")}),s=s.slice(n.length));for(a in r.filter)!(i=V[a].exec(s))||l[a]&&!(i=l[a](i))||(n=i.shift(),o.push({value:n,type:a,matches:i}),s=s.slice(n.length));if(!n)break}return t?s.length:s?oe.error(e):k(e,u).slice(0)};function ve(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function me(e,t,n){var r=t.dir,i=t.next,o=i||r,a=n&&"parentNode"===o,s=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||a)return e(t,n,i);return!1}:function(t,n,u){var l,c,f,p=[T,s];if(u){while(t=t[r])if((1===t.nodeType||a)&&e(t,n,u))return!0}else while(t=t[r])if(1===t.nodeType||a)if(f=t[b]||(t[b]={}),c=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((l=c[o])&&l[0]===T&&l[1]===s)return p[2]=l[2];if(c[o]=p,p[2]=e(t,n,u))return!0}return!1}}function xe(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)oe(e,t[r],n);return n}function we(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Te(e,t,n,r,i,o){return r&&!r[b]&&(r=Te(r)),i&&!i[b]&&(i=Te(i,o)),se(function(o,a,s,u){var l,c,f,p=[],d=[],h=a.length,g=o||be(t||"*",s.nodeType?[s]:s,[]),y=!e||!o&&t?g:we(g,p,e,s,u),v=n?i||(o?e:h||r)?[]:a:y;if(n&&n(y,v,s,u),r){l=we(v,d),r(l,[],s,u),c=l.length;while(c--)(f=l[c])&&(v[d[c]]=!(y[d[c]]=f))}if(o){if(i||e){if(i){l=[],c=v.length;while(c--)(f=v[c])&&l.push(y[c]=f);i(null,v=[],l,u)}c=v.length;while(c--)(f=v[c])&&(l=i?O(o,f):p[c])>-1&&(o[l]=!(a[l]=f))}}else v=we(v===a?v.splice(h,v.length):v),i?i(null,a,v,u):L.apply(a,v)})}function Ce(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],s=a||r.relative[" "],u=a?1:0,c=me(function(e){return e===t},s,!0),f=me(function(e){return O(t,e)>-1},s,!0),p=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];u<o;u++)if(n=r.relative[e[u].type])p=[me(xe(p),n)];else{if((n=r.filter[e[u].type].apply(null,e[u].matches))[b]){for(i=++u;i<o;i++)if(r.relative[e[i].type])break;return Te(u>1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u<i&&Ce(e.slice(u,i)),i<o&&Ce(e=e.slice(i)),i<o&&ve(e))}p.push(n)}return xe(p)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,a,s,u,c){var f,h,y,v=0,m="0",x=o&&[],b=[],w=l,C=o||i&&r.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,k=C.length;for(c&&(l=a===d||a||c);m!==k&&null!=(f=C[m]);m++){if(i&&f){h=0,a||f.ownerDocument===d||(p(f),s=!g);while(y=e[h++])if(y(f,a||d,s)){u.push(f);break}c&&(T=E)}n&&((f=!y&&f)&&v--,o&&x.push(f))}if(v+=m,n&&m!==v){h=0;while(y=t[h++])y(x,b,a,s);if(o){if(v>0)while(m--)x[m]||b[m]||(b[m]=j.call(u));b=we(b)}L.apply(u,b),c&&!o&&b.length>0&&v+t.length>1&&oe.uniqueSort(u)}return c&&(T=E,l=w),x};return n?se(o):o}return s=oe.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},u=oe.select=function(e,t,n,i){var o,u,l,c,f,p="function"==typeof e&&e,d=!i&&a(e=p.selector||e);if(n=n||[],1===d.length){if((u=d[0]=d[0].slice(0)).length>2&&"ID"===(l=u[0]).type&&9===t.nodeType&&g&&r.relative[u[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;p&&(t=t.parentNode),e=e.slice(u.shift().value.length)}o=V.needsContext.test(e)?0:u.length;while(o--){if(l=u[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),K.test(u[0].type)&&ge(t.parentNode)||t))){if(u.splice(o,1),!(e=i.length&&ve(u)))return L.apply(n,i),n;break}}}return(p||s(e,d))(i,t,!g,n,!t||K.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(D).join("")===b,n.detectDuplicates=!!f,p(),n.sortDetached=ue(function(e){return 1&e.compareDocumentPosition(d.createElement("fieldset"))}),ue(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ue(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ue(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var k=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},D=w.expr.match.needsContext;function N(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var A=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return u.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t<r;t++)if(w.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)w.find(e,i[t],n);return r>1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&D.test(e)?w(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:L.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),A.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,q=w(r);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(w.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&w(e);if(!D.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?u.call(w(e),this[0]):u.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return k(e,"parentNode")},parentsUntil:function(e,t,n){return k(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return k(e,"nextSibling")},prevAll:function(e){return k(e,"previousSibling")},nextUntil:function(e,t,n){return k(e,"nextSibling",n)},prevUntil:function(e,t,n){return k(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return N(e,"iframe")?e.contentDocument:(N(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(O[e]||w.uniqueSort(i),H.test(e)&&i.reverse()),this.pushStack(i)}});var M=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(M)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],s=-1,u=function(){for(i=i||e.once,r=t=!0;a.length;s=-1){n=a.shift();while(++s<o.length)!1===o[s].apply(n[0],n[1])&&e.stopOnFalse&&(s=o.length,n=!1)}e.memory||(n=!1),t=!1,i&&(o=n?[]:"")},l={add:function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){w.each(n,function(n,r){g(r)?e.unique&&l.has(r)||o.push(r):r&&r.length&&"string"!==x(r)&&t(r)})}(arguments),n&&!t&&u()),this},remove:function(){return w.each(arguments,function(e,t){var n;while((n=w.inArray(t,o,n))>-1)o.splice(n,1),n<=s&&s--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||u()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function I(e){return e}function W(e){throw e}function $(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var s=this,u=arguments,l=function(){var e,l;if(!(t<o)){if((e=r.apply(s,u))===n.promise())throw new TypeError("Thenable self-resolution");l=e&&("object"==typeof e||"function"==typeof e)&&e.then,g(l)?i?l.call(e,a(o,n,I,i),a(o,n,W,i)):(o++,l.call(e,a(o,n,I,i),a(o,n,W,i),a(o,n,I,n.notifyWith))):(r!==I&&(s=void 0,u=[e]),(i||n.resolveWith)(s,u))}},c=i?l:function(){try{l()}catch(e){w.Deferred.exceptionHook&&w.Deferred.exceptionHook(e,c.stackTrace),t+1>=o&&(r!==W&&(s=void 0,u=[e]),n.rejectWith(s,u))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:I,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:I)),n[2][3].add(a(0,e,g(r)?r:W))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],s=t[5];i[t[1]]=a.add,s&&a.add(function(){r=s},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),s=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&($(e,a.done(s(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)$(i[n],s(n),a.reject);return a.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&B.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function _(){r.removeEventListener("DOMContentLoaded",_),e.removeEventListener("load",_),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",_),e.addEventListener("load",_));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n)){i=!0;for(s in n)z(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},X=/^-ms-/,U=/-([a-z])/g;function V(e,t){return t.toUpperCase()}function G(e){return e.replace(X,"ms-").replace(U,V)}var Y=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function Q(){this.expando=w.expando+Q.uid++}Q.uid=1,Q.prototype={cache:function(e){var t=e[this.expando];return t||(t={},Y(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[G(t)]=n;else for(r in t)i[G(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][G(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(G):(t=G(t))in r?[t]:t.match(M)||[]).length;while(n--)delete r[t[n]]}(void 0===t||w.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!w.isEmptyObject(t)}};var J=new Q,K=new Q,Z=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ee=/[A-Z]/g;function te(e){return"true"===e||"false"!==e&&("null"===e?null:e===+e+""?+e:Z.test(e)?JSON.parse(e):e)}function ne(e,t,n){var r;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(ee,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n=te(n)}catch(e){}K.set(e,t,n)}else n=void 0;return n}w.extend({hasData:function(e){return K.hasData(e)||J.hasData(e)},data:function(e,t,n){return K.access(e,t,n)},removeData:function(e,t){K.remove(e,t)},_data:function(e,t,n){return J.access(e,t,n)},_removeData:function(e,t){J.remove(e,t)}}),w.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=K.get(o),1===o.nodeType&&!J.get(o,"hasDataAttrs"))){n=a.length;while(n--)a[n]&&0===(r=a[n].name).indexOf("data-")&&(r=G(r.slice(5)),ne(o,r,i[r]));J.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof e?this.each(function(){K.set(this,e)}):z(this,function(t){var n;if(o&&void 0===t){if(void 0!==(n=K.get(o,e)))return n;if(void 0!==(n=ne(o,e)))return n}else this.each(function(){K.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){K.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=J.get(e,t),n&&(!r||Array.isArray(n)?r=J.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return J.get(e,n)||J.access(e,n,{empty:w.Callbacks("once memory").add(function(){J.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?w.queue(this[0],e):void 0===t?this:this.each(function(){var n=w.queue(this,e,t);w._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&w.dequeue(this,e)})},dequeue:function(e){return this.each(function(){w.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=w.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=J.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var re=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ie=new RegExp("^(?:([+-])=|)("+re+")([a-z%]*)$","i"),oe=["Top","Right","Bottom","Left"],ae=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&w.contains(e.ownerDocument,e)&&"none"===w.css(e,"display")},se=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};function ue(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return w.css(e,t,"")},u=s(),l=n&&n[3]||(w.cssNumber[t]?"":"px"),c=(w.cssNumber[t]||"px"!==l&&+u)&&ie.exec(w.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)w.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,w.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var le={};function ce(e){var t,n=e.ownerDocument,r=e.nodeName,i=le[r];return i||(t=n.body.appendChild(n.createElement(r)),i=w.css(t,"display"),t.parentNode.removeChild(t),"none"===i&&(i="block"),le[r]=i,i)}function fe(e,t){for(var n,r,i=[],o=0,a=e.length;o<a;o++)(r=e[o]).style&&(n=r.style.display,t?("none"===n&&(i[o]=J.get(r,"display")||null,i[o]||(r.style.display="")),""===r.style.display&&ae(r)&&(i[o]=ce(r))):"none"!==n&&(i[o]="none",J.set(r,"display",n)));for(o=0;o<a;o++)null!=i[o]&&(e[o].style.display=i[o]);return e}w.fn.extend({show:function(){return fe(this,!0)},hide:function(){return fe(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?w(this).show():w(this).hide()})}});var pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?w.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n<r;n++)J.set(e[n],"globalEval",!t||J.get(t[n],"globalEval"))}var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===x(o))w.merge(p,o.nodeType?[o]:o);else if(me.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+w.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;w.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&w.inArray(o,r)>-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="<textarea>x</textarea>",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n<arguments.length;n++)u[n]=arguments[n];if(t.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,t)){s=w.event.handlers.call(this,t,l),n=0;while((o=s[n++])&&!t.isPropagationStopped()){t.currentTarget=o.elem,r=0;while((a=o.handlers[r++])&&!t.isImmediatePropagationStopped())t.rnamespace&&!t.rnamespace.test(a.namespace)||(t.handleObj=a,t.data=a.data,void 0!==(i=((w.event.special[a.origType]||{}).handle||a.handler).apply(o.elem,u))&&!1===(t.result=i)&&(t.preventDefault(),t.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,t),t.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&e.button>=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?w(i,this).index(l)>-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(e,t){Object.defineProperty(w.Event.prototype,e,{enumerable:!0,configurable:!0,get:g(t)?function(){if(this.originalEvent)return t(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[e]},set:function(t){Object.defineProperty(this,e,{enumerable:!0,configurable:!0,writable:!0,value:t})}})},fix:function(e){return e[w.expando]?e:new w.Event(e)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==Se()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===Se()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&N(this,"input"))return this.click(),!1},_default:function(e){return N(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},w.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},w.Event=function(e,t){if(!(this instanceof w.Event))return new w.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?Ee:ke,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&w.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[w.expando]=!0},w.Event.prototype={constructor:w.Event,isDefaultPrevented:ke,isPropagationStopped:ke,isImmediatePropagationStopped:ke,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=Ee,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=Ee,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=Ee,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},w.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(e){var t=e.button;return null==e.which&&we.test(e.type)?null!=e.charCode?e.charCode:e.keyCode:!e.which&&void 0!==t&&Te.test(e.type)?1&t?1:2&t?3:4&t?2:0:e.which}},w.event.addProp),w.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){w.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return i&&(i===r||w.contains(r,i))||(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),w.fn.extend({on:function(e,t,n,r){return De(this,e,t,n,r)},one:function(e,t,n,r){return De(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,w(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=ke),this.each(function(){w.event.remove(this,e,n,t)})}});var Ne=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/<script|<style|<link/i,je=/checked\s*(?:[^=]|=\s*.checked.)/i,qe=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n<r;n++)w.event.add(t,i,l[i][n])}K.hasData(e)&&(s=K.access(e),u=w.extend({},s),K.set(t,u))}}function Me(e,t){var n=t.nodeName.toLowerCase();"input"===n&&pe.test(e.type)?t.checked=e.checked:"input"!==n&&"textarea"!==n||(t.defaultValue=e.defaultValue)}function Re(e,t,n,r){t=a.apply([],t);var i,o,s,u,l,c,f=0,p=e.length,d=p-1,y=t[0],v=g(y);if(v||p>1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f<p;f++)l=i,f!==d&&(l=w.clone(l,!0,!0),u&&w.merge(s,ye(l,"script"))),n.call(e[f],l,f);if(u)for(c=s[s.length-1].ownerDocument,w.map(s,Oe),f=0;f<u;f++)l=s[f],he.test(l.type||"")&&!J.access(l,"globalEval")&&w.contains(c,l)&&(l.src&&"module"!==(l.type||"").toLowerCase()?w._evalUrl&&w._evalUrl(l.src):m(l.textContent.replace(qe,""),c,l))}return e}function Ie(e,t,n){for(var r,i=t?w.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||w.cleanData(ye(r)),r.parentNode&&(n&&w.contains(r.ownerDocument,r)&&ve(ye(r,"script")),r.parentNode.removeChild(r));return e}w.extend({htmlPrefilter:function(e){return e.replace(Ne,"<$1></$2>")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r<i;r++)Me(o[r],a[r]);if(t)if(n)for(o=o||ye(e),a=a||ye(s),r=0,i=o.length;r<i;r++)Pe(o[r],a[r]);else Pe(e,s);return(a=ye(s,"script")).length>0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(w.cleanData(ye(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return Re(this,arguments,function(t){var n=this.parentNode;w.inArray(this,e)<0&&(w.cleanData(ye(this)),n&&n.replaceChild(t,this))},e)}}),w.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){w.fn[e]=function(e){for(var n,r=[],i=w(e),o=i.length-1,a=0;a<=o;a++)n=a===o?this:this.clone(!0),w(i[a])[t](n),s.apply(r,n.get());return this.pushStack(r)}});var We=new RegExp("^("+re+")(?!px)[a-z%]+$","i"),$e=function(t){var n=t.ownerDocument.defaultView;return n&&n.opener||(n=e),n.getComputedStyle(t)},Be=new RegExp(oe.join("|"),"i");!function(){function t(){if(c){l.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",c.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",be.appendChild(l).appendChild(c);var t=e.getComputedStyle(c);i="1%"!==t.top,u=12===n(t.marginLeft),c.style.right="60%",s=36===n(t.right),o=36===n(t.width),c.style.position="absolute",a=36===c.offsetWidth||"absolute",be.removeChild(l),c=null}}function n(e){return Math.round(parseFloat(e))}var i,o,a,s,u,l=r.createElement("div"),c=r.createElement("div");c.style&&(c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",h.clearCloneStyle="content-box"===c.style.backgroundClip,w.extend(h,{boxSizingReliable:function(){return t(),o},pixelBoxStyles:function(){return t(),s},pixelPosition:function(){return t(),i},reliableMarginLeft:function(){return t(),u},scrollboxSize:function(){return t(),a}}))}();function Fe(e,t,n){var r,i,o,a,s=e.style;return(n=n||$e(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||w.contains(e.ownerDocument,e)||(a=w.style(e,t)),!h.pixelBoxStyles()&&We.test(a)&&Be.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function _e(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}var ze=/^(none|table(?!-c[ea]).+)/,Xe=/^--/,Ue={position:"absolute",visibility:"hidden",display:"block"},Ve={letterSpacing:"0",fontWeight:"400"},Ge=["Webkit","Moz","ms"],Ye=r.createElement("div").style;function Qe(e){if(e in Ye)return e;var t=e[0].toUpperCase()+e.slice(1),n=Ge.length;while(n--)if((e=Ge[n]+t)in Ye)return e}function Je(e){var t=w.cssProps[e];return t||(t=w.cssProps[e]=Qe(e)||e),t}function Ke(e,t,n){var r=ie.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function Ze(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=w.css(e,n+oe[a],!0,i)),r?("content"===n&&(u-=w.css(e,"padding"+oe[a],!0,i)),"margin"!==n&&(u-=w.css(e,"border"+oe[a]+"Width",!0,i))):(u+=w.css(e,"padding"+oe[a],!0,i),"padding"!==n?u+=w.css(e,"border"+oe[a]+"Width",!0,i):s+=w.css(e,"border"+oe[a]+"Width",!0,i));return!r&&o>=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a<i;a++)o[t[a]]=w.css(e,t[a],!1,r);return o}return void 0!==n?w.style(e,t,n):w.css(e,t)},e,t,arguments.length>1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function ct(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ae(e),y=J.get(e,"fxshow");n.queue||(null==(a=w._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,w.queue(e,"fx").length||a.empty.fire()})}));for(r in t)if(i=t[r],it.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!y||void 0===y[r])continue;g=!0}d[r]=y&&y[r]||w.style(e,r)}if((u=!w.isEmptyObject(t))||!w.isEmptyObject(d)){f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=y&&y.display)&&(l=J.get(e,"display")),"none"===(c=w.css(e,"display"))&&(l?c=l:(fe([e],!0),l=e.style.display||l,c=w.css(e,"display"),fe([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===w.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1;for(r in d)u||(y?"hidden"in y&&(g=y.hidden):y=J.access(e,"fxshow",{display:l}),o&&(y.hidden=!g),g&&fe([e],!0),p.done(function(){g||fe([e]),J.remove(e,"fxshow");for(r in d)w.style(e,r,d[r])})),u=lt(g?y[r]:0,r,p),r in y||(y[r]=u.start,g&&(u.end=u.start,u.start=0))}}function ft(e,t){var n,r,i,o,a;for(n in e)if(r=G(n),i=t[r],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=w.cssHooks[r])&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function pt(e,t,n){var r,i,o=0,a=pt.prefilters.length,s=w.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=nt||st(),n=Math.max(0,l.startTime+l.duration-t),r=1-(n/l.duration||0),o=0,a=l.tweens.length;o<a;o++)l.tweens[o].run(r);return s.notifyWith(e,[l,r,n]),r<1&&a?n:(a||s.notifyWith(e,[l,1,0]),s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:w.extend({},t),opts:w.extend(!0,{specialEasing:{},easing:w.easing._default},n),originalProperties:t,originalOptions:n,startTime:nt||st(),duration:n.duration,tweens:[],createTween:function(t,n){var r=w.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;n<r;n++)l.tweens[n].run(1);return t?(s.notifyWith(e,[l,1,0]),s.resolveWith(e,[l,t])):s.rejectWith(e,[l,t]),this}}),c=l.props;for(ft(c,l.opts.specialEasing);o<a;o++)if(r=pt.prefilters[o].call(l,e,c,l.opts))return g(r.stop)&&(w._queueHooks(l.elem,l.opts.queue).stop=r.stop.bind(r)),r;return w.map(c,lt,l),g(l.opts.start)&&l.opts.start.call(e,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),w.fx.timer(w.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l}w.Animation=w.extend(pt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return ue(n.elem,e,ie.exec(t),n),n}]},tweener:function(e,t){g(e)?(t=e,e=["*"]):e=e.match(M);for(var n,r=0,i=e.length;r<i;r++)n=e[r],pt.tweeners[n]=pt.tweeners[n]||[],pt.tweeners[n].unshift(t)},prefilters:[ct],prefilter:function(e,t){t?pt.prefilters.unshift(e):pt.prefilters.push(e)}}),w.speed=function(e,t,n){var r=e&&"object"==typeof e?w.extend({},e):{complete:n||!n&&t||g(e)&&e,duration:e,easing:n&&t||t&&!g(t)&&t};return w.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in w.fx.speeds?r.duration=w.fx.speeds[r.duration]:r.duration=w.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){g(r.old)&&r.old.call(this),r.queue&&w.dequeue(this,r.queue)},r},w.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=w.isEmptyObject(e),o=w.speed(t,n,r),a=function(){var t=pt(this,w.extend({},e),o);(i||J.get(this,"finish"))&&t.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&!1!==e&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=w.timers,a=J.get(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&ot.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));!t&&n||w.dequeue(this,e)})},finish:function(e){return!1!==e&&(e=e||"fx"),this.each(function(){var t,n=J.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=w.timers,a=r?r.length:0;for(n.finish=!0,w.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;t<a;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),w.each(["toggle","show","hide"],function(e,t){var n=w.fn[t];w.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ut(t,!0),e,r,i)}}),w.each({slideDown:ut("show"),slideUp:ut("hide"),slideToggle:ut("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){w.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),w.timers=[],w.fx.tick=function(){var e,t=0,n=w.timers;for(nt=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||w.fx.stop(),nt=void 0},w.fx.timer=function(e){w.timers.push(e),w.fx.start()},w.fx.interval=13,w.fx.start=function(){rt||(rt=!0,at())},w.fx.stop=function(){rt=null},w.fx.speeds={slow:600,fast:200,_default:400},w.fn.delay=function(t,n){return t=w.fx?w.fx.speeds[t]||t:t,n=n||"fx",this.queue(n,function(n,r){var i=e.setTimeout(n,t);r.stop=function(){e.clearTimeout(i)}})},function(){var e=r.createElement("input"),t=r.createElement("select").appendChild(r.createElement("option"));e.type="checkbox",h.checkOn=""!==e.value,h.optSelected=t.selected,(e=r.createElement("input")).value="t",e.type="radio",h.radioValue="t"===e.value}();var dt,ht=w.expr.attrHandle;w.fn.extend({attr:function(e,t){return z(this,w.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!N(n.parentNode,"optgroup"))){if(t=w(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=w.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=w.inArray(w.valHooks.option.get(r),o)>-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w("<script>").prop({charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&o("error"===e.type?404:200,e.type)}),r.head.appendChild(t[0])},abort:function(){n&&n()}}}});var Yt=[],Qt=/(=)\?(?=&|$)|\?\?/;w.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Yt.pop()||w.expando+"_"+Et++;return this[e]=!0,e}}),w.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=!1!==t.jsonp&&(Qt.test(t.url)?"url":"string"==typeof t.data&&0===(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&Qt.test(t.data)&&"data");if(s||"jsonp"===t.dataTypes[0])return i=t.jsonpCallback=g(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(Qt,"$1"+i):!1!==t.jsonp&&(t.url+=(kt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||w.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){void 0===o?w(e).removeProp(i):e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,Yt.push(i)),a&&g(o)&&o(a[0]),a=o=void 0}),"script"}),h.createHTMLDocument=function(){var e=r.implementation.createHTMLDocument("").body;return e.innerHTML="<form></form><form></form>",2===e.childNodes.length}(),w.parseHTML=function(e,t,n){if("string"!=typeof e)return[];"boolean"==typeof t&&(n=t,t=!1);var i,o,a;return t||(h.createHTMLDocument?((i=(t=r.implementation.createHTMLDocument("")).createElement("base")).href=r.location.href,t.head.appendChild(i)):t=r),o=A.exec(e),a=!n&&[],o?[t.createElement(o[1])]:(o=xe([e],t,a),a&&a.length&&w(a).remove(),w.merge([],o.childNodes))},w.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return s>-1&&(r=vt(e.slice(s)),e=e.slice(0,s)),g(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),a.length>0&&w.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?w("<div>").append(w.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},w.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){w.fn[t]=function(e){return this.on(t,e)}}),w.expr.pseudos.animated=function(e){return w.grep(w.timers,function(t){return e===t.elem}).length},w.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l,c=w.css(e,"position"),f=w(e),p={};"static"===c&&(e.style.position="relative"),s=f.offset(),o=w.css(e,"top"),u=w.css(e,"left"),(l=("absolute"===c||"fixed"===c)&&(o+u).indexOf("auto")>-1)?(a=(r=f.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),g(t)&&(t=t.call(e,n,w.extend({},s))),null!=t.top&&(p.top=t.top-s.top+a),null!=t.left&&(p.left=t.left-s.left+i),"using"in t?t.using.call(e,p):f.css(p)}},w.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){w.offset.setOffset(this,e,t)});var t,n,r=this[0];if(r)return r.getClientRects().length?(t=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:t.top+n.pageYOffset,left:t.left+n.pageXOffset}):{top:0,left:0}},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===w.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===w.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=w(e).offset()).top+=w.css(e,"borderTopWidth",!0),i.left+=w.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-w.css(r,"marginTop",!0),left:t.left-i.left-w.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===w.css(e,"position"))e=e.offsetParent;return e||be})}}),w.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;w.fn[e]=function(r){return z(this,function(e,r,i){var o;if(y(e)?o=e:9===e.nodeType&&(o=e.defaultView),void 0===i)return o?o[t]:e[r];o?o.scrollTo(n?o.pageXOffset:i,n?i:o.pageYOffset):e[r]=i},e,r,arguments.length)}}),w.each(["top","left"],function(e,t){w.cssHooks[t]=_e(h.pixelPosition,function(e,n){if(n)return n=Fe(e,t),We.test(n)?w(e).position()[t]+"px":n})}),w.each({Height:"height",Width:"width"},function(e,t){w.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){w.fn[r]=function(i,o){var a=arguments.length&&(n||"boolean"!=typeof i),s=n||(!0===i||!0===o?"margin":"border");return z(this,function(t,n,i){var o;return y(t)?0===r.indexOf("outer")?t["inner"+e]:t.document.documentElement["client"+e]:9===t.nodeType?(o=t.documentElement,Math.max(t.body["scroll"+e],o["scroll"+e],t.body["offset"+e],o["offset"+e],o["client"+e])):void 0===i?w.css(t,n,s):w.style(t,n,i,s)},t,a?i:void 0,a)}})}),w.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,t){w.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),w.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),w.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),w.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),g(e))return r=o.call(arguments,2),i=function(){return e.apply(t||this,r.concat(o.call(arguments)))},i.guid=e.guid=e.guid||w.guid++,i},w.holdReady=function(e){e?w.readyWait++:w.ready(!0)},w.isArray=Array.isArray,w.parseJSON=JSON.parse,w.nodeName=N,w.isFunction=g,w.isWindow=y,w.camelCase=G,w.type=x,w.now=Date.now,w.isNumeric=function(e){var t=w.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return w});var Jt=e.jQuery,Kt=e.$;return w.noConflict=function(t){return e.$===w&&(e.$=Kt),t&&e.jQuery===w&&(e.jQuery=Jt),w},t||(e.jQuery=e.$=w),w});

/*! jQuery UI - v1.11.2 - 2014-10-16
* http://jqueryui.com
* Includes: core.js, widget.js, mouse.js, position.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, draggable.js, droppable.js, effect.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js, menu.js, progressbar.js, resizable.js, selectable.js, selectmenu.js, slider.js, sortable.js, spinner.js, tabs.js, tooltip.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */

(function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,s){var n,a,o,r=t.nodeName.toLowerCase();return"area"===r?(n=t.parentNode,a=n.name,t.href&&a&&"map"===n.nodeName.toLowerCase()?(o=e("img[usemap='#"+a+"']")[0],!!o&&i(o)):!1):(/input|select|textarea|button|object/.test(r)?!t.disabled:"a"===r?t.href||s:s)&&i(t)}function i(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}function s(e){for(var t,i;e.length&&e[0]!==document;){if(t=e.css("position"),("absolute"===t||"relative"===t||"fixed"===t)&&(i=parseInt(e.css("zIndex"),10),!isNaN(i)&&0!==i))return i;e=e.parent()}return 0}function n(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,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:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},e.extend(this._defaults,this.regional[""]),this.regional.en=e.extend(!0,{},this.regional[""]),this.regional["en-US"]=e.extend(!0,{},this.regional.en),this.dpDiv=a(e("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function a(t){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.delegate(i,"mouseout",function(){e(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).removeClass("ui-datepicker-next-hover")}).delegate(i,"mouseover",o)}function o(){e.datepicker._isDisabledDatepicker(v.inline?v.dpDiv.parent()[0]:v.input[0])||(e(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),e(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).addClass("ui-datepicker-next-hover"))}function r(t,i){e.extend(t,i);for(var s in i)null==i[s]&&(t[s]=i[s]);return t}function h(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger("change")}}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.2",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}}),e.fn.extend({scrollParent:function(t){var i=this.css("position"),s="absolute"===i,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,a=this.parents().filter(function(){var t=e(this);return s&&"static"===t.css("position")?!1:n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==i&&a.length?a:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),n=isNaN(s);return(n||s>=0)&&t(i,!n)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],a=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(a,s(this,t)+"px")})},e.fn["outer"+i]=function(t,n){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(a,s(this,t,!0,n)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,n=e(this[0]);n.length&&n[0]!==document;){if(i=n.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var n,a=e.ui[t].prototype;for(n in s)a.plugins[n]=a.plugins[n]||[],a.plugins[n].push([i,s[n]])},call:function(e,t,i,s){var n,a=e.plugins[t];if(a&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(n=0;a.length>n;n++)e.options[a[n][0]]&&a[n][1].apply(e.element,i)}};var l=0,u=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,n=u.call(arguments,1),a=0,o=n.length;o>a;a++)for(i in n[a])s=n[a][i],n[a].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(n){var a="string"==typeof n,o=u.call(arguments,1),r=this;return n=!a&&o.length?e.widget.extend.apply(null,[n].concat(o)):n,a?this.each(function(){var i,a=e.data(this,s);return"instance"===n?(r=a,!1):a?e.isFunction(a[n])&&"_"!==n.charAt(0)?(i=a[n].apply(a,o),i!==a&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+n+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+n+"'")}):this.each(function(){var t=e.data(this,s);t?(t.option(n||{}),t._init&&t._init()):e.data(this,s,new i(n,this))}),r}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=l++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget;var d=!1;e(document).mouseup(function(){d=!1}),e.widget("ui.mouse",{version:"1.11.2",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!d){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var i=this,s=1===t.which,n="string"==typeof this.options.cancel&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(t)!==!1,!this._mouseStarted)?(t.preventDefault(),!0):(!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return i._mouseMove(e)},this._mouseUpDelegate=function(e){return i._mouseUp(e)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),d=!0,!0)):!0}},_mouseMove:function(t){if(this._mouseMoved){if(e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button)return this._mouseUp(t);if(!t.which)return this._mouseUp(t)}return(t.which||t.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){return this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),d=!1,!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),function(){function t(e,t,i){return[parseFloat(e[0])*(p.test(e[0])?t/100:1),parseFloat(e[1])*(p.test(e[1])?i/100:1)]}function i(t,i){return parseInt(e.css(t,i),10)||0}function s(t){var i=t[0];return 9===i.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(i)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var n,a,o=Math.max,r=Math.abs,h=Math.round,l=/left|center|right/,u=/top|center|bottom/,d=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,p=/%$/,f=e.fn.position;e.position={scrollbarWidth:function(){if(void 0!==n)return n;var t,i,s=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),a=s.children()[0];return e("body").append(s),t=a.offsetWidth,s.css("overflow","scroll"),i=a.offsetWidth,t===i&&(i=s[0].clientWidth),s.remove(),n=t-i},getScrollInfo:function(t){var i=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),s=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),n="scroll"===i||"auto"===i&&t.width<t.element[0].scrollWidth,a="scroll"===s||"auto"===s&&t.height<t.element[0].scrollHeight;return{width:a?e.position.scrollbarWidth():0,height:n?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var i=e(t||window),s=e.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s||n?i.width():i.outerWidth(),height:s||n?i.height():i.outerHeight()}}},e.fn.position=function(n){if(!n||!n.of)return f.apply(this,arguments);n=e.extend({},n);var p,m,g,v,y,b,_=e(n.of),x=e.position.getWithinInfo(n.within),w=e.position.getScrollInfo(x),k=(n.collision||"flip").split(" "),T={};return b=s(_),_[0].preventDefault&&(n.at="left top"),m=b.width,g=b.height,v=b.offset,y=e.extend({},v),e.each(["my","at"],function(){var e,t,i=(n[this]||"").split(" ");1===i.length&&(i=l.test(i[0])?i.concat(["center"]):u.test(i[0])?["center"].concat(i):["center","center"]),i[0]=l.test(i[0])?i[0]:"center",i[1]=u.test(i[1])?i[1]:"center",e=d.exec(i[0]),t=d.exec(i[1]),T[this]=[e?e[0]:0,t?t[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===k.length&&(k[1]=k[0]),"right"===n.at[0]?y.left+=m:"center"===n.at[0]&&(y.left+=m/2),"bottom"===n.at[1]?y.top+=g:"center"===n.at[1]&&(y.top+=g/2),p=t(T.at,m,g),y.left+=p[0],y.top+=p[1],this.each(function(){var s,l,u=e(this),d=u.outerWidth(),c=u.outerHeight(),f=i(this,"marginLeft"),b=i(this,"marginTop"),D=d+f+i(this,"marginRight")+w.width,S=c+b+i(this,"marginBottom")+w.height,M=e.extend({},y),C=t(T.my,u.outerWidth(),u.outerHeight());"right"===n.my[0]?M.left-=d:"center"===n.my[0]&&(M.left-=d/2),"bottom"===n.my[1]?M.top-=c:"center"===n.my[1]&&(M.top-=c/2),M.left+=C[0],M.top+=C[1],a||(M.left=h(M.left),M.top=h(M.top)),s={marginLeft:f,marginTop:b},e.each(["left","top"],function(t,i){e.ui.position[k[t]]&&e.ui.position[k[t]][i](M,{targetWidth:m,targetHeight:g,elemWidth:d,elemHeight:c,collisionPosition:s,collisionWidth:D,collisionHeight:S,offset:[p[0]+C[0],p[1]+C[1]],my:n.my,at:n.at,within:x,elem:u})}),n.using&&(l=function(e){var t=v.left-M.left,i=t+m-d,s=v.top-M.top,a=s+g-c,h={target:{element:_,left:v.left,top:v.top,width:m,height:g},element:{element:u,left:M.left,top:M.top,width:d,height:c},horizontal:0>i?"left":t>0?"right":"center",vertical:0>a?"top":s>0?"bottom":"middle"};d>m&&m>r(t+i)&&(h.horizontal="center"),c>g&&g>r(s+a)&&(h.vertical="middle"),h.important=o(r(t),r(i))>o(r(s),r(a))?"horizontal":"vertical",n.using.call(this,e,h)}),u.offset(e.extend(M,{using:l}))})},e.ui.position={fit:{left:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=e.left-t.collisionPosition.marginLeft,h=n-r,l=r+t.collisionWidth-a-n;t.collisionWidth>a?h>0&&0>=l?(i=e.left+h+t.collisionWidth-a-n,e.left+=h-i):e.left=l>0&&0>=h?n:h>l?n+a-t.collisionWidth:n:h>0?e.left+=h:l>0?e.left-=l:e.left=o(e.left-r,e.left)},top:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollTop:s.offset.top,a=t.within.height,r=e.top-t.collisionPosition.marginTop,h=n-r,l=r+t.collisionHeight-a-n;t.collisionHeight>a?h>0&&0>=l?(i=e.top+h+t.collisionHeight-a-n,e.top+=h-i):e.top=l>0&&0>=h?n:h>l?n+a-t.collisionHeight:n:h>0?e.top+=h:l>0?e.top-=l:e.top=o(e.top-r,e.top)}},flip:{left:function(e,t){var i,s,n=t.within,a=n.offset.left+n.scrollLeft,o=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=e.left-t.collisionPosition.marginLeft,u=l-h,d=l+t.collisionWidth-o-h,c="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,p="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,f=-2*t.offset[0];0>u?(i=e.left+c+p+f+t.collisionWidth-o-a,(0>i||r(u)>i)&&(e.left+=c+p+f)):d>0&&(s=e.left-t.collisionPosition.marginLeft+c+p+f-h,(s>0||d>r(s))&&(e.left+=c+p+f))},top:function(e,t){var i,s,n=t.within,a=n.offset.top+n.scrollTop,o=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=e.top-t.collisionPosition.marginTop,u=l-h,d=l+t.collisionHeight-o-h,c="top"===t.my[1],p=c?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,f="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,m=-2*t.offset[1];0>u?(s=e.top+p+f+m+t.collisionHeight-o-a,e.top+p+f+m>u&&(0>s||r(u)>s)&&(e.top+=p+f+m)):d>0&&(i=e.top-t.collisionPosition.marginTop+p+f+m-h,e.top+p+f+m>d&&(i>0||d>r(i))&&(e.top+=p+f+m))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,i,s,n,o,r=document.getElementsByTagName("body")[0],h=document.createElement("div");t=document.createElement(r?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},r&&e.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in s)t.style[o]=s[o];t.appendChild(h),i=r||document.documentElement,i.insertBefore(t,i.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",n=e(h).offset().left,a=n>10&&11>n,t.innerHTML="",i.removeChild(t)}()}(),e.ui.position,e.widget("ui.accordion",{version:"1.11.2",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :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 t=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),t.collapsible||t.active!==!1&&null!=t.active||(t.active=0),this._processPanels(),0>t.active&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("<span>").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").removeUniqueId(),this._destroyIcons(),e=this.headers.next().removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").css("display","").removeAttr("role").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&e.css("height","")},_setOption:function(e,t){return"active"===e?(this._activate(t),void 0):("event"===e&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),"collapsible"!==e||t||this.options.active!==!1||this._activate(0),"icons"===e&&(this._destroyIcons(),t&&this._createIcons()),"disabled"===e&&(this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)),void 0)},_keydown:function(t){if(!t.altKey&&!t.ctrlKey){var i=e.ui.keyCode,s=this.headers.length,n=this.headers.index(t.target),a=!1;switch(t.keyCode){case i.RIGHT:case i.DOWN:a=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:a=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(t);break;case i.HOME:a=this.headers[0];break;case i.END:a=this.headers[s-1]}a&&(e(t.target).attr("tabIndex",-1),e(a).attr("tabIndex",0),a.focus(),t.preventDefault())}},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t=this.options;this._processPanels(),t.active===!1&&t.collapsible===!0||!this.headers.length?(t.active=!1,this.active=e()):t.active===!1?this._activate(0):this.active.length&&!e.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=e()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var e=this.headers,t=this.panels;this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-state-default ui-corner-all"),this.panels=this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide(),t&&(this._off(e.not(this.headers)),this._off(t.not(this.panels)))},_refresh:function(){var t,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active).addClass("ui-accordion-header-active ui-state-active ui-corner-top").removeClass("ui-corner-all"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(){var t=e(this),i=t.uniqueId().attr("id"),s=t.next(),n=s.uniqueId().attr("id");t.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(t=n.height(),this.element.siblings(":visible").each(function(){var i=e(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(t-=i.outerHeight(!0))}),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):"auto"===s&&(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).css("height","").height())}).height(t))},_activate:function(t){var i=this._findActive(t)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:e.noop}))},_findActive:function(t){return"number"==typeof t?this.headers.eq(t):e()},_setupEvents:function(t){var i={keydown:"_keydown"};t&&e.each(t.split(" "),function(e,t){i[t]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var i=this.options,s=this.active,n=e(t.currentTarget),a=n[0]===s[0],o=a&&i.collapsible,r=o?e():n.next(),h=s.next(),l={oldHeader:s,oldPanel:h,newHeader:o?e():n,newPanel:r};t.preventDefault(),a&&!i.collapsible||this._trigger("beforeActivate",t,l)===!1||(i.active=o?!1:this.headers.index(n),this.active=a?e():n,this._toggle(l),s.removeClass("ui-accordion-header-active ui-state-active"),i.icons&&s.children(".ui-accordion-header-icon").removeClass(i.icons.activeHeader).addClass(i.icons.header),a||(n.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),i.icons&&n.children(".ui-accordion-header-icon").removeClass(i.icons.header).addClass(i.icons.activeHeader),n.next().addClass("ui-accordion-content-active")))},_toggle:function(t){var i=t.newPanel,s=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,t):(s.hide(),i.show(),this._toggleComplete(t)),s.attr({"aria-hidden":"true"}),s.prev().attr("aria-selected","false"),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===e(this).attr("tabIndex")}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true",tabIndex:0,"aria-expanded":"true"})},_animate:function(e,t,i){var s,n,a,o=this,r=0,h=e.length&&(!t.length||e.index()<t.index()),l=this.options.animate||{},u=h&&l.down||l,d=function(){o._toggleComplete(i)};return"number"==typeof u&&(a=u),"string"==typeof u&&(n=u),n=n||u.easing||l.easing,a=a||u.duration||l.duration,t.length?e.length?(s=e.show().outerHeight(),t.animate(this.hideProps,{duration:a,easing:n,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(this.showProps,{duration:a,easing:n,complete:d,step:function(e,i){i.now=Math.round(e),"height"!==i.prop?r+=i.now:"content"!==o.options.heightStyle&&(i.now=Math.round(s-t.outerHeight()-r),r=0)}}),void 0):t.animate(this.hideProps,a,n,d):e.animate(this.showProps,a,n,d)},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&&(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}}),e.widget("ui.menu",{version:"1.11.2",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},items:"> *",menus:"ul",position:{my:"left-1 top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item":function(e){e.preventDefault()},"click .ui-menu-item":function(t){var i=e(t.target);!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&e(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){if(!this.previousFilter){var i=e(t.currentTarget);i.siblings(".ui-state-active").removeClass("ui-state-active"),this.focus(t,i)
}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var i=this.active||this.element.find(this.options.items).eq(0);t||this.focus(e,i)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){this._closeOnDocumentClick(e)&&this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){var i,s,n,a,o=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:o=!1,s=this.previousFilter||"",n=String.fromCharCode(t.keyCode),a=!1,clearTimeout(this.filterTimer),n===s?a=!0:n=s+n,i=this._filterMenuItems(n),i=a&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(t.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(t,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}o&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.is("[aria-haspopup='true']")?this.expand(e):this.select(e))},refresh:function(){var t,i,s=this,n=this.options.icons.submenu,a=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),a.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),i=t.parent(),s=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);i.attr("aria-haspopup","true").prepend(s),t.attr("aria-labelledby",i.attr("id"))}),t=a.add(this.element),i=t.find(this.options.items),i.not(".ui-menu-item").each(function(){var t=e(this);s._isDivider(t)&&t.addClass("ui-widget-content ui-menu-divider")}),i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){"icons"===e&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this._super(e,t)},focus:function(e,t){var i,s;this.blur(e,e&&"focus"===e.type),this._scrollIntoView(t),this.active=t.first(),s=this.active.addClass("ui-state-focus").removeClass("ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"),e&&"keydown"===e.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=t.children(".ui-menu"),i.length&&e&&/^mouse/.test(e.type)&&this._startOpening(i),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,n=t.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=t.outerHeight(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(e,t){t||clearTimeout(this.timer),this.active&&(this.active.removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active}))},_startOpening:function(e){clearTimeout(this.timer),"true"===e.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(e)},this.delay))},_open:function(t){var i=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(t,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(t),this.activeMenu=s},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active")},_closeOnDocumentClick:function(t){return!e(t.target).closest(".ui-menu").length},_isDivider:function(e){return!/[^\-\u2014\u2013\s]/.test(e.text())},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,i){var s;this.active&&(s="first"===e||"last"===e?this.active["first"===e?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[e+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[t]()),this.focus(i,s)},nextPage:function(t){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=e(this),0>i.offset().top-s-n}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(t),void 0)},previousPage:function(t){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=e(this),i.offset().top-s+n>0}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items).first())),void 0):(this.next(t),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,i)},_filterMenuItems:function(t){var i=t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(e.trim(e(this).text()))})}}),e.widget("ui.autocomplete",{version:"1.11.2",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,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 t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n;this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,void 0;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),void 0):(this._searchTimeout(e),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(e),this._change(e),void 0)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:n})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&e.trim(s).length&&(this.liveRegion.children().hide(),e("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("<span>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t&&t[0]||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_initSource:function(){var t,i,s=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),i=this.menu.element.is(":visible"),s=e.altKey||e.ctrlKey||e.metaKey||e.shiftKey;(!t||t&&!i&&!s)&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length<this.options.minLength?this.close(t):this._trigger("search",t)!==!1?this._search(e):void 0},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var t=++this.requestIndex;return e.proxy(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return"string"==typeof t?{label:t,value:t}:e.extend({},t,{label:t.label||t.value,value:t.value||t.label})})},_suggest:function(t){var i=this.menu.element.empty();this._renderMenu(i,t),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,i){var s=this;e.each(i,function(e,i){s._renderItemData(t,i)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,i){return e("<li>").text(i.label).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[e](t),void 0):(this.search(null,t),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,this.liveRegion.children().hide(),e("<div>").text(i).appendTo(this.liveRegion))}}),e.ui.autocomplete;var c,p="ui-button ui-widget ui-state-default ui-corner-all",f="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",m=function(){var t=e(this);setTimeout(function(){t.find(":ui-button").button("refresh")},1)},g=function(t){var i=t.name,s=t.form,n=e([]);return i&&(i=i.replace(/'/g,"\\'"),n=s?e(s).find("[name='"+i+"'][type=radio]"):e("[name='"+i+"'][type=radio]",t.ownerDocument).filter(function(){return!this.form})),n};e.widget("ui.button",{version:"1.11.2",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,m),"boolean"!=typeof this.options.disabled?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var t=this,i=this.options,s="checkbox"===this.type||"radio"===this.type,n=s?"":"ui-state-active";null===i.label&&(i.label="input"===this.type?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(p).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){i.disabled||this===c&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){i.disabled||e(this).removeClass(n)}).bind("click"+this.eventNamespace,function(e){i.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this._on({focus:function(){this.buttonElement.addClass("ui-state-focus")},blur:function(){this.buttonElement.removeClass("ui-state-focus")}}),s&&this.element.bind("change"+this.eventNamespace,function(){t.refresh()}),"checkbox"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){return i.disabled?!1:void 0}):"radio"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){if(i.disabled)return!1;e(this).addClass("ui-state-active"),t.buttonElement.attr("aria-pressed","true");var s=t.element[0];g(s).not(s).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){return i.disabled?!1:(e(this).addClass("ui-state-active"),c=this,t.document.one("mouseup",function(){c=null}),void 0)}).bind("mouseup"+this.eventNamespace,function(){return i.disabled?!1:(e(this).removeClass("ui-state-active"),void 0)}).bind("keydown"+this.eventNamespace,function(t){return i.disabled?!1:((t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active"),void 0)}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",i.disabled),this._resetButton()},_determineButtonType:function(){var e,t,i;this.type=this.element.is("[type=checkbox]")?"checkbox":this.element.is("[type=radio]")?"radio":this.element.is("input")?"input":"button","checkbox"===this.type||"radio"===this.type?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),i=this.element.is(":checked"),i&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",i)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(p+" ui-state-active "+f).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){return this._super(e,t),"disabled"===e?(this.widget().toggleClass("ui-state-disabled",!!t),this.element.prop("disabled",!!t),t&&("checkbox"===this.type||"radio"===this.type?this.buttonElement.removeClass("ui-state-focus"):this.buttonElement.removeClass("ui-state-focus ui-state-active")),void 0):(this._resetButton(),void 0)},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),"radio"===this.type?g(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):"checkbox"===this.type&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if("input"===this.type)return this.options.label&&this.element.val(this.options.label),void 0;var t=this.buttonElement.removeClass(f),i=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),s=this.options.icons,n=s.primary&&s.secondary,a=[];s.primary||s.secondary?(this.options.text&&a.push("ui-button-text-icon"+(n?"s":s.primary?"-primary":"-secondary")),s.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+s.primary+"'></span>"),s.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+s.secondary+"'></span>"),this.options.text||(a.push(n?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(i)))):a.push("ui-button-text-only"),t.addClass(a.join(" "))}}),e.widget("ui.buttonset",{version:"1.11.2",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){"disabled"===e&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t="rtl"===this.element.css("direction"),i=this.element.find(this.options.items),s=i.filter(":ui-button");i.not(":ui-button").button(),s.button("refresh"),this.buttons=i.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}}),e.ui.button,e.extend(e.ui,{datepicker:{version:"1.11.2"}});var v;e.extend(n.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return r(this._defaults,e||{}),this},_attachDatepicker:function(t,i){var s,n,a;s=t.nodeName.toLowerCase(),n="div"===s||"span"===s,t.id||(this.uuid+=1,t.id="dp"+this.uuid),a=this._newInst(e(t),n),a.settings=e.extend({},i||{}),"input"===s?this._connectDatepicker(t,a):n&&this._inlineDatepicker(t,a)},_newInst:function(t,i){var s=t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?a(e("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,i){var s=e(t);i.append=e([]),i.trigger=e([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(i),e.data(t,"datepicker",i),i.settings.disabled&&this._disableDatepicker(t))},_attachments:function(t,i){var s,n,a,o=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),o&&(i.append=e("<span class='"+this._appendClass+"'>"+o+"</span>"),t[r?"before":"after"](i.append)),t.unbind("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&t.focus(this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),a=this._get(i,"buttonImage"),i.trigger=e(this._get(i,"buttonImageOnly")?e("<img/>").addClass(this._triggerClass).attr({src:a,alt:n,title:n}):e("<button type='button'></button>").addClass(this._triggerClass).html(a?e("<img/>").attr({src:a,alt:n,title:n}):n)),t[r?"before":"after"](i.trigger),i.trigger.click(function(){return e.datepicker._datepickerShowing&&e.datepicker._lastInput===t[0]?e.datepicker._hideDatepicker():e.datepicker._datepickerShowing&&e.datepicker._lastInput!==t[0]?(e.datepicker._hideDatepicker(),e.datepicker._showDatepicker(t[0])):e.datepicker._showDatepicker(t[0]),!1}))},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t,i,s,n,a=new Date(2009,11,20),o=this._get(e,"dateFormat");o.match(/[DM]/)&&(t=function(e){for(i=0,s=0,n=0;e.length>n;n++)e[n].length>i&&(i=e[n].length,s=n);return s},a.setMonth(t(this._get(e,o.match(/MM/)?"monthNames":"monthNamesShort"))),a.setDate(t(this._get(e,o.match(/DD/)?"dayNames":"dayNamesShort"))+20-a.getDay())),e.input.attr("size",this._formatDate(e,a).length)}},_inlineDatepicker:function(t,i){var s=e(t);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),e.data(t,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(t),i.dpDiv.css("display","block"))},_dialogDatepicker:function(t,i,s,n,a){var o,h,l,u,d,c=this._dialogInst;return c||(this.uuid+=1,o="dp"+this.uuid,this._dialogInput=e("<input type='text' id='"+o+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),e("body").append(this._dialogInput),c=this._dialogInst=this._newInst(this._dialogInput,!1),c.settings={},e.data(this._dialogInput[0],"datepicker",c)),r(c.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(c,i):i,this._dialogInput.val(i),this._pos=a?a.length?a:[a.pageX,a.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,u=document.documentElement.scrollLeft||document.body.scrollLeft,d=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+u,l/2-150+d]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),c.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),e.blockUI&&e.blockUI(this.dpDiv),e.data(this._dialogInput[0],"datepicker",c),this},_destroyDatepicker:function(t){var i,s=e(t),n=e.data(t,"datepicker");s.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),e.removeData(t,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty())},_enableDatepicker:function(t){var i,s,n=e(t),a=e.data(t,"datepicker");n.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!1,a.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}))},_disableDatepicker:function(t){var i,s,n=e(t),a=e.data(t,"datepicker");n.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!0,a.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t)},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;this._disabledInputs.length>t;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(t){try{return e.data(t,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(t,i,s){var n,a,o,h,l=this._getInst(t);return 2===arguments.length&&"string"==typeof i?"defaults"===i?e.extend({},e.datepicker._defaults):l?"all"===i?e.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),a=this._getDateDatepicker(t,!0),o=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),r(l.settings,n),null!==o&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,o)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(t):this._enableDatepicker(t)),this._attachments(e(t),l),this._autoSize(l),this._setDate(l,a),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(e,t,i){this._optionDatepicker(e,t,i)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var i=this._getInst(e);i&&(this._setDate(i,t),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(e,t){var i=this._getInst(e);return i&&!i.inline&&this._setDateFromField(i,t),i?this._getDate(i):null},_doKeyDown:function(t){var i,s,n,a=e.datepicker._getInst(t.target),o=!0,r=a.dpDiv.is(".ui-datepicker-rtl");if(a._keyEvent=!0,e.datepicker._datepickerShowing)switch(t.keyCode){case 9:e.datepicker._hideDatepicker(),o=!1;break;case 13:return n=e("td."+e.datepicker._dayOverClass+":not(."+e.datepicker._currentClass+")",a.dpDiv),n[0]&&e.datepicker._selectDay(t.target,a.selectedMonth,a.selectedYear,n[0]),i=e.datepicker._get(a,"onSelect"),i?(s=e.datepicker._formatDate(a),i.apply(a.input?a.input[0]:null,[s,a])):e.datepicker._hideDatepicker(),!1;case 27:e.datepicker._hideDatepicker();break;case 33:e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(a,"stepBigMonths"):-e.datepicker._get(a,"stepMonths"),"M");break;case 34:e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(a,"stepBigMonths"):+e.datepicker._get(a,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&e.datepicker._clearDate(t.target),o=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&e.datepicker._gotoToday(t.target),o=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,r?1:-1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(a,"stepBigMonths"):-e.datepicker._get(a,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,-7,"D"),o=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,r?-1:1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(a,"stepBigMonths"):+e.datepicker._get(a,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,7,"D"),o=t.ctrlKey||t.metaKey;break;default:o=!1}else 36===t.keyCode&&t.ctrlKey?e.datepicker._showDatepicker(this):o=!1;o&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(t){var i,s,n=e.datepicker._getInst(t.target);return e.datepicker._get(n,"constrainInput")?(i=e.datepicker._possibleChars(e.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),t.ctrlKey||t.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0
},_doKeyUp:function(t){var i,s=e.datepicker._getInst(t.target);if(s.input.val()!==s.lastVal)try{i=e.datepicker.parseDate(e.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,e.datepicker._getFormatConfig(s)),i&&(e.datepicker._setDateFromField(s),e.datepicker._updateAlternate(s),e.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(t){if(t=t.target||t,"input"!==t.nodeName.toLowerCase()&&(t=e("input",t.parentNode)[0]),!e.datepicker._isDisabledDatepicker(t)&&e.datepicker._lastInput!==t){var i,n,a,o,h,l,u;i=e.datepicker._getInst(t),e.datepicker._curInst&&e.datepicker._curInst!==i&&(e.datepicker._curInst.dpDiv.stop(!0,!0),i&&e.datepicker._datepickerShowing&&e.datepicker._hideDatepicker(e.datepicker._curInst.input[0])),n=e.datepicker._get(i,"beforeShow"),a=n?n.apply(t,[t,i]):{},a!==!1&&(r(i.settings,a),i.lastVal=null,e.datepicker._lastInput=t,e.datepicker._setDateFromField(i),e.datepicker._inDialog&&(t.value=""),e.datepicker._pos||(e.datepicker._pos=e.datepicker._findPos(t),e.datepicker._pos[1]+=t.offsetHeight),o=!1,e(t).parents().each(function(){return o|="fixed"===e(this).css("position"),!o}),h={left:e.datepicker._pos[0],top:e.datepicker._pos[1]},e.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),e.datepicker._updateDatepicker(i),h=e.datepicker._checkOffset(i,h,o),i.dpDiv.css({position:e.datepicker._inDialog&&e.blockUI?"static":o?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),i.inline||(l=e.datepicker._get(i,"showAnim"),u=e.datepicker._get(i,"duration"),i.dpDiv.css("z-index",s(e(t))+1),e.datepicker._datepickerShowing=!0,e.effects&&e.effects.effect[l]?i.dpDiv.show(l,e.datepicker._get(i,"showOptions"),u):i.dpDiv[l||"show"](l?u:null),e.datepicker._shouldFocusInput(i)&&i.input.focus(),e.datepicker._curInst=i))}},_updateDatepicker:function(t){this.maxRows=4,v=t,t.dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t);var i,s=this._getNumberOfMonths(t),n=s[1],a=17,r=t.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&t.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),t.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===e.datepicker._curInst&&e.datepicker._datepickerShowing&&e.datepicker._shouldFocusInput(t)&&t.input.focus(),t.yearshtml&&(i=t.yearshtml,setTimeout(function(){i===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year:first").replaceWith(t.yearshtml),i=t.yearshtml=null},0))},_shouldFocusInput:function(e){return e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&!e.input.is(":focus")},_checkOffset:function(t,i,s){var n=t.dpDiv.outerWidth(),a=t.dpDiv.outerHeight(),o=t.input?t.input.outerWidth():0,r=t.input?t.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:e(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:e(document).scrollTop());return i.left-=this._get(t,"isRTL")?n-o:0,i.left-=s&&i.left===t.input.offset().left?e(document).scrollLeft():0,i.top-=s&&i.top===t.input.offset().top+r?e(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+a>l&&l>a?Math.abs(a+r):0),i},_findPos:function(t){for(var i,s=this._getInst(t),n=this._get(s,"isRTL");t&&("hidden"===t.type||1!==t.nodeType||e.expr.filters.hidden(t));)t=t[n?"previousSibling":"nextSibling"];return i=e(t).offset(),[i.left,i.top]},_hideDatepicker:function(t){var i,s,n,a,o=this._curInst;!o||t&&o!==e.data(t,"datepicker")||this._datepickerShowing&&(i=this._get(o,"showAnim"),s=this._get(o,"duration"),n=function(){e.datepicker._tidyDialog(o)},e.effects&&(e.effects.effect[i]||e.effects[i])?o.dpDiv.hide(i,e.datepicker._get(o,"showOptions"),s,n):o.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,a=this._get(o,"onClose"),a&&a.apply(o.input?o.input[0]:null,[o.input?o.input.val():"",o]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),e.blockUI&&(e.unblockUI(),e("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(t){if(e.datepicker._curInst){var i=e(t.target),s=e.datepicker._getInst(i[0]);(i[0].id!==e.datepicker._mainDivId&&0===i.parents("#"+e.datepicker._mainDivId).length&&!i.hasClass(e.datepicker.markerClassName)&&!i.closest("."+e.datepicker._triggerClass).length&&e.datepicker._datepickerShowing&&(!e.datepicker._inDialog||!e.blockUI)||i.hasClass(e.datepicker.markerClassName)&&e.datepicker._curInst!==s)&&e.datepicker._hideDatepicker()}},_adjustDate:function(t,i,s){var n=e(t),a=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(a,i+("M"===s?this._get(a,"showCurrentAtPos"):0),s),this._updateDatepicker(a))},_gotoToday:function(t){var i,s=e(t),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(t,i,s){var n=e(t),a=this._getInst(n[0]);a["selected"+("M"===s?"Month":"Year")]=a["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(a),this._adjustDate(n)},_selectDay:function(t,i,s,n){var a,o=e(t);e(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(o[0])||(a=this._getInst(o[0]),a.selectedDay=a.currentDay=e("a",n).html(),a.selectedMonth=a.currentMonth=i,a.selectedYear=a.currentYear=s,this._selectDate(t,this._formatDate(a,a.currentDay,a.currentMonth,a.currentYear)))},_clearDate:function(t){var i=e(t);this._selectDate(i,"")},_selectDate:function(t,i){var s,n=e(t),a=this._getInst(n[0]);i=null!=i?i:this._formatDate(a),a.input&&a.input.val(i),this._updateAlternate(a),s=this._get(a,"onSelect"),s?s.apply(a.input?a.input[0]:null,[i,a]):a.input&&a.input.trigger("change"),a.inline?this._updateDatepicker(a):(this._hideDatepicker(),this._lastInput=a.input[0],"object"!=typeof a.input[0]&&a.input.focus(),this._lastInput=null)},_updateAlternate:function(t){var i,s,n,a=this._get(t,"altField");a&&(i=this._get(t,"altFormat")||this._get(t,"dateFormat"),s=this._getDate(t),n=this.formatDate(i,s,this._getFormatConfig(t)),e(a).each(function(){e(this).val(n)}))},noWeekends:function(e){var t=e.getDay();return[t>0&&6>t,""]},iso8601Week:function(e){var t,i=new Date(e.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),t=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((t-i)/864e5)/7)+1},parseDate:function(t,i,s){if(null==t||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,a,o,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,u="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),d=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,c=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,m=-1,g=-1,v=-1,y=-1,b=!1,_=function(e){var i=t.length>n+1&&t.charAt(n+1)===e;return i&&n++,i},x=function(e){var t=_(e),s="@"===e?14:"!"===e?20:"y"===e&&t?4:"o"===e?3:2,n="y"===e?s:1,a=RegExp("^\\d{"+n+","+s+"}"),o=i.substring(h).match(a);if(!o)throw"Missing number at position "+h;return h+=o[0].length,parseInt(o[0],10)},w=function(t,s,n){var a=-1,o=e.map(_(t)?n:s,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});if(e.each(o,function(e,t){var s=t[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(a=t[0],h+=s.length,!1):void 0}),-1!==a)return a+1;throw"Unknown name at position "+h},k=function(){if(i.charAt(h)!==t.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;t.length>n;n++)if(b)"'"!==t.charAt(n)||_("'")?k():b=!1;else switch(t.charAt(n)){case"d":v=x("d");break;case"D":w("D",d,c);break;case"o":y=x("o");break;case"m":g=x("m");break;case"M":g=w("M",p,f);break;case"y":m=x("y");break;case"@":r=new Date(x("@")),m=r.getFullYear(),g=r.getMonth()+1,v=r.getDate();break;case"!":r=new Date((x("!")-this._ticksTo1970)/1e4),m=r.getFullYear(),g=r.getMonth()+1,v=r.getDate();break;case"'":_("'")?k():b=!0;break;default:k()}if(i.length>h&&(o=i.substr(h),!/^\s+/.test(o)))throw"Extra/unparsed characters found in date: "+o;if(-1===m?m=(new Date).getFullYear():100>m&&(m+=(new Date).getFullYear()-(new Date).getFullYear()%100+(u>=m?0:-100)),y>-1)for(g=1,v=y;;){if(a=this._getDaysInMonth(m,g-1),a>=v)break;g++,v-=a}if(r=this._daylightSavingAdjust(new Date(m,g-1,v)),r.getFullYear()!==m||r.getMonth()+1!==g||r.getDate()!==v)throw"Invalid date";return r},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:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(e,t,i){if(!t)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,a=(i?i.dayNames:null)||this._defaults.dayNames,o=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(t){var i=e.length>s+1&&e.charAt(s+1)===t;return i&&s++,i},l=function(e,t,i){var s=""+t;if(h(e))for(;i>s.length;)s="0"+s;return s},u=function(e,t,i,s){return h(e)?s[t]:i[t]},d="",c=!1;if(t)for(s=0;e.length>s;s++)if(c)"'"!==e.charAt(s)||h("'")?d+=e.charAt(s):c=!1;else switch(e.charAt(s)){case"d":d+=l("d",t.getDate(),2);break;case"D":d+=u("D",t.getDay(),n,a);break;case"o":d+=l("o",Math.round((new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()-new Date(t.getFullYear(),0,0).getTime())/864e5),3);break;case"m":d+=l("m",t.getMonth()+1,2);break;case"M":d+=u("M",t.getMonth(),o,r);break;case"y":d+=h("y")?t.getFullYear():(10>t.getYear()%100?"0":"")+t.getYear()%100;break;case"@":d+=t.getTime();break;case"!":d+=1e4*t.getTime()+this._ticksTo1970;break;case"'":h("'")?d+="'":c=!0;break;default:d+=e.charAt(s)}return d},_possibleChars:function(e){var t,i="",s=!1,n=function(i){var s=e.length>t+1&&e.charAt(t+1)===i;return s&&t++,s};for(t=0;e.length>t;t++)if(s)"'"!==e.charAt(t)||n("'")?i+=e.charAt(t):s=!1;else switch(e.charAt(t)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=e.charAt(t)}return i},_get:function(e,t){return void 0!==e.settings[t]?e.settings[t]:this._defaults[t]},_setDateFromField:function(e,t){if(e.input.val()!==e.lastVal){var i=this._get(e,"dateFormat"),s=e.lastVal=e.input?e.input.val():null,n=this._getDefaultDate(e),a=n,o=this._getFormatConfig(e);try{a=this.parseDate(i,s,o)||n}catch(r){s=t?"":s}e.selectedDay=a.getDate(),e.drawMonth=e.selectedMonth=a.getMonth(),e.drawYear=e.selectedYear=a.getFullYear(),e.currentDay=s?a.getDate():0,e.currentMonth=s?a.getMonth():0,e.currentYear=s?a.getFullYear():0,this._adjustInstDate(e)}},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(t,i,s){var n=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},a=function(i){try{return e.datepicker.parseDate(e.datepicker._get(t,"dateFormat"),i,e.datepicker._getFormatConfig(t))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?e.datepicker._getDate(t):null)||new Date,a=n.getFullYear(),o=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":o+=parseInt(l[1],10),r=Math.min(r,e.datepicker._getDaysInMonth(a,o));break;case"y":case"Y":a+=parseInt(l[1],10),r=Math.min(r,e.datepicker._getDaysInMonth(a,o))}l=h.exec(i)}return new Date(a,o,r)},o=null==i||""===i?s:"string"==typeof i?a(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return o=o&&"Invalid Date"==""+o?s:o,o&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,i){var s=!t,n=e.selectedMonth,a=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),n===e.selectedMonth&&a===e.selectedYear||i||this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(s?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&""===e.input.val()?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(t){var i=this._get(t,"stepMonths"),s="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){e.datepicker._adjustDate(s,-i,"M")},next:function(){e.datepicker._adjustDate(s,+i,"M")},hide:function(){e.datepicker._hideDatepicker()},today:function(){e.datepicker._gotoToday(s)},selectDay:function(){return e.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return e.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return e.datepicker._selectMonthYear(s,this,"Y"),!1}};e(this).bind(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,i,s,n,a,o,r,h,l,u,d,c,p,f,m,g,v,y,b,_,x,w,k,T,D,S,M,C,N,A,P,I,z,H,F,E,O,j,W,L=new Date,R=this._daylightSavingAdjust(new Date(L.getFullYear(),L.getMonth(),L.getDate())),Y=this._get(e,"isRTL"),B=this._get(e,"showButtonPanel"),J=this._get(e,"hideIfNoPrevNext"),q=this._get(e,"navigationAsDateFormat"),K=this._getNumberOfMonths(e),V=this._get(e,"showCurrentAtPos"),U=this._get(e,"stepMonths"),Q=1!==K[0]||1!==K[1],G=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),X=this._getMinMaxDate(e,"min"),$=this._getMinMaxDate(e,"max"),Z=e.drawMonth-V,et=e.drawYear;if(0>Z&&(Z+=12,et--),$)for(t=this._daylightSavingAdjust(new Date($.getFullYear(),$.getMonth()-K[0]*K[1]+1,$.getDate())),t=X&&X>t?X:t;this._daylightSavingAdjust(new Date(et,Z,1))>t;)Z--,0>Z&&(Z=11,et--);for(e.drawMonth=Z,e.drawYear=et,i=this._get(e,"prevText"),i=q?this.formatDate(i,this._daylightSavingAdjust(new Date(et,Z-U,1)),this._getFormatConfig(e)):i,s=this._canAdjustMonth(e,-1,et,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>":J?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>",n=this._get(e,"nextText"),n=q?this.formatDate(n,this._daylightSavingAdjust(new Date(et,Z+U,1)),this._getFormatConfig(e)):n,a=this._canAdjustMonth(e,1,et,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>":J?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>",o=this._get(e,"currentText"),r=this._get(e,"gotoCurrent")&&e.currentDay?G:R,o=q?this.formatDate(o,r,this._getFormatConfig(e)):o,h=e.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(e,"closeText")+"</button>",l=B?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(Y?h:"")+(this._isInRange(e,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+o+"</button>":"")+(Y?"":h)+"</div>":"",u=parseInt(this._get(e,"firstDay"),10),u=isNaN(u)?0:u,d=this._get(e,"showWeek"),c=this._get(e,"dayNames"),p=this._get(e,"dayNamesMin"),f=this._get(e,"monthNames"),m=this._get(e,"monthNamesShort"),g=this._get(e,"beforeShowDay"),v=this._get(e,"showOtherMonths"),y=this._get(e,"selectOtherMonths"),b=this._getDefaultDate(e),_="",w=0;K[0]>w;w++){for(k="",this.maxRows=4,T=0;K[1]>T;T++){if(D=this._daylightSavingAdjust(new Date(et,Z,e.selectedDay)),S=" ui-corner-all",M="",Q){if(M+="<div class='ui-datepicker-group",K[1]>1)switch(T){case 0:M+=" ui-datepicker-group-first",S=" ui-corner-"+(Y?"right":"left");break;case K[1]-1:M+=" ui-datepicker-group-last",S=" ui-corner-"+(Y?"left":"right");break;default:M+=" ui-datepicker-group-middle",S=""}M+="'>"}for(M+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+S+"'>"+(/all|left/.test(S)&&0===w?Y?a:s:"")+(/all|right/.test(S)&&0===w?Y?s:a:"")+this._generateMonthYearHeader(e,Z,et,X,$,w>0||T>0,f,m)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",C=d?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"",x=0;7>x;x++)N=(x+u)%7,C+="<th scope='col'"+((x+u+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+c[N]+"'>"+p[N]+"</span></th>";for(M+=C+"</tr></thead><tbody>",A=this._getDaysInMonth(et,Z),et===e.selectedYear&&Z===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,A)),P=(this._getFirstDayOfMonth(et,Z)-u+7)%7,I=Math.ceil((P+A)/7),z=Q?this.maxRows>I?this.maxRows:I:I,this.maxRows=z,H=this._daylightSavingAdjust(new Date(et,Z,1-P)),F=0;z>F;F++){for(M+="<tr>",E=d?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(H)+"</td>":"",x=0;7>x;x++)O=g?g.apply(e.input?e.input[0]:null,[H]):[!0,""],j=H.getMonth()!==Z,W=j&&!y||!O[0]||X&&X>H||$&&H>$,E+="<td class='"+((x+u+6)%7>=5?" ui-datepicker-week-end":"")+(j?" ui-datepicker-other-month":"")+(H.getTime()===D.getTime()&&Z===e.selectedMonth&&e._keyEvent||b.getTime()===H.getTime()&&b.getTime()===D.getTime()?" "+this._dayOverClass:"")+(W?" "+this._unselectableClass+" ui-state-disabled":"")+(j&&!v?"":" "+O[1]+(H.getTime()===G.getTime()?" "+this._currentClass:"")+(H.getTime()===R.getTime()?" ui-datepicker-today":""))+"'"+(j&&!v||!O[2]?"":" title='"+O[2].replace(/'/g,"&#39;")+"'")+(W?"":" data-handler='selectDay' data-event='click' data-month='"+H.getMonth()+"' data-year='"+H.getFullYear()+"'")+">"+(j&&!v?"&#xa0;":W?"<span class='ui-state-default'>"+H.getDate()+"</span>":"<a class='ui-state-default"+(H.getTime()===R.getTime()?" ui-state-highlight":"")+(H.getTime()===G.getTime()?" ui-state-active":"")+(j?" ui-priority-secondary":"")+"' href='#'>"+H.getDate()+"</a>")+"</td>",H.setDate(H.getDate()+1),H=this._daylightSavingAdjust(H);M+=E+"</tr>"}Z++,Z>11&&(Z=0,et++),M+="</tbody></table>"+(Q?"</div>"+(K[0]>0&&T===K[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),k+=M}_+=k}return _+=l,e._keyEvent=!1,_},_generateMonthYearHeader:function(e,t,i,s,n,a,o,r){var h,l,u,d,c,p,f,m,g=this._get(e,"changeMonth"),v=this._get(e,"changeYear"),y=this._get(e,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",_="";if(a||!g)_+="<span class='ui-datepicker-month'>"+o[t]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,_+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",u=0;12>u;u++)(!h||u>=s.getMonth())&&(!l||n.getMonth()>=u)&&(_+="<option value='"+u+"'"+(u===t?" selected='selected'":"")+">"+r[u]+"</option>");_+="</select>"}if(y||(b+=_+(!a&&g&&v?"":"&#xa0;")),!e.yearshtml)if(e.yearshtml="",a||!v)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(d=this._get(e,"yearRange").split(":"),c=(new Date).getFullYear(),p=function(e){var t=e.match(/c[+\-].*/)?i+parseInt(e.substring(1),10):e.match(/[+\-].*/)?c+parseInt(e,10):parseInt(e,10);return isNaN(t)?c:t},f=p(d[0]),m=Math.max(f,p(d[1]||"")),f=s?Math.max(f,s.getFullYear()):f,m=n?Math.min(m,n.getFullYear()):m,e.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";m>=f;f++)e.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";e.yearshtml+="</select>",b+=e.yearshtml,e.yearshtml=null}return b+=this._get(e,"yearSuffix"),y&&(b+=(!a&&g&&v?"":"&#xa0;")+_),b+="</div>"},_adjustInstDate:function(e,t,i){var s=e.drawYear+("Y"===i?t:0),n=e.drawMonth+("M"===i?t:0),a=Math.min(e.selectedDay,this._getDaysInMonth(s,n))+("D"===i?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(s,n,a)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(e)},_restrictMinMax:function(e,t){var i=this._getMinMaxDate(e,"min"),s=this._getMinMaxDate(e,"max"),n=i&&i>t?i:t;return s&&n>s?s:n},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return null==t?[1,1]:"number"==typeof t?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return new Date(e,t,1).getDay()},_canAdjustMonth:function(e,t,i,s){var n=this._getNumberOfMonths(e),a=this._daylightSavingAdjust(new Date(i,s+(0>t?t:n[0]*n[1]),1));return 0>t&&a.setDate(this._getDaysInMonth(a.getFullYear(),a.getMonth())),this._isInRange(e,a)},_isInRange:function(e,t){var i,s,n=this._getMinMaxDate(e,"min"),a=this._getMinMaxDate(e,"max"),o=null,r=null,h=this._get(e,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),o=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(o+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||t.getTime()>=n.getTime())&&(!a||t.getTime()<=a.getTime())&&(!o||t.getFullYear()>=o)&&(!r||r>=t.getFullYear())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t="string"!=typeof t?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,i,s){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var n=t?"object"==typeof t?t:this._daylightSavingAdjust(new Date(s,i,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),n,this._getFormatConfig(e))}}),e.fn.datepicker=function(t){if(!this.length)return this;e.datepicker.initialized||(e(document).mousedown(e.datepicker._checkExternalClick),e.datepicker.initialized=!0),0===e("#"+e.datepicker._mainDivId).length&&e("body").append(e.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof t||"isDisabled"!==t&&"getDate"!==t&&"widget"!==t?"option"===t&&2===arguments.length&&"string"==typeof arguments[1]?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof t?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this].concat(i)):e.datepicker._attachDatepicker(this,t)}):e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i))},e.datepicker=new n,e.datepicker.initialized=!1,e.datepicker.uuid=(new Date).getTime(),e.datepicker.version="1.11.2",e.datepicker,e.widget("ui.draggable",e.ui.mouse,{version:"1.11.2",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._setHandleClassName(),this._mouseInit()},_setOption:function(e,t){this._super(e,t),"handle"===e&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(t){var i=this.options;return this._blurActiveElement(t),this.helper||i.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(t){this.iframeBlocks=this.document.find(t).map(function(){var t=e(this);return e("<div>").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var i=this.document[0];if(this.handleElement.is(t.target))try{i.activeElement&&"body"!==i.activeElement.nodeName.toLowerCase()&&e(i.activeElement).blur()}catch(s){}},_mouseStart:function(t){var i=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===e(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(t),this.originalPosition=this.position=this._generatePosition(t,!1),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._normalizeRightBottom(),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_refreshOffsets:function(e){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:e.pageX-this.offset.left,top:e.pageY-this.offset.top}},_mouseDrag:function(t,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",t,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var i=this,s=!1;return e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",t)!==!1&&i._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!1},_mouseUp:function(t){return this._unblockFrames(),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),this.handleElement.is(t.target)&&this.element.focus(),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){return this.options.handle?!!e(t.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this.handleElement.addClass("ui-draggable-handle")},_removeHandleClassName:function(){this.handleElement.removeClass("ui-draggable-handle")},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper),n=s?e(i.helper.apply(this.element[0],[t])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_isRootNode:function(e){return/(html|body)/i.test(e.tagName)||e===this.document[0]},_getParentOffset:function(){var t=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var e=this.element.position(),t=this._isRootNode(this.scrollParent[0]);return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+(t?0:this.scrollParent.scrollTop()),left:e.left-(parseInt(this.helper.css("left"),10)||0)+(t?0:this.scrollParent.scrollLeft())}},_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 t,i,s,n=this.options,a=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,e(window).scrollLeft()+e(window).width()-this.helperProportions.width-this.margins.left,e(window).scrollTop()+(e(window).height()||a.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,e(a).width()-this.helperProportions.width-this.margins.left,(e(a).height()||a.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=e(n.containment),s=i[0],s&&(t=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(t?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)
},_convertPositionTo:function(e,t){t||(t=this.position);var i="absolute"===e?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:t.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:t.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(e,t){var i,s,n,a,o=this.options,r=this._isRootNode(this.scrollParent[0]),h=e.pageX,l=e.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),t&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,e.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),e.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),e.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),e.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),o.grid&&(n=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-o.grid[1]:n+o.grid[1]:n,a=o.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,h=i?a-this.offset.click.left>=i[0]||a-this.offset.click.left>i[2]?a:a-this.offset.click.left>=i[0]?a-o.grid[0]:a+o.grid[0]:a),"y"===o.axis&&(h=this.originalPageX),"x"===o.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_normalizeRightBottom:function(){"y"!==this.options.axis&&"auto"!==this.helper.css("right")&&(this.helper.width(this.helper.width()),this.helper.css("right","auto")),"x"!==this.options.axis&&"auto"!==this.helper.css("bottom")&&(this.helper.height(this.helper.height()),this.helper.css("bottom","auto"))},_trigger:function(t,i,s){return s=s||this._uiHash(),e.ui.plugin.call(this,t,[i,s,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),e.Widget.prototype._trigger.call(this,t,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,i,s){var n=e.extend({},i,{item:s.element});s.sortables=[],e(s.options.connectToSortable).each(function(){var i=e(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",t,n))})},stop:function(t,i,s){var n=e.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,e.each(s.sortables,function(){var e=this;e.isOver?(e.isOver=0,s.cancelHelperRemoval=!0,e.cancelHelperRemoval=!1,e._storedCSS={position:e.placeholder.css("position"),top:e.placeholder.css("top"),left:e.placeholder.css("left")},e._mouseStop(t),e.options.helper=e.options._helper):(e.cancelHelperRemoval=!0,e._trigger("deactivate",t,n))})},drag:function(t,i,s){e.each(s.sortables,function(){var n=!1,a=this;a.positionAbs=s.positionAbs,a.helperProportions=s.helperProportions,a.offset.click=s.offset.click,a._intersectsWith(a.containerCache)&&(n=!0,e.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==a&&this._intersectsWith(this.containerCache)&&e.contains(a.element[0],this.element[0])&&(n=!1),n})),n?(a.isOver||(a.isOver=1,a.currentItem=i.helper.appendTo(a.element).data("ui-sortable-item",!0),a.options._helper=a.options.helper,a.options.helper=function(){return i.helper[0]},t.target=a.currentItem[0],a._mouseCapture(t,!0),a._mouseStart(t,!0,!0),a.offset.click.top=s.offset.click.top,a.offset.click.left=s.offset.click.left,a.offset.parent.left-=s.offset.parent.left-a.offset.parent.left,a.offset.parent.top-=s.offset.parent.top-a.offset.parent.top,s._trigger("toSortable",t),s.dropped=a.element,e.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,a.fromOutside=s),a.currentItem&&(a._mouseDrag(t),i.position=a.position)):a.isOver&&(a.isOver=0,a.cancelHelperRemoval=!0,a.options._revert=a.options.revert,a.options.revert=!1,a._trigger("out",t,a._uiHash(a)),a._mouseStop(t,!0),a.options.revert=a.options._revert,a.options.helper=a.options._helper,a.placeholder&&a.placeholder.remove(),s._refreshOffsets(t),i.position=s._generatePosition(t,!0),s._trigger("fromSortable",t),s.dropped=!1,e.each(s.sortables,function(){this.refreshPositions()}))})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,i,s){var n=e("body"),a=s.options;n.css("cursor")&&(a._cursor=n.css("cursor")),n.css("cursor",a.cursor)},stop:function(t,i,s){var n=s.options;n._cursor&&e("body").css("cursor",n._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,i,s){var n=e(i.helper),a=s.options;n.css("opacity")&&(a._opacity=n.css("opacity")),n.css("opacity",a.opacity)},stop:function(t,i,s){var n=s.options;n._opacity&&e(i.helper).css("opacity",n._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(e,t,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(t,i,s){var n=s.options,a=!1,o=s.scrollParentNotHidden[0],r=s.document[0];o!==r&&"HTML"!==o.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+o.offsetHeight-t.pageY<n.scrollSensitivity?o.scrollTop=a=o.scrollTop+n.scrollSpeed:t.pageY-s.overflowOffset.top<n.scrollSensitivity&&(o.scrollTop=a=o.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+o.offsetWidth-t.pageX<n.scrollSensitivity?o.scrollLeft=a=o.scrollLeft+n.scrollSpeed:t.pageX-s.overflowOffset.left<n.scrollSensitivity&&(o.scrollLeft=a=o.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(t.pageY-e(r).scrollTop()<n.scrollSensitivity?a=e(r).scrollTop(e(r).scrollTop()-n.scrollSpeed):e(window).height()-(t.pageY-e(r).scrollTop())<n.scrollSensitivity&&(a=e(r).scrollTop(e(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(t.pageX-e(r).scrollLeft()<n.scrollSensitivity?a=e(r).scrollLeft(e(r).scrollLeft()-n.scrollSpeed):e(window).width()-(t.pageX-e(r).scrollLeft())<n.scrollSensitivity&&(a=e(r).scrollLeft(e(r).scrollLeft()+n.scrollSpeed)))),a!==!1&&e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(s,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,i,s){var n=s.options;s.snapElements=[],e(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var t=e(this),i=t.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:i.top,left:i.left})})},drag:function(t,i,s){var n,a,o,r,h,l,u,d,c,p,f=s.options,m=f.snapTolerance,g=i.offset.left,v=g+s.helperProportions.width,y=i.offset.top,b=y+s.helperProportions.height;for(c=s.snapElements.length-1;c>=0;c--)h=s.snapElements[c].left-s.margins.left,l=h+s.snapElements[c].width,u=s.snapElements[c].top-s.margins.top,d=u+s.snapElements[c].height,h-m>v||g>l+m||u-m>b||y>d+m||!e.contains(s.snapElements[c].item.ownerDocument,s.snapElements[c].item)?(s.snapElements[c].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=!1):("inner"!==f.snapMode&&(n=m>=Math.abs(u-b),a=m>=Math.abs(d-y),o=m>=Math.abs(h-v),r=m>=Math.abs(l-g),n&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.top=s._convertPositionTo("relative",{top:d,left:0}).top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||a||o||r,"outer"!==f.snapMode&&(n=m>=Math.abs(u-y),a=m>=Math.abs(d-b),o=m>=Math.abs(h-g),r=m>=Math.abs(l-v),n&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.top=s._convertPositionTo("relative",{top:d-s.helperProportions.height,left:0}).top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[c].snapping&&(n||a||o||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=n||a||o||r||p)}}),e.ui.plugin.add("draggable","stack",{start:function(t,i,s){var n,a=s.options,o=e.makeArray(e(a.stack)).sort(function(t,i){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(i).css("zIndex"),10)||0)});o.length&&(n=parseInt(e(o[0]).css("zIndex"),10)||0,e(o).each(function(t){e(this).css("zIndex",n+t)}),this.css("zIndex",n+o.length))}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,i,s){var n=e(i.helper),a=s.options;n.css("zIndex")&&(a._zIndex=n.css("zIndex")),n.css("zIndex",a.zIndex)},stop:function(t,i,s){var n=s.options;n._zIndex&&e(i.helper).css("zIndex",n._zIndex)}}),e.ui.draggable,e.widget("ui.resizable",e.ui.mouse,{version:"1.11.2",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(e){return parseInt(e,10)||0},_isNumber:function(e){return!isNaN(parseInt(e,10))},_hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return t[s]>0?!0:(t[s]=1,n=t[s]>0,t[s]=0,n)},_create:function(){var t,i,s,n,a,o=this,r=this.options;if(this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(e("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({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=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom: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({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=r.handles||(e(".ui-resizable-handle",this.element).length?{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"}:"e,s,se"),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={},i=0;t.length>i;i++)s=e.trim(t[i]),a="ui-resizable-"+s,n=e("<div class='ui-resizable-handle "+a+"'></div>"),n.css({zIndex:r.zIndex}),"se"===s&&n.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(n);this._renderAxis=function(t){var i,s,n,a;t=t||this.element;for(i in this.handles)this.handles[i].constructor===String&&(this.handles[i]=this.element.children(this.handles[i]).first().show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(s=e(this.handles[i],this.element),a=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),t.css(n,a),this._proportionallyResize()),e(this.handles[i]).length},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=n&&n[1]?n[1]:"se")}),r.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(e(this).removeClass("ui-resizable-autohide"),o._handles.show())}).mouseleave(function(){r.disabled||o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,i=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(t){var i,s,n=!1;for(i in this.handles)s=e(this.handles[i])[0],(s===t.target||e.contains(s,t.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(t){var i,s,n,a=this.options,o=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),a.containment&&(i+=e(a.containment).scrollLeft()||0,s+=e(a.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:o.width(),height:o.height()},this.originalSize=this._helper?{width:o.outerWidth(),height:o.outerHeight()}:{width:o.width(),height:o.height()},this.sizeDiff={width:o.outerWidth()-o.width(),height:o.outerHeight()-o.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof a.aspectRatio?a.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor","auto"===n?this.axis+"-resize":n),o.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var i,s,n=this.originalMousePosition,a=this.axis,o=t.pageX-n.left||0,r=t.pageY-n.top||0,h=this._change[a];return this._updatePrevProperties(),h?(i=h.apply(this,[t,o,r]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(i=this._updateRatio(i,t)),i=this._respectSize(i,t),this._updateCache(i),this._propagate("resize",t),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",t,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(t){this.resizing=!1;var i,s,n,a,o,r,h,l=this.options,u=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:u.sizeDiff.height,a=s?0:u.sizeDiff.width,o={width:u.helper.width()-a,height:u.helper.height()-n},r=parseInt(u.element.css("left"),10)+(u.position.left-u.originalPosition.left)||null,h=parseInt(u.element.css("top"),10)+(u.position.top-u.originalPosition.top)||null,l.animate||this.element.css(e.extend(o,{top:h,left:r})),u.helper.height(u.size.height),u.helper.width(u.size.width),this._helper&&!l.animate&&this._proportionallyResize()),e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_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 e={};return this.position.top!==this.prevPosition.top&&(e.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(e.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(e.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(e.height=this.size.height+"px"),this.helper.css(e),e},_updateVirtualBoundaries:function(e){var t,i,s,n,a,o=this.options;a={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:1/0,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:1/0},(this._aspectRatio||e)&&(t=a.minHeight*this.aspectRatio,s=a.minWidth/this.aspectRatio,i=a.maxHeight*this.aspectRatio,n=a.maxWidth/this.aspectRatio,t>a.minWidth&&(a.minWidth=t),s>a.minHeight&&(a.minHeight=s),a.maxWidth>i&&(a.maxWidth=i),a.maxHeight>n&&(a.maxHeight=n)),this._vBoundaries=a},_updateCache:function(e){this.offset=this.helper.offset(),this._isNumber(e.left)&&(this.position.left=e.left),this._isNumber(e.top)&&(this.position.top=e.top),this._isNumber(e.height)&&(this.size.height=e.height),this._isNumber(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,i=this.size,s=this.axis;return this._isNumber(e.height)?e.width=e.height*this.aspectRatio:this._isNumber(e.width)&&(e.height=e.width/this.aspectRatio),"sw"===s&&(e.left=t.left+(i.width-e.width),e.top=null),"nw"===s&&(e.top=t.top+(i.height-e.height),e.left=t.left+(i.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,i=this.axis,s=this._isNumber(e.width)&&t.maxWidth&&t.maxWidth<e.width,n=this._isNumber(e.height)&&t.maxHeight&&t.maxHeight<e.height,a=this._isNumber(e.width)&&t.minWidth&&t.minWidth>e.width,o=this._isNumber(e.height)&&t.minHeight&&t.minHeight>e.height,r=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,l=/sw|nw|w/.test(i),u=/nw|ne|n/.test(i);return a&&(e.width=t.minWidth),o&&(e.height=t.minHeight),s&&(e.width=t.maxWidth),n&&(e.height=t.maxHeight),a&&l&&(e.left=r-t.minWidth),s&&l&&(e.left=r-t.maxWidth),o&&u&&(e.top=h-t.minHeight),n&&u&&(e.top=h-t.maxHeight),e.width||e.height||e.left||!e.top?e.width||e.height||e.top||!e.left||(e.left=null):e.top=null,e},_getPaddingPlusBorderDimensions:function(e){for(var t=0,i=[],s=[e.css("borderTopWidth"),e.css("borderRightWidth"),e.css("borderBottomWidth"),e.css("borderLeftWidth")],n=[e.css("paddingTop"),e.css("paddingRight"),e.css("paddingBottom"),e.css("paddingLeft")];4>t;t++)i[t]=parseInt(s[t],10)||0,i[t]+=parseInt(n[t],10)||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var e,t=0,i=this.helper||this.element;this._proportionallyResizeElements.length>t;t++)e=this._proportionallyResizeElements[t],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(e)),e.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var t=this.element,i=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(e,t,i){return{height:this.originalSize.height+i}},se:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},sw:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,i,s]))},ne:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},nw:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,i,s]))}},_propagate:function(t,i){e.ui.plugin.call(this,t,[i,this.ui()]),"resize"!==t&&this._trigger(t,i,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}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var i=e(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,a=n.length&&/textarea/i.test(n[0].nodeName),o=a&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=a?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-o},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,u=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(e.extend(h,u&&l?{top:u,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};n&&n.length&&e(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,i,s,n,a,o,r,h=e(this).resizable("instance"),l=h.options,u=h.element,d=l.containment,c=d instanceof e?d.get(0):/parent/.test(d)?u.parent().get(0):d;c&&(h.containerElement=e(c),/document/.test(d)||d===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(c),i=[],e(["Top","Right","Left","Bottom"]).each(function(e,s){i[e]=h._num(t.css("padding"+s))}),h.containerOffset=t.offset(),h.containerPosition=t.position(),h.containerSize={height:t.innerHeight()-i[3],width:t.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,a=h.containerSize.width,o=h._hasScroll(c,"left")?c.scrollWidth:a,r=h._hasScroll(c)?c.scrollHeight:n,h.parentData={element:c,left:s.left,top:s.top,width:o,height:r}))},resize:function(t){var i,s,n,a,o=e(this).resizable("instance"),r=o.options,h=o.containerOffset,l=o.position,u=o._aspectRatio||t.shiftKey,d={top:0,left:0},c=o.containerElement,p=!0;c[0]!==document&&/static/.test(c.css("position"))&&(d=h),l.left<(o._helper?h.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-h.left:o.position.left-d.left),u&&(o.size.height=o.size.width/o.aspectRatio,p=!1),o.position.left=r.helper?h.left:0),l.top<(o._helper?h.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-h.top:o.position.top),u&&(o.size.width=o.size.height*o.aspectRatio,p=!1),o.position.top=o._helper?h.top:0),n=o.containerElement.get(0)===o.element.parent().get(0),a=/relative|absolute/.test(o.containerElement.css("position")),n&&a?(o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top):(o.offset.left=o.element.offset().left,o.offset.top=o.element.offset().top),i=Math.abs(o.sizeDiff.width+(o._helper?o.offset.left-d.left:o.offset.left-h.left)),s=Math.abs(o.sizeDiff.height+(o._helper?o.offset.top-d.top:o.offset.top-h.top)),i+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-i,u&&(o.size.height=o.size.width/o.aspectRatio,p=!1)),s+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-s,u&&(o.size.width=o.size.height*o.aspectRatio,p=!1)),p||(o.position.left=o.prevPosition.left,o.position.top=o.prevPosition.top,o.size.width=o.prevSize.width,o.size.height=o.prevSize.height)},stop:function(){var t=e(this).resizable("instance"),i=t.options,s=t.containerOffset,n=t.containerPosition,a=t.containerElement,o=e(t.helper),r=o.offset(),h=o.outerWidth()-t.sizeDiff.width,l=o.outerHeight()-t.sizeDiff.height;t._helper&&!i.animate&&/relative/.test(a.css("position"))&&e(this).css({left:r.left-n.left-s.left,width:h,height:l}),t._helper&&!i.animate&&/static/.test(a.css("position"))&&e(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).resizable("instance"),i=t.options,s=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};"object"!=typeof i.alsoResize||i.alsoResize.parentNode?s(i.alsoResize):i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)})},resize:function(t,i){var s=e(this).resizable("instance"),n=s.options,a=s.originalSize,o=s.originalPosition,r={height:s.size.height-a.height||0,width:s.size.width-a.width||0,top:s.position.top-o.top||0,left:s.position.left-o.left||0},h=function(t,s){e(t).each(function(){var t=e(this),n=e(this).data("ui-resizable-alsoresize"),a={},o=s&&s.length?s:t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var i=(n[t]||0)+(r[t]||0);i&&i>=0&&(a[t]=i||null)}),t.css(a)})};"object"!=typeof n.alsoResize||n.alsoResize.nodeType?h(n.alsoResize):e.each(n.alsoResize,function(e,t){h(e,t)})},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).resizable("instance"),i=t.options,s=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof i.ghost?i.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t,i=e(this).resizable("instance"),s=i.options,n=i.size,a=i.originalSize,o=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,u=h[1]||1,d=Math.round((n.width-a.width)/l)*l,c=Math.round((n.height-a.height)/u)*u,p=a.width+d,f=a.height+c,m=s.maxWidth&&p>s.maxWidth,g=s.maxHeight&&f>s.maxHeight,v=s.minWidth&&s.minWidth>p,y=s.minHeight&&s.minHeight>f;s.grid=h,v&&(p+=l),y&&(f+=u),m&&(p-=l),g&&(f-=u),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=o.top-c):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=o.left-d):((0>=f-u||0>=p-l)&&(t=i._getPaddingPlusBorderDimensions(this)),f-u>0?(i.size.height=f,i.position.top=o.top-c):(f=u-t.height,i.size.height=f,i.position.top=o.top+a.height-f),p-l>0?(i.size.width=p,i.position.left=o.left-d):(p=u-t.height,i.size.width=p,i.position.left=o.left+a.width-p))}}),e.ui.resizable,e.widget("ui.dialog",{version:"1.11.2",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"Close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var i=e(this).css(t).offset().top;0>i&&e(this).css("top",t.top-i)}},resizable:!0,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:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_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"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&e.fn.draggable&&this._makeDraggable(),this.options.resizable&&e.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?e(t):this.document.find(t||"body").eq(0)},_destroy:function(){var e,t=this.originalPosition;this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},disable:e.noop,enable:e.noop,close:function(t){var i,s=this;if(this._isOpen&&this._trigger("beforeClose",t)!==!1){if(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),!this.opener.filter(":focusable").focus().length)try{i=this.document[0].activeElement,i&&"body"!==i.nodeName.toLowerCase()&&e(i).blur()}catch(n){}this._hide(this.uiDialog,this.options.hide,function(){s._trigger("close",t)})}},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(t,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+e(this).css("z-index")}).get(),a=Math.max.apply(null,n);return a>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",a+1),s=!0),s&&!i&&this._trigger("focus",t),s},open:function(){var t=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=e(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){t._focusTabbable(),t._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var e=this._focusedElement;e||(e=this.element.find("[autofocus]")),e.length||(e=this.element.find(":tabbable")),e.length||(e=this.uiDialogButtonPane.find(":tabbable")),e.length||(e=this.uiDialogTitlebarClose.filter(":tabbable")),e.length||(e=this.uiDialog),e.eq(0).focus()},_keepFocus:function(t){function i(){var t=this.document[0].activeElement,i=this.uiDialog[0]===t||e.contains(this.uiDialog[0],t);i||this._focusTabbable()}t.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=e("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===e.ui.keyCode.ESCAPE)return t.preventDefault(),this.close(t),void 0;
if(t.keyCode===e.ui.keyCode.TAB&&!t.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");t.target!==n[0]&&t.target!==this.uiDialog[0]||t.shiftKey?t.target!==s[0]&&t.target!==this.uiDialog[0]||!t.shiftKey||(this._delay(function(){n.focus()}),t.preventDefault()):(this._delay(function(){s.focus()}),t.preventDefault())}},mousedown:function(e){this._moveToTop(e)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=e("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(t){e(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=e("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(e){e.preventDefault(),this.close(e)}}),t=e("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(t),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(e){this.options.title||e.html("&#160;"),e.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=e("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=e("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var t=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),e.isEmptyObject(i)||e.isArray(i)&&!i.length?(this.uiDialog.removeClass("ui-dialog-buttons"),void 0):(e.each(i,function(i,s){var n,a;s=e.isFunction(s)?{click:s,text:i}:s,s=e.extend({type:"button"},s),n=s.click,s.click=function(){n.apply(t.element[0],arguments)},a={icons:s.icons,text:s.showText},delete s.icons,delete s.showText,e("<button></button>",s).button(a).appendTo(t.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function t(e){return{position:e.position,offset:e.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){e(this).addClass("ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,t(n))},drag:function(e,s){i._trigger("drag",e,t(s))},stop:function(n,a){var o=a.offset.left-i.document.scrollLeft(),r=a.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(o>=0?"+":"")+o+" "+"top"+(r>=0?"+":"")+r,of:i.window},e(this).removeClass("ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,t(a))}})},_makeResizable:function(){function t(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}var i=this,s=this.options,n=s.resizable,a=this.uiDialog.css("position"),o="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:o,start:function(s,n){e(this).addClass("ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,t(n))},resize:function(e,s){i._trigger("resize",e,t(s))},stop:function(n,a){var o=i.uiDialog.offset(),r=o.left-i.document.scrollLeft(),h=o.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},e(this).removeClass("ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,t(a))}}).css("position",a)},_trackFocus:function(){this._on(this.widget(),{focusin:function(t){this._makeFocusTarget(),this._focusedElement=e(t.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var t=this._trackingInstances(),i=e.inArray(this,t);-1!==i&&t.splice(i,1)},_trackingInstances:function(){var e=this.document.data("ui-dialog-instances");return e||(e=[],this.document.data("ui-dialog-instances",e)),e},_minHeight:function(){var e=this.options;return"auto"===e.height?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(){var e=this.uiDialog.is(":visible");e||this.uiDialog.show(),this.uiDialog.position(this.options.position),e||this.uiDialog.hide()},_setOptions:function(t){var i=this,s=!1,n={};e.each(t,function(e,t){i._setOption(e,t),e in i.sizeRelatedOptions&&(s=!0),e in i.resizableRelatedOptions&&(n[e]=t)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(e,t){var i,s,n=this.uiDialog;"dialogClass"===e&&n.removeClass(this.options.dialogClass).addClass(t),"disabled"!==e&&(this._super(e,t),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:""+t}),"draggable"===e&&(i=n.is(":data(ui-draggable)"),i&&!t&&n.draggable("destroy"),!i&&t&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(s=n.is(":data(ui-resizable)"),s&&!t&&n.resizable("destroy"),s&&"string"==typeof t&&n.resizable("option","handles",t),s||t===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var e,t,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),e=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),t=Math.max(0,s.minHeight-e),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-e):"none","auto"===s.height?this.element.css({minHeight:t,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-e)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var t=e(this);return e("<div>").css({position:"absolute",width:t.outerWidth(),height:t.outerHeight()}).appendTo(t.parent()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(t){return e(t.target).closest(".ui-dialog").length?!0:!!e(t.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var t=!0;this._delay(function(){t=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(e){t||this._allowInteraction(e)||(e.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=e("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),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&&this.overlay){var e=this.document.data("ui-dialog-overlays")-1;e?this.document.data("ui-dialog-overlays",e):this.document.unbind("focusin").removeData("ui-dialog-overlays"),this.overlay.remove(),this.overlay=null}}}),e.widget("ui.droppable",{version:"1.11.2",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=e.isFunction(s)?s:function(e){return e.is(s)},this.proportions=function(){return arguments.length?(t=arguments[0],void 0):t?t:t={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this.element.addClass("ui-droppable")},_addToManager:function(t){e.ui.ddmanager.droppables[t]=e.ui.ddmanager.droppables[t]||[],e.ui.ddmanager.droppables[t].push(this)},_splice:function(e){for(var t=0;e.length>t;t++)e[t]===this&&e.splice(t,1)},_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];this._splice(t),this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,i){if("accept"===t)this.accept=e.isFunction(i)?i:function(e){return e.is(i)};else if("scope"===t){var s=e.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(t,i)},_activate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",t,this.ui(i))},_deactivate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",t,this.ui(i))},_over:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(i)))},_out:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(i)))},_drop:function(t,i){var s=i||e.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=e(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&e.ui.intersect(s,e.extend(i,{offset:i.element.offset()}),i.options.tolerance,t)?(n=!0,!1):void 0}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(s)),this.element):!1):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(){function e(e,t,i){return e>=t&&t+i>e}return function(t,i,s,n){if(!i.offset)return!1;var a=(t.positionAbs||t.position.absolute).left+t.margins.left,o=(t.positionAbs||t.position.absolute).top+t.margins.top,r=a+t.helperProportions.width,h=o+t.helperProportions.height,l=i.offset.left,u=i.offset.top,d=l+i.proportions().width,c=u+i.proportions().height;switch(s){case"fit":return a>=l&&d>=r&&o>=u&&c>=h;case"intersect":return a+t.helperProportions.width/2>l&&d>r-t.helperProportions.width/2&&o+t.helperProportions.height/2>u&&c>h-t.helperProportions.height/2;case"pointer":return e(n.pageY,u,i.proportions().height)&&e(n.pageX,l,i.proportions().width);case"touch":return(o>=u&&c>=o||h>=u&&c>=h||u>o&&h>c)&&(a>=l&&d>=a||r>=l&&d>=r||l>a&&r>d);default:return!1}}}(),e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,i){var s,n,a=e.ui.ddmanager.droppables[t.options.scope]||[],o=i?i.type:null,r=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(s=0;a.length>s;s++)if(!(a[s].options.disabled||t&&!a[s].accept.call(a[s].element[0],t.currentItem||t.element))){for(n=0;r.length>n;n++)if(r[n]===a[s].element[0]){a[s].proportions().height=0;continue e}a[s].visible="none"!==a[s].element.css("display"),a[s].visible&&("mousedown"===o&&a[s]._activate.call(a[s],i),a[s].offset=a[s].element.offset(),a[s].proportions({width:a[s].element[0].offsetWidth,height:a[s].element[0].offsetHeight}))}},drop:function(t,i){var s=!1;return e.each((e.ui.ddmanager.droppables[t.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(t,i){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)})},drag:function(t,i){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,i),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,a,o=e.ui.intersect(t,this,this.options.tolerance,i),r=!o&&this.isover?"isout":o&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,a=this.element.parents(":data(ui-droppable)").filter(function(){return e(this).droppable("instance").options.scope===n}),a.length&&(s=e(a[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(t,i){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)}},e.ui.droppable;var y="ui-effects-",b=e;e.effects={effect:{}},function(e,t){function i(e,t,i){var s=d[t.type]||{};return null==e?i||!t.def?null:t.def:(e=s.floor?~~e:parseFloat(e),isNaN(e)?t.def:s.mod?(e+s.mod)%s.mod:0>e?0:e>s.max?s.max:e)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(e,a){var o,r=a.re.exec(i),h=r&&a.parse(r),l=a.space||"rgba";return h?(o=s[l](h),s[u[l].cache]=o[u[l].cache],n=s._rgba=o._rgba,!1):t}),n.length?("0,0,0,0"===n.join()&&e.extend(n,a.transparent),s):a[i]}function n(e,t,i){return i=(i+1)%1,1>6*i?e+6*(t-e)*i:1>2*i?t:2>3*i?e+6*(t-e)*(2/3-i):e}var a,o="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1],e[2],e[3],e[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(e){return[2.55*e[1],2.55*e[2],2.55*e[3],e[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(e){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(e){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(e){return[e[1],e[2]/100,e[3]/100,e[4]]}}],l=e.Color=function(t,i,s,n){return new e.Color.fn.parse(t,i,s,n)},u={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"}}}},d={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},c=l.support={},p=e("<p>")[0],f=e.each;p.style.cssText="background-color:rgba(1,1,1,.5)",c.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(u,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),l.fn=e.extend(l.prototype,{parse:function(n,o,r,h){if(n===t)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=e(n).css(o),o=t);var d=this,c=e.type(n),p=this._rgba=[];return o!==t&&(n=[n,o,r,h],c="array"),"string"===c?this.parse(s(n)||a._default):"array"===c?(f(u.rgba.props,function(e,t){p[t.idx]=i(n[t.idx],t)}),this):"object"===c?(n instanceof l?f(u,function(e,t){n[t.cache]&&(d[t.cache]=n[t.cache].slice())}):f(u,function(t,s){var a=s.cache;f(s.props,function(e,t){if(!d[a]&&s.to){if("alpha"===e||null==n[e])return;d[a]=s.to(d._rgba)}d[a][t.idx]=i(n[e],t,!0)}),d[a]&&0>e.inArray(null,d[a].slice(0,3))&&(d[a][3]=1,s.from&&(d._rgba=s.from(d[a])))}),this):t},is:function(e){var i=l(e),s=!0,n=this;return f(u,function(e,a){var o,r=i[a.cache];return r&&(o=n[a.cache]||a.to&&a.to(n._rgba)||[],f(a.props,function(e,i){return null!=r[i.idx]?s=r[i.idx]===o[i.idx]:t})),s}),s},_space:function(){var e=[],t=this;return f(u,function(i,s){t[s.cache]&&e.push(i)}),e.pop()},transition:function(e,t){var s=l(e),n=s._space(),a=u[n],o=0===this.alpha()?l("transparent"):this,r=o[a.cache]||a.to(o._rgba),h=r.slice();return s=s[a.cache],f(a.props,function(e,n){var a=n.idx,o=r[a],l=s[a],u=d[n.type]||{};null!==l&&(null===o?h[a]=l:(u.mod&&(l-o>u.mod/2?o+=u.mod:o-l>u.mod/2&&(o-=u.mod)),h[a]=i((l-o)*t+o,n)))}),this[n](h)},blend:function(t){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(t)._rgba;return l(e.map(i,function(e,t){return(1-s)*n[t]+s*e}))},toRgbaString:function(){var t="rgba(",i=e.map(this._rgba,function(e,t){return null==e?t>2?1:0:e});return 1===i[3]&&(i.pop(),t="rgb("),t+i.join()+")"},toHslaString:function(){var t="hsla(",i=e.map(this.hsla(),function(e,t){return null==e&&(e=t>2?1:0),t&&3>t&&(e=Math.round(100*e)+"%"),e});return 1===i[3]&&(i.pop(),t="hsl("),t+i.join()+")"},toHexString:function(t){var i=this._rgba.slice(),s=i.pop();return t&&i.push(~~(255*s)),"#"+e.map(i,function(e){return e=(e||0).toString(16),1===e.length?"0"+e:e}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,u.hsla.to=function(e){if(null==e[0]||null==e[1]||null==e[2])return[null,null,null,e[3]];var t,i,s=e[0]/255,n=e[1]/255,a=e[2]/255,o=e[3],r=Math.max(s,n,a),h=Math.min(s,n,a),l=r-h,u=r+h,d=.5*u;return t=h===r?0:s===r?60*(n-a)/l+360:n===r?60*(a-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=d?l/u:l/(2-u),[Math.round(t)%360,i,d,null==o?1:o]},u.hsla.from=function(e){if(null==e[0]||null==e[1]||null==e[2])return[null,null,null,e[3]];var t=e[0]/360,i=e[1],s=e[2],a=e[3],o=.5>=s?s*(1+i):s+i-s*i,r=2*s-o;return[Math.round(255*n(r,o,t+1/3)),Math.round(255*n(r,o,t)),Math.round(255*n(r,o,t-1/3)),a]},f(u,function(s,n){var a=n.props,o=n.cache,h=n.to,u=n.from;l.fn[s]=function(s){if(h&&!this[o]&&(this[o]=h(this._rgba)),s===t)return this[o].slice();var n,r=e.type(s),d="array"===r||"object"===r?s:arguments,c=this[o].slice();return f(a,function(e,t){var s=d["object"===r?e:t.idx];null==s&&(s=c[t.idx]),c[t.idx]=i(s,t)}),u?(n=l(u(c)),n[o]=c,n):l(c)},f(a,function(t,i){l.fn[t]||(l.fn[t]=function(n){var a,o=e.type(n),h="alpha"===t?this._hsla?"hsla":"rgba":s,l=this[h](),u=l[i.idx];return"undefined"===o?u:("function"===o&&(n=n.call(this,u),o=e.type(n)),null==n&&i.empty?this:("string"===o&&(a=r.exec(n),a&&(n=u+parseFloat(a[2])*("+"===a[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(t){var i=t.split(" ");f(i,function(t,i){e.cssHooks[i]={set:function(t,n){var a,o,r="";if("transparent"!==n&&("string"!==e.type(n)||(a=s(n)))){if(n=l(a||n),!c.rgba&&1!==n._rgba[3]){for(o="backgroundColor"===i?t.parentNode:t;(""===r||"transparent"===r)&&o&&o.style;)try{r=e.css(o,"backgroundColor"),o=o.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{t.style[i]=n}catch(h){}}},e.fx.step[i]=function(t){t.colorInit||(t.start=l(t.elem,i),t.end=l(t.end),t.colorInit=!0),e.cssHooks[i].set(t.elem,t.start.transition(t.end,t.pos))}})},l.hook(o),e.cssHooks.borderColor={expand:function(e){var t={};return f(["Top","Right","Bottom","Left"],function(i,s){t["border"+s+"Color"]=e}),t}},a=e.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"}}(b),function(){function t(t){var i,s,n=t.ownerDocument.defaultView?t.ownerDocument.defaultView.getComputedStyle(t,null):t.currentStyle,a={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(a[e.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(a[i]=n[i]);return a}function i(t,i){var s,a,o={};for(s in i)a=i[s],t[s]!==a&&(n[s]||(e.fx.step[s]||!isNaN(parseFloat(a)))&&(o[s]=a));return o}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,i){e.fx.step[i]=function(e){("none"!==e.end&&!e.setAttr||1===e.pos&&!e.setAttr)&&(b.style(e.elem,i,e.end),e.setAttr=!0)}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e.effects.animateClass=function(n,a,o,r){var h=e.speed(a,o,r);return this.queue(function(){var a,o=e(this),r=o.attr("class")||"",l=h.children?o.find("*").addBack():o;l=l.map(function(){var i=e(this);return{el:i,start:t(this)}}),a=function(){e.each(s,function(e,t){n[t]&&o[t+"Class"](n[t])})},a(),l=l.map(function(){return this.end=t(this.el[0]),this.diff=i(this.start,this.end),this}),o.attr("class",r),l=l.map(function(){var t=this,i=e.Deferred(),s=e.extend({},h,{queue:!1,complete:function(){i.resolve(t)}});return this.el.animate(this.diff,s),i.promise()}),e.when.apply(e,l.get()).done(function(){a(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),h.complete.call(o[0])})})},e.fn.extend({addClass:function(t){return function(i,s,n,a){return s?e.effects.animateClass.call(this,{add:i},s,n,a):t.apply(this,arguments)}}(e.fn.addClass),removeClass:function(t){return function(i,s,n,a){return arguments.length>1?e.effects.animateClass.call(this,{remove:i},s,n,a):t.apply(this,arguments)}}(e.fn.removeClass),toggleClass:function(t){return function(i,s,n,a,o){return"boolean"==typeof s||void 0===s?n?e.effects.animateClass.call(this,s?{add:i}:{remove:i},n,a,o):t.apply(this,arguments):e.effects.animateClass.call(this,{toggle:i},s,n,a)}}(e.fn.toggleClass),switchClass:function(t,i,s,n,a){return e.effects.animateClass.call(this,{add:i,remove:t},s,n,a)}})}(),function(){function t(t,i,s,n){return e.isPlainObject(t)&&(i=t,t=t.effect),t={effect:t},null==i&&(i={}),e.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||e.fx.speeds[i])&&(n=s,s=i,i={}),e.isFunction(s)&&(n=s,s=null),i&&e.extend(t,i),s=s||i.duration,t.duration=e.fx.off?0:"number"==typeof s?s:s in e.fx.speeds?e.fx.speeds[s]:e.fx.speeds._default,t.complete=n||i.complete,t}function i(t){return!t||"number"==typeof t||e.fx.speeds[t]?!0:"string"!=typeof t||e.effects.effect[t]?e.isFunction(t)?!0:"object"!=typeof t||t.effect?!1:!0:!0}e.extend(e.effects,{version:"1.11.2",save:function(e,t){for(var i=0;t.length>i;i++)null!==t[i]&&e.data(y+t[i],e[0].style[t[i]])},restore:function(e,t){var i,s;for(s=0;t.length>s;s++)null!==t[s]&&(i=e.data(y+t[s]),void 0===i&&(i=""),e.css(t[s],i))},setMode:function(e,t){return"toggle"===t&&(t=e.is(":hidden")?"show":"hide"),t},getBaseline:function(e,t){var i,s;switch(e[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=e[0]/t.height}switch(e[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=e[1]/t.width}return{x:s,y:i}},createWrapper:function(t){if(t.parent().is(".ui-effects-wrapper"))return t.parent();var i={width:t.outerWidth(!0),height:t.outerHeight(!0),"float":t.css("float")},s=e("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:t.width(),height:t.height()},a=document.activeElement;try{a.id}catch(o){a=document.body}return t.wrap(s),(t[0]===a||e.contains(t[0],a))&&e(a).focus(),s=t.parent(),"static"===t.css("position")?(s.css({position:"relative"}),t.css({position:"relative"})):(e.extend(i,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,s){i[s]=t.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(n),s.css(i).show()},removeWrapper:function(t){var i=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),(t[0]===i||e.contains(t[0],i))&&e(i).focus()),t},setTransition:function(t,i,s,n){return n=n||{},e.each(i,function(e,i){var a=t.cssUnit(i);a[0]>0&&(n[i]=a[0]*s+a[1])}),n}}),e.fn.extend({effect:function(){function i(t){function i(){e.isFunction(a)&&a.call(n[0]),e.isFunction(t)&&t()}var n=e(this),a=s.complete,r=s.mode;(n.is(":hidden")?"hide"===r:"show"===r)?(n[r](),i()):o.call(n[0],s,i)}var s=t.apply(this,arguments),n=s.mode,a=s.queue,o=e.effects.effect[s.effect];return e.fx.off||!o?n?this[n](s.duration,s.complete):this.each(function(){s.complete&&s.complete.call(this)}):a===!1?this.each(i):this.queue(a||"fx",i)},show:function(e){return function(s){if(i(s))return e.apply(this,arguments);var n=t.apply(this,arguments);return n.mode="show",this.effect.call(this,n)}}(e.fn.show),hide:function(e){return function(s){if(i(s))return e.apply(this,arguments);var n=t.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(e.fn.hide),toggle:function(e){return function(s){if(i(s)||"boolean"==typeof s)return e.apply(this,arguments);var n=t.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(e.fn.toggle),cssUnit:function(t){var i=this.css(t),s=[];return e.each(["em","px","%","pt"],function(e,t){i.indexOf(t)>0&&(s=[parseFloat(i),t])}),s}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,i){t[i]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return 0===e||1===e?e:-Math.pow(2,8*(e-1))*Math.sin((80*(e-1)-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){for(var t,i=4;((t=Math.pow(2,--i))-1)/11>e;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*t-2)/22-e,2)}}),e.each(t,function(t,i){e.easing["easeIn"+t]=i,e.easing["easeOut"+t]=function(e){return 1-i(1-e)},e.easing["easeInOut"+t]=function(e){return.5>e?i(2*e)/2:1-i(-2*e+2)/2}})}(),e.effects,e.effects.effect.blind=function(t,i){var s,n,a,o=e(this),r=/up|down|vertical/,h=/up|left|vertical|horizontal/,l=["position","top","bottom","left","right","height","width"],u=e.effects.setMode(o,t.mode||"hide"),d=t.direction||"up",c=r.test(d),p=c?"height":"width",f=c?"top":"left",m=h.test(d),g={},v="show"===u;o.parent().is(".ui-effects-wrapper")?e.effects.save(o.parent(),l):e.effects.save(o,l),o.show(),s=e.effects.createWrapper(o).css({overflow:"hidden"}),n=s[p](),a=parseFloat(s.css(f))||0,g[p]=v?n:0,m||(o.css(c?"bottom":"right",0).css(c?"top":"left","auto").css({position:"absolute"}),g[f]=v?a:n+a),v&&(s.css(p,0),m||s.css(f,a+n)),s.animate(g,{duration:t.duration,easing:t.easing,queue:!1,complete:function(){"hide"===u&&o.hide(),e.effects.restore(o,l),e.effects.removeWrapper(o),i()}})},e.effects.effect.bounce=function(t,i){var s,n,a,o=e(this),r=["position","top","bottom","left","right","height","width"],h=e.effects.setMode(o,t.mode||"effect"),l="hide"===h,u="show"===h,d=t.direction||"up",c=t.distance,p=t.times||5,f=2*p+(u||l?1:0),m=t.duration/f,g=t.easing,v="up"===d||"down"===d?"top":"left",y="up"===d||"left"===d,b=o.queue(),_=b.length;for((u||l)&&r.push("opacity"),e.effects.save(o,r),o.show(),e.effects.createWrapper(o),c||(c=o["top"===v?"outerHeight":"outerWidth"]()/3),u&&(a={opacity:1},a[v]=0,o.css("opacity",0).css(v,y?2*-c:2*c).animate(a,m,g)),l&&(c/=Math.pow(2,p-1)),a={},a[v]=0,s=0;p>s;s++)n={},n[v]=(y?"-=":"+=")+c,o.animate(n,m,g).animate(a,m,g),c=l?2*c:c/2;l&&(n={opacity:0},n[v]=(y?"-=":"+=")+c,o.animate(n,m,g)),o.queue(function(){l&&o.hide(),e.effects.restore(o,r),e.effects.removeWrapper(o),i()}),_>1&&b.splice.apply(b,[1,0].concat(b.splice(_,f+1))),o.dequeue()},e.effects.effect.clip=function(t,i){var s,n,a,o=e(this),r=["position","top","bottom","left","right","height","width"],h=e.effects.setMode(o,t.mode||"hide"),l="show"===h,u=t.direction||"vertical",d="vertical"===u,c=d?"height":"width",p=d?"top":"left",f={};e.effects.save(o,r),o.show(),s=e.effects.createWrapper(o).css({overflow:"hidden"}),n="IMG"===o[0].tagName?s:o,a=n[c](),l&&(n.css(c,0),n.css(p,a/2)),f[c]=l?a:0,f[p]=l?0:a/2,n.animate(f,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){l||o.hide(),e.effects.restore(o,r),e.effects.removeWrapper(o),i()}})},e.effects.effect.drop=function(t,i){var s,n=e(this),a=["position","top","bottom","left","right","opacity","height","width"],o=e.effects.setMode(n,t.mode||"hide"),r="show"===o,h=t.direction||"left",l="up"===h||"down"===h?"top":"left",u="up"===h||"left"===h?"pos":"neg",d={opacity:r?1:0};e.effects.save(n,a),n.show(),e.effects.createWrapper(n),s=t.distance||n["top"===l?"outerHeight":"outerWidth"](!0)/2,r&&n.css("opacity",0).css(l,"pos"===u?-s:s),d[l]=(r?"pos"===u?"+=":"-=":"pos"===u?"-=":"+=")+s,n.animate(d,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){"hide"===o&&n.hide(),e.effects.restore(n,a),e.effects.removeWrapper(n),i()}})},e.effects.effect.explode=function(t,i){function s(){b.push(this),b.length===d*c&&n()}function n(){p.css({visibility:"visible"}),e(b).remove(),m||p.hide(),i()}var a,o,r,h,l,u,d=t.pieces?Math.round(Math.sqrt(t.pieces)):3,c=d,p=e(this),f=e.effects.setMode(p,t.mode||"hide"),m="show"===f,g=p.show().css("visibility","hidden").offset(),v=Math.ceil(p.outerWidth()/c),y=Math.ceil(p.outerHeight()/d),b=[];for(a=0;d>a;a++)for(h=g.top+a*y,u=a-(d-1)/2,o=0;c>o;o++)r=g.left+o*v,l=o-(c-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-o*v,top:-a*y}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:v,height:y,left:r+(m?l*v:0),top:h+(m?u*y:0),opacity:m?0:1}).animate({left:r+(m?0:l*v),top:h+(m?0:u*y),opacity:m?1:0},t.duration||500,t.easing,s)},e.effects.effect.fade=function(t,i){var s=e(this),n=e.effects.setMode(s,t.mode||"toggle");s.animate({opacity:n},{queue:!1,duration:t.duration,easing:t.easing,complete:i})},e.effects.effect.fold=function(t,i){var s,n,a=e(this),o=["position","top","bottom","left","right","height","width"],r=e.effects.setMode(a,t.mode||"hide"),h="show"===r,l="hide"===r,u=t.size||15,d=/([0-9]+)%/.exec(u),c=!!t.horizFirst,p=h!==c,f=p?["width","height"]:["height","width"],m=t.duration/2,g={},v={};e.effects.save(a,o),a.show(),s=e.effects.createWrapper(a).css({overflow:"hidden"}),n=p?[s.width(),s.height()]:[s.height(),s.width()],d&&(u=parseInt(d[1],10)/100*n[l?0:1]),h&&s.css(c?{height:0,width:u}:{height:u,width:0}),g[f[0]]=h?n[0]:u,v[f[1]]=h?n[1]:0,s.animate(g,m,t.easing).animate(v,m,t.easing,function(){l&&a.hide(),e.effects.restore(a,o),e.effects.removeWrapper(a),i()})},e.effects.effect.highlight=function(t,i){var s=e(this),n=["backgroundImage","backgroundColor","opacity"],a=e.effects.setMode(s,t.mode||"show"),o={backgroundColor:s.css("backgroundColor")};"hide"===a&&(o.opacity=0),e.effects.save(s,n),s.show().css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(o,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){"hide"===a&&s.hide(),e.effects.restore(s,n),i()}})},e.effects.effect.size=function(t,i){var s,n,a,o=e(this),r=["position","top","bottom","left","right","width","height","overflow","opacity"],h=["position","top","bottom","left","right","overflow","opacity"],l=["width","height","overflow"],u=["fontSize"],d=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],c=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=e.effects.setMode(o,t.mode||"effect"),f=t.restore||"effect"!==p,m=t.scale||"both",g=t.origin||["middle","center"],v=o.css("position"),y=f?r:h,b={height:0,width:0,outerHeight:0,outerWidth:0};"show"===p&&o.show(),s={height:o.height(),width:o.width(),outerHeight:o.outerHeight(),outerWidth:o.outerWidth()},"toggle"===t.mode&&"show"===p?(o.from=t.to||b,o.to=t.from||s):(o.from=t.from||("show"===p?b:s),o.to=t.to||("hide"===p?b:s)),a={from:{y:o.from.height/s.height,x:o.from.width/s.width},to:{y:o.to.height/s.height,x:o.to.width/s.width}},("box"===m||"both"===m)&&(a.from.y!==a.to.y&&(y=y.concat(d),o.from=e.effects.setTransition(o,d,a.from.y,o.from),o.to=e.effects.setTransition(o,d,a.to.y,o.to)),a.from.x!==a.to.x&&(y=y.concat(c),o.from=e.effects.setTransition(o,c,a.from.x,o.from),o.to=e.effects.setTransition(o,c,a.to.x,o.to))),("content"===m||"both"===m)&&a.from.y!==a.to.y&&(y=y.concat(u).concat(l),o.from=e.effects.setTransition(o,u,a.from.y,o.from),o.to=e.effects.setTransition(o,u,a.to.y,o.to)),e.effects.save(o,y),o.show(),e.effects.createWrapper(o),o.css("overflow","hidden").css(o.from),g&&(n=e.effects.getBaseline(g,s),o.from.top=(s.outerHeight-o.outerHeight())*n.y,o.from.left=(s.outerWidth-o.outerWidth())*n.x,o.to.top=(s.outerHeight-o.to.outerHeight)*n.y,o.to.left=(s.outerWidth-o.to.outerWidth)*n.x),o.css(o.from),("content"===m||"both"===m)&&(d=d.concat(["marginTop","marginBottom"]).concat(u),c=c.concat(["marginLeft","marginRight"]),l=r.concat(d).concat(c),o.find("*[width]").each(function(){var i=e(this),s={height:i.height(),width:i.width(),outerHeight:i.outerHeight(),outerWidth:i.outerWidth()};
f&&e.effects.save(i,l),i.from={height:s.height*a.from.y,width:s.width*a.from.x,outerHeight:s.outerHeight*a.from.y,outerWidth:s.outerWidth*a.from.x},i.to={height:s.height*a.to.y,width:s.width*a.to.x,outerHeight:s.height*a.to.y,outerWidth:s.width*a.to.x},a.from.y!==a.to.y&&(i.from=e.effects.setTransition(i,d,a.from.y,i.from),i.to=e.effects.setTransition(i,d,a.to.y,i.to)),a.from.x!==a.to.x&&(i.from=e.effects.setTransition(i,c,a.from.x,i.from),i.to=e.effects.setTransition(i,c,a.to.x,i.to)),i.css(i.from),i.animate(i.to,t.duration,t.easing,function(){f&&e.effects.restore(i,l)})})),o.animate(o.to,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){0===o.to.opacity&&o.css("opacity",o.from.opacity),"hide"===p&&o.hide(),e.effects.restore(o,y),f||("static"===v?o.css({position:"relative",top:o.to.top,left:o.to.left}):e.each(["top","left"],function(e,t){o.css(t,function(t,i){var s=parseInt(i,10),n=e?o.to.left:o.to.top;return"auto"===i?n+"px":s+n+"px"})})),e.effects.removeWrapper(o),i()}})},e.effects.effect.scale=function(t,i){var s=e(this),n=e.extend(!0,{},t),a=e.effects.setMode(s,t.mode||"effect"),o=parseInt(t.percent,10)||(0===parseInt(t.percent,10)?0:"hide"===a?0:100),r=t.direction||"both",h=t.origin,l={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()},u={y:"horizontal"!==r?o/100:1,x:"vertical"!==r?o/100:1};n.effect="size",n.queue=!1,n.complete=i,"effect"!==a&&(n.origin=h||["middle","center"],n.restore=!0),n.from=t.from||("show"===a?{height:0,width:0,outerHeight:0,outerWidth:0}:l),n.to={height:l.height*u.y,width:l.width*u.x,outerHeight:l.outerHeight*u.y,outerWidth:l.outerWidth*u.x},n.fade&&("show"===a&&(n.from.opacity=0,n.to.opacity=1),"hide"===a&&(n.from.opacity=1,n.to.opacity=0)),s.effect(n)},e.effects.effect.puff=function(t,i){var s=e(this),n=e.effects.setMode(s,t.mode||"hide"),a="hide"===n,o=parseInt(t.percent,10)||150,r=o/100,h={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()};e.extend(t,{effect:"scale",queue:!1,fade:!0,mode:n,complete:i,percent:a?o:100,from:a?h:{height:h.height*r,width:h.width*r,outerHeight:h.outerHeight*r,outerWidth:h.outerWidth*r}}),s.effect(t)},e.effects.effect.pulsate=function(t,i){var s,n=e(this),a=e.effects.setMode(n,t.mode||"show"),o="show"===a,r="hide"===a,h=o||"hide"===a,l=2*(t.times||5)+(h?1:0),u=t.duration/l,d=0,c=n.queue(),p=c.length;for((o||!n.is(":visible"))&&(n.css("opacity",0).show(),d=1),s=1;l>s;s++)n.animate({opacity:d},u,t.easing),d=1-d;n.animate({opacity:d},u,t.easing),n.queue(function(){r&&n.hide(),i()}),p>1&&c.splice.apply(c,[1,0].concat(c.splice(p,l+1))),n.dequeue()},e.effects.effect.shake=function(t,i){var s,n=e(this),a=["position","top","bottom","left","right","height","width"],o=e.effects.setMode(n,t.mode||"effect"),r=t.direction||"left",h=t.distance||20,l=t.times||3,u=2*l+1,d=Math.round(t.duration/u),c="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},m={},g={},v=n.queue(),y=v.length;for(e.effects.save(n,a),n.show(),e.effects.createWrapper(n),f[c]=(p?"-=":"+=")+h,m[c]=(p?"+=":"-=")+2*h,g[c]=(p?"-=":"+=")+2*h,n.animate(f,d,t.easing),s=1;l>s;s++)n.animate(m,d,t.easing).animate(g,d,t.easing);n.animate(m,d,t.easing).animate(f,d/2,t.easing).queue(function(){"hide"===o&&n.hide(),e.effects.restore(n,a),e.effects.removeWrapper(n),i()}),y>1&&v.splice.apply(v,[1,0].concat(v.splice(y,u+1))),n.dequeue()},e.effects.effect.slide=function(t,i){var s,n=e(this),a=["position","top","bottom","left","right","width","height"],o=e.effects.setMode(n,t.mode||"show"),r="show"===o,h=t.direction||"left",l="up"===h||"down"===h?"top":"left",u="up"===h||"left"===h,d={};e.effects.save(n,a),n.show(),s=t.distance||n["top"===l?"outerHeight":"outerWidth"](!0),e.effects.createWrapper(n).css({overflow:"hidden"}),r&&n.css(l,u?isNaN(s)?"-"+s:-s:s),d[l]=(r?u?"+=":"-=":u?"-=":"+=")+s,n.animate(d,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){"hide"===o&&n.hide(),e.effects.restore(n,a),e.effects.removeWrapper(n),i()}})},e.effects.effect.transfer=function(t,i){var s=e(this),n=e(t.to),a="fixed"===n.css("position"),o=e("body"),r=a?o.scrollTop():0,h=a?o.scrollLeft():0,l=n.offset(),u={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},d=s.offset(),c=e("<div class='ui-effects-transfer'></div>").appendTo(document.body).addClass(t.className).css({top:d.top-r,left:d.left-h,height:s.innerHeight(),width:s.innerWidth(),position:a?"fixed":"absolute"}).animate(u,t.duration,t.easing,function(){c.remove(),i()})},e.widget("ui.progressbar",{version:"1.11.2",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=e("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(e){return void 0===e?this.options.value:(this.options.value=this._constrainedValue(e),this._refreshValue(),void 0)},_constrainedValue:function(e){return void 0===e&&(e=this.options.value),this.indeterminate=e===!1,"number"!=typeof e&&(e=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,e))},_setOptions:function(e){var t=e.value;delete e.value,this._super(e),this.options.value=this._constrainedValue(t),this._refreshValue()},_setOption:function(e,t){"max"===e&&(t=Math.max(this.min,t)),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this._super(e,t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var t=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||t>this.min).toggleClass("ui-corner-right",t===this.options.max).width(i.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=e("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":t}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==t&&(this.oldValue=t,this._trigger("change")),t===this.options.max&&this._trigger("complete")}}),e.widget("ui.selectable",e.ui.mouse,{version:"1.11.2",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(i.options.filter,i.element[0]),t.addClass("ui-selectee"),t.each(function(){var t=e(this),i=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:i.left,top:i.top,right:i.left+t.outerWidth(),bottom:i.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=t.addClass("ui-selectee"),this._mouseInit(),this.helper=e("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(t){var i=this,s=this.options;this.opos=[t.pageX,t.pageY],this.options.disabled||(this.selectees=e(s.filter,this.element[0]),this._trigger("start",t),e(s.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=e.data(this,"selectable-item");s.startselected=!0,t.metaKey||t.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",t,{unselecting:s.element}))}),e(t.target).parents().addBack().each(function(){var s,n=e.data(this,"selectable-item");return n?(s=!t.metaKey&&!t.ctrlKey||!n.$element.hasClass("ui-selected"),n.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",t,{selecting:n.element}):i._trigger("unselecting",t,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(t){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,a=this.opos[0],o=this.opos[1],r=t.pageX,h=t.pageY;return a>r&&(i=r,r=a,a=i),o>h&&(i=h,h=o,o=i),this.helper.css({left:a,top:o,width:r-a,height:h-o}),this.selectees.each(function(){var i=e.data(this,"selectable-item"),l=!1;i&&i.element!==s.element[0]&&("touch"===n.tolerance?l=!(i.left>r||a>i.right||i.top>h||o>i.bottom):"fit"===n.tolerance&&(l=i.left>a&&r>i.right&&i.top>o&&h>i.bottom),l?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",t,{selecting:i.element}))):(i.selecting&&((t.metaKey||t.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",t,{unselecting:i.element}))),i.selected&&(t.metaKey||t.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",t,{unselecting:i.element})))))}),!1}},_mouseStop:function(t){var i=this;return this.dragged=!1,e(".ui-unselecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",t,{unselected:s.element})}),e(".ui-selecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",t,{selected:s.element})}),this._trigger("stop",t),this.helper.remove(),!1}}),e.widget("ui.selectmenu",{version:"1.11.2",defaultElement:"<select>",options:{appendTo:null,disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:null,change:null,close:null,focus:null,open:null,select:null},_create:function(){var e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this.options.disabled&&this.disable()},_drawButton:function(){var t=this,i=this.element.attr("tabindex");this.label=e("label[for='"+this.ids.element+"']").attr("for",this.ids.button),this._on(this.label,{click:function(e){this.button.focus(),e.preventDefault()}}),this.element.hide(),this.button=e("<span>",{"class":"ui-selectmenu-button ui-widget ui-state-default ui-corner-all",tabindex:i||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"}).insertAfter(this.element),e("<span>",{"class":"ui-icon "+this.options.icons.button}).prependTo(this.button),this.buttonText=e("<span>",{"class":"ui-selectmenu-text"}).appendTo(this.button),this._setText(this.buttonText,this.element.find("option:selected").text()),this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){t.menuItems||t._refreshMenu()}),this._hoverable(this.button),this._focusable(this.button)},_drawMenu:function(){var t=this;this.menu=e("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=e("<div>",{"class":"ui-selectmenu-menu ui-front"}).append(this.menu).appendTo(this._appendTo()),this.menuInstance=this.menu.menu({role:"listbox",select:function(e,i){e.preventDefault(),t._setSelection(),t._select(i.item.data("ui-selectmenu-item"),e)},focus:function(e,i){var s=i.item.data("ui-selectmenu-item");null!=t.focusIndex&&s.index!==t.focusIndex&&(t._trigger("focus",e,{item:s}),t.isOpen||t._select(s,e)),t.focusIndex=s.index,t.button.attr("aria-activedescendant",t.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menu.addClass("ui-corner-bottom").removeClass("ui-corner-all"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this._setText(this.buttonText,this._getSelectedItem().text()),this.options.width||this._resizeButton()},_refreshMenu:function(){this.menu.empty();var e,t=this.element.find("option");t.length&&(this._parseOptions(t),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup"),e=this._getSelectedItem(),this.menuInstance.focus(null,e),this._setAria(e.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(e){this.options.disabled||(this.menuItems?(this.menu.find(".ui-state-focus").removeClass("ui-state-focus"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",e))},_position:function(){this.menuWrap.position(e.extend({of:this.button},this.options.position))},close:function(e){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",e))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderMenu:function(t,i){var s=this,n="";e.each(i,function(i,a){a.optgroup!==n&&(e("<li>",{"class":"ui-selectmenu-optgroup ui-menu-divider"+(a.element.parent("optgroup").prop("disabled")?" ui-state-disabled":""),text:a.optgroup}).appendTo(t),n=a.optgroup),s._renderItemData(t,a)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-selectmenu-item",t)},_renderItem:function(t,i){var s=e("<li>");return i.disabled&&s.addClass("ui-state-disabled"),this._setText(s,i.label),s.appendTo(t)},_setText:function(e,t){t?e.text(t):e.html("&#160;")},_move:function(e,t){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex):(i=this.menuItems.eq(this.element[0].selectedIndex),n+=":not(.ui-state-disabled)"),s="first"===e||"last"===e?i["first"===e?"prevAll":"nextAll"](n).eq(-1):i[e+"All"](n).eq(0),s.length&&this.menuInstance.focus(t,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex)},_toggle:function(e){this[this.isOpen?"close":"open"](e)},_setSelection:function(){var e;this.range&&(window.getSelection?(e=window.getSelection(),e.removeAllRanges(),e.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(t){this.isOpen&&(e(t.target).closest(".ui-selectmenu-menu, #"+this.ids.button).length||this.close(t))}},_buttonEvents:{mousedown:function(){var e;window.getSelection?(e=window.getSelection(),e.rangeCount&&(this.range=e.getRangeAt(0))):this.range=document.selection.createRange()},click:function(e){this._setSelection(),this._toggle(e)},keydown:function(t){var i=!0;switch(t.keyCode){case e.ui.keyCode.TAB:case e.ui.keyCode.ESCAPE:this.close(t),i=!1;break;case e.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(t);break;case e.ui.keyCode.UP:t.altKey?this._toggle(t):this._move("prev",t);break;case e.ui.keyCode.DOWN:t.altKey?this._toggle(t):this._move("next",t);break;case e.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(t):this._toggle(t);break;case e.ui.keyCode.LEFT:this._move("prev",t);break;case e.ui.keyCode.RIGHT:this._move("next",t);break;case e.ui.keyCode.HOME:case e.ui.keyCode.PAGE_UP:this._move("first",t);break;case e.ui.keyCode.END:case e.ui.keyCode.PAGE_DOWN:this._move("last",t);break;default:this.menu.trigger(t),i=!1}i&&t.preventDefault()}},_selectFocusedItem:function(e){var t=this.menuItems.eq(this.focusIndex);t.hasClass("ui-state-disabled")||this._select(t.data("ui-selectmenu-item"),e)},_select:function(e,t){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=e.index,this._setText(this.buttonText,e.label),this._setAria(e),this._trigger("select",t,{item:e}),e.index!==i&&this._trigger("change",t,{item:e}),this.close(t)},_setAria:function(e){var t=this.menuItems.eq(e.index).attr("id");this.button.attr({"aria-labelledby":t,"aria-activedescendant":t}),this.menu.attr("aria-activedescendant",t)},_setOption:function(e,t){"icons"===e&&this.button.find("span.ui-icon").removeClass(this.options.icons.button).addClass(t.button),this._super(e,t),"appendTo"===e&&this.menuWrap.appendTo(this._appendTo()),"disabled"===e&&(this.menuInstance.option("disabled",t),this.button.toggleClass("ui-state-disabled",t).attr("aria-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)),"width"===e&&this._resizeButton()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t&&t[0]||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_toggleAttr:function(){this.button.toggleClass("ui-corner-top",this.isOpen).toggleClass("ui-corner-all",!this.isOpen).attr("aria-expanded",this.isOpen),this.menuWrap.toggleClass("ui-selectmenu-open",this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var e=this.options.width;e||(e=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(e)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){return{disabled:this.element.prop("disabled")}},_parseOptions:function(t){var i=[];t.each(function(t,s){var n=e(s),a=n.parent("optgroup");i.push({element:n,index:t,value:n.attr("value"),label:n.text(),optgroup:a.attr("label")||"",disabled:a.prop("disabled")||n.prop("disabled")})}),this.items=i},_destroy:function(){this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.label.attr("for",this.ids.element)}}),e.widget("ui.slider",e.ui.mouse,{version:"1.11.2",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this._refresh(),this._setOption("disabled",this.options.disabled),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var t,i,s=this.options,n=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),a="<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>",o=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),t=n.length;i>t;t++)o.push(a);this.handles=n.add(e(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)})},_createRange:function(){var t=this.options,i="";t.range?(t.range===!0&&(t.values?t.values.length&&2!==t.values.length?t.values=[t.values[0],t.values[0]]:e.isArray(t.values)&&(t.values=t.values.slice(0)):t.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=e("<div></div>").appendTo(this.element),i="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(i+("min"===t.range||"max"===t.range?" ui-slider-range-"+t.range:""))):(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(),this.range&&this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var i,s,n,a,o,r,h,l,u=this,d=this.options;return d.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:t.pageX,y:t.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var i=Math.abs(s-u.values(t));(n>i||n===i&&(t===u._lastChangedValue||u.values(t)===d.min))&&(n=i,a=e(this),o=t)}),r=this._start(t,o),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,a.addClass("ui-state-active").focus(),h=a.offset(),l=!e(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:t.pageX-h.left-a.width()/2,top:t.pageY-h.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},i=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,i),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,i,s,n,a;return"horizontal"===this.orientation?(t=this.elementSize.width,i=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,i=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/t,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),a=this._valueMin()+s*n,this._trimAlignValue(a)},_start:function(e,t){var i={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._trigger("start",e,i)},_slide:function(e,t,i){var s,n,a;this.options.values&&this.options.values.length?(s=this.values(t?0:1),2===this.options.values.length&&this.options.range===!0&&(0===t&&i>s||1===t&&s>i)&&(i=s),i!==this.values(t)&&(n=this.values(),n[t]=i,a=this._trigger("slide",e,{handle:this.handles[t],value:i,values:n}),s=this.values(t?0:1),a!==!1&&this.values(t,i))):i!==this.value()&&(a=this._trigger("slide",e,{handle:this.handles[t],value:i}),a!==!1&&this.value(i))},_stop:function(e,t){var i={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._trigger("stop",e,i)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var i={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._lastChangedValue=t,this._trigger("change",e,i)}},value:function(e){return arguments.length?(this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(t,i){var s,n,a;if(arguments.length>1)return this.options.values[t]=this._trimAlignValue(i),this._refreshValue(),this._change(null,t),void 0;if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();for(s=this.options.values,n=arguments[0],a=0;s.length>a;a+=1)s[a]=this._trimAlignValue(n[a]),this._change(null,a);this._refreshValue()},_setOption:function(t,i){var s,n=0;switch("range"===t&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),e.isArray(this.options.values)&&(n=this.options.values.length),"disabled"===t&&this.element.toggleClass("ui-state-disabled",!!i),this._super(t,i),t){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue(),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=0;n>s;s+=1)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e)},_values:function(e){var t,i,s;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t);if(this.options.values&&this.options.values.length){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(e){if(this._valueMin()>=e)return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,i=(e-this._valueMin())%t,s=e-i;return 2*Math.abs(i)>=t&&(s+=i>0?t:-t),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var e=(this.options.max-this._valueMin())%this.options.step;this.max=this.options.max-e},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshValue:function(){var t,i,s,n,a,o=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,u={};this.options.values&&this.options.values.length?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),u["horizontal"===h.orientation?"left":"bottom"]=i+"%",e(this).stop(1,1)[l?"animate":"css"](u,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-t+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-t+"%"},{queue:!1,duration:r.animate}))),t=i}):(s=this.value(),n=this._valueMin(),a=this._valueMax(),i=a!==n?100*((s-n)/(a-n)):0,u["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](u,r.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===o&&"horizontal"===this.orientation&&this.range[l?"animate":"css"]({width:100-i+"%"},{queue:!1,duration:r.animate}),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===o&&"vertical"===this.orientation&&this.range[l?"animate":"css"]({height:100-i+"%"},{queue:!1,duration:r.animate}))},_handleEvents:{keydown:function(t){var i,s,n,a,o=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(t.preventDefault(),!this._keySliding&&(this._keySliding=!0,e(t.target).addClass("ui-state-active"),i=this._start(t,o),i===!1))return}switch(a=this.options.step,s=n=this.options.values&&this.options.values.length?this.values(o):this.value(),t.keyCode){case e.ui.keyCode.HOME:n=this._valueMin();break;case e.ui.keyCode.END:n=this._valueMax();break;case e.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case e.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+a);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-a)}this._slide(t,o,n)},keyup:function(t){var i=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,i),this._change(t,i),e(t.target).removeClass("ui-state-active"))}}}),e.widget("ui.sortable",e.ui.mouse,{version:"1.11.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,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(e,t,i){return e>=t&&t+i>e},_isFloating:function(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===e.axis||this._isFloating(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(e,t){this._super(e,t),"handle"===e&&this._setHandleClassName()},_setHandleClassName:function(){this.element.find(".ui-sortable-handle").removeClass("ui-sortable-handle"),e.each(this.items,function(){(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item).addClass("ui-sortable-handle")})},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").find(".ui-sortable-handle").removeClass("ui-sortable-handle"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(t,i){var s=null,n=!1,a=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(t),e(t.target).parents().each(function(){return e.data(this,a.widgetName+"-item")===a?(s=e(this),!1):void 0}),e.data(t.target,a.widgetName+"-item")===a&&(s=e(t.target)),s?!this.options.handle||i||(e(this.options.handle,s).find("*").addBack().each(function(){this===t.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(t,i,s){var n,a,o=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(a=this.document.find("body"),this.storedCursor=a.css("cursor"),a.css("cursor",o.cursor),this.storedStylesheet=e("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(a)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",t,this._uiHash(this));
return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var i,s,n,a,o=this.options,r=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+o.scrollSpeed:t.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+o.scrollSpeed:t.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(t.pageY-e(document).scrollTop()<o.scrollSensitivity?r=e(document).scrollTop(e(document).scrollTop()-o.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<o.scrollSensitivity&&(r=e(document).scrollTop(e(document).scrollTop()+o.scrollSpeed)),t.pageX-e(document).scrollLeft()<o.scrollSensitivity?r=e(document).scrollLeft(e(document).scrollLeft()-o.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<o.scrollSensitivity&&(r=e(document).scrollLeft(e(document).scrollLeft()+o.scrollSpeed))),r!==!1&&e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],a=this._intersectsWithPointer(s),a&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===a?"next":"prev"]()[0]!==n&&!e.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],n):!0)){if(this.direction=1===a?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,i){if(t){if(e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t),this.options.revert){var s=this,n=this.placeholder.offset(),a=this.options.axis,o={};a&&"x"!==a||(o.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),a&&"y"!==a||(o.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,e(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){s._clear(t)})}else this._clear(t,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},e(i).each(function(){var i=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);i&&s.push((t.key||i[1]+"[]")+"="+(t.key&&t.expression?i[1]:i[2]))}),!s.length&&t.key&&s.push(t.key+"="),s.join("&")},toArray:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},i.each(function(){s.push(e(t.item||this).attr(t.attribute||"id")||"")}),s},_intersectsWith:function(e){var t=this.positionAbs.left,i=t+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,a=e.left,o=a+e.width,r=e.top,h=r+e.height,l=this.offset.click.top,u=this.offset.click.left,d="x"===this.options.axis||s+l>r&&h>s+l,c="y"===this.options.axis||t+u>a&&o>t+u,p=d&&c;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?p:t+this.helperProportions.width/2>a&&o>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(e){var t="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),i="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),s=t&&i,n=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return s?this.floating?a&&"right"===a||"down"===n?2:1:n&&("down"===n?2:1):!1},_intersectsWithSides:function(e){var t=this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&t||"up"===s&&!t)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function i(){r.push(this)}var s,n,a,o,r=[],h=[],l=this._connectWith();if(l&&t)for(s=l.length-1;s>=0;s--)for(a=e(l[s]),n=a.length-1;n>=0;n--)o=e.data(a[n],this.widgetFullName),o&&o!==this&&!o.options.disabled&&h.push([e.isFunction(o.options.items)?o.options.items.call(o.element):e(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);for(h.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return e(r)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var i=0;t.length>i;i++)if(t[i]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var i,s,n,a,o,r,h,l,u=this.items,d=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],c=this._connectWith();if(c&&this.ready)for(i=c.length-1;i>=0;i--)for(n=e(c[i]),s=n.length-1;s>=0;s--)a=e.data(n[s],this.widgetFullName),a&&a!==this&&!a.options.disabled&&(d.push([e.isFunction(a.options.items)?a.options.items.call(a.element[0],t,{item:this.currentItem}):e(a.options.items,a.element),a]),this.containers.push(a));for(i=d.length-1;i>=0;i--)for(o=d[i][1],r=d[i][0],s=0,l=r.length;l>s;s++)h=e(r[s]),h.data(this.widgetName+"-item",o),u.push({item:h,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,a;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?e(this.options.toleranceElement,s.item):s.item,t||(s.width=n.outerWidth(),s.height=n.outerHeight()),a=n.offset(),s.left=a.left,s.top=a.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)a=this.containers[i].element.offset(),this.containers[i].containerCache.left=a.left,this.containers[i].containerCache.top=a.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(t){t=t||this;var i,s=t.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=t.currentItem[0].nodeName.toLowerCase(),n=e("<"+s+">",t.document[0]).addClass(i||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?t.currentItem.children().each(function(){e("<td>&#160;</td>",t.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(n)}):"img"===s&&n.attr("src",t.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(e,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10)))}}),t.placeholder=e(s.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),s.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var i,s,n,a,o,r,h,l,u,d,c=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(c&&e.contains(this.containers[i].element[0],c.element[0]))continue;c=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0);if(c)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,a=null,u=c.floating||this._isFloating(this.currentItem),o=u?"left":"top",r=u?"width":"height",d=u?"clientX":"clientY",s=this.items.length-1;s>=0;s--)e.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[o],l=!1,t[d]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(t[d]-h)&&(n=Math.abs(t[d]-h),a=this.items[s],this.direction=l?"up":"down"));if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;a?this._rearrange(t,a,null,!0):this._rearrange(t,null,this.containers[p].element,!0),this._trigger("change",t,this._uiHash()),this.containers[p]._trigger("change",t,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||e("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[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")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}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 t,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===n.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===n.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(t=e(n.containment)[0],i=e(n.containment).offset(),s="hidden"!==e(t).css("overflow"),this.containment=[i.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():a?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():a?0:n.scrollLeft())*s}},_generatePosition:function(t){var i,s,n=this.options,a=t.pageX,o=t.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(a=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(a=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1],o=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((a-this.originalPageX)/n.grid[0])*n.grid[0],a=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(e,t,i,s){i?i[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(e,t){function i(e,t,i){return function(s){i._trigger(e,s,t._uiHash(t))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!t&&n.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||n.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(t||(n.push(function(e){this._trigger("remove",e,this._uiHash())}),n.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)t||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,t||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!t){for(s=0;n.length>s;s++)n[s].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var i=t||this;return{helper:i.helper,placeholder:i.placeholder||e([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:t?t.element:null}}}),e.widget("ui.spinner",{version:"1.11.2",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,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),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var t={},i=this.element;return e.each(["min","max","step"],function(e,s){var n=i.attr(s);void 0!==n&&n.length&&(t[s]=n)}),t},_events:{keydown:function(e){this._start(e)&&this._keydown(e)&&e.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",e),void 0)},mousewheel:function(e,t){if(t){if(!this.spinning&&!this._start(e))return!1;this._spin((t>0?1:-1)*this.options.step,e),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(e)},100),e.preventDefault()}},"mousedown .ui-spinner-button":function(t){function i(){var e=this.element[0]===this.document[0].activeElement;e||(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),t.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(t)!==!1&&this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){return e(t.currentTarget).hasClass("ui-state-active")?this._start(t)===!1?!1:(this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var e=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=e.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(.5*e.height())&&e.height()>0&&e.height(e.height()),this.options.disabled&&this.disable()},_keydown:function(t){var i=this.options,s=e.ui.keyCode;switch(t.keyCode){case s.UP:return this._repeat(null,1,t),!0;case s.DOWN:return this._repeat(null,-1,t),!0;case s.PAGE_UP:return this._repeat(null,i.page,t),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,t),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>&#9650;</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>&#9660;</span>"+"</a>"},_start:function(e){return this.spinning||this._trigger("start",e)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(e,t,i){e=e||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,t,i)},e),this._spin(t*this.options.step,i)},_spin:function(e,t){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+e*this._increment(this.counter)),this.spinning&&this._trigger("spin",t,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(t){var i=this.options.incremental;return i?e.isFunction(i)?i(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var e=this._precisionOf(this.options.step);return null!==this.options.min&&(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=""+e,i=t.indexOf(".");return-1===i?0:t.length-i-1},_adjustValue:function(e){var t,i,s=this.options;return t=null!==s.min?s.min:0,i=e-t,i=Math.round(i/s.step)*s.step,e=t+i,e=parseFloat(e.toFixed(this._precision())),null!==s.max&&e>s.max?s.max:null!==s.min&&s.min>e?s.min:e},_stop:function(e){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",e))},_setOption:function(e,t){if("culture"===e||"numberFormat"===e){var i=this._parse(this.element.val());return this.options[e]=t,this.element.val(this._format(i)),void 0}("max"===e||"min"===e||"step"===e)&&"string"==typeof t&&(t=this._parse(t)),"icons"===e&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(t.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(t.down)),this._super(e,t),"disabled"===e&&(this.widget().toggleClass("ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable"))},_setOptions:h(function(e){this._super(e)}),_parse:function(e){return"string"==typeof e&&""!==e&&(e=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(e,10,this.options.culture):+e),""===e||isNaN(e)?null:e},_format:function(e){return""===e?"":window.Globalize&&this.options.numberFormat?Globalize.format(e,this.options.numberFormat,this.options.culture):e},_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 e=this.value();return null===e?!1:e===this._adjustValue(e)},_value:function(e,t){var i;""!==e&&(i=this._parse(e),null!==i&&(t||(i=this._adjustValue(i)),e=this._format(i))),this.element.val(e),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:h(function(e){this._stepUp(e)}),_stepUp:function(e){this._start()&&(this._spin((e||1)*this.options.step),this._stop())},stepDown:h(function(e){this._stepDown(e)}),_stepDown:function(e){this._start()&&(this._spin((e||1)*-this.options.step),this._stop())},pageUp:h(function(e){this._stepUp((e||1)*this.options.page)}),pageDown:h(function(e){this._stepDown((e||1)*this.options.page)}),value:function(e){return arguments.length?(h(this._value).call(this,e),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),e.widget("ui.tabs",{version:"1.11.2",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(){var e=/#.*$/;return function(t){var i,s;t=t.cloneNode(!1),i=t.href.replace(e,""),s=location.href.replace(e,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return t.hash.length>1&&i===s}}(),_create:function(){var t=this,i=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",i.collapsible),this._processTabs(),i.active=this._initialActive(),e.isArray(i.disabled)&&(i.disabled=e.unique(i.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return t.tabs.index(e)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):e(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var t=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===t&&(s&&this.tabs.each(function(i,n){return e(n).attr("aria-controls")===s?(t=i,!1):void 0}),null===t&&(t=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===t||-1===t)&&(t=this.tabs.length?0:!1)),t!==!1&&(t=this.tabs.index(this.tabs.eq(t)),-1===t&&(t=i?!1:0)),!i&&t===!1&&this.anchors.length&&(t=0),t},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(t){var i=e(this.document[0].activeElement).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(t)){switch(t.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:s++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:n=!1,s--;break;case e.ui.keyCode.END:s=this.anchors.length-1;break;case e.ui.keyCode.HOME:s=0;break;case e.ui.keyCode.SPACE:return t.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case e.ui.keyCode.ENTER:return t.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}t.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),t.ctrlKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(t){this._handlePageNav(t)||t.ctrlKey&&t.keyCode===e.ui.keyCode.UP&&(t.preventDefault(),this.active.focus())},_handlePageNav:function(t){return t.altKey&&t.keyCode===e.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):t.altKey&&t.keyCode===e.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(t,i){function s(){return t>n&&(t=0),0>t&&(t=n),t}for(var n=this.tabs.length-1;-1!==e.inArray(s(),this.options.disabled);)t=i?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,t){return"active"===e?(this._activate(t),void 0):"disabled"===e?(this._setupDisabled(t),void 0):(this._super(e,t),"collapsible"===e&&(this.element.toggleClass("ui-tabs-collapsible",t),t||this.options.active!==!1||this._activate(0)),"event"===e&&this._setupEvents(t),"heightStyle"===e&&this._setupHeightStyle(t),void 0)},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,i=this.tablist.children(":has(a[href])");t.disabled=e.map(i.filter(".ui-state-disabled"),function(e){return i.index(e)}),this._processTabs(),t.active!==!1&&this.anchors.length?this.active.length&&!e.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active):(t.active=!1,this.active=e()),this._refresh()},_refresh:function(){this._setupDisabled(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"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this,i=this.tabs,s=this.anchors,n=this.panels;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist").delegate("> li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&&t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return e("a",this)[0]
}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(i,s){var n,a,o,r=e(s).uniqueId().attr("id"),h=e(s).closest("li"),l=h.attr("aria-controls");t._isLocal(s)?(n=s.hash,o=n.substring(1),a=t.element.find(t._sanitizeSelector(n))):(o=h.attr("aria-controls")||e({}).uniqueId()[0].id,n="#"+o,a=t.element.find(n),a.length||(a=t._createPanel(o),a.insertAfter(t.panels[i-1]||t.tablist)),a.attr("aria-live","polite")),a.length&&(t.panels=t.panels.add(a)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":o,"aria-labelledby":r}),a.attr("aria-labelledby",r)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("<div>").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1);for(var i,s=0;i=this.tabs[s];s++)t===!0||-1!==e.inArray(s,t)?e(i).addClass("ui-state-disabled").attr("aria-disabled","true"):e(i).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var i={};t&&e.each(t.split(" "),function(e,t){i[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(e){e.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var i,s=this.element.parent();"fill"===t?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var t=e(this),s=t.css("position");"absolute"!==s&&"fixed"!==s&&(i-=t.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,i-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):"auto"===t&&(i=0,this.panels.each(function(){i=Math.max(i,e(this).height("").height())}).height(i))},_eventHandler:function(t){var i=this.options,s=this.active,n=e(t.currentTarget),a=n.closest("li"),o=a[0]===s[0],r=o&&i.collapsible,h=r?e():this._getPanelForTab(a),l=s.length?this._getPanelForTab(s):e(),u={oldTab:s,oldPanel:l,newTab:r?e():a,newPanel:h};t.preventDefault(),a.hasClass("ui-state-disabled")||a.hasClass("ui-tabs-loading")||this.running||o&&!i.collapsible||this._trigger("beforeActivate",t,u)===!1||(i.active=r?!1:this.tabs.index(a),this.active=o?e():a,this.xhr&&this.xhr.abort(),l.length||h.length||e.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(a),t),this._toggle(t,u))},_toggle:function(t,i){function s(){a.running=!1,a._trigger("activate",t,i)}function n(){i.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&a.options.show?a._show(o,a.options.show,s):(o.show(),s())}var a=this,o=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),n()}):(i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),o.length&&r.length?i.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return 0===e(this).attr("tabIndex")}).attr("tabIndex",-1),o.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(t){var i,s=this._findActive(t);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:e.noop}))},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tablist.unbind(this.eventNamespace),this.tabs.add(this.panels).each(function(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var t=e(this),i=t.data("ui-tabs-aria-controls");i?t.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):t.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(t){var i=this.options.disabled;i!==!1&&(void 0===t?i=!1:(t=this._getIndex(t),i=e.isArray(i)?e.map(i,function(e){return e!==t?e:null}):e.map(this.tabs,function(e,i){return i!==t?i:null})),this._setupDisabled(i))},disable:function(t){var i=this.options.disabled;if(i!==!0){if(void 0===t)i=!0;else{if(t=this._getIndex(t),-1!==e.inArray(t,i))return;i=e.isArray(i)?e.merge([t],i).sort():[t]}this._setupDisabled(i)}},load:function(t,i){t=this._getIndex(t);var s=this,n=this.tabs.eq(t),a=n.find(".ui-tabs-anchor"),o=this._getPanelForTab(n),r={tab:n,panel:o};this._isLocal(a[0])||(this.xhr=e.ajax(this._ajaxSettings(a,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(n.addClass("ui-tabs-loading"),o.attr("aria-busy","true"),this.xhr.success(function(e){setTimeout(function(){o.html(e),s._trigger("load",i,r)},1)}).complete(function(e,t){setTimeout(function(){"abort"===t&&s.panels.stop(!1,!0),n.removeClass("ui-tabs-loading"),o.removeAttr("aria-busy"),e===s.xhr&&delete s.xhr},1)})))},_ajaxSettings:function(t,i,s){var n=this;return{url:t.attr("href"),beforeSend:function(t,a){return n._trigger("beforeLoad",i,e.extend({jqXHR:t,ajaxSettings:a},s))}}},_getPanelForTab:function(t){var i=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}}),e.widget("ui.tooltip",{version:"1.11.2",options:{content:function(){var t=e(this).attr("title")||"";return e("<a>").text(t).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_addDescribedBy:function(t,i){var s=(t.attr("aria-describedby")||"").split(/\s+/);s.push(i),t.data("ui-tooltip-id",i).attr("aria-describedby",e.trim(s.join(" ")))},_removeDescribedBy:function(t){var i=t.data("ui-tooltip-id"),s=(t.attr("aria-describedby")||"").split(/\s+/),n=e.inArray(i,s);-1!==n&&s.splice(n,1),t.removeData("ui-tooltip-id"),s=e.trim(s.join(" ")),s?t.attr("aria-describedby",s):t.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable(),this.liveRegion=e("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body)},_setOption:function(t,i){var s=this;return"disabled"===t?(this[i?"_disable":"_enable"](),this.options[t]=i,void 0):(this._super(t,i),"content"===t&&e.each(this.tooltips,function(e,t){s._updateContent(t.element)}),void 0)},_disable:function(){var t=this;e.each(this.tooltips,function(i,s){var n=e.Event("blur");n.target=n.currentTarget=s.element[0],t.close(n,!0)}),this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.is("[title]")&&t.data("ui-tooltip-title",t.attr("title")).removeAttr("title")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.data("ui-tooltip-title")&&t.attr("title",t.data("ui-tooltip-title"))})},open:function(t){var i=this,s=e(t?t.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),t&&"mouseover"===t.type&&s.parents().each(function(){var t,s=e(this);s.data("ui-tooltip-open")&&(t=e.Event("blur"),t.target=t.currentTarget=this,i.close(t,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._updateContent(s,t))},_updateContent:function(e,t){var i,s=this.options.content,n=this,a=t?t.type:null;return"string"==typeof s?this._open(t,e,s):(i=s.call(e[0],function(i){e.data("ui-tooltip-open")&&n._delay(function(){t&&(t.type=a),this._open(t,e,i)})}),i&&this._open(t,e,i),void 0)},_open:function(t,i,s){function n(e){u.of=e,o.is(":hidden")||o.position(u)}var a,o,r,h,l,u=e.extend({},this.options.position);if(s){if(a=this._find(i))return a.tooltip.find(".ui-tooltip-content").html(s),void 0;i.is("[title]")&&(t&&"mouseover"===t.type?i.attr("title",""):i.removeAttr("title")),a=this._tooltip(i),o=a.tooltip,this._addDescribedBy(i,o.attr("id")),o.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),s.clone?(l=s.clone(),l.removeAttr("id").find("[id]").removeAttr("id")):l=s,e("<div>").html(l).appendTo(this.liveRegion),this.options.track&&t&&/^mouse/.test(t.type)?(this._on(this.document,{mousemove:n}),n(t)):o.position(e.extend({of:i},this.options.position)),o.hide(),this._show(o,this.options.show),this.options.show&&this.options.show.delay&&(h=this.delayedShow=setInterval(function(){o.is(":visible")&&(n(u.of),clearInterval(h))},e.fx.interval)),this._trigger("open",t,{tooltip:o}),r={keyup:function(t){if(t.keyCode===e.ui.keyCode.ESCAPE){var s=e.Event(t);s.currentTarget=i[0],this.close(s,!0)}}},i[0]!==this.element[0]&&(r.remove=function(){this._removeTooltip(o)}),t&&"mouseover"!==t.type||(r.mouseleave="close"),t&&"focusin"!==t.type||(r.focusout="close"),this._on(!0,i,r)}},close:function(t){var i,s=this,n=e(t?t.currentTarget:this.element),a=this._find(n);a&&(i=a.tooltip,a.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),a.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(e(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),t&&"mouseleave"===t.type&&e.each(this.parents,function(t,i){e(i.element).attr("title",i.title),delete s.parents[t]}),a.closing=!0,this._trigger("close",t,{tooltip:i}),a.hiding||(a.closing=!1)))},_tooltip:function(t){var i=e("<div>").attr("role","tooltip").addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||"")),s=i.uniqueId().attr("id");return e("<div>").addClass("ui-tooltip-content").appendTo(i),i.appendTo(this.document[0].body),this.tooltips[s]={element:t,tooltip:i}},_find:function(e){var t=e.data("ui-tooltip-id");return t?this.tooltips[t]:null},_removeTooltip:function(e){e.remove(),delete this.tooltips[e.attr("id")]},_destroy:function(){var t=this;e.each(this.tooltips,function(i,s){var n=e.Event("blur"),a=s.element;n.target=n.currentTarget=a[0],t.close(n,!0),e("#"+i).remove(),a.data("ui-tooltip-title")&&(a.attr("title")||a.attr("title",a.data("ui-tooltip-title")),a.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}})});
function _classCallCheck(t,i){if(!(t instanceof i))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,i){for(var e=0;e<i.length;e++){var s=i[e];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}function _createClass(t,i,e){return i&&_defineProperties(t.prototype,i),e&&_defineProperties(t,e),t}var Sticky=function(){function e(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"",i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};_classCallCheck(this,e),this.selector=t,this.elements=[],this.version="1.3.0",this.vp=this.getViewportSize(),this.body=document.querySelector("body"),this.options={wrap:i.wrap||!1,wrapWith:i.wrapWith||"<span></span>",marginTop:i.marginTop||0,marginBottom:i.marginBottom||0,stickyFor:i.stickyFor||0,stickyClass:i.stickyClass||null,stickyContainer:i.stickyContainer||"body"},this.updateScrollTopPosition=this.updateScrollTopPosition.bind(this),this.updateScrollTopPosition(),window.addEventListener("load",this.updateScrollTopPosition),window.addEventListener("scroll",this.updateScrollTopPosition),this.run()}return _createClass(e,[{key:"run",value:function(){var i=this,e=setInterval(function(){if("complete"===document.readyState){clearInterval(e);var t=document.querySelectorAll(i.selector);i.forEach(t,function(t){return i.renderElement(t)})}},10)}},{key:"renderElement",value:function(t){var i=this;t.sticky={},t.sticky.active=!1,t.sticky.marginTop=parseInt(t.getAttribute("data-margin-top"))||this.options.marginTop,t.sticky.marginBottom=parseInt(t.getAttribute("data-margin-bottom"))||this.options.marginBottom,t.sticky.stickyFor=parseInt(t.getAttribute("data-sticky-for"))||this.options.stickyFor,t.sticky.stickyClass=t.getAttribute("data-sticky-class")||this.options.stickyClass,t.sticky.wrap=!!t.hasAttribute("data-sticky-wrap")||this.options.wrap,t.sticky.stickyContainer=this.options.stickyContainer,t.sticky.container=this.getStickyContainer(t),t.sticky.container.rect=this.getRectangle(t.sticky.container),t.sticky.rect=this.getRectangle(t),"img"===t.tagName.toLowerCase()&&(t.onload=function(){return t.sticky.rect=i.getRectangle(t)}),t.sticky.wrap&&this.wrapElement(t),this.activate(t)}},{key:"wrapElement",value:function(t){t.insertAdjacentHTML("beforebegin",t.getAttribute("data-sticky-wrapWith")||this.options.wrapWith),t.previousSibling.appendChild(t)}},{key:"activate",value:function(t){t.sticky.rect.top+t.sticky.rect.height<t.sticky.container.rect.top+t.sticky.container.rect.height&&t.sticky.stickyFor<this.vp.width&&!t.sticky.active&&(t.sticky.active=!0),this.elements.indexOf(t)<0&&this.elements.push(t),t.sticky.resizeEvent||(this.initResizeEvents(t),t.sticky.resizeEvent=!0),t.sticky.scrollEvent||(this.initScrollEvents(t),t.sticky.scrollEvent=!0),this.setPosition(t)}},{key:"initResizeEvents",value:function(t){var i=this;t.sticky.resizeListener=function(){return i.onResizeEvents(t)},window.addEventListener("resize",t.sticky.resizeListener)}},{key:"destroyResizeEvents",value:function(t){window.removeEventListener("resize",t.sticky.resizeListener)}},{key:"onResizeEvents",value:function(t){this.vp=this.getViewportSize(),t.sticky.rect=this.getRectangle(t),t.sticky.container.rect=this.getRectangle(t.sticky.container),t.sticky.rect.top+t.sticky.rect.height<t.sticky.container.rect.top+t.sticky.container.rect.height&&t.sticky.stickyFor<this.vp.width&&!t.sticky.active?t.sticky.active=!0:(t.sticky.rect.top+t.sticky.rect.height>=t.sticky.container.rect.top+t.sticky.container.rect.height||t.sticky.stickyFor>=this.vp.width&&t.sticky.active)&&(t.sticky.active=!1),this.setPosition(t)}},{key:"initScrollEvents",value:function(t){var i=this;t.sticky.scrollListener=function(){return i.onScrollEvents(t)},window.addEventListener("scroll",t.sticky.scrollListener)}},{key:"destroyScrollEvents",value:function(t){window.removeEventListener("scroll",t.sticky.scrollListener)}},{key:"onScrollEvents",value:function(t){t.sticky&&t.sticky.active&&this.setPosition(t)}},{key:"setPosition",value:function(t){this.css(t,{position:"",width:"",top:"",left:""}),this.vp.height<t.sticky.rect.height||!t.sticky.active||(t.sticky.rect.width||(t.sticky.rect=this.getRectangle(t)),t.sticky.wrap&&this.css(t.parentNode,{display:"block",width:t.sticky.rect.width+"px",height:t.sticky.rect.height+"px"}),0===t.sticky.rect.top&&t.sticky.container===this.body?(this.css(t,{position:"fixed",top:t.sticky.rect.top+"px",left:t.sticky.rect.left+"px",width:t.sticky.rect.width+"px"}),t.sticky.stickyClass&&t.classList.add(t.sticky.stickyClass)):this.scrollTop>t.sticky.rect.top-t.sticky.marginTop?(this.css(t,{position:"fixed",width:t.sticky.rect.width+"px",left:t.sticky.rect.left+"px"}),this.scrollTop+t.sticky.rect.height+t.sticky.marginTop>t.sticky.container.rect.top+t.sticky.container.offsetHeight-t.sticky.marginBottom?(t.sticky.stickyClass&&t.classList.remove(t.sticky.stickyClass),this.css(t,{top:t.sticky.container.rect.top+t.sticky.container.offsetHeight-(this.scrollTop+t.sticky.rect.height+t.sticky.marginBottom)+"px"})):(t.sticky.stickyClass&&t.classList.add(t.sticky.stickyClass),this.css(t,{top:t.sticky.marginTop+"px"}))):(t.sticky.stickyClass&&t.classList.remove(t.sticky.stickyClass),this.css(t,{position:"",width:"",top:"",left:""}),t.sticky.wrap&&this.css(t.parentNode,{display:"",width:"",height:""})))}},{key:"update",value:function(){var i=this;this.forEach(this.elements,function(t){t.sticky.rect=i.getRectangle(t),t.sticky.container.rect=i.getRectangle(t.sticky.container),i.activate(t),i.setPosition(t)})}},{key:"destroy",value:function(){var i=this;window.removeEventListener("load",this.updateScrollTopPosition),window.removeEventListener("scroll",this.updateScrollTopPosition),this.forEach(this.elements,function(t){i.destroyResizeEvents(t),i.destroyScrollEvents(t),delete t.sticky})}},{key:"getStickyContainer",value:function(t){for(var i=t.parentNode;!i.hasAttribute("data-sticky-container")&&!i.parentNode.querySelector(t.sticky.stickyContainer)&&i!==this.body;)i=i.parentNode;return i}},{key:"getRectangle",value:function(t){this.css(t,{position:"",width:"",top:"",left:""});for(var i=Math.max(t.offsetWidth,t.clientWidth,t.scrollWidth),e=Math.max(t.offsetHeight,t.clientHeight,t.scrollHeight),s=0,n=0;s+=t.offsetTop||0,n+=t.offsetLeft||0,t=t.offsetParent;);return{top:s,left:n,width:i,height:e}}},{key:"getViewportSize",value:function(){return{width:Math.max(document.documentElement.clientWidth,window.innerWidth||0),height:Math.max(document.documentElement.clientHeight,window.innerHeight||0)}}},{key:"updateScrollTopPosition",value:function(){this.scrollTop=(window.pageYOffset||document.scrollTop)-(document.clientTop||0)||0}},{key:"forEach",value:function(t,i){for(var e=0,s=t.length;e<s;e++)i(t[e])}},{key:"css",value:function(t,i){for(var e in i)i.hasOwnProperty(e)&&(t.style[e]=i[e])}}]),e}();!function(t,i){"undefined"!=typeof exports?module.exports=i:"function"==typeof define&&define.amd?define([],function(){return i}):t.Sticky=i}(this,Sticky);
/*
* jQuery File Download Plugin v1.4.5
*
* http://www.johnculviner.com
*
* Copyright (c) 2013 - John Culviner
*
* Licensed under the MIT license:
*   http://www.opensource.org/licenses/mit-license.php
*
* !!!!NOTE!!!!
* You must also write a cookie in conjunction with using this plugin as mentioned in the orignal post:
* http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
* !!!!NOTE!!!!
*/

(function($, window){
	// i'll just put them here to get evaluated on script load
	var htmlSpecialCharsRegEx = /[<>&\r\n"']/gm;
	var htmlSpecialCharsPlaceHolders = {
				'<': 'lt;',
				'>': 'gt;',
				'&': 'amp;',
				'\r': "#13;",
				'\n': "#10;",
				'"': 'quot;',
				"'": '#39;' /*single quotes just to be safe, IE8 doesn't support &apos;, so use &#39; instead */
	};

$.extend({
    //
    //$.fileDownload('/path/to/url/', options)
    //  see directly below for possible 'options'
    fileDownload: function (fileUrl, options) {

        //provide some reasonable defaults to any unspecified options below
        var settings = $.extend({

            //
            //Requires jQuery UI: provide a message to display to the user when the file download is being prepared before the browser's dialog appears
            //
            preparingMessageHtml: null,

            //
            //Requires jQuery UI: provide a message to display to the user when a file download fails
            //
            failMessageHtml: null,

            //
            //the stock android browser straight up doesn't support file downloads initiated by a non GET: http://code.google.com/p/android/issues/detail?id=1780
            //specify a message here to display if a user tries with an android browser
            //if jQuery UI is installed this will be a dialog, otherwise it will be an alert
            //Set to null to disable the message and attempt to download anyway
            //
            androidPostUnsupportedMessageHtml: "Unfortunately your Android browser doesn't support this type of file download. Please try again with a different browser.",

            //
            //Requires jQuery UI: options to pass into jQuery UI Dialog
            //
            dialogOptions: { modal: true },

            //
            //a function to call while the dowload is being prepared before the browser's dialog appears
            //Args:
            //  url - the original url attempted
            //
            prepareCallback: function (url) { },

            //
            //a function to call after a file download successfully completed
            //Args:
            //  url - the original url attempted
            //
            successCallback: function (url) { },

            //
            //a function to call after a file download request was canceled
            //Args:
            //  url - the original url attempted
            //
            abortCallback: function (url) { },

            //
            //a function to call after a file download failed
            //Args:
            //  responseHtml    - the html that came back in response to the file download. this won't necessarily come back depending on the browser.
            //                      in less than IE9 a cross domain error occurs because 500+ errors cause a cross domain issue due to IE subbing out the
            //                      server's error message with a "helpful" IE built in message
            //  url             - the original url attempted
            //  error           - original error cautch from exception
            //
            failCallback: function (responseHtml, url, error) { },

            //
            // the HTTP method to use. Defaults to "GET".
            //
            httpMethod: "GET",

            //
            // if specified will perform a "httpMethod" request to the specified 'fileUrl' using the specified data.
            // data must be an object (which will be $.param serialized) or already a key=value param string
            //
            data: null,

            //
            //a period in milliseconds to poll to determine if a successful file download has occured or not
            //
            checkInterval: 100,

            //
            //the cookie name to indicate if a file download has occured
            //
            cookieName: "fileDownload",

            //
            //the cookie value for the above name to indicate that a file download has occured
            //
            cookieValue: "true",

            //
            //the cookie path for above name value pair
            //
            cookiePath: "/",

            //
            //if specified it will be used when attempting to clear the above name value pair
            //useful for when downloads are being served on a subdomain (e.g. downloads.example.com)
            //
            cookieDomain: null,

            //
            //the title for the popup second window as a download is processing in the case of a mobile browser
            //
            popupWindowTitle: "Initiating file download...",

            //
            //Functionality to encode HTML entities for a POST, need this if data is an object with properties whose values contains strings with quotation marks.
            //HTML entity encoding is done by replacing all &,<,>,',",\r,\n characters.
            //Note that some browsers will POST the string htmlentity-encoded whilst others will decode it before POSTing.
            //It is recommended that on the server, htmlentity decoding is done irrespective.
            //
            encodeHTMLEntities: true

        }, options);

        var deferred = new $.Deferred();

        //Setup mobile browser detection: Partial credit: http://detectmobilebrowser.com/
        var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase();

        var isIos;                  //has full support of features in iOS 4.0+, uses a new window to accomplish this.
        var isAndroid;              //has full support of GET features in 4.0+ by using a new window. Non-GET is completely unsupported by the browser. See above for specifying a message.
        var isOtherMobileBrowser;   //there is no way to reliably guess here so all other mobile devices will GET and POST to the current window.

        if (/ip(ad|hone|od)/.test(userAgent)) {

            isIos = true;

        } else if (userAgent.indexOf('android') !== -1) {

            isAndroid = true;

        } else {

            isOtherMobileBrowser = /avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|playbook|silk|iemobile|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0, 4));

        }

        var httpMethodUpper = settings.httpMethod.toUpperCase();

        if (isAndroid && httpMethodUpper !== "GET" && settings.androidPostUnsupportedMessageHtml) {
            //the stock android browser straight up doesn't support file downloads initiated by non GET requests: http://code.google.com/p/android/issues/detail?id=1780

            if ($().dialog) {
                $("<div>").html(settings.androidPostUnsupportedMessageHtml).dialog(settings.dialogOptions);
            } else {
                alert(settings.androidPostUnsupportedMessageHtml);
            }

            return deferred.reject();
        }

        var $preparingDialog = null;

        var internalCallbacks = {

            onPrepare: function (url) {

                //wire up a jquery dialog to display the preparing message if specified
                if (settings.preparingMessageHtml) {

                    $preparingDialog = $("<div>").html(settings.preparingMessageHtml).dialog(settings.dialogOptions);

                } else if (settings.prepareCallback) {

                    settings.prepareCallback(url);

                }

            },

            onSuccess: function (url) {

                //remove the perparing message if it was specified
                if ($preparingDialog) {
                    $preparingDialog.dialog('close');
                }

                settings.successCallback(url);

                deferred.resolve(url);
            },

            onAbort: function (url) {

                //remove the perparing message if it was specified
                if ($preparingDialog) {
                    $preparingDialog.dialog('close');
                };

                settings.abortCallback(url);

                deferred.reject(url);
            },

            onFail: function (responseHtml, url, error) {

                //remove the perparing message if it was specified
                if ($preparingDialog) {
                    $preparingDialog.dialog('close');
                }

                //wire up a jquery dialog to display the fail message if specified
                if (settings.failMessageHtml) {
                    $("<div>").html(settings.failMessageHtml).dialog(settings.dialogOptions);
                }

                settings.failCallback(responseHtml, url, error);

                deferred.reject(responseHtml, url);
            }
        };

        internalCallbacks.onPrepare(fileUrl);

        //make settings.data a param string if it exists and isn't already
        if (settings.data !== null && typeof settings.data !== "string") {
            settings.data = $.param(settings.data);
        }


        var $iframe,
            downloadWindow,
            formDoc,
            $form;

        if (httpMethodUpper === "GET") {

            if (settings.data !== null) {
                //need to merge any fileUrl params with the data object

                var qsStart = fileUrl.indexOf('?');

                if (qsStart !== -1) {
                    //we have a querystring in the url

                    if (fileUrl.substring(fileUrl.length - 1) !== "&") {
                        fileUrl = fileUrl + "&";
                    }
                } else {

                    fileUrl = fileUrl + "?";
                }

                fileUrl = fileUrl + settings.data;
            }

            if (isIos || isAndroid) {

                downloadWindow = window.open(fileUrl);
                downloadWindow.document.title = settings.popupWindowTitle;
                window.focus();

            } else if (isOtherMobileBrowser) {

                window.location(fileUrl);

            } else {

                //create a temporary iframe that is used to request the fileUrl as a GET request
		$iframe = $("<iframe style='display: none' src='"+fileUrl+"'></iframe>").appendTo("body");
            }

        } else {

            var formInnerHtml = "";

            if (settings.data !== null) {

                $.each(settings.data.replace(/\+/g, ' ').split("&"), function () {

                    var kvp = this.split("=");

                    //Issue: When value contains sign '=' then the kvp array does have more than 2 items. We have to join value back
                    var k = kvp[0];
                    kvp.shift();
                    var v = kvp.join("=");
                    kvp = [k, v];

                    var key = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[0])) : decodeURIComponent(kvp[0]);
                    if (key) {
                        var value = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[1])) : decodeURIComponent(kvp[1]);
                    formInnerHtml += '<input type="hidden" name="' + key + '" value="' + value + '" />';
                    }
                });
            }

            if (isOtherMobileBrowser) {

                $form = $("<form>").appendTo("body");
                $form.hide()
                    .prop('method', settings.httpMethod)
                    .prop('action', fileUrl)
                    .html(formInnerHtml);

            } else {

                if (isIos) {

                    downloadWindow = window.open("about:blank");
                    downloadWindow.document.title = settings.popupWindowTitle;
                    formDoc = downloadWindow.document;
                    window.focus();

                } else {

                    $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body");
                    formDoc = getiframeDocument($iframe);
                }

                formDoc.write("<html><head></head><body><form method='" + settings.httpMethod + "' action='" + fileUrl + "'>" + formInnerHtml + "</form>" + settings.popupWindowTitle + "</body></html>");
                $form = $(formDoc).find('form');
            }

            $form.submit();
        }


        //check if the file download has completed every checkInterval ms
        setTimeout(checkFileDownloadComplete, settings.checkInterval);


        function checkFileDownloadComplete() {
            //has the cookie been written due to a file download occuring?

            var cookieValue = settings.cookieValue;
            if(typeof cookieValue == 'string') {
                cookieValue = cookieValue.toLowerCase();
            }

            var lowerCaseCookie = settings.cookieName.toLowerCase() + "=" + cookieValue;

            if (document.cookie.toLowerCase().indexOf(lowerCaseCookie) > -1) {

                //execute specified callback
                internalCallbacks.onSuccess(fileUrl);

                //remove cookie
                var cookieData = settings.cookieName + "=; path=" + settings.cookiePath + "; expires=" + new Date(0).toUTCString() + ";";
                if (settings.cookieDomain) cookieData += " domain=" + settings.cookieDomain + ";";
                document.cookie = cookieData;

                //remove iframe
                cleanUp(false);

                return;
            }

            //has an error occured?
            //if neither containers exist below then the file download is occuring on the current window
            if (downloadWindow || $iframe) {

                //has an error occured?
                try {

                    var formDoc = downloadWindow ? downloadWindow.document : getiframeDocument($iframe);

                    if (formDoc && formDoc.body !== null && formDoc.body.innerHTML.length) {

                        var isFailure = true;

                        if ($form && $form.length) {
                            var $contents = $(formDoc.body).contents().first();

                            try {
                                if ($contents.length && $contents[0] === $form[0]) {
                                    isFailure = false;
                                }
                            } catch (e) {
                                if (e && e.number == -2146828218) {
                                    // IE 8-10 throw a permission denied after the form reloads on the "$contents[0] === $form[0]" comparison
                                    isFailure = true;
                                } else {
                                    throw e;
                                }
                            }
                        }

                        if (isFailure) {
                            // IE 8-10 don't always have the full content available right away, they need a litle bit to finish
                            setTimeout(function () {
                                internalCallbacks.onFail(formDoc.body.innerHTML, fileUrl);
                                cleanUp(true);
                            }, 100);

                            return;
                        }
                    }
                }
                catch (err) {

                    //500 error less than IE9
                    internalCallbacks.onFail('', fileUrl, err);

                    cleanUp(true);

                    return;
                }
            }


            //keep checking...
            setTimeout(checkFileDownloadComplete, settings.checkInterval);
        }

        //gets an iframes document in a cross browser compatible manner
        function getiframeDocument($iframe) {
            var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
            if (iframeDoc.document) {
                iframeDoc = iframeDoc.document;
            }
            return iframeDoc;
        }

        function cleanUp(isFailure) {

            setTimeout(function() {

                if (downloadWindow) {

                    if (isAndroid) {
                        downloadWindow.close();
                    }

                    if (isIos) {
                        if (downloadWindow.focus) {
                            downloadWindow.focus(); //ios safari bug doesn't allow a window to be closed unless it is focused
                            if (isFailure) {
                                downloadWindow.close();
                            }
                        }
                    }
                }

                //iframe cleanup appears to randomly cause the download to fail
                //not doing it seems better than failure...
                //if ($iframe) {
                //    $iframe.remove();
                //}

            }, 0);
        }


        function htmlSpecialCharsEntityEncode(str) {
            return str.replace(htmlSpecialCharsRegEx, function(match) {
                return '&' + htmlSpecialCharsPlaceHolders[match];
        	});
        }
        var promise = deferred.promise();
        promise.abort = function() {
            cleanUp();
            $iframe.attr('src', '').html('');
            internalCallbacks.onAbort(fileUrl);
        };
        return promise;
    }
});

})(jQuery, this || window);

/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.7",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a("#"===f?[]:f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.7",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c).prop(c,!0)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c).prop(c,!1))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target).closest(".btn");b.call(d,"toggle"),a(c.target).is('input[type="radio"], input[type="checkbox"]')||(c.preventDefault(),d.is("input,button")?d.trigger("focus"):d.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(a>this.$items.length-1||a<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.7",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.7",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){document===a.target||this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.7",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);if(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),!c.isInStateTrue())return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element&&e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);if(this.$element.trigger(g),!g.isDefaultPrevented())return f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=window.SVGElement&&c instanceof window.SVGElement,g=d?{top:0,left:0}:f?null:b.offset(),h={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},i=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,h,i,g)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null,a.$element=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.7",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.7",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){
this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.7",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e<c&&"top";if("bottom"==this.affixed)return null!=c?!(e+this.unpin<=f.top)&&"bottom":!(e+g<=a-d)&&"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&e<=c?"top":null!=d&&i+j>=a-d&&"bottom"},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
/*! animateCSS - v1.2.1 - 2015-10-18
* https://github.com/craigmdennis/animateCSS
* Copyright (c) 2015 Craig Dennis; Licensed MIT */

(function(){"use strict";var a;a=jQuery,a.fn.extend({animateCSS:function(b,c){var d,e,f,g,h,i,j,k,l,m;return k={effect:b,delay:0,animationClass:"animated",infinite:!1,callback:c,duration:1e3,debug:!1},l="webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",k=a.extend(k,c),h=function(a){return e(a)},e=function(a){return k.infinite===!0&&(k.animationClass+=" infinite"),setTimeout(function(){return j(a),m(a),d(a),g(a)},k.delay)},d=function(a){return a.addClass(k.effect+" "+k.animationClass+" ")},m=function(a){return"hidden"===a.css("visibility")&&a.css("visibility","visible"),a.is(":hidden")?a.show():void 0},i=function(a){return a.removeClass(k.effect+" "+k.animationClass)},j=function(a){return a.css({"-webkit-animation-duration":k.duration+"ms","-moz-animation-duration":k.duration+"ms","-o-animation-duration":k.duration+"ms","animation-duration":k.duration+"ms"})},f=function(a){return k.infinite===!1&&i(a),"function"==typeof k.callback?k.callback.call(a):void 0},g=function(a){return a.one(l,function(b){return b.stopPropagation(),f(a)})},this.each(function(){return h(a(this))})}})}).call(this);
!function(t,e,i,s){function n(e,i){this.settings=null,this.options=t.extend({},n.Defaults,i),this.$element=t(e),this._handlers={},this._plugins={},this._supress={},this._current=null,this._speed=null,this._coordinates=[],this._breakpoint=null,this._width=null,this._items=[],this._clones=[],this._mergers=[],this._widths=[],this._invalidated={},this._pipe=[],this._drag={time:null,target:null,pointer:null,stage:{start:null,current:null},direction:null},this._states={current:{},tags:{initializing:["busy"],animating:["busy"],dragging:["interacting"]}},t.each(["onResize","onThrottledResize"],t.proxy(function(e,i){this._handlers[i]=t.proxy(this[i],this)},this)),t.each(n.Plugins,t.proxy(function(t,e){this._plugins[t.charAt(0).toLowerCase()+t.slice(1)]=new e(this)},this)),t.each(n.Workers,t.proxy(function(e,i){this._pipe.push({filter:i.filter,run:t.proxy(i.run,this)})},this)),this.setup(),this.initialize()}n.Defaults={items:3,loop:!1,center:!1,rewind:!1,mouseDrag:!0,touchDrag:!0,pullDrag:!0,freeDrag:!1,margin:0,stagePadding:0,merge:!1,mergeFit:!0,autoWidth:!1,startPosition:0,rtl:!1,smartSpeed:250,fluidSpeed:!1,dragEndSpeed:!1,responsive:{},responsiveRefreshRate:200,responsiveBaseElement:e,fallbackEasing:"swing",info:!1,nestedItemSelector:!1,itemElement:"div",stageElement:"div",refreshClass:"owl-refresh",loadedClass:"owl-loaded",loadingClass:"owl-loading",rtlClass:"owl-rtl",responsiveClass:"owl-responsive",dragClass:"owl-drag",itemClass:"owl-item",stageClass:"owl-stage",stageOuterClass:"owl-stage-outer",grabClass:"owl-grab"},n.Width={Default:"default",Inner:"inner",Outer:"outer"},n.Type={Event:"event",State:"state"},n.Plugins={},n.Workers=[{filter:["width","settings"],run:function(){this._width=this.$element.width()}},{filter:["width","items","settings"],run:function(t){t.current=this._items&&this._items[this.relative(this._current)]}},{filter:["items","settings"],run:function(){this.$stage.children(".cloned").remove()}},{filter:["width","items","settings"],run:function(t){var e=this.settings.margin||"",i=!this.settings.autoWidth,s=this.settings.rtl,n={width:"auto","margin-left":s?e:"","margin-right":s?"":e};!i&&this.$stage.children().css(n),t.css=n}},{filter:["width","items","settings"],run:function(t){var e=(this.width()/this.settings.items).toFixed(3)-this.settings.margin,i=null,s=this._items.length,n=!this.settings.autoWidth,o=[];for(t.items={merge:!1,width:e};s--;)i=this._mergers[s],i=this.settings.mergeFit&&Math.min(i,this.settings.items)||i,t.items.merge=i>1||t.items.merge,o[s]=n?e*i:this._items[s].width();this._widths=o}},{filter:["items","settings"],run:function(){var e=[],i=this._items,s=this.settings,n=Math.max(2*s.items,4),o=2*Math.ceil(i.length/2),r=s.loop&&i.length?s.rewind?n:Math.max(n,o):0,a="",h="";for(r/=2;r--;)e.push(this.normalize(e.length/2,!0)),a+=i[e[e.length-1]][0].outerHTML,e.push(this.normalize(i.length-1-(e.length-1)/2,!0)),h=i[e[e.length-1]][0].outerHTML+h;this._clones=e,t(a).addClass("cloned").appendTo(this.$stage),t(h).addClass("cloned").prependTo(this.$stage)}},{filter:["width","items","settings"],run:function(){for(var t=this.settings.rtl?1:-1,e=this._clones.length+this._items.length,i=-1,s=0,n=0,o=[];++i<e;)s=o[i-1]||0,n=this._widths[this.relative(i)]+this.settings.margin,o.push(s+n*t);this._coordinates=o}},{filter:["width","items","settings"],run:function(){var t=this.settings.stagePadding,e=this._coordinates,i={width:Math.ceil(Math.abs(e[e.length-1]))+2*t,"padding-left":t||"","padding-right":t||""};this.$stage.css(i)}},{filter:["width","items","settings"],run:function(t){var e=this._coordinates.length,i=!this.settings.autoWidth,s=this.$stage.children();if(i&&t.items.merge)for(;e--;)t.css.width=this._widths[this.relative(e)],s.eq(e).css(t.css);else i&&(t.css.width=t.items.width,s.css(t.css))}},{filter:["items"],run:function(){this._coordinates.length<1&&this.$stage.removeAttr("style")}},{filter:["width","items","settings"],run:function(t){t.current=t.current?this.$stage.children().index(t.current):0,t.current=Math.max(this.minimum(),Math.min(this.maximum(),t.current)),this.reset(t.current)}},{filter:["position"],run:function(){this.animate(this.coordinates(this._current))}},{filter:["width","position","items","settings"],run:function(){var t,e,i,s,n=this.settings.rtl?1:-1,o=2*this.settings.stagePadding,r=this.coordinates(this.current())+o,a=r+this.width()*n,h=[];for(i=0,s=this._coordinates.length;i<s;i++)t=this._coordinates[i-1]||0,e=Math.abs(this._coordinates[i])+o*n,(this.op(t,"<=",r)&&this.op(t,">",a)||this.op(e,"<",r)&&this.op(e,">",a))&&h.push(i);this.$stage.children(".active").removeClass("active"),this.$stage.children(":eq("+h.join("), :eq(")+")").addClass("active"),this.settings.center&&(this.$stage.children(".center").removeClass("center"),this.$stage.children().eq(this.current()).addClass("center"))}}],n.prototype.initialize=function(){var e,i,n;(this.enter("initializing"),this.trigger("initialize"),this.$element.toggleClass(this.settings.rtlClass,this.settings.rtl),this.settings.autoWidth&&!this.is("pre-loading"))&&(e=this.$element.find("img"),i=this.settings.nestedItemSelector?"."+this.settings.nestedItemSelector:s,n=this.$element.children(i).width(),e.length&&n<=0&&this.preloadAutoWidthImages(e));this.$element.addClass(this.options.loadingClass),this.$stage=t("<"+this.settings.stageElement+' class="'+this.settings.stageClass+'"/>').wrap('<div class="'+this.settings.stageOuterClass+'"/>'),this.$element.append(this.$stage.parent()),this.replace(this.$element.children().not(this.$stage.parent())),this.$element.is(":visible")?this.refresh():this.invalidate("width"),this.$element.removeClass(this.options.loadingClass).addClass(this.options.loadedClass),this.registerEventHandlers(),this.leave("initializing"),this.trigger("initialized")},n.prototype.setup=function(){var e=this.viewport(),i=this.options.responsive,s=-1,n=null;i?(t.each(i,function(t){t<=e&&t>s&&(s=Number(t))}),"function"==typeof(n=t.extend({},this.options,i[s])).stagePadding&&(n.stagePadding=n.stagePadding()),delete n.responsive,n.responsiveClass&&this.$element.attr("class",this.$element.attr("class").replace(new RegExp("("+this.options.responsiveClass+"-)\\S+\\s","g"),"$1"+s))):n=t.extend({},this.options),this.trigger("change",{property:{name:"settings",value:n}}),this._breakpoint=s,this.settings=n,this.invalidate("settings"),this.trigger("changed",{property:{name:"settings",value:this.settings}})},n.prototype.optionsLogic=function(){this.settings.autoWidth&&(this.settings.stagePadding=!1,this.settings.merge=!1)},n.prototype.prepare=function(e){var i=this.trigger("prepare",{content:e});return i.data||(i.data=t("<"+this.settings.itemElement+"/>").addClass(this.options.itemClass).append(e)),this.trigger("prepared",{content:i.data}),i.data},n.prototype.update=function(){for(var e=0,i=this._pipe.length,s=t.proxy(function(t){return this[t]},this._invalidated),n={};e<i;)(this._invalidated.all||t.grep(this._pipe[e].filter,s).length>0)&&this._pipe[e].run(n),e++;this._invalidated={},!this.is("valid")&&this.enter("valid")},n.prototype.width=function(t){switch(t=t||n.Width.Default){case n.Width.Inner:case n.Width.Outer:return this._width;default:return this._width-2*this.settings.stagePadding+this.settings.margin}},n.prototype.refresh=function(){this.enter("refreshing"),this.trigger("refresh"),this.setup(),this.optionsLogic(),this.$element.addClass(this.options.refreshClass),this.update(),this.$element.removeClass(this.options.refreshClass),this.leave("refreshing"),this.trigger("refreshed")},n.prototype.onThrottledResize=function(){e.clearTimeout(this.resizeTimer),this.resizeTimer=e.setTimeout(this._handlers.onResize,this.settings.responsiveRefreshRate)},n.prototype.onResize=function(){return!!this._items.length&&this._width!==this.$element.width()&&!!this.$element.is(":visible")&&(this.enter("resizing"),this.trigger("resize").isDefaultPrevented()?(this.leave("resizing"),!1):(this.invalidate("width"),this.refresh(),this.leave("resizing"),void this.trigger("resized")))},n.prototype.registerEventHandlers=function(){t.support.transition&&this.$stage.on(t.support.transition.end+".owl.core",t.proxy(this.onTransitionEnd,this)),!1!==this.settings.responsive&&this.on(e,"resize",this._handlers.onThrottledResize),this.settings.mouseDrag&&(this.$element.addClass(this.options.dragClass),this.$stage.on("mousedown.owl.core",t.proxy(this.onDragStart,this)),this.$stage.on("dragstart.owl.core selectstart.owl.core",function(){return!1})),this.settings.touchDrag&&(this.$stage.on("touchstart.owl.core",t.proxy(this.onDragStart,this)),this.$stage.on("touchcancel.owl.core",t.proxy(this.onDragEnd,this)))},n.prototype.onDragStart=function(e){var s=null;3!==e.which&&(t.support.transform3d?s={x:(s=this.$stage.css("transform").replace(/.*\(|\)| /g,"").split(","))[16===s.length?12:4],y:s[16===s.length?13:5]}:(s=this.$stage.position(),s={x:this.settings.rtl?s.left+this.$stage.width()-this.width()+this.settings.margin:s.left,y:s.top}),this.is("animating")&&(t.support.transform?this.animate(s.x):this.$stage.stop(),this.invalidate("position")),this.$element.toggleClass(this.options.grabClass,"mousedown"===e.type),this.speed(0),this._drag.time=(new Date).getTime(),this._drag.target=t(e.target),this._drag.stage.start=s,this._drag.stage.current=s,this._drag.pointer=this.pointer(e),t(i).on("mouseup.owl.core touchend.owl.core",t.proxy(this.onDragEnd,this)),t(i).one("mousemove.owl.core touchmove.owl.core",t.proxy(function(e){var s=this.difference(this._drag.pointer,this.pointer(e));t(i).on("mousemove.owl.core touchmove.owl.core",t.proxy(this.onDragMove,this)),Math.abs(s.x)<Math.abs(s.y)&&this.is("valid")||(e.preventDefault(),this.enter("dragging"),this.trigger("drag"))},this)))},n.prototype.onDragMove=function(t){var e=null,i=null,s=null,n=this.difference(this._drag.pointer,this.pointer(t)),o=this.difference(this._drag.stage.start,n);this.is("dragging")&&(t.preventDefault(),this.settings.loop?(e=this.coordinates(this.minimum()),i=this.coordinates(this.maximum()+1)-e,o.x=((o.x-e)%i+i)%i+e):(e=this.settings.rtl?this.coordinates(this.maximum()):this.coordinates(this.minimum()),i=this.settings.rtl?this.coordinates(this.minimum()):this.coordinates(this.maximum()),s=this.settings.pullDrag?-1*n.x/5:0,o.x=Math.max(Math.min(o.x,e+s),i+s)),this._drag.stage.current=o,this.animate(o.x))},n.prototype.onDragEnd=function(e){var s=this.difference(this._drag.pointer,this.pointer(e)),n=this._drag.stage.current,o=s.x>0^this.settings.rtl?"left":"right";t(i).off(".owl.core"),this.$element.removeClass(this.options.grabClass),(0!==s.x&&this.is("dragging")||!this.is("valid"))&&(this.speed(this.settings.dragEndSpeed||this.settings.smartSpeed),this.current(this.closest(n.x,0!==s.x?o:this._drag.direction)),this.invalidate("position"),this.update(),this._drag.direction=o,(Math.abs(s.x)>3||(new Date).getTime()-this._drag.time>300)&&this._drag.target.one("click.owl.core",function(){return!1})),this.is("dragging")&&(this.leave("dragging"),this.trigger("dragged"))},n.prototype.closest=function(e,i){var s=-1,n=this.width(),o=this.coordinates();return this.settings.freeDrag||t.each(o,t.proxy(function(t,r){return"left"===i&&e>r-30&&e<r+30?s=t:"right"===i&&e>r-n-30&&e<r-n+30?s=t+1:this.op(e,"<",r)&&this.op(e,">",o[t+1]||r-n)&&(s="left"===i?t+1:t),-1===s},this)),this.settings.loop||(this.op(e,">",o[this.minimum()])?s=e=this.minimum():this.op(e,"<",o[this.maximum()])&&(s=e=this.maximum())),s},n.prototype.animate=function(e){var i=this.speed()>0;this.is("animating")&&this.onTransitionEnd(),i&&(this.enter("animating"),this.trigger("translate")),t.support.transform3d&&t.support.transition?this.$stage.css({transform:"translate3d("+e+"px,0px,0px)",transition:this.speed()/1e3+"s"}):i?this.$stage.animate({left:e+"px"},this.speed(),this.settings.fallbackEasing,t.proxy(this.onTransitionEnd,this)):this.$stage.css({left:e+"px"})},n.prototype.is=function(t){return this._states.current[t]&&this._states.current[t]>0},n.prototype.current=function(t){if(t===s)return this._current;if(0===this._items.length)return s;if(t=this.normalize(t),this._current!==t){var e=this.trigger("change",{property:{name:"position",value:t}});e.data!==s&&(t=this.normalize(e.data)),this._current=t,this.invalidate("position"),this.trigger("changed",{property:{name:"position",value:this._current}})}return this._current},n.prototype.invalidate=function(e){return"string"===t.type(e)&&(this._invalidated[e]=!0,this.is("valid")&&this.leave("valid")),t.map(this._invalidated,function(t,e){return e})},n.prototype.reset=function(t){(t=this.normalize(t))!==s&&(this._speed=0,this._current=t,this.suppress(["translate","translated"]),this.animate(this.coordinates(t)),this.release(["translate","translated"]))},n.prototype.normalize=function(t,e){var i=this._items.length,n=e?0:this._clones.length;return!this.isNumeric(t)||i<1?t=s:(t<0||t>=i+n)&&(t=((t-n/2)%i+i)%i+n/2),t},n.prototype.relative=function(t){return t-=this._clones.length/2,this.normalize(t,!0)},n.prototype.maximum=function(t){var e,i,s,n=this.settings,o=this._coordinates.length;if(n.loop)o=this._clones.length/2+this._items.length-1;else if(n.autoWidth||n.merge){for(e=this._items.length,i=this._items[--e].width(),s=this.$element.width();e--&&!((i+=this._items[e].width()+this.settings.margin)>s););o=e+1}else o=n.center?this._items.length-1:this._items.length-n.items;return t&&(o-=this._clones.length/2),Math.max(o,0)},n.prototype.minimum=function(t){return t?0:this._clones.length/2},n.prototype.items=function(t){return t===s?this._items.slice():(t=this.normalize(t,!0),this._items[t])},n.prototype.mergers=function(t){return t===s?this._mergers.slice():(t=this.normalize(t,!0),this._mergers[t])},n.prototype.clones=function(e){var i=this._clones.length/2,n=i+this._items.length,o=function(t){return t%2==0?n+t/2:i-(t+1)/2};return e===s?t.map(this._clones,function(t,e){return o(e)}):t.map(this._clones,function(t,i){return t===e?o(i):null})},n.prototype.speed=function(t){return t!==s&&(this._speed=t),this._speed},n.prototype.coordinates=function(e){var i,n=1,o=e-1;return e===s?t.map(this._coordinates,t.proxy(function(t,e){return this.coordinates(e)},this)):(this.settings.center?(this.settings.rtl&&(n=-1,o=e+1),i=this._coordinates[e],i+=(this.width()-i+(this._coordinates[o]||0))/2*n):i=this._coordinates[o]||0,i=Math.ceil(i))},n.prototype.duration=function(t,e,i){return 0===i?0:Math.min(Math.max(Math.abs(e-t),1),6)*Math.abs(i||this.settings.smartSpeed)},n.prototype.to=function(t,e){var i=this.current(),s=null,n=t-this.relative(i),o=(n>0)-(n<0),r=this._items.length,a=this.minimum(),h=this.maximum();this.settings.loop?(!this.settings.rewind&&Math.abs(n)>r/2&&(n+=-1*o*r),(s=(((t=i+n)-a)%r+r)%r+a)!==t&&s-n<=h&&s-n>0&&(i=s-n,t=s,this.reset(i))):this.settings.rewind?t=(t%(h+=1)+h)%h:t=Math.max(a,Math.min(h,t)),this.speed(this.duration(i,t,e)),this.current(t),this.$element.is(":visible")&&this.update()},n.prototype.next=function(t){t=t||!1,this.to(this.relative(this.current())+1,t)},n.prototype.prev=function(t){t=t||!1,this.to(this.relative(this.current())-1,t)},n.prototype.onTransitionEnd=function(t){if(t!==s&&(t.stopPropagation(),(t.target||t.srcElement||t.originalTarget)!==this.$stage.get(0)))return!1;this.leave("animating"),this.trigger("translated")},n.prototype.viewport=function(){var s;return this.options.responsiveBaseElement!==e?s=t(this.options.responsiveBaseElement).width():e.innerWidth?s=e.innerWidth:i.documentElement&&i.documentElement.clientWidth?s=i.documentElement.clientWidth:console.warn("Can not detect viewport width."),s},n.prototype.replace=function(e){this.$stage.empty(),this._items=[],e&&(e=e instanceof jQuery?e:t(e)),this.settings.nestedItemSelector&&(e=e.find("."+this.settings.nestedItemSelector)),e.filter(function(){return 1===this.nodeType}).each(t.proxy(function(t,e){e=this.prepare(e),this.$stage.append(e),this._items.push(e),this._mergers.push(1*e.find("[data-merge]").addBack("[data-merge]").attr("data-merge")||1)},this)),this.reset(this.isNumeric(this.settings.startPosition)?this.settings.startPosition:0),this.invalidate("items")},n.prototype.add=function(e,i){var n=this.relative(this._current);i=i===s?this._items.length:this.normalize(i,!0),e=e instanceof jQuery?e:t(e),this.trigger("add",{content:e,position:i}),e=this.prepare(e),0===this._items.length||i===this._items.length?(0===this._items.length&&this.$stage.append(e),0!==this._items.length&&this._items[i-1].after(e),this._items.push(e),this._mergers.push(1*e.find("[data-merge]").addBack("[data-merge]").attr("data-merge")||1)):(this._items[i].before(e),this._items.splice(i,0,e),this._mergers.splice(i,0,1*e.find("[data-merge]").addBack("[data-merge]").attr("data-merge")||1)),this._items[n]&&this.reset(this._items[n].index()),this.invalidate("items"),this.trigger("added",{content:e,position:i})},n.prototype.remove=function(t){(t=this.normalize(t,!0))!==s&&(this.trigger("remove",{content:this._items[t],position:t}),this._items[t].remove(),this._items.splice(t,1),this._mergers.splice(t,1),this.invalidate("items"),this.trigger("removed",{content:null,position:t}))},n.prototype.preloadAutoWidthImages=function(e){e.each(t.proxy(function(e,i){this.enter("pre-loading"),i=t(i),t(new Image).one("load",t.proxy(function(t){i.attr("src",t.target.src),i.css("opacity",1),this.leave("pre-loading"),!this.is("pre-loading")&&!this.is("initializing")&&this.refresh()},this)).attr("src",i.attr("src")||i.attr("data-src")||i.attr("data-src-retina"))},this))},n.prototype.destroy=function(){this.$element.off(".owl.core"),this.$stage.off(".owl.core"),t(i).off(".owl.core"),!1!==this.settings.responsive&&(e.clearTimeout(this.resizeTimer),this.off(e,"resize",this._handlers.onThrottledResize));for(var s in this._plugins)this._plugins[s].destroy();this.$stage.children(".cloned").remove(),this.$stage.unwrap(),this.$stage.children().contents().unwrap(),this.$stage.children().unwrap(),this.$element.removeClass(this.options.refreshClass).removeClass(this.options.loadingClass).removeClass(this.options.loadedClass).removeClass(this.options.rtlClass).removeClass(this.options.dragClass).removeClass(this.options.grabClass).attr("class",this.$element.attr("class").replace(new RegExp(this.options.responsiveClass+"-\\S+\\s","g"),"")).removeData("owl.carousel")},n.prototype.op=function(t,e,i){var s=this.settings.rtl;switch(e){case"<":return s?t>i:t<i;case">":return s?t<i:t>i;case">=":return s?t<=i:t>=i;case"<=":return s?t>=i:t<=i}},n.prototype.on=function(t,e,i,s){t.addEventListener?t.addEventListener(e,i,s):t.attachEvent&&t.attachEvent("on"+e,i)},n.prototype.off=function(t,e,i,s){t.removeEventListener?t.removeEventListener(e,i,s):t.detachEvent&&t.detachEvent("on"+e,i)},n.prototype.trigger=function(e,i,s,o,r){var a={item:{count:this._items.length,index:this.current()}},h=t.camelCase(t.grep(["on",e,s],function(t){return t}).join("-").toLowerCase()),l=t.Event([e,"owl",s||"carousel"].join(".").toLowerCase(),t.extend({relatedTarget:this},a,i));return this._supress[e]||(t.each(this._plugins,function(t,e){e.onTrigger&&e.onTrigger(l)}),this.register({type:n.Type.Event,name:e}),this.$element.trigger(l),this.settings&&"function"==typeof this.settings[h]&&this.settings[h].call(this,l)),l},n.prototype.enter=function(e){t.each([e].concat(this._states.tags[e]||[]),t.proxy(function(t,e){this._states.current[e]===s&&(this._states.current[e]=0),this._states.current[e]++},this))},n.prototype.leave=function(e){t.each([e].concat(this._states.tags[e]||[]),t.proxy(function(t,e){this._states.current[e]--},this))},n.prototype.register=function(e){if(e.type===n.Type.Event){if(t.event.special[e.name]||(t.event.special[e.name]={}),!t.event.special[e.name].owl){var i=t.event.special[e.name]._default;t.event.special[e.name]._default=function(t){return!i||!i.apply||t.namespace&&-1!==t.namespace.indexOf("owl")?t.namespace&&t.namespace.indexOf("owl")>-1:i.apply(this,arguments)},t.event.special[e.name].owl=!0}}else e.type===n.Type.State&&(this._states.tags[e.name]?this._states.tags[e.name]=this._states.tags[e.name].concat(e.tags):this._states.tags[e.name]=e.tags,this._states.tags[e.name]=t.grep(this._states.tags[e.name],t.proxy(function(i,s){return t.inArray(i,this._states.tags[e.name])===s},this)))},n.prototype.suppress=function(e){t.each(e,t.proxy(function(t,e){this._supress[e]=!0},this))},n.prototype.release=function(e){t.each(e,t.proxy(function(t,e){delete this._supress[e]},this))},n.prototype.pointer=function(t){var i={x:null,y:null};return(t=(t=t.originalEvent||t||e.event).touches&&t.touches.length?t.touches[0]:t.changedTouches&&t.changedTouches.length?t.changedTouches[0]:t).pageX?(i.x=t.pageX,i.y=t.pageY):(i.x=t.clientX,i.y=t.clientY),i},n.prototype.isNumeric=function(t){return!isNaN(parseFloat(t))},n.prototype.difference=function(t,e){return{x:t.x-e.x,y:t.y-e.y}},t.fn.owlCarousel=function(e){var i=Array.prototype.slice.call(arguments,1);return this.each(function(){var s=t(this),o=s.data("owl.carousel");o||(o=new n(this,"object"==typeof e&&e),s.data("owl.carousel",o),t.each(["next","prev","to","destroy","refresh","replace","add","remove"],function(e,i){o.register({type:n.Type.Event,name:i}),o.$element.on(i+".owl.carousel.core",t.proxy(function(t){t.namespace&&t.relatedTarget!==this&&(this.suppress([i]),o[i].apply(this,[].slice.call(arguments,1)),this.release([i]))},o))})),"string"==typeof e&&"_"!==e.charAt(0)&&o[e].apply(o,i)})},t.fn.owlCarousel.Constructor=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){var n=function(e){this._core=e,this._interval=null,this._visible=null,this._handlers={"initialized.owl.carousel":t.proxy(function(t){t.namespace&&this._core.settings.autoRefresh&&this.watch()},this)},this._core.options=t.extend({},n.Defaults,this._core.options),this._core.$element.on(this._handlers)};n.Defaults={autoRefresh:!0,autoRefreshInterval:500},n.prototype.watch=function(){this._interval||(this._visible=this._core.$element.is(":visible"),this._interval=e.setInterval(t.proxy(this.refresh,this),this._core.settings.autoRefreshInterval))},n.prototype.refresh=function(){this._core.$element.is(":visible")!==this._visible&&(this._visible=!this._visible,this._core.$element.toggleClass("owl-hidden",!this._visible),this._visible&&this._core.invalidate("width")&&this._core.refresh())},n.prototype.destroy=function(){var t,i;e.clearInterval(this._interval);for(t in this._handlers)this._core.$element.off(t,this._handlers[t]);for(i in Object.getOwnPropertyNames(this))"function"!=typeof this[i]&&(this[i]=null)},t.fn.owlCarousel.Constructor.Plugins.AutoRefresh=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){var n=function(e){this._core=e,this._loaded=[],this._handlers={"initialized.owl.carousel change.owl.carousel resized.owl.carousel":t.proxy(function(e){if(e.namespace&&this._core.settings&&this._core.settings.lazyLoad&&(e.property&&"position"==e.property.name||"initialized"==e.type))for(var i=this._core.settings,s=i.center&&Math.ceil(i.items/2)||i.items,n=i.center&&-1*s||0,o=(e.property&&void 0!==e.property.value?e.property.value:this._core.current())+n,r=this._core.clones().length,a=t.proxy(function(t,e){this.load(e)},this);n++<s;)this.load(r/2+this._core.relative(o)),r&&t.each(this._core.clones(this._core.relative(o)),a),o++},this)},this._core.options=t.extend({},n.Defaults,this._core.options),this._core.$element.on(this._handlers)};n.Defaults={lazyLoad:!1},n.prototype.load=function(i){var s=this._core.$stage.children().eq(i),n=s&&s.find(".owl-lazy");!n||t.inArray(s.get(0),this._loaded)>-1||(n.each(t.proxy(function(i,s){var n,o=t(s),r=e.devicePixelRatio>1&&o.attr("data-src-retina")||o.attr("data-src");this._core.trigger("load",{element:o,url:r},"lazy"),o.is("img")?o.one("load.owl.lazy",t.proxy(function(){o.css("opacity",1),this._core.trigger("loaded",{element:o,url:r},"lazy")},this)).attr("src",r):((n=new Image).onload=t.proxy(function(){o.css({"background-image":'url("'+r+'")',opacity:"1"}),this._core.trigger("loaded",{element:o,url:r},"lazy")},this),n.src=r)},this)),this._loaded.push(s.get(0)))},n.prototype.destroy=function(){var t,e;for(t in this.handlers)this._core.$element.off(t,this.handlers[t]);for(e in Object.getOwnPropertyNames(this))"function"!=typeof this[e]&&(this[e]=null)},t.fn.owlCarousel.Constructor.Plugins.Lazy=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){var n=function(e){this._core=e,this._handlers={"initialized.owl.carousel refreshed.owl.carousel":t.proxy(function(t){t.namespace&&this._core.settings.autoHeight&&this.update()},this),"changed.owl.carousel":t.proxy(function(t){t.namespace&&this._core.settings.autoHeight&&"position"==t.property.name&&this.update()},this),"loaded.owl.lazy":t.proxy(function(t){t.namespace&&this._core.settings.autoHeight&&t.element.closest("."+this._core.settings.itemClass).index()===this._core.current()&&this.update()},this)},this._core.options=t.extend({},n.Defaults,this._core.options),this._core.$element.on(this._handlers)};n.Defaults={autoHeight:!1,autoHeightClass:"owl-height"},n.prototype.update=function(){var e,i=this._core._current,s=i+this._core.settings.items,n=this._core.$stage.children().toArray().slice(i,s),o=[];t.each(n,function(e,i){o.push(t(i).height())}),e=Math.max.apply(null,o),this._core.$stage.parent().height(e).addClass(this._core.settings.autoHeightClass)},n.prototype.destroy=function(){var t,e;for(t in this._handlers)this._core.$element.off(t,this._handlers[t]);for(e in Object.getOwnPropertyNames(this))"function"!=typeof this[e]&&(this[e]=null)},t.fn.owlCarousel.Constructor.Plugins.AutoHeight=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){var n=function(e){this._core=e,this._videos={},this._playing=null,this._handlers={"initialized.owl.carousel":t.proxy(function(t){t.namespace&&this._core.register({type:"state",name:"playing",tags:["interacting"]})},this),"resize.owl.carousel":t.proxy(function(t){t.namespace&&this._core.settings.video&&this.isInFullScreen()&&t.preventDefault()},this),"refreshed.owl.carousel":t.proxy(function(t){t.namespace&&this._core.is("resizing")&&this._core.$stage.find(".cloned .owl-video-frame").remove()},this),"changed.owl.carousel":t.proxy(function(t){t.namespace&&"position"===t.property.name&&this._playing&&this.stop()},this),"prepared.owl.carousel":t.proxy(function(e){if(e.namespace){var i=t(e.content).find(".owl-video");i.length&&(i.css("display","none"),this.fetch(i,t(e.content)))}},this)},this._core.options=t.extend({},n.Defaults,this._core.options),this._core.$element.on(this._handlers),this._core.$element.on("click.owl.video",".owl-video-play-icon",t.proxy(function(t){this.play(t)},this))};n.Defaults={video:!1,videoHeight:!1,videoWidth:!1},n.prototype.fetch=function(t,e){var i=t.attr("data-vimeo-id")?"vimeo":t.attr("data-vzaar-id")?"vzaar":"youtube",s=t.attr("data-vimeo-id")||t.attr("data-youtube-id")||t.attr("data-vzaar-id"),n=t.attr("data-width")||this._core.settings.videoWidth,o=t.attr("data-height")||this._core.settings.videoHeight,r=t.attr("href");if(!r)throw new Error("Missing video URL.");if((s=r.match(/(http:|https:|)\/\/(player.|www.|app.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com)|vzaar\.com)\/(video\/|videos\/|embed\/|channels\/.+\/|groups\/.+\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/))[3].indexOf("youtu")>-1)i="youtube";else if(s[3].indexOf("vimeo")>-1)i="vimeo";else{if(!(s[3].indexOf("vzaar")>-1))throw new Error("Video URL not supported.");i="vzaar"}s=s[6],this._videos[r]={type:i,id:s,width:n,height:o},e.attr("data-video",r),this.thumbnail(t,this._videos[r])},n.prototype.thumbnail=function(e,i){var s,n,o,r=i.width&&i.height?'style="width:'+i.width+"px;height:"+i.height+'px;"':"",a=e.find("img"),h="src",l="",c=this._core.settings,p=function(t){n='<div class="owl-video-play-icon"></div>',s=c.lazyLoad?'<div class="owl-video-tn '+l+'" '+h+'="'+t+'"></div>':'<div class="owl-video-tn" style="opacity:1;background-image:url('+t+')"></div>',e.after(s),e.after(n)};if(e.wrap('<div class="owl-video-wrapper"'+r+"></div>"),this._core.settings.lazyLoad&&(h="data-src",l="owl-lazy"),a.length)return p(a.attr(h)),a.remove(),!1;"youtube"===i.type?(o="//img.youtube.com/vi/"+i.id+"/hqdefault.jpg",p(o)):"vimeo"===i.type?t.ajax({type:"GET",url:"//vimeo.com/api/v2/video/"+i.id+".json",jsonp:"callback",dataType:"jsonp",success:function(t){o=t[0].thumbnail_large,p(o)}}):"vzaar"===i.type&&t.ajax({type:"GET",url:"//vzaar.com/api/videos/"+i.id+".json",jsonp:"callback",dataType:"jsonp",success:function(t){o=t.framegrab_url,p(o)}})},n.prototype.stop=function(){this._core.trigger("stop",null,"video"),this._playing.find(".owl-video-frame").remove(),this._playing.removeClass("owl-video-playing"),this._playing=null,this._core.leave("playing"),this._core.trigger("stopped",null,"video")},n.prototype.play=function(e){var i,s=t(e.target).closest("."+this._core.settings.itemClass),n=this._videos[s.attr("data-video")],o=n.width||"100%",r=n.height||this._core.$stage.height();this._playing||(this._core.enter("playing"),this._core.trigger("play",null,"video"),s=this._core.items(this._core.relative(s.index())),this._core.reset(s.index()),"youtube"===n.type?i='<iframe width="'+o+'" height="'+r+'" src="//www.youtube.com/embed/'+n.id+"?autoplay=1&rel=0&v="+n.id+'" frameborder="0" allowfullscreen></iframe>':"vimeo"===n.type?i='<iframe src="//player.vimeo.com/video/'+n.id+'?autoplay=1" width="'+o+'" height="'+r+'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>':"vzaar"===n.type&&(i='<iframe frameborder="0"height="'+r+'"width="'+o+'" allowfullscreen mozallowfullscreen webkitAllowFullScreen src="//view.vzaar.com/'+n.id+'/player?autoplay=true"></iframe>'),t('<div class="owl-video-frame">'+i+"</div>").insertAfter(s.find(".owl-video")),this._playing=s.addClass("owl-video-playing"))},n.prototype.isInFullScreen=function(){var e=i.fullscreenElement||i.mozFullScreenElement||i.webkitFullscreenElement;return e&&t(e).parent().hasClass("owl-video-frame")},n.prototype.destroy=function(){var t,e;this._core.$element.off("click.owl.video");for(t in this._handlers)this._core.$element.off(t,this._handlers[t]);for(e in Object.getOwnPropertyNames(this))"function"!=typeof this[e]&&(this[e]=null)},t.fn.owlCarousel.Constructor.Plugins.Video=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){var n=function(e){this.core=e,this.core.options=t.extend({},n.Defaults,this.core.options),this.swapping=!0,this.previous=void 0,this.next=void 0,this.handlers={"change.owl.carousel":t.proxy(function(t){t.namespace&&"position"==t.property.name&&(this.previous=this.core.current(),this.next=t.property.value)},this),"drag.owl.carousel dragged.owl.carousel translated.owl.carousel":t.proxy(function(t){t.namespace&&(this.swapping="translated"==t.type)},this),"translate.owl.carousel":t.proxy(function(t){t.namespace&&this.swapping&&(this.core.options.animateOut||this.core.options.animateIn)&&this.swap()},this)},this.core.$element.on(this.handlers)};n.Defaults={animateOut:!1,animateIn:!1},n.prototype.swap=function(){if(1===this.core.settings.items&&t.support.animation&&t.support.transition){this.core.speed(0);var e,i=t.proxy(this.clear,this),s=this.core.$stage.children().eq(this.previous),n=this.core.$stage.children().eq(this.next),o=this.core.settings.animateIn,r=this.core.settings.animateOut;this.core.current()!==this.previous&&(r&&(e=this.core.coordinates(this.previous)-this.core.coordinates(this.next),s.one(t.support.animation.end,i).css({left:e+"px"}).addClass("animated owl-animated-out").addClass(r)),o&&n.one(t.support.animation.end,i).addClass("animated owl-animated-in").addClass(o))}},n.prototype.clear=function(e){t(e.target).css({left:""}).removeClass("animated owl-animated-out owl-animated-in").removeClass(this.core.settings.animateIn).removeClass(this.core.settings.animateOut),this.core.onTransitionEnd()},n.prototype.destroy=function(){var t,e;for(t in this.handlers)this.core.$element.off(t,this.handlers[t]);for(e in Object.getOwnPropertyNames(this))"function"!=typeof this[e]&&(this[e]=null)},t.fn.owlCarousel.Constructor.Plugins.Animate=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){var n=function(e){this._core=e,this._timeout=null,this._paused=!1,this._handlers={"changed.owl.carousel":t.proxy(function(t){t.namespace&&"settings"===t.property.name?this._core.settings.autoplay?this.play():this.stop():t.namespace&&"position"===t.property.name&&this._core.settings.autoplay&&this._setAutoPlayInterval()},this),"initialized.owl.carousel":t.proxy(function(t){t.namespace&&this._core.settings.autoplay&&this.play()},this),"play.owl.autoplay":t.proxy(function(t,e,i){t.namespace&&this.play(e,i)},this),"stop.owl.autoplay":t.proxy(function(t){t.namespace&&this.stop()},this),"mouseover.owl.autoplay":t.proxy(function(){this._core.settings.autoplayHoverPause&&this._core.is("rotating")&&this.pause()},this),"mouseleave.owl.autoplay":t.proxy(function(){this._core.settings.autoplayHoverPause&&this._core.is("rotating")&&this.play()},this),"touchstart.owl.core":t.proxy(function(){this._core.settings.autoplayHoverPause&&this._core.is("rotating")&&this.pause()},this),"touchend.owl.core":t.proxy(function(){this._core.settings.autoplayHoverPause&&this.play()},this)},this._core.$element.on(this._handlers),this._core.options=t.extend({},n.Defaults,this._core.options)};n.Defaults={autoplay:!1,autoplayTimeout:5e3,autoplayHoverPause:!1,autoplaySpeed:!1},n.prototype.play=function(t,e){this._paused=!1,this._core.is("rotating")||(this._core.enter("rotating"),this._setAutoPlayInterval())},n.prototype._getNextTimeout=function(s,n){return this._timeout&&e.clearTimeout(this._timeout),e.setTimeout(t.proxy(function(){this._paused||this._core.is("busy")||this._core.is("interacting")||i.hidden||this._core.next(n||this._core.settings.autoplaySpeed)},this),s||this._core.settings.autoplayTimeout)},n.prototype._setAutoPlayInterval=function(){this._timeout=this._getNextTimeout()},n.prototype.stop=function(){this._core.is("rotating")&&(e.clearTimeout(this._timeout),this._core.leave("rotating"))},n.prototype.pause=function(){this._core.is("rotating")&&(this._paused=!0)},n.prototype.destroy=function(){var t,e;this.stop();for(t in this._handlers)this._core.$element.off(t,this._handlers[t]);for(e in Object.getOwnPropertyNames(this))"function"!=typeof this[e]&&(this[e]=null)},t.fn.owlCarousel.Constructor.Plugins.autoplay=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){"use strict";var n=function(e){this._core=e,this._initialized=!1,this._pages=[],this._controls={},this._templates=[],this.$element=this._core.$element,this._overrides={next:this._core.next,prev:this._core.prev,to:this._core.to},this._handlers={"prepared.owl.carousel":t.proxy(function(e){e.namespace&&this._core.settings.dotsData&&this._templates.push('<div class="'+this._core.settings.dotClass+'">'+t(e.content).find("[data-dot]").addBack("[data-dot]").attr("data-dot")+"</div>")},this),"added.owl.carousel":t.proxy(function(t){t.namespace&&this._core.settings.dotsData&&this._templates.splice(t.position,0,this._templates.pop())},this),"remove.owl.carousel":t.proxy(function(t){t.namespace&&this._core.settings.dotsData&&this._templates.splice(t.position,1)},this),"changed.owl.carousel":t.proxy(function(t){t.namespace&&"position"==t.property.name&&this.draw()},this),"initialized.owl.carousel":t.proxy(function(t){t.namespace&&!this._initialized&&(this._core.trigger("initialize",null,"navigation"),this.initialize(),this.update(),this.draw(),this._initialized=!0,this._core.trigger("initialized",null,"navigation"))},this),"refreshed.owl.carousel":t.proxy(function(t){t.namespace&&this._initialized&&(this._core.trigger("refresh",null,"navigation"),this.update(),this.draw(),this._core.trigger("refreshed",null,"navigation"))},this)},this._core.options=t.extend({},n.Defaults,this._core.options),this.$element.on(this._handlers)};n.Defaults={nav:!1,navText:["prev","next"],navSpeed:!1,navElement:"div",navContainer:!1,navContainerClass:"owl-nav",navClass:["owl-prev","owl-next"],slideBy:1,dotClass:"owl-dot",dotsClass:"owl-dots",dots:!0,dotsEach:!1,dotsData:!1,dotsSpeed:!1,dotsContainer:!1},n.prototype.initialize=function(){var e,i=this._core.settings;this._controls.$relative=(i.navContainer?t(i.navContainer):t("<div>").addClass(i.navContainerClass).appendTo(this.$element)).addClass("disabled"),this._controls.$previous=t("<"+i.navElement+">").addClass(i.navClass[0]).html(i.navText[0]).prependTo(this._controls.$relative).on("click",t.proxy(function(t){this.prev(i.navSpeed)},this)),this._controls.$next=t("<"+i.navElement+">").addClass(i.navClass[1]).html(i.navText[1]).appendTo(this._controls.$relative).on("click",t.proxy(function(t){this.next(i.navSpeed)},this)),i.dotsData||(this._templates=[t("<div>").addClass(i.dotClass).append(t("<span>")).prop("outerHTML")]),this._controls.$absolute=(i.dotsContainer?t(i.dotsContainer):t("<div>").addClass(i.dotsClass).appendTo(this.$element)).addClass("disabled"),this._controls.$absolute.on("click","div",t.proxy(function(e){var s=t(e.target).parent().is(this._controls.$absolute)?t(e.target).index():t(e.target).parent().index();e.preventDefault(),this.to(s,i.dotsSpeed)},this));for(e in this._overrides)this._core[e]=t.proxy(this[e],this)},n.prototype.destroy=function(){var t,e,i,s;for(t in this._handlers)this.$element.off(t,this._handlers[t]);for(e in this._controls)this._controls[e].remove();for(s in this.overides)this._core[s]=this._overrides[s];for(i in Object.getOwnPropertyNames(this))"function"!=typeof this[i]&&(this[i]=null)},n.prototype.update=function(){var t,e,i=this._core.clones().length/2,s=i+this._core.items().length,n=this._core.maximum(!0),o=this._core.settings,r=o.center||o.autoWidth||o.dotsData?1:o.dotsEach||o.items;if("page"!==o.slideBy&&(o.slideBy=Math.min(o.slideBy,o.items)),o.dots||"page"==o.slideBy)for(this._pages=[],t=i,e=0,0;t<s;t++){if(e>=r||0===e){if(this._pages.push({start:Math.min(n,t-i),end:t-i+r-1}),Math.min(n,t-i)===n)break;e=0,0}e+=this._core.mergers(this._core.relative(t))}},n.prototype.draw=function(){var e,i=this._core.settings,s=this._core.items().length<=i.items,n=this._core.relative(this._core.current()),o=i.loop||i.rewind;this._controls.$relative.toggleClass("disabled",!i.nav||s),i.nav&&(this._controls.$previous.toggleClass("disabled",!o&&n<=this._core.minimum(!0)),this._controls.$next.toggleClass("disabled",!o&&n>=this._core.maximum(!0))),this._controls.$absolute.toggleClass("disabled",!i.dots||s),i.dots&&(e=this._pages.length-this._controls.$absolute.children().length,i.dotsData&&0!==e?this._controls.$absolute.html(this._templates.join("")):e>0?this._controls.$absolute.append(new Array(e+1).join(this._templates[0])):e<0&&this._controls.$absolute.children().slice(e).remove(),this._controls.$absolute.find(".active").removeClass("active"),this._controls.$absolute.children().eq(t.inArray(this.current(),this._pages)).addClass("active"))},n.prototype.onTrigger=function(e){var i=this._core.settings;e.page={index:t.inArray(this.current(),this._pages),count:this._pages.length,size:i&&(i.center||i.autoWidth||i.dotsData?1:i.dotsEach||i.items)}},n.prototype.current=function(){var e=this._core.relative(this._core.current());return t.grep(this._pages,t.proxy(function(t,i){return t.start<=e&&t.end>=e},this)).pop()},n.prototype.getPosition=function(e){var i,s,n=this._core.settings;return"page"==n.slideBy?(i=t.inArray(this.current(),this._pages),s=this._pages.length,e?++i:--i,i=this._pages[(i%s+s)%s].start):(i=this._core.relative(this._core.current()),s=this._core.items().length,e?i+=n.slideBy:i-=n.slideBy),i},n.prototype.next=function(e){t.proxy(this._overrides.to,this._core)(this.getPosition(!0),e)},n.prototype.prev=function(e){t.proxy(this._overrides.to,this._core)(this.getPosition(!1),e)},n.prototype.to=function(e,i,s){var n;!s&&this._pages.length?(n=this._pages.length,t.proxy(this._overrides.to,this._core)(this._pages[(e%n+n)%n].start,i)):t.proxy(this._overrides.to,this._core)(e,i)},t.fn.owlCarousel.Constructor.Plugins.Navigation=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){"use strict";var n=function(i){this._core=i,this._hashes={},this.$element=this._core.$element,this._handlers={"initialized.owl.carousel":t.proxy(function(i){i.namespace&&"URLHash"===this._core.settings.startPosition&&t(e).trigger("hashchange.owl.navigation")},this),"prepared.owl.carousel":t.proxy(function(e){if(e.namespace){var i=t(e.content).find("[data-hash]").addBack("[data-hash]").attr("data-hash");if(!i)return;this._hashes[i]=e.content}},this),"changed.owl.carousel":t.proxy(function(i){if(i.namespace&&"position"===i.property.name){var s=this._core.items(this._core.relative(this._core.current())),n=t.map(this._hashes,function(t,e){return t===s?e:null}).join();if(!n||e.location.hash.slice(1)===n)return;e.location.hash=n}},this)},this._core.options=t.extend({},n.Defaults,this._core.options),this.$element.on(this._handlers),t(e).on("hashchange.owl.navigation",t.proxy(function(t){var i=e.location.hash.substring(1),s=this._core.$stage.children(),n=this._hashes[i]&&s.index(this._hashes[i]);void 0!==n&&n!==this._core.current()&&this._core.to(this._core.relative(n),!1,!0)},this))};n.Defaults={URLhashListener:!1},n.prototype.destroy=function(){var i,s;t(e).off("hashchange.owl.navigation");for(i in this._handlers)this._core.$element.off(i,this._handlers[i]);for(s in Object.getOwnPropertyNames(this))"function"!=typeof this[s]&&(this[s]=null)},t.fn.owlCarousel.Constructor.Plugins.Hash=n}(window.Zepto||window.jQuery,window,document),function(t,e,i,s){function n(e,i){var n=!1,o=e.charAt(0).toUpperCase()+e.slice(1);return t.each((e+" "+a.join(o+" ")+o).split(" "),function(t,e){if(r[e]!==s)return n=!i||e,!1}),n}function o(t){return n(t,!0)}var r=t("<support>").get(0).style,a="Webkit Moz O ms".split(" "),h={transition:{end:{WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd",transition:"transitionend"}},animation:{end:{WebkitAnimation:"webkitAnimationEnd",MozAnimation:"animationend",OAnimation:"oAnimationEnd",animation:"animationend"}}},l=function(){return!!n("transform")},c=function(){return!!n("perspective")},p=function(){return!!n("animation")};(function(){return!!n("transition")})()&&(t.support.transition=new String(o("transition")),t.support.transition.end=h.transition.end[t.support.transition]),p()&&(t.support.animation=new String(o("animation")),t.support.animation.end=h.animation.end[t.support.animation]),l()&&(t.support.transform=new String(o("transform")),t.support.transform3d=c())}(window.Zepto||window.jQuery,window,document);
/*!
 * JavaScript Cookie v2.2.0
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
;(function (factory) {
    var registeredInModuleLoader = false;
    if (typeof define === 'function' && define.amd) {
        define(factory);
        registeredInModuleLoader = true;
    }
    if (typeof exports === 'object') {
        module.exports = factory();
        registeredInModuleLoader = true;
    }
    if (!registeredInModuleLoader) {
        var OldCookies = window.Cookies;
        var api = window.Cookies = factory();
        api.noConflict = function () {
            window.Cookies = OldCookies;
            return api;
        };
    }
}(function () {
    function extend() {
        var i = 0;
        var result = {};
        for (; i < arguments.length; i++) {
            var attributes = arguments[i];
            for (var key in attributes) {
                result[key] = attributes[key];
            }
        }
        return result;
    }

    function init(converter) {
        function api(key, value, attributes) {
            var result;
            if (typeof document === 'undefined') {
                return;
            }

            // Write

            if (arguments.length > 1) {
                attributes = extend({
                    path: '/'
                }, api.defaults, attributes);

                if (typeof attributes.expires === 'number') {
                    var expires = new Date();
                    expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
                    attributes.expires = expires;
                }

                // We're using "expires" because "max-age" is not supported by IE
                attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';

                try {
                    result = JSON.stringify(value);
                    if (/^[\{\[]/.test(result)) {
                        value = result;
                    }
                } catch (e) {
                }

                if (!converter.write) {
                    value = encodeURIComponent(String(value))
                        .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
                } else {
                    value = converter.write(value, key);
                }

                key = encodeURIComponent(String(key));
                key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
                key = key.replace(/[\(\)]/g, escape);

                var stringifiedAttributes = '';

                for (var attributeName in attributes) {
                    if (!attributes[attributeName]) {
                        continue;
                    }
                    stringifiedAttributes += '; ' + attributeName;
                    if (attributes[attributeName] === true) {
                        continue;
                    }
                    stringifiedAttributes += '=' + attributes[attributeName];
                }
                return (document.cookie = key + '=' + value + stringifiedAttributes);
            }

            // Read

            if (!key) {
                result = {};
            }

            // To prevent the for loop in the first place assign an empty array
            // in case there are no cookies at all. Also prevents odd result when
            // calling "get()"
            var cookies = document.cookie ? document.cookie.split('; ') : [];
            var rdecode = /(%[0-9A-Z]{2})+/g;
            var i = 0;

            for (; i < cookies.length; i++) {
                var parts = cookies[i].split('=');
                var cookie = parts.slice(1).join('=');

                if (!this.json && cookie.charAt(0) === '"') {
                    cookie = cookie.slice(1, -1);
                }

                try {
                    var name = parts[0].replace(rdecode, decodeURIComponent);
                    cookie = converter.read ?
                        converter.read(cookie, name) : converter(cookie, name) ||
                        cookie.replace(rdecode, decodeURIComponent);

                    if (this.json) {
                        try {
                            cookie = JSON.parse(cookie);
                        } catch (e) {
                        }
                    }

                    if (key === name) {
                        result = cookie;
                        break;
                    }

                    if (!key) {
                        result[name] = cookie;
                    }
                } catch (e) {
                }
            }

            return result;
        }

        api.set = api;
        api.get = function (key) {
            return api.call(api, key);
        };
        api.getJSON = function () {
            return api.apply({
                json: true
            }, [].slice.call(arguments));
        };
        api.defaults = {};

        api.remove = function (key, attributes) {
            api(key, '', extend(attributes, {
                expires: -1
            }));
        };

        api.withConverter = init;

        return api;
    }

    return init(function () {
    });
}));
/*!
 * imagesLoaded PACKAGED v4.1.4
 * JavaScript is all like "You images are done yet or what?"
 * MIT License
 */

!function(e,t){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",t):"object"==typeof module&&module.exports?module.exports=t():e.EvEmitter=t()}("undefined"!=typeof window?window:this,function(){function e(){}var t=e.prototype;return t.on=function(e,t){if(e&&t){var i=this._events=this._events||{},n=i[e]=i[e]||[];return n.indexOf(t)==-1&&n.push(t),this}},t.once=function(e,t){if(e&&t){this.on(e,t);var i=this._onceEvents=this._onceEvents||{},n=i[e]=i[e]||{};return n[t]=!0,this}},t.off=function(e,t){var i=this._events&&this._events[e];if(i&&i.length){var n=i.indexOf(t);return n!=-1&&i.splice(n,1),this}},t.emitEvent=function(e,t){var i=this._events&&this._events[e];if(i&&i.length){i=i.slice(0),t=t||[];for(var n=this._onceEvents&&this._onceEvents[e],o=0;o<i.length;o++){var r=i[o],s=n&&n[r];s&&(this.off(e,r),delete n[r]),r.apply(this,t)}return this}},t.allOff=function(){delete this._events,delete this._onceEvents},e}),function(e,t){"use strict";"function"==typeof define&&define.amd?define(["ev-emitter/ev-emitter"],function(i){return t(e,i)}):"object"==typeof module&&module.exports?module.exports=t(e,require("ev-emitter")):e.imagesLoaded=t(e,e.EvEmitter)}("undefined"!=typeof window?window:this,function(e,t){function i(e,t){for(var i in t)e[i]=t[i];return e}function n(e){if(Array.isArray(e))return e;var t="object"==typeof e&&"number"==typeof e.length;return t?d.call(e):[e]}function o(e,t,r){if(!(this instanceof o))return new o(e,t,r);var s=e;return"string"==typeof e&&(s=document.querySelectorAll(e)),s?(this.elements=n(s),this.options=i({},this.options),"function"==typeof t?r=t:i(this.options,t),r&&this.on("always",r),this.getImages(),h&&(this.jqDeferred=new h.Deferred),void setTimeout(this.check.bind(this))):void a.error("Bad element for imagesLoaded "+(s||e))}function r(e){this.img=e}function s(e,t){this.url=e,this.element=t,this.img=new Image}var h=e.jQuery,a=e.console,d=Array.prototype.slice;o.prototype=Object.create(t.prototype),o.prototype.options={},o.prototype.getImages=function(){this.images=[],this.elements.forEach(this.addElementImages,this)},o.prototype.addElementImages=function(e){"IMG"==e.nodeName&&this.addImage(e),this.options.background===!0&&this.addElementBackgroundImages(e);var t=e.nodeType;if(t&&u[t]){for(var i=e.querySelectorAll("img"),n=0;n<i.length;n++){var o=i[n];this.addImage(o)}if("string"==typeof this.options.background){var r=e.querySelectorAll(this.options.background);for(n=0;n<r.length;n++){var s=r[n];this.addElementBackgroundImages(s)}}}};var u={1:!0,9:!0,11:!0};return o.prototype.addElementBackgroundImages=function(e){var t=getComputedStyle(e);if(t)for(var i=/url\((['"])?(.*?)\1\)/gi,n=i.exec(t.backgroundImage);null!==n;){var o=n&&n[2];o&&this.addBackground(o,e),n=i.exec(t.backgroundImage)}},o.prototype.addImage=function(e){var t=new r(e);this.images.push(t)},o.prototype.addBackground=function(e,t){var i=new s(e,t);this.images.push(i)},o.prototype.check=function(){function e(e,i,n){setTimeout(function(){t.progress(e,i,n)})}var t=this;return this.progressedCount=0,this.hasAnyBroken=!1,this.images.length?void this.images.forEach(function(t){t.once("progress",e),t.check()}):void this.complete()},o.prototype.progress=function(e,t,i){this.progressedCount++,this.hasAnyBroken=this.hasAnyBroken||!e.isLoaded,this.emitEvent("progress",[this,e,t]),this.jqDeferred&&this.jqDeferred.notify&&this.jqDeferred.notify(this,e),this.progressedCount==this.images.length&&this.complete(),this.options.debug&&a&&a.log("progress: "+i,e,t)},o.prototype.complete=function(){var e=this.hasAnyBroken?"fail":"done";if(this.isComplete=!0,this.emitEvent(e,[this]),this.emitEvent("always",[this]),this.jqDeferred){var t=this.hasAnyBroken?"reject":"resolve";this.jqDeferred[t](this)}},r.prototype=Object.create(t.prototype),r.prototype.check=function(){var e=this.getIsImageComplete();return e?void this.confirm(0!==this.img.naturalWidth,"naturalWidth"):(this.proxyImage=new Image,this.proxyImage.addEventListener("load",this),this.proxyImage.addEventListener("error",this),this.img.addEventListener("load",this),this.img.addEventListener("error",this),void(this.proxyImage.src=this.img.src))},r.prototype.getIsImageComplete=function(){return this.img.complete&&this.img.naturalWidth},r.prototype.confirm=function(e,t){this.isLoaded=e,this.emitEvent("progress",[this,this.img,t])},r.prototype.handleEvent=function(e){var t="on"+e.type;this[t]&&this[t](e)},r.prototype.onload=function(){this.confirm(!0,"onload"),this.unbindEvents()},r.prototype.onerror=function(){this.confirm(!1,"onerror"),this.unbindEvents()},r.prototype.unbindEvents=function(){this.proxyImage.removeEventListener("load",this),this.proxyImage.removeEventListener("error",this),this.img.removeEventListener("load",this),this.img.removeEventListener("error",this)},s.prototype=Object.create(r.prototype),s.prototype.check=function(){this.img.addEventListener("load",this),this.img.addEventListener("error",this),this.img.src=this.url;var e=this.getIsImageComplete();e&&(this.confirm(0!==this.img.naturalWidth,"naturalWidth"),this.unbindEvents())},s.prototype.unbindEvents=function(){this.img.removeEventListener("load",this),this.img.removeEventListener("error",this)},s.prototype.confirm=function(e,t){this.isLoaded=e,this.emitEvent("progress",[this,this.element,t])},o.makeJQueryPlugin=function(t){t=t||e.jQuery,t&&(h=t,h.fn.imagesLoaded=function(e,t){var i=new o(this,e,t);return i.jqDeferred.promise(h(this))})},o.makeJQueryPlugin(),o});
/*!
 * Masonry PACKAGED v4.2.2
 * Cascading grid layout library
 * https://masonry.desandro.com
 * MIT License
 * by David DeSandro
 */

/**
 * Bridget makes jQuery widgets
 * v2.0.1
 * MIT license
 */

/* jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'jquery-bridget/jquery-bridget',[ 'jquery' ], function( jQuery ) {
      return factory( window, jQuery );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('jquery')
    );
  } else {
    // browser global
    window.jQueryBridget = factory(
      window,
      window.jQuery
    );
  }

}( window, function factory( window, jQuery ) {
'use strict';

// ----- utils ----- //

var arraySlice = Array.prototype.slice;

// helper function for logging errors
// $.error breaks jQuery chaining
var console = window.console;
var logError = typeof console == 'undefined' ? function() {} :
  function( message ) {
    console.error( message );
  };

// ----- jQueryBridget ----- //

function jQueryBridget( namespace, PluginClass, $ ) {
  $ = $ || jQuery || window.jQuery;
  if ( !$ ) {
    return;
  }

  // add option method -> $().plugin('option', {...})
  if ( !PluginClass.prototype.option ) {
    // option setter
    PluginClass.prototype.option = function( opts ) {
      // bail out if not an object
      if ( !$.isPlainObject( opts ) ){
        return;
      }
      this.options = $.extend( true, this.options, opts );
    };
  }

  // make jQuery plugin
  $.fn[ namespace ] = function( arg0 /*, arg1 */ ) {
    if ( typeof arg0 == 'string' ) {
      // method call $().plugin( 'methodName', { options } )
      // shift arguments by 1
      var args = arraySlice.call( arguments, 1 );
      return methodCall( this, arg0, args );
    }
    // just $().plugin({ options })
    plainCall( this, arg0 );
    return this;
  };

  // $().plugin('methodName')
  function methodCall( $elems, methodName, args ) {
    var returnValue;
    var pluginMethodStr = '$().' + namespace + '("' + methodName + '")';

    $elems.each( function( i, elem ) {
      // get instance
      var instance = $.data( elem, namespace );
      if ( !instance ) {
        logError( namespace + ' not initialized. Cannot call methods, i.e. ' +
          pluginMethodStr );
        return;
      }

      var method = instance[ methodName ];
      if ( !method || methodName.charAt(0) == '_' ) {
        logError( pluginMethodStr + ' is not a valid method' );
        return;
      }

      // apply method, get return value
      var value = method.apply( instance, args );
      // set return value if value is returned, use only first value
      returnValue = returnValue === undefined ? value : returnValue;
    });

    return returnValue !== undefined ? returnValue : $elems;
  }

  function plainCall( $elems, options ) {
    $elems.each( function( i, elem ) {
      var instance = $.data( elem, namespace );
      if ( instance ) {
        // set options & init
        instance.option( options );
        instance._init();
      } else {
        // initialize new instance
        instance = new PluginClass( elem, options );
        $.data( elem, namespace, instance );
      }
    });
  }

  updateJQuery( $ );

}

// ----- updateJQuery ----- //

// set $.bridget for v1 backwards compatibility
function updateJQuery( $ ) {
  if ( !$ || ( $ && $.bridget ) ) {
    return;
  }
  $.bridget = jQueryBridget;
}

updateJQuery( jQuery || window.jQuery );

// -----  ----- //

return jQueryBridget;

}));

/**
 * EvEmitter v1.1.0
 * Lil' event emitter
 * MIT License
 */

/* jshint unused: true, undef: true, strict: true */

( function( global, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, window */
  if ( typeof define == 'function' && define.amd ) {
    // AMD - RequireJS
    define( 'ev-emitter/ev-emitter',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS - Browserify, Webpack
    module.exports = factory();
  } else {
    // Browser globals
    global.EvEmitter = factory();
  }

}( typeof window != 'undefined' ? window : this, function() {



function EvEmitter() {}

var proto = EvEmitter.prototype;

proto.on = function( eventName, listener ) {
  if ( !eventName || !listener ) {
    return;
  }
  // set events hash
  var events = this._events = this._events || {};
  // set listeners array
  var listeners = events[ eventName ] = events[ eventName ] || [];
  // only add once
  if ( listeners.indexOf( listener ) == -1 ) {
    listeners.push( listener );
  }

  return this;
};

proto.once = function( eventName, listener ) {
  if ( !eventName || !listener ) {
    return;
  }
  // add event
  this.on( eventName, listener );
  // set once flag
  // set onceEvents hash
  var onceEvents = this._onceEvents = this._onceEvents || {};
  // set onceListeners object
  var onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {};
  // set flag
  onceListeners[ listener ] = true;

  return this;
};

proto.off = function( eventName, listener ) {
  var listeners = this._events && this._events[ eventName ];
  if ( !listeners || !listeners.length ) {
    return;
  }
  var index = listeners.indexOf( listener );
  if ( index != -1 ) {
    listeners.splice( index, 1 );
  }

  return this;
};

proto.emitEvent = function( eventName, args ) {
  var listeners = this._events && this._events[ eventName ];
  if ( !listeners || !listeners.length ) {
    return;
  }
  // copy over to avoid interference if .off() in listener
  listeners = listeners.slice(0);
  args = args || [];
  // once stuff
  var onceListeners = this._onceEvents && this._onceEvents[ eventName ];

  for ( var i=0; i < listeners.length; i++ ) {
    var listener = listeners[i]
    var isOnce = onceListeners && onceListeners[ listener ];
    if ( isOnce ) {
      // remove listener
      // remove before trigger to prevent recursion
      this.off( eventName, listener );
      // unset once flag
      delete onceListeners[ listener ];
    }
    // trigger listener
    listener.apply( this, args );
  }

  return this;
};

proto.allOff = function() {
  delete this._events;
  delete this._onceEvents;
};

return EvEmitter;

}));

/*!
 * getSize v2.0.3
 * measure size of elements
 * MIT license
 */

/* jshint browser: true, strict: true, undef: true, unused: true */
/* globals console: false */

( function( window, factory ) {
  /* jshint strict: false */ /* globals define, module */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'get-size/get-size',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.getSize = factory();
  }

})( window, function factory() {
'use strict';

// -------------------------- helpers -------------------------- //

// get a number from a string, not a percentage
function getStyleSize( value ) {
  var num = parseFloat( value );
  // not a percent like '100%', and a number
  var isValid = value.indexOf('%') == -1 && !isNaN( num );
  return isValid && num;
}

function noop() {}

var logError = typeof console == 'undefined' ? noop :
  function( message ) {
    console.error( message );
  };

// -------------------------- measurements -------------------------- //

var measurements = [
  'paddingLeft',
  'paddingRight',
  'paddingTop',
  'paddingBottom',
  'marginLeft',
  'marginRight',
  'marginTop',
  'marginBottom',
  'borderLeftWidth',
  'borderRightWidth',
  'borderTopWidth',
  'borderBottomWidth'
];

var measurementsLength = measurements.length;

function getZeroSize() {
  var size = {
    width: 0,
    height: 0,
    innerWidth: 0,
    innerHeight: 0,
    outerWidth: 0,
    outerHeight: 0
  };
  for ( var i=0; i < measurementsLength; i++ ) {
    var measurement = measurements[i];
    size[ measurement ] = 0;
  }
  return size;
}

// -------------------------- getStyle -------------------------- //

/**
 * getStyle, get style of element, check for Firefox bug
 * https://bugzilla.mozilla.org/show_bug.cgi?id=548397
 */
function getStyle( elem ) {
  var style = getComputedStyle( elem );
  if ( !style ) {
    logError( 'Style returned ' + style +
      '. Are you running this code in a hidden iframe on Firefox? ' +
      'See https://bit.ly/getsizebug1' );
  }
  return style;
}

// -------------------------- setup -------------------------- //

var isSetup = false;

var isBoxSizeOuter;

/**
 * setup
 * check isBoxSizerOuter
 * do on first getSize() rather than on page load for Firefox bug
 */
function setup() {
  // setup once
  if ( isSetup ) {
    return;
  }
  isSetup = true;

  // -------------------------- box sizing -------------------------- //

  /**
   * Chrome & Safari measure the outer-width on style.width on border-box elems
   * IE11 & Firefox<29 measures the inner-width
   */
  var div = document.createElement('div');
  div.style.width = '200px';
  div.style.padding = '1px 2px 3px 4px';
  div.style.borderStyle = 'solid';
  div.style.borderWidth = '1px 2px 3px 4px';
  div.style.boxSizing = 'border-box';

  var body = document.body || document.documentElement;
  body.appendChild( div );
  var style = getStyle( div );
  // round value for browser zoom. desandro/masonry#928
  isBoxSizeOuter = Math.round( getStyleSize( style.width ) ) == 200;
  getSize.isBoxSizeOuter = isBoxSizeOuter;

  body.removeChild( div );
}

// -------------------------- getSize -------------------------- //

function getSize( elem ) {
  setup();

  // use querySeletor if elem is string
  if ( typeof elem == 'string' ) {
    elem = document.querySelector( elem );
  }

  // do not proceed on non-objects
  if ( !elem || typeof elem != 'object' || !elem.nodeType ) {
    return;
  }

  var style = getStyle( elem );

  // if hidden, everything is 0
  if ( style.display == 'none' ) {
    return getZeroSize();
  }

  var size = {};
  size.width = elem.offsetWidth;
  size.height = elem.offsetHeight;

  var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box';

  // get all measurements
  for ( var i=0; i < measurementsLength; i++ ) {
    var measurement = measurements[i];
    var value = style[ measurement ];
    var num = parseFloat( value );
    // any 'auto', 'medium' value will be 0
    size[ measurement ] = !isNaN( num ) ? num : 0;
  }

  var paddingWidth = size.paddingLeft + size.paddingRight;
  var paddingHeight = size.paddingTop + size.paddingBottom;
  var marginWidth = size.marginLeft + size.marginRight;
  var marginHeight = size.marginTop + size.marginBottom;
  var borderWidth = size.borderLeftWidth + size.borderRightWidth;
  var borderHeight = size.borderTopWidth + size.borderBottomWidth;

  var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;

  // overwrite width and height if we can get it from style
  var styleWidth = getStyleSize( style.width );
  if ( styleWidth !== false ) {
    size.width = styleWidth +
      // add padding and border unless it's already including it
      ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
  }

  var styleHeight = getStyleSize( style.height );
  if ( styleHeight !== false ) {
    size.height = styleHeight +
      // add padding and border unless it's already including it
      ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
  }

  size.innerWidth = size.width - ( paddingWidth + borderWidth );
  size.innerHeight = size.height - ( paddingHeight + borderHeight );

  size.outerWidth = size.width + marginWidth;
  size.outerHeight = size.height + marginHeight;

  return size;
}

return getSize;

});

/**
 * matchesSelector v2.0.2
 * matchesSelector( element, '.selector' )
 * MIT license
 */

/*jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  /*global define: false, module: false */
  'use strict';
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'desandro-matches-selector/matches-selector',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.matchesSelector = factory();
  }

}( window, function factory() {
  'use strict';

  var matchesMethod = ( function() {
    var ElemProto = window.Element.prototype;
    // check for the standard method name first
    if ( ElemProto.matches ) {
      return 'matches';
    }
    // check un-prefixed
    if ( ElemProto.matchesSelector ) {
      return 'matchesSelector';
    }
    // check vendor prefixes
    var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];

    for ( var i=0; i < prefixes.length; i++ ) {
      var prefix = prefixes[i];
      var method = prefix + 'MatchesSelector';
      if ( ElemProto[ method ] ) {
        return method;
      }
    }
  })();

  return function matchesSelector( elem, selector ) {
    return elem[ matchesMethod ]( selector );
  };

}));

/**
 * Fizzy UI utils v2.0.7
 * MIT license
 */

/*jshint browser: true, undef: true, unused: true, strict: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /*globals define, module, require */

  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'fizzy-ui-utils/utils',[
      'desandro-matches-selector/matches-selector'
    ], function( matchesSelector ) {
      return factory( window, matchesSelector );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('desandro-matches-selector')
    );
  } else {
    // browser global
    window.fizzyUIUtils = factory(
      window,
      window.matchesSelector
    );
  }

}( window, function factory( window, matchesSelector ) {



var utils = {};

// ----- extend ----- //

// extends objects
utils.extend = function( a, b ) {
  for ( var prop in b ) {
    a[ prop ] = b[ prop ];
  }
  return a;
};

// ----- modulo ----- //

utils.modulo = function( num, div ) {
  return ( ( num % div ) + div ) % div;
};

// ----- makeArray ----- //

var arraySlice = Array.prototype.slice;

// turn element or nodeList into an array
utils.makeArray = function( obj ) {
  if ( Array.isArray( obj ) ) {
    // use object if already an array
    return obj;
  }
  // return empty array if undefined or null. #6
  if ( obj === null || obj === undefined ) {
    return [];
  }

  var isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';
  if ( isArrayLike ) {
    // convert nodeList to array
    return arraySlice.call( obj );
  }

  // array of single index
  return [ obj ];
};

// ----- removeFrom ----- //

utils.removeFrom = function( ary, obj ) {
  var index = ary.indexOf( obj );
  if ( index != -1 ) {
    ary.splice( index, 1 );
  }
};

// ----- getParent ----- //

utils.getParent = function( elem, selector ) {
  while ( elem.parentNode && elem != document.body ) {
    elem = elem.parentNode;
    if ( matchesSelector( elem, selector ) ) {
      return elem;
    }
  }
};

// ----- getQueryElement ----- //

// use element as selector string
utils.getQueryElement = function( elem ) {
  if ( typeof elem == 'string' ) {
    return document.querySelector( elem );
  }
  return elem;
};

// ----- handleEvent ----- //

// enable .ontype to trigger from .addEventListener( elem, 'type' )
utils.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

// ----- filterFindElements ----- //

utils.filterFindElements = function( elems, selector ) {
  // make array of elems
  elems = utils.makeArray( elems );
  var ffElems = [];

  elems.forEach( function( elem ) {
    // check that elem is an actual element
    if ( !( elem instanceof HTMLElement ) ) {
      return;
    }
    // add elem if no selector
    if ( !selector ) {
      ffElems.push( elem );
      return;
    }
    // filter & find items if we have a selector
    // filter
    if ( matchesSelector( elem, selector ) ) {
      ffElems.push( elem );
    }
    // find children
    var childElems = elem.querySelectorAll( selector );
    // concat childElems to filterFound array
    for ( var i=0; i < childElems.length; i++ ) {
      ffElems.push( childElems[i] );
    }
  });

  return ffElems;
};

// ----- debounceMethod ----- //

utils.debounceMethod = function( _class, methodName, threshold ) {
  threshold = threshold || 100;
  // original method
  var method = _class.prototype[ methodName ];
  var timeoutName = methodName + 'Timeout';

  _class.prototype[ methodName ] = function() {
    var timeout = this[ timeoutName ];
    clearTimeout( timeout );

    var args = arguments;
    var _this = this;
    this[ timeoutName ] = setTimeout( function() {
      method.apply( _this, args );
      delete _this[ timeoutName ];
    }, threshold );
  };
};

// ----- docReady ----- //

utils.docReady = function( callback ) {
  var readyState = document.readyState;
  if ( readyState == 'complete' || readyState == 'interactive' ) {
    // do async to allow for other scripts to run. metafizzy/flickity#441
    setTimeout( callback );
  } else {
    document.addEventListener( 'DOMContentLoaded', callback );
  }
};

// ----- htmlInit ----- //

// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
utils.toDashed = function( str ) {
  return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {
    return $1 + '-' + $2;
  }).toLowerCase();
};

var console = window.console;
/**
 * allow user to initialize classes via [data-namespace] or .js-namespace class
 * htmlInit( Widget, 'widgetName' )
 * options are parsed from data-namespace-options
 */
utils.htmlInit = function( WidgetClass, namespace ) {
  utils.docReady( function() {
    var dashedNamespace = utils.toDashed( namespace );
    var dataAttr = 'data-' + dashedNamespace;
    var dataAttrElems = document.querySelectorAll( '[' + dataAttr + ']' );
    var jsDashElems = document.querySelectorAll( '.js-' + dashedNamespace );
    var elems = utils.makeArray( dataAttrElems )
      .concat( utils.makeArray( jsDashElems ) );
    var dataOptionsAttr = dataAttr + '-options';
    var jQuery = window.jQuery;

    elems.forEach( function( elem ) {
      var attr = elem.getAttribute( dataAttr ) ||
        elem.getAttribute( dataOptionsAttr );
      var options;
      try {
        options = attr && JSON.parse( attr );
      } catch ( error ) {
        // log error, do not initialize
        if ( console ) {
          console.error( 'Error parsing ' + dataAttr + ' on ' + elem.className +
          ': ' + error );
        }
        return;
      }
      // initialize
      var instance = new WidgetClass( elem, options );
      // make available via $().data('namespace')
      if ( jQuery ) {
        jQuery.data( elem, namespace, instance );
      }
    });

  });
};

// -----  ----- //

return utils;

}));

/**
 * Outlayer Item
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD - RequireJS
    define( 'outlayer/item',[
        'ev-emitter/ev-emitter',
        'get-size/get-size'
      ],
      factory
    );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS - Browserify, Webpack
    module.exports = factory(
      require('ev-emitter'),
      require('get-size')
    );
  } else {
    // browser global
    window.Outlayer = {};
    window.Outlayer.Item = factory(
      window.EvEmitter,
      window.getSize
    );
  }

}( window, function factory( EvEmitter, getSize ) {
'use strict';

// ----- helpers ----- //

function isEmptyObj( obj ) {
  for ( var prop in obj ) {
    return false;
  }
  prop = null;
  return true;
}

// -------------------------- CSS3 support -------------------------- //


var docElemStyle = document.documentElement.style;

var transitionProperty = typeof docElemStyle.transition == 'string' ?
  'transition' : 'WebkitTransition';
var transformProperty = typeof docElemStyle.transform == 'string' ?
  'transform' : 'WebkitTransform';

var transitionEndEvent = {
  WebkitTransition: 'webkitTransitionEnd',
  transition: 'transitionend'
}[ transitionProperty ];

// cache all vendor properties that could have vendor prefix
var vendorProperties = {
  transform: transformProperty,
  transition: transitionProperty,
  transitionDuration: transitionProperty + 'Duration',
  transitionProperty: transitionProperty + 'Property',
  transitionDelay: transitionProperty + 'Delay'
};

// -------------------------- Item -------------------------- //

function Item( element, layout ) {
  if ( !element ) {
    return;
  }

  this.element = element;
  // parent layout class, i.e. Masonry, Isotope, or Packery
  this.layout = layout;
  this.position = {
    x: 0,
    y: 0
  };

  this._create();
}

// inherit EvEmitter
var proto = Item.prototype = Object.create( EvEmitter.prototype );
proto.constructor = Item;

proto._create = function() {
  // transition objects
  this._transn = {
    ingProperties: {},
    clean: {},
    onEnd: {}
  };

  this.css({
    position: 'absolute'
  });
};

// trigger specified handler for event type
proto.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

proto.getSize = function() {
  this.size = getSize( this.element );
};

/**
 * apply CSS styles to element
 * @param {Object} style
 */
proto.css = function( style ) {
  var elemStyle = this.element.style;

  for ( var prop in style ) {
    // use vendor property if available
    var supportedProp = vendorProperties[ prop ] || prop;
    elemStyle[ supportedProp ] = style[ prop ];
  }
};

 // measure position, and sets it
proto.getPosition = function() {
  var style = getComputedStyle( this.element );
  var isOriginLeft = this.layout._getOption('originLeft');
  var isOriginTop = this.layout._getOption('originTop');
  var xValue = style[ isOriginLeft ? 'left' : 'right' ];
  var yValue = style[ isOriginTop ? 'top' : 'bottom' ];
  var x = parseFloat( xValue );
  var y = parseFloat( yValue );
  // convert percent to pixels
  var layoutSize = this.layout.size;
  if ( xValue.indexOf('%') != -1 ) {
    x = ( x / 100 ) * layoutSize.width;
  }
  if ( yValue.indexOf('%') != -1 ) {
    y = ( y / 100 ) * layoutSize.height;
  }
  // clean up 'auto' or other non-integer values
  x = isNaN( x ) ? 0 : x;
  y = isNaN( y ) ? 0 : y;
  // remove padding from measurement
  x -= isOriginLeft ? layoutSize.paddingLeft : layoutSize.paddingRight;
  y -= isOriginTop ? layoutSize.paddingTop : layoutSize.paddingBottom;

  this.position.x = x;
  this.position.y = y;
};

// set settled position, apply padding
proto.layoutPosition = function() {
  var layoutSize = this.layout.size;
  var style = {};
  var isOriginLeft = this.layout._getOption('originLeft');
  var isOriginTop = this.layout._getOption('originTop');

  // x
  var xPadding = isOriginLeft ? 'paddingLeft' : 'paddingRight';
  var xProperty = isOriginLeft ? 'left' : 'right';
  var xResetProperty = isOriginLeft ? 'right' : 'left';

  var x = this.position.x + layoutSize[ xPadding ];
  // set in percentage or pixels
  style[ xProperty ] = this.getXValue( x );
  // reset other property
  style[ xResetProperty ] = '';

  // y
  var yPadding = isOriginTop ? 'paddingTop' : 'paddingBottom';
  var yProperty = isOriginTop ? 'top' : 'bottom';
  var yResetProperty = isOriginTop ? 'bottom' : 'top';

  var y = this.position.y + layoutSize[ yPadding ];
  // set in percentage or pixels
  style[ yProperty ] = this.getYValue( y );
  // reset other property
  style[ yResetProperty ] = '';

  this.css( style );
  this.emitEvent( 'layout', [ this ] );
};

proto.getXValue = function( x ) {
  var isHorizontal = this.layout._getOption('horizontal');
  return this.layout.options.percentPosition && !isHorizontal ?
    ( ( x / this.layout.size.width ) * 100 ) + '%' : x + 'px';
};

proto.getYValue = function( y ) {
  var isHorizontal = this.layout._getOption('horizontal');
  return this.layout.options.percentPosition && isHorizontal ?
    ( ( y / this.layout.size.height ) * 100 ) + '%' : y + 'px';
};

proto._transitionTo = function( x, y ) {
  this.getPosition();
  // get current x & y from top/left
  var curX = this.position.x;
  var curY = this.position.y;

  var didNotMove = x == this.position.x && y == this.position.y;

  // save end position
  this.setPosition( x, y );

  // if did not move and not transitioning, just go to layout
  if ( didNotMove && !this.isTransitioning ) {
    this.layoutPosition();
    return;
  }

  var transX = x - curX;
  var transY = y - curY;
  var transitionStyle = {};
  transitionStyle.transform = this.getTranslate( transX, transY );

  this.transition({
    to: transitionStyle,
    onTransitionEnd: {
      transform: this.layoutPosition
    },
    isCleaning: true
  });
};

proto.getTranslate = function( x, y ) {
  // flip cooridinates if origin on right or bottom
  var isOriginLeft = this.layout._getOption('originLeft');
  var isOriginTop = this.layout._getOption('originTop');
  x = isOriginLeft ? x : -x;
  y = isOriginTop ? y : -y;
  return 'translate3d(' + x + 'px, ' + y + 'px, 0)';
};

// non transition + transform support
proto.goTo = function( x, y ) {
  this.setPosition( x, y );
  this.layoutPosition();
};

proto.moveTo = proto._transitionTo;

proto.setPosition = function( x, y ) {
  this.position.x = parseFloat( x );
  this.position.y = parseFloat( y );
};

// ----- transition ----- //

/**
 * @param {Object} style - CSS
 * @param {Function} onTransitionEnd
 */

// non transition, just trigger callback
proto._nonTransition = function( args ) {
  this.css( args.to );
  if ( args.isCleaning ) {
    this._removeStyles( args.to );
  }
  for ( var prop in args.onTransitionEnd ) {
    args.onTransitionEnd[ prop ].call( this );
  }
};

/**
 * proper transition
 * @param {Object} args - arguments
 *   @param {Object} to - style to transition to
 *   @param {Object} from - style to start transition from
 *   @param {Boolean} isCleaning - removes transition styles after transition
 *   @param {Function} onTransitionEnd - callback
 */
proto.transition = function( args ) {
  // redirect to nonTransition if no transition duration
  if ( !parseFloat( this.layout.options.transitionDuration ) ) {
    this._nonTransition( args );
    return;
  }

  var _transition = this._transn;
  // keep track of onTransitionEnd callback by css property
  for ( var prop in args.onTransitionEnd ) {
    _transition.onEnd[ prop ] = args.onTransitionEnd[ prop ];
  }
  // keep track of properties that are transitioning
  for ( prop in args.to ) {
    _transition.ingProperties[ prop ] = true;
    // keep track of properties to clean up when transition is done
    if ( args.isCleaning ) {
      _transition.clean[ prop ] = true;
    }
  }

  // set from styles
  if ( args.from ) {
    this.css( args.from );
    // force redraw. http://blog.alexmaccaw.com/css-transitions
    var h = this.element.offsetHeight;
    // hack for JSHint to hush about unused var
    h = null;
  }
  // enable transition
  this.enableTransition( args.to );
  // set styles that are transitioning
  this.css( args.to );

  this.isTransitioning = true;

};

// dash before all cap letters, including first for
// WebkitTransform => -webkit-transform
function toDashedAll( str ) {
  return str.replace( /([A-Z])/g, function( $1 ) {
    return '-' + $1.toLowerCase();
  });
}

var transitionProps = 'opacity,' + toDashedAll( transformProperty );

proto.enableTransition = function(/* style */) {
  // HACK changing transitionProperty during a transition
  // will cause transition to jump
  if ( this.isTransitioning ) {
    return;
  }

  // make `transition: foo, bar, baz` from style object
  // HACK un-comment this when enableTransition can work
  // while a transition is happening
  // var transitionValues = [];
  // for ( var prop in style ) {
  //   // dash-ify camelCased properties like WebkitTransition
  //   prop = vendorProperties[ prop ] || prop;
  //   transitionValues.push( toDashedAll( prop ) );
  // }
  // munge number to millisecond, to match stagger
  var duration = this.layout.options.transitionDuration;
  duration = typeof duration == 'number' ? duration + 'ms' : duration;
  // enable transition styles
  this.css({
    transitionProperty: transitionProps,
    transitionDuration: duration,
    transitionDelay: this.staggerDelay || 0
  });
  // listen for transition end event
  this.element.addEventListener( transitionEndEvent, this, false );
};

// ----- events ----- //

proto.onwebkitTransitionEnd = function( event ) {
  this.ontransitionend( event );
};

proto.onotransitionend = function( event ) {
  this.ontransitionend( event );
};

// properties that I munge to make my life easier
var dashedVendorProperties = {
  '-webkit-transform': 'transform'
};

proto.ontransitionend = function( event ) {
  // disregard bubbled events from children
  if ( event.target !== this.element ) {
    return;
  }
  var _transition = this._transn;
  // get property name of transitioned property, convert to prefix-free
  var propertyName = dashedVendorProperties[ event.propertyName ] || event.propertyName;

  // remove property that has completed transitioning
  delete _transition.ingProperties[ propertyName ];
  // check if any properties are still transitioning
  if ( isEmptyObj( _transition.ingProperties ) ) {
    // all properties have completed transitioning
    this.disableTransition();
  }
  // clean style
  if ( propertyName in _transition.clean ) {
    // clean up style
    this.element.style[ event.propertyName ] = '';
    delete _transition.clean[ propertyName ];
  }
  // trigger onTransitionEnd callback
  if ( propertyName in _transition.onEnd ) {
    var onTransitionEnd = _transition.onEnd[ propertyName ];
    onTransitionEnd.call( this );
    delete _transition.onEnd[ propertyName ];
  }

  this.emitEvent( 'transitionEnd', [ this ] );
};

proto.disableTransition = function() {
  this.removeTransitionStyles();
  this.element.removeEventListener( transitionEndEvent, this, false );
  this.isTransitioning = false;
};

/**
 * removes style property from element
 * @param {Object} style
**/
proto._removeStyles = function( style ) {
  // clean up transition styles
  var cleanStyle = {};
  for ( var prop in style ) {
    cleanStyle[ prop ] = '';
  }
  this.css( cleanStyle );
};

var cleanTransitionStyle = {
  transitionProperty: '',
  transitionDuration: '',
  transitionDelay: ''
};

proto.removeTransitionStyles = function() {
  // remove transition
  this.css( cleanTransitionStyle );
};

// ----- stagger ----- //

proto.stagger = function( delay ) {
  delay = isNaN( delay ) ? 0 : delay;
  this.staggerDelay = delay + 'ms';
};

// ----- show/hide/remove ----- //

// remove element from DOM
proto.removeElem = function() {
  this.element.parentNode.removeChild( this.element );
  // remove display: none
  this.css({ display: '' });
  this.emitEvent( 'remove', [ this ] );
};

proto.remove = function() {
  // just remove element if no transition support or no transition
  if ( !transitionProperty || !parseFloat( this.layout.options.transitionDuration ) ) {
    this.removeElem();
    return;
  }

  // start transition
  this.once( 'transitionEnd', function() {
    this.removeElem();
  });
  this.hide();
};

proto.reveal = function() {
  delete this.isHidden;
  // remove display: none
  this.css({ display: '' });

  var options = this.layout.options;

  var onTransitionEnd = {};
  var transitionEndProperty = this.getHideRevealTransitionEndProperty('visibleStyle');
  onTransitionEnd[ transitionEndProperty ] = this.onRevealTransitionEnd;

  this.transition({
    from: options.hiddenStyle,
    to: options.visibleStyle,
    isCleaning: true,
    onTransitionEnd: onTransitionEnd
  });
};

proto.onRevealTransitionEnd = function() {
  // check if still visible
  // during transition, item may have been hidden
  if ( !this.isHidden ) {
    this.emitEvent('reveal');
  }
};

/**
 * get style property use for hide/reveal transition end
 * @param {String} styleProperty - hiddenStyle/visibleStyle
 * @returns {String}
 */
proto.getHideRevealTransitionEndProperty = function( styleProperty ) {
  var optionStyle = this.layout.options[ styleProperty ];
  // use opacity
  if ( optionStyle.opacity ) {
    return 'opacity';
  }
  // get first property
  for ( var prop in optionStyle ) {
    return prop;
  }
};

proto.hide = function() {
  // set flag
  this.isHidden = true;
  // remove display: none
  this.css({ display: '' });

  var options = this.layout.options;

  var onTransitionEnd = {};
  var transitionEndProperty = this.getHideRevealTransitionEndProperty('hiddenStyle');
  onTransitionEnd[ transitionEndProperty ] = this.onHideTransitionEnd;

  this.transition({
    from: options.visibleStyle,
    to: options.hiddenStyle,
    // keep hidden stuff hidden
    isCleaning: true,
    onTransitionEnd: onTransitionEnd
  });
};

proto.onHideTransitionEnd = function() {
  // check if still hidden
  // during transition, item may have been un-hidden
  if ( this.isHidden ) {
    this.css({ display: 'none' });
    this.emitEvent('hide');
  }
};

proto.destroy = function() {
  this.css({
    position: '',
    left: '',
    right: '',
    top: '',
    bottom: '',
    transition: '',
    transform: ''
  });
};

return Item;

}));

/*!
 * Outlayer v2.1.1
 * the brains and guts of a layout library
 * MIT license
 */

( function( window, factory ) {
  'use strict';
  // universal module definition
  /* jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD - RequireJS
    define( 'outlayer/outlayer',[
        'ev-emitter/ev-emitter',
        'get-size/get-size',
        'fizzy-ui-utils/utils',
        './item'
      ],
      function( EvEmitter, getSize, utils, Item ) {
        return factory( window, EvEmitter, getSize, utils, Item);
      }
    );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS - Browserify, Webpack
    module.exports = factory(
      window,
      require('ev-emitter'),
      require('get-size'),
      require('fizzy-ui-utils'),
      require('./item')
    );
  } else {
    // browser global
    window.Outlayer = factory(
      window,
      window.EvEmitter,
      window.getSize,
      window.fizzyUIUtils,
      window.Outlayer.Item
    );
  }

}( window, function factory( window, EvEmitter, getSize, utils, Item ) {
'use strict';

// ----- vars ----- //

var console = window.console;
var jQuery = window.jQuery;
var noop = function() {};

// -------------------------- Outlayer -------------------------- //

// globally unique identifiers
var GUID = 0;
// internal store of all Outlayer intances
var instances = {};


/**
 * @param {Element, String} element
 * @param {Object} options
 * @constructor
 */
function Outlayer( element, options ) {
  var queryElement = utils.getQueryElement( element );
  if ( !queryElement ) {
    if ( console ) {
      console.error( 'Bad element for ' + this.constructor.namespace +
        ': ' + ( queryElement || element ) );
    }
    return;
  }
  this.element = queryElement;
  // add jQuery
  if ( jQuery ) {
    this.$element = jQuery( this.element );
  }

  // options
  this.options = utils.extend( {}, this.constructor.defaults );
  this.option( options );

  // add id for Outlayer.getFromElement
  var id = ++GUID;
  this.element.outlayerGUID = id; // expando
  instances[ id ] = this; // associate via id

  // kick it off
  this._create();

  var isInitLayout = this._getOption('initLayout');
  if ( isInitLayout ) {
    this.layout();
  }
}

// settings are for internal use only
Outlayer.namespace = 'outlayer';
Outlayer.Item = Item;

// default options
Outlayer.defaults = {
  containerStyle: {
    position: 'relative'
  },
  initLayout: true,
  originLeft: true,
  originTop: true,
  resize: true,
  resizeContainer: true,
  // item options
  transitionDuration: '0.4s',
  hiddenStyle: {
    opacity: 0,
    transform: 'scale(0.001)'
  },
  visibleStyle: {
    opacity: 1,
    transform: 'scale(1)'
  }
};

var proto = Outlayer.prototype;
// inherit EvEmitter
utils.extend( proto, EvEmitter.prototype );

/**
 * set options
 * @param {Object} opts
 */
proto.option = function( opts ) {
  utils.extend( this.options, opts );
};

/**
 * get backwards compatible option value, check old name
 */
proto._getOption = function( option ) {
  var oldOption = this.constructor.compatOptions[ option ];
  return oldOption && this.options[ oldOption ] !== undefined ?
    this.options[ oldOption ] : this.options[ option ];
};

Outlayer.compatOptions = {
  // currentName: oldName
  initLayout: 'isInitLayout',
  horizontal: 'isHorizontal',
  layoutInstant: 'isLayoutInstant',
  originLeft: 'isOriginLeft',
  originTop: 'isOriginTop',
  resize: 'isResizeBound',
  resizeContainer: 'isResizingContainer'
};

proto._create = function() {
  // get items from children
  this.reloadItems();
  // elements that affect layout, but are not laid out
  this.stamps = [];
  this.stamp( this.options.stamp );
  // set container style
  utils.extend( this.element.style, this.options.containerStyle );

  // bind resize method
  var canBindResize = this._getOption('resize');
  if ( canBindResize ) {
    this.bindResize();
  }
};

// goes through all children again and gets bricks in proper order
proto.reloadItems = function() {
  // collection of item elements
  this.items = this._itemize( this.element.children );
};


/**
 * turn elements into Outlayer.Items to be used in layout
 * @param {Array or NodeList or HTMLElement} elems
 * @returns {Array} items - collection of new Outlayer Items
 */
proto._itemize = function( elems ) {

  var itemElems = this._filterFindItemElements( elems );
  var Item = this.constructor.Item;

  // create new Outlayer Items for collection
  var items = [];
  for ( var i=0; i < itemElems.length; i++ ) {
    var elem = itemElems[i];
    var item = new Item( elem, this );
    items.push( item );
  }

  return items;
};

/**
 * get item elements to be used in layout
 * @param {Array or NodeList or HTMLElement} elems
 * @returns {Array} items - item elements
 */
proto._filterFindItemElements = function( elems ) {
  return utils.filterFindElements( elems, this.options.itemSelector );
};

/**
 * getter method for getting item elements
 * @returns {Array} elems - collection of item elements
 */
proto.getItemElements = function() {
  return this.items.map( function( item ) {
    return item.element;
  });
};

// ----- init & layout ----- //

/**
 * lays out all items
 */
proto.layout = function() {
  this._resetLayout();
  this._manageStamps();

  // don't animate first layout
  var layoutInstant = this._getOption('layoutInstant');
  var isInstant = layoutInstant !== undefined ?
    layoutInstant : !this._isLayoutInited;
  this.layoutItems( this.items, isInstant );

  // flag for initalized
  this._isLayoutInited = true;
};

// _init is alias for layout
proto._init = proto.layout;

/**
 * logic before any new layout
 */
proto._resetLayout = function() {
  this.getSize();
};


proto.getSize = function() {
  this.size = getSize( this.element );
};

/**
 * get measurement from option, for columnWidth, rowHeight, gutter
 * if option is String -> get element from selector string, & get size of element
 * if option is Element -> get size of element
 * else use option as a number
 *
 * @param {String} measurement
 * @param {String} size - width or height
 * @private
 */
proto._getMeasurement = function( measurement, size ) {
  var option = this.options[ measurement ];
  var elem;
  if ( !option ) {
    // default to 0
    this[ measurement ] = 0;
  } else {
    // use option as an element
    if ( typeof option == 'string' ) {
      elem = this.element.querySelector( option );
    } else if ( option instanceof HTMLElement ) {
      elem = option;
    }
    // use size of element, if element
    this[ measurement ] = elem ? getSize( elem )[ size ] : option;
  }
};

/**
 * layout a collection of item elements
 * @api public
 */
proto.layoutItems = function( items, isInstant ) {
  items = this._getItemsForLayout( items );

  this._layoutItems( items, isInstant );

  this._postLayout();
};

/**
 * get the items to be laid out
 * you may want to skip over some items
 * @param {Array} items
 * @returns {Array} items
 */
proto._getItemsForLayout = function( items ) {
  return items.filter( function( item ) {
    return !item.isIgnored;
  });
};

/**
 * layout items
 * @param {Array} items
 * @param {Boolean} isInstant
 */
proto._layoutItems = function( items, isInstant ) {
  this._emitCompleteOnItems( 'layout', items );

  if ( !items || !items.length ) {
    // no items, emit event with empty array
    return;
  }

  var queue = [];

  items.forEach( function( item ) {
    // get x/y object from method
    var position = this._getItemLayoutPosition( item );
    // enqueue
    position.item = item;
    position.isInstant = isInstant || item.isLayoutInstant;
    queue.push( position );
  }, this );

  this._processLayoutQueue( queue );
};

/**
 * get item layout position
 * @param {Outlayer.Item} item
 * @returns {Object} x and y position
 */
proto._getItemLayoutPosition = function( /* item */ ) {
  return {
    x: 0,
    y: 0
  };
};

/**
 * iterate over array and position each item
 * Reason being - separating this logic prevents 'layout invalidation'
 * thx @paul_irish
 * @param {Array} queue
 */
proto._processLayoutQueue = function( queue ) {
  this.updateStagger();
  queue.forEach( function( obj, i ) {
    this._positionItem( obj.item, obj.x, obj.y, obj.isInstant, i );
  }, this );
};

// set stagger from option in milliseconds number
proto.updateStagger = function() {
  var stagger = this.options.stagger;
  if ( stagger === null || stagger === undefined ) {
    this.stagger = 0;
    return;
  }
  this.stagger = getMilliseconds( stagger );
  return this.stagger;
};

/**
 * Sets position of item in DOM
 * @param {Outlayer.Item} item
 * @param {Number} x - horizontal position
 * @param {Number} y - vertical position
 * @param {Boolean} isInstant - disables transitions
 */
proto._positionItem = function( item, x, y, isInstant, i ) {
  if ( isInstant ) {
    // if not transition, just set CSS
    item.goTo( x, y );
  } else {
    item.stagger( i * this.stagger );
    item.moveTo( x, y );
  }
};

/**
 * Any logic you want to do after each layout,
 * i.e. size the container
 */
proto._postLayout = function() {
  this.resizeContainer();
};

proto.resizeContainer = function() {
  var isResizingContainer = this._getOption('resizeContainer');
  if ( !isResizingContainer ) {
    return;
  }
  var size = this._getContainerSize();
  if ( size ) {
    this._setContainerMeasure( size.width, true );
    this._setContainerMeasure( size.height, false );
  }
};

/**
 * Sets width or height of container if returned
 * @returns {Object} size
 *   @param {Number} width
 *   @param {Number} height
 */
proto._getContainerSize = noop;

/**
 * @param {Number} measure - size of width or height
 * @param {Boolean} isWidth
 */
proto._setContainerMeasure = function( measure, isWidth ) {
  if ( measure === undefined ) {
    return;
  }

  var elemSize = this.size;
  // add padding and border width if border box
  if ( elemSize.isBorderBox ) {
    measure += isWidth ? elemSize.paddingLeft + elemSize.paddingRight +
      elemSize.borderLeftWidth + elemSize.borderRightWidth :
      elemSize.paddingBottom + elemSize.paddingTop +
      elemSize.borderTopWidth + elemSize.borderBottomWidth;
  }

  measure = Math.max( measure, 0 );
  this.element.style[ isWidth ? 'width' : 'height' ] = measure + 'px';
};

/**
 * emit eventComplete on a collection of items events
 * @param {String} eventName
 * @param {Array} items - Outlayer.Items
 */
proto._emitCompleteOnItems = function( eventName, items ) {
  var _this = this;
  function onComplete() {
    _this.dispatchEvent( eventName + 'Complete', null, [ items ] );
  }

  var count = items.length;
  if ( !items || !count ) {
    onComplete();
    return;
  }

  var doneCount = 0;
  function tick() {
    doneCount++;
    if ( doneCount == count ) {
      onComplete();
    }
  }

  // bind callback
  items.forEach( function( item ) {
    item.once( eventName, tick );
  });
};

/**
 * emits events via EvEmitter and jQuery events
 * @param {String} type - name of event
 * @param {Event} event - original event
 * @param {Array} args - extra arguments
 */
proto.dispatchEvent = function( type, event, args ) {
  // add original event to arguments
  var emitArgs = event ? [ event ].concat( args ) : args;
  this.emitEvent( type, emitArgs );

  if ( jQuery ) {
    // set this.$element
    this.$element = this.$element || jQuery( this.element );
    if ( event ) {
      // create jQuery event
      var $event = jQuery.Event( event );
      $event.type = type;
      this.$element.trigger( $event, args );
    } else {
      // just trigger with type if no event available
      this.$element.trigger( type, args );
    }
  }
};

// -------------------------- ignore & stamps -------------------------- //


/**
 * keep item in collection, but do not lay it out
 * ignored items do not get skipped in layout
 * @param {Element} elem
 */
proto.ignore = function( elem ) {
  var item = this.getItem( elem );
  if ( item ) {
    item.isIgnored = true;
  }
};

/**
 * return item to layout collection
 * @param {Element} elem
 */
proto.unignore = function( elem ) {
  var item = this.getItem( elem );
  if ( item ) {
    delete item.isIgnored;
  }
};

/**
 * adds elements to stamps
 * @param {NodeList, Array, Element, or String} elems
 */
proto.stamp = function( elems ) {
  elems = this._find( elems );
  if ( !elems ) {
    return;
  }

  this.stamps = this.stamps.concat( elems );
  // ignore
  elems.forEach( this.ignore, this );
};

/**
 * removes elements to stamps
 * @param {NodeList, Array, or Element} elems
 */
proto.unstamp = function( elems ) {
  elems = this._find( elems );
  if ( !elems ){
    return;
  }

  elems.forEach( function( elem ) {
    // filter out removed stamp elements
    utils.removeFrom( this.stamps, elem );
    this.unignore( elem );
  }, this );
};

/**
 * finds child elements
 * @param {NodeList, Array, Element, or String} elems
 * @returns {Array} elems
 */
proto._find = function( elems ) {
  if ( !elems ) {
    return;
  }
  // if string, use argument as selector string
  if ( typeof elems == 'string' ) {
    elems = this.element.querySelectorAll( elems );
  }
  elems = utils.makeArray( elems );
  return elems;
};

proto._manageStamps = function() {
  if ( !this.stamps || !this.stamps.length ) {
    return;
  }

  this._getBoundingRect();

  this.stamps.forEach( this._manageStamp, this );
};

// update boundingLeft / Top
proto._getBoundingRect = function() {
  // get bounding rect for container element
  var boundingRect = this.element.getBoundingClientRect();
  var size = this.size;
  this._boundingRect = {
    left: boundingRect.left + size.paddingLeft + size.borderLeftWidth,
    top: boundingRect.top + size.paddingTop + size.borderTopWidth,
    right: boundingRect.right - ( size.paddingRight + size.borderRightWidth ),
    bottom: boundingRect.bottom - ( size.paddingBottom + size.borderBottomWidth )
  };
};

/**
 * @param {Element} stamp
**/
proto._manageStamp = noop;

/**
 * get x/y position of element relative to container element
 * @param {Element} elem
 * @returns {Object} offset - has left, top, right, bottom
 */
proto._getElementOffset = function( elem ) {
  var boundingRect = elem.getBoundingClientRect();
  var thisRect = this._boundingRect;
  var size = getSize( elem );
  var offset = {
    left: boundingRect.left - thisRect.left - size.marginLeft,
    top: boundingRect.top - thisRect.top - size.marginTop,
    right: thisRect.right - boundingRect.right - size.marginRight,
    bottom: thisRect.bottom - boundingRect.bottom - size.marginBottom
  };
  return offset;
};

// -------------------------- resize -------------------------- //

// enable event handlers for listeners
// i.e. resize -> onresize
proto.handleEvent = utils.handleEvent;

/**
 * Bind layout to window resizing
 */
proto.bindResize = function() {
  window.addEventListener( 'resize', this );
  this.isResizeBound = true;
};

/**
 * Unbind layout to window resizing
 */
proto.unbindResize = function() {
  window.removeEventListener( 'resize', this );
  this.isResizeBound = false;
};

proto.onresize = function() {
  this.resize();
};

utils.debounceMethod( Outlayer, 'onresize', 100 );

proto.resize = function() {
  // don't trigger if size did not change
  // or if resize was unbound. See #9
  if ( !this.isResizeBound || !this.needsResizeLayout() ) {
    return;
  }

  this.layout();
};

/**
 * check if layout is needed post layout
 * @returns Boolean
 */
proto.needsResizeLayout = function() {
  var size = getSize( this.element );
  // check that this.size and size are there
  // IE8 triggers resize on body size change, so they might not be
  var hasSizes = this.size && size;
  return hasSizes && size.innerWidth !== this.size.innerWidth;
};

// -------------------------- methods -------------------------- //

/**
 * add items to Outlayer instance
 * @param {Array or NodeList or Element} elems
 * @returns {Array} items - Outlayer.Items
**/
proto.addItems = function( elems ) {
  var items = this._itemize( elems );
  // add items to collection
  if ( items.length ) {
    this.items = this.items.concat( items );
  }
  return items;
};

/**
 * Layout newly-appended item elements
 * @param {Array or NodeList or Element} elems
 */
proto.appended = function( elems ) {
  var items = this.addItems( elems );
  if ( !items.length ) {
    return;
  }
  // layout and reveal just the new items
  this.layoutItems( items, true );
  this.reveal( items );
};

/**
 * Layout prepended elements
 * @param {Array or NodeList or Element} elems
 */
proto.prepended = function( elems ) {
  var items = this._itemize( elems );
  if ( !items.length ) {
    return;
  }
  // add items to beginning of collection
  var previousItems = this.items.slice(0);
  this.items = items.concat( previousItems );
  // start new layout
  this._resetLayout();
  this._manageStamps();
  // layout new stuff without transition
  this.layoutItems( items, true );
  this.reveal( items );
  // layout previous items
  this.layoutItems( previousItems );
};

/**
 * reveal a collection of items
 * @param {Array of Outlayer.Items} items
 */
proto.reveal = function( items ) {
  this._emitCompleteOnItems( 'reveal', items );
  if ( !items || !items.length ) {
    return;
  }
  var stagger = this.updateStagger();
  items.forEach( function( item, i ) {
    item.stagger( i * stagger );
    item.reveal();
  });
};

/**
 * hide a collection of items
 * @param {Array of Outlayer.Items} items
 */
proto.hide = function( items ) {
  this._emitCompleteOnItems( 'hide', items );
  if ( !items || !items.length ) {
    return;
  }
  var stagger = this.updateStagger();
  items.forEach( function( item, i ) {
    item.stagger( i * stagger );
    item.hide();
  });
};

/**
 * reveal item elements
 * @param {Array}, {Element}, {NodeList} items
 */
proto.revealItemElements = function( elems ) {
  var items = this.getItems( elems );
  this.reveal( items );
};

/**
 * hide item elements
 * @param {Array}, {Element}, {NodeList} items
 */
proto.hideItemElements = function( elems ) {
  var items = this.getItems( elems );
  this.hide( items );
};

/**
 * get Outlayer.Item, given an Element
 * @param {Element} elem
 * @param {Function} callback
 * @returns {Outlayer.Item} item
 */
proto.getItem = function( elem ) {
  // loop through items to get the one that matches
  for ( var i=0; i < this.items.length; i++ ) {
    var item = this.items[i];
    if ( item.element == elem ) {
      // return item
      return item;
    }
  }
};

/**
 * get collection of Outlayer.Items, given Elements
 * @param {Array} elems
 * @returns {Array} items - Outlayer.Items
 */
proto.getItems = function( elems ) {
  elems = utils.makeArray( elems );
  var items = [];
  elems.forEach( function( elem ) {
    var item = this.getItem( elem );
    if ( item ) {
      items.push( item );
    }
  }, this );

  return items;
};

/**
 * remove element(s) from instance and DOM
 * @param {Array or NodeList or Element} elems
 */
proto.remove = function( elems ) {
  var removeItems = this.getItems( elems );

  this._emitCompleteOnItems( 'remove', removeItems );

  // bail if no items to remove
  if ( !removeItems || !removeItems.length ) {
    return;
  }

  removeItems.forEach( function( item ) {
    item.remove();
    // remove item from collection
    utils.removeFrom( this.items, item );
  }, this );
};

// ----- destroy ----- //

// remove and disable Outlayer instance
proto.destroy = function() {
  // clean up dynamic styles
  var style = this.element.style;
  style.height = '';
  style.position = '';
  style.width = '';
  // destroy items
  this.items.forEach( function( item ) {
    item.destroy();
  });

  this.unbindResize();

  var id = this.element.outlayerGUID;
  delete instances[ id ]; // remove reference to instance by id
  delete this.element.outlayerGUID;
  // remove data for jQuery
  if ( jQuery ) {
    jQuery.removeData( this.element, this.constructor.namespace );
  }

};

// -------------------------- data -------------------------- //

/**
 * get Outlayer instance from element
 * @param {Element} elem
 * @returns {Outlayer}
 */
Outlayer.data = function( elem ) {
  elem = utils.getQueryElement( elem );
  var id = elem && elem.outlayerGUID;
  return id && instances[ id ];
};


// -------------------------- create Outlayer class -------------------------- //

/**
 * create a layout class
 * @param {String} namespace
 */
Outlayer.create = function( namespace, options ) {
  // sub-class Outlayer
  var Layout = subclass( Outlayer );
  // apply new options and compatOptions
  Layout.defaults = utils.extend( {}, Outlayer.defaults );
  utils.extend( Layout.defaults, options );
  Layout.compatOptions = utils.extend( {}, Outlayer.compatOptions  );

  Layout.namespace = namespace;

  Layout.data = Outlayer.data;

  // sub-class Item
  Layout.Item = subclass( Item );

  // -------------------------- declarative -------------------------- //

  utils.htmlInit( Layout, namespace );

  // -------------------------- jQuery bridge -------------------------- //

  // make into jQuery plugin
  if ( jQuery && jQuery.bridget ) {
    jQuery.bridget( namespace, Layout );
  }

  return Layout;
};

function subclass( Parent ) {
  function SubClass() {
    Parent.apply( this, arguments );
  }

  SubClass.prototype = Object.create( Parent.prototype );
  SubClass.prototype.constructor = SubClass;

  return SubClass;
}

// ----- helpers ----- //

// how many milliseconds are in each unit
var msUnits = {
  ms: 1,
  s: 1000
};

// munge time-like parameter into millisecond number
// '0.4s' -> 40
function getMilliseconds( time ) {
  if ( typeof time == 'number' ) {
    return time;
  }
  var matches = time.match( /(^\d*\.?\d*)(\w*)/ );
  var num = matches && matches[1];
  var unit = matches && matches[2];
  if ( !num.length ) {
    return 0;
  }
  num = parseFloat( num );
  var mult = msUnits[ unit ] || 1;
  return num * mult;
}

// ----- fin ----- //

// back in global
Outlayer.Item = Item;

return Outlayer;

}));

/*!
 * Masonry v4.2.2
 * Cascading grid layout library
 * https://masonry.desandro.com
 * MIT License
 * by David DeSandro
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( [
        'outlayer/outlayer',
        'get-size/get-size'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('outlayer'),
      require('get-size')
    );
  } else {
    // browser global
    window.Masonry = factory(
      window.Outlayer,
      window.getSize
    );
  }

}( window, function factory( Outlayer, getSize ) {



// -------------------------- masonryDefinition -------------------------- //

  // create an Outlayer layout class
  var Masonry = Outlayer.create('masonry');
  // isFitWidth -> fitWidth
  Masonry.compatOptions.fitWidth = 'isFitWidth';

  var proto = Masonry.prototype;

  proto._resetLayout = function() {
    this.getSize();
    this._getMeasurement( 'columnWidth', 'outerWidth' );
    this._getMeasurement( 'gutter', 'outerWidth' );
    this.measureColumns();

    // reset column Y
    this.colYs = [];
    for ( var i=0; i < this.cols; i++ ) {
      this.colYs.push( 0 );
    }

    this.maxY = 0;
    this.horizontalColIndex = 0;
  };

  proto.measureColumns = function() {
    this.getContainerWidth();
    // if columnWidth is 0, default to outerWidth of first item
    if ( !this.columnWidth ) {
      var firstItem = this.items[0];
      var firstItemElem = firstItem && firstItem.element;
      // columnWidth fall back to item of first element
      this.columnWidth = firstItemElem && getSize( firstItemElem ).outerWidth ||
        // if first elem has no width, default to size of container
        this.containerWidth;
    }

    var columnWidth = this.columnWidth += this.gutter;

    // calculate columns
    var containerWidth = this.containerWidth + this.gutter;
    var cols = containerWidth / columnWidth;
    // fix rounding errors, typically with gutters
    var excess = columnWidth - containerWidth % columnWidth;
    // if overshoot is less than a pixel, round up, otherwise floor it
    var mathMethod = excess && excess < 1 ? 'round' : 'floor';
    cols = Math[ mathMethod ]( cols );
    this.cols = Math.max( cols, 1 );
  };

  proto.getContainerWidth = function() {
    // container is parent if fit width
    var isFitWidth = this._getOption('fitWidth');
    var container = isFitWidth ? this.element.parentNode : this.element;
    // check that this.size and size are there
    // IE8 triggers resize on body size change, so they might not be
    var size = getSize( container );
    this.containerWidth = size && size.innerWidth;
  };

  proto._getItemLayoutPosition = function( item ) {
    item.getSize();
    // how many columns does this brick span
    var remainder = item.size.outerWidth % this.columnWidth;
    var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil';
    // round if off by 1 pixel, otherwise use ceil
    var colSpan = Math[ mathMethod ]( item.size.outerWidth / this.columnWidth );
    colSpan = Math.min( colSpan, this.cols );
    // use horizontal or top column position
    var colPosMethod = this.options.horizontalOrder ?
      '_getHorizontalColPosition' : '_getTopColPosition';
    var colPosition = this[ colPosMethod ]( colSpan, item );
    // position the brick
    var position = {
      x: this.columnWidth * colPosition.col,
      y: colPosition.y
    };
    // apply setHeight to necessary columns
    var setHeight = colPosition.y + item.size.outerHeight;
    var setMax = colSpan + colPosition.col;
    for ( var i = colPosition.col; i < setMax; i++ ) {
      this.colYs[i] = setHeight;
    }

    return position;
  };

  proto._getTopColPosition = function( colSpan ) {
    var colGroup = this._getTopColGroup( colSpan );
    // get the minimum Y value from the columns
    var minimumY = Math.min.apply( Math, colGroup );

    return {
      col: colGroup.indexOf( minimumY ),
      y: minimumY,
    };
  };

  /**
   * @param {Number} colSpan - number of columns the element spans
   * @returns {Array} colGroup
   */
  proto._getTopColGroup = function( colSpan ) {
    if ( colSpan < 2 ) {
      // if brick spans only one column, use all the column Ys
      return this.colYs;
    }

    var colGroup = [];
    // how many different places could this brick fit horizontally
    var groupCount = this.cols + 1 - colSpan;
    // for each group potential horizontal position
    for ( var i = 0; i < groupCount; i++ ) {
      colGroup[i] = this._getColGroupY( i, colSpan );
    }
    return colGroup;
  };

  proto._getColGroupY = function( col, colSpan ) {
    if ( colSpan < 2 ) {
      return this.colYs[ col ];
    }
    // make an array of colY values for that one group
    var groupColYs = this.colYs.slice( col, col + colSpan );
    // and get the max value of the array
    return Math.max.apply( Math, groupColYs );
  };

  // get column position based on horizontal index. #873
  proto._getHorizontalColPosition = function( colSpan, item ) {
    var col = this.horizontalColIndex % this.cols;
    var isOver = colSpan > 1 && col + colSpan > this.cols;
    // shift to next row if item can't fit on current row
    col = isOver ? 0 : col;
    // don't let zero-size items take up space
    var hasSize = item.size.outerWidth && item.size.outerHeight;
    this.horizontalColIndex = hasSize ? col + colSpan : this.horizontalColIndex;

    return {
      col: col,
      y: this._getColGroupY( col, colSpan ),
    };
  };

  proto._manageStamp = function( stamp ) {
    var stampSize = getSize( stamp );
    var offset = this._getElementOffset( stamp );
    // get the columns that this stamp affects
    var isOriginLeft = this._getOption('originLeft');
    var firstX = isOriginLeft ? offset.left : offset.right;
    var lastX = firstX + stampSize.outerWidth;
    var firstCol = Math.floor( firstX / this.columnWidth );
    firstCol = Math.max( 0, firstCol );
    var lastCol = Math.floor( lastX / this.columnWidth );
    // lastCol should not go over if multiple of columnWidth #425
    lastCol -= lastX % this.columnWidth ? 0 : 1;
    lastCol = Math.min( this.cols - 1, lastCol );
    // set colYs to bottom of the stamp

    var isOriginTop = this._getOption('originTop');
    var stampMaxY = ( isOriginTop ? offset.top : offset.bottom ) +
      stampSize.outerHeight;
    for ( var i = firstCol; i <= lastCol; i++ ) {
      this.colYs[i] = Math.max( stampMaxY, this.colYs[i] );
    }
  };

  proto._getContainerSize = function() {
    this.maxY = Math.max.apply( Math, this.colYs );
    var size = {
      height: this.maxY
    };

    if ( this._getOption('fitWidth') ) {
      size.width = this._getContainerFitWidth();
    }

    return size;
  };

  proto._getContainerFitWidth = function() {
    var unusedCols = 0;
    // count unused columns
    var i = this.cols;
    while ( --i ) {
      if ( this.colYs[i] !== 0 ) {
        break;
      }
      unusedCols++;
    }
    // fit container to columns that have been used
    return ( this.cols - unusedCols ) * this.columnWidth - this.gutter;
  };

  proto.needsResizeLayout = function() {
    var previousWidth = this.containerWidth;
    this.getContainerWidth();
    return previousWidth != this.containerWidth;
  };

  return Masonry;

}));


/*
 Sticky-kit v1.1.2 | WTFPL | Leaf Corcoran 2015 | http://leafo.net
*/


(function () {

    var leftScroll = "0"
    if (Math.max(document.documentElement.clientWidth, window.innerWidth || 0) >= 2560) {
        leftScroll = "";
    } else {
        leftScroll = "initial";
    }
    var b, f;
    b = this.jQuery || window.jQuery;
    f = b(window);
    b.fn.stick_in_parent = function (d) {
        var A, w, J, n, B, K, p, q, k, E, t;
        null == d && (d = {});
        t = d.sticky_class;
        B = d.inner_scrolling;
        E = d.recalc_every;
        k = d.parent;
        q = d.offset_top;
        p = d.spacer;
        w = d.bottoming;
        null == q && (q = 0);
        null == k && (k = void 0);
        null == B && (B = !0);
        null == t && (t = "is_stuck");
        A = b(document);
        null == w && (w = !0);
        J = function (a, d, n, C, F, u, r, G) {
            var v, H, m, D, I, c, g, x, y, z, h, l;
            if (!a.data("sticky_kit")) {
                a.data("sticky_kit", !0);
                I = A.height();
                g = a.parent();
                null != k && (g = g.closest(k));
                if (!g.length) throw "failed to find stick parent";
                v = m = !1;
                (h = null != p ? p && a.closest(p) : b("<div />")) && h.css("position", a.css("position"));
                x = function () {
                    var c, f, e;
                    if (!G && (I = A.height(), c = parseInt(g.css("border-top-width"), 10), f = parseInt(g.css("padding-top"), 10), d = parseInt(g.css("padding-bottom"), 10), n = g.offset().top + c + f, C = g.height(), m && (v = m = !1, null == p && (a.insertAfter(h), h.detach()), a.css({
                        position: "",
                        top: "",
                        width: "",
                        left: "initial",
                        bottom: ""
                    }).removeClass(t), e = !0), F = a.offset().top - (parseInt(a.css("margin-top"), 10) || 0) - q,
                        u = a.outerHeight(!0), r = a.css("float"), h && h.css({
                            width: "",
                            height: u,
                            display: a.css("display"),
                            "vertical-align": a.css("vertical-align"),
                            "float": r
                        }), e)) return l()
                };
                x();
                if (u !== C) return D = void 0, c = q, z = E, l = function () {
                    var b, l, e, k;
                    if (!G && (e = !1, null != z && (--z, 0 >= z && (z = E, x(), e = !0)), e || A.height() === I || x(), e = f.scrollTop(), null != D && (l = e - D), D = e, m ? (w && (k = e + u + c > C + n, v && !k && (v = !1, a.removeClass("end").css({
                        position: "fixed",
                        bottom: "",
                        top: "0px",
                     
                    }).trigger("sticky_kit:unbottom").parent().removeClass("end"))), e < F && (m = !1, c = q, null == p && ("left" !== r && "right" !== r || a.insertAfter(h),
                        h.detach()), b = {
                            position: "",
                            width: "",
                            top: ""
                        }, a.css(b).removeClass(t).trigger("sticky_kit:unstick")), B && (b = f.height(), u + q > b && !v && (c -= l, c = Math.max(b - u, c), c = Math.min(q, c), m && a.css({
                            top: "50px",
                            left: leftScroll
                        })))) : e > F && (m = !0, b = {
                            position: "fixed",
                            top: "0"
                        }, b.width = "border-box" === a.css("box-sizing") ? a.outerWidth() + "px" : a.width() + "px", a.css(b).addClass(t), null == p && (a.after(h), "left" !== r && "right" !== r || h.append(a)), a.trigger("sticky_kit:stick")).removeClass("end"), m && w && (null == k && (k = e + u + c > C + n), !v && k))) return v = !0, "static" === g.css("position") && g.css({
                            position: "relative"
                        }),
                            a.addClass("end").css({
                                position: "absolute",
                                bottom: d,
                                top: "auto",
                                left: "initial"
                            }).trigger("sticky_kit:bottom").parent().addClass("end");
                }, y = function () {
                    x();
                    return l()
                }, H = function () {
                    G = !0;
                    f.off("touchmove", l);
                    f.off("scroll", l);
                    f.off("resize", y);
                    b(document.body).off("sticky_kit:recalc", y);
                    a.off("sticky_kit:detach", H);
                    a.removeData("sticky_kit");
                    a.css({
                        position: "",
                        bottom: "",
                        top: "",
                        width: "",
                        left: "initial"
                    });
                    g.position("position", "");
                    if (m) return null == p && ("left" !== r && "right" !== r || a.insertAfter(h), h.remove()), a.removeClass(t)
                }, f.on("touchmove", l), f.on("scroll", l), f.on("resize",
                    y), b(document.body).on("sticky_kit:recalc", y), a.on("sticky_kit:detach", H), setTimeout(l, 0)
            }
        };
        n = 0;
        for (K = this.length; n < K; n++) d = this[n], J(b(d));
        return this
    }



}).call(this);
/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright 2015 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});
/* perfect-scrollbar v0.6.7 */
!function t(e,n,r){function o(l,s){if(!n[l]){if(!e[l]){var a="function"==typeof require&&require;if(!s&&a)return a(l,!0);if(i)return i(l,!0);var c=new Error("Cannot find module '"+l+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[l]={exports:{}};e[l][0].call(u.exports,function(t){var n=e[l][1][t];return o(n?n:t)},u,u.exports,t,e,n,r)}return n[l].exports}for(var i="function"==typeof require&&require,l=0;l<r.length;l++)o(r[l]);return o}({1:[function(t,e,n){"use strict";function r(t){t.fn.perfectScrollbar=function(e){return this.each(function(){if("object"==typeof e||"undefined"==typeof e){var n=e;i.get(this)||o.initialize(this,n)}else{var r=e;"update"===r?o.update(this):"destroy"===r&&o.destroy(this)}return t(this)})}}var o=t("../main"),i=t("../plugin/instances");if("function"==typeof define&&define.amd)define(["jquery"],r);else{var l=window.jQuery?window.jQuery:window.$;"undefined"!=typeof l&&r(l)}e.exports=r},{"../main":7,"../plugin/instances":18}],2:[function(t,e,n){"use strict";function r(t,e){var n=t.className.split(" ");n.indexOf(e)<0&&n.push(e),t.className=n.join(" ")}function o(t,e){var n=t.className.split(" "),r=n.indexOf(e);r>=0&&n.splice(r,1),t.className=n.join(" ")}n.add=function(t,e){t.classList?t.classList.add(e):r(t,e)},n.remove=function(t,e){t.classList?t.classList.remove(e):o(t,e)},n.list=function(t){return t.classList?Array.prototype.slice.apply(t.classList):t.className.split(" ")}},{}],3:[function(t,e,n){"use strict";function r(t,e){return window.getComputedStyle(t)[e]}function o(t,e,n){return"number"==typeof n&&(n=n.toString()+"px"),t.style[e]=n,t}function i(t,e){for(var n in e){var r=e[n];"number"==typeof r&&(r=r.toString()+"px"),t.style[n]=r}return t}var l={};l.e=function(t,e){var n=document.createElement(t);return n.className=e,n},l.appendTo=function(t,e){return e.appendChild(t),t},l.css=function(t,e,n){return"object"==typeof e?i(t,e):"undefined"==typeof n?r(t,e):o(t,e,n)},l.matches=function(t,e){return"undefined"!=typeof t.matches?t.matches(e):"undefined"!=typeof t.matchesSelector?t.matchesSelector(e):"undefined"!=typeof t.webkitMatchesSelector?t.webkitMatchesSelector(e):"undefined"!=typeof t.mozMatchesSelector?t.mozMatchesSelector(e):"undefined"!=typeof t.msMatchesSelector?t.msMatchesSelector(e):void 0},l.remove=function(t){"undefined"!=typeof t.remove?t.remove():t.parentNode&&t.parentNode.removeChild(t)},l.queryChildren=function(t,e){return Array.prototype.filter.call(t.childNodes,function(t){return l.matches(t,e)})},e.exports=l},{}],4:[function(t,e,n){"use strict";var r=function(t){this.element=t,this.events={}};r.prototype.bind=function(t,e){"undefined"==typeof this.events[t]&&(this.events[t]=[]),this.events[t].push(e),this.element.addEventListener(t,e,!1)},r.prototype.unbind=function(t,e){var n="undefined"!=typeof e;this.events[t]=this.events[t].filter(function(r){return n&&r!==e?!0:(this.element.removeEventListener(t,r,!1),!1)},this)},r.prototype.unbindAll=function(){for(var t in this.events)this.unbind(t)};var o=function(){this.eventElements=[]};o.prototype.eventElement=function(t){var e=this.eventElements.filter(function(e){return e.element===t})[0];return"undefined"==typeof e&&(e=new r(t),this.eventElements.push(e)),e},o.prototype.bind=function(t,e,n){this.eventElement(t).bind(e,n)},o.prototype.unbind=function(t,e,n){this.eventElement(t).unbind(e,n)},o.prototype.unbindAll=function(){for(var t=0;t<this.eventElements.length;t++)this.eventElements[t].unbindAll()},o.prototype.once=function(t,e,n){var r=this.eventElement(t),o=function(t){r.unbind(e,o),n(t)};r.bind(e,o)},e.exports=o},{}],5:[function(t,e,n){"use strict";e.exports=function(){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return function(){return t()+t()+"-"+t()+"-"+t()+"-"+t()+"-"+t()+t()+t()}}()},{}],6:[function(t,e,n){"use strict";var r=t("./class"),o=t("./dom");n.toInt=function(t){return parseInt(t,10)||0},n.clone=function(t){if(null===t)return null;if("object"==typeof t){var e={};for(var n in t)e[n]=this.clone(t[n]);return e}return t},n.extend=function(t,e){var n=this.clone(t);for(var r in e)n[r]=this.clone(e[r]);return n},n.isEditable=function(t){return o.matches(t,"input,[contenteditable]")||o.matches(t,"select,[contenteditable]")||o.matches(t,"textarea,[contenteditable]")||o.matches(t,"button,[contenteditable]")},n.removePsClasses=function(t){for(var e=r.list(t),n=0;n<e.length;n++){var o=e[n];0===o.indexOf("ps-")&&r.remove(t,o)}},n.outerWidth=function(t){return this.toInt(o.css(t,"width"))+this.toInt(o.css(t,"paddingLeft"))+this.toInt(o.css(t,"paddingRight"))+this.toInt(o.css(t,"borderLeftWidth"))+this.toInt(o.css(t,"borderRightWidth"))},n.startScrolling=function(t,e){r.add(t,"ps-in-scrolling"),"undefined"!=typeof e?r.add(t,"ps-"+e):(r.add(t,"ps-x"),r.add(t,"ps-y"))},n.stopScrolling=function(t,e){r.remove(t,"ps-in-scrolling"),"undefined"!=typeof e?r.remove(t,"ps-"+e):(r.remove(t,"ps-x"),r.remove(t,"ps-y"))},n.env={isWebKit:"WebkitAppearance"in document.documentElement.style,supportsTouch:"ontouchstart"in window||window.DocumentTouch&&document instanceof window.DocumentTouch,supportsIePointer:null!==window.navigator.msMaxTouchPoints}},{"./class":2,"./dom":3}],7:[function(t,e,n){"use strict";var r=t("./plugin/destroy"),o=t("./plugin/initialize"),i=t("./plugin/update");e.exports={initialize:o,update:i,destroy:r}},{"./plugin/destroy":9,"./plugin/initialize":17,"./plugin/update":21}],8:[function(t,e,n){"use strict";e.exports={maxScrollbarLength:null,minScrollbarLength:null,scrollXMarginOffset:0,scrollYMarginOffset:0,stopPropagationOnClick:!0,suppressScrollX:!1,suppressScrollY:!1,swipePropagation:!0,useBothWheelAxes:!1,useKeyboard:!0,useSelectionScroll:!1,wheelPropagation:!1,wheelSpeed:1}},{}],9:[function(t,e,n){"use strict";var r=t("../lib/dom"),o=t("../lib/helper"),i=t("./instances");e.exports=function(t){var e=i.get(t);e&&(e.event.unbindAll(),r.remove(e.scrollbarX),r.remove(e.scrollbarY),r.remove(e.scrollbarXRail),r.remove(e.scrollbarYRail),o.removePsClasses(t),i.remove(t))}},{"../lib/dom":3,"../lib/helper":6,"./instances":18}],10:[function(t,e,n){"use strict";function r(t,e){function n(t){return t.getBoundingClientRect()}var r=window.Event.prototype.stopPropagation.bind;e.settings.stopPropagationOnClick&&e.event.bind(e.scrollbarY,"click",r),e.event.bind(e.scrollbarYRail,"click",function(r){var i=o.toInt(e.scrollbarYHeight/2),a=e.railYRatio*(r.pageY-window.scrollY-n(e.scrollbarYRail).top-i),c=e.railYRatio*(e.railYHeight-e.scrollbarYHeight),u=a/c;0>u?u=0:u>1&&(u=1),s(t,"top",(e.contentHeight-e.containerHeight)*u),l(t),r.stopPropagation()}),e.settings.stopPropagationOnClick&&e.event.bind(e.scrollbarX,"click",r),e.event.bind(e.scrollbarXRail,"click",function(r){var i=o.toInt(e.scrollbarXWidth/2),a=e.railXRatio*(r.pageX-window.scrollX-n(e.scrollbarXRail).left-i),c=e.railXRatio*(e.railXWidth-e.scrollbarXWidth),u=a/c;0>u?u=0:u>1&&(u=1),s(t,"left",(e.contentWidth-e.containerWidth)*u-e.negativeScrollAdjustment),l(t),r.stopPropagation()})}var o=t("../../lib/helper"),i=t("../instances"),l=t("../update-geometry"),s=t("../update-scroll");e.exports=function(t){var e=i.get(t);r(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19,"../update-scroll":20}],11:[function(t,e,n){"use strict";function r(t,e){function n(n){var o=r+n*e.railXRatio,i=e.scrollbarXRail.getBoundingClientRect().left+e.railXRatio*(e.railXWidth-e.scrollbarXWidth);0>o?e.scrollbarXLeft=0:o>i?e.scrollbarXLeft=i:e.scrollbarXLeft=o;var s=l.toInt(e.scrollbarXLeft*(e.contentWidth-e.containerWidth)/(e.containerWidth-e.railXRatio*e.scrollbarXWidth))-e.negativeScrollAdjustment;c(t,"left",s)}var r=null,o=null,s=function(e){n(e.pageX-o),a(t),e.stopPropagation(),e.preventDefault()},u=function(){l.stopScrolling(t,"x"),e.event.unbind(e.ownerDocument,"mousemove",s)};e.event.bind(e.scrollbarX,"mousedown",function(n){o=n.pageX,r=l.toInt(i.css(e.scrollbarX,"left"))*e.railXRatio,l.startScrolling(t,"x"),e.event.bind(e.ownerDocument,"mousemove",s),e.event.once(e.ownerDocument,"mouseup",u),n.stopPropagation(),n.preventDefault()})}function o(t,e){function n(n){var o=r+n*e.railYRatio,i=e.scrollbarYRail.getBoundingClientRect().top+e.railYRatio*(e.railYHeight-e.scrollbarYHeight);0>o?e.scrollbarYTop=0:o>i?e.scrollbarYTop=i:e.scrollbarYTop=o;var s=l.toInt(e.scrollbarYTop*(e.contentHeight-e.containerHeight)/(e.containerHeight-e.railYRatio*e.scrollbarYHeight));c(t,"top",s)}var r=null,o=null,s=function(e){n(e.pageY-o),a(t),e.stopPropagation(),e.preventDefault()},u=function(){l.stopScrolling(t,"y"),e.event.unbind(e.ownerDocument,"mousemove",s)};e.event.bind(e.scrollbarY,"mousedown",function(n){o=n.pageY,r=l.toInt(i.css(e.scrollbarY,"top"))*e.railYRatio,l.startScrolling(t,"y"),e.event.bind(e.ownerDocument,"mousemove",s),e.event.once(e.ownerDocument,"mouseup",u),n.stopPropagation(),n.preventDefault()})}var i=t("../../lib/dom"),l=t("../../lib/helper"),s=t("../instances"),a=t("../update-geometry"),c=t("../update-scroll");e.exports=function(t){var e=s.get(t);r(t,e),o(t,e)}},{"../../lib/dom":3,"../../lib/helper":6,"../instances":18,"../update-geometry":19,"../update-scroll":20}],12:[function(t,e,n){"use strict";function r(t,e){function n(n,r){var o=t.scrollTop;if(0===n){if(!e.scrollbarYActive)return!1;if(0===o&&r>0||o>=e.contentHeight-e.containerHeight&&0>r)return!e.settings.wheelPropagation}var i=t.scrollLeft;if(0===r){if(!e.scrollbarXActive)return!1;if(0===i&&0>n||i>=e.contentWidth-e.containerWidth&&n>0)return!e.settings.wheelPropagation}return!0}var r=!1;e.event.bind(t,"mouseenter",function(){r=!0}),e.event.bind(t,"mouseleave",function(){r=!1});var i=!1;e.event.bind(e.ownerDocument,"keydown",function(a){if((!a.isDefaultPrevented||!a.isDefaultPrevented())&&r){var c=document.activeElement?document.activeElement:e.ownerDocument.activeElement;if(c){for(;c.shadowRoot;)c=c.shadowRoot.activeElement;if(o.isEditable(c))return}var u=0,d=0;switch(a.which){case 37:u=-30;break;case 38:d=30;break;case 39:u=30;break;case 40:d=-30;break;case 33:d=90;break;case 32:d=a.shiftKey?90:-90;break;case 34:d=-90;break;case 35:d=a.ctrlKey?-e.contentHeight:-e.containerHeight;break;case 36:d=a.ctrlKey?t.scrollTop:e.containerHeight;break;default:return}s(t,"top",t.scrollTop-d),s(t,"left",t.scrollLeft+u),l(t),i=n(u,d),i&&a.preventDefault()}})}var o=t("../../lib/helper"),i=t("../instances"),l=t("../update-geometry"),s=t("../update-scroll");e.exports=function(t){var e=i.get(t);r(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19,"../update-scroll":20}],13:[function(t,e,n){"use strict";function r(t,e){function n(n,r){var o=t.scrollTop;if(0===n){if(!e.scrollbarYActive)return!1;if(0===o&&r>0||o>=e.contentHeight-e.containerHeight&&0>r)return!e.settings.wheelPropagation}var i=t.scrollLeft;if(0===r){if(!e.scrollbarXActive)return!1;if(0===i&&0>n||i>=e.contentWidth-e.containerWidth&&n>0)return!e.settings.wheelPropagation}return!0}function r(t){var e=t.deltaX,n=-1*t.deltaY;return("undefined"==typeof e||"undefined"==typeof n)&&(e=-1*t.wheelDeltaX/6,n=t.wheelDeltaY/6),t.deltaMode&&1===t.deltaMode&&(e*=10,n*=10),e!==e&&n!==n&&(e=0,n=t.wheelDelta),[e,n]}function i(e,n){var r=t.querySelector("textarea:hover");if(r){var o=r.scrollHeight-r.clientHeight;if(o>0&&!(0===r.scrollTop&&n>0||r.scrollTop===o&&0>n))return!0;var i=r.scrollLeft-r.clientWidth;if(i>0&&!(0===r.scrollLeft&&0>e||r.scrollLeft===i&&e>0))return!0}return!1}function a(a){if(o.env.isWebKit||!t.querySelector("select:focus")){var u=r(a),d=u[0],p=u[1];i(d,p)||(c=!1,e.settings.useBothWheelAxes?e.scrollbarYActive&&!e.scrollbarXActive?(p?s(t,"top",t.scrollTop-p*e.settings.wheelSpeed):s(t,"top",t.scrollTop+d*e.settings.wheelSpeed),c=!0):e.scrollbarXActive&&!e.scrollbarYActive&&(d?s(t,"left",t.scrollLeft+d*e.settings.wheelSpeed):s(t,"left",t.scrollLeft-p*e.settings.wheelSpeed),c=!0):(s(t,"top",t.scrollTop-p*e.settings.wheelSpeed),s(t,"left",t.scrollLeft+d*e.settings.wheelSpeed)),l(t),c=c||n(d,p),c&&(a.stopPropagation(),a.preventDefault()))}}var c=!1;"undefined"!=typeof window.onwheel?e.event.bind(t,"wheel",a):"undefined"!=typeof window.onmousewheel&&e.event.bind(t,"mousewheel",a)}var o=t("../../lib/helper"),i=t("../instances"),l=t("../update-geometry"),s=t("../update-scroll");e.exports=function(t){var e=i.get(t);r(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19,"../update-scroll":20}],14:[function(t,e,n){"use strict";function r(t,e){e.event.bind(t,"scroll",function(){i(t)})}var o=t("../instances"),i=t("../update-geometry");e.exports=function(t){var e=o.get(t);r(t,e)}},{"../instances":18,"../update-geometry":19}],15:[function(t,e,n){"use strict";function r(t,e){function n(){var t=window.getSelection?window.getSelection():document.getSelection?document.getSelection():"";return 0===t.toString().length?null:t.getRangeAt(0).commonAncestorContainer}function r(){c||(c=setInterval(function(){return i.get(t)?(s(t,"top",t.scrollTop+u.top),s(t,"left",t.scrollLeft+u.left),void l(t)):void clearInterval(c)},50))}function a(){c&&(clearInterval(c),c=null),o.stopScrolling(t)}var c=null,u={top:0,left:0},d=!1;e.event.bind(e.ownerDocument,"selectionchange",function(){t.contains(n())?d=!0:(d=!1,a())}),e.event.bind(window,"mouseup",function(){d&&(d=!1,a())}),e.event.bind(window,"mousemove",function(e){if(d){var n={x:e.pageX,y:e.pageY},i={left:t.offsetLeft,right:t.offsetLeft+t.offsetWidth,top:t.offsetTop,bottom:t.offsetTop+t.offsetHeight};n.x<i.left+3?(u.left=-5,o.startScrolling(t,"x")):n.x>i.right-3?(u.left=5,o.startScrolling(t,"x")):u.left=0,n.y<i.top+3?(i.top+3-n.y<5?u.top=-5:u.top=-20,o.startScrolling(t,"y")):n.y>i.bottom-3?(n.y-i.bottom+3<5?u.top=5:u.top=20,o.startScrolling(t,"y")):u.top=0,0===u.top&&0===u.left?a():r()}})}var o=t("../../lib/helper"),i=t("../instances"),l=t("../update-geometry"),s=t("../update-scroll");e.exports=function(t){var e=i.get(t);r(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19,"../update-scroll":20}],16:[function(t,e,n){"use strict";function r(t,e,n,r){function s(n,r){var o=t.scrollTop,i=t.scrollLeft,l=Math.abs(n),s=Math.abs(r);if(s>l){if(0>r&&o===e.contentHeight-e.containerHeight||r>0&&0===o)return!e.settings.swipePropagation}else if(l>s&&(0>n&&i===e.contentWidth-e.containerWidth||n>0&&0===i))return!e.settings.swipePropagation;return!0}function a(e,n){l(t,"top",t.scrollTop-n),l(t,"left",t.scrollLeft-e),i(t)}function c(){Y=!0}function u(){Y=!1}function d(t){return t.targetTouches?t.targetTouches[0]:t}function p(t){return t.targetTouches&&1===t.targetTouches.length?!0:t.pointerType&&"mouse"!==t.pointerType&&t.pointerType!==t.MSPOINTER_TYPE_MOUSE?!0:!1}function f(t){if(p(t)){w=!0;var e=d(t);b.pageX=e.pageX,b.pageY=e.pageY,g=(new Date).getTime(),null!==y&&clearInterval(y),t.stopPropagation()}}function h(t){if(!Y&&w&&p(t)){var e=d(t),n={pageX:e.pageX,pageY:e.pageY},r=n.pageX-b.pageX,o=n.pageY-b.pageY;a(r,o),b=n;var i=(new Date).getTime(),l=i-g;l>0&&(m.x=r/l,m.y=o/l,g=i),s(r,o)&&(t.stopPropagation(),t.preventDefault())}}function v(){!Y&&w&&(w=!1,clearInterval(y),y=setInterval(function(){return o.get(t)?Math.abs(m.x)<.01&&Math.abs(m.y)<.01?void clearInterval(y):(a(30*m.x,30*m.y),m.x*=.8,void(m.y*=.8)):void clearInterval(y)},10))}var b={},g=0,m={},y=null,Y=!1,w=!1;n&&(e.event.bind(window,"touchstart",c),e.event.bind(window,"touchend",u),e.event.bind(t,"touchstart",f),e.event.bind(t,"touchmove",h),e.event.bind(t,"touchend",v)),r&&(window.PointerEvent?(e.event.bind(window,"pointerdown",c),e.event.bind(window,"pointerup",u),e.event.bind(t,"pointerdown",f),e.event.bind(t,"pointermove",h),e.event.bind(t,"pointerup",v)):window.MSPointerEvent&&(e.event.bind(window,"MSPointerDown",c),e.event.bind(window,"MSPointerUp",u),e.event.bind(t,"MSPointerDown",f),e.event.bind(t,"MSPointerMove",h),e.event.bind(t,"MSPointerUp",v)))}var o=t("../instances"),i=t("../update-geometry"),l=t("../update-scroll");e.exports=function(t,e,n){var i=o.get(t);r(t,i,e,n)}},{"../instances":18,"../update-geometry":19,"../update-scroll":20}],17:[function(t,e,n){"use strict";var r=t("../lib/class"),o=t("../lib/helper"),i=t("./instances"),l=t("./update-geometry"),s=t("./handler/click-rail"),a=t("./handler/drag-scrollbar"),c=t("./handler/keyboard"),u=t("./handler/mouse-wheel"),d=t("./handler/native-scroll"),p=t("./handler/selection"),f=t("./handler/touch");e.exports=function(t,e){e="object"==typeof e?e:{},r.add(t,"ps-container");var n=i.add(t);n.settings=o.extend(n.settings,e),s(t),a(t),u(t),d(t),n.settings.useSelectionScroll&&p(t),(o.env.supportsTouch||o.env.supportsIePointer)&&f(t,o.env.supportsTouch,o.env.supportsIePointer),n.settings.useKeyboard&&c(t),l(t)}},{"../lib/class":2,"../lib/helper":6,"./handler/click-rail":10,"./handler/drag-scrollbar":11,"./handler/keyboard":12,"./handler/mouse-wheel":13,"./handler/native-scroll":14,"./handler/selection":15,"./handler/touch":16,"./instances":18,"./update-geometry":19}],18:[function(t,e,n){"use strict";function r(t){var e=this;e.settings=d.clone(a),e.containerWidth=null,e.containerHeight=null,e.contentWidth=null,e.contentHeight=null,e.isRtl="rtl"===s.css(t,"direction"),e.isNegativeScroll=function(){var e=t.scrollLeft,n=null;return t.scrollLeft=-1,n=t.scrollLeft<0,t.scrollLeft=e,n}(),e.negativeScrollAdjustment=e.isNegativeScroll?t.scrollWidth-t.clientWidth:0,e.event=new c,e.ownerDocument=t.ownerDocument||document,e.scrollbarXRail=s.appendTo(s.e("div","ps-scrollbar-x-rail"),t),e.scrollbarX=s.appendTo(s.e("div","ps-scrollbar-x"),e.scrollbarXRail),e.scrollbarXActive=null,e.scrollbarXWidth=null,e.scrollbarXLeft=null,e.scrollbarXBottom=d.toInt(s.css(e.scrollbarXRail,"bottom")),e.isScrollbarXUsingBottom=e.scrollbarXBottom===e.scrollbarXBottom,e.scrollbarXTop=e.isScrollbarXUsingBottom?null:d.toInt(s.css(e.scrollbarXRail,"top")),e.railBorderXWidth=d.toInt(s.css(e.scrollbarXRail,"borderLeftWidth"))+d.toInt(s.css(e.scrollbarXRail,"borderRightWidth")),s.css(e.scrollbarXRail,"display","block"),e.railXMarginWidth=d.toInt(s.css(e.scrollbarXRail,"marginLeft"))+d.toInt(s.css(e.scrollbarXRail,"marginRight")),s.css(e.scrollbarXRail,"display",""),e.railXWidth=null,e.railXRatio=null,e.scrollbarYRail=s.appendTo(s.e("div","ps-scrollbar-y-rail"),t),e.scrollbarY=s.appendTo(s.e("div","ps-scrollbar-y"),e.scrollbarYRail),e.scrollbarYActive=null,e.scrollbarYHeight=null,e.scrollbarYTop=null,e.scrollbarYRight=d.toInt(s.css(e.scrollbarYRail,"right")),e.isScrollbarYUsingRight=e.scrollbarYRight===e.scrollbarYRight,e.scrollbarYLeft=e.isScrollbarYUsingRight?null:d.toInt(s.css(e.scrollbarYRail,"left")),e.scrollbarYOuterWidth=e.isRtl?d.outerWidth(e.scrollbarY):null,e.railBorderYWidth=d.toInt(s.css(e.scrollbarYRail,"borderTopWidth"))+d.toInt(s.css(e.scrollbarYRail,"borderBottomWidth")),s.css(e.scrollbarYRail,"display","block"),e.railYMarginHeight=d.toInt(s.css(e.scrollbarYRail,"marginTop"))+d.toInt(s.css(e.scrollbarYRail,"marginBottom")),s.css(e.scrollbarYRail,"display",""),e.railYHeight=null,e.railYRatio=null}function o(t){return"undefined"==typeof t.dataset?t.getAttribute("data-ps-id"):t.dataset.psId}function i(t,e){"undefined"==typeof t.dataset?t.setAttribute("data-ps-id",e):t.dataset.psId=e}function l(t){"undefined"==typeof t.dataset?t.removeAttribute("data-ps-id"):delete t.dataset.psId}var s=t("../lib/dom"),a=t("./default-setting"),c=t("../lib/event-manager"),u=t("../lib/guid"),d=t("../lib/helper"),p={};n.add=function(t){var e=u();return i(t,e),p[e]=new r(t),p[e]},n.remove=function(t){delete p[o(t)],l(t)},n.get=function(t){return p[o(t)]}},{"../lib/dom":3,"../lib/event-manager":4,"../lib/guid":5,"../lib/helper":6,"./default-setting":8}],19:[function(t,e,n){"use strict";function r(t,e){return t.settings.minScrollbarLength&&(e=Math.max(e,t.settings.minScrollbarLength)),t.settings.maxScrollbarLength&&(e=Math.min(e,t.settings.maxScrollbarLength)),e}function o(t,e){var n={width:e.railXWidth};e.isRtl?n.left=e.negativeScrollAdjustment+t.scrollLeft+e.containerWidth-e.contentWidth:n.left=t.scrollLeft,e.isScrollbarXUsingBottom?n.bottom=e.scrollbarXBottom-t.scrollTop:n.top=e.scrollbarXTop+t.scrollTop,l.css(e.scrollbarXRail,n);var r={top:t.scrollTop,height:e.railYHeight};e.isScrollbarYUsingRight?e.isRtl?r.right=e.contentWidth-(e.negativeScrollAdjustment+t.scrollLeft)-e.scrollbarYRight-e.scrollbarYOuterWidth:r.right=e.scrollbarYRight-t.scrollLeft:e.isRtl?r.left=e.negativeScrollAdjustment+t.scrollLeft+2*e.containerWidth-e.contentWidth-e.scrollbarYLeft-e.scrollbarYOuterWidth:r.left=e.scrollbarYLeft+t.scrollLeft,l.css(e.scrollbarYRail,r),l.css(e.scrollbarX,{left:e.scrollbarXLeft,width:e.scrollbarXWidth-e.railBorderXWidth}),l.css(e.scrollbarY,{top:e.scrollbarYTop,height:e.scrollbarYHeight-e.railBorderYWidth})}var i=t("../lib/class"),l=t("../lib/dom"),s=t("../lib/helper"),a=t("./instances"),c=t("./update-scroll");e.exports=function(t){var e=a.get(t);e.containerWidth=t.clientWidth,e.containerHeight=t.clientHeight,e.contentWidth=t.scrollWidth,e.contentHeight=t.scrollHeight;var n;t.contains(e.scrollbarXRail)||(n=l.queryChildren(t,".ps-scrollbar-x-rail"),n.length>0&&n.forEach(function(t){l.remove(t)}),l.appendTo(e.scrollbarXRail,t)),t.contains(e.scrollbarYRail)||(n=l.queryChildren(t,".ps-scrollbar-y-rail"),n.length>0&&n.forEach(function(t){l.remove(t)}),l.appendTo(e.scrollbarYRail,t)),!e.settings.suppressScrollX&&e.containerWidth+e.settings.scrollXMarginOffset<e.contentWidth?(e.scrollbarXActive=!0,e.railXWidth=e.containerWidth-e.railXMarginWidth,e.railXRatio=e.containerWidth/e.railXWidth,e.scrollbarXWidth=r(e,s.toInt(e.railXWidth*e.containerWidth/e.contentWidth)),e.scrollbarXLeft=s.toInt((e.negativeScrollAdjustment+t.scrollLeft)*(e.railXWidth-e.scrollbarXWidth)/(e.contentWidth-e.containerWidth))):(e.scrollbarXActive=!1,e.scrollbarXWidth=0,e.scrollbarXLeft=0,t.scrollLeft=0),!e.settings.suppressScrollY&&e.containerHeight+e.settings.scrollYMarginOffset<e.contentHeight?(e.scrollbarYActive=!0,e.railYHeight=e.containerHeight-e.railYMarginHeight,e.railYRatio=e.containerHeight/e.railYHeight,e.scrollbarYHeight=r(e,s.toInt(e.railYHeight*e.containerHeight/e.contentHeight)),e.scrollbarYTop=s.toInt(t.scrollTop*(e.railYHeight-e.scrollbarYHeight)/(e.contentHeight-e.containerHeight))):(e.scrollbarYActive=!1,e.scrollbarYHeight=0,e.scrollbarYTop=0,c(t,"top",0)),e.scrollbarXLeft>=e.railXWidth-e.scrollbarXWidth&&(e.scrollbarXLeft=e.railXWidth-e.scrollbarXWidth),e.scrollbarYTop>=e.railYHeight-e.scrollbarYHeight&&(e.scrollbarYTop=e.railYHeight-e.scrollbarYHeight),o(t,e),i[e.scrollbarXActive?"add":"remove"](t,"ps-active-x"),i[e.scrollbarYActive?"add":"remove"](t,"ps-active-y")}},{"../lib/class":2,"../lib/dom":3,"../lib/helper":6,"./instances":18,"./update-scroll":20}],20:[function(t,e,n){"use strict";var r,o,i=t("./instances"),l=document.createEvent("Event"),s=document.createEvent("Event"),a=document.createEvent("Event"),c=document.createEvent("Event"),u=document.createEvent("Event"),d=document.createEvent("Event"),p=document.createEvent("Event"),f=document.createEvent("Event"),h=document.createEvent("Event"),v=document.createEvent("Event");l.initEvent("ps-scroll-up",!0,!0),s.initEvent("ps-scroll-down",!0,!0),a.initEvent("ps-scroll-left",!0,!0),c.initEvent("ps-scroll-right",!0,!0),u.initEvent("ps-scroll-y",!0,!0),d.initEvent("ps-scroll-x",!0,!0),p.initEvent("ps-x-reach-start",!0,!0),f.initEvent("ps-x-reach-end",!0,!0),h.initEvent("ps-y-reach-start",!0,!0),v.initEvent("ps-y-reach-end",!0,!0),e.exports=function(t,e,n){if("undefined"==typeof t)throw"You must provide an element to the update-scroll function";if("undefined"==typeof e)throw"You must provide an axis to the update-scroll function";if("undefined"==typeof n)throw"You must provide a value to the update-scroll function";if("top"===e&&0>=n)return t.scrollTop=0,void t.dispatchEvent(h);if("left"===e&&0>=n)return t.scrollLeft=0,void t.dispatchEvent(p);var b=i.get(t);return"top"===e&&n>b.contentHeight-b.containerHeight?(t.scrollTop=b.contentHeight-b.containerHeight,void t.dispatchEvent(v)):"left"===e&&n>b.contentWidth-b.containerWidth?(t.scrollLeft=b.contentWidth-b.containerWidth,void t.dispatchEvent(f)):(r||(r=t.scrollTop),o||(o=t.scrollLeft),"top"===e&&r>n&&t.dispatchEvent(l),"top"===e&&n>r&&t.dispatchEvent(s),"left"===e&&o>n&&t.dispatchEvent(a),"left"===e&&n>o&&t.dispatchEvent(c),"top"===e&&(t.scrollTop=r=n,t.dispatchEvent(u)),void("left"===e&&(t.scrollLeft=o=n,t.dispatchEvent(d))))}},{"./instances":18}],21:[function(t,e,n){"use strict";var r=t("../lib/dom"),o=t("../lib/helper"),i=t("./instances"),l=t("./update-geometry");e.exports=function(t){var e=i.get(t);e&&(e.negativeScrollAdjustment=e.isNegativeScroll?t.scrollWidth-t.clientWidth:0,r.css(e.scrollbarXRail,"display","block"),r.css(e.scrollbarYRail,"display","block"),e.railXMarginWidth=o.toInt(r.css(e.scrollbarXRail,"marginLeft"))+o.toInt(r.css(e.scrollbarXRail,"marginRight")),e.railYMarginHeight=o.toInt(r.css(e.scrollbarYRail,"marginTop"))+o.toInt(r.css(e.scrollbarYRail,"marginBottom")),r.css(e.scrollbarXRail,"display","none"),r.css(e.scrollbarYRail,"display","none"),l(t),r.css(e.scrollbarXRail,"display",""),r.css(e.scrollbarYRail,"display",""))}},{"../lib/dom":3,"../lib/helper":6,"./instances":18,"./update-geometry":19}]},{},[1]);
/**package
{ "name": "modernizr",
  "version": "2.8.3",
  "description":"Modernizr, without the complaints" }
**/

/*!
 * Modernizr v2.8.3
 * www.modernizr.com
 *
 * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton
 * Available under the BSD and MIT licenses: www.modernizr.com/license/
 */

/*
 * Modernizr tests which native CSS3 and HTML5 features are available in
 * the current UA and makes the results available to you in two ways:
 * as properties on a global Modernizr object, and as classes on the
 * <html> element. This information allows you to progressively enhance
 * your pages with a granular level of control over the experience.
 *
 * Modernizr has an optional (not included) conditional resource loader
 * called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
 * To get a build that includes Modernizr.load(), as well as choosing
 * which tests to include, go to www.modernizr.com/download/
 *
 * Authors        Faruk Ates, Paul Irish, Alex Sexton
 * Contributors   Ryan Seddon, Ben Alman
 */

window.Modernizr = (function( window, document, undefined ) {

    var version = '2.8.3',

    Modernizr = {},

    /*>>cssclasses*/
    // option for enabling the HTML classes to be added
    enableClasses = true,
    /*>>cssclasses*/

    docElement = document.documentElement,

    /**
     * Create our "modernizr" element that we do most feature tests on.
     */
    mod = 'modernizr',
    modElem = document.createElement(mod),
    mStyle = modElem.style,

    /**
     * Create the input element for various Web Forms feature tests.
     */
    inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ ,

    /*>>smile*/
    smile = ':)',
    /*>>smile*/

    toString = {}.toString,

    // TODO :: make the prefixes more granular
    /*>>prefixes*/
    // List of property values to set for css tests. See ticket #21
    prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
    /*>>prefixes*/

    /*>>domprefixes*/
    // Following spec is to expose vendor-specific style properties as:
    //   elem.style.WebkitBorderRadius
    // and the following would be incorrect:
    //   elem.style.webkitBorderRadius

    // Webkit ghosts their properties in lowercase but Opera & Moz do not.
    // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+
    //   erik.eae.net/archives/2008/03/10/21.48.10/

    // More here: github.com/Modernizr/Modernizr/issues/issue/21
    omPrefixes = 'Webkit Moz O ms',

    cssomPrefixes = omPrefixes.split(' '),

    domPrefixes = omPrefixes.toLowerCase().split(' '),
    /*>>domprefixes*/

    /*>>ns*/
    ns = {'svg': 'http://www.w3.org/2000/svg'},
    /*>>ns*/

    tests = {},
    inputs = {},
    attrs = {},

    classes = [],

    slice = classes.slice,

    featureName, // used in testing loop


    /*>>teststyles*/
    // Inject element with style element and some CSS rules
    injectElementWithStyles = function( rule, callback, nodes, testnames ) {

      var style, ret, node, docOverflow,
          div = document.createElement('div'),
          // After page load injecting a fake body doesn't work so check if body exists
          body = document.body,
          // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it.
          fakeBody = body || document.createElement('body');

      if ( parseInt(nodes, 10) ) {
          // In order not to give false positives we create a node for each test
          // This also allows the method to scale for unspecified uses
          while ( nodes-- ) {
              node = document.createElement('div');
              node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
              div.appendChild(node);
          }
      }

      // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
      // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
      // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
      // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
      // Documents served as xml will throw if using &shy; so use xml friendly encoded version. See issue #277
      style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join('');
      div.id = mod;
      // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
      // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
      (body ? div : fakeBody).innerHTML += style;
      fakeBody.appendChild(div);
      if ( !body ) {
          //avoid crashing IE8, if background image is used
          fakeBody.style.background = '';
          //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
          fakeBody.style.overflow = 'hidden';
          docOverflow = docElement.style.overflow;
          docElement.style.overflow = 'hidden';
          docElement.appendChild(fakeBody);
      }

      ret = callback(div, rule);
      // If this is done after page load we don't want to remove the body so check if body exists
      if ( !body ) {
          fakeBody.parentNode.removeChild(fakeBody);
          docElement.style.overflow = docOverflow;
      } else {
          div.parentNode.removeChild(div);
      }

      return !!ret;

    },
    /*>>teststyles*/

    /*>>mq*/
    // adapted from matchMedia polyfill
    // by Scott Jehl and Paul Irish
    // gist.github.com/786768
    testMediaQuery = function( mq ) {

      var matchMedia = window.matchMedia || window.msMatchMedia;
      if ( matchMedia ) {
        return matchMedia(mq) && matchMedia(mq).matches || false;
      }

      var bool;

      injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
        bool = (window.getComputedStyle ?
                  getComputedStyle(node, null) :
                  node.currentStyle)['position'] == 'absolute';
      });

      return bool;

     },
     /*>>mq*/


    /*>>hasevent*/
    //
    // isEventSupported determines if a given element supports the given event
    // kangax.github.com/iseventsupported/
    //
    // The following results are known incorrects:
    //   Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative
    //   Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333
    //   ...
    isEventSupported = (function() {

      var TAGNAMES = {
        'select': 'input', 'change': 'input',
        'submit': 'form', 'reset': 'form',
        'error': 'img', 'load': 'img', 'abort': 'img'
      };

      function isEventSupported( eventName, element ) {

        element = element || document.createElement(TAGNAMES[eventName] || 'div');
        eventName = 'on' + eventName;

        // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
        var isSupported = eventName in element;

        if ( !isSupported ) {
          // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
          if ( !element.setAttribute ) {
            element = document.createElement('div');
          }
          if ( element.setAttribute && element.removeAttribute ) {
            element.setAttribute(eventName, '');
            isSupported = is(element[eventName], 'function');

            // If property was created, "remove it" (by setting value to `undefined`)
            if ( !is(element[eventName], 'undefined') ) {
              element[eventName] = undefined;
            }
            element.removeAttribute(eventName);
          }
        }

        element = null;
        return isSupported;
      }
      return isEventSupported;
    })(),
    /*>>hasevent*/

    // TODO :: Add flag for hasownprop ? didn't last time

    // hasOwnProperty shim by kangax needed for Safari 2.0 support
    _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;

    if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
      hasOwnProp = function (object, property) {
        return _hasOwnProperty.call(object, property);
      };
    }
    else {
      hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
        return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
      };
    }

    // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js
    // es5.github.com/#x15.3.4.5

    if (!Function.prototype.bind) {
      Function.prototype.bind = function bind(that) {

        var target = this;

        if (typeof target != "function") {
            throw new TypeError();
        }

        var args = slice.call(arguments, 1),
            bound = function () {

            if (this instanceof bound) {

              var F = function(){};
              F.prototype = target.prototype;
              var self = new F();

              var result = target.apply(
                  self,
                  args.concat(slice.call(arguments))
              );
              if (Object(result) === result) {
                  return result;
              }
              return self;

            } else {

              return target.apply(
                  that,
                  args.concat(slice.call(arguments))
              );

            }

        };

        return bound;
      };
    }

    /**
     * setCss applies given styles to the Modernizr DOM node.
     */
    function setCss( str ) {
        mStyle.cssText = str;
    }

    /**
     * setCssAll extrapolates all vendor-specific css strings.
     */
    function setCssAll( str1, str2 ) {
        return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
    }

    /**
     * is returns a boolean for if typeof obj is exactly type.
     */
    function is( obj, type ) {
        return typeof obj === type;
    }

    /**
     * contains returns a boolean for if substr is found within str.
     */
    function contains( str, substr ) {
        return !!~('' + str).indexOf(substr);
    }

    /*>>testprop*/

    // testProps is a generic CSS / DOM property test.

    // In testing support for a given CSS property, it's legit to test:
    //    `elem.style[styleName] !== undefined`
    // If the property is supported it will return an empty string,
    // if unsupported it will return undefined.

    // We'll take advantage of this quick test and skip setting a style
    // on our modernizr element, but instead just testing undefined vs
    // empty string.

    // Because the testing of the CSS property names (with "-", as
    // opposed to the camelCase DOM properties) is non-portable and
    // non-standard but works in WebKit and IE (but not Gecko or Opera),
    // we explicitly reject properties with dashes so that authors
    // developing in WebKit or IE first don't end up with
    // browser-specific content by accident.

    function testProps( props, prefixed ) {
        for ( var i in props ) {
            var prop = props[i];
            if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
                return prefixed == 'pfx' ? prop : true;
            }
        }
        return false;
    }
    /*>>testprop*/

    // TODO :: add testDOMProps
    /**
     * testDOMProps is a generic DOM property test; if a browser supports
     *   a certain property, it won't return undefined for it.
     */
    function testDOMProps( props, obj, elem ) {
        for ( var i in props ) {
            var item = obj[props[i]];
            if ( item !== undefined) {

                // return the property name as a string
                if (elem === false) return props[i];

                // let's bind a function
                if (is(item, 'function')){
                  // default to autobind unless override
                  return item.bind(elem || obj);
                }

                // return the unbound function or obj or value
                return item;
            }
        }
        return false;
    }

    /*>>testallprops*/
    /**
     * testPropsAll tests a list of DOM properties we want to check against.
     *   We specify literally ALL possible (known and/or likely) properties on
     *   the element including the non-vendor prefixed one, for forward-
     *   compatibility.
     */
    function testPropsAll( prop, prefixed, elem ) {

        var ucProp  = prop.charAt(0).toUpperCase() + prop.slice(1),
            props   = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');

        // did they call .prefixed('boxSizing') or are we just testing a prop?
        if(is(prefixed, "string") || is(prefixed, "undefined")) {
          return testProps(props, prefixed);

        // otherwise, they called .prefixed('requestAnimationFrame', window[, elem])
        } else {
          props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
          return testDOMProps(props, prefixed, elem);
        }
    }
    /*>>testallprops*/


    /**
     * Tests
     * -----
     */

    // The *new* flexbox
    // dev.w3.org/csswg/css3-flexbox

    tests['flexbox'] = function() {
      return testPropsAll('flexWrap');
    };

    // The *old* flexbox
    // www.w3.org/TR/2009/WD-css3-flexbox-20090723/

    tests['flexboxlegacy'] = function() {
        return testPropsAll('boxDirection');
    };

    // On the S60 and BB Storm, getContext exists, but always returns undefined
    // so we actually have to call getContext() to verify
    // github.com/Modernizr/Modernizr/issues/issue/97/

    tests['canvas'] = function() {
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    };

    tests['canvastext'] = function() {
        return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
    };

    // webk.it/70117 is tracking a legit WebGL feature detect proposal

    // We do a soft detect which may false positive in order to avoid
    // an expensive context creation: bugzil.la/732441

    tests['webgl'] = function() {
        return !!window.WebGLRenderingContext;
    };

    /*
     * The Modernizr.touch test only indicates if the browser supports
     *    touch events, which does not necessarily reflect a touchscreen
     *    device, as evidenced by tablets running Windows 7 or, alas,
     *    the Palm Pre / WebOS (touch) phones.
     *
     * Additionally, Chrome (desktop) used to lie about its support on this,
     *    but that has since been rectified: crbug.com/36415
     *
     * We also test for Firefox 4 Multitouch Support.
     *
     * For more info, see: modernizr.github.com/Modernizr/touch.html
     */

    tests['touch'] = function() {
        var bool;

        if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
          bool = true;
        } else {
          injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
            bool = node.offsetTop === 9;
          });
        }

        return bool;
    };


    // geolocation is often considered a trivial feature detect...
    // Turns out, it's quite tricky to get right:
    //
    // Using !!navigator.geolocation does two things we don't want. It:
    //   1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513
    //   2. Disables page caching in WebKit: webk.it/43956
    //
    // Meanwhile, in Firefox < 8, an about:config setting could expose
    // a false positive that would throw an exception: bugzil.la/688158

    tests['geolocation'] = function() {
        return 'geolocation' in navigator;
    };


    tests['postmessage'] = function() {
      return !!window.postMessage;
    };


    // Chrome incognito mode used to throw an exception when using openDatabase
    // It doesn't anymore.
    tests['websqldatabase'] = function() {
      return !!window.openDatabase;
    };

    // Vendors had inconsistent prefixing with the experimental Indexed DB:
    // - Webkit's implementation is accessible through webkitIndexedDB
    // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
    // For speed, we don't test the legacy (and beta-only) indexedDB
    tests['indexedDB'] = function() {
      return !!testPropsAll("indexedDB", window);
    };

    // documentMode logic from YUI to filter out IE8 Compat Mode
    //   which false positives.
    tests['hashchange'] = function() {
      return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
    };

    // Per 1.6:
    // This used to be Modernizr.historymanagement but the longer
    // name has been deprecated in favor of a shorter and property-matching one.
    // The old API is still available in 1.6, but as of 2.0 will throw a warning,
    // and in the first release thereafter disappear entirely.
    tests['history'] = function() {
      return !!(window.history && history.pushState);
    };

    tests['draganddrop'] = function() {
        var div = document.createElement('div');
        return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
    };

    // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10
    // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17.
    // FF10 still uses prefixes, so check for it until then.
    // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/
    tests['websockets'] = function() {
        return 'WebSocket' in window || 'MozWebSocket' in window;
    };


    // css-tricks.com/rgba-browser-support/
    tests['rgba'] = function() {
        // Set an rgba() color and check the returned value

        setCss('background-color:rgba(150,255,150,.5)');

        return contains(mStyle.backgroundColor, 'rgba');
    };

    tests['hsla'] = function() {
        // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
        //   except IE9 who retains it as hsla

        setCss('background-color:hsla(120,40%,100%,.5)');

        return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
    };

    tests['multiplebgs'] = function() {
        // Setting multiple images AND a color on the background shorthand property
        //  and then querying the style.background property value for the number of
        //  occurrences of "url(" is a reliable method for detecting ACTUAL support for this!

        setCss('background:url(https://),url(https://),red url(https://)');

        // If the UA supports multiple backgrounds, there should be three occurrences
        //   of the string "url(" in the return value for elemStyle.background

        return (/(url\s*\(.*?){3}/).test(mStyle.background);
    };



    // this will false positive in Opera Mini
    //   github.com/Modernizr/Modernizr/issues/396

    tests['backgroundsize'] = function() {
        return testPropsAll('backgroundSize');
    };

    tests['borderimage'] = function() {
        return testPropsAll('borderImage');
    };


    // Super comprehensive table about all the unique implementations of
    // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance

    tests['borderradius'] = function() {
        return testPropsAll('borderRadius');
    };

    // WebOS unfortunately false positives on this test.
    tests['boxshadow'] = function() {
        return testPropsAll('boxShadow');
    };

    // FF3.0 will false positive on this test
    tests['textshadow'] = function() {
        return document.createElement('div').style.textShadow === '';
    };


    tests['opacity'] = function() {
        // Browsers that actually have CSS Opacity implemented have done so
        //  according to spec, which means their return values are within the
        //  range of [0.0,1.0] - including the leading zero.

        setCssAll('opacity:.55');

        // The non-literal . in this regex is intentional:
        //   German Chrome returns this value as 0,55
        // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
        return (/^0.55$/).test(mStyle.opacity);
    };


    // Note, Android < 4 will pass this test, but can only animate
    //   a single property at a time
    //   goo.gl/v3V4Gp
    tests['cssanimations'] = function() {
        return testPropsAll('animationName');
    };


    tests['csscolumns'] = function() {
        return testPropsAll('columnCount');
    };


    tests['cssgradients'] = function() {
        /**
         * For CSS Gradients syntax, please see:
         * webkit.org/blog/175/introducing-css-gradients/
         * developer.mozilla.org/en/CSS/-moz-linear-gradient
         * developer.mozilla.org/en/CSS/-moz-radial-gradient
         * dev.w3.org/csswg/css3-images/#gradients-
         */

        var str1 = 'background-image:',
            str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
            str3 = 'linear-gradient(left top,#9f9, white);';

        setCss(
             // legacy webkit syntax (FIXME: remove when syntax not in use anymore)
              (str1 + '-webkit- '.split(' ').join(str2 + str1) +
             // standard syntax             // trailing 'background-image:'
              prefixes.join(str3 + str1)).slice(0, -str1.length)
        );

        return contains(mStyle.backgroundImage, 'gradient');
    };


    tests['cssreflections'] = function() {
        return testPropsAll('boxReflect');
    };


    tests['csstransforms'] = function() {
        return !!testPropsAll('transform');
    };


    tests['csstransforms3d'] = function() {

        var ret = !!testPropsAll('perspective');

        // Webkit's 3D transforms are passed off to the browser's own graphics renderer.
        //   It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
        //   some conditions. As a result, Webkit typically recognizes the syntax but
        //   will sometimes throw a false positive, thus we must do a more thorough check:
        if ( ret && 'webkitPerspective' in docElement.style ) {

          // Webkit allows this media query to succeed only if the feature is enabled.
          // `@media (transform-3d),(-webkit-transform-3d){ ... }`
          injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
            ret = node.offsetLeft === 9 && node.offsetHeight === 3;
          });
        }
        return ret;
    };


    tests['csstransitions'] = function() {
        return testPropsAll('transition');
    };


    /*>>fontface*/
    // @font-face detection routine by Diego Perini
    // javascript.nwbox.com/CSSSupport/

    // false positives:
    //   WebOS github.com/Modernizr/Modernizr/issues/342
    //   WP7   github.com/Modernizr/Modernizr/issues/538
    tests['fontface'] = function() {
        var bool;

        injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) {
          var style = document.getElementById('smodernizr'),
              sheet = style.sheet || style.styleSheet,
              cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';

          bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
        });

        return bool;
    };
    /*>>fontface*/

    // CSS generated content detection
    tests['generatedcontent'] = function() {
        var bool;

        injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) {
          bool = node.offsetHeight >= 3;
        });

        return bool;
    };



    // These tests evaluate support of the video/audio elements, as well as
    // testing what types of content they support.
    //
    // We're using the Boolean constructor here, so that we can extend the value
    // e.g.  Modernizr.video     // true
    //       Modernizr.video.ogg // 'probably'
    //
    // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
    //                     thx to NielsLeenheer and zcorpan

    // Note: in some older browsers, "no" was a return value instead of empty string.
    //   It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
    //   It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5

    tests['video'] = function() {
        var elem = document.createElement('video'),
            bool = false;

        // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('video/ogg; codecs="theora"')      .replace(/^no$/,'');

                // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
                bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');

                bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
            }

        } catch(e) { }

        return bool;
    };

    tests['audio'] = function() {
        var elem = document.createElement('audio'),
            bool = false;

        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,'');
                bool.mp3  = elem.canPlayType('audio/mpeg;')               .replace(/^no$/,'');

                // Mimetypes accepted:
                //   developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
                //   bit.ly/iphoneoscodecs
                bool.wav  = elem.canPlayType('audio/wav; codecs="1"')     .replace(/^no$/,'');
                bool.m4a  = ( elem.canPlayType('audio/x-m4a;')            ||
                              elem.canPlayType('audio/aac;'))             .replace(/^no$/,'');
            }
        } catch(e) { }

        return bool;
    };


    // In FF4, if disabled, window.localStorage should === null.

    // Normally, we could not test that directly and need to do a
    //   `('localStorage' in window) && ` test first because otherwise Firefox will
    //   throw bugzil.la/365772 if cookies are disabled

    // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem
    // will throw the exception:
    //   QUOTA_EXCEEDED_ERRROR DOM Exception 22.
    // Peculiarly, getItem and removeItem calls do not throw.

    // Because we are forced to try/catch this, we'll go aggressive.

    // Just FWIW: IE8 Compat mode supports these features completely:
    //   www.quirksmode.org/dom/html5.html
    // But IE8 doesn't support either with local files

    tests['localstorage'] = function() {
        try {
            localStorage.setItem(mod, mod);
            localStorage.removeItem(mod);
            return true;
        } catch(e) {
            return false;
        }
    };

    tests['sessionstorage'] = function() {
        try {
            sessionStorage.setItem(mod, mod);
            sessionStorage.removeItem(mod);
            return true;
        } catch(e) {
            return false;
        }
    };


    tests['webworkers'] = function() {
        return !!window.Worker;
    };


    tests['applicationcache'] = function() {
        return !!window.applicationCache;
    };


    // Thanks to Erik Dahlstrom
    tests['svg'] = function() {
        return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
    };

    // specifically for SVG inline in HTML, not within XHTML
    // test page: paulirish.com/demo/inline-svg
    tests['inlinesvg'] = function() {
      var div = document.createElement('div');
      div.innerHTML = '<svg/>';
      return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
    };

    // SVG SMIL animation
    tests['smil'] = function() {
        return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
    };

    // This test is only for clip paths in SVG proper, not clip paths on HTML content
    // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg

    // However read the comments to dig into applying SVG clippaths to HTML content here:
    //   github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491
    tests['svgclippaths'] = function() {
        return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
    };

    /*>>webforms*/
    // input features and input types go directly onto the ret object, bypassing the tests loop.
    // Hold this guy to execute in a moment.
    function webforms() {
        /*>>input*/
        // Run through HTML5's new input attributes to see if the UA understands any.
        // We're using f which is the <input> element created early on
        // Mike Taylr has created a comprehensive resource for testing these attributes
        //   when applied to all input types:
        //   miketaylr.com/code/input-type-attr.html
        // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary

        // Only input placeholder is tested while textarea's placeholder is not.
        // Currently Safari 4 and Opera 11 have support only for the input placeholder
        // Both tests are available in feature-detects/forms-placeholder.js
        Modernizr['input'] = (function( props ) {
            for ( var i = 0, len = props.length; i < len; i++ ) {
                attrs[ props[i] ] = !!(props[i] in inputElem);
            }
            if (attrs.list){
              // safari false positive's on datalist: webk.it/74252
              // see also github.com/Modernizr/Modernizr/issues/146
              attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement);
            }
            return attrs;
        })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
        /*>>input*/

        /*>>inputtypes*/
        // Run through HTML5's new input types to see if the UA understands any.
        //   This is put behind the tests runloop because it doesn't return a
        //   true/false like all the other tests; instead, it returns an object
        //   containing each input type with its corresponding true/false value

        // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/
        Modernizr['inputtypes'] = (function(props) {

            for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {

                inputElem.setAttribute('type', inputElemType = props[i]);
                bool = inputElem.type !== 'text';

                // We first check to see if the type we give it sticks..
                // If the type does, we feed it a textual value, which shouldn't be valid.
                // If the value doesn't stick, we know there's input sanitization which infers a custom UI
                if ( bool ) {

                    inputElem.value         = smile;
                    inputElem.style.cssText = 'position:absolute;visibility:hidden;';

                    if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {

                      docElement.appendChild(inputElem);
                      defaultView = document.defaultView;

                      // Safari 2-4 allows the smiley as a value, despite making a slider
                      bool =  defaultView.getComputedStyle &&
                              defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
                              // Mobile android web browser has false positive, so must
                              // check the height to see if the widget is actually there.
                              (inputElem.offsetHeight !== 0);

                      docElement.removeChild(inputElem);

                    } else if ( /^(search|tel)$/.test(inputElemType) ){
                      // Spec doesn't define any special parsing or detectable UI
                      //   behaviors so we pass these through as true

                      // Interestingly, opera fails the earlier test, so it doesn't
                      //  even make it here.

                    } else if ( /^(url|email)$/.test(inputElemType) ) {
                      // Real url and email support comes with prebaked validation.
                      bool = inputElem.checkValidity && inputElem.checkValidity() === false;

                    } else {
                      // If the upgraded input compontent rejects the :) text, we got a winner
                      bool = inputElem.value != smile;
                    }
                }

                inputs[ props[i] ] = !!bool;
            }
            return inputs;
        })('search tel url email datetime date month week time datetime-local number range color'.split(' '));
        /*>>inputtypes*/
    }
    /*>>webforms*/


    // End of test definitions
    // -----------------------



    // Run through all tests and detect their support in the current UA.
    // todo: hypothetically we could be doing an array of tests and use a basic loop here.
    for ( var feature in tests ) {
        if ( hasOwnProp(tests, feature) ) {
            // run the test, throw the return value into the Modernizr,
            //   then based on that boolean, define an appropriate className
            //   and push it into an array of classes we'll join later.
            featureName  = feature.toLowerCase();
            Modernizr[featureName] = tests[feature]();

            classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
        }
    }

    /*>>webforms*/
    // input tests need to run.
    Modernizr.input || webforms();
    /*>>webforms*/


    /**
     * addTest allows the user to define their own feature tests
     * the result will be added onto the Modernizr object,
     * as well as an appropriate className set on the html element
     *
     * @param feature - String naming the feature
     * @param test - Function returning true if feature is supported, false if not
     */
     Modernizr.addTest = function ( feature, test ) {
       if ( typeof feature == 'object' ) {
         for ( var key in feature ) {
           if ( hasOwnProp( feature, key ) ) {
             Modernizr.addTest( key, feature[ key ] );
           }
         }
       } else {

         feature = feature.toLowerCase();

         if ( Modernizr[feature] !== undefined ) {
           // we're going to quit if you're trying to overwrite an existing test
           // if we were to allow it, we'd do this:
           //   var re = new RegExp("\\b(no-)?" + feature + "\\b");
           //   docElement.className = docElement.className.replace( re, '' );
           // but, no rly, stuff 'em.
           return Modernizr;
         }

         test = typeof test == 'function' ? test() : test;

         if (typeof enableClasses !== "undefined" && enableClasses) {
           docElement.className += ' ' + (test ? '' : 'no-') + feature;
         }
         Modernizr[feature] = test;

       }

       return Modernizr; // allow chaining.
     };


    // Reset modElem.cssText to nothing to reduce memory footprint.
    setCss('');
    modElem = inputElem = null;

    /*>>shiv*/
    /**
     * @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
     */
    ;(function(window, document) {
        /*jshint evil:true */
        /** version */
        var version = '3.7.0';

        /** Preset options */
        var options = window.html5 || {};

        /** Used to skip problem elements */
        var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;

        /** Not all elements can be cloned in IE **/
        var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;

        /** Detect whether the browser supports default html5 styles */
        var supportsHtml5Styles;

        /** Name of the expando, to work with multiple documents or to re-shiv one document */
        var expando = '_html5shiv';

        /** The id for the the documents expando */
        var expanID = 0;

        /** Cached data for each document */
        var expandoData = {};

        /** Detect whether the browser supports unknown elements */
        var supportsUnknownElements;

        (function() {
          try {
            var a = document.createElement('a');
            a.innerHTML = '<xyz></xyz>';
            //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
            supportsHtml5Styles = ('hidden' in a);

            supportsUnknownElements = a.childNodes.length == 1 || (function() {
              // assign a false positive if unable to shiv
              (document.createElement)('a');
              var frag = document.createDocumentFragment();
              return (
                typeof frag.cloneNode == 'undefined' ||
                typeof frag.createDocumentFragment == 'undefined' ||
                typeof frag.createElement == 'undefined'
              );
            }());
          } catch(e) {
            // assign a false positive if detection fails => unable to shiv
            supportsHtml5Styles = true;
            supportsUnknownElements = true;
          }

        }());

        /*--------------------------------------------------------------------------*/

        /**
         * Creates a style sheet with the given CSS text and adds it to the document.
         * @private
         * @param {Document} ownerDocument The document.
         * @param {String} cssText The CSS text.
         * @returns {StyleSheet} The style element.
         */
        function addStyleSheet(ownerDocument, cssText) {
          var p = ownerDocument.createElement('p'),
          parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;

          p.innerHTML = 'x<style>' + cssText + '</style>';
          return parent.insertBefore(p.lastChild, parent.firstChild);
        }

        /**
         * Returns the value of `html5.elements` as an array.
         * @private
         * @returns {Array} An array of shived element node names.
         */
        function getElements() {
          var elements = html5.elements;
          return typeof elements == 'string' ? elements.split(' ') : elements;
        }

        /**
         * Returns the data associated to the given document
         * @private
         * @param {Document} ownerDocument The document.
         * @returns {Object} An object of data.
         */
        function getExpandoData(ownerDocument) {
          var data = expandoData[ownerDocument[expando]];
          if (!data) {
            data = {};
            expanID++;
            ownerDocument[expando] = expanID;
            expandoData[expanID] = data;
          }
          return data;
        }

        /**
         * returns a shived element for the given nodeName and document
         * @memberOf html5
         * @param {String} nodeName name of the element
         * @param {Document} ownerDocument The context document.
         * @returns {Object} The shived element.
         */
        function createElement(nodeName, ownerDocument, data){
          if (!ownerDocument) {
            ownerDocument = document;
          }
          if(supportsUnknownElements){
            return ownerDocument.createElement(nodeName);
          }
          if (!data) {
            data = getExpandoData(ownerDocument);
          }
          var node;

          if (data.cache[nodeName]) {
            node = data.cache[nodeName].cloneNode();
          } else if (saveClones.test(nodeName)) {
            node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
          } else {
            node = data.createElem(nodeName);
          }

          // Avoid adding some elements to fragments in IE < 9 because
          // * Attributes like `name` or `type` cannot be set/changed once an element
          //   is inserted into a document/fragment
          // * Link elements with `src` attributes that are inaccessible, as with
          //   a 403 response, will cause the tab/window to crash
          // * Script elements appended to fragments will execute when their `src`
          //   or `text` property is set
          return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
        }

        /**
         * returns a shived DocumentFragment for the given document
         * @memberOf html5
         * @param {Document} ownerDocument The context document.
         * @returns {Object} The shived DocumentFragment.
         */
        function createDocumentFragment(ownerDocument, data){
          if (!ownerDocument) {
            ownerDocument = document;
          }
          if(supportsUnknownElements){
            return ownerDocument.createDocumentFragment();
          }
          data = data || getExpandoData(ownerDocument);
          var clone = data.frag.cloneNode(),
          i = 0,
          elems = getElements(),
          l = elems.length;
          for(;i<l;i++){
            clone.createElement(elems[i]);
          }
          return clone;
        }

        /**
         * Shivs the `createElement` and `createDocumentFragment` methods of the document.
         * @private
         * @param {Document|DocumentFragment} ownerDocument The document.
         * @param {Object} data of the document.
         */
        function shivMethods(ownerDocument, data) {
          if (!data.cache) {
            data.cache = {};
            data.createElem = ownerDocument.createElement;
            data.createFrag = ownerDocument.createDocumentFragment;
            data.frag = data.createFrag();
          }


          ownerDocument.createElement = function(nodeName) {
            //abort shiv
            if (!html5.shivMethods) {
              return data.createElem(nodeName);
            }
            return createElement(nodeName, ownerDocument, data);
          };

          ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
                                                          'var n=f.cloneNode(),c=n.createElement;' +
                                                          'h.shivMethods&&(' +
                                                          // unroll the `createElement` calls
                                                          getElements().join().replace(/[\w\-]+/g, function(nodeName) {
            data.createElem(nodeName);
            data.frag.createElement(nodeName);
            return 'c("' + nodeName + '")';
          }) +
            ');return n}'
                                                         )(html5, data.frag);
        }

        /*--------------------------------------------------------------------------*/

        /**
         * Shivs the given document.
         * @memberOf html5
         * @param {Document} ownerDocument The document to shiv.
         * @returns {Document} The shived document.
         */
        function shivDocument(ownerDocument) {
          if (!ownerDocument) {
            ownerDocument = document;
          }
          var data = getExpandoData(ownerDocument);

          if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
            data.hasCSS = !!addStyleSheet(ownerDocument,
                                          // corrects block display not defined in IE6/7/8/9
                                          'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
                                            // adds styling not present in IE6/7/8/9
                                            'mark{background:#FF0;color:#000}' +
                                            // hides non-rendered elements
                                            'template{display:none}'
                                         );
          }
          if (!supportsUnknownElements) {
            shivMethods(ownerDocument, data);
          }
          return ownerDocument;
        }

        /*--------------------------------------------------------------------------*/

        /**
         * The `html5` object is exposed so that more elements can be shived and
         * existing shiving can be detected on iframes.
         * @type Object
         * @example
         *
         * // options can be changed before the script is included
         * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
         */
        var html5 = {

          /**
           * An array or space separated string of node names of the elements to shiv.
           * @memberOf html5
           * @type Array|String
           */
          'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video',

          /**
           * current version of html5shiv
           */
          'version': version,

          /**
           * A flag to indicate that the HTML5 style sheet should be inserted.
           * @memberOf html5
           * @type Boolean
           */
          'shivCSS': (options.shivCSS !== false),

          /**
           * Is equal to true if a browser supports creating unknown/HTML5 elements
           * @memberOf html5
           * @type boolean
           */
          'supportsUnknownElements': supportsUnknownElements,

          /**
           * A flag to indicate that the document's `createElement` and `createDocumentFragment`
           * methods should be overwritten.
           * @memberOf html5
           * @type Boolean
           */
          'shivMethods': (options.shivMethods !== false),

          /**
           * A string to describe the type of `html5` object ("default" or "default print").
           * @memberOf html5
           * @type String
           */
          'type': 'default',

          // shivs the document according to the specified `html5` object options
          'shivDocument': shivDocument,

          //creates a shived element
          createElement: createElement,

          //creates a shived documentFragment
          createDocumentFragment: createDocumentFragment
        };

        /*--------------------------------------------------------------------------*/

        // expose html5
        window.html5 = html5;

        // shiv the document
        shivDocument(document);

    }(this, document));
    /*>>shiv*/

    // Assign private properties to the return object with prefix
    Modernizr._version      = version;

    // expose these for the plugin API. Look in the source for how to join() them against your input
    /*>>prefixes*/
    Modernizr._prefixes     = prefixes;
    /*>>prefixes*/
    /*>>domprefixes*/
    Modernizr._domPrefixes  = domPrefixes;
    Modernizr._cssomPrefixes  = cssomPrefixes;
    /*>>domprefixes*/

    /*>>mq*/
    // Modernizr.mq tests a given media query, live against the current state of the window
    // A few important notes:
    //   * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
    //   * A max-width or orientation query will be evaluated against the current state, which may change later.
    //   * You must specify values. Eg. If you are testing support for the min-width media query use:
    //       Modernizr.mq('(min-width:0)')
    // usage:
    // Modernizr.mq('only screen and (max-width:768)')
    Modernizr.mq            = testMediaQuery;
    /*>>mq*/

    /*>>hasevent*/
    // Modernizr.hasEvent() detects support for a given event, with an optional element to test on
    // Modernizr.hasEvent('gesturestart', elem)
    Modernizr.hasEvent      = isEventSupported;
    /*>>hasevent*/

    /*>>testprop*/
    // Modernizr.testProp() investigates whether a given style property is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testProp('pointerEvents')
    Modernizr.testProp      = function(prop){
        return testProps([prop]);
    };
    /*>>testprop*/

    /*>>testallprops*/
    // Modernizr.testAllProps() investigates whether a given style property,
    //   or any of its vendor-prefixed variants, is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testAllProps('boxSizing')
    Modernizr.testAllProps  = testPropsAll;
    /*>>testallprops*/


    /*>>teststyles*/
    // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
    // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
    Modernizr.testStyles    = injectElementWithStyles;
    /*>>teststyles*/


    /*>>prefixed*/
    // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
    // Modernizr.prefixed('boxSizing') // 'MozBoxSizing'

    // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
    // Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
    //
    //     str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');

    // If you're trying to ascertain which transition end event to bind to, you might do something like...
    //
    //     var transEndEventNames = {
    //       'WebkitTransition' : 'webkitTransitionEnd',
    //       'MozTransition'    : 'transitionend',
    //       'OTransition'      : 'oTransitionEnd',
    //       'msTransition'     : 'MSTransitionEnd',
    //       'transition'       : 'transitionend'
    //     },
    //     transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];

    Modernizr.prefixed      = function(prop, obj, elem){
      if(!obj) {
        return testPropsAll(prop, 'pfx');
      } else {
        // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame'
        return testPropsAll(prop, obj, elem);
      }
    };
    /*>>prefixed*/


    /*>>cssclasses*/
    // Remove "no-js" class from <html> element, if it exists:
    docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +

                            // Add the new classes to the <html> element.
                            (enableClasses ? ' js ' + classes.join(' ') : '');
    /*>>cssclasses*/

    return Modernizr;

})(this, this.document);
(function ($) {
    'use strict';

    var testElement = document.createElement('_');

    testElement.classList.toggle('c3', false);

    // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
    // support the second argument.
    if (testElement.classList.contains('c3')) {
        var _toggle = DOMTokenList.prototype.toggle;

        DOMTokenList.prototype.toggle = function (token, force) {
            if (1 in arguments && !this.contains(token) === !force) {
                return force;
            } else {
                return _toggle.call(this, token);
            }
        };
    }

    // shallow array comparison
    function isEqual(array1, array2) {
        return array1.length === array2.length && array1.every(function (element, index) {
            return element === array2[index];
        });
    };

    //<editor-fold desc="Shims">
    if (!String.prototype.startsWith) {
        (function () {
            'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
            var defineProperty = (function () {
                // IE 8 only supports `Object.defineProperty` on DOM elements
                try {
                    var object = {};
                    var $defineProperty = Object.defineProperty;
                    var result = $defineProperty(object, object, object) && $defineProperty;
                } catch (error) {
                }
                return result;
            }());
            var toString = {}.toString;
            var startsWith = function (search) {
                if (this == null) {
                    throw new TypeError();
                }
                var string = String(this);
                if (search && toString.call(search) == '[object RegExp]') {
                    throw new TypeError();
                }
                var stringLength = string.length;
                var searchString = String(search);
                var searchLength = searchString.length;
                var position = arguments.length > 1 ? arguments[1] : undefined;
                // `ToInteger`
                var pos = position ? Number(position) : 0;
                if (pos != pos) { // better `isNaN`
                    pos = 0;
                }
                var start = Math.min(Math.max(pos, 0), stringLength);
                // Avoid the `indexOf` call if no match is possible
                if (searchLength + start > stringLength) {
                    return false;
                }
                var index = -1;
                while (++index < searchLength) {
                    if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
                        return false;
                    }
                }
                return true;
            };
            if (defineProperty) {
                defineProperty(String.prototype, 'startsWith', {
                    'value': startsWith,
                    'configurable': true,
                    'writable': true
                });
            } else {
                String.prototype.startsWith = startsWith;
            }
        }());
    }

    if (!Object.keys) {
        Object.keys = function (
            o, // object
            k, // key
            r  // result array
        ) {
            // initialize object and result
            r = [];
            // iterate over object keys
            for (k in o)
                // fill result array with non-prototypical keys
                r.hasOwnProperty.call(o, k) && r.push(k);
            // return result
            return r;
        };
    }

    // much faster than $.val()
    function getSelectValues(select) {
        var result = [];
        var options = select && select.options;
        var opt;

        if (select.multiple) {
            for (var i = 0, len = options.length; i < len; i++) {
                opt = options[i];

                if (opt.selected) {
                    result.push(opt.value || opt.text);
                }
            }
        } else {
            result = select.value;
        }

        return result;
    }

    // set data-selected on select element if the value has been programmatically selected
    // prior to initialization of bootstrap-select
    // * consider removing or replacing an alternative method *
    var valHooks = {
        useDefault: false,
        _set: $.valHooks.select.set
    };

    $.valHooks.select.set = function (elem, value) {
        if (value && !valHooks.useDefault) $(elem).data('selected', true);

        return valHooks._set.apply(this, arguments);
    };

    var changed_arguments = null;

    var EventIsSupported = (function () {
        try {
            new Event('change');
            return true;
        } catch (e) {
            return false;
        }
    })();

    $.fn.triggerNative = function (eventName) {
        var el = this[0],
            event;

        if (el.dispatchEvent) { // for modern browsers & IE9+
            if (EventIsSupported) {
                // For modern browsers
                event = new Event(eventName, {
                    bubbles: true
                });
            } else {
                // For IE since it doesn't support Event constructor
                event = document.createEvent('Event');
                event.initEvent(eventName, true, false);
            }

            el.dispatchEvent(event);
        } else if (el.fireEvent) { // for IE8
            event = document.createEventObject();
            event.eventType = eventName;
            el.fireEvent('on' + eventName, event);
        } else {
            // fall back to jQuery.trigger
            this.trigger(eventName);
        }
    };

    //</editor-fold>

    function stringSearch(li, searchString, method, normalize) {
        var stringTypes = [
                'content',
                'subtext',
                'tokens'
            ],
            searchSuccess = false;

        for (var i = 0; i < stringTypes.length; i++) {
            var stringType = stringTypes[i],
                string = li[stringType];

            if (string) {
                string = string.toString();

                // Strip HTML tags. This isn't perfect, but it's much faster than any other method
                if (stringType === 'content') {
                    string = string.replace(/<[^>]+>/g, '');
                }

                if (normalize) string = normalizeToBase(string);
                string = string.toUpperCase();

                if (method === 'contains') {
                    searchSuccess = string.indexOf(searchString) >= 0;
                } else {
                    searchSuccess = string.startsWith(searchString);
                }

                if (searchSuccess) break;
            }
        }

        return searchSuccess;
    }

    function toInteger(value) {
        return parseInt(value, 10) || 0;
    }

    /**
     * Remove all diatrics from the given text.
     * @access private
     * @param {String} text
     * @returns {String}
     */
    function normalizeToBase(text) {
        var rExps = [
            {re: /[\xC0-\xC6]/g, ch: "A"},
            {re: /[\xE0-\xE6]/g, ch: "a"},
            {re: /[\xC8-\xCB]/g, ch: "E"},
            {re: /[\xE8-\xEB]/g, ch: "e"},
            {re: /[\xCC-\xCF]/g, ch: "I"},
            {re: /[\xEC-\xEF]/g, ch: "i"},
            {re: /[\xD2-\xD6]/g, ch: "O"},
            {re: /[\xF2-\xF6]/g, ch: "o"},
            {re: /[\xD9-\xDC]/g, ch: "U"},
            {re: /[\xF9-\xFC]/g, ch: "u"},
            {re: /[\xC7-\xE7]/g, ch: "c"},
            {re: /[\xD1]/g, ch: "N"},
            {re: /[\xF1]/g, ch: "n"}
        ];
        $.each(rExps, function () {
            text = text ? text.replace(this.re, this.ch) : '';
        });
        return text;
    }


    // List of HTML entities for escaping.
    var escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        '`': '&#x60;'
    };

    var unescapeMap = {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#x27;': "'",
        '&#x60;': '`'
    };

    // Functions for escaping and unescaping strings to/from HTML interpolation.
    var createEscaper = function (map) {
        var escaper = function (match) {
            return map[match];
        };
        // Regexes for identifying a key that needs to be escaped.
        var source = '(?:' + Object.keys(map).join('|') + ')';
        var testRegexp = RegExp(source);
        var replaceRegexp = RegExp(source, 'g');
        return function (string) {
            string = string == null ? '' : '' + string;
            return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
        };
    };

    var htmlEscape = createEscaper(escapeMap);
    var htmlUnescape = createEscaper(unescapeMap);

    /**
     * ------------------------------------------------------------------------
     * Constants
     * ------------------------------------------------------------------------
     */

    var keyCodeMap = {
        32: ' ',
        48: '0',
        49: '1',
        50: '2',
        51: '3',
        52: '4',
        53: '5',
        54: '6',
        55: '7',
        56: '8',
        57: '9',
        59: ';',
        65: 'A',
        66: 'B',
        67: 'C',
        68: 'D',
        69: 'E',
        70: 'F',
        71: 'G',
        72: 'H',
        73: 'I',
        74: 'J',
        75: 'K',
        76: 'L',
        77: 'M',
        78: 'N',
        79: 'O',
        80: 'P',
        81: 'Q',
        82: 'R',
        83: 'S',
        84: 'T',
        85: 'U',
        86: 'V',
        87: 'W',
        88: 'X',
        89: 'Y',
        90: 'Z',
        96: '0',
        97: '1',
        98: '2',
        99: '3',
        100: '4',
        101: '5',
        102: '6',
        103: '7',
        104: '8',
        105: '9'
    };

    var keyCodes = {
        ESCAPE: 27, // KeyboardEvent.which value for Escape (Esc) key
        ENTER: 13, // KeyboardEvent.which value for Enter key
        SPACE: 32, // KeyboardEvent.which value for space key
        TAB: 9, // KeyboardEvent.which value for tab key
        ARROW_UP: 38, // KeyboardEvent.which value for up arrow key
        ARROW_DOWN: 40 // KeyboardEvent.which value for down arrow key
    }

    var version = {
        success: false,
        major: '3'
    };

    try {
        version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
        version.major = version.full[0];
        version.success = true;
    }
    catch (err) {
        console.warn(
            'There was an issue retrieving Bootstrap\'s version. ' +
            'Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. ' +
            'If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.'
            , err);
    }

    var classNames = {
        DISABLED: 'disabled',
        DIVIDER: 'divider',
        SHOW: 'open',
        DROPUP: 'dropup',
        MENU: 'dropdown-menu',
        MENURIGHT: 'dropdown-menu-right',
        MENULEFT: 'dropdown-menu-left',
        // to-do: replace with more advanced template/customization options
        BUTTONCLASS: 'btn-default',
        POPOVERHEADER: 'popover-title'
    }

    var Selector = {
        MENU: '.' + classNames.MENU
    }

    if (version.major === '4') {
        classNames.DIVIDER = 'dropdown-divider';
        classNames.SHOW = 'show';
        classNames.BUTTONCLASS = 'btn-light';
        classNames.POPOVERHEADER = 'popover-header';
    }

    var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN);
    var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE);
    var REGEXP_ENTER_OR_SPACE = new RegExp(keyCodes.ENTER + '|' + keyCodes.SPACE);

    var Selectpicker = function (element, options) {
        var that = this;

        // bootstrap-select has been initialized - revert valHooks.select.set back to its original function
        if (!valHooks.useDefault) {
            $.valHooks.select.set = valHooks._set;
            valHooks.useDefault = true;
        }

        this.$element = $(element);
        this.$newElement = null;
        this.$button = null;
        this.$menu = null;
        this.options = options;
        this.selectpicker = {
            main: {
                // store originalIndex (key) and newIndex (value) in this.selectpicker.main.map.newIndex for fast accessibility
                // allows us to do this.main.elements[this.selectpicker.main.map.newIndex[index]] to select an element based on the originalIndex
                map: {
                    newIndex: {},
                    originalIndex: {}
                }
            },
            current: {
                map: {}
            }, // current changes if a search is in progress
            search: {
                map: {}
            },
            view: {},
            keydown: {
                keyHistory: '',
                resetKeyHistory: {
                    start: function () {
                        return setTimeout(function () {
                            that.selectpicker.keydown.keyHistory = '';
                        }, 800);
                    }
                }
            }
        };
        // If we have no title yet, try to pull it from the html title attribute (jQuery doesnt' pick it up as it's not a
        // data-attribute)
        if (this.options.title === null) {
            this.options.title = this.$element.attr('title');
        }

        // Format window padding
        var winPad = this.options.windowPadding;
        if (typeof winPad === 'number') {
            this.options.windowPadding = [winPad, winPad, winPad, winPad];
        }

        //Expose public methods
        this.val = Selectpicker.prototype.val;
        this.render = Selectpicker.prototype.render;
        this.refresh = Selectpicker.prototype.refresh;
        this.setStyle = Selectpicker.prototype.setStyle;
        this.selectAll = Selectpicker.prototype.selectAll;
        this.deselectAll = Selectpicker.prototype.deselectAll;
        this.destroy = Selectpicker.prototype.destroy;
        this.remove = Selectpicker.prototype.remove;
        this.show = Selectpicker.prototype.show;
        this.hide = Selectpicker.prototype.hide;

        this.init();
    };

    Selectpicker.VERSION = '1.13.2';

    Selectpicker.BootstrapVersion = version.major;

    // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
    Selectpicker.DEFAULTS = {
        noneSelectedText: 'Nothing selected',
        noneResultsText: 'No results matched {0}',
        countSelectedText: function (numSelected, numTotal) {
            return (numSelected == 1) ? "{0} item selected" : "{0} items selected";
        },
        maxOptionsText: function (numAll, numGroup) {
            return [
                (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
                (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
            ];
        },
        selectAllText: 'Select All',
        deselectAllText: 'Deselect All',
        doneButton: false,
        doneButtonText: 'Close',
        multipleSeparator: ', ',
        styleBase: 'btn',
        style: classNames.BUTTONCLASS,
        size: 'auto',
        title: null,
        selectedTextFormat: 'values',
        width: false,
        container: false,
        hideDisabled: false,
        showSubtext: false,
        showIcon: true,
        showContent: true,
        dropupAuto: true,
        header: false,
        liveSearch: false,
        liveSearchPlaceholder: null,
        liveSearchNormalize: false,
        liveSearchStyle: 'contains',
        actionsBox: false,
        iconBase: 'glyphicon',
        tickIcon: 'glyphicon-ok',
        showTick: false,
        template: {
            caret: '<img  src="/fileadmin/templates/img/news/arrow-down.png">'
        },
        maxOptions: false,
        mobile: false,
        selectOnTab: false,
        dropdownAlignRight: false,
        windowPadding: 0,
        virtualScroll: 600,
        display: false
    };

    if (version.major === '4') {
        Selectpicker.DEFAULTS.style = 'btn-light';
        Selectpicker.DEFAULTS.iconBase = '';
        Selectpicker.DEFAULTS.tickIcon = 'bs-ok-default';
    }

    Selectpicker.prototype = {

        constructor: Selectpicker,

        init: function () {
            var that = this,
                id = this.$element.attr('id');

            this.$element.addClass('bs-select-hidden');

            this.multiple = this.$element.prop('multiple');
            this.autofocus = this.$element.prop('autofocus');
            this.$newElement = this.createDropdown();
            this.createLi();
            this.$element
                .after(this.$newElement)
                .prependTo(this.$newElement);
            this.$button = this.$newElement.children('button');
            this.$menu = this.$newElement.children(Selector.MENU);
            this.$menuInner = this.$menu.children('.inner');
            this.$searchbox = this.$menu.find('input');

            this.$element.removeClass('bs-select-hidden');

            if (this.options.dropdownAlignRight === true) this.$menu.addClass(classNames.MENURIGHT);

            if (typeof id !== 'undefined') {
                this.$button.attr('data-id', id);
            }

            this.checkDisabled();
            this.clickListener();
            if (this.options.liveSearch) this.liveSearchListener();
            this.render();
            this.setStyle();
            this.setWidth();
            if (this.options.container) {
                this.selectPosition();
            } else {
                this.$element.on('hide.bs.select', function () {
                    if (that.isVirtual()) {
                        // empty menu on close
                        var menuInner = that.$menuInner[0],
                            emptyMenu = menuInner.firstChild.cloneNode(false);

                        // replace the existing UL with an empty one - this is faster than $.empty() or innerHTML = ''
                        menuInner.replaceChild(emptyMenu, menuInner.firstChild);
                        menuInner.scrollTop = 0;
                    }
                });
            }
            this.$menu.data('this', this);
            this.$newElement.data('this', this);
            if (this.options.mobile) this.mobile();

            this.$newElement.on({
                'hide.bs.dropdown': function (e) {
                    that.$menuInner.attr('aria-expanded', false);
                    that.$element.trigger('hide.bs.select', e);
                },
                'hidden.bs.dropdown': function (e) {
                    that.$element.trigger('hidden.bs.select', e);
                },
                'show.bs.dropdown': function (e) {
                    that.$menuInner.attr('aria-expanded', true);
                    that.$element.trigger('show.bs.select', e);
                },
                'shown.bs.dropdown': function (e) {
                    that.$element.trigger('shown.bs.select', e);
                }
            });

            if (that.$element[0].hasAttribute('required')) {
                this.$element.on('invalid', function () {
                    that.$button.addClass('bs-invalid');

                    that.$element.on({
                        'shown.bs.select': function () {
                            that.$element
                                .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened
                                .off('shown.bs.select');
                        },
                        'rendered.bs.select': function () {
                            // if select is no longer invalid, remove the bs-invalid class
                            if (this.validity.valid) that.$button.removeClass('bs-invalid');
                            that.$element.off('rendered.bs.select');
                        }
                    });

                    that.$button.on('blur.bs.select', function () {
                        that.$element.focus().blur();
                        that.$button.off('blur.bs.select');
                    });
                });
            }

            setTimeout(function () {
                that.$element.trigger('loaded.bs.select');
            });
        },

        createDropdown: function () {
            // Options
            // If we are multiple or showTick option is set, then add the show-tick class
            var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '',
                autofocus = this.autofocus ? ' autofocus' : '';
            // Elements
            var header = this.options.header ? '<div class="' + classNames.POPOVERHEADER + '"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + '</div>' : '';
            var searchbox = this.options.liveSearch ?
                '<div class="bs-searchbox">' +
                '<input type="text" class="form-control" autocomplete="off"' +
                (null === this.options.liveSearchPlaceholder ? '' : ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"') + ' role="textbox" aria-label="Search">' +
                '</div>'
                : '';
            var actionsbox = this.multiple && this.options.actionsBox ?
                '<div class="bs-actionsbox">' +
                '<div class="btn-group btn-group-sm btn-block">' +
                '<button type="button" class="actions-btn bs-select-all btn ' + classNames.BUTTONCLASS + '">' +
                this.options.selectAllText +
                '</button>' +
                '<button type="button" class="actions-btn bs-deselect-all btn ' + classNames.BUTTONCLASS + '">' +
                this.options.deselectAllText +
                '</button>' +
                '</div>' +
                '</div>'
                : '';
            var donebutton = this.multiple && this.options.doneButton ?
                '<div class="bs-donebutton">' +
                '<div class="btn-group btn-block">' +
                '<button type="button" class="btn btn-sm ' + classNames.BUTTONCLASS + '">' +
                this.options.doneButtonText +
                '</button>' +
                '</div>' +
                '</div>'
                : '';
            var drop =
                '<div class="dropdown bootstrap-select' + showTick + '">' +
                '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" ' + (this.options.display === 'static' ? 'data-display="static"' : '') + 'data-toggle="dropdown"' + autofocus + ' role="button">' +
                '<div class="filter-option">' +
                '<div class="filter-option-inner">' +
                '<div class="filter-option-inner-inner"></div>' +
                '</div> ' +
                '</div>' +
                (version.major === '4' ?
                        '' :
                        '<span class="bs-caret">' +
                        this.options.template.caret +
                        '</span>'
                ) +
                '</button>' +
                '<div class="' + classNames.MENU + ' ' + (version.major === '4' ? '' : classNames.SHOW) + '" role="combobox">' +
                header +
                searchbox +
                actionsbox +
                '<div class="inner ' + classNames.SHOW + '" role="listbox" aria-expanded="false" tabindex="-1">' +
                '<ul class="' + classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '') + '">' +
                '</ul>' +
                '</div>' +
                donebutton +
                '</div>' +
                '</div>';

            return $(drop);
        },

        setPositionData: function () {
            this.selectpicker.view.canHighlight = [];

            for (var i = 0; i < this.selectpicker.current.data.length; i++) {
                var li = this.selectpicker.current.data[i],
                    canHighlight = true;

                if (li.type === 'divider') {
                    canHighlight = false;
                    li.height = this.sizeInfo.dividerHeight;
                } else if (li.type === 'optgroup-label') {
                    canHighlight = false;
                    li.height = this.sizeInfo.dropdownHeaderHeight;
                } else {
                    li.height = this.sizeInfo.liHeight;
                }

                if (li.disabled) canHighlight = false;

                this.selectpicker.view.canHighlight.push(canHighlight);

                li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height;
            }
        },

        isVirtual: function () {
            return (this.options.virtualScroll !== false) && this.selectpicker.main.elements.length >= this.options.virtualScroll || this.options.virtualScroll === true;
        },

        createView: function (isSearching, scrollTop) {
            scrollTop = scrollTop || 0;

            var that = this;

            this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main;

            var $lis;
            var active = [];
            var selected;
            var prevActive;
            var activeIndex;
            var prevActiveIndex;

            this.setPositionData();

            scroll(scrollTop, true);

            this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) {
                if (!that.noScroll) scroll(this.scrollTop, updateValue);
                that.noScroll = false;
            });

            function scroll(scrollTop, init) {
                var size = that.selectpicker.current.elements.length,
                    chunks = [],
                    chunkSize,
                    chunkCount,
                    firstChunk,
                    lastChunk,
                    currentChunk = undefined,
                    prevPositions,
                    positionIsDifferent,
                    previousElements,
                    menuIsDifferent = true,
                    isVirtual = that.isVirtual();

                that.selectpicker.view.scrollTop = scrollTop;

                if (isVirtual === true) {
                    // if an option that is encountered that is wider than the current menu width, update the menu width accordingly
                    if (that.sizeInfo.hasScrollBar && that.$menu[0].offsetWidth > that.sizeInfo.totalMenuWidth) {
                        that.sizeInfo.menuWidth = that.$menu[0].offsetWidth;
                        that.sizeInfo.totalMenuWidth = that.sizeInfo.menuWidth + that.sizeInfo.scrollBarWidth;
                        that.$menu.css('min-width', that.sizeInfo.menuWidth);
                    }
                }

                chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk
                chunkCount = Math.round(size / chunkSize) || 1; // number of chunks

                for (var i = 0; i < chunkCount; i++) {
                    var end_of_chunk = (i + 1) * chunkSize;

                    if (i === chunkCount - 1) {
                        end_of_chunk = size;
                    }

                    chunks[i] = [
                        (i) * chunkSize + (!i ? 0 : 1),
                        end_of_chunk
                    ];

                    if (!size) break;

                    if (currentChunk === undefined && scrollTop <= that.selectpicker.current.data[end_of_chunk - 1].position - that.sizeInfo.menuInnerHeight) {
                        currentChunk = i;
                    }
                }

                if (currentChunk === undefined) currentChunk = 0;

                prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1];

                // always display previous, current, and next chunks
                firstChunk = Math.max(0, currentChunk - 1);
                lastChunk = Math.min(chunkCount - 1, currentChunk + 1);

                that.selectpicker.view.position0 = Math.max(0, chunks[firstChunk][0]) || 0;
                that.selectpicker.view.position1 = Math.min(size, chunks[lastChunk][1]) || 0;

                positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1;

                if (that.activeIndex !== undefined) {
                    prevActive = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.prevActiveIndex]];
                    active = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.activeIndex]];
                    selected = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.selectedIndex]];

                    if (init) {
                        if (that.activeIndex !== that.selectedIndex) {
                            active.classList.remove('active');
                            if (active.firstChild) active.firstChild.classList.remove('active');
                        }
                        that.activeIndex = undefined;
                    }

                    if (that.activeIndex && that.activeIndex !== that.selectedIndex && selected && selected.length) {
                        selected.classList.remove('active');
                        if (selected.firstChild) selected.firstChild.classList.remove('active');
                    }
                }

                if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex && prevActive && prevActive.length) {
                    prevActive.classList.remove('active');
                    if (prevActive.firstChild) prevActive.firstChild.classList.remove('active');
                }

                if (init || positionIsDifferent) {
                    previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : [];

                    that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1);

                    that.setOptionStatus();

                    // if searching, check to make sure the list has actually been updated before updating DOM
                    // this prevents unnecessary repaints
                    if (isSearching || (isVirtual === false && init)) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements);

                    // if virtual scroll is disabled and not searching,
                    // menu should never need to be updated more than once
                    if ((init || isVirtual === true) && menuIsDifferent) {
                        var menuInner = that.$menuInner[0],
                            menuFragment = document.createDocumentFragment(),
                            emptyMenu = menuInner.firstChild.cloneNode(false),
                            marginTop,
                            marginBottom,
                            elements = isVirtual === true ? that.selectpicker.view.visibleElements : that.selectpicker.current.elements;

                        // replace the existing UL with an empty one - this is faster than $.empty()
                        menuInner.replaceChild(emptyMenu, menuInner.firstChild);

                        for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) {
                            menuFragment.appendChild(elements[i]);
                        }

                        if (isVirtual === true) {
                            marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position),
                                marginBottom = (that.selectpicker.view.position1 > size - 1 ? 0 : that.selectpicker.current.data[size - 1].position - that.selectpicker.current.data[that.selectpicker.view.position1 - 1].position);

                            menuInner.firstChild.style.marginTop = marginTop + 'px';
                            menuInner.firstChild.style.marginBottom = marginBottom + 'px';
                        }

                        menuInner.firstChild.appendChild(menuFragment);
                    }
                }

                that.prevActiveIndex = that.activeIndex;

                if (!that.options.liveSearch) {
                    that.$menuInner.focus();
                } else if (isSearching && init) {
                    var index = 0,
                        newActive;

                    if (!that.selectpicker.view.canHighlight[index]) {
                        index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true);
                    }

                    newActive = that.selectpicker.view.visibleElements[index];

                    if (that.selectpicker.view.currentActive) {
                        that.selectpicker.view.currentActive.classList.remove('active');
                        if (that.selectpicker.view.currentActive.firstChild) that.selectpicker.view.currentActive.firstChild.classList.remove('active');
                    }

                    if (newActive) {
                        newActive.classList.add('active');
                        if (newActive.firstChild) newActive.firstChild.classList.add('active');
                    }

                    that.activeIndex = that.selectpicker.current.map.originalIndex[index];
                }
            }

            $(window).off('resize.createView').on('resize.createView', function () {
                scroll(that.$menuInner[0].scrollTop);
            });
        },

        createLi: function () {
            var that = this,
                mainElements = [],
                widestOption,
                availableOptionsCount = 0,
                widestOptionLength = 0,
                mainData = [],
                optID = 0,
                headerIndex = 0,
                liIndex = -1; // increment liIndex whenever a new <li> element is created to ensure newIndex is correct

            if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option');

            var elementTemplates = {
                    span: document.createElement('span'),
                    subtext: document.createElement('small'),
                    a: document.createElement('a'),
                    li: document.createElement('li'),
                    whitespace: document.createTextNode("\u00A0")
                },
                checkMark = elementTemplates.span.cloneNode(false),
                fragment = document.createDocumentFragment();

            checkMark.className = that.options.iconBase + ' ' + that.options.tickIcon + ' check-mark';
            elementTemplates.a.appendChild(checkMark);
            elementTemplates.a.setAttribute('role', 'option');

            elementTemplates.subtext.className = 'text-muted';

            elementTemplates.text = elementTemplates.span.cloneNode(false);
            elementTemplates.text.className = 'text';

            // Helper functions
            /**
             * @param content
             * @param [index]
             * @param [classes]
             * @param [optgroup]
             * @returns {HTMLElement}
             */
            var generateLI = function (content, index, classes, optgroup) {
                var li = elementTemplates.li.cloneNode(false);

                if (content) {
                    if (content.nodeType === 1 || content.nodeType === 11) {
                        li.appendChild(content);
                    } else {
                        li.innerHTML = content;
                    }
                }

                if (typeof classes !== 'undefined' && '' !== classes) li.className = classes;
                if (typeof optgroup !== 'undefined' && null !== optgroup) li.classList.add('optgroup-' + optgroup);

                return li;
            };

            /**
             * @param text
             * @param [classes]
             * @param [inline]
             * @returns {string}
             */
            var generateA = function (text, classes, inline) {
                var a = elementTemplates.a.cloneNode(true);

                if (text) {
                    if (text.nodeType === 11) {
                        a.appendChild(text);
                    } else {
                        a.insertAdjacentHTML('beforeend', text);
                    }
                }

                if (typeof classes !== 'undefined' & '' !== classes) a.className = classes;
                if (version.major === '4') a.classList.add('dropdown-item');
                if (inline) a.setAttribute('style', inline);

                return a;
            };

            var generateText = function (options) {
                var textElement = elementTemplates.text.cloneNode(false),
                    optionSubtextElement,
                    optionIconElement;

                if (options.optionContent) {
                    textElement.innerHTML = options.optionContent;
                } else {
                    textElement.textContent = options.text;

                    if (options.optionIcon) {
                        var whitespace = elementTemplates.whitespace.cloneNode(false);

                        optionIconElement = elementTemplates.span.cloneNode(false);
                        optionIconElement.className = that.options.iconBase + ' ' + options.optionIcon;

                        fragment.appendChild(optionIconElement);
                        fragment.appendChild(whitespace);
                    }

                    if (options.optionSubtext) {
                        optionSubtextElement = elementTemplates.subtext.cloneNode(false);
                        optionSubtextElement.innerHTML = options.optionSubtext;
                        textElement.appendChild(optionSubtextElement);
                    }
                }

                fragment.appendChild(textElement);

                return fragment;
            };

            var generateLabel = function (options) {
                var labelTextElement = elementTemplates.text.cloneNode(false),
                    labelSubtextElement,
                    labelIconElement;

                labelTextElement.innerHTML = options.labelEscaped;

                if (options.labelIcon) {
                    var whitespace = elementTemplates.whitespace.cloneNode(false);

                    labelIconElement = elementTemplates.span.cloneNode(false);
                    labelIconElement.className = that.options.iconBase + ' ' + options.labelIcon;

                    fragment.appendChild(labelIconElement);
                    fragment.appendChild(whitespace);
                }

                if (options.labelSubtext) {
                    labelSubtextElement = elementTemplates.subtext.cloneNode(false);
                    labelSubtextElement.textContent = options.labelSubtext;
                    labelTextElement.appendChild(labelSubtextElement);
                }

                fragment.appendChild(labelTextElement);

                return fragment;
            }

            if (this.options.title && !this.multiple) {
                // this option doesn't create a new <li> element, but does add a new option, so liIndex is decreased
                // since newIndex is recalculated on every refresh, liIndex needs to be decreased even if the titleOption is already appended
                liIndex--;

                var element = this.$element[0],
                    isSelected = false,
                    titleNotAppended = !this.selectpicker.view.titleOption.parentNode;

                if (titleNotAppended) {
                    // Use native JS to prepend option (faster)
                    this.selectpicker.view.titleOption.className = 'bs-title-option';
                    this.selectpicker.view.titleOption.value = '';

                    // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
                    // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
                    // if so, the select will have the data-selected attribute
                    var $opt = $(element.options[element.selectedIndex]);
                    isSelected = $opt.attr('selected') === undefined && this.$element.data('selected') === undefined;
                }

                if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) {
                    element.insertBefore(this.selectpicker.view.titleOption, element.firstChild);
                }

                // Set selected *after* appending to select,
                // otherwise the option doesn't get selected in IE
                // set using selectedIndex, as setting the selected attr to true here doesn't work in IE11
                if (isSelected) element.selectedIndex = 0;
            }

            var $selectOptions = this.$element.find('option');

            $selectOptions.each(function (index) {
                var $this = $(this);

                liIndex++;

                if ($this.hasClass('bs-title-option')) return;

                var thisData = $this.data();

                // Get the class and text for the option
                var optionClass = this.className || '',
                    inline = htmlEscape(this.style.cssText),
                    optionContent = thisData.content,
                    text = this.textContent,
                    tokens = thisData.tokens,
                    subtext = thisData.subtext,
                    icon = thisData.icon,
                    $parent = $this.parent(),
                    parent = $parent[0],
                    isOptgroup = parent.tagName === 'OPTGROUP',
                    isOptgroupDisabled = isOptgroup && parent.disabled,
                    isDisabled = this.disabled || isOptgroupDisabled,
                    prevHiddenIndex,
                    showDivider = this.previousElementSibling && this.previousElementSibling.tagName === 'OPTGROUP',
                    textElement;

                var parentData = $parent.data();

                if (thisData.hidden === true || that.options.hideDisabled && (isDisabled && !isOptgroup || isOptgroupDisabled)) {
                    // set prevHiddenIndex - the index of the first hidden option in a group of hidden options
                    // used to determine whether or not a divider should be placed after an optgroup if there are
                    // hidden options between the optgroup and the first visible option
                    prevHiddenIndex = thisData.prevHiddenIndex;
                    $this.next().data('prevHiddenIndex', (prevHiddenIndex !== undefined ? prevHiddenIndex : index));

                    liIndex--;

                    // if previous element is not an optgroup
                    if (!showDivider) {
                        if (prevHiddenIndex !== undefined) {
                            // select the element **before** the first hidden element in the group
                            var prevHidden = $selectOptions[prevHiddenIndex].previousElementSibling;

                            if (prevHidden && prevHidden.tagName === 'OPTGROUP' && !prevHidden.disabled) {
                                showDivider = true;
                            }
                        }
                    }

                    if (showDivider && mainData[mainData.length - 1].type !== 'divider') {
                        liIndex++;
                        mainElements.push(
                            generateLI(
                                false,
                                null,
                                classNames.DIVIDER,
                                optID + 'div'
                            )
                        );
                        mainData.push({
                            type: 'divider',
                            optID: optID
                        });
                    }

                    return;
                }

                if (isOptgroup && thisData.divider !== true) {
                    if (that.options.hideDisabled && isDisabled) {
                        if (parentData.allOptionsDisabled === undefined) {
                            var $options = $parent.children();
                            $parent.data('allOptionsDisabled', $options.filter(':disabled').length === $options.length);
                        }

                        if ($parent.data('allOptionsDisabled')) {
                            liIndex--;
                            return;
                        }
                    }

                    var optGroupClass = ' ' + parent.className || '';

                    if (!this.previousElementSibling) { // Is it the first option of the optgroup?
                        optID += 1;

                        // Get the opt group label
                        var label = parent.label,
                            labelEscaped = htmlEscape(label),
                            labelSubtext = parentData.subtext,
                            labelIcon = parentData.icon;

                        if (index !== 0 && mainElements.length > 0) { // Is it NOT the first option of the select && are there elements in the dropdown?
                            liIndex++;
                            mainElements.push(
                                generateLI(
                                    false,
                                    null,
                                    classNames.DIVIDER,
                                    optID + 'div'
                                )
                            );
                            mainData.push({
                                type: 'divider',
                                optID: optID
                            });
                        }
                        liIndex++;

                        var labelElement = generateLabel({
                            labelEscaped: labelEscaped,
                            labelSubtext: labelSubtext,
                            labelIcon: labelIcon
                        });

                        mainElements.push(generateLI(labelElement, null, 'dropdown-header' + optGroupClass, optID));
                        mainData.push({
                            content: labelEscaped,
                            subtext: labelSubtext,
                            type: 'optgroup-label',
                            optID: optID
                        });

                        headerIndex = liIndex - 1;
                    }

                    if (that.options.hideDisabled && isDisabled || thisData.hidden === true) {
                        liIndex--;
                        return;
                    }

                    textElement = generateText({
                        text: text,
                        optionContent: optionContent,
                        optionSubtext: subtext,
                        optionIcon: icon
                    });

                    mainElements.push(generateLI(generateA(textElement, 'opt ' + optionClass + optGroupClass, inline), index, '', optID));
                    mainData.push({
                        content: optionContent || text,
                        subtext: subtext,
                        tokens: tokens,
                        type: 'option',
                        optID: optID,
                        headerIndex: headerIndex,
                        lastIndex: headerIndex + parent.childElementCount,
                        originalIndex: index,
                        data: thisData
                    });

                    availableOptionsCount++;
                } else if (thisData.divider === true) {
                    mainElements.push(generateLI(false, index, classNames.DIVIDER));
                    mainData.push({
                        type: 'divider',
                        originalIndex: index,
                        data: thisData
                    });
                } else {
                    // if previous element is not an optgroup and hideDisabled is true
                    if (!showDivider && that.options.hideDisabled) {
                        prevHiddenIndex = thisData.prevHiddenIndex;

                        if (prevHiddenIndex !== undefined) {
                            // select the element **before** the first hidden element in the group
                            var prevHidden = $selectOptions[prevHiddenIndex].previousElementSibling;

                            if (prevHidden && prevHidden.tagName === 'OPTGROUP' && !prevHidden.disabled) {
                                showDivider = true;
                            }
                        }
                    }

                    if (showDivider && mainData[mainData.length - 1].type !== 'divider') {
                        liIndex++;
                        mainElements.push(
                            generateLI(
                                false,
                                null,
                                classNames.DIVIDER,
                                optID + 'div'
                            )
                        );
                        mainData.push({
                            type: 'divider',
                            optID: optID
                        });
                    }

                    textElement = generateText({
                        text: text,
                        optionContent: optionContent,
                        optionSubtext: subtext,
                        optionIcon: icon
                    });

                    mainElements.push(generateLI(generateA(textElement, optionClass, inline), index));
                    mainData.push({
                        content: optionContent || text,
                        subtext: subtext,
                        tokens: tokens,
                        type: 'option',
                        originalIndex: index,
                        data: thisData
                    });

                    availableOptionsCount++;
                }

                that.selectpicker.main.map.newIndex[index] = liIndex;
                that.selectpicker.main.map.originalIndex[liIndex] = index;

                // get the most recent option info added to mainData
                var _mainDataLast = mainData[mainData.length - 1];

                _mainDataLast.disabled = isDisabled;

                var combinedLength = 0;

                // count the number of characters in the option - not perfect, but should work in most cases
                if (_mainDataLast.content) combinedLength += _mainDataLast.content.length;
                if (_mainDataLast.subtext) combinedLength += _mainDataLast.subtext.length;
                // if there is an icon, ensure this option's width is checked
                if (icon) combinedLength += 1;

                if (combinedLength > widestOptionLength) {
                    widestOptionLength = combinedLength;

                    // guess which option is the widest
                    // use this when calculating menu width
                    // not perfect, but it's fast, and the width will be updating accordingly when scrolling
                    widestOption = mainElements[mainElements.length - 1];
                }
            });

            this.selectpicker.main.elements = mainElements;
            this.selectpicker.main.data = mainData;

            this.selectpicker.current = this.selectpicker.main;

            this.selectpicker.view.widestOption = widestOption;
            this.selectpicker.view.availableOptionsCount = availableOptionsCount; // faster way to get # of available options without filter
        },

        findLis: function () {
            return this.$menuInner.find('.inner > li');
        },

        render: function () {
            var that = this,
                $selectOptions = this.$element.find('option'),
                selectedItems = [],
                selectedItemsInTitle = [];

            this.togglePlaceholder();

            this.tabIndex();

            for (var i = 0, len = this.selectpicker.main.elements.length; i < len; i++) {
                var index = this.selectpicker.main.map.originalIndex[i],
                    option = $selectOptions[index];

                if (option && option.selected) {
                    selectedItems.push(option);

                    if (selectedItemsInTitle.length < 100 && that.options.selectedTextFormat !== 'count' || selectedItems.length === 1) {
                        if (that.options.hideDisabled && (option.disabled || option.parentNode.tagName === 'OPTGROUP' && option.parentNode.disabled)) return;

                        var thisData = this.selectpicker.main.data[i].data,
                            icon = thisData.icon && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + thisData.icon + '"></i> ' : '',
                            subtext,
                            titleItem;

                        if (that.options.showSubtext && thisData.subtext && !that.multiple) {
                            subtext = ' <small class="text-muted">' + thisData.subtext + '</small>';
                        } else {
                            subtext = '';
                        }

                        if (option.title) {
                            titleItem = option.title;
                        } else if (thisData.content && that.options.showContent) {
                            titleItem = thisData.content.toString();
                        } else {
                            titleItem = icon + option.innerHTML.trim() + subtext;
                        }

                        selectedItemsInTitle.push(titleItem);
                    }
                }
            }

            //Fixes issue in IE10 occurring when no default option is selected and at least one option is disabled
            //Convert all the values into a comma delimited string
            var title = !this.multiple ? selectedItemsInTitle[0] : selectedItemsInTitle.join(this.options.multipleSeparator);

            // add ellipsis
            if (selectedItems.length > 50) title += '...';

            // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected etc..
            if (this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1) {
                var max = this.options.selectedTextFormat.split('>');

                if ((max.length > 1 && selectedItems.length > max[1]) || (max.length === 1 && selectedItems.length >= 2)) {
                    var totalCount = this.selectpicker.view.availableOptionsCount,
                        tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedItems.length, totalCount) : this.options.countSelectedText;

                    title = tr8nText.replace('{0}', selectedItems.length.toString()).replace('{1}', totalCount.toString());
                }
            }

            if (this.options.title == undefined) {
                // use .attr to ensure undefined is returned if title attribute is not set
                this.options.title = this.$element.attr('title');
            }

            if (this.options.selectedTextFormat == 'static') {
                title = this.options.title;
            }

            //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
            if (!title) {
                title = typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText;
            }

            //strip all HTML tags and trim the result, then unescape any escaped tags
            this.$button[0].title = htmlUnescape(title.replace(/<[^>]*>?/g, '').trim());
            this.$button.find('.filter-option-inner-inner')[0].innerHTML = title;

            this.$element.trigger('rendered.bs.select');
        },

        /**
         * @param [style]
         * @param [status]
         */
        setStyle: function (style, status) {
            if (this.$element.attr('class')) {
                this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
            }

            var buttonClass = style ? style : this.options.style;

            if (status == 'add') {
                this.$button.addClass(buttonClass);
            } else if (status == 'remove') {
                this.$button.removeClass(buttonClass);
            } else {
                this.$button.removeClass(this.options.style);
                this.$button.addClass(buttonClass);
            }
        },

        liHeight: function (refresh) {
            if (!refresh && (this.options.size === false || this.sizeInfo)) return;

            if (!this.sizeInfo) this.sizeInfo = {};

            var newElement = document.createElement('div'),
                menu = document.createElement('div'),
                menuInner = document.createElement('div'),
                menuInnerInner = document.createElement('ul'),
                divider = document.createElement('li'),
                dropdownHeader = document.createElement('li'),
                li = document.createElement('li'),
                a = document.createElement('a'),
                text = document.createElement('span'),
                header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null,
                search = this.options.liveSearch ? document.createElement('div') : null,
                actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
                doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null;

            this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth;

            text.className = 'text';
            a.className = 'dropdown-item ' + this.$element.find('option')[0].className;
            newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
            newElement.style.width = this.sizeInfo.selectWidth + 'px';
            if (this.options.width === 'auto') menu.style.minWidth = 0;
            menu.className = classNames.MENU + ' ' + classNames.SHOW;
            menuInner.className = 'inner ' + classNames.SHOW;
            menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '');
            divider.className = classNames.DIVIDER;
            dropdownHeader.className = 'dropdown-header';

            text.appendChild(document.createTextNode('Inner text'));
            a.appendChild(text);
            li.appendChild(a);
            dropdownHeader.appendChild(text.cloneNode(true));

            if (this.selectpicker.view.widestOption) {
                menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true));
            }

            menuInnerInner.appendChild(li);
            menuInnerInner.appendChild(divider);
            menuInnerInner.appendChild(dropdownHeader);
            if (header) menu.appendChild(header);
            if (search) {
                var input = document.createElement('input');
                search.className = 'bs-searchbox';
                input.className = 'form-control';
                search.appendChild(input);
                menu.appendChild(search);
            }
            if (actions) menu.appendChild(actions);
            menuInner.appendChild(menuInnerInner);
            menu.appendChild(menuInner);
            if (doneButton) menu.appendChild(doneButton);
            newElement.appendChild(menu);

            document.body.appendChild(newElement);

            var liHeight = a.offsetHeight,
                dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0,
                headerHeight = header ? header.offsetHeight : 0,
                searchHeight = search ? search.offsetHeight : 0,
                actionsHeight = actions ? actions.offsetHeight : 0,
                doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
                dividerHeight = $(divider).outerHeight(true),
                // fall back to jQuery if getComputedStyle is not supported
                menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false,
                menuWidth = menu.offsetWidth,
                $menu = menuStyle ? null : $(menu),
                menuPadding = {
                    vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
                    toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
                    toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
                    toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
                    horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
                    toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
                    toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
                    toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
                },
                menuExtras = {
                    vert: menuPadding.vert +
                    toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
                    toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
                    horiz: menuPadding.horiz +
                    toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
                    toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
                },
                scrollBarWidth;

            menuInner.style.overflowY = 'scroll';

            scrollBarWidth = menu.offsetWidth - menuWidth;

            document.body.removeChild(newElement);

            this.sizeInfo.liHeight = liHeight;
            this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight;
            this.sizeInfo.headerHeight = headerHeight;
            this.sizeInfo.searchHeight = searchHeight;
            this.sizeInfo.actionsHeight = actionsHeight;
            this.sizeInfo.doneButtonHeight = doneButtonHeight;
            this.sizeInfo.dividerHeight = dividerHeight;
            this.sizeInfo.menuPadding = menuPadding;
            this.sizeInfo.menuExtras = menuExtras;
            this.sizeInfo.menuWidth = menuWidth;
            this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth;
            this.sizeInfo.scrollBarWidth = scrollBarWidth;
            this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight;

            this.setPositionData();
        },

        getSelectPosition: function () {
            var that = this,
                $window = $(window),
                pos = that.$newElement.offset(),
                $container = $(that.options.container),
                containerPos;

            if (that.options.container && !$container.is('body')) {
                containerPos = $container.offset();
                containerPos.top += parseInt($container.css('borderTopWidth'));
                containerPos.left += parseInt($container.css('borderLeftWidth'));
            } else {
                containerPos = {top: 0, left: 0};
            }

            var winPad = that.options.windowPadding;

            this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
            this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo['selectHeight'] - containerPos.top - winPad[2];
            this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
            this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo['selectWidth'] - containerPos.left - winPad[1];
            this.sizeInfo.selectOffsetTop -= winPad[0];
            this.sizeInfo.selectOffsetLeft -= winPad[3];
        },

        setMenuSize: function (isAuto) {
            this.getSelectPosition();

            var selectWidth = this.sizeInfo['selectWidth'],
                liHeight = this.sizeInfo['liHeight'],
                headerHeight = this.sizeInfo['headerHeight'],
                searchHeight = this.sizeInfo['searchHeight'],
                actionsHeight = this.sizeInfo['actionsHeight'],
                doneButtonHeight = this.sizeInfo['doneButtonHeight'],
                divHeight = this.sizeInfo['dividerHeight'],
                menuPadding = this.sizeInfo['menuPadding'],
                menuInnerHeight,
                menuHeight,
                divLength = 0,
                minHeight,
                _minHeight,
                maxHeight,
                menuInnerMinHeight,
                estimate;

            if (this.options.dropupAuto) {
                // Get the estimated height of the menu without scrollbars.
                // This is useful for smaller menus, where there might be plenty of room
                // below the button without setting dropup, but we can't know
                // the exact height of the menu until createView is called later
                estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert;
                this.$newElement.toggleClass(classNames.DROPUP, this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot);
            }

            if (this.options.size === 'auto') {
                _minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0;
                menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert;
                minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
                menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0);

                if (this.$newElement.hasClass(classNames.DROPUP)) {
                    menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert;
                }

                maxHeight = menuHeight;
                menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert;
            } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
                for (var i = 0; i < this.options.size; i++) {
                    if (this.selectpicker.current.data[i].type === 'divider') divLength++;
                }

                menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
                menuInnerHeight = menuHeight - menuPadding.vert;
                maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
                minHeight = menuInnerMinHeight = '';
            }

            if (this.options.dropdownAlignRight === 'auto') {
                this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.$menu[0].offsetWidth - selectWidth));
            }

            this.$menu.css({
                'max-height': maxHeight + 'px',
                'overflow': 'hidden',
                'min-height': minHeight + 'px'
            });

            this.$menuInner.css({
                'max-height': menuInnerHeight + 'px',
                'overflow-y': 'auto',
                'min-height': menuInnerMinHeight + 'px'
            });

            this.sizeInfo['menuInnerHeight'] = menuInnerHeight;

            if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) {
                this.sizeInfo.hasScrollBar = true;
                this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth;

                this.$menu.css('min-width', this.sizeInfo.totalMenuWidth);
            }

            if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update();
        },

        setSize: function (refresh) {
            this.liHeight(refresh);

            if (this.options.header) this.$menu.css('padding-top', 0);
            if (this.options.size === false) return;

            var that = this,
                $window = $(window),
                selectedIndex,
                offset = 0;

            this.setMenuSize();

            if (this.options.size === 'auto') {
                this.$searchbox.off('input.setMenuSize propertychange.setMenuSize').on('input.setMenuSize propertychange.setMenuSize', function () {
                    return that.setMenuSize();
                });
                $window.off('resize.setMenuSize scroll.setMenuSize').on('resize.setMenuSize scroll.setMenuSize', function () {
                    return that.setMenuSize();
                });
            } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
                this.$searchbox.off('input.setMenuSize propertychange.setMenuSize');
                $window.off('resize.setMenuSize scroll.setMenuSize');
            }

            if (refresh) {
                offset = this.$menuInner[0].scrollTop;
            } else if (!that.multiple) {
                selectedIndex = that.selectpicker.main.map.newIndex[that.$element[0].selectedIndex];

                if (typeof selectedIndex === 'number' && that.options.size !== false) {
                    offset = that.sizeInfo.liHeight * selectedIndex;
                    offset = offset - (that.sizeInfo.menuInnerHeight / 2) + (that.sizeInfo.liHeight / 2);
                }
            }

            that.createView(false, offset);
        },

        setWidth: function () {
            var that = this;

            if (this.options.width === 'auto') {
                requestAnimationFrame(function () {
                    that.$menu.css('min-width', '0');
                    that.liHeight();
                    that.setMenuSize();

                    // Get correct width if element is hidden
                    var $selectClone = that.$newElement.clone().appendTo('body'),
                        btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth();

                    $selectClone.remove();

                    // Set width to whatever's larger, button title or longest option
                    that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth);
                    that.$newElement.css('width', that.sizeInfo.selectWidth + 'px');
                });
            } else if (this.options.width === 'fit') {
                // Remove inline min-width so width can be changed from 'auto'
                this.$menu.css('min-width', '');
                this.$newElement.css('width', '').addClass('fit-width');
            } else if (this.options.width) {
                // Remove inline min-width so width can be changed from 'auto'
                this.$menu.css('min-width', '');
                this.$newElement.css('width', this.options.width);
            } else {
                // Remove inline min-width/width so width can be changed
                this.$menu.css('min-width', '');
                this.$newElement.css('width', '');
            }
            // Remove fit-width class if width is changed programmatically
            if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
                this.$newElement.removeClass('fit-width');
            }
        },

        selectPosition: function () {
            this.$bsContainer = $('<div class="bs-container" />');

            var that = this,
                $container = $(this.options.container),
                pos,
                containerPos,
                actualHeight,
                getPlacement = function ($element) {
                    var containerPosition = {},
                        // fall back to dropdown's default display setting if display is not manually set
                        display = that.options.display || $.fn.dropdown.Constructor.Default.display;

                    that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP));
                    pos = $element.offset();

                    if (!$container.is('body')) {

                        containerPos = $container.offset();
                        containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
                        containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
                    } else {
                        containerPos = {top: 0, left: 0};
                    }

                    actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight;

                    // Bootstrap 4+ uses Popper for menu positioning
                    if (version.major < 4 || display === 'static') {
                        containerPosition['top'] = pos.top - containerPos.top + actualHeight;
                        containerPosition['left'] = pos.left - containerPos.left;
                    }

                    containerPosition['width'] = $element[0].offsetWidth;

                    that.$bsContainer.css(containerPosition);
                };

            this.$button.on('click.bs.dropdown.data-api', function () {
                if (that.isDisabled()) {
                    return;
                }

                getPlacement(that.$newElement);

                that.$bsContainer
                    .appendTo(that.options.container)
                    .toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW))
                    .append(that.$menu);
            });

            $(window).on('resize scroll', function () {
                getPlacement(that.$newElement);
            });

            this.$element.on('hide.bs.select', function () {
                that.$menu.data('height', that.$menu.height());
                that.$bsContainer.detach();
            });
        },

        setOptionStatus: function () {
            var that = this,
                $selectOptions = this.$element.find('option');

            that.noScroll = false;

            if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) {
                for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) {
                    var index = that.selectpicker.current.map.originalIndex[i + that.selectpicker.view.position0], // faster than $(li).data('originalIndex')
                        option = $selectOptions[index];

                    if (option) {
                        var liIndex = this.selectpicker.main.map.newIndex[index],
                            li = this.selectpicker.main.elements[liIndex];

                        that.setDisabled(
                            index,
                            option.disabled || option.parentNode.tagName === 'OPTGROUP' && option.parentNode.disabled,
                            liIndex,
                            li
                        );

                        that.setSelected(
                            index,
                            option.selected,
                            liIndex,
                            li
                        );
                    }
                }
            }
        },

        /**
         * @param {number} index - the index of the option that is being changed
         * @param {boolean} selected - true if the option is being selected, false if being deselected
         */
        setSelected: function (index, selected, liIndex, li) {
            var activeIndexIsSet = this.activeIndex !== undefined,
                thisIsActive = this.activeIndex === index,
                prevActiveIndex,
                prevActive,
                a,
                // if current option is already active
                // OR
                // if the current option is being selected, it's NOT multiple, and
                // activeIndex is undefined:
                //  - when the menu is first being opened, OR
                //  - after a search has been performed, OR
                //  - when retainActive is false when selecting a new option (i.e. index of the newly selected option is not the same as the current activeIndex)
                keepActive = thisIsActive || selected && !this.multiple && !activeIndexIsSet;

            if (!liIndex) liIndex = this.selectpicker.main.map.newIndex[index];
            if (!li) li = this.selectpicker.main.elements[liIndex];

            a = li.firstChild;

            if (selected) {
                this.selectedIndex = index;
            }

            li.classList.toggle('selected', selected);
            li.classList.toggle('active', keepActive);

            if (keepActive) {
                this.selectpicker.view.currentActive = li;
                this.activeIndex = index;
            }

            if (a) {
                a.classList.toggle('selected', selected);
                a.classList.toggle('active', keepActive);
                a.setAttribute('aria-selected', selected);
            }

            if (!keepActive) {
                if (!activeIndexIsSet && selected && this.prevActiveIndex !== undefined) {
                    prevActiveIndex = this.selectpicker.main.map.newIndex[this.prevActiveIndex];
                    prevActive = this.selectpicker.main.elements[prevActiveIndex];

                    prevActive.classList.toggle('selected', selected);
                    prevActive.classList.remove('active');
                    if (prevActive.firstChild) {
                        prevActive.firstChild.classList.toggle('selected', selected);
                        prevActive.firstChild.classList.remove('active');
                    }
                }
            }
        },

        /**
         * @param {number} index - the index of the option that is being disabled
         * @param {boolean} disabled - true if the option is being disabled, false if being enabled
         */
        setDisabled: function (index, disabled, liIndex, li) {
            var a;

            if (!liIndex) liIndex = this.selectpicker.main.map.newIndex[index];
            if (!li) li = this.selectpicker.main.elements[liIndex];

            a = li.firstChild;

            li.classList.toggle(classNames.DISABLED, disabled);

            if (a) {
                if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled);

                a.setAttribute('aria-disabled', disabled);

                if (disabled) {
                    a.setAttribute('tabindex', -1);
                } else {
                    a.setAttribute('tabindex', 0);
                }
            }
        },

        isDisabled: function () {
            return this.$element[0].disabled;
        },

        checkDisabled: function () {
            var that = this;

            if (this.isDisabled()) {
                this.$newElement.addClass(classNames.DISABLED);
                this.$button.addClass(classNames.DISABLED).attr('tabindex', -1).attr('aria-disabled', true);
            } else {
                if (this.$button.hasClass(classNames.DISABLED)) {
                    this.$newElement.removeClass(classNames.DISABLED);
                    this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false);
                }

                if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
                    this.$button.removeAttr('tabindex');
                }
            }

            this.$button.click(function () {
                return !that.isDisabled();
            });
        },

        togglePlaceholder: function () {
            // much faster than calling $.val()
            var element = this.$element[0],
                selectedIndex = element.selectedIndex,
                nothingSelected = selectedIndex === -1;

            if (!nothingSelected && !element.options[selectedIndex].value) nothingSelected = true;

            this.$button.toggleClass('bs-placeholder', nothingSelected);
        },

        tabIndex: function () {
            if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
                (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
                this.$element.data('tabindex', this.$element.attr('tabindex'));
                this.$button.attr('tabindex', this.$element.data('tabindex'));
            }

            this.$element.attr('tabindex', -98);
        },

        clickListener: function () {

            var that = this,
                $document = $(document);

            $document.data('spaceSelect', false);

            this.$button.on('keyup', function (e) {
                if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
                    e.preventDefault();
                    $document.data('spaceSelect', false);
                }
            });

            this.$newElement.on('show.bs.dropdown', function () {
                if (version.major > 3 && !that.dropdown) {
                    that.dropdown = that.$button.data('bs.dropdown');
                    that.dropdown._menu = that.$menu[0];
                }
            });

            this.$button.on('click.bs.dropdown.data-api', function () {

                if (!that.$newElement.hasClass(classNames.SHOW)) {
                    that.setSize();
                }
            });

            function setFocus() {
                if (that.options.liveSearch) {
                    that.$searchbox.focus();
                } else {
                    that.$menuInner.focus();
                }
            }

            function checkPopperExists() {
                if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) {
                    setFocus();
                } else {
                    requestAnimationFrame(checkPopperExists);
                }
            }

            this.$element.on('shown.bs.select', function () {
                if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) {
                    that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop;
                }

                if (version.major > 3) {
                    requestAnimationFrame(checkPopperExists);
                } else {
                    setFocus();
                }
            });

            this.$menuInner.on('click', 'li a', function (e, retainActive) {
                var $this = $(this),
                    position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
                    clickedIndex = that.selectpicker.current.map.originalIndex[$this.parent().index() + position0],
                    prevValue = getSelectValues(that.$element[0]),
                    prevIndex = that.$element.prop('selectedIndex'),
                    triggerChange = true;

                // Don't close on multi choice menu
                if (that.multiple && that.options.maxOptions !== 1) {
                    e.stopPropagation();
                }

                e.preventDefault();

                //Don't run if we have been disabled
                if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) {
                    var $options = that.$element.find('option'),
                        $option = $options.eq(clickedIndex),
                        state = $option.prop('selected'),
                        $optgroup = $option.parent('optgroup'),
                        $optgroupOptions = $optgroup.find('option'),
                        maxOptions = that.options.maxOptions,
                        maxOptionsGrp = $optgroup.data('maxOptions') || false;

                    if (clickedIndex === that.activeIndex) retainActive = true;

                    if (!retainActive) {
                        that.prevActiveIndex = that.activeIndex;
                        that.activeIndex = undefined;
                    }

                    if (!that.multiple) { // Deselect all others if not multi select box
                        $options.prop('selected', false);
                        $option.prop('selected', true);
                        that.setSelected(clickedIndex, true);
                    } else { // Toggle the one we have chosen if we are multi select.
                        $option.prop('selected', !state);

                        that.setSelected(clickedIndex, !state);
                        $this.blur();

                        if (maxOptions !== false || maxOptionsGrp !== false) {
                            var maxReached = maxOptions < $options.filter(':selected').length,
                                maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;

                            if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
                                if (maxOptions && maxOptions == 1) {
                                    $options.prop('selected', false);
                                    $option.prop('selected', true);

                                    for (var i = 0; i < $options.length; i++) {
                                        that.setSelected(i, false);
                                    }

                                    that.setSelected(clickedIndex, true);
                                } else if (maxOptionsGrp && maxOptionsGrp == 1) {
                                    $optgroup.find('option:selected').prop('selected', false);
                                    $option.prop('selected', true);

                                    for (var i = 0; i < $optgroupOptions.length; i++) {
                                        var option = $optgroupOptions[i];
                                        that.setSelected($options.index(option), false);
                                    }

                                    that.setSelected(clickedIndex, true);
                                } else {
                                    var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
                                        maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
                                        maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
                                        maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
                                        $notify = $('<div class="notify"></div>');
                                    // If {var} is set in array, replace it
                                    /** @deprecated */
                                    if (maxOptionsArr[2]) {
                                        maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
                                        maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
                                    }

                                    $option.prop('selected', false);

                                    that.$menu.append($notify);

                                    if (maxOptions && maxReached) {
                                        $notify.append($('<div>' + maxTxt + '</div>'));
                                        triggerChange = false;
                                        that.$element.trigger('maxReached.bs.select');
                                    }

                                    if (maxOptionsGrp && maxReachedGrp) {
                                        $notify.append($('<div>' + maxTxtGrp + '</div>'));
                                        triggerChange = false;
                                        that.$element.trigger('maxReachedGrp.bs.select');
                                    }

                                    setTimeout(function () {
                                        that.setSelected(clickedIndex, false);
                                    }, 10);

                                    $notify.delay(750).fadeOut(300, function () {
                                        $(this).remove();
                                    });
                                }
                            }
                        }
                    }

                    if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
                        that.$button.focus();
                    } else if (that.options.liveSearch) {
                        that.$searchbox.focus();
                    }

                    // Trigger select 'change'
                    if (triggerChange) {
                        if ((prevValue != getSelectValues(that.$element[0]) && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
                            // $option.prop('selected') is current option state (selected/unselected). prevValue is the value of the select prior to being changed.
                            changed_arguments = [clickedIndex, $option.prop('selected'), prevValue];
                            that.$element
                                .triggerNative('change');
                        }
                    }
                }
            });

            this.$menu.on('click', 'li.' + classNames.DISABLED + ' a, .' + classNames.POPOVERHEADER + ', .' + classNames.POPOVERHEADER + ' :not(.close)', function (e) {
                if (e.currentTarget == this) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (that.options.liveSearch && !$(e.target).hasClass('close')) {
                        that.$searchbox.focus();
                    } else {
                        that.$button.focus();
                    }
                }
            });

            this.$menuInner.on('click', '.divider, .dropdown-header', function (e) {
                e.preventDefault();
                e.stopPropagation();
                if (that.options.liveSearch) {
                    that.$searchbox.focus();
                } else {
                    that.$button.focus();
                }
            });

            this.$menu.on('click', '.' + classNames.POPOVERHEADER + ' .close', function () {
                that.$button.click();
            });

            this.$searchbox.on('click', function (e) {
                e.stopPropagation();
            });

            this.$menu.on('click', '.actions-btn', function (e) {
                if (that.options.liveSearch) {
                    that.$searchbox.focus();
                } else {
                    that.$button.focus();
                }

                e.preventDefault();
                e.stopPropagation();

                if ($(this).hasClass('bs-select-all')) {
                    that.selectAll();
                } else {
                    that.deselectAll();
                }
            });

            this.$element.on({
                'change': function () {
                    that.render();
                    that.$element.trigger('changed.bs.select', changed_arguments);
                    changed_arguments = null;
                },
                'focus': function () {
                    that.$button.focus();
                }
            });
        },

        liveSearchListener: function () {
            var that = this,
                no_results = document.createElement('li');

            this.$button.on('click.bs.dropdown.data-api', function () {
                if (!!that.$searchbox.val()) {
                    that.$searchbox.val('');
                }
            });

            this.$searchbox.on('click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api', function (e) {
                e.stopPropagation();
            });

            this.$searchbox.on('input propertychange', function () {
                var searchValue = that.$searchbox.val();

                that.selectpicker.search.map.newIndex = {};
                that.selectpicker.search.map.originalIndex = {};
                that.selectpicker.search.elements = [];
                that.selectpicker.search.data = [];

                if (searchValue) {
                    var i,
                        searchMatch = [],
                        q = searchValue.toUpperCase(),
                        cache = {},
                        cacheArr = [],
                        searchStyle = that._searchStyle(),
                        normalizeSearch = that.options.liveSearchNormalize;

                    that._$lisSelected = that.$menuInner.find('.selected');

                    for (var i = 0; i < that.selectpicker.main.data.length; i++) {
                        var li = that.selectpicker.main.data[i];

                        if (!cache[i]) {
                            cache[i] = stringSearch(li, q, searchStyle, normalizeSearch);
                        }

                        if (cache[i] && li.headerIndex !== undefined && cacheArr.indexOf(li.headerIndex) === -1) {
                            if (li.headerIndex > 0) {
                                cache[li.headerIndex - 1] = true;
                                cacheArr.push(li.headerIndex - 1);
                            }

                            cache[li.headerIndex] = true;
                            cacheArr.push(li.headerIndex);

                            cache[li.lastIndex + 1] = true;
                        }

                        if (cache[i] && li.type !== 'optgroup-label') cacheArr.push(i);
                    }

                    for (var i = 0, cacheLen = cacheArr.length; i < cacheLen; i++) {
                        var index = cacheArr[i],
                            prevIndex = cacheArr[i - 1],
                            li = that.selectpicker.main.data[index],
                            liPrev = that.selectpicker.main.data[prevIndex];

                        if (li.type !== 'divider' || (li.type === 'divider' && liPrev && liPrev.type !== 'divider' && cacheLen - 1 !== i)) {
                            that.selectpicker.search.data.push(li);
                            searchMatch.push(that.selectpicker.main.elements[index]);

                            if (li.hasOwnProperty('originalIndex')) {
                                that.selectpicker.search.map.newIndex[li.originalIndex] = searchMatch.length - 1;
                                that.selectpicker.search.map.originalIndex[searchMatch.length - 1] = li.originalIndex;
                            }
                        }
                    }

                    that.activeIndex = undefined;
                    that.noScroll = true;
                    that.$menuInner.scrollTop(0);
                    that.selectpicker.search.elements = searchMatch;
                    that.createView(true);

                    if (!searchMatch.length) {
                        no_results.className = 'no-results';
                        no_results.innerHTML = that.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"');
                        that.$menuInner[0].firstChild.appendChild(no_results);
                    }
                } else {
                    that.$menuInner.scrollTop(0);
                    that.createView(false);
                }
            });
        },

        _searchStyle: function () {
            return this.options.liveSearchStyle || 'contains';
        },

        val: function (value) {
            if (typeof value !== 'undefined') {
                this.$element
                    .val(value)
                    .triggerNative('change');

                return this.$element;
            } else {
                return this.$element.val();
            }
        },

        changeAll: function (status) {
            if (!this.multiple) return;
            if (typeof status === 'undefined') status = true;

            var $selectOptions = this.$element.find('option'),
                previousSelected = 0,
                currentSelected = 0,
                prevValue = getSelectValues(this.$element[0]);

            this.$element.addClass('bs-select-hidden');

            for (var i = 0; i < this.selectpicker.current.elements.length; i++) {
                var liData = this.selectpicker.current.data[i],
                    index = this.selectpicker.current.map.originalIndex[i], // faster than $(li).data('originalIndex')
                    option = $selectOptions[index];

                if (option && !option.disabled && liData.type !== 'divider') {
                    if (option.selected) previousSelected++;
                    option.selected = status;
                    if (option.selected) currentSelected++;
                }
            }

            this.$element.removeClass('bs-select-hidden');

            if (previousSelected === currentSelected) return;

            this.setOptionStatus();

            this.togglePlaceholder();

            changed_arguments = [null, null, prevValue];

            this.$element
                .triggerNative('change');
        },

        selectAll: function () {
            return this.changeAll(true);
        },

        deselectAll: function () {
            return this.changeAll(false);
        },

        toggle: function (e) {
            e = e || window.event;

            if (e) e.stopPropagation();

            this.$button.trigger('click.bs.dropdown.data-api');
        },

        keydown: function (e) {
            var $this = $(this),
                isToggle = $this.hasClass('dropdown-toggle'),
                $parent = isToggle ? $this.closest('.dropdown') : $this.closest(Selector.MENU),
                that = $parent.data('this'),
                $items = that.findLis(),
                index,
                isActive,
                liActive,
                activeLi,
                offset,
                updateScroll = false,
                downOnTab = e.which === keyCodes.TAB && !isToggle && !that.options.selectOnTab,
                isArrowKey = REGEXP_ARROW.test(e.which) || downOnTab,
                scrollTop = that.$menuInner[0].scrollTop,
                isVirtual = that.isVirtual(),
                position0 = isVirtual === true ? that.selectpicker.view.position0 : 0;

            isActive = that.$newElement.hasClass(classNames.SHOW);

            if (
                !isActive &&
                (
                    isArrowKey ||
                    e.which >= 48 && e.which <= 57 ||
                    e.which >= 96 && e.which <= 105 ||
                    e.which >= 65 && e.which <= 90
                )
            ) {
                that.$button.trigger('click.bs.dropdown.data-api');
            }

            if (e.which === keyCodes.ESCAPE && isActive) {
                e.preventDefault();
                that.$button.trigger('click.bs.dropdown.data-api').focus();
            }

            if (isArrowKey) { // if up or down
                if (!$items.length) return;

                // $items.index/.filter is too slow with a large list and no virtual scroll
                index = isVirtual === true ? $items.index($items.filter('.active')) : that.selectpicker.current.map.newIndex[that.activeIndex];

                if (index === undefined) index = -1;

                if (index !== -1) {
                    liActive = that.selectpicker.current.elements[index + position0];
                    liActive.classList.remove('active');
                    if (liActive.firstChild) liActive.firstChild.classList.remove('active');
                }

                if (e.which === keyCodes.ARROW_UP) { // up
                    if (index !== -1) index--;
                    if (index + position0 < 0) index += $items.length;

                    if (!that.selectpicker.view.canHighlight[index + position0]) {
                        index = that.selectpicker.view.canHighlight.slice(0, index + position0).lastIndexOf(true) - position0;
                        if (index === -1) index = $items.length - 1;
                    }
                } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
                    index++;
                    if (index + position0 >= that.selectpicker.view.canHighlight.length) index = 0;

                    if (!that.selectpicker.view.canHighlight[index + position0]) {
                        index = index + 1 + that.selectpicker.view.canHighlight.slice(index + position0 + 1).indexOf(true);
                    }
                }

                e.preventDefault();

                var liActiveIndex = position0 + index;

                if (e.which === keyCodes.ARROW_UP) { // up
                    // scroll to bottom and highlight last option
                    if (position0 === 0 && index === $items.length - 1) {
                        that.$menuInner[0].scrollTop = that.$menuInner[0].scrollHeight;

                        liActiveIndex = that.selectpicker.current.elements.length - 1;
                    } else {
                        activeLi = that.selectpicker.current.data[liActiveIndex];
                        offset = activeLi.position - activeLi.height;

                        updateScroll = offset < scrollTop;
                    }
                } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
                    // scroll to top and highlight first option
                    if (index === 0) {
                        that.$menuInner[0].scrollTop = 0;

                        liActiveIndex = 0;
                    } else {
                        activeLi = that.selectpicker.current.data[liActiveIndex];
                        offset = activeLi.position - that.sizeInfo.menuInnerHeight;

                        updateScroll = offset > scrollTop;
                    }
                }

                liActive = that.selectpicker.current.elements[liActiveIndex];

                if (liActive) {
                    liActive.classList.add('active');
                    if (liActive.firstChild) liActive.firstChild.classList.add('active');
                }

                that.activeIndex = that.selectpicker.current.map.originalIndex[liActiveIndex];

                that.selectpicker.view.currentActive = liActive;

                if (updateScroll) that.$menuInner[0].scrollTop = offset;

                if (that.options.liveSearch) {
                    that.$searchbox.focus();
                } else {
                    $this.focus();
                }
            } else if (
                !$this.is('input') &&
                !REGEXP_TAB_OR_ESCAPE.test(e.which) ||
                (e.which === keyCodes.SPACE && that.selectpicker.keydown.keyHistory)
            ) {
                var searchMatch,
                    matches = [],
                    keyHistory;

                e.preventDefault();

                that.selectpicker.keydown.keyHistory += keyCodeMap[e.which];

                if (that.selectpicker.keydown.resetKeyHistory.cancel) clearTimeout(that.selectpicker.keydown.resetKeyHistory.cancel);
                that.selectpicker.keydown.resetKeyHistory.cancel = that.selectpicker.keydown.resetKeyHistory.start();

                keyHistory = that.selectpicker.keydown.keyHistory;

                // if all letters are the same, set keyHistory to just the first character when searching
                if (/^(.)\1+$/.test(keyHistory)) {
                    keyHistory = keyHistory.charAt(0);
                }

                // find matches
                for (var i = 0; i < that.selectpicker.current.data.length; i++) {
                    var li = that.selectpicker.current.data[i],
                        hasMatch;

                    hasMatch = stringSearch(li, keyHistory, 'startsWith', true);

                    if (hasMatch && that.selectpicker.view.canHighlight[i]) {
                        li.index = i;
                        matches.push(li.originalIndex);
                    }
                }

                if (matches.length) {
                    var matchIndex = 0;

                    $items.removeClass('active').find('a').removeClass('active');

                    // either only one key has been pressed or they are all the same key
                    if (keyHistory.length === 1) {
                        matchIndex = matches.indexOf(that.activeIndex);

                        if (matchIndex === -1 || matchIndex === matches.length - 1) {
                            matchIndex = 0;
                        } else {
                            matchIndex++;
                        }
                    }

                    searchMatch = that.selectpicker.current.map.newIndex[matches[matchIndex]];

                    activeLi = that.selectpicker.current.data[searchMatch];

                    if (scrollTop - activeLi.position > 0) {
                        offset = activeLi.position - activeLi.height;
                        updateScroll = true;
                    } else {
                        offset = activeLi.position - that.sizeInfo.menuInnerHeight;
                        // if the option is already visible at the current scroll position, just keep it the same
                        updateScroll = activeLi.position > scrollTop + that.sizeInfo.menuInnerHeight;
                    }

                    liActive = that.selectpicker.current.elements[searchMatch];
                    liActive.classList.add('active');
                    if (liActive.firstChild) liActive.firstChild.classList.add('active');
                    that.activeIndex = matches[matchIndex];

                    liActive.firstChild.focus();

                    if (updateScroll) that.$menuInner[0].scrollTop = offset;

                    $this.focus();
                }
            }

            // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
            if (
                isActive &&
                (
                    (e.which === keyCodes.SPACE && !that.selectpicker.keydown.keyHistory) ||
                    e.which === keyCodes.ENTER ||
                    (e.which === keyCodes.TAB && that.options.selectOnTab)
                )
            ) {
                if (e.which !== keyCodes.SPACE) e.preventDefault();

                if (!that.options.liveSearch || e.which !== keyCodes.SPACE) {
                    that.$menuInner.find('.active a').trigger('click', true); // retain active class
                    $this.focus();

                    if (!that.options.liveSearch) {
                        // Prevent screen from scrolling if the user hits the spacebar
                        e.preventDefault();
                        // Fixes spacebar selection of dropdown items in FF & IE
                        $(document).data('spaceSelect', true);
                    }
                }
            }
        },

        mobile: function () {
            this.$element.addClass('mobile-device');
        },

        refresh: function () {
            // update options if data attributes have been changed
            var config = $.extend({}, this.options, this.$element.data());
            this.options = config;

            this.selectpicker.main.map.newIndex = {};
            this.selectpicker.main.map.originalIndex = {};
            this.createLi();
            this.checkDisabled();
            this.render();
            this.setStyle();
            this.setWidth();

            this.setSize(true);

            this.$element.trigger('refreshed.bs.select');
        },

        hide: function () {
            this.$newElement.hide();
        },

        show: function () {
            this.$newElement.show();
        },

        remove: function () {
            this.$newElement.remove();
            this.$element.remove();
        },

        destroy: function () {
            this.$newElement.before(this.$element).remove();

            if (this.$bsContainer) {
                this.$bsContainer.remove();
            } else {
                this.$menu.remove();
            }

            this.$element
                .off('.bs.select')
                .removeData('selectpicker')
                .removeClass('bs-select-hidden selectpicker');
        }
    };

    // SELECTPICKER PLUGIN DEFINITION
    // ==============================
    function Plugin(option) {
        // get the args of the outer function..
        var args = arguments;
        // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
        // to get lost/corrupted in android 2.3 and IE9 #715 #775
        var _option = option;

        [].shift.apply(args);

        // if the version was not set successfully
        if (!version.success) {
            // try to retreive it again
            try {
                version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
            }
                // fall back to use BootstrapVersion
            catch (err) {
                version.full = Selectpicker.BootstrapVersion.split(' ')[0].split('.');
            }

            version.major = version.full[0];
            version.success = true;

            if (version.major === '4') {
                classNames.DIVIDER = 'dropdown-divider';
                classNames.SHOW = 'show';
                classNames.BUTTONCLASS = 'btn-light';
                Selectpicker.DEFAULTS.style = classNames.BUTTONCLASS = 'btn-light';
                classNames.POPOVERHEADER = 'popover-header';
            }
        }

        var value;
        var chain = this.each(function () {
            var $this = $(this);
            if ($this.is('select')) {
                var data = $this.data('selectpicker'),
                    options = typeof _option == 'object' && _option;

                if (!data) {
                    var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, $this.data(), options);
                    config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), $this.data().template, options.template);
                    $this.data('selectpicker', (data = new Selectpicker(this, config)));
                } else if (options) {
                    for (var i in options) {
                        if (options.hasOwnProperty(i)) {
                            data.options[i] = options[i];
                        }
                    }
                }

                if (typeof _option == 'string') {
                    if (data[_option] instanceof Function) {
                        value = data[_option].apply(data, args);
                    } else {
                        value = data.options[_option];
                    }
                }
            }
        });

        if (typeof value !== 'undefined') {
            //noinspection JSUnusedAssignment
            return value;
        } else {
            return chain;
        }
    }

    var old = $.fn.selectpicker;
    $.fn.selectpicker = Plugin;
    $.fn.selectpicker.Constructor = Selectpicker;

    // SELECTPICKER NO CONFLICT
    // ========================
    $.fn.selectpicker.noConflict = function () {
        $.fn.selectpicker = old;
        return this;
    };

    $(document)
        .off('keydown.bs.dropdown.data-api')
        .on('keydown.bs.select', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bs-searchbox input', Selectpicker.prototype.keydown)
        .on('focusin.modal', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bs-searchbox input', function (e) {
            e.stopPropagation();
        });

    // SELECTPICKER DATA-API
    // =====================
    $(window).on('load.bs.select.data-api', function () {
        $('.selectpicker').each(function () {
            var $selectpicker = $(this);
            Plugin.call($selectpicker, $selectpicker.data());
        })
    });
})(jQuery);


$(function () {
    $('.selectpicker').on('hide.bs.select', function () {
        $(this).next().find(".bs-caret").find("img").toggleClass(" rotate-arrow-accordion");



        if ($(this).attr("id") === "news-type-search") {

            /*if ($(this).val() === "Archivio") {
                $(".container-header-news .title").addClass("hidden");
                $(".container-header-news .date-filter").removeClass("hidden");
            } else {
                $(".container-header-news .title").removeClass("hidden");
                $(".container-header-news .date-filter").addClass("hidden");
            }*/
        }
    });

    $('.selectpicker').on('show.bs.select', function () {
        $(this).next().find(".bs-caret").find("img").toggleClass(" rotate-arrow-accordion");
    });


});
$("#news-type-search").selectpicker('render');
/*!
 * Datepicker for Bootstrap v1.6.4 (https://github.com/eternicode/bootstrap-datepicker)
 *
 * Copyright 2012 Stefan Petre
 * Improvements by Andrew Rowls
 * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 */
! function(a) {
    "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : jQuery)
}(function(a, b) {
    function c() {
        return new Date(Date.UTC.apply(Date, arguments))
    }

    function d() {
        var a = new Date;
        return c(a.getFullYear(), a.getMonth(), a.getDate())
    }

    function e(a, b) {
        return a.getUTCFullYear() === b.getUTCFullYear() && a.getUTCMonth() === b.getUTCMonth() && a.getUTCDate() === b.getUTCDate()
    }

    function f(a) {
        return function() {
            return this[a].apply(this, arguments)
        }
    }

    function g(a) {
        return a && !isNaN(a.getTime())
    }

    function h(b, c) {
        function d(a, b) {
            return b.toLowerCase()
        }
        var e, f = a(b).data(),
            g = {},
            h = new RegExp("^" + c.toLowerCase() + "([A-Z])");
        c = new RegExp("^" + c.toLowerCase());
        for (var i in f) c.test(i) && (e = i.replace(h, d), g[e] = f[i]);
        return g
    }

    function i(b) {
        var c = {};
        if (q[b] || (b = b.split("-")[0], q[b])) {
            var d = q[b];
            return a.each(p, function(a, b) {
                b in d && (c[b] = d[b])
            }), c
        }
    }
    var j = function() {
            var b = {
                get: function(a) {
                    return this.slice(a)[0]
                },
                contains: function(a) {
                    for (var b = a && a.valueOf(), c = 0, d = this.length; d > c; c++)
                        if (this[c].valueOf() === b) return c;
                    return -1
                },
                remove: function(a) {
                    this.splice(a, 1)
                },
                replace: function(b) {
                    b && (a.isArray(b) || (b = [b]), this.clear(), this.push.apply(this, b))
                },
                clear: function() {
                    this.length = 0
                },
                copy: function() {
                    var a = new j;
                    return a.replace(this), a
                }
            };
            return function() {
                var c = [];
                return c.push.apply(c, arguments), a.extend(c, b), c
            }
        }(),
        k = function(b, c) {
            a(b).data("datepicker", this), this._process_options(c), this.dates = new j, this.viewDate = this.o.defaultViewDate, this.focusDate = null, this.element = a(b), this.isInput = this.element.is("input"), this.inputField = this.isInput ? this.element : this.element.find("input"), this.component = this.element.hasClass("date") ? this.element.find(".add-on, .input-group-addon, .btn") : !1, this.hasInput = this.component && this.inputField.length, this.component && 0 === this.component.length && (this.component = !1), this.isInline = !this.component && this.element.is("div"), this.picker = a(r.template), this._check_template(this.o.templates.leftArrow) && this.picker.find(".prev").html(this.o.templates.leftArrow), this._check_template(this.o.templates.rightArrow) && this.picker.find(".next").html(this.o.templates.rightArrow), this._buildEvents(), this._attachEvents(), this.isInline ? this.picker.addClass("datepicker-inline").appendTo(this.element) : this.picker.addClass("datepicker-dropdown dropdown-menu"), this.o.rtl && this.picker.addClass("datepicker-rtl"), this.viewMode = this.o.startView, this.o.calendarWeeks && this.picker.find("thead .datepicker-title, tfoot .today, tfoot .clear").attr("colspan", function(a, b) {
                return parseInt(b) + 1
            }), this._allow_update = !1, this.setStartDate(this._o.startDate), this.setEndDate(this._o.endDate), this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled), this.setDaysOfWeekHighlighted(this.o.daysOfWeekHighlighted), this.setDatesDisabled(this.o.datesDisabled), this.fillDow(), this.fillMonths(), this._allow_update = !0, this.update(), this.showMode(), this.isInline && this.show()
        };
    k.prototype = {
        constructor: k,
        _resolveViewName: function(a, c) {
            return 0 === a || "days" === a || "month" === a ? 0 : 1 === a || "months" === a || "year" === a ? 1 : 2 === a || "years" === a || "decade" === a ? 2 : 3 === a || "decades" === a || "century" === a ? 3 : 4 === a || "centuries" === a || "millennium" === a ? 4 : c === b ? !1 : c
        },
        _check_template: function(c) {
            try {
                if (c === b || "" === c) return !1;
                if ((c.match(/[<>]/g) || []).length <= 0) return !0;
                var d = a(c);
                return d.length > 0
            } catch (e) {
                return !1
            }
        },
        _process_options: function(b) {
            this._o = a.extend({}, this._o, b);
            var e = this.o = a.extend({}, this._o),
                f = e.language;
            q[f] || (f = f.split("-")[0], q[f] || (f = o.language)), e.language = f, e.startView = this._resolveViewName(e.startView, 0), e.minViewMode = this._resolveViewName(e.minViewMode, 0), e.maxViewMode = this._resolveViewName(e.maxViewMode, 4), e.startView = Math.min(e.startView, e.maxViewMode), e.startView = Math.max(e.startView, e.minViewMode), e.multidate !== !0 && (e.multidate = Number(e.multidate) || !1, e.multidate !== !1 && (e.multidate = Math.max(0, e.multidate))), e.multidateSeparator = String(e.multidateSeparator), e.weekStart %= 7, e.weekEnd = (e.weekStart + 6) % 7;
            var g = r.parseFormat(e.format);
            e.startDate !== -(1 / 0) && (e.startDate ? e.startDate instanceof Date ? e.startDate = this._local_to_utc(this._zero_time(e.startDate)) : e.startDate = r.parseDate(e.startDate, g, e.language, e.assumeNearbyYear) : e.startDate = -(1 / 0)), e.endDate !== 1 / 0 && (e.endDate ? e.endDate instanceof Date ? e.endDate = this._local_to_utc(this._zero_time(e.endDate)) : e.endDate = r.parseDate(e.endDate, g, e.language, e.assumeNearbyYear) : e.endDate = 1 / 0), e.daysOfWeekDisabled = e.daysOfWeekDisabled || [], a.isArray(e.daysOfWeekDisabled) || (e.daysOfWeekDisabled = e.daysOfWeekDisabled.split(/[,\s]*/)), e.daysOfWeekDisabled = a.map(e.daysOfWeekDisabled, function(a) {
                return parseInt(a, 10)
            }), e.daysOfWeekHighlighted = e.daysOfWeekHighlighted || [], a.isArray(e.daysOfWeekHighlighted) || (e.daysOfWeekHighlighted = e.daysOfWeekHighlighted.split(/[,\s]*/)), e.daysOfWeekHighlighted = a.map(e.daysOfWeekHighlighted, function(a) {
                return parseInt(a, 10)
            }), e.datesDisabled = e.datesDisabled || [], a.isArray(e.datesDisabled) || (e.datesDisabled = [e.datesDisabled]), e.datesDisabled = a.map(e.datesDisabled, function(a) {
                return r.parseDate(a, g, e.language, e.assumeNearbyYear)
            });
            var h = String(e.orientation).toLowerCase().split(/\s+/g),
                i = e.orientation.toLowerCase();
            if (h = a.grep(h, function(a) {
                return /^auto|left|right|top|bottom$/.test(a)
            }), e.orientation = {
                x: "auto",
                y: "auto"
            }, i && "auto" !== i)
                if (1 === h.length) switch (h[0]) {
                    case "top":
                    case "bottom":
                        e.orientation.y = h[0];
                        break;
                    case "left":
                    case "right":
                        e.orientation.x = h[0]
                } else i = a.grep(h, function(a) {
                    return /^left|right$/.test(a)
                }), e.orientation.x = i[0] || "auto", i = a.grep(h, function(a) {
                    return /^top|bottom$/.test(a)
                }), e.orientation.y = i[0] || "auto";
            else;
            if (e.defaultViewDate) {
                var j = e.defaultViewDate.year || (new Date).getFullYear(),
                    k = e.defaultViewDate.month || 0,
                    l = e.defaultViewDate.day || 1;
                e.defaultViewDate = c(j, k, l)
            } else e.defaultViewDate = d()
        },
        _events: [],
        _secondaryEvents: [],
        _applyEvents: function(a) {
            for (var c, d, e, f = 0; f < a.length; f++) c = a[f][0], 2 === a[f].length ? (d = b, e = a[f][1]) : 3 === a[f].length && (d = a[f][1], e = a[f][2]), c.on(e, d)
        },
        _unapplyEvents: function(a) {
            for (var c, d, e, f = 0; f < a.length; f++) c = a[f][0], 2 === a[f].length ? (e = b, d = a[f][1]) : 3 === a[f].length && (e = a[f][1], d = a[f][2]), c.off(d, e)
        },
        _buildEvents: function() {
            var b = {
                keyup: a.proxy(function(b) {
                    -1 === a.inArray(b.keyCode, [27, 37, 39, 38, 40, 32, 13, 9]) && this.update()
                }, this),
                keydown: a.proxy(this.keydown, this),
                paste: a.proxy(this.paste, this)
            };
            this.o.showOnFocus === !0 && (b.focus = a.proxy(this.show, this)), this.isInput ? this._events = [
                [this.element, b]
            ] : this.component && this.hasInput ? this._events = [
                [this.inputField, b],
                [this.component, {
                    click: a.proxy(this.show, this)
                }]
            ] : this._events = [
                [this.element, {
                    click: a.proxy(this.show, this),
                    keydown: a.proxy(this.keydown, this)
                }]
            ], this._events.push([this.element, "*", {
                blur: a.proxy(function(a) {
                    this._focused_from = a.target
                }, this)
            }], [this.element, {
                blur: a.proxy(function(a) {
                    this._focused_from = a.target
                }, this)
            }]), this.o.immediateUpdates && this._events.push([this.element, {
                "changeYear changeMonth": a.proxy(function(a) {
                    this.update(a.date)
                }, this)
            }]), this._secondaryEvents = [
                [this.picker, {
                    click: a.proxy(this.click, this)
                }],
                [a(window), {
                    resize: a.proxy(this.place, this)
                }],
                [a(document), {
                    mousedown: a.proxy(function(a) {
                        this.element.is(a.target) || this.element.find(a.target).length || this.picker.is(a.target) || this.picker.find(a.target).length || this.isInline || this.hide()
                    }, this)
                }]
            ]
        },
        _attachEvents: function() {
            this._detachEvents(), this._applyEvents(this._events)
        },
        _detachEvents: function() {
            this._unapplyEvents(this._events)
        },
        _attachSecondaryEvents: function() {
            this._detachSecondaryEvents(), this._applyEvents(this._secondaryEvents)
        },
        _detachSecondaryEvents: function() {
            this._unapplyEvents(this._secondaryEvents)
        },
        _trigger: function(b, c) {
            var d = c || this.dates.get(-1),
                e = this._utc_to_local(d);
            this.element.trigger({
                type: b,
                date: e,
                dates: a.map(this.dates, this._utc_to_local),
                format: a.proxy(function(a, b) {
                    0 === arguments.length ? (a = this.dates.length - 1, b = this.o.format) : "string" == typeof a && (b = a, a = this.dates.length - 1), b = b || this.o.format;
                    var c = this.dates.get(a);
                    return r.formatDate(c, b, this.o.language)
                }, this)
            })
        },
        show: function() {
            return this.inputField.prop("disabled") || this.inputField.prop("readonly") && this.o.enableOnReadonly === !1 ? void 0 : (this.isInline || this.picker.appendTo(this.o.container), this.place(), this.picker.show(), this._attachSecondaryEvents(), this._trigger("show"), (window.navigator.msMaxTouchPoints || "ontouchstart" in document) && this.o.disableTouchKeyboard && a(this.element).blur(), this)
        },
        hide: function() {
            return this.isInline || !this.picker.is(":visible") ? this : (this.focusDate = null, this.picker.hide().detach(), this._detachSecondaryEvents(), this.viewMode = this.o.startView, this.showMode(), this.o.forceParse && this.inputField.val() && this.setValue(), this._trigger("hide"), this)
        },
        destroy: function() {
            return this.hide(), this._detachEvents(), this._detachSecondaryEvents(), this.picker.remove(), delete this.element.data().datepicker, this.isInput || delete this.element.data().date, this
        },
        paste: function(b) {
            var c;
            if (b.originalEvent.clipboardData && b.originalEvent.clipboardData.types && -1 !== a.inArray("text/plain", b.originalEvent.clipboardData.types)) c = b.originalEvent.clipboardData.getData("text/plain");
            else {
                if (!window.clipboardData) return;
                c = window.clipboardData.getData("Text")
            }
            this.setDate(c), this.update(), b.preventDefault()
        },
        _utc_to_local: function(a) {
            return a && new Date(a.getTime() + 6e4 * a.getTimezoneOffset())
        },
        _local_to_utc: function(a) {
            return a && new Date(a.getTime() - 6e4 * a.getTimezoneOffset())
        },
        _zero_time: function(a) {
            return a && new Date(a.getFullYear(), a.getMonth(), a.getDate())
        },
        _zero_utc_time: function(a) {
            return a && new Date(Date.UTC(a.getUTCFullYear(), a.getUTCMonth(), a.getUTCDate()))
        },
        getDates: function() {
            return a.map(this.dates, this._utc_to_local)
        },
        getUTCDates: function() {
            return a.map(this.dates, function(a) {
                return new Date(a)
            })
        },
        getDate: function() {
            return this._utc_to_local(this.getUTCDate())
        },
        getUTCDate: function() {
            var a = this.dates.get(-1);
            return "undefined" != typeof a ? new Date(a) : null
        },
        clearDates: function() {
            this.inputField && this.inputField.val(""), this.update(), this._trigger("changeDate"), this.o.autoclose && this.hide()
        },
        setDates: function() {
            var b = a.isArray(arguments[0]) ? arguments[0] : arguments;
            return this.update.apply(this, b), this._trigger("changeDate"), this.setValue(), this
        },
        setUTCDates: function() {
            var b = a.isArray(arguments[0]) ? arguments[0] : arguments;
            return this.update.apply(this, a.map(b, this._utc_to_local)), this._trigger("changeDate"), this.setValue(), this
        },
        setDate: f("setDates"),
        setUTCDate: f("setUTCDates"),
        remove: f("destroy"),
        setValue: function() {
            var a = this.getFormattedDate();
            return this.inputField.val(a), this
        },
        getFormattedDate: function(c) {
            c === b && (c = this.o.format);
            var d = this.o.language;
            return a.map(this.dates, function(a) {
                return r.formatDate(a, c, d)
            }).join(this.o.multidateSeparator)
        },
        getStartDate: function() {
            return this.o.startDate
        },
        setStartDate: function(a) {
            return this._process_options({
                startDate: a
            }), this.update(), this.updateNavArrows(), this
        },
        getEndDate: function() {
            return this.o.endDate
        },
        setEndDate: function(a) {
            return this._process_options({
                endDate: a
            }), this.update(), this.updateNavArrows(), this
        },
        setDaysOfWeekDisabled: function(a) {
            return this._process_options({
                daysOfWeekDisabled: a
            }), this.update(), this.updateNavArrows(), this
        },
        setDaysOfWeekHighlighted: function(a) {
            return this._process_options({
                daysOfWeekHighlighted: a
            }), this.update(), this
        },
        setDatesDisabled: function(a) {
            this._process_options({
                datesDisabled: a
            }), this.update(), this.updateNavArrows()
        },
        place: function() {
            if (this.isInline) return this;
            var b = this.picker.outerWidth(),
                c = this.picker.outerHeight(),
                d = 10,
                e = a(this.o.container),
                f = e.width(),
                g = "body" === this.o.container ? a(document).scrollTop() : e.scrollTop(),
                h = e.offset(),
                i = [];
            this.element.parents().each(function() {
                var b = a(this).css("z-index");
                "auto" !== b && 0 !== b && i.push(parseInt(b))
            });
            var j = Math.max.apply(Math, i) + this.o.zIndexOffset,
                k = this.component ? this.component.parent().offset() : this.element.offset(),
                l = this.component ? this.component.outerHeight(!0) : this.element.outerHeight(!1),
                m = this.component ? this.component.outerWidth(!0) : this.element.outerWidth(!1),
                n = k.left - h.left,
                o = k.top - h.top;
            "body" !== this.o.container && (o += g), this.picker.removeClass("datepicker-orient-top datepicker-orient-bottom datepicker-orient-right datepicker-orient-left"), "auto" !== this.o.orientation.x ? (this.picker.addClass("datepicker-orient-" + this.o.orientation.x), "right" === this.o.orientation.x && (n -= b - m)) : k.left < 0 ? (this.picker.addClass("datepicker-orient-left"), n -= k.left - d) : n + b > f ? (this.picker.addClass("datepicker-orient-right"), n += m - b) : this.picker.addClass("datepicker-orient-left");
            var p, q = this.o.orientation.y;
            if ("auto" === q && (p = -g + o - c, q = 0 > p ? "bottom" : "top"), this.picker.addClass("datepicker-orient-" + q), "top" === q ? o -= c + parseInt(this.picker.css("padding-top")) : o += l, this.o.rtl) {
                var r = f - (n + m);
                this.picker.css({
                    top: o,
                    right: r,
                    zIndex: j
                })
            } else this.picker.css({
                top: o,
                left: n,
                zIndex: j
            });
            return this
        },
        _allow_update: !0,
        update: function() {
            if (!this._allow_update) return this;
            var b = this.dates.copy(),
                c = [],
                d = !1;
            return arguments.length ? (a.each(arguments, a.proxy(function(a, b) {
                b instanceof Date && (b = this._local_to_utc(b)), c.push(b)
            }, this)), d = !0) : (c = this.isInput ? this.element.val() : this.element.data("date") || this.inputField.val(), c = c && this.o.multidate ? c.split(this.o.multidateSeparator) : [c], delete this.element.data().date), c = a.map(c, a.proxy(function(a) {
                return r.parseDate(a, this.o.format, this.o.language, this.o.assumeNearbyYear)
            }, this)), c = a.grep(c, a.proxy(function(a) {
                return !this.dateWithinRange(a) || !a
            }, this), !0), this.dates.replace(c), this.dates.length ? this.viewDate = new Date(this.dates.get(-1)) : this.viewDate < this.o.startDate ? this.viewDate = new Date(this.o.startDate) : this.viewDate > this.o.endDate ? this.viewDate = new Date(this.o.endDate) : this.viewDate = this.o.defaultViewDate, d ? this.setValue() : c.length && String(b) !== String(this.dates) && this._trigger("changeDate"), !this.dates.length && b.length && this._trigger("clearDate"), this.fill(), this.element.change(), this
        },
        fillDow: function() {
            var b = this.o.weekStart,
                c = "<tr>";
            for (this.o.calendarWeeks && (this.picker.find(".datepicker-days .datepicker-switch").attr("colspan", function(a, b) {
                return parseInt(b) + 1
            }), c += '<th class="cw">&#160;</th>'); b < this.o.weekStart + 7;) c += '<th class="dow', a.inArray(b, this.o.daysOfWeekDisabled) > -1 && (c += " disabled"), c += '">' + q[this.o.language].daysMin[b++ % 7] + "</th>";
            c += "</tr>", this.picker.find(".datepicker-days thead").append(c)
        },
        fillMonths: function() {
            for (var a = this._utc_to_local(this.viewDate), b = "", c = 0; 12 > c;) {
                var d = a && a.getMonth() === c ? " focused" : "";
                b += '<span class="month' + d + '">' + q[this.o.language].monthsShort[c++] + "</span>"
            }
            this.picker.find(".datepicker-months td").html(b)
        },
        setRange: function(b) {
            b && b.length ? this.range = a.map(b, function(a) {
                return a.valueOf()
            }) : delete this.range, this.fill()
        },
        getClassNames: function(b) {
            var c = [],
                d = this.viewDate.getUTCFullYear(),
                e = this.viewDate.getUTCMonth(),
                f = new Date;
            return b.getUTCFullYear() < d || b.getUTCFullYear() === d && b.getUTCMonth() < e ? c.push("old") : (b.getUTCFullYear() > d || b.getUTCFullYear() === d && b.getUTCMonth() > e) && c.push("new"), this.focusDate && b.valueOf() === this.focusDate.valueOf() && c.push("focused"), this.o.todayHighlight && b.getUTCFullYear() === f.getFullYear() && b.getUTCMonth() === f.getMonth() && b.getUTCDate() === f.getDate() && c.push("today"), -1 !== this.dates.contains(b) && c.push("active"), this.dateWithinRange(b) || c.push("disabled"), this.dateIsDisabled(b) && c.push("disabled", "disabled-date"), -1 !== a.inArray(b.getUTCDay(), this.o.daysOfWeekHighlighted) && c.push("highlighted"), this.range && (b > this.range[0] && b < this.range[this.range.length - 1] && c.push("range"), -1 !== a.inArray(b.valueOf(), this.range) && c.push("selected"), b.valueOf() === this.range[0] && c.push("range-start"), b.valueOf() === this.range[this.range.length - 1] && c.push("range-end")), c
        },
        _fill_yearsView: function(c, d, e, f, g, h, i, j) {
            var k, l, m, n, o, p, q, r, s, t, u;
            for (k = "", l = this.picker.find(c), m = parseInt(g / e, 10) * e, o = parseInt(h / f, 10) * f, p = parseInt(i / f, 10) * f, n = a.map(this.dates, function(a) {
                return parseInt(a.getUTCFullYear() / f, 10) * f
            }), l.find(".datepicker-switch").text(m + "-" + (m + 9 * f)), q = m - f, r = -1; 11 > r; r += 1) s = [d], t = null, -1 === r ? s.push("old") : 10 === r && s.push("new"), -1 !== a.inArray(q, n) && s.push("active"), (o > q || q > p) && s.push("disabled"), q === this.viewDate.getFullYear() && s.push("focused"), j !== a.noop && (u = j(new Date(q, 0, 1)), u === b ? u = {} : "boolean" == typeof u ? u = {
                enabled: u
            } : "string" == typeof u && (u = {
                classes: u
            }), u.enabled === !1 && s.push("disabled"), u.classes && (s = s.concat(u.classes.split(/\s+/))), u.tooltip && (t = u.tooltip)), k += '<span class="' + s.join(" ") + '"' + (t ? ' title="' + t + '"' : "") + ">" + q + "</span>", q += f;
            l.find("td").html(k)
        },
        fill: function() {
            var d, e, f = new Date(this.viewDate),
                g = f.getUTCFullYear(),
                h = f.getUTCMonth(),
                i = this.o.startDate !== -(1 / 0) ? this.o.startDate.getUTCFullYear() : -(1 / 0),
                j = this.o.startDate !== -(1 / 0) ? this.o.startDate.getUTCMonth() : -(1 / 0),
                k = this.o.endDate !== 1 / 0 ? this.o.endDate.getUTCFullYear() : 1 / 0,
                l = this.o.endDate !== 1 / 0 ? this.o.endDate.getUTCMonth() : 1 / 0,
                m = q[this.o.language].today || q.en.today || "",
                n = q[this.o.language].clear || q.en.clear || "",
                o = q[this.o.language].titleFormat || q.en.titleFormat;
            if (!isNaN(g) && !isNaN(h)) {
                this.picker.find(".datepicker-days .datepicker-switch").text(r.formatDate(f, o, this.o.language)), this.picker.find("tfoot .today").text(m).toggle(this.o.todayBtn !== !1), this.picker.find("tfoot .clear").text(n).toggle(this.o.clearBtn !== !1), this.picker.find("thead .datepicker-title").text(this.o.title).toggle("" !== this.o.title), this.updateNavArrows(), this.fillMonths();
                var p = c(g, h - 1, 28),
                    s = r.getDaysInMonth(p.getUTCFullYear(), p.getUTCMonth());
                p.setUTCDate(s), p.setUTCDate(s - (p.getUTCDay() - this.o.weekStart + 7) % 7);
                var t = new Date(p);
                p.getUTCFullYear() < 100 && t.setUTCFullYear(p.getUTCFullYear()), t.setUTCDate(t.getUTCDate() + 42), t = t.valueOf();
                for (var u, v = []; p.valueOf() < t;) {
                    if (p.getUTCDay() === this.o.weekStart && (v.push("<tr>"), this.o.calendarWeeks)) {
                        var w = new Date(+p + (this.o.weekStart - p.getUTCDay() - 7) % 7 * 864e5),
                            x = new Date(Number(w) + (11 - w.getUTCDay()) % 7 * 864e5),
                            y = new Date(Number(y = c(x.getUTCFullYear(), 0, 1)) + (11 - y.getUTCDay()) % 7 * 864e5),
                            z = (x - y) / 864e5 / 7 + 1;
                        v.push('<td class="cw">' + z + "</td>")
                    }
                    u = this.getClassNames(p), u.push("day"), this.o.beforeShowDay !== a.noop && (e = this.o.beforeShowDay(this._utc_to_local(p)), e === b ? e = {} : "boolean" == typeof e ? e = {
                        enabled: e
                    } : "string" == typeof e && (e = {
                        classes: e
                    }), e.enabled === !1 && u.push("disabled"), e.classes && (u = u.concat(e.classes.split(/\s+/))), e.tooltip && (d = e.tooltip)), u = a.isFunction(a.uniqueSort) ? a.uniqueSort(u) : a.unique(u), v.push('<td class="' + u.join(" ") + '"' + (d ? ' title="' + d + '"' : "") + ">" + p.getUTCDate() + "</td>"), d = null, p.getUTCDay() === this.o.weekEnd && v.push("</tr>"), p.setUTCDate(p.getUTCDate() + 1)
                }
                this.picker.find(".datepicker-days tbody").empty().append(v.join(""));
                var A = q[this.o.language].monthsTitle || q.en.monthsTitle || "Months",
                    B = this.picker.find(".datepicker-months").find(".datepicker-switch").text(this.o.maxViewMode < 2 ? A : g).end().find("span").removeClass("active");
                if (a.each(this.dates, function(a, b) {
                    b.getUTCFullYear() === g && B.eq(b.getUTCMonth()).addClass("active")
                }), (i > g || g > k) && B.addClass("disabled"), g === i && B.slice(0, j).addClass("disabled"), g === k && B.slice(l + 1).addClass("disabled"), this.o.beforeShowMonth !== a.noop) {
                    var C = this;
                    a.each(B, function(c, d) {
                        var e = new Date(g, c, 1),
                            f = C.o.beforeShowMonth(e);
                        f === b ? f = {} : "boolean" == typeof f ? f = {
                            enabled: f
                        } : "string" == typeof f && (f = {
                            classes: f
                        }), f.enabled !== !1 || a(d).hasClass("disabled") || a(d).addClass("disabled"), f.classes && a(d).addClass(f.classes), f.tooltip && a(d).prop("title", f.tooltip)
                    })
                }
                this._fill_yearsView(".datepicker-years", "year", 10, 1, g, i, k, this.o.beforeShowYear), this._fill_yearsView(".datepicker-decades", "decade", 100, 10, g, i, k, this.o.beforeShowDecade), this._fill_yearsView(".datepicker-centuries", "century", 1e3, 100, g, i, k, this.o.beforeShowCentury)
            }
        },
        updateNavArrows: function() {
            if (this._allow_update) {
                var a = new Date(this.viewDate),
                    b = a.getUTCFullYear(),
                    c = a.getUTCMonth();
                switch (this.viewMode) {
                    case 0:
                        this.o.startDate !== -(1 / 0) && b <= this.o.startDate.getUTCFullYear() && c <= this.o.startDate.getUTCMonth() ? this.picker.find(".prev").css({
                            visibility: "hidden"
                        }) : this.picker.find(".prev").css({
                            visibility: "visible"
                        }), this.o.endDate !== 1 / 0 && b >= this.o.endDate.getUTCFullYear() && c >= this.o.endDate.getUTCMonth() ? this.picker.find(".next").css({
                            visibility: "hidden"
                        }) : this.picker.find(".next").css({
                            visibility: "visible"
                        });
                        break;
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        this.o.startDate !== -(1 / 0) && b <= this.o.startDate.getUTCFullYear() || this.o.maxViewMode < 2 ? this.picker.find(".prev").css({
                            visibility: "hidden"
                        }) : this.picker.find(".prev").css({
                            visibility: "visible"
                        }), this.o.endDate !== 1 / 0 && b >= this.o.endDate.getUTCFullYear() || this.o.maxViewMode < 2 ? this.picker.find(".next").css({
                            visibility: "hidden"
                        }) : this.picker.find(".next").css({
                            visibility: "visible"
                        })
                }
            }
        },
        click: function(b) {
            b.preventDefault(), b.stopPropagation();
            var e, f, g, h, i, j, k;
            e = a(b.target), e.hasClass("datepicker-switch") && this.showMode(1);
            var l = e.closest(".prev, .next");
            l.length > 0 && (f = r.modes[this.viewMode].navStep * (l.hasClass("prev") ? -1 : 1), 0 === this.viewMode ? (this.viewDate = this.moveMonth(this.viewDate, f), this._trigger("changeMonth", this.viewDate)) : (this.viewDate = this.moveYear(this.viewDate, f), 1 === this.viewMode && this._trigger("changeYear", this.viewDate)), this.fill()), e.hasClass("today") && !e.hasClass("day") && (this.showMode(-2), this._setDate(d(), "linked" === this.o.todayBtn ? null : "view")), e.hasClass("clear") && this.clearDates(), e.hasClass("disabled") || (e.hasClass("day") && (g = parseInt(e.text(), 10) || 1, h = this.viewDate.getUTCFullYear(), i = this.viewDate.getUTCMonth(), e.hasClass("old") && (0 === i ? (i = 11, h -= 1, j = !0, k = !0) : (i -= 1, j = !0)), e.hasClass("new") && (11 === i ? (i = 0, h += 1, j = !0, k = !0) : (i += 1, j = !0)), this._setDate(c(h, i, g)), k && this._trigger("changeYear", this.viewDate), j && this._trigger("changeMonth", this.viewDate)), e.hasClass("month") && (this.viewDate.setUTCDate(1), g = 1, i = e.parent().find("span").index(e), h = this.viewDate.getUTCFullYear(), this.viewDate.setUTCMonth(i), this._trigger("changeMonth", this.viewDate), 1 === this.o.minViewMode ? (this._setDate(c(h, i, g)), this.showMode()) : this.showMode(-1), this.fill()), (e.hasClass("year") || e.hasClass("decade") || e.hasClass("century")) && (this.viewDate.setUTCDate(1), g = 1, i = 0, h = parseInt(e.text(), 10) || 0, this.viewDate.setUTCFullYear(h), e.hasClass("year") && (this._trigger("changeYear", this.viewDate), 2 === this.o.minViewMode && this._setDate(c(h, i, g))), e.hasClass("decade") && (this._trigger("changeDecade", this.viewDate), 3 === this.o.minViewMode && this._setDate(c(h, i, g))), e.hasClass("century") && (this._trigger("changeCentury", this.viewDate), 4 === this.o.minViewMode && this._setDate(c(h, i, g))), this.showMode(-1), this.fill())), this.picker.is(":visible") && this._focused_from && a(this._focused_from).focus(), delete this._focused_from
        },
        _toggle_multidate: function(a) {
            var b = this.dates.contains(a);
            if (a || this.dates.clear(), -1 !== b ? (this.o.multidate === !0 || this.o.multidate > 1 || this.o.toggleActive) && this.dates.remove(b) : this.o.multidate === !1 ? (this.dates.clear(), this.dates.push(a)) : this.dates.push(a), "number" == typeof this.o.multidate)
                for (; this.dates.length > this.o.multidate;) this.dates.remove(0)
        },
        _setDate: function(a, b) {
            b && "date" !== b || this._toggle_multidate(a && new Date(a)), b && "view" !== b || (this.viewDate = a && new Date(a)), this.fill(), this.setValue(), b && "view" === b || this._trigger("changeDate"), this.inputField && this.inputField.change(), !this.o.autoclose || b && "date" !== b || this.hide()
        },
        moveDay: function(a, b) {
            var c = new Date(a);
            return c.setUTCDate(a.getUTCDate() + b), c
        },
        moveWeek: function(a, b) {
            return this.moveDay(a, 7 * b)
        },
        moveMonth: function(a, b) {
            if (!g(a)) return this.o.defaultViewDate;
            if (!b) return a;
            var c, d, e = new Date(a.valueOf()),
                f = e.getUTCDate(),
                h = e.getUTCMonth(),
                i = Math.abs(b);
            if (b = b > 0 ? 1 : -1, 1 === i) d = -1 === b ? function() {
                return e.getUTCMonth() === h
            } : function() {
                return e.getUTCMonth() !== c
            }, c = h + b, e.setUTCMonth(c), (0 > c || c > 11) && (c = (c + 12) % 12);
            else {
                for (var j = 0; i > j; j++) e = this.moveMonth(e, b);
                c = e.getUTCMonth(), e.setUTCDate(f), d = function() {
                    return c !== e.getUTCMonth()
                }
            }
            for (; d();) e.setUTCDate(--f), e.setUTCMonth(c);
            return e
        },
        moveYear: function(a, b) {
            return this.moveMonth(a, 12 * b)
        },
        moveAvailableDate: function(a, b, c) {
            do {
                if (a = this[c](a, b), !this.dateWithinRange(a)) return !1;
                c = "moveDay"
            } while (this.dateIsDisabled(a));
            return a
        },
        weekOfDateIsDisabled: function(b) {
            return -1 !== a.inArray(b.getUTCDay(), this.o.daysOfWeekDisabled)
        },
        dateIsDisabled: function(b) {
            return this.weekOfDateIsDisabled(b) || a.grep(this.o.datesDisabled, function(a) {
                return e(b, a)
            }).length > 0
        },
        dateWithinRange: function(a) {
            return a >= this.o.startDate && a <= this.o.endDate
        },
        keydown: function(a) {
            if (!this.picker.is(":visible")) return void((40 === a.keyCode || 27 === a.keyCode) && (this.show(), a.stopPropagation()));
            var b, c, d = !1,
                e = this.focusDate || this.viewDate;
            switch (a.keyCode) {
                case 27:
                    this.focusDate ? (this.focusDate = null, this.viewDate = this.dates.get(-1) || this.viewDate, this.fill()) : this.hide(), a.preventDefault(), a.stopPropagation();
                    break;
                case 37:
                case 38:
                case 39:
                case 40:
                    if (!this.o.keyboardNavigation || 7 === this.o.daysOfWeekDisabled.length) break;
                    b = 37 === a.keyCode || 38 === a.keyCode ? -1 : 1, 0 === this.viewMode ? a.ctrlKey ? (c = this.moveAvailableDate(e, b, "moveYear"), c && this._trigger("changeYear", this.viewDate)) : a.shiftKey ? (c = this.moveAvailableDate(e, b, "moveMonth"), c && this._trigger("changeMonth", this.viewDate)) : 37 === a.keyCode || 39 === a.keyCode ? c = this.moveAvailableDate(e, b, "moveDay") : this.weekOfDateIsDisabled(e) || (c = this.moveAvailableDate(e, b, "moveWeek")) : 1 === this.viewMode ? ((38 === a.keyCode || 40 === a.keyCode) && (b = 4 * b), c = this.moveAvailableDate(e, b, "moveMonth")) : 2 === this.viewMode && ((38 === a.keyCode || 40 === a.keyCode) && (b = 4 * b), c = this.moveAvailableDate(e, b, "moveYear")), c && (this.focusDate = this.viewDate = c, this.setValue(), this.fill(), a.preventDefault());
                    break;
                case 13:
                    if (!this.o.forceParse) break;
                    e = this.focusDate || this.dates.get(-1) || this.viewDate, this.o.keyboardNavigation && (this._toggle_multidate(e), d = !0), this.focusDate = null, this.viewDate = this.dates.get(-1) || this.viewDate, this.setValue(), this.fill(), this.picker.is(":visible") && (a.preventDefault(), a.stopPropagation(), this.o.autoclose && this.hide());
                    break;
                case 9:
                    this.focusDate = null, this.viewDate = this.dates.get(-1) || this.viewDate, this.fill(), this.hide()
            }
            d && (this.dates.length ? this._trigger("changeDate") : this._trigger("clearDate"), this.inputField && this.inputField.change())
        },
        showMode: function(a) {
            a && (this.viewMode = Math.max(this.o.minViewMode, Math.min(this.o.maxViewMode, this.viewMode + a))), this.picker.children("div").hide().filter(".datepicker-" + r.modes[this.viewMode].clsName).show(), this.updateNavArrows()
        }
    };
    var l = function(b, c) {
        a(b).data("datepicker", this), this.element = a(b), this.inputs = a.map(c.inputs, function(a) {
            return a.jquery ? a[0] : a
        }), delete c.inputs, n.call(a(this.inputs), c).on("changeDate", a.proxy(this.dateUpdated, this)), this.pickers = a.map(this.inputs, function(b) {
            return a(b).data("datepicker")
        }), this.updateDates()
    };
    l.prototype = {
        updateDates: function() {
            this.dates = a.map(this.pickers, function(a) {
                return a.getUTCDate()
            }), this.updateRanges()
        },
        updateRanges: function() {
            var b = a.map(this.dates, function(a) {
                return a.valueOf()
            });
            a.each(this.pickers, function(a, c) {
                c.setRange(b)
            })
        },
        dateUpdated: function(b) {
            if (!this.updating) {
                this.updating = !0;
                var c = a(b.target).data("datepicker");
                if ("undefined" != typeof c) {
                    var d = c.getUTCDate(),
                        e = a.inArray(b.target, this.inputs),
                        f = e - 1,
                        g = e + 1,
                        h = this.inputs.length;
                    if (-1 !== e) {
                        if (a.each(this.pickers, function(a, b) {
                            b.getUTCDate() || b.setUTCDate(d)
                        }), d < this.dates[f])
                            for (; f >= 0 && d < this.dates[f];) this.pickers[f--].setUTCDate(d);
                        else if (d > this.dates[g])
                            for (; h > g && d > this.dates[g];) this.pickers[g++].setUTCDate(d);
                        this.updateDates(), delete this.updating
                    }
                }
            }
        },
        remove: function() {
            a.map(this.pickers, function(a) {
                a.remove()
            }), delete this.element.data().datepicker
        }
    };
    var m = a.fn.datepicker,
        n = function(c) {
            var d = Array.apply(null, arguments);
            d.shift();
            var e;
            if (this.each(function() {
                var b = a(this),
                    f = b.data("datepicker"),
                    g = "object" == typeof c && c;
                if (!f) {
                    var j = h(this, "date"),
                        m = a.extend({}, o, j, g),
                        n = i(m.language),
                        p = a.extend({}, o, n, j, g);
                    b.hasClass("input-daterange") || p.inputs ? (a.extend(p, {
                        inputs: p.inputs || b.find("input").toArray()
                    }), f = new l(this, p)) : f = new k(this, p), b.data("datepicker", f)
                }
                "string" == typeof c && "function" == typeof f[c] && (e = f[c].apply(f, d))
            }), e === b || e instanceof k || e instanceof l) return this;
            if (this.length > 1) throw new Error("Using only allowed for the collection of a single element (" + c + " function)");
            return e
        };
    a.fn.datepicker = n;
    var o = a.fn.datepicker.defaults = {
            assumeNearbyYear: !1,
            autoclose: !1,
            beforeShowDay: a.noop,
            beforeShowMonth: a.noop,
            beforeShowYear: a.noop,
            beforeShowDecade: a.noop,
            beforeShowCentury: a.noop,
            calendarWeeks: !1,
            clearBtn: !1,
            toggleActive: !1,
            daysOfWeekDisabled: [],
            daysOfWeekHighlighted: [],
            datesDisabled: [],
            endDate: 1 / 0,
            forceParse: !0,
            format: "mm/dd/yyyy",
            keyboardNavigation: !0,
            language: "en",
            minViewMode: 0,
            maxViewMode: 4,
            multidate: !1,
            multidateSeparator: ",",
            orientation: "auto",
            rtl: !1,
            startDate: -(1 / 0),
            startView: 0,
            todayBtn: !1,
            todayHighlight: !1,
            weekStart: 0,
            disableTouchKeyboard: !1,
            enableOnReadonly: !0,
            showOnFocus: !0,
            zIndexOffset: 10,
            container: "body",
            immediateUpdates: !1,
            title: "",
            templates: {
                leftArrow: "&laquo;",
                rightArrow: "&raquo;"
            }
        },
        p = a.fn.datepicker.locale_opts = ["format", "rtl", "weekStart"];
    a.fn.datepicker.Constructor = k;
    var q = a.fn.datepicker.dates = {
            en: {
                days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"],
                daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"],
                daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa"],
                months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
                monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
                today: "Oggi",
                clear: "reset",
                titleFormat: "MM yyyy"
            }
        },
        r = {
            modes: [{
                clsName: "days",
                navFnc: "Month",
                navStep: 1
            }, {
                clsName: "months",
                navFnc: "FullYear",
                navStep: 1
            }, {
                clsName: "years",
                navFnc: "FullYear",
                navStep: 10
            }, {
                clsName: "decades",
                navFnc: "FullDecade",
                navStep: 100
            }, {
                clsName: "centuries",
                navFnc: "FullCentury",
                navStep: 1e3
            }],
            isLeapYear: function(a) {
                return a % 4 === 0 && a % 100 !== 0 || a % 400 === 0
            },
            getDaysInMonth: function(a, b) {
                return [31, r.isLeapYear(a) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][b]
            },
            validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
            nonpunctuation: /[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,
            parseFormat: function(a) {
                if ("function" == typeof a.toValue && "function" == typeof a.toDisplay) return a;
                var b = a.replace(this.validParts, "\x00").split("\x00"),
                    c = a.match(this.validParts);
                if (!b || !b.length || !c || 0 === c.length) throw new Error("Invalid date format.");
                return {
                    separators: b,
                    parts: c
                }
            },
            parseDate: function(e, f, g, h) {
                function i(a, b) {
                    return b === !0 && (b = 10), 100 > a && (a += 2e3, a > (new Date).getFullYear() + b && (a -= 100)), a
                }

                function j() {
                    var a = this.slice(0, s[n].length),
                        b = s[n].slice(0, a.length);
                    return a.toLowerCase() === b.toLowerCase()
                }
                if (!e) return b;
                if (e instanceof Date) return e;
                if ("string" == typeof f && (f = r.parseFormat(f)), f.toValue) return f.toValue(e, f, g);
                var l, m, n, o, p = /([\-+]\d+)([dmwy])/,
                    s = e.match(/([\-+]\d+)([dmwy])/g),
                    t = {
                        d: "moveDay",
                        m: "moveMonth",
                        w: "moveWeek",
                        y: "moveYear"
                    },
                    u = {
                        yesterday: "-1d",
                        today: "+0d",
                        tomorrow: "+1d"
                    };
                if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(e)) {
                    for (e = new Date, n = 0; n < s.length; n++) l = p.exec(s[n]), m = parseInt(l[1]), o = t[l[2]], e = k.prototype[o](e, m);
                    return c(e.getUTCFullYear(), e.getUTCMonth(), e.getUTCDate())
                }
                if ("undefined" != typeof u[e] && (e = u[e], s = e.match(/([\-+]\d+)([dmwy])/g), /^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(e))) {
                    for (e = new Date, n = 0; n < s.length; n++) l = p.exec(s[n]), m = parseInt(l[1]), o = t[l[2]], e = k.prototype[o](e, m);
                    return c(e.getUTCFullYear(), e.getUTCMonth(), e.getUTCDate())
                }
                s = e && e.match(this.nonpunctuation) || [], e = new Date;
                var v, w, x = {},
                    y = ["yyyy", "yy", "M", "MM", "m", "mm", "d", "dd"],
                    z = {
                        yyyy: function(a, b) {
                            return a.setUTCFullYear(h ? i(b, h) : b)
                        },
                        yy: function(a, b) {
                            return a.setUTCFullYear(h ? i(b, h) : b)
                        },
                        m: function(a, b) {
                            if (isNaN(a)) return a;
                            for (b -= 1; 0 > b;) b += 12;
                            for (b %= 12, a.setUTCMonth(b); a.getUTCMonth() !== b;) a.setUTCDate(a.getUTCDate() - 1);
                            return a
                        },
                        d: function(a, b) {
                            return a.setUTCDate(b)
                        }
                    };
                z.M = z.MM = z.mm = z.m, z.dd = z.d, e = d();
                var A = f.parts.slice();
                if (s.length !== A.length && (A = a(A).filter(function(b, c) {
                    return -1 !== a.inArray(c, y)
                }).toArray()), s.length === A.length) {
                    var B;
                    for (n = 0, B = A.length; B > n; n++) {
                        if (v = parseInt(s[n], 10), l = A[n], isNaN(v)) switch (l) {
                            case "MM":
                                w = a(q[g].months).filter(j), v = a.inArray(w[0], q[g].months) + 1;
                                break;
                            case "M":
                                w = a(q[g].monthsShort).filter(j), v = a.inArray(w[0], q[g].monthsShort) + 1
                        }
                        x[l] = v
                    }
                    var C, D;
                    for (n = 0; n < y.length; n++) D = y[n], D in x && !isNaN(x[D]) && (C = new Date(e), z[D](C, x[D]), isNaN(C) || (e = C))
                }
                return e
            },
            formatDate: function(b, c, d) {
                if (!b) return "";
                if ("string" == typeof c && (c = r.parseFormat(c)),
                    c.toDisplay) return c.toDisplay(b, c, d);
                var e = {
                    d: b.getUTCDate(),
                    D: q[d].daysShort[b.getUTCDay()],
                    DD: q[d].days[b.getUTCDay()],
                    m: b.getUTCMonth() + 1,
                    M: q[d].monthsShort[b.getUTCMonth()],
                    MM: q[d].months[b.getUTCMonth()],
                    yy: b.getUTCFullYear().toString().substring(2),
                    yyyy: b.getUTCFullYear()
                };
                e.dd = (e.d < 10 ? "0" : "") + e.d, e.mm = (e.m < 10 ? "0" : "") + e.m, b = [];
                for (var f = a.extend([], c.separators), g = 0, h = c.parts.length; h >= g; g++) f.length && b.push(f.shift()), b.push(e[c.parts[g]]);
                return b.join("")
            },
            headTemplate: '<thead><tr><th colspan="7" class="datepicker-title"></th></tr><tr><th class="prev">&laquo;</th><th colspan="5" class="datepicker-switch"></th><th class="next">&raquo;</th></tr></thead>',
            contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
            footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
        };
    r.template = '<div class="datepicker"><div class="datepicker-days"><table class="table-condensed">' + r.headTemplate + "<tbody></tbody>" + r.footTemplate + '</table></div><div class="datepicker-months"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + '</table></div><div class="datepicker-years"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + '</table></div><div class="datepicker-decades"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + '</table></div><div class="datepicker-centuries"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + "</table></div></div>", a.fn.datepicker.DPGlobal = r, a.fn.datepicker.noConflict = function() {
        return a.fn.datepicker = m, this
    }, a.fn.datepicker.version = "1.6.4", a(document).on("focus.datepicker.data-api click.datepicker.data-api", '[data-provide="datepicker"]', function(b) {
        var c = a(this);
        c.data("datepicker") || (b.preventDefault(), n.call(c, "show"))
    }), a(function() {
        n.call(a('[data-provide="datepicker-inline"]'))
    })
});
/*
 * Copyright 2012 John Papa and Hans Fjällemark.  
 * All Rights Reserved.  
 * Use, reproduction, distribution, and modification of this code is subject to the terms and 
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Author: John Papa and Hans Fjällemark
 * Project: https://github.com/CodeSeven/toastr
 */
; (function (define) {
	define(['jquery'], function ($) {
		return (function () {
			var version = '1.3.1',
				$container,
			    toastType = {
			        error: 'error',
			        info: 'info',
			        success: 'success',
			        warning: 'warning'
			    },
				listener,
				toastId = 0,

				defaults = {
					tapToDismiss: true,
					toastClass: 'toast',
					containerId: 'toast-container',
					debug: false,
					fadeIn: 300,
					onFadeIn: undefined,
					fadeOut: 1000,
					onFadeOut: undefined,
					extendedTimeOut: 1000,
					iconClasses: {
						error: 'toast-error',
						info: 'toast-info',
						success: 'toast-success',
						warning: 'toast-warning'
					},
					iconClass: 'toast-info',
					positionClass: 'toast-top-right',
					timeOut: 5000, // Set timeOut and extendedTimeout to 0 to make it sticky
					titleClass: 'toast-title',
					messageClass: 'toast-message',
					target: 'body',
					newestOnTop: true
				},

				error = function (message, title, optionsOverride) {
				    return notify({
				        type: toastType.error,
						iconClass: getOptions().iconClasses.error,
						message: message,
						optionsOverride: optionsOverride,
						title: title
					});
				},

				info = function (message, title, optionsOverride) {
					return notify({
					    type: toastType.info,
					    iconClass: getOptions().iconClasses.info,
						message: message,
						optionsOverride: optionsOverride,
						title: title
					});
				},

				subscribe = function (callback) {
					listener = callback;
				},

				success = function (message, title, optionsOverride) {
					return notify({
					    type: toastType.success,
					    iconClass: getOptions().iconClasses.success,
						message: message,
						optionsOverride: optionsOverride,
						title: title
					});
				},

				warning = function (message, title, optionsOverride) {
					return notify({
					    type: toastType.warning,
					    iconClass: getOptions().iconClasses.warning,
						message: message,
						optionsOverride: optionsOverride,
						title: title
					});
				},

				clear = function ($toastElement) {
					var options = getOptions();
					if (!$container) {
						getContainer(options);
					}
					if ($toastElement && $(':focus', $toastElement).length === 0) {
						$toastElement.fadeOut(options.fadeOut, function () {
							removeToast($toastElement);
						});
						return;
					}
					if ($container.children().length) {
						$container.fadeOut(options.fadeOut, function () {
							$container.remove();
						});
					}
				};

			var toastr = {
				clear: clear,
				error: error,
				getContainer: getContainer,
				info: info,
				options: {},
				subscribe: subscribe,
				success: success,
				version: version,
				warning: warning
			};

			return toastr;

			//#region Internal Methods

			function publish(args) {
				if (!listener) {
					return;
				}
				listener(args);
			}

			function notify(map) {
				var
					options = getOptions(),
					iconClass = map.iconClass || options.iconClass;

				if (typeof (map.optionsOverride) !== 'undefined') {
					options = $.extend(options, map.optionsOverride);
					iconClass = map.optionsOverride.iconClass || iconClass;
				}

				toastId++;

				$container = getContainer(options);
				var
					intervalId = null,
					$toastElement = $('<div/>'),
					$titleElement = $('<div/>'),
					$messageElement = $('<div/>'),
					response = {
						toastId: toastId,
						state: 'visible',
						startTime: new Date(),
						options: options,
						map: map
					};

				if (map.iconClass) {
					$toastElement.addClass(options.toastClass).addClass(iconClass);
				}

				if (map.title) {
					$titleElement.append(map.title).addClass(options.titleClass);
					$toastElement.append($titleElement);
				}

				if (map.message) {
					$messageElement.append(map.message).addClass(options.messageClass);
					$toastElement.append($messageElement);
				}

				$toastElement.hide();
				if (options.newestOnTop) {
					$container.prepend($toastElement);
				} else {
					$container.append($toastElement);
				}
				$toastElement.fadeIn(options.fadeIn, options.onFadeIn);
				if (options.timeOut > 0) {
					intervalId = setTimeout(fadeAway, options.timeOut);
				}

				$toastElement.hover(stickAround, delayedFadeAway);
				if (!options.onclick && options.tapToDismiss) {
					$toastElement.click(fadeAway);
				}

				if (options.onclick) {
					$toastElement.click(function () {
						options.onclick() && fadeAway();
					});
				}

				publish(response);


				return $toastElement;

				function fadeAway() {
					if ($(':focus', $toastElement).length > 0) {
						return;
					}
					return $toastElement.fadeOut(options.fadeOut, function () {
						removeToast($toastElement);
						if (options.onFadeOut) {
							options.onFadeOut();
						}
						response.state = 'hidden';
					    response.endTime = new Date(),
						publish(response);
					});
				}

				function delayedFadeAway() {
					if (options.timeOut > 0 || options.extendedTimeOut > 0) {
						intervalId = setTimeout(fadeAway, options.extendedTimeOut);
					}
				}

				function stickAround() {
					clearTimeout(intervalId);
					$toastElement.stop(true, true).fadeIn(options.fadeIn);
				}
			}
			function getContainer(options) {
				if (!options) { options = getOptions(); }
				$container = $('#' + options.containerId);
				if ($container.length) {
					return $container;
				}
				$container = $('<div/>')
					.attr('id', options.containerId)
					.addClass(options.positionClass);
				$container.appendTo($(options.target));
				return $container;
			}

			function getOptions() {
				return $.extend({}, defaults, toastr.options);
			}

			function removeToast($toastElement) {
				if (!$container) { $container = getContainer(); }
				if ($toastElement.is(':visible')) {
					return;
				}
				$toastElement.remove();
				$toastElement = null;
				if ($container.children().length === 0) {
					$container.remove();
				}
			}
			//#endregion

		})();
	});
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
	if (typeof module !== 'undefined' && module.exports) { //Node
		module.exports = factory(require('jquery'));
	} else {
		window['toastr'] = factory(window['jQuery']);
	}
}));

$(function() {
    if ($('#train-trips-content')) {
        /// Your code here

    }
});
/*!
 * jQuery Placeholder Plugin v2.3.1
 * https://github.com/mathiasbynens/jquery-placeholder
 *
 * Copyright 2011, 2015 Mathias Bynens
 * Released under the MIT license
 */
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {

    /****
     * Allows plugin behavior simulation in modern browsers for easier debugging. 
     * When setting to true, use attribute "placeholder-x" rather than the usual "placeholder" in your inputs/textareas 
     * i.e. <input type="text" placeholder-x="my placeholder text" />
     */
    var debugMode = false; 

    // Opera Mini v7 doesn't support placeholder although its DOM seems to indicate so
    var isOperaMini = Object.prototype.toString.call(window.operamini) === '[object OperaMini]';
    var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini && !debugMode;
    var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini && !debugMode;
    var valHooks = $.valHooks;
    var propHooks = $.propHooks;
    var hooks;
    var placeholder;
    var settings = {};

    if (isInputSupported && isTextareaSupported) {

        placeholder = $.fn.placeholder = function() {
            return this;
        };

        placeholder.input = true;
        placeholder.textarea = true;

    } else {

        placeholder = $.fn.placeholder = function(options) {

            var defaults = {customClass: 'placeholder'};
            settings = $.extend({}, defaults, options);

            return this.filter((isInputSupported ? 'textarea' : ':input') + '[' + (debugMode ? 'placeholder-x' : 'placeholder') + ']')
                .not('.'+settings.customClass)
                .not(':radio, :checkbox, [type=hidden]')
                .bind({
                    'focus.placeholder': clearPlaceholder,
                    'blur.placeholder': setPlaceholder
                })
                .data('placeholder-enabled', true)
                .trigger('blur.placeholder');
        };

        placeholder.input = isInputSupported;
        placeholder.textarea = isTextareaSupported;

        hooks = {
            'get': function(element) {

                var $element = $(element);
                var $passwordInput = $element.data('placeholder-password');

                if ($passwordInput) {
                    return $passwordInput[0].value;
                }

                return $element.data('placeholder-enabled') && $element.hasClass(settings.customClass) ? '' : element.value;
            },
            'set': function(element, value) {

                var $element = $(element);
                var $replacement;
                var $passwordInput;

                if (value !== '') {

                    $replacement = $element.data('placeholder-textinput');
                    $passwordInput = $element.data('placeholder-password');

                    if ($replacement) {
                        clearPlaceholder.call($replacement[0], true, value) || (element.value = value);
                        $replacement[0].value = value;

                    } else if ($passwordInput) {
                        clearPlaceholder.call(element, true, value) || ($passwordInput[0].value = value);
                        element.value = value;
                    }
                }

                if (!$element.data('placeholder-enabled')) {
                    element.value = value;
                    return $element;
                }

                if (value === '') {
                    
                    element.value = value;
                    
                    // Setting the placeholder causes problems if the element continues to have focus.
                    if (element != safeActiveElement()) {
                        // We can't use `triggerHandler` here because of dummy text/password inputs :(
                        setPlaceholder.call(element);
                    }

                } else {
                    
                    if ($element.hasClass(settings.customClass)) {
                        clearPlaceholder.call(element);
                    }

                    element.value = value;
                }
                // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
                return $element;
            }
        };

        if (!isInputSupported) {
            valHooks.input = hooks;
            propHooks.value = hooks;
        }

        if (!isTextareaSupported) {
            valHooks.textarea = hooks;
            propHooks.value = hooks;
        }

        $(function() {
            // Look for forms
            $(document).delegate('form', 'submit.placeholder', function() {
                
                // Clear the placeholder values so they don't get submitted
                var $inputs = $('.'+settings.customClass, this).each(function() {
                    clearPlaceholder.call(this, true, '');
                });

                setTimeout(function() {
                    $inputs.each(setPlaceholder);
                }, 10);
            });
        });

        // Clear placeholder values upon page reload
        $(window).bind('beforeunload.placeholder', function() {

            var clearPlaceholders = true;

            try {
                // Prevent IE javascript:void(0) anchors from causing cleared values
                if (document.activeElement.toString() === 'javascript:void(0)') {
                    clearPlaceholders = false;
                }
            } catch (exception) { }

            if (clearPlaceholders) {
                $('.'+settings.customClass).each(function() {
                    this.value = '';
                });
            }
        });
    }

    function args(elem) {
        // Return an object of element attributes
        var newAttrs = {};
        var rinlinejQuery = /^jQuery\d+$/;

        $.each(elem.attributes, function(i, attr) {
            if (attr.specified && !rinlinejQuery.test(attr.name)) {
                newAttrs[attr.name] = attr.value;
            }
        });

        return newAttrs;
    }

    function clearPlaceholder(event, value) {
        
        var input = this;
        var $input = $(this);
        
        if (input.value === $input.attr((debugMode ? 'placeholder-x' : 'placeholder')) && $input.hasClass(settings.customClass)) {
            
            input.value = '';
            $input.removeClass(settings.customClass);

            if ($input.data('placeholder-password')) {

                $input = $input.hide().nextAll('input[type="password"]:first').show().attr('id', $input.removeAttr('id').data('placeholder-id'));
                
                // If `clearPlaceholder` was called from `$.valHooks.input.set`
                if (event === true) {
                    $input[0].value = value;

                    return value;
                }

                $input.focus();

            } else {
                input == safeActiveElement() && input.select();
            }
        }
    }

    function setPlaceholder(event) {
        var $replacement;
        var input = this;
        var $input = $(this);
        var id = input.id;

        // If the placeholder is activated, triggering blur event (`$input.trigger('blur')`) should do nothing.
        if (event && event.type === 'blur' && $input.hasClass(settings.customClass)) {
            return;
        }

        if (input.value === '') {
            if (input.type === 'password') {
                if (!$input.data('placeholder-textinput')) {
                    
                    try {
                        $replacement = $input.clone().prop({ 'type': 'text' });
                    } catch(e) {
                        $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
                    }

                    $replacement
                        .removeAttr('name')
                        .data({
                            'placeholder-enabled': true,
                            'placeholder-password': $input,
                            'placeholder-id': id
                        })
                        .bind('focus.placeholder', clearPlaceholder);

                    $input
                        .data({
                            'placeholder-textinput': $replacement,
                            'placeholder-id': id
                        })
                        .before($replacement);
                }

                input.value = '';
                $input = $input.removeAttr('id').hide().prevAll('input[type="text"]:first').attr('id', $input.data('placeholder-id')).show();

            } else {
                
                var $passwordInput = $input.data('placeholder-password');

                if ($passwordInput) {
                    $passwordInput[0].value = '';
                    $input.attr('id', $input.data('placeholder-id')).show().nextAll('input[type="password"]:last').hide().removeAttr('id');
                }
            }

            $input.addClass(settings.customClass);
            $input[0].value = $input.attr((debugMode ? 'placeholder-x' : 'placeholder'));

        } else {
            $input.removeClass(settings.customClass);
        }
    }

    function safeActiveElement() {
        // Avoid IE9 `document.activeElement` of death
        try {
            return document.activeElement;
        } catch (exception) {}
    }
}));

if(typeof Object.create!=="function"){Object.create=function(b){function a(){}a.prototype=b;return new a()}}var ua={toString:function(){return navigator.userAgent},test:function(a){return this.toString().toLowerCase().indexOf(a.toLowerCase())>-1}};ua.version=(ua.toString().toLowerCase().match(/[\s\S]+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1];ua.webkit=ua.test("webkit");ua.gecko=ua.test("gecko")&&!ua.webkit;ua.opera=ua.test("opera");ua.ie=ua.test("msie")&&!ua.opera;ua.ie6=ua.ie&&document.compatMode&&typeof document.documentElement.style.maxHeight==="undefined";ua.ie7=ua.ie&&document.documentElement&&typeof document.documentElement.style.maxHeight!=="undefined"&&typeof XDomainRequest==="undefined";ua.ie8=ua.ie&&typeof XDomainRequest!=="undefined";var domReady=function(){var a=[];var b=function(){if(!arguments.callee.done){arguments.callee.done=true;for(var c=0;c<a.length;c++){a[c]()}}};if(document.addEventListener){document.addEventListener("DOMContentLoaded",b,false)}if(ua.ie){(function(){try{document.documentElement.doScroll("left")}catch(c){setTimeout(arguments.callee,50);return}b()})();document.onreadystatechange=function(){if(document.readyState==="complete"){document.onreadystatechange=null;b()}}}if(ua.webkit&&document.readyState){(function(){if(document.readyState!=="loading"){b()}else{setTimeout(arguments.callee,10)}})()}window.onload=b;return function(c){if(typeof c==="function"){a[a.length]=c}return c}}();var cssHelper=function(){var g={BLOCKS:/[^\s{][^{]*\{(?:[^{}]*\{[^{}]*\}[^{}]*|[^{}]*)*\}/g,BLOCKS_INSIDE:/[^\s{][^{]*\{[^{}]*\}/g,DECLARATIONS:/[a-zA-Z\-]+[^;]*:[^;]+;/g,RELATIVE_URLS:/url\(['"]?([^\/\)'"][^:\)'"]+)['"]?\)/g,REDUNDANT_COMPONENTS:/(?:\/\*([^*\\\\]|\*(?!\/))+\*\/|@import[^;]+;)/g,REDUNDANT_WHITESPACE:/\s*(,|:|;|\{|\})\s*/g,MORE_WHITESPACE:/\s{2,}/g,FINAL_SEMICOLONS:/;\}/g,NOT_WHITESPACE:/\S+/g};var k,j=false;var b=[];var t=function(u){if(typeof u==="function"){b[b.length]=u}};var m=function(){for(var u=0;u<b.length;u++){b[u](k)}};var c={};var n=function(y,u){if(c[y]){var x=c[y].listeners;if(x){for(var w=0;w<x.length;w++){x[w](u)}}}};var h=function(v,w,z){if(ua.ie&&!window.XMLHttpRequest){window.XMLHttpRequest=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}if(!XMLHttpRequest){return""}var x=new XMLHttpRequest();try{x.open("get",v,true);x.setRequestHeader("X_REQUESTED_WITH","XMLHttpRequest")}catch(y){z();return}var u=false;setTimeout(function(){u=true},5000);document.documentElement.style.cursor="progress";x.onreadystatechange=function(){if(x.readyState===4&&!u){if(!x.status&&location.protocol==="file:"||(x.status>=200&&x.status<300)||x.status===304||navigator.userAgent.indexOf("Safari")>-1&&typeof x.status==="undefined"){w(x.responseText)}else{z()}document.documentElement.style.cursor="";x=null}};x.send("")};var f=function(u){u=u.replace(g.REDUNDANT_COMPONENTS,"");u=u.replace(g.REDUNDANT_WHITESPACE,"$1");u=u.replace(g.MORE_WHITESPACE," ");u=u.replace(g.FINAL_SEMICOLONS,"}");return u};var a={mediaQueryList:function(C){var u={};var B=C.indexOf("{");var y=C.substring(0,B);C=C.substring(B+1,C.length-1);var x=[],w=[];var v=y.toLowerCase().substring(7).split(",");for(var A=0;A<v.length;A++){x[x.length]=a.mediaQuery(v[A],u)}var z=C.match(g.BLOCKS_INSIDE);if(z!==null){for(A=0;A<z.length;A++){w[w.length]=a.rule(z[A],u)}}u.getMediaQueries=function(){return x};u.getRules=function(){return w};u.getListText=function(){return y};u.getCssText=function(){return C};return u},mediaQuery:function(D,C){D=D||"";var v=false,B;var x=[];var u=true;var A=D.match(g.NOT_WHITESPACE);for(var z=0;z<A.length;z++){var w=A[z];if(!B&&(w==="not"||w==="only")){if(w==="not"){v=true}}else{if(!B){B=w}else{if(w.charAt(0)==="("){var y=w.substring(1,w.length-1).split(":");x[x.length]={mediaFeature:y[0],value:y[1]||null}}}}}return{getList:function(){return C||null},getValid:function(){return u},getNot:function(){return v},getMediaType:function(){return B},getExpressions:function(){return x}}},rule:function(B,y){var u={};var z=B.indexOf("{");var A=B.substring(0,z);var C=A.split(",");var v=[];var w=B.substring(z+1,B.length-1).split(";");for(var x=0;x<w.length;x++){v[v.length]=a.declaration(w[x],u)}u.getMediaQueryList=function(){return y||null};u.getSelectors=function(){return C};u.getSelectorText=function(){return A};u.getDeclarations=function(){return v};u.getPropertyValue=function(E){for(var D=0;D<v.length;D++){if(v[D].getProperty()===E){return v[D].getValue()}}return null};return u},declaration:function(x,y){var u=x.indexOf(":");var z=x.substring(0,u);var w=x.substring(u+1);return{getRule:function(){return y||null},getProperty:function(){return z},getValue:function(){return w}}}};var s=function(z){if(typeof z.cssHelperText!=="string"){return}var y={mediaQueryLists:[],rules:[],selectors:{},declarations:[],properties:{}};var E=y.mediaQueryLists;var D=y.rules;var u=z.cssHelperText.match(g.BLOCKS);if(u!==null){for(var C=0;C<u.length;C++){if(u[C].substring(0,7)==="@media "){E[E.length]=a.mediaQueryList(u[C]);D=y.rules=D.concat(E[E.length-1].getRules())}else{D[D.length]=a.rule(u[C])}}}var w=y.selectors;var v=function(H){var G=H.getSelectors();for(var F=0;F<G.length;F++){var I=G[F];if(!w[I]){w[I]=[]}w[I][w[I].length]=H}};for(C=0;C<D.length;C++){v(D[C])}var B=y.declarations;for(C=0;C<D.length;C++){B=y.declarations=B.concat(D[C].getDeclarations())}var x=y.properties;for(C=0;C<B.length;C++){var A=B[C].getProperty();if(!x[A]){x[A]=[]}x[A][x[A].length]=B[C]}z.cssHelperParsed=y;k[k.length]=z;return y};var d=function(v,u){v.cssHelperText=f(u||v.innerHTML);return s(v)};var r=function(){j=true;k=[];var v=[];var B=function(){for(var D=0;D<v.length;D++){s(v[D])}var E=document.getElementsByTagName("style");for(D=0;D<E.length;D++){d(E[D])}j=false;m()};var C=document.getElementsByTagName("link");for(var x=0;x<C.length;x++){var A=C[x];try{if(A.getAttribute("rel").indexOf("style")>-1&&A.href&&A.href.length!==0&&!A.disabled){v[v.length]=A}}catch(y){}}if(v.length>0){var z=0;var w=function(){z++;if(z===v.length){B()}};var u=function(E){var D=E.href;h(D,function(F){F=f(F).replace(g.RELATIVE_URLS,"url("+D.substring(0,D.lastIndexOf("/"))+"/$1)");E.cssHelperText=F;w()},w)};for(x=0;x<v.length;x++){u(v[x])}}else{B()}};var l={mediaQueryLists:"array",rules:"array",selectors:"object",declarations:"array",properties:"object"};var q={mediaQueryLists:null,rules:null,selectors:null,declarations:null,properties:null};var i=function(w,u){if(q[w]!==null){if(l[w]==="array"){return(q[w]=q[w].concat(u))}else{var y=q[w];for(var x in u){if(u.hasOwnProperty(x)){if(!y[x]){y[x]=u[x]}else{y[x]=y[x].concat(u[x])}}}return y}}};var o=function(u){q[u]=(l[u]==="array")?[]:{};for(var v=0;v<k.length;v++){i(u,k[v].cssHelperParsed[u])}return q[u]};domReady(function(){var v=document.body.getElementsByTagName("*");for(var u=0;u<v.length;u++){v[u].checkedByCssHelper=true}if(document.implementation.hasFeature("MutationEvents","2.0")||window.MutationEvent){document.body.addEventListener("DOMNodeInserted",function(x){var w=x.target;if(w.nodeType===1){n("DOMElementInserted",w);w.checkedByCssHelper=true}},false)}else{setInterval(function(){var x=document.body.getElementsByTagName("*");for(var w=0;w<x.length;w++){if(!x[w].checkedByCssHelper){n("DOMElementInserted",x[w]);x[w].checkedByCssHelper=true}}},1000)}});var p=function(u){if(typeof window.innerWidth!="undefined"){return window["inner"+u]}else{if(typeof document.documentElement!="undefined"&&typeof document.documentElement.clientWidth!="undefined"&&document.documentElement.clientWidth!=0){return document.documentElement["client"+u]}}};return{addStyle:function(v,w){var u=document.createElement("style");u.setAttribute("type","text/css");document.getElementsByTagName("head")[0].appendChild(u);if(u.styleSheet){u.styleSheet.cssText=v}else{u.appendChild(document.createTextNode(v))}u.addedWithCssHelper=true;if(typeof w==="undefined"||w===true){cssHelper.parsed(function(x){var y=d(u,v);for(var z in y){if(y.hasOwnProperty(z)){i(z,y[z])}}n("newStyleParsed",u)})}else{u.parsingDisallowed=true}return u},removeStyle:function(u){return u.parentNode.removeChild(u)},parsed:function(u){if(j){t(u)}else{if(typeof k!=="undefined"){if(typeof u==="function"){u(k)}}else{t(u);r()}}},mediaQueryLists:function(u){cssHelper.parsed(function(v){u(q.mediaQueryLists||o("mediaQueryLists"))})},rules:function(u){cssHelper.parsed(function(v){u(q.rules||o("rules"))})},selectors:function(u){cssHelper.parsed(function(v){u(q.selectors||o("selectors"))})},declarations:function(u){cssHelper.parsed(function(v){u(q.declarations||o("declarations"))})},properties:function(u){cssHelper.parsed(function(v){u(q.properties||o("properties"))})},broadcast:n,addListener:function(v,u){if(typeof u==="function"){if(!c[v]){c[v]={listeners:[]}}c[v].listeners[c[v].listeners.length]=u}},removeListener:function(x,w){if(typeof w==="function"&&c[x]){var u=c[x].listeners;for(var v=0;v<u.length;v++){if(u[v]===w){u.splice(v,1);v-=1}}}},getViewportWidth:function(){return p("Width")},getViewportHeight:function(){return p("Height")}}}();domReady(function enableCssMediaQueries(){var f;var l={LENGTH_UNIT:/[0-9]+(em|ex|px|in|cm|mm|pt|pc)$/,RESOLUTION_UNIT:/[0-9]+(dpi|dpcm)$/,ASPECT_RATIO:/^[0-9]+\/[0-9]+$/,ABSOLUTE_VALUE:/^[0-9]*(\.[0-9]+)*$/};var o=[];var j=function(){var s="css3-mediaqueries-test";var r=document.createElement("div");r.id=s;var q=cssHelper.addStyle("@media all and (width) { #"+s+" { width: 1px !important; } }",false);document.body.appendChild(r);var p=r.offsetWidth===1;q.parentNode.removeChild(q);r.parentNode.removeChild(r);j=function(){return p};return p};var b=function(){f=document.createElement("div");f.style.cssText="position:absolute;top:-9999em;left:-9999em;margin:0;border:none;padding:0;width:1em;font-size:1em;";document.body.appendChild(f);if(f.offsetWidth!==16){f.style.fontSize=16/f.offsetWidth+"em"}f.style.width=""};var a=function(q){f.style.width=q;var p=f.offsetWidth;f.style.width="";return p};var n=function(B,y){var r=B.length;var u=(B.substring(0,4)==="min-");var x=(!u&&B.substring(0,4)==="max-");if(y!==null){var t;var v;if(l.LENGTH_UNIT.exec(y)){t="length";v=a(y)}else{if(l.RESOLUTION_UNIT.exec(y)){t="resolution";v=parseInt(y,10);var z=y.substring((v+"").length)}else{if(l.ASPECT_RATIO.exec(y)){t="aspect-ratio";v=y.split("/")}else{if(l.ABSOLUTE_VALUE){t="absolute";v=y}else{t="unknown"}}}}}var q,A;if("device-width"===B.substring(r-12,r)){q=screen.width;if(y!==null){if(t==="length"){return((u&&q>=v)||(x&&q<v)||(!u&&!x&&q===v))}else{return false}}else{return q>0}}else{if("device-height"===B.substring(r-13,r)){A=screen.height;if(y!==null){if(t==="length"){return((u&&A>=v)||(x&&A<v)||(!u&&!x&&A===v))}else{return false}}else{return A>0}}else{if("width"===B.substring(r-5,r)){q=document.documentElement.clientWidth||document.body.clientWidth;if(y!==null){if(t==="length"){return((u&&q>=v)||(x&&q<v)||(!u&&!x&&q===v))}else{return false}}else{return q>0}}else{if("height"===B.substring(r-6,r)){A=document.documentElement.clientHeight||document.body.clientHeight;if(y!==null){if(t==="length"){return((u&&A>=v)||(x&&A<v)||(!u&&!x&&A===v))}else{return false}}else{return A>0}}else{if("device-aspect-ratio"===B.substring(r-19,r)){return t==="aspect-ratio"&&screen.width*v[1]===screen.height*v[0]}else{if("color-index"===B.substring(r-11,r)){var p=Math.pow(2,screen.colorDepth);if(y!==null){if(t==="absolute"){return((u&&p>=v)||(x&&p<v)||(!u&&!x&&p===v))}else{return false}}else{return p>0}}else{if("color"===B.substring(r-5,r)){var s=screen.colorDepth;if(y!==null){if(t==="absolute"){return((u&&s>=v)||(x&&s<v)||(!u&&!x&&s===v))}else{return false}}else{return s>0}}else{if("resolution"===B.substring(r-10,r)){var w;if(z==="dpcm"){w=a("1cm")}else{w=a("1in")}if(y!==null){if(t==="resolution"){return((u&&w>=v)||(x&&w<v)||(!u&&!x&&w===v))}else{return false}}else{return w>0}}else{return false}}}}}}}}};var g=function(r){var u=r.getValid();var t=r.getExpressions();var p=t.length;if(p>0){for(var q=0;q<p&&u;q++){u=n(t[q].mediaFeature,t[q].value)}var s=r.getNot();return(u&&!s||s&&!u)}};var m=function(p){var u=p.getMediaQueries();var r={};for(var q=0;q<u.length;q++){if(g(u[q])){r[u[q].getMediaType()]=true}}var v=[],x=0;for(var w in r){if(r.hasOwnProperty(w)){if(x>0){v[x++]=","}v[x++]=w}}if(v.length>0){o[o.length]=cssHelper.addStyle("@media "+v.join("")+"{"+p.getCssText()+"}",false)}};var d=function(p){for(var q=0;q<p.length;q++){m(p[q])}if(ua.ie){document.documentElement.style.display="block";setTimeout(function(){document.documentElement.style.display=""},0);setTimeout(function(){cssHelper.broadcast("cssMediaQueriesTested")},100)}else{cssHelper.broadcast("cssMediaQueriesTested")}};var k=function(){for(var p=0;p<o.length;p++){cssHelper.removeStyle(o[p])}o=[];cssHelper.mediaQueryLists(d)};var i=0;var h=function(){var r=cssHelper.getViewportWidth();var t=cssHelper.getViewportHeight();if(ua.ie){var q=document.createElement("div");q.style.position="absolute";q.style.top="-9999em";q.style.overflow="scroll";document.body.appendChild(q);i=q.offsetWidth-q.clientWidth;document.body.removeChild(q)}var s;var p=function(){var u=cssHelper.getViewportWidth();var v=cssHelper.getViewportHeight();if(Math.abs(u-r)>i||Math.abs(v-t)>i){r=u;t=v;clearTimeout(s);s=setTimeout(function(){if(!j()){k()}else{cssHelper.broadcast("cssMediaQueriesTested")}},500)}};window.onresize=function(){var u=window.onresize||function(){};return function(){u();p()}}()};var c=document.documentElement;c.style.marginLeft="-32767px";setTimeout(function(){c.style.marginTop=""},20000);return function(){if(!j()){cssHelper.addListener("newStyleParsed",function(p){d(p.cssHelperParsed.mediaQueryLists)});cssHelper.addListener("cssMediaQueriesTested",function(){if(ua.ie){c.style.width="1px"}setTimeout(function(){c.style.width="";c.style.marginLeft=""},0);cssHelper.removeListener("cssMediaQueriesTested",arguments.callee)});b();k()}else{c.style.marginLeft=""}h()}}());try{document.execCommand("BackgroundImageCache",false,true)}catch(e){};



$(document).ready(function() {


 

//per far andare il placeholdr in ie9
jQuery('input[placeholder]').focus(function() {
    var input = jQuery(this);
    if (input.val() === input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
    }
}).blur(function() {
    var input = jQuery(this);
    if (input.val() === '' || input.val() === input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }
}).blur().parents('form').submit(function() {
    jQuery(this).find('[placeholder]').each(function() {
        var input = jQuery(this);
        if (input.val() === input.attr('placeholder')) {
            input.val('');
        }
    });
});




});







/* Disable minification (remove `.min` from URL path) for more info */

(function(self, undefined) {function Call(t,l){var n=arguments.length>2?arguments[2]:[];if(!1===IsCallable(t))throw new TypeError(Object.prototype.toString.call(t)+"is not a function.");return t.apply(l,n)}function CreateMethodProperty(e,r,t){var a={value:t,writable:!0,enumerable:!1,configurable:!0};Object.defineProperty(e,r,a)}function Get(n,t){return n[t]}function HasOwnProperty(r,t){return Object.prototype.hasOwnProperty.call(r,t)}function IsCallable(n){return"function"==typeof n}function SameValueNonNumber(e,n){return e===n}function ToInteger(n){var i=Number(n);return isNaN(i)?0:1/i===Infinity||1/i==-Infinity||i===Infinity||i===-Infinity?i:(i<0?-1:1)*Math.floor(Math.abs(i))}function ToLength(n){var t=ToInteger(n);return t<=0?0:Math.min(t,Math.pow(2,53)-1)}function ToObject(e){if(null===e||e===undefined)throw TypeError();return Object(e)}function GetV(t,e){return ToObject(t)[e]}function GetMethod(e,n){var r=GetV(e,n);if(null===r||r===undefined)return undefined;if(!1===IsCallable(r))throw new TypeError("Method not callable: "+n);return r}function Type(e){switch(typeof e){case"undefined":return"undefined";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"symbol":return"symbol";default:return null===e?"null":"Symbol"in self&&(e instanceof self.Symbol||e.constructor===self.Symbol)?"symbol":"object"}}function OrdinaryToPrimitive(r,t){if("string"===t)var e=["toString","valueOf"];else e=["valueOf","toString"];for(var i=0;i<e.length;++i){var n=e[i],a=Get(r,n);if(IsCallable(a)){var o=Call(a,r);if("object"!==Type(o))return o}}throw new TypeError("Cannot convert to primitive.")}function SameValueZero(n,e){return Type(n)===Type(e)&&("number"===Type(n)?!(!isNaN(n)||!isNaN(e))||(1/n===Infinity&&1/e==-Infinity||(1/n==-Infinity&&1/e===Infinity||n===e)):SameValueNonNumber(n,e))}function ToPrimitive(e){var t=arguments.length>1?arguments[1]:undefined;if("object"===Type(e)){if(arguments.length<2)var i="default";else t===String?i="string":t===Number&&(i="number");var r="function"==typeof self.Symbol&&"symbol"==typeof self.Symbol.toPrimitive?GetMethod(e,self.Symbol.toPrimitive):undefined;if(r!==undefined){var n=Call(r,e,[i]);if("object"!==Type(n))return n;throw new TypeError("Cannot convert exotic object to primitive.")}return"default"===i&&(i="number"),OrdinaryToPrimitive(e,i)}return e}function ToString(t){switch(Type(t)){case"symbol":throw new TypeError("Cannot convert a Symbol value to a string");case"object":return ToString(ToPrimitive(t,String));default:return String(t)}}function ToPropertyKey(r){var i=ToPrimitive(r,String);return"symbol"===Type(i)?i:ToString(i)}CreateMethodProperty(Array.prototype,"includes",function e(r){"use strict";var t=ToObject(this),o=ToLength(Get(t,"length"));if(0===o)return!1;var n=ToInteger(arguments[1]);if(n>=0)var a=n;else(a=o+n)<0&&(a=0);for(;a<o;){var i=Get(t,ToString(a));if(SameValueZero(r,i))return!0;a+=1}return!1});!function(){function e(e,t){if(!e)throw new Error("Not enough arguments");var n;if("createEvent"in document){n=document.createEvent("Event");var o=!(!t||t.bubbles===undefined)&&t.bubbles,i=!(!t||t.cancelable===undefined)&&t.cancelable;return n.initEvent(e,o,i),n}return n=document.createEventObject(),n.type=e,n.bubbles=!(!t||t.bubbles===undefined)&&t.bubbles,n.cancelable=!(!t||t.cancelable===undefined)&&t.cancelable,n}var t={click:1,dblclick:1,keyup:1,keypress:1,keydown:1,mousedown:1,mouseup:1,mousemove:1,mouseover:1,mouseenter:1,mouseleave:1,mouseout:1,storage:1,storagecommit:1,textinput:1};if("undefined"!=typeof document&&"undefined"!=typeof window){var n=window.Event&&window.Event.prototype||null;e.NONE=0,e.CAPTURING_PHASE=1,e.AT_TARGET=2,e.BUBBLING_PHASE=3,window.Event=Window.prototype.Event=e,n&&Object.defineProperty(window.Event,"prototype",{configurable:!1,enumerable:!1,writable:!0,value:n}),"createEvent"in document||(window.addEventListener=Window.prototype.addEventListener=Document.prototype.addEventListener=Element.prototype.addEventListener=function o(){var e=this,n=arguments[0],o=arguments[1];if(e===window&&n in t)throw new Error("In IE8 the event: "+n+" is not available on the window object. Please see https://github.com/Financial-Times/polyfill-service/issues/317 for more information.");e._events||(e._events={}),e._events[n]||(e._events[n]=function(t){var n,o=e._events[t.type].list,i=o.slice(),r=-1,c=i.length;for(t.preventDefault=function a(){!1!==t.cancelable&&(t.returnValue=!1)},t.stopPropagation=function l(){t.cancelBubble=!0},t.stopImmediatePropagation=function s(){t.cancelBubble=!0,t.cancelImmediate=!0},t.currentTarget=e,t.relatedTarget=t.fromElement||null,t.target=t.target||t.srcElement||e,t.timeStamp=(new Date).getTime(),t.clientX&&(t.pageX=t.clientX+document.documentElement.scrollLeft,t.pageY=t.clientY+document.documentElement.scrollTop);++r<c&&!t.cancelImmediate;)r in i&&(n=i[r],o.includes(n)&&"function"==typeof n&&n.call(e,t))},e._events[n].list=[],e.attachEvent&&e.attachEvent("on"+n,e._events[n])),e._events[n].list.push(o)},window.removeEventListener=Window.prototype.removeEventListener=Document.prototype.removeEventListener=Element.prototype.removeEventListener=function i(){var e,t=this,n=arguments[0],o=arguments[1];t._events&&t._events[n]&&t._events[n].list&&-1!==(e=t._events[n].list.indexOf(o))&&(t._events[n].list.splice(e,1),t._events[n].list.length||(t.detachEvent&&t.detachEvent("on"+n,t._events[n]),delete t._events[n]))},window.dispatchEvent=Window.prototype.dispatchEvent=Document.prototype.dispatchEvent=Element.prototype.dispatchEvent=function r(e){if(!arguments.length)throw new Error("Not enough arguments");if(!e||"string"!=typeof e.type)throw new Error("DOM Events Exception 0");var t=this,n=e.type;try{if(!e.bubbles){e.cancelBubble=!0;var o=function(e){e.cancelBubble=!0,(t||window).detachEvent("on"+n,o)};this.attachEvent("on"+n,o)}this.fireEvent("on"+n,e)}catch(i){e.target=t;do{e.currentTarget=t,"_events"in t&&"function"==typeof t._events[n]&&t._events[n].call(t,e),"function"==typeof t["on"+n]&&t["on"+n].call(t,e),t=9===t.nodeType?t.parentWindow:t.parentNode}while(t&&!e.cancelBubble)}return!0},document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&document.dispatchEvent(new e("DOMContentLoaded",{bubbles:!0}))}))}}();!function(t,e){"use strict";function n(t){this.time=t.time,this.target=t.target,this.rootBounds=t.rootBounds,this.boundingClientRect=t.boundingClientRect,this.intersectionRect=t.intersectionRect||a();try{this.isIntersecting=!!t.intersectionRect}catch(r){}var e=this.boundingClientRect,n=e.width*e.height,o=this.intersectionRect,i=o.width*o.height;this.intersectionRatio=n?Number((i/n).toFixed(4)):this.isIntersecting?1:0}function o(t,e){var n=e||{};if("function"!=typeof t)throw new Error("callback must be a function");if(n.root&&1!=n.root.nodeType)throw new Error("root must be an Element");this._checkForIntersections=r(this._checkForIntersections.bind(this),this.THROTTLE_TIMEOUT),this._callback=t,this._observationTargets=[],this._queuedEntries=[],this._rootMarginValues=this._parseRootMargin(n.rootMargin),this.thresholds=this._initThresholds(n.threshold),this.root=n.root||null,this.rootMargin=this._rootMarginValues.map(function(t){return t.value+t.unit}).join(" ")}function i(){return t.performance&&performance.now&&performance.now()}function r(t,e){var n=null;return function(){n||(n=setTimeout(function(){t(),n=null},e))}}function s(t,e,n,o){"function"==typeof t.addEventListener?t.addEventListener(e,n,o||!1):"function"==typeof t.attachEvent&&t.attachEvent("on"+e,n)}function h(t,e,n,o){"function"==typeof t.removeEventListener?t.removeEventListener(e,n,o||!1):"function"==typeof t.detatchEvent&&t.detatchEvent("on"+e,n)}function c(t,e){var n=Math.max(t.top,e.top),o=Math.min(t.bottom,e.bottom),i=Math.max(t.left,e.left),r=Math.min(t.right,e.right),s=r-i,h=o-n;return s>=0&&h>=0&&{top:n,bottom:o,left:i,right:r,width:s,height:h}}function u(t){var e;try{e=t.getBoundingClientRect()}catch(n){}return e?(e.width&&e.height||(e={top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.right-e.left,height:e.bottom-e.top}),e):a()}function a(){return{top:0,bottom:0,left:0,right:0,width:0,height:0}}function l(t,e){for(var n=e;n;){if(n==t)return!0;n=p(n)}return!1}function p(t){var e=t.parentNode;return e&&11==e.nodeType&&e.host?e.host:e&&e.assignedSlot?e.assignedSlot.parentNode:e}var f=[];o.prototype.THROTTLE_TIMEOUT=100,o.prototype.POLL_INTERVAL=null,o.prototype.USE_MUTATION_OBSERVER=!0,o.prototype.observe=function(t){if(!this._observationTargets.some(function(e){return e.element==t})){if(!t||1!=t.nodeType)throw new Error("target must be an Element");this._registerInstance(),this._observationTargets.push({element:t,entry:null}),this._monitorIntersections(),this._checkForIntersections()}},o.prototype.unobserve=function(t){this._observationTargets=this._observationTargets.filter(function(e){return e.element!=t}),this._observationTargets.length||(this._unmonitorIntersections(),this._unregisterInstance())},o.prototype.disconnect=function(){this._observationTargets=[],this._unmonitorIntersections(),this._unregisterInstance()},o.prototype.takeRecords=function(){var t=this._queuedEntries.slice();return this._queuedEntries=[],t},o.prototype._initThresholds=function(t){var e=t||[0];return Array.isArray(e)||(e=[e]),e.sort().filter(function(t,e,n){if("number"!=typeof t||isNaN(t)||t<0||t>1)throw new Error("threshold must be a number between 0 and 1 inclusively");return t!==n[e-1]})},o.prototype._parseRootMargin=function(t){var e=t||"0px",n=e.split(/\s+/).map(function(t){var e=/^(-?\d*\.?\d+)(px|%)$/.exec(t);if(!e)throw new Error("rootMargin must be specified in pixels or percent");return{value:parseFloat(e[1]),unit:e[2]}});return n[1]=n[1]||n[0],n[2]=n[2]||n[0],n[3]=n[3]||n[1],n},o.prototype._monitorIntersections=function(){this._monitoringIntersections||(this._monitoringIntersections=!0,this.POLL_INTERVAL?this._monitoringInterval=setInterval(this._checkForIntersections,this.POLL_INTERVAL):(s(t,"resize",this._checkForIntersections,!0),s(e,"scroll",this._checkForIntersections,!0),this.USE_MUTATION_OBSERVER&&"MutationObserver"in t&&(this._domObserver=new MutationObserver(this._checkForIntersections),this._domObserver.observe(e,{attributes:!0,childList:!0,characterData:!0,subtree:!0}))))},o.prototype._unmonitorIntersections=function(){this._monitoringIntersections&&(this._monitoringIntersections=!1,clearInterval(this._monitoringInterval),this._monitoringInterval=null,h(t,"resize",this._checkForIntersections,!0),h(e,"scroll",this._checkForIntersections,!0),this._domObserver&&(this._domObserver.disconnect(),this._domObserver=null))},o.prototype._checkForIntersections=function(){var t=this._rootIsInDom(),e=t?this._getRootRect():a();this._observationTargets.forEach(function(o){var r=o.element,s=u(r),h=this._rootContainsTarget(r),c=o.entry,a=t&&h&&this._computeTargetAndRootIntersection(r,e),l=o.entry=new n({time:i(),target:r,boundingClientRect:s,rootBounds:e,intersectionRect:a});c?t&&h?this._hasCrossedThreshold(c,l)&&this._queuedEntries.push(l):c&&c.isIntersecting&&this._queuedEntries.push(l):this._queuedEntries.push(l)},this),this._queuedEntries.length&&this._callback(this.takeRecords(),this)},o.prototype._computeTargetAndRootIntersection=function(n,o){if("none"!=t.getComputedStyle(n).display){for(var i=u(n),r=i,s=p(n),h=!1;!h;){var a=null,l=1==s.nodeType?t.getComputedStyle(s):{};if("none"==l.display)return;if(s==this.root||s==e?(h=!0,a=o):s!=e.body&&s!=e.documentElement&&"visible"!=l.overflow&&(a=u(s)),a&&!(r=c(a,r)))break;s=p(s)}return r}},o.prototype._getRootRect=function(){var t;if(this.root)t=u(this.root);else{var n=e.documentElement,o=e.body;t={top:0,left:0,right:n.clientWidth||o.clientWidth,width:n.clientWidth||o.clientWidth,bottom:n.clientHeight||o.clientHeight,height:n.clientHeight||o.clientHeight}}return this._expandRectByRootMargin(t)},o.prototype._expandRectByRootMargin=function(t){var e=this._rootMarginValues.map(function(e,n){return"px"==e.unit?e.value:e.value*(n%2?t.width:t.height)/100}),n={top:t.top-e[0],right:t.right+e[1],bottom:t.bottom+e[2],left:t.left-e[3]};return n.width=n.right-n.left,n.height=n.bottom-n.top,n},o.prototype._hasCrossedThreshold=function(t,e){var n=t&&t.isIntersecting?t.intersectionRatio||0:-1,o=e.isIntersecting?e.intersectionRatio||0:-1;if(n!==o)for(var i=0;i<this.thresholds.length;i++){var r=this.thresholds[i];if(r==n||r==o||r<n!=r<o)return!0}},o.prototype._rootIsInDom=function(){return!this.root||l(e,this.root)},o.prototype._rootContainsTarget=function(t){return l(this.root||e,t)},o.prototype._registerInstance=function(){f.indexOf(this)<0&&f.push(this)},o.prototype._unregisterInstance=function(){var t=f.indexOf(this);-1!=t&&f.splice(t,1)},t.IntersectionObserver=o,t.IntersectionObserverEntry=n}(window,document);!function(){var e=Object.getOwnPropertyDescriptor,t=function(){try{return 1===Object.defineProperty(document.createElement("div"),"one",{get:function(){return 1}}).one}catch(e){return!1}},r={}.toString,n="".split;CreateMethodProperty(Object,"getOwnPropertyDescriptor",function c(o,i){var a=ToObject(o);a=("string"===Type(a)||a instanceof String)&&"[object String]"==r.call(o)?n.call(o,""):Object(o);var u=ToPropertyKey(i);if(t)try{return e(a,u)}catch(l){}if(HasOwnProperty(a,u))return{enumerable:!0,configurable:!0,writable:!0,value:a[u]}})}();CreateMethodProperty(Object,"keys",function(){"use strict";function t(t){var e=r.call(t),n="[object Arguments]"===e;return n||(n="[object Array]"!==e&&null!==t&&"object"==typeof t&&"number"==typeof t.length&&t.length>=0&&"[object Function]"===r.call(t.callee)),n}var e=Object.prototype.hasOwnProperty,r=Object.prototype.toString,n=Object.prototype.propertyIsEnumerable,o=!n.call({toString:null},"toString"),l=n.call(function(){},"prototype"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],i=function(t){var e=t.constructor;return e&&e.prototype===t},u={$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!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},a=function(){if("undefined"==typeof window)return!1;for(var t in window)try{if(!u["$"+t]&&e.call(window,t)&&null!==window[t]&&"object"==typeof window[t])try{i(window[t])}catch(r){return!0}}catch(r){return!0}return!1}(),f=function(t){if("undefined"==typeof window||!a)return i(t);try{return i(t)}catch(e){return!1}};return function p(n){var i="[object Function]"===r.call(n),u=t(n),a="[object String]"===r.call(n),p=[];if(n===undefined||null===n)throw new TypeError("Cannot convert undefined or null to object");var s=l&&i;if(a&&n.length>0&&!e.call(n,0))for(var y=0;y<n.length;++y)p.push(String(y));if(u&&n.length>0)for(var g=0;g<n.length;++g)p.push(String(g));else for(var h in n)s&&"prototype"===h||!e.call(n,h)||p.push(String(h));if(o)for(var w=f(n),d=0;d<c.length;++d)w&&"constructor"===c[d]||!e.call(n,c[d])||p.push(c[d]);return p}}());CreateMethodProperty(Object,"assign",function e(t,r){var n=ToObject(t);if(1===arguments.length)return n;var o,c,a,l,i=Array.prototype.slice.call(arguments,1);for(o=0;o<i.length;o++){var p=i[o];for(p===undefined||null===p?a=[]:(l="[object String]"===Object.prototype.toString.call(p)?String(p).split(""):ToObject(p),a=Object.keys(l)),c=0;c<a.length;c++){var b,y=a[c];try{var g=Object.getOwnPropertyDescriptor(l,y);b=g!==undefined&&!0===g.enumerable}catch(u){b=Object.prototype.propertyIsEnumerable.call(l,y)}if(b){var j=Get(l,y);n[y]=j}}}return n});})('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});

/*! lozad.js - v1.16.0 - 2020-09-06
* https://github.com/ApoorvSaxena/lozad.js
* Copyright (c) 2020 Apoorv Saxena; Licensed MIT */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.lozad=e()}(this,function(){"use strict";
/**
   * Detect IE browser
   * @const {boolean}
   * @private
   */var g="undefined"!=typeof document&&document.documentMode,f={rootMargin:"0px",threshold:0,load:function(t){if("picture"===t.nodeName.toLowerCase()){var e=t.querySelector("img"),r=!1;null===e&&(e=document.createElement("img"),r=!0),g&&t.getAttribute("data-iesrc")&&(e.src=t.getAttribute("data-iesrc")),t.getAttribute("data-alt")&&(e.alt=t.getAttribute("data-alt")),r&&t.append(e)}if("video"===t.nodeName.toLowerCase()&&!t.getAttribute("data-src")&&t.children){for(var a=t.children,o=void 0,i=0;i<=a.length-1;i++)(o=a[i].getAttribute("data-src"))&&(a[i].src=o);t.load()}t.getAttribute("data-poster")&&(t.poster=t.getAttribute("data-poster")),t.getAttribute("data-src")&&(t.src=t.getAttribute("data-src")),t.getAttribute("data-srcset")&&t.setAttribute("srcset",t.getAttribute("data-srcset"));var n=",";if(t.getAttribute("data-background-delimiter")&&(n=t.getAttribute("data-background-delimiter")),t.getAttribute("data-background-image"))t.style.backgroundImage="url('"+t.getAttribute("data-background-image").split(n).join("'),url('")+"')";else if(t.getAttribute("data-background-image-set")){var d=t.getAttribute("data-background-image-set").split(n),u=d[0].substr(0,d[0].indexOf(" "))||d[0];// Substring before ... 1x
u=-1===u.indexOf("url(")?"url("+u+")":u,1===d.length?t.style.backgroundImage=u:t.setAttribute("style",(t.getAttribute("style")||"")+"background-image: "+u+"; background-image: -webkit-image-set("+d+"); background-image: image-set("+d+")")}t.getAttribute("data-toggle-class")&&t.classList.toggle(t.getAttribute("data-toggle-class"))},loaded:function(){}};function A(t){t.setAttribute("data-loaded",!0)}var m=function(t){return"true"===t.getAttribute("data-loaded")},v=function(t){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:document;return t instanceof Element?[t]:t instanceof NodeList?t:e.querySelectorAll(t)};return function(){var r,a,o=0<arguments.length&&void 0!==arguments[0]?arguments[0]:".lozad",t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},e=Object.assign({},f,t),i=e.root,n=e.rootMargin,d=e.threshold,u=e.load,g=e.loaded,s=void 0;"undefined"!=typeof window&&window.IntersectionObserver&&(s=new IntersectionObserver((r=u,a=g,function(t,e){t.forEach(function(t){(0<t.intersectionRatio||t.isIntersecting)&&(e.unobserve(t.target),m(t.target)||(r(t.target),A(t.target),a(t.target)))})}),{root:i,rootMargin:n,threshold:d}));for(var c,l=v(o,i),b=0;b<l.length;b++)(c=l[b]).getAttribute("data-placeholder-background")&&(c.style.background=c.getAttribute("data-placeholder-background"));return{observe:function(){for(var t=v(o,i),e=0;e<t.length;e++)m(t[e])||(s?s.observe(t[e]):(u(t[e]),A(t[e]),g(t[e])))},triggerLoad:function(t){m(t)||(u(t),A(t),g(t))},observer:s}}});

var Trenord = {

    lang: {
        calendar: {
            title: ""
        },
        flightCalendar: {
            titleLeft: "",
            titleRight: "",
            titleCalendar: ""

        }
    },

    globals: {
        debug: false,
        TabControl: 1,
        /*  tab control desktop (3 tab) */
        TabControlMobile: 1,
        /*  tab control mobile (dots) */
        /*   MaxHeight : 1, //   MaxHeight init */
        /*   lastIdFooterTab : 1 //   last id tab -> footer top */
        widget: {
            overlay: false
        },

        /* questi testi statici */
        /* servono per essere scambiati tra le api */
        static: {
            trainDescription: ""
        },
        currentLanguage: 0,
        currentPid: -1,
        mxpAirportLabel: "Aeroporto Malpensa (MXP)",
        checkAiport: true,
        calendar: {
            dateRange: [],
        }

    },

    breakpoint: {
        tablet: {
            maxWidth: 1024,
            minWidth: 768
        },
        mobile: {
            maxWidth: 768,
            minWidth: 320
        },
    },

    user: {

        checkSso: false,
        sso: Cookies.get('sso'),
        enableLogin: true,

        init: function () {
            Trenord.console.log("init {}");
        },

        login: function (username, password) {
            Trenord.console.log("login {}");
        },

        logout: function () {
            Trenord.console.log("logout {}");
        },

        crossCookieSet: function () {
            Trenord.console.log("crossCookieSet {}");
        },
        acceptCookie: function () {
            Trenord.console.log("acceptCookie {}");
        },
        haveAcceptedCookie: function () {
            Trenord.console.log("haveAcceptedCookie {}");
        },
        isLogged: function () {

            Trenord.console.log("isLogged {}");
        }

    },

    fatture: {

        updateFolderId: function () {

            Trenord.popUpMessage.waitResponse();
            $.get('/rest/cta/folderid', function (response) {
                $("#folderId").val(response.message);
                Trenord.popUpMessage.hideModalBox();
                Trenord.popUpMessage.stopSpinner();
            })
        },

        getComuni: function (chiaveProvincia, descrizione) {
            var header = $(".comuni-async .mobile-header-select").clone();
            $("#province").val(descrizione);
            $("#province").parents(".md-input").removeClass("error-stepper");
            Trenord.popUpMessage.waitResponse();

            $.get('/rest/cta/comuni', {
                chiaveProvincia: chiaveProvincia
            }, function (response) {

                $(".comuni-async").html("");

                $(response).each(function (index, value) {

                    //di solito genero un HTML già completo da inserire in pagina
                    // in questo caso data la semplicità del codice facciamo prima così
                    // infatti uso CTA, altrimenti avrei usate RENDER come rest api
                    var el = $("<li>");

                    $(el).html(value.Descrizione);
                    $(el).data('value', value.Chiave);
                    $(".comuni-async").append(el);
                    $(".select-search.comuni").removeClass("disable");


                });
                header.prependTo(".comuni-async");
                $(".select-search  .optionsFilter").val("");
                Trenord.fatture.initSelect();

                Trenord.popUpMessage.hideModalBox();
                Trenord.popUpMessage.stopSpinner();
            });

        },

        initSelect: function () {


            //close mobile select

            $(".mobile-header-select img").click(function () {
                $(".options.active").removeClass("active");
                $(".select-search.active").removeClass("active");
            });


            //contorllo search-select
            $(".select-search").unbind();
            $(".select-search .label").click(function () {
                $(this).parent().trigger("click");
            })
            $(".select-search").click(function () {


                if ($(this).hasClass("active")) {

                    if ($(".select-search.active").length > 1) {
                        $(".select-search").removeClass("active");

                    }
                    $(".select-search.active  .optionsFilter").val("").css("z-index", "-1");
                    $(this).parent().find(".options").toggleClass("active");

                    $(this).toggleClass("active");
                } else {

                    if ($(".select-search.active").length == 1) {
                        $(".select-search").removeClass("active");
                        $(".options").removeClass("active");
                    }

                    $(this).parent().find(".options").toggleClass("active");

                    $(this).toggleClass("active");
                    $(".select-search.active  .optionsFilter").removeClass("hidden");
                    $(".select-search.active  .optionsFilter").focus();
                }


            });

            $(".options li").unbind();
            $(".options li").click(function () {
                $(this).parent().parent().find(".label").addClass("active");
                $(this).parent().parent().find(".selected-option").html($(this).text());
                if ($(this).parent().hasClass("comune")) {
                    $("#city").val($(this).text());
                    $("#city").parents(".md-input").removeClass("error-stepper");// get the current valu
                }
                $(this).parent().removeClass("active");
                $(".select-search.active  .optionsFilter").addClass("hidden");
                $(".select-search.active  .optionsFilter").val("");
                $(".select-search.active ").removeClass("active");
            });

            //ricerca live
            $(".select-search  .optionsFilter").unbind();
            $(".select-search  .optionsFilter").keyup(function () {


                if ($(this).parent().parent().find(".options li.selected").length == 0) {
                    if ($(this).val().length > 0) {
                        $(this).css("z-index", "1");
                    } else {
                        $(this).css("z-index", "-1");
                    }

                    // Retrieve the input field text and reset the count to zero
                    var filter = $(this).val(),
                        count = 0;

                    // Loop through the comment list
                    $(".select-search.active").next().find("li").each(function () {

                        // If the list item does not contain the text phrase fade it out
                        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                            $(this).fadeOut();

                            // Show the list item if the phrase matches and increase the count by 1
                        } else {
                            $(this).show();
                            count++;
                        }
                    });
                }


                // Update the count

            });
        }, init: function () {

            $(document).on('click', function (e) {

                if ($(".options.active").length > 0 && !$(e.target).hasClass("select-search")) {

                    if ($(e.target).closest(".options").length === 0) {
                        $(".options.active").fadeIn();
                        $(".select-search.active .optionsFilter").val("").css("z-index", "-1");
                        $(".options.active li").fadeIn();
                        $(".options").removeClass("active");
                        $(".select-search.active ").removeClass("active");

                    }
                }
                ;
            })

            Trenord.fatture.initSelect();


            $('#canale_acquisto').on('show.bs.select', function () {
                if (Trenord.utility.isMobile() && $(".archivio-filter .dropdown-menu.open .inner.open .mobile-header-select").length == 0) {
                    var header = $(".mobile-header-select.canali-acquisto").clone();
                    header.removeClass("hidden").prependTo(".archivio-filter .dropdown-menu.open .inner.open")
                }

            });

            //label select
            $('#canale_acquisto').on('change', function (e) {
                $(".label-station-select-partenza-andata").addClass("active");

                $('#canale_acquisto').parents(".md-input").removeClass("error-stepper");


            });//CHECK EMAIL
            function isValidEmailAddress(emailAddress) {
                var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
                return pattern.test(emailAddress);
            };


            $("#submit-fatture").click(function () {


                //   return true;
                if ($('input[type=hidden][name=province]').val() == "" || $('input[type=hidden][name=province]').val() === null) {
                    $('input[type=hidden][name=province]').parents(".md-input").addClass("error-stepper");
                } else {
                    $('input[type=hidden][name=province]').parents(".md-input").removeClass("error-stepper");
                }

                if ($('input[type=hidden][name=city]').val() == "" || $('input[type=hidden][name=city]').val() === null) {

                    $('input[type=hidden][name=city]').parents(".md-input").addClass("error-stepper");

                } else {
                    $('input[type=hidden][name=city]').parents(".md-input").removeClass("error-stepper");
                }

                $(".fatture").find(".required:not(div):visible").each(function () {
                    if ($(this).val() == "" || $(this).val() === null) {

                        $(this).parents(".md-input").addClass("error-stepper");

                    } else {


                        //check fatturazione elettronica
                        if ($(this).attr("name") == "sdiCode") {

                            if (($(this).val().length == 6 || $(this).val().length == 7)) {
                                $(this).parents(".md-input").removeClass("error-stepper");
                            } else {
                                $(this).parents(".md-input").addClass("error-stepper");
                            }
                        }


                        //codice fiscale
                        if ($(this).attr("name") == "fiscalCode") {
                            var regex_cf = /^(?:[A-Z][AEIOU][AEIOUX]|[B-DF-HJ-NP-TV-Z]{2}[A-Z]){2}(?:[\dLMNP-V]{2}(?:[A-EHLMPR-T](?:[04LQ][1-9MNP-V]|[15MR][\dLMNP-V]|[26NS][0-8LMNP-U])|[DHPS][37PT][0L]|[ACELMRT][37PT][01LM]|[AC-EHLMPR-T][26NS][9V])|(?:[02468LNQSU][048LQU]|[13579MPRTV][26NS])B[26NS][9V])(?:[A-MZ][1-9MNP-V][\dLMNP-V]{2}|[A-M][0L](?:[1-9MNP-V][\dLMNP-V]|[0L][1-9MNP-V]))[A-Z]$/i;

                            var cf = $(this).val();

                            if (!regex_cf.test(cf)) {
                                $("#codice_fiscale").parents(".md-input").addClass("error-stepper");
                            } else {
                                $("#codice_fiscale").parents(".md-input").removeClass("error-stepper");

                            }
                        }

                        if ($(this).attr("name") == "email" || $(this).attr("name") == "pec") {
                            if (!isValidEmailAddress($(this).val())) {
                                $(this).parents(".md-input").addClass("error-stepper");
                            } else {
                                $(this).parents(".md-input").removeClass("error-stepper");
                            }
                        }


                    }
                });

                var errors = $(".fatture .error-container:visible")

                if (errors.length == 0) {
                    if (document.getElementById("upload_fatture").files.length == 0) {
                        Trenord.popUpMessage.open('error', 'Oops!', "Biglietto o scontrino di ricarica obbligatori");
                    } else {
                        var dateSplit = $("#data_fattura").val().split("Alle");
                        var dateSplitted = dateSplit[0].split("/");
                        var tempDate = "" + dateSplitted[1] + "/" + dateSplitted[0] + "/" + dateSplitted[2] + " " + dateSplit[1] + "";
                        var dateSelected = new Date(tempDate);
                        var dateOne = dateSelected;
                        var dateTwo = new Date();

                        var milliseconds = Math.abs(dateOne - dateTwo);
                        var hours = milliseconds / 36e5;

                        if (hours >= 24) {
                            Trenord.popUpMessage.open("error", "Errore!", "E' possibile selezionare una data massimo 24 ore dall'acquisto");
                        } else {
                            var formData = $("#form-fatture").serializeArray();
                            Trenord.popUpMessage.waitResponse();
                            $.post('/rest/cta/invoices?command=add', formData, function (result) {

                                if (result.response.info.http_code == 200) {
                                    $("#form-fatture")[0].reset();
                                    Trenord.popUpMessage.open('success', 'Ok!', "I dati sono stati caricati con successo", function () {
                                        // window.location.reload();
                                        window.location.href = '/store/#/it/reserved-area'
                                    });
                                } else {
                                    Trenord.popUpMessage.open('error', 'Oops!', "Qualcosa è andato storto!<br>Controlla i dati e riprova.");
                                }

                                if (result.newFolderId)
                                    $("#folderId").val(result.newFolderId);
                            });
                        }

                    }
                } else {
                    $('.container-error-contatti').show();
                    /// Scroll to first error
                    $('html, body').animate({
                        scrollTop: errors.offset().top - 100
                    }, 500);
                }
            });


            $("#upload_fatture").change(function (e) {

                Trenord.popUpMessage.waitResponse();

                var fdata = new FormData();
                var files = e.target.files;
                var checkFiles = [];

                if (files.length > 0) {

                    fdata.append("command", 'upload');
                    fdata.append("folderId", $("#folderId").val());

                    $.each(files, function (i, file) {

                        var checkFile = {
                            file: file,
                            error: "",
                        };

                        var splittedName = file.name.split(".");
                        var extension = splittedName[splittedName.length - 1].toLowerCase();

                        if (extension != "png" && extension != "pdf" && extension !== "jpeg" && extension !== "jpg") {
                            checkFile.error = "ext";
                        } else if (file.size > 1572864) {
                            checkFile.error = "size";
                        } else {
                            fdata.append(file.name, file);
                        }

                        checkFiles.push(checkFile);
                    });

                    $.ajax({
                        url: "/rest/cta/invoices?command=upload",
                        type: "post",
                        data: fdata, //add the FormData object to the data parameter
                        processData: false, //tell jquery not to process data
                        contentType: false, //tell jquery not to set content-type
                        success: function (response, status, jqxhr) {

                            var errors = "";
                            $.each(checkFiles, function (i, data) {

                                if (data.error == "") {
                                    $("<li class='not-style'><p>" + data.file.name + "<img data-file='" + data.file.name + "' class='icon-28 inline-icon removeUpload lozad' src='/fileadmin/templates/img/icons/Close.svg'></p></li>").insertAfter("#trigger_upload_fatture");
                                } else {

                                    errors += data.file.name;

                                    switch (data.error) {
                                        case "ext":

                                            errors += " - estensione non valida</br>";

                                            break;
                                        case "size":

                                            errors += " - file troppo grande</br>";
                                            break;
                                    }

                                    //reset input
                                    document.getElementById("upload_fatture").value = "";

                                }
                            });

                            if (errors != "") {
                                Trenord.popUpMessage.open("error", "Oops!", "Alcuni file non sono stati caricati</br></br>" + errors);
                            } else {
                                Trenord.popUpMessage.open("success", "Ok", "Caricamento dei files avvenuto con successo.");
                            }

                            //eliminazione allegato aggiungendo classe hidden
                            $(".removeUpload").unbind();
                            $(".removeUpload").on("click", function (event) {

                                var obj = this;

                                Trenord.popUpMessage.waitResponse();
                                $.post('/rest/cta/invoices?command=delete', {
                                    "fileName": $(this).data('file'),
                                    "folderId": $("#folderId").val()
                                }, function (result) {

                                    if (result.response.info.http_code == 200) {
                                        Trenord.popUpMessage.open('success', 'Ok!', "allegato rimosso con successo.");
                                        document.getElementById("upload_fatture").value = "";
                                        $(obj).parent().parent().addClass("hidden");

                                    } else {
                                        Trenord.popUpMessage.open('error', 'Oops', "qualcosa è andato storto.");
                                    }
                                })

                            });

                        },
                        error: function (jqxhr, status, errorMessage) {
                            Trenord.popUpMessage.open("error", "Oops!", "Qualcosa è andato storto.");
                        }
                    });
                }
            });


            $("#trigger_upload_fatture").click(function () {

                $("#upload_fatture").trigger("click");
            });

            if ($('#data_fattura').length) {
                $('#data_fattura').datepicker({
                    language: 'IT',
                    setDate: new Date(),
                    weekStart: 1,
                    startDate: '-1d', format: 'dd/mm/yyyy',
                    orientation: 'auto bottom',
                }).on('changeDate', function (ev) {
                    $("#label-date-andata").addClass("active");


                    if ($("#data_fattura").val() !== "") {
                        var dateInput = $("#data_fattura").val().split("Alle");
                        $("#data_fattura").val("" + dateInput[0].replace(/\s/g, "") + " Alle " + $(".slider-time").text() + "");
                    } else {
                        $("#data_fattura").val(" ");
                        $("#data_fattura").val(" Alle " + $("#orario1").val() + "");

                    }


                }).on("show", function (e) {
                    if (Trenord.utility.isMobile()) {
                        $(" .datepicker").addClass("mobile-date-viaggio");
                    } else {
                        $(" .datepicker").removeClass("mobile-date-viaggio");
                    }

                    var timeRange = $("#time-range");
                    timeRange.show();
                    $(" .datepicker .prev, .datepicker .next").empty();

                    if (!$(".datepicker-dropdown h4").length) {

                        $(".datepicker-dropdown").prepend("<h4>Data</h4>");
                        $(".datepicker-dropdown").prepend("<img alt='icona_chiudi_calendario'  class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");
                        $(".datepicker-dropdown").append(timeRange);
                        if ($(".fatture").length > 0) {
                            $(".slider-range").slider("destroy");

                            $(".slider-range").slider({
                                range: false,
                                min: 0,
                                max: 1440,
                                step: 30,
                                values: [Trenord.ui.malpensaVoli.currentHours],
                                slide: Trenord.ui.malpensaVoli.sliderFunction
                            });
                        }
                    } else {
                        var timeRange = $("#time-range");
                        timeRange.show();
                        $(".datepicker-dropdown").append(timeRange);
                    }

                    $(".copy-time").val($(".slider-time").text());

                    $(".datepicker-dropdown .close-datepicker").click(function () {
                        $('.datepicker').hide();
                    });


                }).on('hide', function (date) {


                    if ($("#data_fattura").val() !== "") {
                        var dateInput = $("#data_fattura").val().split("Alle");
                        $("#data_fattura").val("" + dateInput[0].replace(/\s/g, "") + " Alle " + $(".copy-time").val() + "");
                    } else {

                        $("#data_fattura").val(" ");
                        $("#data_fattura").val(" Alle " + $("#orario1").val() + "");

                    }

                }).attr('readonly', 'readonly');
            }


            $('input[type=radio][name=tipologia_richiesta_fattura]').change(function () {


                if (this.value == 'privato') {
                    $("#professionista").addClass("hidden");
                    $("#privato").removeClass("hidden");

                } else {
                    $("#privato").addClass("hidden");
                    $("#professionista").removeClass("hidden");
                }
            });

            $('input[type=radio][name=fatturazione_elettronica]').change(function () {


                if (this.value == 'pec') {

                    $(".cod_destinatario_container").addClass("hidden");
                    $(".pec_container").removeClass("hidden");


                } else {

                    if (this.value == 'no_cod') {
                        $(".pec_container").addClass("hidden");
                        $(".cod_destinatario_container").removeClass("hidden");
                        $("input[name='sdiCode']").val("0000000");
                        $("input[name='sdiCode']").attr('readonly', true);
                        $("input[name='sdiCode']").parent().find("label").addClass("active");
                    } else {
                        $(".pec_container").addClass("hidden");
                        $(".cod_destinatario_container").removeClass("hidden");
                        $("input[name='sdiCode']").val("");
                        $("input[name='sdiCode']").attr('readonly', false);
                        $("input[name='sdiCode']").parent().find("label").removeClass("active");

                    }



                }
            });

            $('input[type=radio][name=titolo_viaggio]').change(function () {


                if (this.value == 'abbonamento') {

                    $(".biglietto_container").addClass("hidden");
                    $(".abbonamento_container").removeClass("hidden");

                } else {
                    $(".abbonamento_container").addClass("hidden");
                    $(".biglietto_container").removeClass("hidden");

                }
            });


        }


    },


    ivif: {

        data: {}
        ,

        mediaLoaded: 0,
        mediaToLoad:
            0,

        mirrorDate:

            function (date) {

                var split = date.split('-');
                var newDate = split.reverse().join('/');

                return newDate;
            }

        ,

        convertBeforeSend: function () {

            Trenord.ivif.mediaToLoad = 0;
            Trenord.ivif.mediaLoaded = 0;

            $(".dropzone").each(function (index, value) {

                var fieldName = $(value).attr('name');
                var fileData = value.files[0];

                if (fileData) {

                    Trenord.ivif.mediaToLoad++;

                    var reader = new FileReader();

                    reader.onloadend = function () {
                        Trenord.ivif.data[fieldName] = reader.result;
                        Trenord.ivif.mediaLoaded++;

                        if (Trenord.ivif.mediaLoaded == Trenord.ivif.mediaToLoad) {
                            Trenord.ivif.send();
                        }
                    }

                    reader.readAsDataURL(fileData);
                }

            });

        }
        ,

        send: function () {

            $.post('/rest/user/ivif', Trenord.ivif.data, function (result) {
                Trenord.popUpMessage.stopSpinner();
                Trenord.popUpMessage.hideModalBox();

                if (Trenord.utility.isMobile()) {
                    $("header-stepper").addClass("hidden");
                }
                $(".header-stepper .third").addClass("full");
                $(".header-stepper a").css("pointer-events", "none");

                $("#step4 #nome_richiedente_succ").html($("#nome_referente").val().toUpperCase().trim());
                $("#step4 #cognome_richiedente_succ").html($("#cognome_referente").val().toUpperCase().trim());
                $("#step4 #data_richiedente_succ").html(Trenord.ivif.mirrorDate($(" #step1 .data-nascita-riepilogo").val()));
                $("#step4 #comune_richiedente_succ").html($("#comune_di_nascita").val());
                $("#step4 #email_richiedente_succ").html($("#email_referente").val());
                $("#step4 #telefono_richiedente_succ").html($("#telefono_refente").val());
                $("#step4 #provincia_richiedente_succ").html(Trenord.ivif.data.Comune + " - " + Trenord.ivif.data.Provincia);
                $("#step4 #indirizzo_richiedente_succ").html(Trenord.ivif.data.Indirizzo + ", " + Trenord.ivif.data.numero_civico);
                $("#step4 #cap_richiedente_succ").html(Trenord.ivif.data.Cap);

                //figlio
                $("#figlio_1_succ .nome").html($("#nome_figlio1").val());
                $("#figlio_1_succ .cognome").html($("#cognome_figlio1").val());
                $("#figlio_1_succ .data").html(Trenord.ivif.mirrorDate($(".container-form.figlio_1 .data-nascita-riepilogo ").val()));
                $("#figlio_1_succ .luogo").html($("#luogo_figlio1").val());


                if ($("#nome_figlio2").val() !== "") {
                    $("#figlio_2_succ .nome").html($("#nome_figlio2").val());
                    $("#figlio_2_succ .cognome").html($("#cognome_figlio2").val());
                    $("#figlio_2_succ .data").html(Trenord.ivif.mirrorDate($(".container-form.figlio_2 .data-nascita-riepilogo ").val()));
                    $("#figlio_2_succ .luogo").html($("#luogo_figlio2").val());
                } else {
                    $("#figlio_2_succ").addClass("hidden");
                }


                if ($("#nome_figlio3").val() !== "") {
                    $("#figlio_3_succ .nome").html($("#nome_figlio3").val());
                    $("#figlio_3_succ .cognome").html($("#cognome_figlio3").val());
                    $("#figlio_3_succ .data").html(Trenord.ivif.mirrorDate($(".container-form.figlio_3 .data-nascita-riepilogo ").val()));
                    $("#figlio_3_succ .luogo").html($("#luogo_figlio3").val());
                } else {
                    $("#figlio_3_succ").addClass("hidden");
                }


                $("#accompagnatore_1_succ .nome").html($(".container-form.accompagnatore_1   #nome_accompagnatore1").val());
                $("#accompagnatore_1_succ .cognome").html($(".container-form.accompagnatore_1   #cognome_accompagnatore1").val());
                $("#accompagnatore_1_succ .parentela").html($(".container-form.accompagnatore_1 button").attr("title"));

                if ($(".container-form.accompagnatore_2   #nome_accompagnatore2").val() !== "") {
                    $("#accompagnatore_2_succ .nome").html($(".container-form.accompagnatore_2   #nome_accompagnatore2").val());
                    $("#accompagnatore_2_succ .cognome").html($(".container-form.accompagnatore_2   #cognome_accompagnatore2").val());
                    $("#accompagnatore_2_succ .parentela").html($(".container-form.accompagnatore_2 button").attr("title"));
                } else {
                    $("#accompagnatore_2_succ").addClass("hidden");
                }

                if ($(".container-form.accompagnatore_3   #nome_accompagnatore3").val() !== "") {
                    $("#accompagnatore_3_succ .nome").html($(".container-form.accompagnatore_3   #nome_accompagnatore3").val());
                    $("#accompagnatore_3_succ .cognome").html($(".container-form.accompagnatore_3   #cognome_accompagnatore3").val());
                    $("#accompagnatore_3_succ .parentela").html($(".container-form.accompagnatore_3 button").attr("title"));
                } else {
                    $("#accompagnatore_3_succ").addClass("hidden");
                }

                if ($(".container-form.accompagnatore_4   #nome_accompagnatore4").val() !== "") {
                    $("#accompagnatore_4_succ .nome").html($(".container-form.accompagnatore_4   #nome_accompagnatore4").val());
                    $("#accompagnatore_4_succ .cognome").html($(".container-form.accompagnatore_4  #cognome_accompagnatore4").val());
                    $("#accompagnatore_4_succ .parentela").html($(".container-form.accompagnatore_4 button").attr("title"));
                } else {
                    $("#accompagnatore_4_succ").addClass("hidden");
                }

                if ($(".container-form.accompagnatore_5   #nome_accompagnatore5").val() !== "") {
                    $("#accompagnatore_5_succ .nome").html($(".container-form.accompagnatore_5   #nome_accompagnatore5").val());
                    $("#accompagnatore_5_succ .cognome").html($(".container-form.accompagnatore_5   #cognome_accompagnatore5").val());
                    $("#accompagnatore_5_succ .parentela").html($(".container-form.accompagnatore_5 button").attr("title"));
                } else {
                    $("#accompagnatore_5_succ").addClass("hidden");
                }


                if ($(".container-form.accompagnatore_6   #nome_accompagnatore6").val() !== "") {
                    $("#accompagnatore_6_succ .nome").html($(".container-form.accompagnatore_6   #nome_accompagnatore6").val());
                    $("#accompagnatore_6_succ .cognome").html($(".container-form.accompagnatore_6   #cognome_accompagnatore6").val());
                    $("#accompagnatore_6_succ .parentela").html($(".container-form.accompagnatore_6 button").attr("title"));
                } else {
                    $("#accompagnatore_6_succ").addClass("hidden");
                }

            })

        }
        ,

        init: function () {
            if ($("#submit-indirizzo")[0]) {
                var head = document.head;
                var script = document.createElement('script');
                script.type = 'text/javascript';
                var key = window.location.href.indexOf('local.') > -1 ? "AIzaSyCYbn2vquvqhcU1YB3DO61KsyEjqv5WkUw" : "AIzaSyCfouM1AgNmV7khj3qT0458FkrEwb7b54s"
                script.src = "https://maps.googleapis.com/maps/api/js?key=" + key + "&libraries=places&callback=";
                // Fire the loading
                head.appendChild(script);
            }

            $(".stepper .back").click(function () {
                window.history.back();
            });


            window.addEventListener('resize', function () {

                if (!Trenord.utility.isMobile()) {
                    $(".header-stepper .first , .header-stepper .second , .header-stepper .third").removeClass("hidden");
                } else {
                    $(".header-stepper .first , .header-stepper .second , .header-stepper .third").addClass("hidden");
                    if ($(".stepper .tab-pane.active").attr("id") == "step1") {
                        $(".header-stepper .first").removeClass("hidden");
                    }
                    if ($(".stepper .tab-pane.active").attr("id") == "step2") {
                        $(".header-stepper .second").removeClass("hidden");
                    }
                    if ($(".stepper .tab-pane.active").attr("id") == "step3") {
                        $(".header-stepper .third").removeClass("hidden");
                    }
                }
            });
            //controllo mobile
            if (Trenord.utility.isMobile()) {
                $(".header-stepper .second, .header-stepper .third").addClass("hidden");
            }

            //da creare tessere form
            $("#submit-richiedente").click(function () {
                check_required_inputs(".richiedente");
                if (!$(".richiedente .md-input.error-stepper").length) {
                    $(".richiedente .content-acc").slideUp();
                    $(".richiedente").addClass("active-acc");
                    $(".indirizzo").removeClass("disable");
                }
            });

            var convertPlaceToFormUser = function (place) {
                let form = {
                    cap: '',
                    address: '',
                    address_n: '',
                    city: '',
                    province: '',
                    nation: "Italia",
                }

                for (const component of place.address_components) {
                    const componentType = component.types[0];

                    switch (componentType) {
                        case "street_number": {
                            form.address_n = `${component.long_name}`;
                            break;
                        }

                        case "route": {
                            form.address += component.short_name;
                            break;
                        }

                        case "postal_code": {
                            form.cap = `${component.long_name}${form.cap}`;
                            break;
                        }

                        case "postal_code_suffix": {
                            form.cap = `${form.cap}-${component.long_name}`;
                            break;
                        }

                        case "locality":
                            form.city = component.long_name;
                            break;

                        case "administrative_area_level_2": {
                            form.province = component.short_name;
                            break;
                        }
                        case "country": {
                            form.nation = component.long_name;
                            break;
                        }
                        default:
                            break;
                    }
                }
                return form
            }

            var formatUserAddress = function (formData) {
                return Trenord.ivif.data.Indirizzo + ", " + Trenord.ivif.data.numero_civico + ", " + Trenord.ivif.data.Cap + " " + Trenord.ivif.data.Comune + " " + Trenord.ivif.data.Provincia + ", " + Trenord.ivif.data.Paese;
            }

            $("#submit-indirizzo").click(function () {
                check_required_inputs(".indirizzo");

                if (!$(".indirizzo .md-input.error-stepper").length) {

                    let element = document.createElement('div');
                    const service = new google.maps.places.PlacesService(element);
                    const autocompleteService = new google.maps.places.AutocompleteService();

                    var address = formatUserAddress()

                    const request = {
                        input: address,
                        fields: ["name", "place_id"],
                    };

                    autocompleteService.getPlacePredictions(request, (results, status) => {
                        if (results && results.length > 0) {
                            /// Get the details of the place
                            const req = {
                                placeId: results[0].place_id,
                                fields: ['formatted_address', 'address_components']
                            }
                            service.getDetails(req, (place, status) => {
                                if (place.formatted_address.toLowerCase() !== formatUserAddress().toLowerCase()) {
                                    // Set place to show confirm from
                                    $('#address-confirm-container').removeClass('hidden');
                                    $('#address-form-container').addClass('hidden');

                                    $("#address-confirm-choises").html(
                                        '<div><div class="radio radio-success"><input id="placeRadio" checked type="radio" name="addressChoise" value="place"/><label for="placeRadio"><b>' + place.formatted_address + '</b></label></div></div>' +
                                        '</div><div class="radio radio-success"><input id="userRadio" type="radio" name="addressChoise" value="user"/><label for="userRadio">' + formatUserAddress() + '</label></div></div>'
                                    )
                                    $('#submit-address-confirm').click(function () {

                                        var choise = $('input[name=addressChoise]:checked', '#address-confirm-container').val();
                                        if (choise === "place") {
                                            var addr = convertPlaceToFormUser(place)
                                            Trenord.ivif.data.Provincia = addr.province;
                                            $("#provincia").val(addr.province);

                                            Trenord.ivif.data.Comune = addr.city;
                                            $("#Comune").val(addr.city);

                                            Trenord.ivif.data.Cap = addr.cap;
                                            $("#cap").val(addr.cap);

                                            Trenord.ivif.data.numero_civico = addr.address_n;
                                            $("#numero_civico").val(addr.address_n);

                                            Trenord.ivif.data.Indirizzo = addr.address;
                                            $("#indirizzo_referente").val(addr.address);

                                            Trenord.ivif.data.Paese = addr.nation;
                                            $("#paese").val(addr.nation);
                                        }

                                        $('#address-form-container').removeClass('hidden');
                                        $('#address-confirm-container').addClass('hidden');

                                        $(".indirizzo .content-acc").slideUp();
                                        $(".indirizzo").addClass("active-acc");
                                        $(".stazione").removeClass("disable");
                                        Trenord.popUpMessage.stopSpinner();
                                        Trenord.popUpMessage.hideModalBox();
                                    })

                                } else {
                                    $(".indirizzo .content-acc").slideUp();
                                    $(".indirizzo").addClass("active-acc");
                                    $(".stazione").removeClass("disable");
                                    Trenord.popUpMessage.stopSpinner();
                                    Trenord.popUpMessage.hideModalBox();
                                }
                            });
                        } else {
                            Trenord.popUpMessage.open('error', "Attenzione", "Indirizzo non riconosciuto correttamente, ricontrollare i dati inseriti e riprovare");
                        }
                    });

                }
            });

            $("#submit-stazione").click(function () {
                check_required_inputs(".stazione");
                if (!$(".stazione .md-input.error-stepper").length) {
                    $(".stazione .content-acc").slideUp();
                    $(".stazione").addClass("active-acc");
                    $(".button-step1").removeClass("disable");
                    $(".figlio_1 .label-date-andata").removeClass("active");
                }
            });

            $("#submit-figlio-1").click(function () {
                check_required_inputs(".figlio_1");
                if (!$(".figlio_1 .md-input.error-stepper").length) {
                    $(".figlio_1 .content-acc").slideUp();
                    $(".figlio_1").addClass("active-acc");
                    $(".foto_figlio_1").removeClass("disable");


                }
            });

            $("#submit-figlio-2").click(function () {
                check_required_inputs(".figlio_2");
                if (!$(".figlio_2 .md-input.error-stepper").length) {
                    $(".figlio_2 .content-acc").slideUp();
                    $(".figlio_2").addClass("active-acc");
                    $(".foto_figlio_2").removeClass("disable");
                }
            });

            $("#submit-figlio-3").click(function () {
                check_required_inputs(".figlio_3");
                if (!$(".figlio_3 .md-input.error-stepper").length) {
                    $(".figlio_3 .content-acc").slideUp();
                    $(".figlio_3").addClass("active-acc");
                    $(".foto_figlio_3").removeClass("disable");


                }
            });

            $(".button-upload-close1").click(function () {
                $(".foto_figlio_1").addClass("active-acc");
                $(".foto_figlio_1 .content-acc").slideUp();
                $(".button-step2").removeClass("disable");
                $("#submit-foto-figlio-1").text("CAMBIA FOTO");
                $(".add-child-container").removeClass("hidden");
                $(".container-primo-figlio.form-childs .label-figlio").html("Primo figlio: " + $("#nome_figlio1").val() + " " + $("#cognome_figlio1").val() + "");
            });

            $(".button-upload-close2").click(function () {
                $(".foto_figlio_2").addClass("active-acc");
                $(".foto_figlio_2 .content-acc").slideUp();
                $("#submit-foto-figlio-2").text("CAMBIA FOTO");
                $(".button-step2").removeClass("disable");
                $(".container-secondo-figlio.form-childs  .label-figlio").html("Secondo figlio: " + $("#nome_figlio2").val() + " " + $("#cognome_figlio2").val() + "");
            });

            $(".button-upload-close3").click(function () {
                $(".foto_figlio_3 .content-acc").slideUp();
                $(".foto_figlio_3").addClass("active-acc");
                $(".button-step2").removeClass("disable");
                $("#submit-foto-figlio-3").text("CAMBIA FOTO");
                $(".container-terzo-figlio.form-childs  .label-figlio").html("Terzo figlio: " + $("#nome_figlio3").val() + " " + $("#cognome_figlio3").val() + "");
            });

            $("#submit-accompagnatore-1").click(function () {
                check_required_inputs(".accompagnatore_1");
                if (!$(".accompagnatore_1 .md-input.error-stepper").length) {
                    $(".accompagnatore_1 .content-acc").slideUp();
                    $(".accompagnatore_1").addClass("active-acc");
                    $(".add-child-container-accompagnatore").removeClass("hidden");
                    $(".button-step3").removeClass("disable");
                    $(".container-primo-figlio.childs-accompagnatori .label-figlio").html("Primo accompagnatore: " + $("#nome_accompagnatore1").val() + " " + $("#cognome_accompagnatore1").val() + "");
                }
            });

            $("#submit-accompagnatore-2").click(function () {
                check_required_inputs(".accompagnatore_2");
                if (!$(".accompagnatore_2 .md-input.error-stepper").length) {
                    $(".accompagnatore_2 .content-acc").slideUp();
                    $(".accompagnatore_2").addClass("active-acc");
                    $(".add-child-container").removeClass("hidden");

                    $(".container-secondo-figlio.childs-accompagnatori .label-figlio").html("Secondo accompagnatore: " + $("#nome_accompagnatore2").val() + " " + $("#cognome_accompagnatore2").val() + "");
                    $(".button-step3").removeClass("disable");
                }
            });

            $("#submit-accompagnatore-3").click(function () {
                check_required_inputs(".accompagnatore_3");
                if (!$(".accompagnatore_3 .md-input.error-stepper").length) {
                    $(".accompagnatore_3 .content-acc").slideUp();
                    $(".accompagnatore_3").addClass("active-acc");

                    $(".container-terzo-figlio.childs-accompagnatori .label-figlio").html("Terzo accompagnatore: " + $("#nome_accompagnatore3").val() + " " + $("#cognome_accompagnatore3").val() + "");
                    $(".button-step3").removeClass("disable");
                }
            });


            $("#submit-accompagnatore-4").click(function () {
                check_required_inputs(".accompagnatore_4");
                if (!$(".accompagnatore_4 .md-input.error-stepper").length) {
                    $(".accompagnatore_4 .content-acc").slideUp();
                    $(".accompagnatore_4").addClass("active-acc");
                    $(".container-quarto-figlio.childs-accompagnatori .label-figlio").html("Quarto accompagnatore: " + $("#nome_accompagnatore4").val() + " " + $("#cognome_accompagnatore4").val() + "");
                    $(".button-step3").removeClass("disable");
                }
            });


            $("#submit-accompagnatore-5").click(function () {
                check_required_inputs(".accompagnatore_3");
                if (!$(".accompagnatore_5 .md-input.error-stepper").length) {
                    $(".accompagnatore_5 .content-acc").slideUp();
                    $(".accompagnatore_5").addClass("active-acc");

                    $(".container-quinto-figlio.childs-accompagnatori .label-figlio").html("Quinto accompagnatore: " + $("#nome_accompagnatore5").val() + " " + $("#cognome_accompagnatore5").val() + "");
                    $(".button-step3").removeClass("disable");
                }
            });


            $("#submit-accompagnatore-6").click(function () {
                check_required_inputs(".accompagnatore_6");
                if (!$(".accompagnatore_6 .md-input.error-stepper").length) {
                    $(".accompagnatore_6 .content-acc").slideUp();
                    $(".accompagnatore_6").addClass("active-acc");


                    $(".container-sesto-figlio.childs-accompagnatori .label-figlio").html("Sesto accompagnatore: " + $("#nome_accompagnatore6").val() + " " + $("#cognome_accompagnatore6").val() + "");
                    $(".button-step3").removeClass("disable");
                }
            });


            $(".button-step1").click(function () {
                if (Trenord.utility.isMobile()) {
                    $(".header-stepper .first").addClass("hidden");
                    $(".header-stepper .second").removeClass("hidden");
                }
                $(".header-stepper .first").addClass("active");
                $(".header-stepper .second").addClass("active");

                $(".dynamic-referenceName").html($("#nome_referente").val().toUpperCase().trim() + " " + $("#cognome_referente").val().toUpperCase().trim());
            });

            $(".button-step2").click(function () {

                if (Trenord.utility.isMobile()) {
                    $(".header-stepper .second").addClass("hidden");
                    $(".header-stepper .third").removeClass("hidden");
                }
                $(".header-stepper .third").addClass("active");
                $(".header-stepper .second").addClass("double");
            });


            $(".button-step3").click(function (event) {


                if (!$('.custom-checkbox label input:checked').length > 0) {
                    $(".custom-checkbox label").css("color", "red");
                    event.stopPropagation();
                }

                Trenord.popUpMessage.waitResponse();

                Trenord.ivif.convertBeforeSend();


            });


            $(".custom-checkbox label input").change(function () {
                if (this.checked) {
                    $(".custom-checkbox label input").prop('checked', false);
                    $(this).prop('checked', true);
                    $(".custom-checkbox label").css("color", "#4a4a4a");
                }
            });


            $(".back-step1").click(function () {

                if (Trenord.utility.isMobile()) {
                    $(".header-stepper .first").removeClass("hidden");
                    $(".header-stepper .second").addClass("hidden");
                }
                $(".header-stepper .second").removeClass("active");
                $(".header-stepper .first").removeClass("active");
            });

            $(".back-step2").click(function () {
                if (Trenord.utility.isMobile()) {
                    $(".header-stepper .second").removeClass("hidden");
                    $(".header-stepper .third").addClass("hidden");
                }
                $(".header-stepper .third").removeClass("active");
                $(".header-stepper .second").removeClass("double");

            });


            $(" .form-childs .remove").click(function () {
                $(".button-step2").removeClass("disable");
                $(".add-child-container").removeClass("hidden");
                if ($(this).hasClass("2")) {

                    if ($(".container-terzo-figlio.form-childs").is(":visible")) {
                        if ($("#nome_figlio3").val() !== "") {
                            $(".container-secondo-figlio.form-childs  .label-figlio").html("Secondo figlio: " + $("#nome_figlio3").val() + " " + $("#cognome_figlio3").val() + "");
                        } else {
                            $(".container-secondo-figlio.form-childs  .label-figlio").html("Secondo figlio");
                        }


                        $(".container-terzo-figlio.form-childs input").each(function (index, item) {

                            $(".container-secondo-figlio.form-childs input").get(index).value = index == 4 ? "" : $(this).val();

                        });

                        $("#step2 .form-childs:visible:last input").val("");
                        $("#step2 .form-childs:visible:last").addClass("hidden");
                        $(".container-terzo-figlio.form-childs  .label-figlio").html("Terzo figlio");


                        $("#submit-foto-figlio-3").text("SCEGLI FOTO");
                        $(".foto_figlio_3 .preview-zone").remove();

                    } else {
                        $(".container-secondo-figlio.form-childs input").val("");
                        $(".container-secondo-figlio.form-childs").addClass("hidden");
                        $(".container-secondo-figlio.form-childs  .label-figlio").html("Secondo figlio");
                        $("#submit-foto-figlio-2").text("SCEGLI FOTO");
                        $(".foto_figlio_2 .preview-zone").remove();
                    }


                } else {


                    $("#step2 .form-childs:visible:last input").val("");
                    $("#step2 .form-childs:visible:last").addClass("hidden");
                    $(".container-terzo-figlio.form-childs  .label-figlio").html("Terzo figlio");
                    $("#submit-foto-figlio-3").text("SCEGLI FOTO");
                    $(".foto_figlio_3 .preview-zone").remove();
                }

            });


            $(".remove-accompagnatore").click(function () {
                $(".button-step3").removeClass("disable");
                $(".add-child-container-accompagnatore").removeClass("hidden");

                var elem = $(this);


                if (elem.hasClass("" + $(".childs-accompagnatori:visible").length + "")) {
                    var label = $(".childs-accompagnatori." + $(".childs-accompagnatori:visible").length + " .label-figlio").text().split(":");
                    $(".childs-accompagnatori." + $(".childs-accompagnatori:visible").length + " input").val("");
                    $(".childs-accompagnatori." + $(".childs-accompagnatori:visible").length + "").find("parentela").removeAttr('selected').selectpicker("refresh");
                    $(".childs-accompagnatori." + $(".childs-accompagnatori:visible").length + " .label-figlio").text(label[0]);
                    $(".childs-accompagnatori." + $(".childs-accompagnatori:visible").length + "").addClass("hidden");
                } else {

                    $(".childs-accompagnatori:visible").each(function (index, item) {
                        index++;
                        if (elem.hasClass("" + index + "")) {
                            var labelDaCopiare = $(this).next().find(".label-figlio").text().split(":");


                            var etichetta = $(this).find(".label-figlio").text().split(":");

                            if (labelDaCopiare[1]) {
                                $(this).find(".label-figlio").text("" + etichetta[0] + ":" + labelDaCopiare[1] + "");
                            } else {
                                $(this).find(".label-figlio").text("" + etichetta[0] + "");
                            }

                            $(this).next().find(".label-figlio").text("" + labelDaCopiare[0] + "");
                            var nextIndex = index + 1;
                            var rightIndex = index;
                            $(".childs-accompagnatori." + nextIndex + " input").each(function (index, item) {

                                $(".childs-accompagnatori." + rightIndex + " input").get(index).value = $(this).val();

                            });
                            $(this).next().find("input").val("");
                            $(this).next().addClass("hidden");
                        }
                        ;
                    });

                }


            });


            $(".add-child").click(function () {
                $(".button-step2").addClass("disable");

                $("#step2 .form-childs:visible:last").next().removeClass("hidden");
                if ($("#step2 .form-childs:visible").length == 3) {
                    $(".add-child-container").addClass("hidden");
                }

            });

            $(".add-child-accompagnatore").click(function () {
                $(".button-step3").addClass("disable");
                $("#step3 .form-childs-accompagnatore:visible:last").next().removeClass("hidden");
                if ($("#step3 .form-childs-accompagnatore:visible").length == 6) {
                    $(".add-child-container-accompagnatore").addClass("hidden");
                }
            });


            $("#step2 .back").click(function () {
                $("#step2 .required").val('');
                $(" #step2 .container-form:visible ").removeClass("active-acc");
                $("#step2 .container-form-contatti").not(':first').addClass("disable");
                $("#step2 .form-childs").not(':first').addClass("hidden");
                $("#step2 .figlio_1 .content-acc").show();
                $(".button-step2").addClass("disable");
            });
            $("#step3 .back").click(function () {
                $("#step3 .required").val('');
                $(" #step3 .container-form:visible ").removeClass("active-acc");
                $("#step3 .container-form-contatti").not(':first').addClass("disable");
                $("#step3 .form-childs-accompagnatore").not(':first').addClass("hidden");
                $("#step3 .accompagnatore_1 .content-acc").show();
                $(".parentela").selectpicker('refresh');
                $(".button-step3").addClass("disable");
            });


            $(".arrow-acc").click(function () {
                $(this).parent().find(".content-acc").slideToggle();
            });


            $('.required').on('change', function () {
                if ($(this).val() == "") {


                } else {
                    $(this).parent().removeClass("error-stepper");
                }
            });


            $('#parentela1').on('change', function (e) {
                $('.label-parentela1').addClass("active");
            });

            $('#parentela2').on('change', function (e) {
                $('.label-parentela2').addClass("active");
            });

            $('#parentela3').on('change', function (e) {
                $('.label-parentela3').addClass("active");
            });
            $('#parentela4').on('change', function (e) {
                $('.label-parentela4').addClass("active");
            });
            $('#parentela5').on('change', function (e) {
                $('.label-parentela5').addClass("active");
            });
            $('#parentela6').on('change', function (e) {
                $('.label-parentela6').addClass("active");
            });

            //check form generica
            function check_required_inputs(parent) {

                function calculateAge(birthMonth, birthDay, birthYear) {
                    var currentDate = new Date();
                    var currentYear = currentDate.getFullYear();
                    var currentMonth = currentDate.getMonth();
                    var currentDay = currentDate.getDate();
                    var calculatedAge = currentYear - birthYear;

                    if (currentMonth < birthMonth - 1) {
                        calculatedAge--;
                    }
                    if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
                        calculatedAge--;
                    }
                    return calculatedAge;
                }

                $(parent).find(".required:not(div)").each(function () {

                    var fieldVal = $(this).val()
                    var fieldName = $(this).attr('name');

                    //costruisce dinamicamente il form all'interno dell'oggetto
                    if (fieldVal) {
                        eval("Trenord.ivif.data." + fieldName + " = '" + fieldVal.toString().replace(/'/g, "\\'") + "';");
                    }

                    if ($(this).val() == "" || $(this).val() === null) {
                        $(this).parents(".md-input").addClass("error-stepper");

                    } else {
                        if ($(this).attr("name") == "Email") {


                            if (!isValidEmailAddress($(this).val())) {
                                $(this).parents(".md-input").addClass("error-stepper");
                            } else {
                                $(this).parents(".md-input").removeClass("error-stepper");
                            }
                        }
                        if ($(this).attr("name") == "Cap") {

                            if (($(this).val().length < 4)) {
                                $(this).parents(".md-input").addClass("error-stepper");
                            } else {
                                $(this).parents(".md-input").removeClass("error-stepper");
                            }
                        }

                        if ($(this).attr("name") == "DataNascitaGenitore") {

                            var dateSelected = $(this).val().split("-");

                            var age = calculateAge(dateSelected[1], dateSelected[2], dateSelected[0]);
                            if (age < 18) {
                                Trenord.popUpMessage.open('error', "Data di nascita errata", "Il richiedente della tessera Io Viaggio in Famiglia deve avere un età maggiore o uguale a 18 anni");
                                $(this).val(" ");
                                $(this).parents(".md-input").addClass("error-stepper");
                            }

                        }

                        if ($(this).attr("name").includes("data_nascita_figlio")) {

                            var dateSelected = $(this).val().split("-");

                            var age = calculateAge(dateSelected[1], dateSelected[2], dateSelected[0]);
                            if (age < 4) {
                                Trenord.popUpMessage.open('error', "Data di nascita errata", "I minori di 4 anni come da Condizioni di Trasporto possono viaggiare gratuitamente senza alcun titolo di viaggio");

                                $(this).val(" ");
                                $(this).parents(".md-input").addClass("error-stepper");
                            }
                            if (age >= 14) {
                                Trenord.popUpMessage.open('error', "Data di nascita errata", "La richiesta di una tessera Io Viaggio in Famiglia può essere effettuata per ragazzi fino a 14 anni di età.");
                                $(this).val(" ");
                                $(this).parents(".md-input").addClass("error-stepper");

                            }

                        }


                    }
                });


                return true;
            }


            function isValidEmailAddress(emailAddress) {
                var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
                return pattern.test(emailAddress);
            };

            function readFile(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
                    var valueName = input.files[0].name.split(".");


                    if (input.files[0].size < 1572864) {
                        //Initiate the JavaScript Image object.

                        reader.onload = function (e) {

                            var image = new Image();


                            image.src = e.target.result;
                            image.onload = function () {
                                var height = this.height;
                                var width = this.width;
                                if (height >= 280 && width >= 250) {


                                    var htmlPreview =
                                        '<img alt="preview-image" width="200" src="' + e.target.result + '" />' +
                                        '<p>' + input.files[0].name + '</p>';

                                    var wrapperZone = $(input).parent();
                                    var previewZone = $(input).parent().parent().find('.preview-zone');
                                    var boxZone = $(input).parent().parent().find('.preview-zone').find('.box').find('.box-body');

                                    wrapperZone.removeClass('dragover');
                                    previewZone.removeClass('hidden');
                                    boxZone.empty();
                                    boxZone.append(htmlPreview);
                                    $(".btn-up:visible").removeClass("disable");




                                } else {
                                    Trenord.popUpMessage.open("error", "File Errato", "La risoluzione minima è di 250x280");
                                }
                            }
                        };


                        reader.readAsDataURL(input.files[0]);
                    } else {
                        Trenord.popUpMessage.open("error", "File Errato", "La dimensione massima è di 1,5mb");
                    }

                }

            }

            function reset(e) {
                e.wrap('<form>').closest('form').get(0).reset();
                e.unwrap();
            }

            $(".dropzone").change(function () {
                readFile(this);
            });

            $('.dropzone-wrapper').on('dragover', function (e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).addClass('dragover');
            });

            $('.dropzone-wrapper').on('dragleave', function (e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('dragover');
            });

            $('.remove-preview').on('click', function () {
                var boxZone = $(this).parents('.preview-zone').find('.box-body');
                var previewZone = $(this).parents('.preview-zone');
                var dropzone = $(this).parents('.form-group').find('.dropzone');
                boxZone.empty();
                previewZone.addClass('hidden');
                reset(dropzone);
            });

            if ($('.data-nascita').length) {


                $('.data-nascita').datepicker({
                    language: 'IT',
                    format: 'dd/mm/yyyy',
                    orientation: 'auto bottom',
                    startView: 2,
                    maxViewMode: "years",
                }).on('changeDate', function (ev) {
                    $('.datepicker').hide();
                    $(".label-date-andata:visible").addClass("active");

                }).on("show", function (e) {


                    if (Trenord.utility.isMobile()) {
                        $(" .datepicker").addClass("mobile-date-viaggio");
                    } else {
                        $(" .datepicker").removeClass("mobile-date-viaggio");
                    }
                    $(" .datepicker").addClass("dx-viaggio");
                    $(" .datepicker .prev, .datepicker .next").empty();


                    $(".datepicker-dropdown h4").remove("");
                    $(".datepicker-dropdown").prepend("<h4>Data</h4>");
                    $(".datepicker-dropdown").prepend("<img alt='icona_chiudi_calendario'  class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");


                    $(".datepicker-dropdown .close-datepicker").click(function () {
                        $('.datepicker').hide();
                    });


                }).on('hide', function (date) {


                });


                $(".container-form.richiedente .data-nascita").datepicker("destroy");
                $('.container-form.richiedente .data-nascita').datepicker({
                    language: 'IT',
                    format: 'dd/mm/yyyy',
                    orientation: 'auto bottom',
                    startView: 2,
                    maxViewMode: "years",
                    endDate: '-18y',
                });


                $(".container-form.figlio_1 .data-nascita").datepicker("destroy");
                $('.container-form.figlio_1 .data-nascita').datepicker({
                    language: 'IT',
                    format: 'dd/mm/yyyy',
                    orientation: 'auto bottom',
                    startView: 2,
                    maxViewMode: "years",
                    endDate: '-0y',
                }).on('changeDate', function (ev) {

                    dateSelected = $(".container-form.figlio_1 .data-nascita").val().split("/");
                    var age = calculateAge(dateSelected[1], dateSelected[0], dateSelected[2]);
                    if (age <= 4) {
                        alert("I minori di 4 anni come da Condizioni di Trasporto possono viaggiare gratuitamente senza alcun titolo di viaggio")
                        $(".container-form.figlio_1 .data-nascita").data('datepicker').setDate(null);
                    }


                });


                $(".container-form.figlio_2 .data-nascita").datepicker("destroy");
                $('.container-form.figlio_2 .data-nascita').datepicker({
                    language: 'IT',
                    format: 'dd/mm/yyyy',
                    orientation: 'auto bottom',
                    startView: 2,
                    maxViewMode: "years",
                    endDate: '-0y',
                }).on('changeDate', function (ev) {

                    dateSelected = $(".container-form.figlio_2 .data-nascita").val().split("/");
                    var age = calculateAge(dateSelected[1], dateSelected[0], dateSelected[2]);
                    if (age <= 4) {
                        alert("I minori di 4 anni come da Condizioni di Trasporto possono viaggiare gratuitamente senza alcun titolo di viaggio")
                        $(".container-form.figlio_2 .data-nascita").data('datepicker').setDate(null);
                    }


                });


                $(".container-form.figlio_3 .data-nascita").datepicker("destroy");
                $('.container-form.figlio_3 .data-nascita').datepicker({
                    language: 'IT',
                    format: 'dd/mm/yyyy',
                    orientation: 'auto bottom',
                    startView: 2,
                    maxViewMode: "years",
                    endDate: '-0y',
                }).on('changeDate', function (ev) {

                    dateSelected = $(".container-form.figlio_3 .data-nascita").val().split("/");
                    var age = calculateAge(dateSelected[1], dateSelected[0], dateSelected[2]);
                    if (age <= 4) {
                        alert("I minori di 4 anni come da Condizioni di Trasporto possono viaggiare gratuitamente senza alcun titolo di viaggio")
                        $(".container-form.figlio_3 .data-nascita").data('datepicker').setDate(null);
                    }


                });


            }

            //fine tessere

        }
    }
    ,

    ui: {

        elementsVisibilityFromUserAgent: function () {
            /* implementata in menu.js */
            Trenord.console.log("elementsVisibilityFromUserAgent {}");
        }
        ,

        menu: function () {
            /* implementata in menu.js */
            Trenord.console.log("menu {}");
        }
        ,

        sliderHome: function () {
            /* implementata in sliderHome.js */
            Trenord.console.log("slider {}");
        }
        ,

        sideNav: function () {
            /* implementata in sideNav.js */
            Trenord.console.log("sideNav {}");
        }
        ,

        searchNav: {

            initEvents: function () {
                /* implementata in searchNav.js */
                Trenord.console.log("initEvents {}");
            }
            ,

            suggest: function () {

                Trenord.console.log("suggest {}");

            }
        }
        ,

        inEvidenza: function () {
            /* implementata in searchNav.js */
            Trenord.console.log("inEvidenza {}");
        }
        ,
        carosuelInEvidenza: function () {
            /* implementata in carosuelInEvidenza.js */
            Trenord.console.log("carosuelInEvidenza {}");
        }
        ,
        ideeDiViaggio: {
            init: function () {
                /* implementata in ideeDiViaggio.js */
                Trenord.console.log("idee viaggio init {}");
            }
            ,

            nextPage: function () {
                /* implementata in ideeDiViaggio.js */
                Trenord.console.log("ideeViaggio nextPage{}");

            }
        }
        ,
        carouselNews: function () {
            /* implementata in carouselNews.js */
            Trenord.console.log("carouselNews {}");
        }
        ,
        formGruppi: function () {
            //implementata in carouselNews.js
            Trenord.console.log("formGruppi {}");
        }
        ,


        tabFooterTop: function () {
            /* implementata in tabFooterTop.js */
            Trenord.console.log("tabFooterTop {}");
        }
        ,

        carouselDoubleColumn: function () {

            $(".carouselDoubleColumn").owlCarousel({
                items: 1,
                center: true,
                loop: true,
                nav: false,
                responsive: {
                    0: {
                        mousedrag: true,
                        items: 1,

                    },
                    768: {
                        mousedrag: true,
                        items: 1,

                    },
                    1024: {
                        mousedrag: true,
                        items: 1,
                        dots: true
                    },
                    1280: {
                        mousedrag: true,
                        items: 1,
                        dots: true
                    },
                    1440: {
                        mousedrag: true,
                        items: 1,
                        dots: true,
                    },
                    1680: {
                        mousedrag: true,
                        items: 1,
                        dots: true,
                    },
                    2800: {
                        mousedrag: true,
                        items: 1,
                        dots: true,
                        loop: true,
                    },

                }
            });


            if (Trenord.utility.isMobile()) {
                $(".carouselDoubleColumn").owlCarousel();
                $(".carouselDoubleColumn").addClass("owl-carousel").addClass("owl-theme");

            } else {
                $('.carouselDoubleColumn').trigger('destroy.owl.carousel');
                $(".carouselDoubleColumn").removeClass("owl-carousel").removeClass("owl-theme");
            }

        }
        ,

        carosuelAgevolazioniSupplementi: function () {
            /* implementata in carosuelAgevolazioniSupplementi.js */
            Trenord.console.log("carosuelAgevolazioniSupplementi {}");
        }
        ,

        carouselGeneric: function () {
            /* implementata in carosuelGeneric.js */
            Trenord.console.log("carosuelGeneric {}");
        }
        ,
        carouselAppTrenord: function () {
            /* implementata in carouselAppTrenord.js */
            Trenord.console.log("carouselAppTrenord {}");
        }
        ,
        carouselLine: function () {
            /* implementata in carouselLine.js */
            Trenord.console.log("carouselLine {}");
        }
        ,
        filterLine: function () {
            /* implementata in carouselLine.js */
            Trenord.console.log("carouselLine {}");
        }
        ,

        carouselMedia: function () {
            /* implementata in carouselMedia.js */
            Trenord.console.log("carouselMedia {}");
        }
        ,
        laNostraOfferta: function () {
            /* implementata in laNostraOfferta.js */
            Trenord.console.log("laNostraOfferta {}");
        }
        ,
        carosuelMobileGreenCard: function () {
            /* implementata in carosuelMobileGreenCard.js */
            Trenord.console.log("carosuelMobileGreenCard {}");
        }
        ,

        malpensaVoli: {
            initEvents: function () {
                Trenord.console.log("malpensaVoli.initEvents {}");
            }
        }
        ,

        timeCircle: {
            initEvents: function () {
                Trenord.console.log("timeCircle.initEvents {}");
            }
        }
        ,

        lineeMappeOrari: {
            initEvents: function () {
                Trenord.console.log("lineeMappeOrari.initEvents {}");
            }
        }
        ,

        malpensaTreni: {
            initEvents: function () {
                Trenord.console.log("malpensaTreni.initEvents {}");
            }
        }
        ,

        malpensaProssimiTreni: {
            initEvents: function () {
                Trenord.console.log("malpensaTreni.initEvents {}");
            }
        }
        ,
        login: {

            initEvents: function () {
                /* implementata in login.js */
                Trenord.console.log("login {}");
            }
        }
        ,

        searchNews: function () {
            /* implementata in searchNews.js */
            Trenord.console.log("searchNews {}");
        }
        ,
        serp: function () {
            /* implementata in serp.js */
            Trenord.console.log("serp {}");
        }
        ,
        accesibilita: function () {
            /* implementata in serp.js */
            Trenord.console.log("serp {}");
        }
        ,
        lazyLoad: function () {
            /* implementata in lazyLoad.js */
            Trenord.console.log("lazyLoad {}");
        }
        ,


        payGo: function () {
            /* implementata in serp.js */
            Trenord.console.log("payGo {}");
        }
        ,

        toggleIVOLWidgetOverlay: function () {
            if (Trenord.globals.widget.overlay) {
                $(".search-box-ivol-widget.full-overlay .right-shoulder").removeClass("widget-in");
                setTimeout(function () {
                    $(".search-box-ivol-widget.full-overlay").addClass('hidden');
                    $("body,html").css("overflow", "initial");
                }, 400);
                Trenord.globals.widget.overlay = false;
                Trenord.events.trigger('closedShoulder');
            } else {
                $(".search-box-ivol-widget.full-overlay").removeClass('hidden');
                setTimeout(function () {
                    $(".search-box-ivol-widget.full-overlay .right-shoulder").addClass("widget-in");
                    $("body,html").css("overflow", "hidden");
                }, 100);

                Trenord.events.trigger('openedShoulder');
                Trenord.globals.widget.overlay = true;
            }
        },

        toggleWidgetOverlay: function () {
            if (Trenord.globals.widget.overlay) {
                $(".search-box-widget.full-overlay .right-shoulder").removeClass("widget-in");

                setTimeout(function () {
                    $(".search-box-widget.full-overlay").addClass('hidden');
                    $("body,html").css("overflow", "initial");
                }, 400);
                Trenord.globals.widget.overlay = false;
                Trenord.events.trigger('closedShoulder');
            } else {
                $(".search-box-widget.full-overlay").removeClass('hidden');
                setTimeout(function () {
                    $(".search-box-widget.full-overlay .right-shoulder").addClass("widget-in");
                    $("body,html").css("overflow", "hidden");
                }, 100);

                Trenord.events.trigger('openedShoulder');
                Trenord.globals.widget.overlay = true;
            }
        }
        ,

        setLoggedUser: function () {
            Trenord.console.log('ui logged user');
        }
        ,

        setNotLoggedUser: function () {
            Trenord.console.log('ui unlogged user');
        }
        ,

        allAlertSiteOpen: function () {

            var allAlertSiteCookie = Cookies.get('allAlertSiteCookie');

            if (!allAlertSiteCookie) {
                $(".container-alert").slideDown();
            }
        }
        ,

        allAlertSiteClosed: function () {


            var currentDomain = window.location.hostname

            Cookies.remove('allAlertSiteCookie', {
                path: '/'
            });
            Cookies.set('allAlertSiteCookie', "true", {
                expires: 1
            });

            //$("#cross-cookie").attr('src', otherDomain + '/rest/user/saveLoggedUser?sso=' + allAlertSiteCookie + "&logout=" + logout + "&no_cache=1");
        }
        ,

        infoMobilita: {

            initEvents: function (train_id) {

            }
        }
    }
    ,

    utility: {

        /* livello di lavorazione */
        /* indica quanti contianer devono essere elaborati */
        resizeHeightLevel: null,
        timeInterval:
            null,

        resizeHeight:

            function (className) {
                /* implementata in utility.js */
                Trenord.console.log("resize {}");
            }

        ,

        resizeHeightWidget: function () {
            Trenord.console.log("resizeHeightWidget {}");
        }
        ,

        Tooltip: function () {
            Trenord.console.log("Tooltip {}");
        }
        ,

        Tab: function () {
            Trenord.console.log("Tab {}");
        }
        ,

        Modal: function () {
            Trenord.console.log("Modal {}");
        }
        ,
        Faq: function () {
            Trenord.console.log("Faq {}");
        }
        ,

        Accordion: function () {
            Trenord.console.log("Accordion {}");
        }
        ,

        resizeSliderHome: function (element) {
            /* implementata in utility.js */
            Trenord.console.log("resizeSliderHome {}");
        }
        ,

        getMaxofClass: function (element) {
            /* implementata in utility.js */
            Trenord.console.log("getMaxofClass {}");
        }
        ,

        sumHeight: function (element) {
            /* implementata in utility.js */
            Trenord.console.log("sumHeight {}");
        }
        ,

        resizeTriangleMobile: function () {
            /* implementata in utility.js */
            Trenord.console.log("resizeTriangleMobile {}");
        }
        ,
        alert: function () {
            /* implementata in utility.js */
            Trenord.console.log("alert {}");
        }
        ,

        setCssAuto: function (object) {
            /* implementata in utility.js */
            Trenord.console.log("setCssAuto {}");
        }
        ,

        multipleTab: function (object) {
            /* implementata in utility.js */
            Trenord.console.log("MultipleTab {}");
        }
        ,

        VediAncheHover: function (object) {
            /* implementata in utility.js */
            Trenord.console.log("VediAncheHover {}");
        }
        ,

        mobileDetector: function (object) {
            /* implementata in utility.js */
            Trenord.console.log("mobileDetector {}");
        }
        ,
        tornaSu: function (object) {
            /* implementata in utility.js */
            Trenord.console.log("tornaSu {}");
        }
        ,
        changeStyleInPage: function (object) {
            /* implementata in utility.js */
            Trenord.console.log("utility {}");
        }
        ,
        widgetTool: function (object) {
            /* implementata in utility.js */
            Trenord.console.log("widgetTool {}");
        }
        ,

        isTablet: function () {
            Trenord.console.log("isTablet {}");
        }
        ,

        isMobile: function () {
            Trenord.console.log("isMobile {}");
        }
        ,

        initPassengerShoulder: function () {
            Trenord.console.log("initPassengerShoulder {}");
        }
        ,

        waitAndRedirect404: function () {
            Trenord.console.log("redirectHome {}");
        }

    }
    ,

    CTA: {
        event: null,
        availableTabConfig: {
            ticket: 'TICKET',
            subscription: 'SUBSCRIPTION',
            ticket_subscription: 'TICKET_SUBSCRIPTION',
        },
        reload: function () {
            Trenord.CTA.event = new CustomEvent('updateconfig', {
                detail: Trenord.CTA.config
            });
        },
        config: {
            /* oggetto richiesto dal widget */
            search: {
                /*  stazione di partenza */
                from: {
                    name: '',
                    codice_mir: ''
                },
                /*  stazione di arrivo */
                to: {
                    name: '',
                    codice_mir: ''
                },
                /*  flag per accendere/spegnere il ritorno */
                ar: false,
                /*  viaggiatori (la somma dei tre valori deve essere compresa tra 1 e 9 estremi inclusi) */
                travellers:
                {
                    adults: 1,
                    children: 0,
                    seniors: 0,
                    family: 0
                }
            },
            /*  flag per decidere se il cassetto laterale deve aprirsi a destra (true) o a sinistra (false) */
            right: false,
            /*   flag per decidere se mostrare il tab biglietto (false) o abbonamento (true) */
            subscription: false,
            tabConfig: 'TICKET_SUBSCRIPTION'
        },
        bici: function (fromStation, toStation, tabConfig) {
            Trenord.CTA.config.search.travellers.seniors = 0;
            Trenord.CTA.config.search.travellers.adults = 1;
            Trenord.CTA.config.search.travellers.children = 0;
            Trenord.CTA.config.search.travellers.family = 0;
            Trenord.CTA.config.isFamily = false;
            Trenord.CTA.config.subscription = false;
            Trenord.CTA.config.search.from = fromStation;
            Trenord.CTA.config.search.to = toStation;
            Trenord.CTA.config.tabConfig = tabConfig ? tabConfig : Trenord.CTA.availableTabConfig.ticket_subscription;
            Trenord.CTA.reload();
            Trenord.CTA._dispatch();
            Trenord.ui.toggleWidgetOverlay();
        },
        family: function (fromStation, toStation, tabConfig) {
            /* per settare correttamente */
            Trenord.CTA.config.search.travellers.seniors = 0;
            Trenord.CTA.config.search.travellers.adults = 0;
            Trenord.CTA.config.search.travellers.children = 0;
            Trenord.CTA.config.search.travellers.family = 1;
            Trenord.CTA.config.isFamily = true;
            Trenord.CTA.config.subscription = false;
            Trenord.CTA.config.search.from = fromStation;
            Trenord.CTA.config.search.to = toStation;
            Trenord.CTA.config.tabConfig = tabConfig ? tabConfig : Trenord.CTA.availableTabConfig.ticket_subscription;
            /* ricarico gli eventi */
            Trenord.CTA.reload();
            /* lancio l'evento */
            Trenord.CTA._dispatch();
            Trenord.ui.toggleWidgetOverlay();
        },
        seniors: function (fromStation, toStation, tabConfig) {
            /* per settare correttamente */
            Trenord.CTA.config.search.travellers.seniors = 1;
            Trenord.CTA.config.search.travellers.adults = 0;
            Trenord.CTA.config.search.travellers.children = 0;
            Trenord.CTA.config.search.travellers.family = 0;
            Trenord.CTA.config.isFamily = false;
            Trenord.CTA.config.subscription = false;
            Trenord.CTA.config.search.from = fromStation;
            Trenord.CTA.config.search.to = toStation;
            Trenord.CTA.config.tabConfig = tabConfig ? tabConfig : Trenord.CTA.availableTabConfig.ticket_subscription;
            /* ricarico gli eventi */
            Trenord.CTA.reload();
            /* lancio l'evento */
            Trenord.CTA._dispatch();
            Trenord.ui.toggleWidgetOverlay();
        },
        children: function (fromStation, toStation, tabConfig) {
            /* per settare correttamente */
            Trenord.CTA.config.search.travellers.seniors = 0;
            Trenord.CTA.config.search.travellers.adults = 0;
            Trenord.CTA.config.search.travellers.children = 1;
            Trenord.CTA.config.search.travellers.family = 0;
            Trenord.CTA.config.isFamily = false;
            Trenord.CTA.config.subscription = false;
            Trenord.CTA.config.search.from = fromStation;
            Trenord.CTA.config.search.to = toStation;
            Trenord.CTA.config.tabConfig = tabConfig ? tabConfig : Trenord.CTA.availableTabConfig.ticket_subscription;
            /* ricarico gli eventi */
            Trenord.CTA.reload();
            /* lancio l'evento */
            Trenord.CTA._dispatch();
            Trenord.ui.toggleWidgetOverlay();
        },
        base: function (fromStation, toStation, tabConfig) {
            Trenord.CTA.config.search.travellers.seniors = 0;
            Trenord.CTA.config.search.travellers.adults = 1;
            Trenord.CTA.config.search.travellers.children = 0;
            Trenord.CTA.config.search.travellers.family = 0;
            Trenord.CTA.config.isFamily = false;
            Trenord.CTA.config.subscription = false;
            Trenord.CTA.config.search.from = fromStation;
            Trenord.CTA.config.search.to = toStation;
            Trenord.CTA.config.tabConfig = tabConfig ? tabConfig : Trenord.CTA.availableTabConfig.ticket_subscription;
            /* ricarico gli eventi */
            Trenord.CTA.reload();
            /* lancio l'evento */
            Trenord.CTA._dispatch();
            Trenord.ui.toggleWidgetOverlay();
        },
        base_station: function (stationName) {
            Trenord.CTA.config.search.travellers.seniors = 0;
            Trenord.CTA.config.search.travellers.adults = 1;
            Trenord.CTA.config.search.travellers.children = 0;
            Trenord.CTA.config.search.travellers.family = 0;
            Trenord.CTA.config.isFamily = false;
            Trenord.CTA.config.subscription = false;
            Trenord.CTA.config.search.from = { name: '', codice_mir: '' };
            Trenord.CTA.config.search.to = { name: stationName, codice_mir: '' };
            /* ricarico gli eventi */
            Trenord.CTA.reload();
            /* lancio l'evento */
            Trenord.CTA._dispatch();
            Trenord.ui.toggleWidgetOverlay();
        },
        abbonamento: function (fromStation, toStation, tabConfig) {
            Trenord.CTA.config.search.travellers.seniors = 0;
            Trenord.CTA.config.search.travellers.adults = 1;
            Trenord.CTA.config.search.travellers.children = 0;
            Trenord.CTA.config.search.travellers.family = 0;
            Trenord.CTA.config.isFamily = false;
            Trenord.CTA.config.subscription = true;
            Trenord.CTA.config.search.from = fromStation;
            Trenord.CTA.config.search.to = toStation;
            if (tabConfig === Trenord.CTA.availableTabConfig.ticket) {
                Trenord.CTA.config.tabConfig = Trenord.CTA.availableTabConfig.ticket_subscription
            } else {
                Trenord.CTA.config.tabConfig = tabConfig ? tabConfig : Trenord.CTA.availableTabConfig.ticket_subscription;
            }
            /* ricarico gli eventi */
            Trenord.CTA.reload();
            /* lancio l'evento */
            Trenord.CTA._dispatch();
            Trenord.ui.toggleWidgetOverlay();
        },
        carnet: function (fromStation, toStation) {
            if (fromStation.codice_mir && fromStation.name) {
                Trenord.carnet.setOrigin(fromStation.codice_mir, fromStation.name, '');
                $('#startStation')[0].value = fromStation.name;
                $('#label-station').addClass('active');
            }
            if (toStation.codice_mir && toStation.name) {
                Trenord.carnet.setDestination(toStation.codice_mir, toStation.name, '');
                $('#arriveStation')[0].value = toStation.name
                $('#label-arrive-station').addClass('active');
            }
            Trenord.ui.toggleWidgetOverlay();
        },
        ivol: function () {
            Trenord.ui.toggleIVOLWidgetOverlay();
        },
        ancillary: function () {
            Trenord.ui.toggleWidgetOverlay();
        },
        _dispatch: function () {
            document.dispatchEvent(Trenord.CTA.event);
        }
    }
    ,

    passengersWidget: {

        totalMax: 9,
        singleMin:
            0,
        increment:
            1,
        from:
            '',
        to:
            '',
        trainClass:
            'firstClass',
        date:
            '',
        time:
            '',
        travellers:
        {
            adults: 1,
            children:
                0,
            seniors:
                0,
            family:
                0
        }
        ,

        init: function () {


            if (window.location.hostname.indexOf("trenord.it") > -1) {

                Trenord.ui.malpensaWidget.loadTrenordVisualization();

            } else if (window.location.hostname.indexOf("malpensaexpress.it") > -1) {

                Trenord.ui.malpensaWidget.loadMalpensaVisualization();

            }
        }
        ,

        triggerPositive: function () {
            Trenord.passengersWidget.increment = 1;
        }
        ,

        triggerNegative: function () {
            Trenord.passengersWidget.increment = -1;
        }
        ,

        setDate: function (date) {
            Trenord.passengersWidget.date = date;
        }
        ,

        setTime: function () {
            Trenord.passengersWidget.date = time;
        }
        ,

        setFromStation: function (station) {

            Trenord.passengersWidget.from = station;
        }
        ,

        setToStation: function (station) {
            Trenord.passengersWidget.to = station;
        }
        ,

        addAdults: function () {

            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.adults))
                Trenord.passengersWidget.travellers.adults += Trenord.passengersWidget.increment;

        }
        ,

        addChildren: function () {
            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.children))
                Trenord.passengersWidget.travellers.children += Trenord.passengersWidget.increment;
        }
        ,

        addSenior: function () {

            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.seniors))
                Trenord.passengersWidget.travellers.seniors += Trenord.passengersWidget.increment;
        }
        ,

        addFamily: function () {

            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.family))
                Trenord.passengersWidget.travellers.family += Trenord.passengersWidget.increment;
        }
        ,

        removeAdults: function () {

            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.adults))
                Trenord.passengersWidget.travellers.adults -= Trenord.passengersWidget.increment;
        }
        ,

        removeChildren: function () {
            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.children))
                Trenord.passengersWidget.travellers.children -= Trenord.passengersWidget.increment;
        }
        ,

        removeSenior: function () {
            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.seniors))
                Trenord.passengersWidget.travellers.seniors -= Trenord.passengersWidget.increment;
        }
        ,

        removeFamily: function () {
            if (Trenord.passengersWidget.canIncrement(Trenord.passengersWidget.travellers.family))
                Trenord.passengersWidget.travellers.family -= Trenord.passengersWidget.increment;
        }
        ,

        getTotal: function () {

            return Trenord.passengersWidget.travellers.children +
                Trenord.passengersWidget.travellers.adults +
                Trenord.passengersWidget.travellers.seniors +
                Trenord.passengersWidget.travellers.family;
        }
        ,

        getApiUrl: function () {

            /* per semplicità mi aspetto un json encodato */
            var apiUrl = '/rest/content/selected-solution?params='
            var params = encodeURIComponent(JSON.stringify(Trenord.passengersWidget));

            return apiUrl + params;
        }
        ,

        canIncrement: function (property) {

            if (Trenord.passengersWidget.increment > 0) {
                return Trenord.passengersWidget.getTotal() < Trenord.passengersWidget.totalMax;
            } else {

                if (property == 1 && Trenord.passengersWidget.getTotal() == 1) {
                    return false;
                }

                return property > 0;
            }

        }
    }
    ,

    shoulderLines: {

        init: function () {

            var search = Trenord.utility.locationSearchToObject();
            /* se è malpensa devo gestire la casistica */
            var mxp = window.location.hostname.indexOf("malpensaexpress.it") > -1;

            /* comunque carico le linee per le interazioni successive */


            /* questa logica permette di caricare il dettaglio di una linea */
            /* se specificata e appartenente al corretto dominio */


            if ($("body").hasClass("malpensaStyle")) {
                Trenord.shoulderLines.allLines(mxp);

            } else {
                var searchParams = new URLSearchParams(window.location.search);
                var code = searchParams.get('code');

                if (code) {
                    Trenord.shoulderLines.lineDetail(code, false);
                } else {
                    var mxp = window.location.hostname.indexOf("malpensaexpress.it") > -1;
                    Trenord.shoulderLines.allLines(mxp);
                }
            }


            if (search.line != undefined && search.line != "" && code == "") {
                Trenord.shoulderLines.lineDetail(search.line, false);
            }


            $(document).on("showLineFromMap", function (event, line) {
                Trenord.shoulderLines.lineDetail(line, true);
            });

        }
        ,

        allLines: function (mxp) {


            $.get('/rest/render/shoulder-lines?no_cache=1', {
                'mxp': mxp,
                'L': Trenord.globals.currentLanguage
            }, function (data) {

                $(".all-lines .list.result").html(data.message);
                $(".all-lines .list.skeleton").addClass("hidden");
                $(".all-lines .list.result").removeClass("hidden");

                Trenord.ui.shoulderLines.initLineEvent();
                Trenord.ui.lineeMappeOrari.initEvents();

                /* CHIAMATA ESTERNA LIBRERIA NOOVLE.JS */
                setMap();


                function setMap() {

                    if (Trenord.utility.GeoProj) {
                        showAllLines();
                    } else {

                        setTimeout(function () {
                            setMap();
                        }, 1000);

                    }

                }


            });
        },

        lineDetail: function (line, fromMap) {
            var params = {
                code: line.toUpperCase(),
                L: Trenord.globals.currentLanguage
            };

            $(".all-lines").addClass("hidden");
            $(".specific-line.skeleton").removeClass("hidden");

            Trenord.popUpMessage.waitResponse("linee-mappe-orari");

            $.get('/rest/render/line-details', params, function (data) {
                $(".result-details-line.hidden").append(data.message);
                $(".specific-line.result").html(data.message);
                $(".specific-line.skeleton").addClass("hidden");
                $(".specific-line.result").removeClass("hidden");

                Trenord.ui.carouselLine();
                Trenord.ui.filterLine();
                Trenord.ui.ideeDiViaggio.init();
                Trenord.ui.lineeMappeOrari.initEvents();
                Trenord.popUpMessage.hideModalBox("linee-mappe-orari");

                //new linee
                $(".line-img-code").attr("src", $(".name-line .img-line").attr("src"));

                if ($(".carousel-line .owl-item .item:last-child:not(.info) .body-texts").length > 0) {
                    $(".last-update").text($(".update-line").text());
                    $(".single-box.state span.text p.title ").after($(".carousel-line .owl-item .item:last-child:not(.info) .body-texts").html());
                    $(".single-box.state .img").html($(".title-icon .status-line").parent().html().replace("Stato della linea", ""));
                    $(".single-box.state .img .p2").addClass("hidden");
                    $(".single-box.state span.text p.title").text("Circolazione " + $(".single-box.state .img .p2").text().toLowerCase())
                } else {
                    $(".last-update").text($(".update-line").text());

                    $(".single-box.state .img").html('<div class=" status-line no-margin green-line 2 "><span class="dot"></span><p class="p2 hidden"></p></div>');
                    $(".single-box.state .img .p2").addClass("hidden");
                    $(".single-box.state span.text p.title").text("Circolazione Regolare");

                }

                if ($(".carousel-line .owl-item .item.info:last-child .body-texts").length > 0) {
                    $(".single-box.avvisi span.text .title.date").text($(".carousel-line .owl-item:last-child .item .date_news").text());
                    $(".single-box.avvisi span.text p.title ").after($(".carousel-line .owl-item .item.info:last-child .body-texts").html());
                    $(".single-box.avvisi span.img img.results").removeClass("hidden");
                    $(".single-box.avvisi span.img img.no-results ").addClass("hidden");
                } else {

                    $(".single-box.avvisi span.text p.title ").text("Nessun avviso").removeClass("date");
                    $(".single-box.avvisi span.img img.no-results ").removeClass("hidden");
                    $(".single-box.avvisi span.img img.results ").addClass("hidden");

                }

                // LineDetail - STATO DELLA LINEA
                $(".carousel-line .owl-item .item:not(.info)").each(function () {
                    $(".news-state.line").append($(this).parent().html());
                });
                if ($(".news-state.line .item").length > 1) {
                    $(".news-state.line .item").first().after('<div class="first-news">Informazioni precedenti</div>');
                }

                // LineDetail - AVVISI
                $('.carousel-line .owl-item .item.info').each(function () {
                    $(".news-state.avvisi").append($(this).parent().html());
                });
                if ($(".news-state.avvisi .item").length > 1) {
                    $(".news-state.avvisi .item").first().after('<div class="first-news">Avvisi precedenti</div>');
                }

                $(".modal-content.news .item").each(function () {
                    if ($(this).hasClass("info")) {

                    } else {
                        $(this).find(".status-line").prependTo(this);
                    }

                });


                if ($(".carousel-line .owl-item .item:not(.info)").length > 1) {
                    $(".more-news-direttrice").removeClass("hidden");
                } else {
                    $(".more-news-direttrice").addClass("hidden");
                }

                if ($(".carousel-line .owl-item .item.info").length > 1) {
                    $(".more-appro").removeClass("hidden");
                } else {
                    $(".more-appro").addClass("hidden");
                }


                $(".station-type li").each(function () {
                    var space = " ";

                    var id = "'" + $(this).data("id") + "'";
                    var titleStation = $(this).find(".col-xs-6 p").text()
                    var biglietteria = $(this).data("type-station-biglietteria") ? '<img class="biglietteria" src="/fileadmin/templates/img/biglietto_elettronico_mini.png">' : '';
                    var distributore = $(this).data("type-station-distributori") ? '<img class="distributori" src="/fileadmin/templates/img/distributori-mini.png">' : '';
                    var disabili = $(this).data("type-station-disabili") ? '<img class="disabili" src="/fileadmin/templates/img/accesibili_mini.png">' : '';
                    var banchine = $(this).data("type-station-banchine") ? '<span  class="bc"> <img src="/fileadmin/templates/img/banchina_corta_mini.png"> <p>Banchina corta</p></span>' : '';
                    var srcLine = $(this).find(".link-station-type").attr("href");

                    $(".container-station-list .list ul").append('<li  onmouseover="setOverStateFromStation(' + id + ')" onmouseout="removeOverStateFromStation(' + id + ')"class= "element-item  "   ><a href=' + srcLine + '><span class="title"><p>' + titleStation + '</p></span><span class="fr">' +
                        '<span class="icons">' + biglietteria + '' + distributore + disabili + banchine +
                        '</span><span class="arrow "><svg class="rotate-arrow" xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 240 240"><path id="left-a" d="M59.55 51.054l48.6-49.004a6.902 6.902 0 0 1 9.818 0c2.71 2.734 2.71 7.166 0 9.9l-53.554 54a6.902 6.902 0 0 1-9.863-.047l-52.562-54c-2.686-2.759-2.645-7.19.091-9.899a6.902 6.902 0 0 1 9.818.093L59.55 51.054z"></path></svg></span></span></a></li>');
                });


                $(".filter-button-list .button-filter-service:not(.hidden-desktop)").click(function () {
                    if ($(this).hasClass("active")) {
                        $(".filter-button-list .button-filter-service").removeClass("active");

                        resetStations();
                        $(".container-station-list .list ul li").each(function () {
                            $(this).removeClass("hidden");
                        });
                    } else {
                        $(".filter-button-list .button-filter-service").removeClass("active");
                        $(this).addClass("active");
                        var attr = $(this).data("filter");
                        $(".container-station-list .list ul li").each(function () {
                            if ($(this).find("." + attr + "").length > 0) {
                                $(this).removeClass("hidden");
                            } else {
                                $(this).addClass("hidden");
                            }
                        });
                    }
                });


                $(".submitFilterMobile").click(function () {




                    $(".container-station-list .list ul li span.icons").each(function () {

                        if ($("#biglietteriaMobile:checked").length > 0) {
                            if ($(this).find("img").hasClass("biglietteria")) {
                                $(this).parent().parent().parent().removeClass("hidden");
                            } else {
                                $(this).parent().parent().parent().addClass("hidden");
                            }
                        }

                        if ($("#distributoriMobile:checked").length > 0) {
                            if ($(this).find("img").hasClass("distributori")) {
                                $(this).parent().parent().parent().removeClass("hidden");
                            } else {
                                $(this).parent().parent().parent().addClass("hidden");
                            }
                        }

                        if ($("#accesibiliMobile:checked").length > 0) {
                            if ($(this).find("img").hasClass("disabili")) {
                                $(this).parent().parent().parent().removeClass("hidden");
                            } else {
                                $(this).parent().parent().parent().addClass("hidden");
                            }
                        }
                    });

                    $("#close-filter-mobile").trigger("click");

                });

                $(".button-filter-service.hidden-desktop").click(function () {
                    $(".container-button-filter-mobile").removeClass("hidden");
                });


                $("#close-filter-mobile").click(function () {
                    $(".container-button-filter-mobile").addClass("hidden");
                });


                $(".filter-mobile-body .ui-autocomplete-input").bind('change', function () {

                    if ($(".filter-mobile-body .ui-autocomplete-input:checked").length > 1) {
                        $(".remove-filter-mobile").removeClass("hidden");
                    } else {
                        $(".remove-filter-mobile").addClass("hidden");
                    }
                });

                $(".remove-filter-mobile").click(function () {
                    $(".ui-autocomplete-input").prop('checked', false);
                    $(this).addClass("hidden");
                });

                $(".container-station-list .list ul").perfectScrollbar();




                /* var searchParams = new URLSearchParams(window.location.search)
                     var nameLine = searchParams.get('line').replace("%20", " ");
                     var nameLineFiltered = nameLine.replace("+", " ");
    
                    $("[id='" + nameLineFiltered + "'] .caption").removeClass("hidden");
                    $("[id='" + nameLineFiltered + "']").prependTo(".sidebar");
     */
                if ($("body").hasClass("malpensaStyle")) {
                    $("#donwload_line").removeClass("hidden");

                } else {
                    $(".description-line").addClass("hidden");
                    var imgSource = $(".name-line .img-line").attr("src");


                    $(" .caption:visible .img-line-detail img").attr("src", imgSource);


                    $("#donwload_line").addClass("hidden");

                    if (Trenord.utility.isMobile()) {
                        if ($(".caption:visible .img-line-detail").length > 1) {

                        } else {
                            $(".caption:visible .img-line-detail:visible ").insertAfter($(".caption:visible .link-back"));
                        }
                    }

                    if ($(window).width() < 768) {

                        setTimeout(function () {
                            if ($(".sidebar .all-lines:visible").length > 0) {

                                $(".linee-orari #noovle-map").removeClass("active");
                            } else {
                                $(".linee-orari #noovle-map").addClass("active");
                            }
                        }, 400);

                    }
                }
                if (!fromMap) {
                    setMapLines();


                    function setMapLines() {

                        if (Trenord.utility.GeoProj) {
                            //      showLine(line)
                        } else {

                            setTimeout(function () {
                                setMapLines();
                            }, 1000);

                        }

                    }
                }

            });
        },

        filter: function (string) {


            var listResult = $(".new_line li a");

            if (string.length == 0) {
                $(".new_line").removeClass("hidden");
                listResult.parent().show();

                $(".new_line").each(function () {
                    if ($(this).find("li").length == 0) {
                        $(this).addClass("hidden");
                    }
                });
            } else {

                listResult.parent().hide();

                listResult.each(function (index, value) {

                    var code = $(value).data('code');
                    var dir = $(value).data('direttrice');
                    var name = $(value).data('name');

                    var compare = code.toLowerCase() + dir.toLowerCase() + name.toLowerCase();

                    var match = compare.indexOf(string.trim()) >= 0;

                    if (match) {
                        $(value).parent().show();
                        $(".new_line").removeClass("hidden");
                    }

                })


                $(".new_line").each(function () {
                    $(this).find("li:visible").length > 0 ? null : $(this).addClass("hidden");
                });
            }



        }

    }
    ,

    infoMobilita: {

        initEvents: function () {
            Trenord.console.log("trainSearch {}");
        }
        ,

        searchTrain: function () {

            Trenord.console.log("searchTrain {}");
        }
        ,

        stationDetails: function () {
            Trenord.console.log("stationDetails {}");
        }
    }
    ,

    payGo: {

        download: function (repost, ticketId) {

            var url = "/rest/render/pay-go-receipt?" + repost + "&ticketId=" + ticketId;

            Trenord.popUpMessage.waitResponse('pay-go');

            $.fileDownload(url, {
                successCallback: function (url) {
                    Trenord.popUpMessage.open("success", "Success", "Download eseguito con successo.");
                },
                failCallback: function (responseHtml, url) {
                    Trenord.popUpMessage.open("error", "Oops!", "Qualcosa è andato storto.<br> Ti invitiamo a riprovare.");
                }
            });

        }
        ,

        verify: function () {

            var formData = $("#payGo-form").serialize();

            Trenord.popUpMessage.waitResponse("pay-go");
            $.post('/rest/render/pay-go', formData, function (data) {


                var count = (data.message.match(/<tr>/g) || []).length;

                if (count > 10) {
                    $(".container-mostra-altri.payGo").fadeIn();
                }

                $([document.documentElement, document.body]).animate({
                    scrollTop: $(".table-ricevute-result").offset().top + 300
                }, 1000);
                $(".table-ricevute-result").html(data.message);

                Trenord.popUpMessage.hideModalBox("pay-go");

            });
        }
    }
    ,

    form: {

        contatti: {

            validateSend: function () {
                var c = 0;

                $(".container-form-contatti .input-form").each(function (index) {

                    if ($(this).hasClass("bootstrap-select") || $(this).hasClass("selectpicker")) {

                    } else if ($(this).attr("id") === "informativaCheck") {
                        if (!$(this).is(":checked")) {
                            $(this).parent().addClass("error-stepper")
                            c++;
                        }
                        else {
                            $(this).parent().removeClass("error-stepper")
                        }
                    }
                    else {
                        if ($(this).val() === "") {
                            $(this).parent().find("label").addClass("error-input");
                            if ($(this).attr("id") === "richiesta") {
                                $("#label-richiesta").addClass("error-input");
                                c++;
                            }
                            if (!selected) {
                                $("p#label-motivo").addClass("error-input");
                                c++;
                            }
                            c++;
                        } else {
                            if ($(this).attr("id") === "email") {
                                var email = $(this).val();
                                var emailValidator = /^\w+[\w-+\.]*\@\w+([-\.]\w+)*\.[a-zA-Z]{2,}$/;

                                if (!email.match(emailValidator)) {
                                    $("label#label-email").css("color", "#ff0000");
                                    c++;
                                } else {
                                    $("label#label-email").css("color", "#4a4a4a");
                                }

                            }
                        }
                    }
                });

                if (grecaptcha != undefined) {
                    response = grecaptcha.getResponse();

                    if (response == "") {
                        c++;
                        $(".g-recaptcha > div").addClass("err-captcha");
                    }
                } else {
                    c++;
                    $(".g-recaptcha > div").addClass("err-captcha");
                }

                if (c > 0) {
                    $(".container-form-contatti .container-error-contatti").css("display", "inline-block");
                } else {
                    $(".container-form-contatti .container-error-contatti").css("display", "none");
                    $(".g-recaptcha > div").removeClass("err-captcha");
                    return true;
                }

                return false;
            }
            ,


            validateSendIndenizzi: function () {
                var c = 0;

                $(".selectpicker").each(function (index) {
                    if ($(this).val() === null) {
                        for(ids of $(this).attr("id").split(" ")){
                           $("."+ids).addClass("error-input");
                        }
                    }
                })

                $(".container-form-contatti .input-form").each(function (index) {
                    if ($(this).hasClass("bootstrap-select") || $(this).attr("id") === "richiesta") {

                    } else if ($(this).attr("id") === "informativaCheck") {
                        if (!$(this).is(":checked")) {
                            $(this).parent().addClass("error-stepper")
                            c++;
                        }
                        else {
                            $(this).parent().removeClass("error-stepper")
                        }
                    }
                    else {
                        if ($(this).val() === "") {
                            $(this).parent().find("label").addClass("error-input");
                            if ($(this).attr("id") === "richiesta") {
                                $("#label-richiesta").addClass("error-input");
                                c++;
                            }
                            if (!selected) {
                                // $("p#label-motivo").addClass("error-input");
                                c++;
                            }
                            c++;
                        } else {
                            if ($(this).attr("id") === "email") {
                                var email = $(this).val();
                                var emailValidator = /^\w+[\w-+\.]*\@\w+([-\.]\w+)*\.[a-zA-Z]{2,}$/;

                                if (!email.match(emailValidator)) {
                                    $("label#label-email").css("color", "#ff0000");
                                    c++;
                                } else {
                                    $("label#label-email").css("color", "#4a4a4a");
                                }

                            }
                        }
                    }
                });

                if (grecaptcha != undefined) {
                    response = grecaptcha.getResponse();

                    if (response == "") {
                        c++;
                        $(".g-recaptcha > div").addClass("err-captcha");
                    }
                } else {
                    c++;
                    $(".g-recaptcha > div").addClass("err-captcha");
                }

                if (c > 0) {
                    $(".container-form-contatti .container-error-contatti").css("display", "inline-block");
                } else {
                    $(".container-form-contatti .container-error-contatti").css("display", "none");
                    $(".g-recaptcha > div").removeClass("err-captcha");
                    return true;
                }

                return false;
            }
            ,

            uploadedFiles: [],

            initEvents: function () {

                $("#submit-form-contatti").click(function (event) {
                    if (Trenord.form.contatti.validateSend())
                        Trenord.form.contatti.send();
                });

                $("#submit-form-contatti-indenizzo").click(function (event) {
                    if (Trenord.form.contatti.validateSendIndenizzi())
                        Trenord.form.contatti.sendIndenizzi();
                });

                $("#link-informativa").click(function (event) {
                    $("#informativaCheck").prop("disabled", false)
                });

                var convertBlobToBase64 = function (blob) {
                    return new Promise(function (resolve, reject) {
                        const reader = new FileReader;
                        reader.onerror = reject;
                        reader.onload = () => {
                            resolve(reader.result);
                        };
                        reader.readAsDataURL(blob);
                    })
                };

                function extractMimeAndBase64(fileString) {
                    var format = /data:(.*\/.*);base64,(.*)/g
                    var extractedData = format.exec(fileString)

                    if (extractedData !== null) {
                        var mime = extractedData[1]
                        var b64 = extractedData[2]

                        if (mime !== null &&
                            b64 !== null) {
                            return {
                                fileMimeType: mime,
                                fileContentBase64: b64
                            }
                        }
                    }
                }

                $("#upload_allegati").change(function (e) {
                    if (e.target.value === "")
                        return

                    Trenord.popUpMessage.waitResponse();
                    var files = Array.from(e.target.files);

                    var maxFiles = 1
                    if (files.length > maxFiles ||
                        files.length + Trenord.form.contatti.uploadedFiles.length > maxFiles) {
                        handleTooManyFilesError(maxFiles)
                        return
                    }

                    if (files.length > 0) {
                        Promise.all(
                            files.map(function (file) {
                                var checkData = {
                                    fileName: file.name,
                                    error: "",
                                }

                                return new Promise(async function (resolve, reject) {
                                    twoMBSize = 1572864
                                    if (file.size > twoMBSize) {
                                        checkData.error = "size"
                                        reject(checkData)
                                        return
                                    }

                                    const b64result = await convertBlobToBase64(file);
                                    if ((extractedValues = extractMimeAndBase64(b64result)) !== null) {
                                        resolve({ fileName: file.name, ...extractedValues });
                                        return
                                    }
                                    else {
                                        checkData.error = "read"
                                        reject(checkData)
                                        return
                                    }
                                })
                            })
                        )
                            .then((results) => {
                                Trenord.form.contatti.uploadedFiles = [...Trenord.form.contatti.uploadedFiles, ...results]
                                handleUploadedFiles(results)
                                setupFileRemovalEvent()
                            })
                            .catch((checkData) => {
                                handleUploadError(checkData)
                                setupFileRemovalEvent()
                            })
                    }
                })

                function handleTooManyFilesError(maxFiles) {
                    //reset input
                    document.getElementById("upload_allegati").value = "";
                    Trenord.popUpMessage.open("error", "Oops!", `Stai cercando di allegare troppi file, il massimo consentito è ${maxFiles} document${maxFiles === 1 ? 'o' : 'i'}.</br></br>`);
                }

                function handleUploadedFiles(filesData) {
                    $.each(filesData, function (_, data) {
                        // create uploaded item list element to insert below the upload button
                        $(`<li class='not-style'><p>${data.fileName}<img data-file='${data.fileName}' class='icon-28 inline-icon removeUpload lozad' src='/fileadmin/templates/img/icons/Close.svg'></p></li>`).insertAfter("#trigger_upload_allegati");
                    })

                    Trenord.popUpMessage.open("success", "Ok", "Caricamento dei files avvenuto con successo.");
                }

                function handleUploadError(checkData) {
                    var errorMessage = checkData.fileName

                    switch (checkData.error) {
                        case "size":
                            errorMessage += " - file troppo grande</br>";
                            break;
                        case "read":
                            errorMessage += " - errore durante il caricamento</br>";
                            break;
                    }

                    //reset input
                    document.getElementById("upload_allegati").value = "";

                    Trenord.popUpMessage.open("error", "Oops!", "Alcuni file non sono stati caricati</br></br>" + errorMessage);
                }

                function setupFileRemovalEvent() {
                    //eliminazione allegato aggiungendo classe hidden
                    $(".removeUpload").unbind();
                    $(".removeUpload").on("click", function (event) {
                        Trenord.popUpMessage.waitResponse();
                        Trenord.popUpMessage.open('success', 'Ok!', "allegato rimosso con successo.");
                        document.getElementById("upload_allegati").value = "";
                        $(this).parent().parent().addClass("hidden");

                        // remove from list
                        Trenord.form.contatti.uploadedFiles = Trenord.form.contatti.uploadedFiles.filter(
                            (file) => { return file.fileName !== $(this).attr('data-file') }
                        )
                    });
                }

                $("#trigger_upload_allegati").click(function () {
                    $("#upload_allegati").trigger("click");
                });

            }
            ,

            send: function () {
                var unindexedParams = $("#form-contatti").serializeArray();
                var params = {};

                $.map(unindexedParams, function (n, i) {
                    params[n['name']] = n['value'];
                });
                params.files = Trenord.form.contatti.uploadedFiles
                var isModal = $("#form-contatti").data('modal');

                if (isModal) {
                    $("#close-modal-form-overaly").trigger('click');
                }

                Trenord.popUpMessage.waitResponse('contact-form');
                $.post('/rest/cta/send-contact', params, function (data) {

                    if (data && data.ResultStatus === true) {
                        dataLayer.push({
                            'event': 'form-submitted',
                            'formType': 'contatti',
                            'evtCat': 'form',
                            'evtAction': 'submit',
                            'evtLabel' : params['reason']
                        });
                    }
                    
                    switch (params.sendType) {
                        case 'email':
                            if (data) {
                                Trenord.popUpMessage.open("success", "Invio effettuato con successo", "Un nostro operatore ti risponderà nel più breve tempo possibile </br> per fornirti assistenza e rispondere alle tue domande.");
                            } else {
                                Trenord.popUpMessage.open("error", "Oops!", "Qualcosa è andato storto.<br> Ti invitiamo a riprovare.");
                            }
                            break
                        case 'service':
                            if (data && data.ResultStatus) {
                                Trenord.popUpMessage.open("success", "Invio effettuato con successo", "Numero protocollo: " + data.Message + ".<br />Un nostro operatore ti risponderà nel più breve tempo possibile </br>" +
                                    " per fornirti assistenza e rispondere alle tue domande.");
                            } else if (data && data.Message) {
                                Trenord.popUpMessage.open("error", "Attenzione", data.Message);
                            } else {
                                Trenord.popUpMessage.open("error", "Oops!", "Qualcosa è andato storto.<br> Ti invitiamo a riprovare.");
                            }
                            break
                    }
                    if (data && data.ResultStatus) {
                        $("#form-contatti")[0].reset();
                    }

                    if (grecaptcha != undefined)
                        grecaptcha.reset();
                });
            }
            ,
            sendIndenizzi: function () {
                var unindexedParams = $("#form-contatti").serializeArray();
                var params = {};

                $.map(unindexedParams, function (n, i) {
                    params[n['name']] = n['value'];
                });
                params.files = Trenord.form.contatti.uploadedFiles
                var isModal = $("#form-contatti").data('modal');

                if (isModal) {
                    $("#close-modal-form-overaly").trigger('click');
                }

                Trenord.popUpMessage.waitResponse('contact-form');
                $.post('/rest/cta/send-contact-indenizzi', params, function (data) {
                    if (data) {
                        Trenord.popUpMessage.openComplete("success", "Dichiarazione effettuata con successo", "Grazie per aver compilato il form, riceverai un email di conferma.", () => {location.reload()});
                    } else {
                        Trenord.popUpMessage.openComplete("error", "Oops!", "Qualcosa è andato storto.<br> Ti invitiamo a riprovare.");
                    }
                    // // console.log(data)
                    // // console.log(data.ResultStatus)
                    // if (data) {
                    //     console.log('reset');
                    //     $("#form-contatti")[0].reset();
                    //     $('select').prop('selectedIndex', 0);
                    // }

                    // if (grecaptcha != undefined)
                    //     grecaptcha.reset();
                });
            }
        }
    }
    ,

    popUpMessage: {

        waitResponse: function () {

            Trenord.popUpMessage.hideModalBoxForm();
            Trenord.popUpMessage.startSpinner();
            Trenord.popUpMessage.showModalBox();
        }
        ,

        open: function (status, title, description, closeCallback) {

            Trenord.popUpMessage.stopSpinner();
            Trenord.popUpMessage.showModalBoxForm();
            Trenord.popUpMessage.setMessageStatus(status);
            Trenord.popUpMessage.setMessageInfo(title, description);
            Trenord.popUpMessage.setCloseCallback(closeCallback);
            Trenord.popUpMessage.showModalBox();
        }
        ,

        openComplete: function (status, title, description, closeCallback) {

            Trenord.popUpMessage.stopSpinner();
            Trenord.popUpMessage.showModalBoxForm();
            Trenord.popUpMessage.setMessageStatus(status);
            Trenord.popUpMessage.setMessageInfo(title, description);
            Trenord.popUpMessage.setCompleteCloseCallback(closeCallback);
            Trenord.popUpMessage.showModalBox();
        }
        ,

        openWithBackgroundTransparent: function (status, title, description, closeCallback) {

            Trenord.popUpMessage.stopSpinner();
            Trenord.popUpMessage.showModalBoxForm();
            Trenord.popUpMessage.setMessageStatus(status);
            Trenord.popUpMessage.setMessageInfo(title, description);
            Trenord.popUpMessage.setCloseCallback(closeCallback);
            Trenord.popUpMessage.setBackgroundTransparent();
            Trenord.popUpMessage.fixTexts();
            Trenord.popUpMessage.showModalBox();
        }
        ,

        openCompleteWithBackgroundTransparent: function (status, title, description, closeCallback) {

            Trenord.popUpMessage.stopSpinner();
            Trenord.popUpMessage.showModalBoxForm();
            Trenord.popUpMessage.setMessageStatus(status);
            Trenord.popUpMessage.setMessageInfo(title, description);
            Trenord.popUpMessage.setCompleteCloseCallback(closeCallback);
            Trenord.popUpMessage.setBackgroundTransparent();
            Trenord.popUpMessage.fixTexts();
            Trenord.popUpMessage.showModalBox();
        }
        ,

        fixTexts: function () {
            $("#modal-popup-message .pop-up-title").css("font-size", "32px");
            $("#modal-popup-message .pop-up-title").css("line-height", "1.5");
            $("#modal-popup-message .pop-up-description").css("font-size", "24px");
            $("#modal-popup-message .pop-up-description").css("line-height", "1.2");
        }
        ,

        setBackgroundTransparent: function () {
            $("#modal-popup-message").css("background-color","rgba(46,46,46,.65)");
        },

        setMessageInfo: function (title, description) {

            $("#modal-popup-message .pop-up-title").html(title);
            $("#modal-popup-message .pop-up-description").html(description);
        }
        ,

        setMessageStatus: function (status) {
            $("#modal-popup-message").find(".status").hide();
            $("#modal-popup-message").find("." + status).show();
        }
        ,

        setCloseCallback: function (cb) {
            $("#close-modal-result", $("#modal-popup-message")).on('click', cb)
        },

        setCompleteCloseCallback: function (cb) {
            $("#modal-popup-message").on('click', cb)
        },

        hideModalBoxForm: function () {

            $("#modal-popup-message").find(".modal-form").hide();
        }
        ,

        showModalBoxForm: function () {
            $("#modal-popup-message").find(".modal-form").show();
        }
        ,

        /**
         * non è utilizzata perchè l'utente deve chiudere il form
         * @param id
         */
        hideModalBox: function () {

            $("#modal-popup-message").hide();
        }
        ,

        showModalBox: function () {
            $("#modal-popup-message").show();
        }
        ,

        startSpinner: function () {

            Trenord.spinner.show();
        }
        ,

        /**
         * interrpome lo spinner ma non chiude il modale
         * questo perchè il modale è un flussio di fine, poi è l'azione dell'utente che chiude il modale
         * @param id
         */
        stopSpinner: function () {

            Trenord.spinner.hide();
        }


    }
    ,

    spinner: {

        show: function () {
            $(".custom-spinner").show();
        }
        ,

        hide: function () {
            $(".custom-spinner").hide();
        }

    }
    ,

    events: {

        register: function (name, params, callback) {

            $(document).on(name, params, callback);

        }
        ,

        trigger: function (name) {
            $(document).trigger(name);
        }
        ,

        remove: function (name, params, callback) {
            $(document).off(name, params, callback);
        }
        ,

        widgetOnBuild: function () {



            /* serve per gestire la lingua del widget */
            var config = {
                language: Trenord.globals.currentLanguage == 0 ? 'it' : 'en'
            };

            var event = new CustomEvent('updateconfig', {
                detail: config
            });

            document.dispatchEvent(event);



        }
    }
    ,

    carnet: {

        originId: "",
        originName: "",
        destinationId:
            "",
        destinationName:
            "",
        validateUrl:
            "/store/#/it/carnet/step1?",
        stibmOrigin: '',
        stibmDestination: '',
        startStationSearch:
            null,
        arriveStationSearch:
            null,


        goToBuy:

            function () {

                var params = {
                    mir_f: Trenord.carnet.originId,
                    departure: Trenord.carnet.originName,
                    mir_t: Trenord.carnet.destinationId,
                    destination: Trenord.carnet.destinationName,
                    stibmOrigin: Trenord.carnet.stibmOrigin,
                    stibmDestination: Trenord.carnet.stibmDestination
                };


                //prima facciamo la validazione
                var fields = ['startStation', 'arriveStation'];
                var valid = true;

                $(".container-generic-error").addClass('hidden');

                $(fields).each(function (index, value) {

                    if ($("#" + value).val() == "") {
                        $("#" + value).parent().parent().find(".container-generic-error.field").removeClass('hidden');
                        valid = false;
                    }
                });


                if (params.mir_f == "" && params.mir_t == "") {
                    $(".container-generic-error.field").removeClass('hidden');
                    valid = false;
                } else if (params.mir_f == "") {
                    $(".container-generic-error.field.origin").removeClass('hidden');
                    valid = false;
                } else if (params.mir_t == "") {
                    $(".container-generic-error.field.destination").removeClass('hidden');
                    valid = false;
                } else if (params.departure == params.destination) {
                    $(".container-generic-error.station").removeClass('hidden');
                    valid = false;
                }

                if (valid) {
                    var urlParam = decodeURIComponent($.param(params));
                    window.location.href = Trenord.carnet.validateUrl + urlParam;
                }

            }

        ,


        setOrigin: function (id, name, stibm) {
            Trenord.carnet.originId = id;
            Trenord.carnet.originName = name;
            Trenord.carnet.stibmOrigin = stibm;
        }
        ,

        setDestination: function (id, name, stibm) {
            Trenord.carnet.destinationId = id;
            Trenord.carnet.destinationName = name;
            Trenord.carnet.stibmDestination = stibm;
        }
        ,

        init: function () {

            Trenord.carnet.startStationSearch = new Trenord.ui.searchStation('#carnet-start-station', '.station-list-result', 'carnet-partenza');
            Trenord.carnet.startStationSearch.init();
            Trenord.carnet.startStationSearch.search("");

            Trenord.carnet.arriveStationSearch = new Trenord.ui.searchStation('#carnet-arrive-station', '.station-list-result', 'carnet-arrivo');
            Trenord.carnet.arriveStationSearch.init();
            Trenord.carnet.arriveStationSearch.search("");

        }

    }
    ,

    ancillary: {

        ids: [], //id relativi all'oggetto venduto
        qt:
            [], //id relativi
        price:
            0,
        total:
            0,
        validateUrl:
            "/store/#/it/ancillary?",
        canRegisterEvent:
            true,


        reset:

            function () {

                Trenord.ancillary.ids = [];
                Trenord.ancillary.qt = [];
            }

        ,


        goToBy: function () {

            if (Trenord.user.isLogged()) {

                var params = {
                    id: Trenord.ancillary.ids.join(','),
                    qt: Trenord.ancillary.qt.join(','),
                    backurl: window.location.toString()
                };

                var urlParam = decodeURIComponent($.param(params));
                window.location.href = Trenord.ancillary.validateUrl + urlParam;

            } else {


                if (Trenord.ancillary.canRegisterEvent) {
                    //per istanziarlo una volta sola

                    Trenord.events.register('userLogged', {}, function (event) {

                        Trenord.ancillary.canRegisterEvent = false;
                        //provo ad aspettare un attimo perchè lo stato di logged deve essere certo sul server
                        //altrimenti non avremo i dati da loggato
                        setTimeout(function () {
                            Trenord.ancillary.goToBy();
                        }, 100);

                    });
                }

                Trenord.ui.toggleWidgetOverlay();
                Trenord.ui.login.open();


            }
        }
        ,

        ticket: function (operation, id, price) {

            //convertion
            id = parseInt(id);
            price = parseFloat(price);

            switch (operation) {

                case "add":


                    Trenord.ancillary.total++;

                    if ($.inArray(id, Trenord.ancillary.ids) == -1) {
                        Trenord.ancillary.ids.push(id);
                        Trenord.ancillary.setQt(id, 1, Trenord.ancillary.price + price);


                    } else {
                        //aumento la quantità
                        Trenord.ancillary.setQt(id, Trenord.ancillary.getQt(id) + 1, Trenord.ancillary.price + price);
                    }


                    break;

                case "remove":

                    if (Trenord.ancillary.total > 0) {

                        if ($.inArray(id, Trenord.ancillary.ids) >= 0) {

                            var position = Trenord.ancillary.ids.indexOf(id);
                            var val = Trenord.ancillary.qt[position];

                            Trenord.ancillary.total--;

                            if (val == 1) {

                                Trenord.ancillary.setQt(id, 0, Trenord.ancillary.price - price);
                                Trenord.ancillary.ids.splice(position, 1);
                                Trenord.ancillary.qt.splice(position, 1);

                            } else {
                                Trenord.ancillary.setQt(id, Trenord.ancillary.getQt(id) - 1, Trenord.ancillary.price - price);

                            }
                        }
                    }

                    break;
            }

            //check add remove
            //reset
            $("#ancillary-shoulder .add-remove svg").removeClass('active');

            if (Trenord.ancillary.total == 0) {

                $("#ancillary-shoulder .add-remove .add ").addClass('active');
                $("#ancillary-shoulder .add-remove .remove ").removeClass('active');

                $("#anicllary-buy").prop('disabled', true);
                $("#anicllary-buy").addClass('disable');


            } else {
                $("#ancillary-shoulder .add-remove .add ").addClass('active');
                $("#ancillary-shoulder .add-remove .remove ").addClass('active');

                $("#anicllary-buy").prop('disabled', false);
                $("#anicllary-buy").removeClass('disable');

            }

            //correggo il singolo elemento in casi specifici
            $(".row-ticket").each(function (index, value) {

                var val = parseInt($(value).find('.ticket-value').html());

                if (val == 0) {
                    $(value).find('.remove').removeClass('active');
                }
            });

        }
        ,

        getQt: function (id) {

            return Trenord.ancillary.qt[Trenord.ancillary.ids.indexOf(id)];
        }
        ,


        setQt: function (id, qt, price) {

            Trenord.ancillary.qt[Trenord.ancillary.ids.indexOf(id)] = qt;
            Trenord.ancillary.price = price;

            $("#ancillary-shoulder .number.ancillary-" + id).html(qt);

            $("#ancillary-price").html(price.toFixed(2));

        }
        ,
    }
    ,

    discovery: {
        parentTariffId: null, // ID tariffa padre
        childrenTariffIds: [], // ID tariffe figlie vendute
        qt: [], // Qta relative alle tariffe figlie
        types: [],
        sp: null,
        sa: null,
        dp: null,
        ar: null,
        dr: null,

        filters:
        {
            periods: "default",
            categories:
                "default",
            places:
                "default",
            groups:
                "default",
            subGroups:
                "default",
        }
        ,
        subGroupFilters: [],
        filterKeys:
            [
                "periods",
                "categories",
                "places",
                "groups",
                "subGroups"
            ],

        total:
            0,
        price:
            0,
        validateUrl:
            "/store/#/it/trips?",
        dateRange:
            [],

        canRegisterEvent:
            true,

        initFilters:

            function () {

                $(document).ready(function () {
                    //Trenord.discovery.updateCatalog();

                    Trenord.discovery.initFilterColumns();
                    Trenord.discovery.initFilterEvents();
                })

            }

        ,

        initFilterEvents: function () {

            $(".button-content ul li a").unbind();
            $(".button-content ul li a").click(function () {

                var el = this;
                var filterType = $(el).data('filter-type');
                var newFilter = $(el).data('filter-value');
                var currentFilter = Trenord.discovery.filters[filterType];

                Trenord.ui.ideeDiViaggio.onClickFilterValues(el);

                if (currentFilter != newFilter) {
                    Trenord.discovery.filters[filterType] = newFilter;
                    Trenord.discovery.updateCatalog();
                    Trenord.discovery.updateFilters();
                }


                let defN = 0;
                $(Trenord.discovery.filterKeys).each(function (index, key) {
                    let filValye = Trenord.discovery.filters[key];
                    if (filValye == "default")
                        defN++;
                });

                if (defN == 5) {
                    $(".catalog-button").show();
                    Trenord.ui.ideeDiViaggio.page = 0;
                    Trenord.ui.ideeDiViaggio.nextPage();
                } else {
                    $(".catalog-button").hide();
                }

            });

        }
        ,

        updateFilters: function () {

            $(".discovery-filters li").addClass("hidden");
            $(".discovery-filters li .count").html("(0)");

            $(Trenord.discovery.filteredCards).each(function (index, card) {

                var keys = Trenord.discovery.filterKeys;

                $(keys).each(function (index, key) {


                    var filterName = "filter-" + key;
                    var filterCheck = "" + eval("Trenord.discovery.filters." + key);
                    var filterData = "" + $(card).data(filterName);
                    var filterValues = filterData.split(",");

                    var filterList = "#discovery-" + key;
                    var filterItems = filterList + " li";

                    $(filterItems).each(function (index, filter) {

                        var filterEl = $(filter).find("a");
                        var filterValue = "" + $(filterEl).data("filter-value");

                        var filterCount = $(filterEl).find(".count")
                        var filterCountValue = filterCount.text().replace("(", "").replace(")", "");
                        filterCountValue = parseInt(filterCountValue);

                        if ($.inArray(filterValue, filterValues) >= 0 && filterValue != filterCheck) {
                            $(filter).removeClass('hidden');
                            filterCountValue++;
                        } else if (filterValue == "default" && filterValue != filterCheck) {
                            $(filter).removeClass('hidden');
                            filterCountValue++;
                        }

                        $(filterCount).html("(" + filterCountValue + ")");
                    });

                });

            });
        }
        ,

        updateCatalog: function () {

            Trenord.discovery.filteredCards = [];

            $(".discovery-card").removeClass('hidden');

            //logiche per la gestione dei filtri
            $(".discovery-card").each(function (index, card) {

                var keys = Trenord.discovery.filterKeys;
                var visible = true;

                $(keys).each(function (index, key) {

                    var filterName = "filter-" + key;
                    var filterCheck = "" + eval("Trenord.discovery.filters." + key);
                    var filterData = "" + $(card).data(filterName);
                    var filterValues = filterData.split(",");

                    if (filterCheck == "default") {
                        visible = visible && true;
                    } else if ($.inArray(filterCheck, filterValues) >= 0) {
                        visible = visible && true;
                    } else {
                        visible = false;
                    }


                });

                if (visible) {
                    Trenord.discovery.filteredCards.push(card);
                    $(card).removeClass('hidden');
                } else {
                    $(card).addClass('hidden');
                }

            });

        }
        ,

        initFilterColumns: function () {

            $(".button-content").each(function (index, value) {

                var elCount = $(value).find("ul li").length;

                if (elCount <= 5) {
                    $(value).addClass('single-column');
                } else {
                    $(value).removeClass('single-column');
                }

            });
        }
        ,

        buy: function () { // Acquisto modalità singola CTA

            // add google Analytics event
            dataLayer.push({
                event: 'select_promotion',
                promotion_name: `promo ${document.title}`,
                creative_name: 'HP-cta_main_banner'
            });
            
            if (Trenord.globals.calendar.dateRange.length == 0) {
                Trenord.popUpMessage.open("error", "Offerta non vendibile", "Siamo spiacenti, al momento l'offerta non può essere acquistata.");
            } else {
                Trenord.popUpMessage.hideModalBoxForm();
                Trenord.popUpMessage.startSpinner();
                Trenord.popUpMessage.showModalBox();

                $.get('/rest/cta/tariff', { tariff_id: Trenord.discovery.parentTariffId }, function (parentTariff) {

                    Trenord.popUpMessage.stopSpinner();
                    Trenord.popUpMessage.hideModalBox();

                    if (parentTariff.units === 0) {
                        Trenord.popUpMessage.open("error", "Biglietti esauriti", "Siamo spiacenti, ma i biglietti per questo evento sono esauriti.");
                    } else {
                        $("#passengerList").val(Trenord.discovery.passengerListString());
                        Trenord.ui.toggleWidgetOverlay();
                    }
                });
            }
        }
        ,

        asyncBuy: function (childTariffId) { // Acquisto modalità multipla CTA

            Trenord.popUpMessage.hideModalBoxForm();
            Trenord.popUpMessage.startSpinner();
            Trenord.popUpMessage.showModalBox();

            $.get('/rest/cta/tariff', { tariff_id: childTariffId }, function (childTariff) {
                if (childTariff.units === 0) {
                    Trenord.popUpMessage.stopSpinner();
                    Trenord.popUpMessage.hideModalBox();
                    Trenord.popUpMessage.open("error", "Biglietti esauriti", "Siamo spiacenti, ma i biglietti per questo evento sono esauriti.");
                    return;
                }

                $.get('/rest/render/passengerShoulder', {
                    id: childTariffId
                }, function (data) {

                    Trenord.popUpMessage.stopSpinner();
                    Trenord.popUpMessage.hideModalBox();

                    $('#asyncPassenger').html(data.message);
                    Trenord.ui.toggleWidgetOverlay();
                });
            })
        }
        ,

        reset: function () {
            Trenord.discovery.parentTariffId = null;
            Trenord.discovery.childrenTariffIds = [];
            Trenord.discovery.qt = [];
            Trenord.discovery.types = [];
            Trenord.discovery.total = 0;
            Trenord.discovery.price = 0;
        }
        ,

        goToBy: function () {

            var params = {
                id: Trenord.discovery.childrenTariffIds.join(','),
                qt: Trenord.discovery.qt.join(','),
                sp: Trenord.discovery.sp,
                sa: Trenord.discovery.sa,
                dp: Trenord.discovery.dp,
                ar: Trenord.discovery.ar,
                dr: Trenord.discovery.dr
            };

            var urlParam = decodeURIComponent($.param(params));
            window.location.href = Trenord.discovery.validateUrl + urlParam;
        }
        ,

        validate: function () {

            //prima facciamo la validazione
            var fields = ['startStation', 'arriveStation'];
            var valid = true;

            $(".container-generic-error").addClass('hidden');

            $(fields).each(function (index, value) {

                if (valid && $("#" + value).val() == "") {
                    $(".container-generic-error." + value).removeClass('hidden');
                    valid = false;
                }
            });

            if (valid) {

                if (Trenord.user.isLogged()) {

                    Trenord.discovery.goToBy();

                } else {


                    if (Trenord.discovery.canRegisterEvent) {
                        //per istanziarlo una volta sola

                        Trenord.events.register('userLogged', {}, function (event) {

                            Trenord.discovery.canRegisterEvent = false;
                            //provo ad aspettare un attimo perchè lo stato di logged deve essere certo sul server
                            //altrimenti non avremo i dati da loggato
                            setTimeout(function () {
                                Trenord.discovery.goToBy();
                            }, 100);

                        });
                    }

                    Trenord.ui.toggleWidgetOverlay();
                    Trenord.ui.login.open();


                }
            }
        }
        ,

        ticketOnReady: function (parentTariffId, childTariffId, type, price) {
            $(document).ready(function () {
                Trenord.discovery.parentTariffId = parseInt(parentTariffId, 10);
                Trenord.discovery.ticket('add', childTariffId, type, price);
            })
        }
        ,

        ticket: function (operation, childTariffId, type, price) {

            //convertion
            childTariffId = parseInt(childTariffId, 10);
            price = parseFloat(price);
            //99 for security reason, but should equal to unlimited functionally
            totalLimit = 99

            switch (operation) {

                case "add":

                    if (Trenord.discovery.total < totalLimit) {

                        Trenord.discovery.total++;

                        if ($.inArray(childTariffId, Trenord.discovery.childrenTariffIds) == -1) {
                            Trenord.discovery.childrenTariffIds.push(childTariffId);
                            Trenord.discovery.types.push(type);
                            Trenord.discovery.setQt(childTariffId, 1, type, Trenord.discovery.price + price);
                        } else {
                            //aumento la quantità
                            Trenord.discovery.setQt(childTariffId, Trenord.discovery.getQt(childTariffId) + 1, type, Trenord.discovery.price + price);
                        }

                    }

                    break;

                case "remove":

                    if (Trenord.discovery.total > 1) {

                        if ($.inArray(childTariffId, Trenord.discovery.childrenTariffIds) >= 0) {

                            var position = Trenord.discovery.childrenTariffIds.indexOf(childTariffId);
                            var val = Trenord.discovery.qt[position];

                            Trenord.discovery.total--;

                            if (val == 1) {
                                Trenord.discovery.setQt(childTariffId, 0, type, Trenord.discovery.price - price);
                                Trenord.discovery.childrenTariffIds.splice(position, 1);
                                Trenord.discovery.qt.splice(position, 1);
                                Trenord.discovery.types.splice(position, 1);

                            } else {
                                Trenord.discovery.setQt(childTariffId, Trenord.discovery.getQt(childTariffId) - 1, type, Trenord.discovery.price - price);
                            }
                        }
                    }

                    break;
            }

            //check add remove
            //reset
            $(".control-ticket svg").removeClass('active');

            if (Trenord.discovery.total >= totalLimit) {
                $(".control-ticket .add ").removeClass('active');
                $(".control-ticket .remove ").addClass('active');
            } else if (Trenord.discovery.total <= 1) {
                $(".control-ticket .add ").addClass('active');
                $(".control-ticket .remove ").removeClass('active');
            } else {
                $(".control-ticket .add ").addClass('active');
                $(".control-ticket .remove ").addClass('active');
            }

            //correggo il singolo elemento in casi specifici
            $(".row-ticket").each(function (index, value) {

                var val = parseInt($(value).find('.ticket-value').html());

                if (val == 0) {
                    $(value).find('.remove').removeClass('active');
                }
            });

        }
        ,

        getQt: function (id) {
            return Trenord.discovery.qt[Trenord.discovery.childrenTariffIds.indexOf(id)];
        }
        ,

        getType: function (id) {
            return Trenord.discovery.types[Trenord.discovery.childrenTariffIds.indexOf(id)];
        }
        ,

        setQt: function (id, qt, type, price) {

            Trenord.discovery.qt[Trenord.discovery.childrenTariffIds.indexOf(id)] = qt;
            Trenord.discovery.price = price;

            $(".ticket-number-" + type + " .ticket-value").html(qt);

            $("#discovery-price").html((Math.round(price * 100) / 100).toFixed(2));
            $("#passengerList").val(Trenord.discovery.passengerListString());
        }
        ,

        setDestination: function (id) {

            var ids = id.split(",");
            var destination = [];

            $(ids).each(function (index, value) {
                if (value != "") {
                    destination.push(value);
                }
            });

            Trenord.discovery.sa = destination.join(",");
        }
        ,

        //il parametro name deve esserci anche se non usato qui
        setOrigin: function (id, name) {

            Trenord.discovery.sp = id;
        }
        ,

        setStartDate: function (date) {

            if (date == "")
                return date;

            date = date.split('/');

            Trenord.discovery.dp = ([date[2], date[1], date[0]]).join("-");
        }
        ,

        passengerListString: function () {

            var passengerList = [];


            $(Trenord.discovery.childrenTariffIds).each(function (index, value) {

                var type = Trenord.discovery.getType(value);
                var qt = Trenord.discovery.getQt(value);

                if (qt > 0) {

                    if (qt > 1) {
                        switch (type) {
                            case "adulto":
                                type = "adulti";
                                break;
                            case "ragazzo":
                                type = "ragazzi"
                                break;
                        }
                    }

                    passengerList.push(qt + " " + type);
                }
            });

            return passengerList.join(", ");
        }
        ,

        rebuy: function () {

            var params = Trenord.utility.locationSearchToObject();

            if (params.rebuy) {
                Trenord.ui.toggleWidgetOverlay();
            }

        }
        ,

        toggleSubfilter: function (filterName) {

            $(".discovery-card").hide()

            var subFilterPos = Trenord.discovery.subGroupFilters.indexOf(filterName);

            if (subFilterPos >= 0)
                Trenord.discovery.subGroupFilters.splice(subFilterPos, 1);
            else {
                Trenord.discovery.subGroupFilters.push(filterName);
            }

            $(Trenord.discovery.subGroupFilters).each(function (index, filter) {
                $('.discovery-subgroups-filter-' + filter).show();
            });

            if (Trenord.discovery.subGroupFilters.length == 0) {
                $(".discovery-card").show();
            }


        }
        ,

        resetFilters: function () {
            Trenord.discovery.subGroupFilters = [];
            $(".discovery-card").show();
        }
        ,

        loadFavourites: function () {

            $.get('/rest/cta/favourites', { type: 'discovery' }, function (response) {
                $(response).each(function (key, value) {
                    Trenord.ui.bookmarks.setStarStatus(value, true);
                });

            });
        },

        linkToStation: function () {

            var lts = $(".link-to-station");

            if (lts.length > 0) {

                if (lts.length > 1)
                    lts = lts[0];

                $([document.documentElement, document.body]).animate({
                    scrollTop: $(lts).offset().top - 200
                }, 500);

            } else {

                $(".container-title").each(function (index, value) {

                    var containerText = $(value).text().toLowerCase().trim();

                    if (containerText == "come arrivare" || containerText == "how to get") {

                        $([document.documentElement, document.body]).animate({
                            scrollTop: $(value).offset().top - 200
                        }, 500);

                        return;
                    }
                })
            }

        }
    }
    ,


    console: {

        log: function (message) {

            if (Trenord.globals.debug) {
                console.log(message);
            }
        }
    }
}
/*  trenord */

var selected = "";
(function () {
    if (typeof window.CustomEvent === "function") return false; //If not IE

    function CustomEvent(event, params) {
        params = params || {
            bubbles: false,
            cancelable: false,
            detail: undefined
        };
        var evt = document.createEvent('CustomEvent');
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
        return evt;
    }

    CustomEvent.prototype = window.Event.prototype;

    window.CustomEvent = CustomEvent;
})();

//bug caricamento bootstrap-select, troppo lento issue 154
$("#news-type-search").selectpicker('render');


equalheight = function(container){

    var currentTallest = 0,
        currentRowStart = 0,
        rowDivs = new Array(),
        $el,
        topPosition = 0;
    $(container).each(function() {

        $el = $(this);
        $($el).height('auto')
        topPostion = $el.position().top;

        if (currentRowStart != topPostion) {
            for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
                rowDivs[currentDiv].height(currentTallest);
            }
            rowDivs.length = 0; // empty the array
            currentRowStart = topPostion;
            currentTallest = $el.height();
            rowDivs.push($el);
        } else {
            rowDivs.push($el);
            currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
        }
        for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
            rowDivs[currentDiv].height(currentTallest);
        }
    });
}



;(function ($, window, document) {

    var $this;
    var content = {};

    var to;
    var settings = {
        // Defaults
        storyElem: '.chapter',
        barsContainer: 'barsContainer',
        barClass: 'toc-storybar',
        headlineSelector: '.title-capitolo',
        topText: 'Back to top'
    }

    $.fn.tocProgress = function (options) {

        //reference to the element that called the plugin
        $this = $(this);

        settings = $.extend(settings, options);


        // First hide the table of contents
        $this.hide();

        $(window).resize(function (event) {
            // Wait 500ms after resizing window to reset things
            if (to != null) {
                clearTimeout(to);
            }
            to = window.setTimeout(function () {
                delete content;
                content = thestories();
                makeBarsClickable();
            }, 500);

        });

        $(window).on('load', function () {


            $this.prepend('<div class="toc-title">' + $('h1').first().text() + '</div>');
            $this.append('<div id="' + settings.barsContainer + '"></div>');

            setupHTML(settings.storyElem);
            initProgressBars(
                settings.barsContainer,
                settings.barClass,
                settings.headlineSelector,
                settings.topText
            );
            content = thestories();
            makeBarsClickable();

            var rtime;
            var timeout = false;
            var delta = 200;
            $(window).scroll(function () {
                rtime = new Date();
                if (timeout === false) {
                    timeout = true;
                    setTimeout(resizeend, delta);
                }
                calcProgress();
            });

            function resizeend() {
                if (new Date() - rtime < delta) {
                    setTimeout(resizeend, delta);

                } else {
                    timeout = false;
                    calcProgress();
                }
            }

            $this.fadeIn(1000);
            return this;

        });
    }

    /* Helpers */
    function Story() {
    }

    function numStories() {
        var i = 0;
        $('[data-index]').each(function () {
            i++;
        });
        return i;
    }

    var getHeadline = function (i, elem) {
        return $('[data-index=' + i + '] ' + elem + '').first().text();
    }

    var setupHTML = function (storyElem) {
        //
        $(storyElem).each(function (index, el) {
            $(this).attr({'data-index': index});
        });

    }

    var initProgressBars = function (barsContainer, barClass, headlineSelector, topText) {

        var output = "";
        for (var i = 0; i < numStories(); i++) {
            output += '<div class="' + barClass + '";" data-story="' + i + '">';
            output += '<p>' + getHeadline(i, headlineSelector) + '</p>';
            output += '<div class="toc-bar"></div>';
            output += '</div>';
        }
        ;

        $('#' + barsContainer).append(output);
        $('.' + barClass).css('cursor', 'pointer');

        addTopLink(topText); //


        if (window.location.hash) {

            var hash = window.location.hash.split("c");
            if (hash) {

                var num = parseInt(hash[1]) - 1;

                if ($(".container-capitoli").length > 0) {
                    $('html, body').animate({
                        scrollTop: $(".container-capitoli:eq(" + num + ")").offset().top
                    }, 2000);
                }

            }
        }

    }

    function addTopLink(wording) {

        $this.append('<div class="toc-top">' + wording + '</div>');
        $('.toc-top').css('cursor', 'pointer');
        $('.toc-top').click(function (event) {
            $('body,html').animate({'scrollTop': 0});
        });
    }

    function makeBarsClickable() {

        $("[data-story]").each(function (index, el) {
            var scrollTopValue = content[index].top + 2;
            $(this).off('click'); // Remove any click events before assigning another
            $(this).unbind('click');
            $(this).click(function () {
                $('body,html').animate({'scrollTop': scrollTopValue});
            });
        });

    }

    function getNavContainerHeight(offsetElem) {
        return $(offsetElem).height();
    }

    function thestories() {

        var navHeight = getNavContainerHeight(settings.offsetElem);
        var numberStories = numStories();

        $('[data-index]').each(function (index, el) {

            content[index] = new Story();
            content[index].index = index;
            content[index].height = $(this).height() - (navHeight !== undefined ? navHeight : 0);
            content[index].top = $(this).offset().top - (navHeight !== undefined ? navHeight : 0);
            content[index].bottom = $(this).position().top + $(this).outerHeight(true) - (navHeight !== undefined ? navHeight : 0);

        });

        return content;

    }

    function calcProgress() {
        var scrollTop = $(window).scrollTop();
        var temp;
        var width;

        if (content != null) {
            $.each(content, function (index, story) {
                temp = scrollTop - story.top;
                width = temp / story.height * 100;
                setBarWidth(story.index, width);
            });

        }
    }

    function setBarWidth(index, width, color) {

        var elem = $("[data-story=" + index + "]");
        var bar = $("[data-story=" + index + "] .toc-bar");
        // user has scrolled passed
        if (width > 100) {
            elem.css('font-weight', 'normal');
            bar.css({
                width: "100%",
                background: color
            });
            // user is before the story
        } else if (width < 0) {
            elem.css('font-weight', 'normal');
            bar.css({
                width: "0%",
            });
            // user is on the story
        } else {
            elem.css({'font-weight': 'bold'});
            bar.css({
                height: width + "%",
                background: color
            });
        }


        console.log($(".toc-storybar:last-child .toc-bar").height(), ($(".toc-storybar:last-child .toc-bar").height() > 43.000))


        if ($(".toc-storybar:last-child .toc-bar").height() > 42.400) {

            $("#progress").css("visibility", "hidden");
        } else {
            $("#progress").css("visibility", "visible");
        }


    }


})(jQuery, window, document);

$(window).on('beforeunload', function () {
    if ($(".container-capitoli").length > 0) {
        $(window).scrollTop(0);
    }
});

//lazyload
const observer = lozad('.lozad', {
    rootMargin: '10px 0px', // syntax similar to that of CSS Margin
    threshold: 0.1, // ratio of element convergence
    enableAutoReload: true // it will reload the new image when validating attributes changes
});
observer.observe();

$(document).ready(function () {

    $(".container-grid .grid .item").each(function(){
        var blank = $(this).prev().attr("target") ? true : false;
        if(blank){   $(this).find("a").attr("target","blank");   }
    });

    const privacyModal = document.getElementById('privacy-modal')
    if (privacyModal) {
        privacyModal.dispatchEvent(new Event('navigationEnd'))
    }

if(Trenord.utility.isMobile()){

}else{
    equalheight('.card-app-linee');
    equalheight('.approfondimenti-linea .card-app-linee .title');
}


    $(".boxPromo span.close-promo").click(function(){
        $(".boxPromo").toggleClass("active");

        if( $(".boxPromo").hasClass("active")){
            $(".boxPromo span.close-promo svg").show();
            $(".boxPromo span.close-promo img").hide();
        }else{
            $(".boxPromo span.close-promo svg").hide();
            $(".boxPromo span.close-promo img").show();
        }
    });

    if(Trenord.utility.isMobile()){
        $('input').on('click', function(){

                $(window).off('resize');


        });

        $('.tn-tabnav__item').on('click', function () {

            $('input').on('click', function(){

                $(window).off('resize');


            });

        });

    }



    $('#progress').tocProgress({
        storyElem: '.chapter',
        headlineSelector: '.title-capitolo'
    });


//sticky capitoli

    if (!Trenord.utility.isMobile()) {
        $(".container-capitoli .col-sm-6:nth-child(2)").stick_in_parent({
            spacer: false
        });
    }


    ////////////////da inserire campus js///
    $(".campus-carousel").owlCarousel({
        navigation: true,
        slideSpeed: 300,
        paginationSpeed: 400,
        singleItem: true,
        pagination: false,
        items: 1,
        nav: false,
        dots: false,
        rewindSpeed: 500
    });

    var campus_carousel = $(".campus-carousel");

    campus_carousel.owlCarousel();
    //Custom Navigation Events
    $(".arrow-campus.right ").click(function () {

        campus_carousel.trigger("next.owl.carousel");

        $(".arrow-campus.left ").removeClass("hidden");

        if ($('.campus-carousel.owl-carousel .owl-item').last().hasClass('active')) {
            $(".arrow-campus.right ").addClass("hidden");
        }
        $(".campus-carousel .owl-item").each(function (index) {

            if ($(this).hasClass("active")) {

                $(".line-container .status .dot").removeClass("current");
                $('.line-container .status .dot[data-dots=' + index + ']').addClass("current");
            }
        });

    });
    $(".arrow-campus.left ").click(function () {
        var owl = campus_carousel.data('owlCarousel');
        campus_carousel.trigger("prev.owl.carousel");
        $(".arrow-campus.right ").removeClass("hidden");

        if ($('.campus-carousel.owl-carousel .owl-item:first-child').hasClass('active')) {
            $(".arrow-campus.left ").addClass("hidden");
        }

        $(".campus-carousel .owl-item").each(function (index) {
            if ($(this).hasClass("active")) {

                $(".line-container .status .dot").removeClass("current");
                $('.line-container .status .dot[data-dots=' + index + ']').addClass("current");
            }
        });

    });

    $(".status  .dot").click(function () {
        var id = $(this).data("dots");
        campus_carousel.trigger('to.owl.carousel', [id, 300]);
        $(".status .dot.current").removeClass("current");
        $(this).addClass("current");

        if ($('.campus-carousel.owl-carousel .owl-item:first-child').hasClass('active')) {
            $(".arrow-campus.left ").addClass("hidden");
            $(".arrow-campus.right ").removeClass("hidden");
        }

        if ($('.campus-carousel.owl-carousel .owl-item').last().hasClass('active')) {
            $(".arrow-campus.right ").addClass("hidden");
            $(".arrow-campus.left ").removeClass("hidden");
        }
    });


    //campus quiz

    //
    var counterQuiz = 0;

    //cambio domanda
    function changeAnswer() {
        $(".quiz .nav-tabs li.active").next().find("a").trigger("click");
        var idCurrent = $(".container-quiz.active").attr("id").split("tab-quiz");
        var currentFiltered = parseInt(idCurrent[1]) + 2;
        var totalQuiz = $(".container-quiz").length;
        $(".quiz .counter-quiz").html("" + currentFiltered + " di " + totalQuiz + "");

    }

    function percentage(partialValue, totalValue) {
        return (100 * partialValue) / totalValue;
    }

    //riposta utente
    $(".container-quiz .container-answers .answers").click(function () {
        if ($(this).data("answers") == "correct") {
            $(this).addClass("correct");
            counterQuiz++;
            $(this).parent().find(".answers").css("pointer-events", "none");
            var idCurrent = $(".container-quiz.active").attr("id").split("tab-quiz");

            var currentFiltered = parseInt(idCurrent[1]) + 2;

            var totalQuiz = $(".container-quiz").length;


            $(".box-answers.correct-answer").removeClass("hidden");
            setTimeout(function () {
                $(".box-answers.correct-answer").addClass("hidden");
                var totalQuiz = $(".container-quiz").length;
                if (currentFiltered <= totalQuiz) {
                    changeAnswer()
                } else {
                    var totalQuiz = $(".container-quiz").length;
                    $(".container-quiz.active").removeClass("active").removeClass("in");
                    $("#tab-quiz-final").addClass("active").addClass("in");
                    $("#tab-quiz-final .box-final-quiz .counter-final-quiz").html("<span class='big'>" + counterQuiz + "</span> / " + totalQuiz + "");

                    if (percentage(counterQuiz, totalQuiz) < 33) {
                        $(".level-quiz").html("Beginner")
                    }
                    if (percentage(counterQuiz, totalQuiz) > 33 && percentage(counterQuiz, totalQuiz) < 66) {
                        $(".level-quiz").html("Medium");
                    }
                    if (percentage(counterQuiz, totalQuiz) > 66) {
                        $(".level-quiz").html("Top");
                    }
                    $(".quiz .nav-tabs, .counter-quiz").addClass("hidden");
                }
            }, 5000);

        } else {
            $(this).addClass("incorrect");
            $(this).parent().find(".answers").css("pointer-events", "none");
            var idCurrent = $(".container-quiz.active").attr("id").split("tab-quiz");

            var currentFiltered = parseInt(idCurrent[1]) + 2;

            var totalQuiz = $(".container-quiz").length;

            $(".box-answers.incorrect-answer").removeClass("hidden");
            setTimeout(function () {
                $(".box-answers.incorrect-answer").addClass("hidden");
                var totalQuiz = $(".container-quiz").length;
                if (currentFiltered <= totalQuiz) {
                    changeAnswer()
                } else {
                    var totalQuiz = $(".container-quiz").length;
                    $(".container-quiz.active").removeClass("active").removeClass("in");
                    $("#tab-quiz-final").addClass("active").addClass("in");
                    $("#tab-quiz-final .box-final-quiz .counter-final-quiz").html("<span class='big'>" + counterQuiz + "</span> / " + totalQuiz + "");

                    if (percentage(counterQuiz, totalQuiz) <= 33) {
                        $(".level-quiz").html("Beginner")
                    }
                    if (percentage(counterQuiz, totalQuiz) > 33 && percentage(counterQuiz, totalQuiz) <= 66) {
                        $(".level-quiz").html("Medium");
                    }
                    if (percentage(counterQuiz, totalQuiz) > 66 && percentage(counterQuiz, totalQuiz) <= 99) {
                        $(".level-quiz").html("Top");
                    }
                    if (percentage(counterQuiz, totalQuiz) == 100) {
                        $(".level-quiz").html("Pro");
                    }
                    $(".quiz .nav-tabs, .counter-quiz").addClass("hidden");
                }
            }, 4000);

        }
    });

    //copertura temporanea cdn
/*
    if($(".news-carousel .item .image-container img").length > 0){
        $(".news-carousel .item .image-container img").each(function(){
            var splitted =   $(this).attr("src").split(".it");

            if(splitted){
                $(this).attr("src",splitted[1] );
            }

        });
    }

    $('.news-carousel .item .image-container.image').each(function(){
        var bg_img = $(this).css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1');
        var filter = bg_img.split("https://trenord-europe-trenord-endpoint-prd.azureedge.net/www.trenord.it")
        if(filter){
            $(this).css('background-image', 'url(' + filter[1] + ')');
        }

    });


    $(".container-lingua a img").each(function(){
        var splitted = $(this).attr("src").split("//trenord-europe-trenord-endpoint-prd.azureedge.net/");
        if(splitted){
            $(this).attr("src",$(this).attr("src").split("//trenord-europe-trenord-endpoint-prd.azureedge.net/")[1]);

        }
    });
    */

    //da inserire per faq slide
    //Scroll movement
    var tabWidth;

//Calculate width of element list
    function maxWidth(elem) {
        var $elem = $(elem);
        var allWidth = 0;
        $elem.children().each(function () {
            allWidth += $(this)[0].getBoundingClientRect().width
        });
        // $elem.css('width', allWidth);
    }

//Display timeline nav if necessary
    function getNav(elem) {
        var $elem = $(elem);
        if ($elem.siblings().width() <= $elem.parent().width()) {
            $elem.addClass('hide');
        } else {
            $elem.removeClass('hide');
            ;
        }
    }

    function scrollPos() {

        var maxScrollLeft = $(".timeline-tab")[0].scrollWidth - $(".timeline-tab")[0].clientWidth;
        var scrollPos = $(".timeline-tab").scrollLeft();


        scrollPos === 0 ? $(".timeline-nav-prev").addClass("hidden") : $(".timeline-nav-prev").removeClass("hidden");
        scrollPos === maxScrollLeft ? $(".timeline-nav-next").addClass("hidden") : $(".timeline-nav-next").removeClass("hidden");
    }


    $(window).on("load resize", function () {


        if(Trenord.utility.isMobile()){

        }else{
            equalheight('.card-app-linee');
            equalheight('.approfondimenti-linea .card-app-linee .title');
        }


        setTimeout(function () {
            getNav(".timeline-nav");
            tabWidth = $(".timeline-tab").width() - $(".timeline-item").width();
            // scrollPos();
        }, 600);
        maxWidth(".timeline-list");
        $(".timeline-tab").perfectScrollbar();
    });


    $(".timeline-tab").scroll(function () {
        scrollPos();
    });

    $(".timeline-nav-next").click(function () {
        $(".timeline-tab").stop(true, false).animate({
            scrollLeft: '+=' + $(".timeline-item").width()
        }, 300);
        return false;
    });
    $(".timeline-nav-prev").click(function () {
        $(".timeline-tab").stop(true, false).animate({
            scrollLeft: '-=' + $(".timeline-item").width()
        }, 300);
        return false;
    });

    //blocca resize sull'input
    if(Trenord.utility.isMobile()) {
        $('input').on('click', function(){

                $(window).off('resize');


        });

        $('.tn-tabnav__item').on('click', function () {

                $(window).off('resize');

        });
    }

//buca di ricerca

    if ($("#searchNews").length > 0) {
        setTimeout(function () {
            $("#searchNews").removeClass("hidden");
        }, 600)

    }


//rimzione title
    if ($(".container-image-sticky").length > 0) {
        setTimeout(function () {
            $(".container-image-sticky").attr("title", "");
        }, 500)
    }

    //prolema immagini typo3 mette un link errato solo in alcuni casi
    $(".container-news .image-container").each(function () {
        if ($(this).parent().hasClass("link-news")) {
            $(this).parent().parent().wrap("<a class='link-news' href='" + $(this).parent().attr('href') + "'></a>")
            $(this).parent().contents().unwrap();

        }
    });


    $(".mobile-header-filter  img").click(function () {
        $(".map-research__wrapper .filtering__cta a").trigger("click");
    });

    //spostamento bonus regionale se mobile(perchè la parte sticky viene nascosta)
    if (Trenord.utility.isMobile() || Trenord.utility.isTablet() && $(".position-bonus").length) {
        setTimeout(function () {
            $(".container-box-sticky").insertAfter($(" .position-bonus"));
        }, 500);

    } else {
        $("#sticky-div").prepend($(".container-box-sticky"));
    }


    $("#news-type-search").selectpicker('render');
    //problema gestione spazio senza visore(foglia news)
    if ($(".container-foglia-news") && $(".visore-immagine-titolo").length == 0) {
        $(".container-foglia-news").css("margin-top", "100px");
    }

    //form fatture  fine

    $(".accordion-toggle").click(function () {

        if ($(this).next().hasClass("active-arrow-faq")) {
            $(".accordion-heading svg").removeClass("active-arrow-faq");

        } else {
            $(".accordion-heading svg").not(this).removeClass("active-arrow-faq");
            $(this).next().toggleClass("active-arrow-faq");
        }

    });
    Trenord.fatture.init();

    Trenord.ivif.init();

    if ($("body").hasClass("malpensaStyle")) {
        if (getCookie('Contrasto') === "on") {
            $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px #a00000fa');
            $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
            $(".quadrilater").css('border-bottom-style', 'solid');
            $(".quadrilater").css('border-bottom-color', 'rgba(208, 2, 27, 0.8)');
        } else {
            $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px #d0021bd9');
            $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
            $(".quadrilater").css('border-bottom-style', 'solid');
            $(".quadrilater").css('border-bottom-color', 'rgba(208,2,27,0.8)');

        }

    } else {
        $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px #0c683fd1');
        $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
        $(".quadrilater").css('border-bottom-style', 'solid');
        $(".quadrilater").css('border-bottom-color', 'rgba(0, 114, 63,0.8)');
    }

    //diablito l'autocomplete ovunque
    // var fakedata = ['T','R ','E'];

    // $('input').autocomplete({source:fakedata}).focus(function () {
    //     $(this).attr('autocomplete', 'off');
    // });

    $('input').attr('autocomplete', 'off');


    if ($(" .container-social").length) {
        $(".container-sticky .container-social").stick_in_parent({
            offset_top: 10,
        });
        $("#sticky-div").addClass("hidden");
    }

    if (Trenord.utility.isMobile() || Trenord.utility.isTablet()) {

        $('.idee-di-viaggio-dx input').focus(function () {
            $('.idee-di-viaggio-dx').animate({
                scrollTop: ($(this).offset().top - 10)
            }, 1);
            return false;
        });
    }


    $(".close-ticket").click(function () {


        $(".ticket-passenger-container").removeClass("active");
    });

    $(".passenger-switch").click(function () {
        $(".close-ticket").trigger("click");
        if (!$(".ticket-passenger-container").hasClass("active")) {
            $(".ticket-passenger-container").addClass("active");
        }
    });

    $('[data-toggle="tooltip-passenger"]').tooltip();

    if (!Trenord.utility.isMobile() || !Trenord.utility.isTablet() && $(".position-bonus").length) {

        $("#sticky-div").prepend($(".container-box-sticky"));
    }


    if ($('#data-dx-viaggio').length) {

        $('#data-dx-viaggio').datepicker({
            language: 'IT',
            format: 'dd/mm/yyyy',
            weekStart: 1,
            orientation: 'auto bottom',
            maxViewMode: "years",
            beforeShowDay: function (date) {
                return true;
            }

        }).on('changeDate', function (ev) {
            $('.datepicker').hide();
            $("#label-date-andata").addClass("active");

        }).on("show", function (e) {


            if (Trenord.utility.isMobile()) {
                $(" .datepicker").addClass("mobile-date-viaggio");
            } else {
                $(" .datepicker").removeClass("mobile-date-viaggio");
            }
            $(" .datepicker").addClass("dx-viaggio");
            $(" .datepicker .prev, .datepicker .next").empty();

            if (!$(".datepicker-dropdown h4").length) {

                $(".datepicker-dropdown").prepend("<h4>Data</h4>");
                $(".datepicker-dropdown").prepend("<img alt='icona_chiudi' class='close-datepicker lozad'  src='/fileadmin/templates/img/news/close.png'>");

            }

            $(".datepicker-dropdown .close-datepicker").click(function () {
                $('.datepicker').hide();
            });


        }).on('hide', function (date) {


            if ($("#orario1").val() !== "") {

                if ($("#data").val() !== "") {
                    $("#andata_form_gruppi").val("" + $("#data").val() + " Tra le " + $("#orario1").val() + "e le " + $("#orario2").val() + "");
                } else {
                    $("#andata_form_gruppi").val(" Tra le " + $("#orario1").val() + "e le " + $("#orario2").val() + "");

                }
            }

        }).attr('readonly', 'readonly');

        if ($("#data-dx-viaggio").val() == "") {
            $('#data-dx-viaggio').datepicker('setDate', new Date());
        }

    }

    $('#switch-map-idv').change(
        function () {
            if ($(this).is(':checked')) {
                var sticky = new Sticky('.map-idv-container');
                $(".title-idv").addClass("left");
                $(".container-idv-fluid").addClass("map-idv");
            } else {
                $(".title-idv").removeClass("left");
                $(".container-idv-fluid").removeClass("map-idv");
            }
        });


    if ($(".big-table-border,.tabella-tessere").length > 0) {

        var bigBorderTable = $(".big-table-border,.tabella-tessere");

        $(bigBorderTable).parents(".panel-default").removeClass("accordion-custom-style");

        /* da rimettere perchè typo3 non lo fa*/
        $(bigBorderTable).addClass('contenttable');

        var minus = "<img  alt='icona_minus-tabella-dinamica'  class='lozad' src='/fileadmin/templates/img/icons/minus-tabella-dinamica.svg' />";
        var tick = "<img alt='icona_tick-tabella-dinamica' class='lozad'src='/fileadmin/templates/img/icons/tick-tabella-dinamica.svg' />";

        $(bigBorderTable).each(function (index, value) {
            $(value).find("tr").each(function (i, value) {

                if (!$(value).hasClass('head-row')) {
                    $(value).find("td").each(function (j, value) {

                        if (i > 0 && j > 0) {

                            var text = $(value).text();

                            if (text == "-") {
                                $(value).text("").html(minus);
                            }

                            if (text == "v") {
                                $(value).text("").html(tick);
                            }


                        }
                    });
                }
            });
        });


    }

    //rimozione stile per la tabella grandre big-table-border

    //tab dinamico slider-home
    Trenord.globals.TabControl = $(".container-tab .tab:first-child a").length > 0 ? parseInt($(".container-tab .tab:first-child a").attr("id").match(/\d+/)[0]) : null;
    Trenord.globals.TabControlMobile = $(".container-tab .tab:first-child a").length > 0 ? parseInt($(".container-tab .tab:first-child a").attr("id").match(/\d+/)[0]) : null;

    //rimozione immagine news mobile
    if ($(".container-foglia-news").length && $(window).width() < 768) {
        $(".visore-immagine-titolo").css("display", "none");
        $(".container-foglia-news").css("margin-top", "0");
    } else {
        $(".visore-immagine-titolo").css("display", "block");

    }

    //problema ancore figlie in news
    $(".container-tag a").click(function (e) {
        e.stopPropagation();
        eval($(this).attr("onclick"));
    });

    var lastHeight = $(".container-tab").height();

    $('.sticky-carousel-station').owlCarousel({
        loop: false,
        margin: 10,
        nav: false,
        dots: true,
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 1
            },
            1000: {
                items: 1
            }
        }
    });

    //label mappe
    $(".input-container input").focus(function () {
        $(this).prev().addClass("label-active-map");
    });


    $(".input-container input").focusout(function () {
        if (!$(this).val()) {
            $(this).prev().removeClass("label-active-map");
        }
    });

    //faq
    var hash = window.location.hash.replace("#", "").split("-");

    if (window.location.hash === "#ricerca-stazione") {
        setTimeout(function () {
            $("#ric-stazione").trigger("click");
        }, 200);
    }

    setTimeout(function () {
        $("#button-tab-faq-" + hash[0] + "").trigger("click");
    }, 200);

    setTimeout(function () {
        $("a[href='#accordion" + hash[0] + "-faq" + hash[1] + "']").trigger("click");
    }, 1000);

    //social
    $('.social-share').on("click", function () {
        var href = "";
        href = $(this).data("social");

        let channel;
        if(href.startsWith('http://twitter.com/')) {
            channel = 'Twitter'
        } else if (href.startsWith('https://www.facebook.com/')) {
            channel = 'Facebook'
        } else if (href.startsWith('https://www.linkedin.com/')) {
            channel = 'Linkedin'
        } 
        if(channel) {
            dataLayer.push({
                event: 'share',
                method: channel
            });
        }
        
        window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
    });

    //banner cookie
    Trenord.ui.cookie.initEvents();


    //infomobilità
    $('.infomob-ricerca-mobile #search-term-mobile').change(function () {
        $('#station-search').val($(this).val());
    });

    $('.infomob-ricerca-mobile .list-stations li').click(function () {
        $('#station-search').val($(this).find("p").text());
        $(".infomob-ricerca-mobile").fadeOut();
    });


    if (Trenord.utility.isMobile()) {
        var $context = $(".infomob-ricerca-mobile li");
        var $input = $(".infomob-ricerca-mobile #search-term-mobile");
    } else {
        var $context = $(".station-list-result li");
        var $input = $("#station-search");
    }

    $input.on("input focus", function () {
        var term = $(this).val();
        $context.show().unmark();
        if (term.length > 1) {
            if (Trenord.utility.isMobile()) {
                $(" .infomob-ricerca-mobile .list-stations").fadeIn();
            } else {
                $(".station-list-result").fadeIn();

            }

            $context.mark(term, {
                done: function () {
                    $context.not(":has(mark)").hide();

                    if (Trenord.utility.isMobile()) {
                        if ($(".infomob-ricerca-mobile .list-stations li:visible").length != 0) {
                            $(".infomob-ricerca-mobile .list-stations .no-result").hide();
                        } else {
                            $(".infomob-ricerca-mobile .list-stations .no-result").fadeIn();
                        }
                    } else {
                        if ($(".station-list-result li:visible").length != 0) {
                            $(".station-list-result .no-result").hide();
                        } else {
                            $(".station-list-result .no-result").fadeIn();
                        }
                    }


                }
            });
        } else {
            if (Trenord.utility.isMobile()) {
                $(" .infomob-ricerca-mobile .list-stations").hide();
            } else {
                $(".station-list-result").hide();
            }

        }
    });


    $(document).on('click', '.star-red', function () {
        $(this).find("svg").toggleClass("active");
    });
    //accesssibilità

    var numDiff = 0;
    var elem = 0;


    if (!Trenord.utility.isMobile() && !Trenord.utility.isTablet()) {

        if (getCookie('Contrasto') === "on") {
            contrastoOn();
        } else {
            contrastoOff();
        }


        if (getCookie("FontSize") === "") {
            $(".container-link .dropdown-menu.access-text li a span ").removeClass("active");
            $(".container-link .dropdown-menu.access-text li a > span.normal").addClass("active").click();
            $("html").addClass("normal-size").removeClass("small-size").removeClass("big-size");

        }

        if (getCookie("FontSize") === "normal") {
            $("html").addClass("normal-size").removeClass("small-size").removeClass("big-size");
            $("<style type='text/css'> .tn-select__label[_ngcontent-c4]{font-size: 16px;}.tn-select__option[_ngcontent-c4]{font-size: 20px;}.tn-input-text__label[_ngcontent-c2]{font-size: 16px;}.tn-toggle__title[_ngcontent-c5]{font-size: 20px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 18px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 13px;}.tn-select__label--open[_ngcontent-c4]{font-size: 12px;}.tn-select__current[_ngcontent-c4]{font-size: 16px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 18px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 13px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 16px;}.ng-dates__title[_ngcontent-c13]{font-size: 18px;}.ng-dates__week-days[_ngcontent-c13]{font-size: 16px;}.ng-dates__day[_ngcontent-c13]{font-size: 16px;}.tn-date-panel__time-title[_ngcontent-c9]{font-size: 14px;}.tn-slider__value{font-size: 14px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 16px;}.tn-counter__title[_ngcontent-c12]{font-size: 22px;}.tn-counter__text[_ngcontent-c12]{font-size: 14px;}.tn-travellers__text[_ngcontent-c10]{font-size: 12px;}.ng-dates__week-days[_ngcontent-c12]{font-size: 16px;}.ng-dates__day[_ngcontent-c12]{font-size: 16px;}.ng-dates__title[_ngcontent-c12]{font-size: 18px;}.tn-button--big[_ngcontent-c6]{font-size: 20px;}</style>").appendTo("head");


            $(".container-link .dropdown-menu.access-text li a > span").removeClass("active");
            setTimeout(function () {
                $(".container-link .dropdown-menu.access-text li a > span.normal").addClass("active").click();
            }, 20);
        }

        if (getCookie("FontSize") === "big1") {
            $("html").removeClass("normal-size").removeClass("small-size").addClass("big-size");
            $("<style type='text/css'> .tn-button--big[_ngcontent-c6]{font-size: 22px;}.tn-select__label[_ngcontent-c4]{font-size: 18px;}.tn-select__option[_ngcontent-c4]{font-size: 22px;}.tn-input-text__label[_ngcontent-c2]{font-size: 18px;}.tn-toggle__title[_ngcontent-c5]{font-size: 22px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 20px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 15px;}.tn-select__label--open[_ngcontent-c4]{font-size: 14px;}.tn-select__current[_ngcontent-c4]{font-size: 18px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 20px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 15px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 18px;}.ng-dates__title[_ngcontent-c13]{font-size: 20px;}.ng-dates__week-days[_ngcontent-c13]{font-size: 18px;}.ng-dates__day[_ngcontent-c13]{font-size: 18px;}.tn-date-panel__time-title[_ngcontent-c9]{font-size: 16px;}.tn-slider__value{font-size: 16px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 18px;}.tn-counter__title[_ngcontent-c12]{font-size: 24px;}.tn-counter__text[_ngcontent-c12]{font-size: 16px;}.tn-travellers__text[_ngcontent-c10]{font-size: 14px;}.ng-dates__week-days[_ngcontent-c12]{font-size: 18px;}.ng-dates__day[_ngcontent-c12]{font-size: 18px;}.ng-dates__title[_ngcontent-c12]{font-size: 20px;}</style>").appendTo("head");


            $(".container-link .dropdown-menu.access-text li a span ").removeClass("active");
            eraseCookie("FontSize");
            setCookie('FontSize', 'big1', 1);
            $(".container-link .dropdown-menu.access-text li a span.big ").addClass("big1").addClass("active");
            $("html").css("font-size", "20px");
        }


        if (getCookie("FontSize") === "small") {
            $("html").removeClass("normal-size").addClass("small-size").removeClass("big-size");
            $("<style type='text/css'> .tn-button--big[_ngcontent-c6]{font-size: 18px;}.tn-select__label[_ngcontent-c4]{font-size: 14px;}.tn-select__option[_ngcontent-c4]{font-size: 18px;}.tn-input-text__label[_ngcontent-c2]{font-size: 14px;}.tn-toggle__title[_ngcontent-c5]{font-size: 18px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 16px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 11px;}.tn-select__label--open[_ngcontent-c4]{font-size: 10px;}.tn-select__current[_ngcontent-c4]{font-size: 14px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 16px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 11px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 14px;}.ng-dates__title[_ngcontent-c13]{font-size: 16px;}.ng-dates__week-days[_ngcontent-c13]{font-size: 14px;}.ng-dates__day[_ngcontent-c13]{font-size: 14px;}.tn-date-panel__time-title[_ngcontent-c9]{font-size: 12px;}.tn-slider__value{font-size: 12px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 14px;}.tn-counter__title[_ngcontent-c12]{font-size: 20px;}.tn-counter__text[_ngcontent-c12]{font-size: 12px;}.tn-travellers__text[_ngcontent-c10]{font-size: 10px;}.ng-dates__week-days[_ngcontent-c12]{font-size: 14px;}.ng-dates__day[_ngcontent-c12]{font-size: 14px;}.ng-dates__title[_ngcontent-c12]{font-size: 16px;}</style>").appendTo("head");


            $(".container-link .dropdown-menu.access-text li a  span").removeClass("active");

            $(".container-link .dropdown-menu.access-text li a > span").removeClass("active");
            setTimeout(function () {
                $(".container-link .dropdown-menu.access-text li a > span.small").addClass("active").click();
            }, 20);
        }


    }
    $(".container-link .dropdown-menu.access-text li a").click(function () {
        var activeElement = $(".container-link .dropdown-menu.access-text li a .active").attr("id");

    });


    $("#contrastoElevato").click(function () {

        if (!$(this).hasClass("active")) {
            $(".triangle-slider-mobile").css("border-color", "transparent transparent #a00000 transparent;");

            eraseCookie('Contrasto')
            $("#contrastoElevato").addClass("active");
            setCookie('Contrasto', 'on', 1);

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(0, 102, 51)';
            }).each(function () {
                $(this).css('background-color', 'rgb(0, 80, 0)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(0, 102, 51)';
            }).each(function () {
                $(this).css('color', 'rgb(0, 80, 0)');
            });

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(210, 0, 25)';
            }).each(function () {
                $(this).css('background-color', 'rgb(160, 0, 0)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(210, 0, 25)';
            }).each(function () {
                $(this).css('color', 'rgb(160, 0, 0)');
            });

            $('*').filter(function () {
                return $(this).css('fill') == 'rgb(210, 0, 25)';
            }).each(function () {
                $(this).css('fill', 'rgb(160, 0, 0)');
            });


            $('*').filter(function () {
                return $(this).css('fill') == 'rgb(0, 102, 51)';
            }).each(function () {
                $(this).css('fill', 'rgb(0, 80, 0)');
            });


            if ($("body").hasClass("malpensaStyle")) {
                $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px rgba(160, 0,0,0.98)');
                $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
                $(".quadrilater").css('border-bottom-style', 'solid');
                $(".quadrilater").css('border-bottom-color', 'rgba(160, 0,0,0.98)');
            }

        } else {
            $(".triangle-slider-mobile").css("border-color", "transparent transparent #d20019 transparent;");

            eraseCookie('Contrasto')
            $("#contrastoElevato").removeClass("active");
            setCookie('Contrasto', 'off', 1);

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(0, 80, 0)';
            }).each(function () {
                $(this).css('background-color', 'rgb(0, 102, 51)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(0, 80, 0)';
            }).each(function () {
                $(this).css('color', 'rgb(0, 102, 51)');
            });

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(160, 0, 0)';
            }).each(function () {
                $(this).css('background-color', 'rgb(210, 0, 25)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(160, 0, 0)';
            }).each(function () {
                $(this).css('color', 'rgb(210, 0, 25)');
            });

            $('*').filter(function () {
                return $(this).css('fill') == ' rgb(160, 0, 0)';
            }).each(function () {
                $(this).css('fill', 'rgb(210, 0, 25)');
            });


            $('*').filter(function () {
                return $(this).css('fill') == ' rgb(0, 80, 0)';
            }).each(function () {
                $(this).css('fill', 'rgb(0, 102, 51)');
            });

            if ($("body").hasClass("malpensaStyle")) {
                $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px rgba(208, 2, 27,0.8)');
                $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
                $(".quadrilater").css('border-bottom-style', 'solid');
                $(".quadrilater").css('border-bottom-color', 'rgba(208, 2, 27,0.8)');

            }

        }
    });


    function contrastoOff() {
        $(".triangle-slider-mobile").css("border-color", "transparent transparent #d20019 transparent;");

        eraseCookie('Contrasto')
        $("#contrastoElevato").removeClass("active");
        setCookie('Contrasto', 'off', 1);

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(0, 80, 0)';
        }).each(function () {
            $(this).css('background-color', 'rgb(0, 102, 51)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(0, 80, 0)';
        }).each(function () {
            $(this).css('color', 'rgb(0, 102, 51)');
        });

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(160, 0, 0)';
        }).each(function () {
            $(this).css('background-color', 'rgb(210, 0, 25)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(160, 0, 0)';
        }).each(function () {
            $(this).css('color', 'rgb(210, 0, 25)');
        });


        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(160, 0, 0)';
        }).each(function () {
            $(this).css('fill', 'rgb(210, 0, 25)');
        });


        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(0, 80, 0)';
        }).each(function () {
            $(this).css('fill', 'rgb(0, 102, 51)');
        });

        if ($("body").hasClass("malpensaStyle")) {
            $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px rgba(208, 2, 27,0.8)');
            $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
            $(".quadrilater").css('border-bottom-style', 'solid');
            $(".quadrilater").css('border-bottom-color', 'rgba(208, 2, 27,0.8)');

        }

        $("#contrastoElevato").removeClass("active");
    }


    function contrastoOn() {

        $(".triangle-slider-mobile").css("border-color", "transparent transparent #a00000 transparent;");


        eraseCookie('Contrasto')
        $("#contrastoElevato").removeClass("active");
        setCookie('Contrasto', 'on', 1);

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(0, 102, 51)';
        }).each(function () {
            $(this).css('background-color', 'rgb(0, 80, 0)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(0, 102, 51)';
        }).each(function () {
            $(this).css('color', 'rgb(0, 80, 0)');
        });

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(210, 0, 25)';
        }).each(function () {
            $(this).css('background-color', 'rgb(160, 0, 0)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(210, 0, 25)';
        }).each(function () {
            $(this).css('color', 'rgb(160, 0, 0)');
        });

        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(210, 0, 25)';
        }).each(function () {
            $(this).css('fill', 'rgb(160, 0, 0)');
        });


        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(0, 102, 51)';
        }).each(function () {
            $(this).css('fill', 'rgb(0, 80, 0)');
        });

        if ($("body").hasClass("malpensaStyle")) {
            $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px rgba(160, 0,0,0.98)');
            $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
            $(".quadrilater").css('border-bottom-style', 'solid');
            $(".quadrilater").css('border-bottom-color', 'rgba(160, 0,0,0.98)');

        }

        $("#contrastoElevato").addClass("active");
    }

    //circle countdown 404

    // hide result form
    $(".container-modal-result,#close-modal-result").click(function () {
        $(".container-modal-result ").fadeOut();
    });


    //scroll infomobilità

    $(".list-station ul").each(function (index) {
        $(this).attr("data-children", "" + $(this).children().length - 2 + "");
    });

    var countStations = null;
    //$('.list-station ul li').length - 1;
    var poScroll = null;


    $(".modal-content, .modal-body").click(function () {

        if ($(this).parents(".video-modal").length > 0) {
            $('.myModal').modal('hide');
            var iframePlayer = $(this).find('iframe');
            $(iframePlayer).attr('src', $(iframePlayer).attr('src'));
        }
    });


    //infomob da creare infomobilità
    $(".infomob-ricerca-mobile .reset-search").click(function () {
        $(".infomob-ricerca-mobile #search-term-mobile").val("");
        $(".infomob-ricerca-mobile #search-term-mobile").trigger("input");
    });


    $("#station-search").focus(function () {
        if (Trenord.utility.isMobile() || Trenord.utility.isTablet()) {
            $(".infomob-ricerca-mobile").fadeIn();
            $(".infomob-ricerca-mobile #search-term-mobile").focus();
        }
    });


    $(".infomob-ricerca-mobile .close-search-mobile  img").click(function () {
        $(".infomob-ricerca-mobile").fadeOut();
    });

    //mobile
    $(function () {
        var $input = $(".infomob-ricerca-mobile #search-term-mobile");
        var $context = $(".dropdown-menu.ricerca-infomob.result li ");

        $input.on("input", function () {
            if ($input.val().length !== 0) {
                $(".infomob-ricerca-mobile .reset-search").fadeIn();
            } else {
                $(".infomob-ricerca-mobile .reset-search").fadeOut();
            }
            setTimeout(function () {

                if ($(".infomob-ricerca-mobile .dropdown-menu.ricerca-infomob.result li:visible").length === 0) {

                    $(".dropdown-menu.ricerca-infomob.no-result").show();

                } else {
                    $(".dropdown-menu.ricerca-infomob.no-result").hide();
                }
            }, 50);


        });
    });

    //desktop
    $(function () {
        var $input = $("input[name='infomobRicerca']");
        var $context = $(".dropdown-menu.ricerca-infomob li");
        $input.on("input", function () {


        });
    });


    Trenord.ui.carouselLine();
    Trenord.ui.filterLine();
    //sposto mappa nel mobile di sticky station

    if (Trenord.utility.isMobile() || Trenord.utility.isTablet() && $(".sticky-station").length) {
        $("#sticky-div,.container-image-sticky").prependTo(".container-sticky");
    }


    $("input, select, textarea").attr("autocomplete", "off");

    Trenord.ui.elementsVisibilityFromUserAgent();

    function expandTextarea(id) {
        document.getElementById(id).addEventListener('keyup', function () {
            this.style.overflow = 'hidden';
            this.style.height = 0;
            this.style.height = this.scrollHeight + 'px';
        }, false);
    }

    if ($("#richiesta").length) {
        expandTextarea('richiesta');
    }


    $('#js-date-voli-aereo,#js-date-next-train-end,#js-date-next-train-start').keypress(function (event) {
        event.preventDefault();
    });

    $(document).on('click', '.mostra-altri', function () {
        var elementHidden = 0;
        var c = 5;
        $(".archivio-dettaglio .container-train").each(function (index) {


            if ($(this).css('display') == 'none' && c > 0) {
                var element = $(this);
                $(this).hide().removeClass("hidden");

                setTimeout(function () {
                    element.fadeIn("slow").delay("1000");
                }, 200);
                c--;
            }


        });

        $(".archivio-dettaglio .container-train").each(function (index) {
            if ($(this).css('display') == 'none') {
                elementHidden++;

            }
        });

        if (elementHidden == 0) {

            if (!$('.container-mostra-altri').hasClass("avvisi")) {
                $('.container-mostra-altri').fadeOut();
            }

        }

    });


    $(".container-link .dropdown-menu.access-text li a span").click(function () {


        var element = $(this);

        if (element.hasClass("big")) {
            $(".container-link .dropdown-menu.access-text li a span.small").css("color", "#d20019");
            $(".container-link .dropdown-menu.access-text li a span").removeClass("active");
            $("html").removeClass("normal-size").removeClass("small-size").addClass("big-size");
            $(".container-link .dropdown-menu.access-text li a span").removeClass("active");
            setCookie('FontSize', 'big1', 1);
            element.addClass("big1");
            element.addClass("active");
            $("html").css("font-size", "20px");
            element.css("color", "#9b9b9b");
            $("<style type='text/css'> .tn-button--big[_ngcontent-c6]{font-size: 22px;}.tn-select__label[_ngcontent-c4]{font-size: 18px;}.tn-select__option[_ngcontent-c4]{font-size: 22px;}.tn-input-text__label[_ngcontent-c2]{font-size: 18px;}.tn-toggle__title[_ngcontent-c5]{font-size: 22px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 20px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 15px;}.tn-select__label--open[_ngcontent-c4]{font-size: 14px;}.tn-select__current[_ngcontent-c4]{font-size: 18px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 20px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 15px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 18px;}.ng-dates__title[_ngcontent-c13]{font-size: 20px;}.ng-dates__week-days[_ngcontent-c13]{font-size: 18px;}.ng-dates__day[_ngcontent-c13]{font-size: 18px;}.tn-date-panel__time-title[_ngcontent-c9]{font-size: 16px;}.tn-slider__value{font-size: 16px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 18px;}.tn-counter__title[_ngcontent-c12]{font-size: 24px;}.tn-counter__text[_ngcontent-c12]{font-size: 16px;}.tn-travellers__text[_ngcontent-c10]{font-size: 14px;}.ng-dates__week-days[_ngcontent-c12]{font-size: 18px;}.ng-dates__day[_ngcontent-c12]{font-size: 18px;}.ng-dates__title[_ngcontent-c12]{font-size: 20px;}</style>").appendTo("head");

        }

        if (element.hasClass("small")) {
            $("html").removeClass("normal-size").addClass("small-size").removeClass("big-size");


            setCookie('FontSize', 'small', 1);

            $(".container-link .dropdown-menu.access-text li a span.big").removeClass("big1");
            $(".container-link .dropdown-menu.access-text li a span.big").removeClass("big2");
            $(".container-link .dropdown-menu.access-text li a span").removeClass("active");
            $("html").css("font-size", "16px");
            $(".container-link .dropdown-menu.access-text li a span.big").css("color", "#d20019");
            $("<style type='text/css'> .tn-button--big[_ngcontent-c6]{font-size: 18px;}.tn-select__label[_ngcontent-c4]{font-size: 14px;}.tn-select__option[_ngcontent-c4]{font-size: 18px;}.tn-input-text__label[_ngcontent-c2]{font-size: 14px;}.tn-toggle__title[_ngcontent-c5]{font-size: 18px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 16px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 11px;}.tn-select__label--open[_ngcontent-c4]{font-size: 10px;}.tn-select__current[_ngcontent-c4]{font-size: 14px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 16px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 11px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 14px;}.ng-dates__title[_ngcontent-c13]{font-size: 16px;}.ng-dates__week-days[_ngcontent-c13]{font-size: 14px;}.ng-dates__day[_ngcontent-c13]{font-size: 14px;}.tn-date-panel__time-title[_ngcontent-c9]{font-size: 12px;}.tn-slider__value{font-size: 12px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 14px;}.tn-counter__title[_ngcontent-c12]{font-size: 20px;}.tn-counter__text[_ngcontent-c12]{font-size: 12px;}.tn-travellers__text[_ngcontent-c10]{font-size: 10px;}.ng-dates__week-days[_ngcontent-c12]{font-size: 14px;}.ng-dates__day[_ngcontent-c12]{font-size: 14px;}.ng-dates__title[_ngcontent-c12]{font-size: 16px;}</style>").appendTo("head");

            element.css("color", "#9b9b9b");
            element.addClass("active");
        }
        if (element.hasClass("normal")) {
            $("html").addClass("normal-size").removeClass("small-size").removeClass("big-size");
            $("<style type='text/css'> .tn-select__label[_ngcontent-c4]{font-size: 16px;}.tn-select__option[_ngcontent-c4]{font-size: 20px;}.tn-input-text__label[_ngcontent-c2]{font-size: 16px;}.tn-toggle__title[_ngcontent-c5]{font-size: 20px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 18px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 13px;}.tn-select__label--open[_ngcontent-c4]{font-size: 12px;}.tn-select__current[_ngcontent-c4]{font-size: 16px;}.tn-input-text__input.tn-input-text--small[_ngcontent-c2]{font-size: 18px;}.tn-input-text--open[_ngcontent-c2] .tn-input-text__label[_ngcontent-c2]{font-size: 13px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 16px;}.ng-dates__title[_ngcontent-c13]{font-size: 18px;}.ng-dates__week-days[_ngcontent-c13]{font-size: 16px;}.ng-dates__day[_ngcontent-c13]{font-size: 16px;}.tn-date-panel__time-title[_ngcontent-c9]{font-size: 14px;}.tn-slider__value{font-size: 14px;}.tn-sliding-panel__title[_ngcontent-c7]{font-size: 16px;}.tn-counter__title[_ngcontent-c12]{font-size: 22px;}.tn-counter__text[_ngcontent-c12]{font-size: 14px;}.tn-travellers__text[_ngcontent-c10]{font-size: 12px;}.ng-dates__week-days[_ngcontent-c12]{font-size: 16px;}.ng-dates__day[_ngcontent-c12]{font-size: 16px;}.ng-dates__title[_ngcontent-c12]{font-size: 18px;}.tn-button--big[_ngcontent-c6]{font-size: 20px;}</style>").appendTo("head");

            setCookie('FontSize', 'normal', 1);

            $(".container-link .dropdown-menu.access-text li a span.big").removeClass("big1");
            $(".container-link .dropdown-menu.access-text li a span.big").removeClass("big2");
            $(".container-link .dropdown-menu.access-text li a span.small").css("color", "#d20019");
            $(".container-link .dropdown-menu.access-text li a span.big").css("color", "#d20019");
            $(".container-link .dropdown-menu.access-text li a span").removeClass("active");
            $("html").css("font-size", "18px");
            element.addClass("active");
        }

        setTimeout(function () {
            window.dispatchEvent(new Event('resize'));
        }, 100);

    });


    var h1 = 0;
    var h2 = 0;
    $(".organi-societari").each(function (index) {
        $(this).find(".first li").each(function (numli) {
            h1 = $(this).height();
            h2 = $(this).parent().parent().parent().find(".second li:eq(" + numli + ")").height();

            if (h1 > h2) {
                $(this).parent().parent().parent().find(".second li:eq(" + numli + ")").height(h1);
            } else {
                $(this).height(h2);
            }
        });
    });


    var initialContainer = $('.columns'),
        columnItems = $('.columns li'),
        columns = null,
        column = 1; // account for initial column
    function updateColumns() {
        column = 0;
        columnItems.each(function (idx, el) {
            if (idx !== 0 && idx > (columnItems.length / columns.length) + (column * idx)) {
                column += 1;
            }

            $(columns.get(column)).append(el);
        });
    }

    function setupColumns() {
        columnItems.detach();
        while (column++ < initialContainer.data('columns')) {
            initialContainer.clone().insertBefore(initialContainer);
            column++;
        }
        columns = $('.columns');
        updateColumns();
    }

    $(setupColumns);


    $('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
        selected = $(e.currentTarget).val();


        if (selected) {

            if ($(this).parent().parent().parent().attr("class") === "item") {
                $("label#label-motivo").css("top", "9px");
                $("label#label-motivo").css("font-size", "12px");
            } else {
                $("label#label-motivo").css("top", "37px");
                $("label#label-motivo").css("font-size", "14px");
                $("p#label-motivo").removeClass("error-input");
                $("label#label-motivo").removeClass("error-input");
            }

        }
    });

    $('.selectpicker').on('show.bs.select', function (e, clickedIndex, newValue, oldValue) {

        $("#label-motivo").removeClass("error-input");

        if (!Trenord.utility.isMobile() && !Trenord.utility.isTablet()) {
            $(".mobile-form-contatti .title-container").remove();
        }

        selected = $(this).attr("id");

        if ($(this).parent().parent().parent().attr("class") === "item") {
            $("label#label-motivo").css("top", "9px");
            $("label#label-motivo").css("font-size", "12px");
        } else {
            $("label#label-motivo").css("top", "15px");
            $("label#label-motivo").css("font-size", "14px");
        }


        if (selected === "motivo-form-contatti" && Trenord.utility.isMobile() && !$(".dropdown-menu.open .inner .title-container").length) {
            if (!$(".archivio-filter .dropdown-menu.open .title-form-mobile").length) {
                $(".archivio-filter .dropdown-menu.open").prepend("<div class='title-form-mobile'><h4>Seleziona un motivo</h4><img alt='icona-chiudi-form' class='lozad' src='/fileadmin/templates/img/close_form.png'></div>")
            }
            $("body,html").css("overflow", "hidden");
            $(".archivio-filter .dropdown-menu.open").addClass("mobile-form-contatti");
        }
        if (!Trenord.utility.isMobile() && !Trenord.utility.isTablet()) {
            $(".mobile-form-contatti .title-container").remove();
        }

        selected = $(this).attr("id");

        if (selected === "motivo-form-contatti") {
            $("label#label-motivo").css("top", "15px");
            $("label#label-motivo").css("font-size", "14px");
        }


        if (selected === "motivo-form-contatti" && Trenord.utility.isMobile() && !$(".dropdown-menu.open .inner .title-container").length) {
            $("body,html").css("overflow", "hidden");
            $(".archivio-filter .dropdown-menu.open").addClass("mobile-form-contatti");

        }

        if (selected === "motivo-form-contatti-train" && Trenord.utility.isMobile() && !$(".dropdown-menu.open .inner .title-container").length) {

            $("body,html").css("overflow", "hidden");
            $(".archivio-filter .dropdown-menu.open").addClass("mobile-form-contatti");

            if (!$(".mobile-form-contatti .title-container").length) {
                $(".mobile-form-contatti ").prepend("<div class='title-container'><h4>Seleziona una stazione</h4>   <svg class=\"close\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"240\" height=\"240\" viewBox=\"0 0 240 240\">\n" +
                    "\n" +
                    "                <path fill=\"#4a4a4a\" id=\"a\" d=\"M99.67 90.836a6.247 6.247 0 1 1-8.834 8.834L51 59.834 11.164 99.67a6.247 6.247 0 1 1-8.834-8.834L42.166 51 2.33 11.164a6.247 6.247 0 1 1 8.834-8.834L51 42.166 90.836 2.33a6.247 6.247 0 1 1 8.834 8.834L59.834 51 99.67 90.836z\"></path>\n" +
                    "\n" +
                    "                </svg></div>");
            }

        }


    });

    $('.selectpicker').on('hide.bs.select', function (e, clickedIndex, newValue, oldValue) {

        selected = $(this).attr("id");
        if (selected === "motivo-form-contatti") {

            $("body,html").css("overflow", "initial");
            if ($("#motivo-form-contatti").val() === null) {
                $("label#label-motivo").css("top", "30px");
                $("label#label-motivo").css("font-size", "16px");

            } else {
                $("label#label-motivo").css("top", "15px");
                $("label#label-motivo").css("font-size", "16px");
            }
        }
    });

    $('#richiesta').keydown(function (e) {
        if ($(this).val().length > 0) {
            $("#label-richiesta").removeClass("error-input");
        }

    });

    $('#richiesta').on('keyup', function () {
        $(".container-counter .current-counter").html(this.value.length);


    });


    var err = 0;


    $(".multiple-carnet:visible").each(function (index) {
        var i = 1;
        var numUl = $(this).find("ul").length;
        var numLi = $(this).find("ul").find("li").length / numUl;
        var max = 0;
        for (i = 0; i < numLi; i++) {
            max = 0;
            $(this).find("ul").each(function (index) {
                if ($(this).children().eq(i).height() > max) {
                    max = $(this).children().eq(i).height();
                }
            });


            $(this).find("ul").each(function (index) {
                $(this).children().eq(i).height(max);
            });
        }
    });


    var timeoutDropdown;


    $('a.user-logged').mouseenter(function (event) {
        $('.container-link .dropdown-menu.user').addClass("hidden");
        $('.dropdown-menu.user-logged-dropdown').removeClass("hidden");
        $('.container-link .dropdown-menu.access-text').addClass("hidden");
        clearTimeout(timeoutDropdown); // reset timeout submenu
        $(this).next().fadeIn();
    }).mouseleave(function (event) {
        timeoutDropdown = setTimeout(function () {
            $(".dropdown-menu").fadeOut();
        }, 400)
    });

    $('.user-toggle').mouseenter(function (event) {
        $('.container-link .dropdown-menu.user').removeClass("hidden");
        $('.dropdown-menu.user-logged-dropdown').addClass("hidden");
        $('.container-link .dropdown-menu.access-text').addClass("hidden");
        clearTimeout(timeoutDropdown); // reset timeout submenu
        $(this).next().fadeIn();
    }).mouseleave(function (event) {
        timeoutDropdown = setTimeout(function () {
            $(".dropdown-menu").fadeOut();
        }, 400)
    });


    $('.link-accessibility').mouseenter(function (event) {
        $('.container-link .dropdown-menu.user').addClass("hidden");
        $('.dropdown-menu.user-logged-dropdown').addClass("hidden");
        $('.container-link .dropdown-menu.access-text').removeClass("hidden");
        clearTimeout(timeoutDropdown); // reset timeout submenu
        $(this).next().fadeIn();
    }).mouseleave(function (event) {
        timeoutDropdown = setTimeout(function () {
            $(".dropdown-menu").fadeOut();
        }, 400)
    });


    $('.dropdown-menu').mouseenter(function (event) {

        clearTimeout(timeoutDropdown); // reset timeout submenu
    }).mouseleave(function (event) {
        timeoutDropdown = setTimeout(function () {
            $(".dropdown-menu").fadeOut();
        }, 400)
    });

    Trenord.ui.allAlertSiteOpen();
    Trenord.user.init();


    //remove autocomplete e autofill
    $(document).on('focus', ':input', function () {
        $(this).attr('autocomplete', 'off');
    });

    $(".container-bar .bar").fadeIn("1000");
    $(".container-ticket").fadeIn("50");



    Trenord.passengersWidget.init();
    //home menu start
    Trenord.ui.menu();
    //slider home start
    Trenord.ui.sliderHome();
    //Sidenav start
    Trenord.ui.sideNav();
    //Sidenav start
    Trenord.ui.searchNav.initEvents();
    //in evidenza start
    Trenord.ui.inEvidenza();
    //carouselNews start
    Trenord.ui.carouselNews();
    //carouselPartners start
    Trenord.ui.carouselPartners();
    //tabFooterTop start
    Trenord.ui.tabFooterTop();
    //carosuelAgevolazioniSupplementi start
    Trenord.ui.carosuelAgevolazioniSupplementi();
    //carosuelInEvidenza start
    Trenord.ui.carosuelInEvidenza();
    //carosuelGeneric start
    Trenord.ui.carouselGeneric();
    //laNostraOfferta start
    Trenord.ui.laNostraOfferta();
    Trenord.ui.lineeMappeOrari.initEvents();
    //Malpensa voli
    Trenord.ui.malpensaVoli.initEvents();
    //Malpensa treni
    Trenord.ui.malpensaTreni.initEvents();
    //ideeDiViaggio start
    Trenord.ui.ideeDiViaggio.init();
    //Login start
    Trenord.ui.login.initEvents();
    //timeCircle start
    Trenord.ui.timeCircle.initEvents();
    //malpensaWidget start
    Trenord.ui.malpensaWidget.initEvents()
    //searchNews start
    Trenord.ui.searchNews();
    //malpensaWidget start
    Trenord.ui.serp();
    //accesibilità
    Trenord.ui.accesibilita();
    Trenord.ui.lazyLoad();
    //malpensaProssimiTreni
    Trenord.ui.malpensaProssimiTreni.initEvents();
    //payGo
    Trenord.ui.payGo();
    //footer title top
    Trenord.utility.resizeHeight();
    Trenord.utility.resizeTriangleMobile();
    Trenord.utility.resizeHeightWidget();
    Trenord.utility.Accordion();
    Trenord.utility.Tooltip();
    Trenord.utility.Tab();
    Trenord.utility.Modal();
    Trenord.utility.Faq.initEvents();
    Trenord.ui.carouselAppTrenord();
    Trenord.ui.carosuelMobileGreenCard();
    Trenord.ui.carouselDoubleColumn();
    Trenord.ui.carouselMedia();


    Trenord.utility.multipleTab();
    Trenord.utility.mobileDetector();
    Trenord.utility.alert();
    Trenord.utility.VediAncheHover();
    Trenord.utility.tornaSu();
    Trenord.utility.widgetTool();

    Trenord.infoMobilita.initEvents();
    Trenord.ui.infoMobilita.initEvents();
    Trenord.ui.formGruppi();
    Trenord.form.contatti.initEvents();

    Trenord.carnet.init();

    if ($(".container-sticky .content").height() > $(".container-sticky #sticky-div").height()) {
        $("#sticky-div,.container-image-sticky").length > 0 ? $("#sticky-div,.container-image-sticky").stick_in_parent({
            spacer: false
        }) : null;
    } else {
        $("#sticky-div").trigger("sticky_kit:detach");
    }
});


$(window).resize(function () {


    equalheight('.card-app-linee');
    equalheight('.approfondimenti-linea .card-app-linee .title');

    //problema gestione spazio senza visore(foglia news)

    if ($(".container-foglia-news") && $(".visore-immagine-titolo").length == 0) {
        $(".container-foglia-news").css("margin-top", "100px");
    }

    //rimozione immagine news 

    if ($(".container-foglia-news").length && $(window).width() < 768) {
        $(".visore-immagine-titolo").css("display", "none");
        $(".container-foglia-news").css("margin-top", "0");
    } else {
        $(".visore-immagine-titolo").css("display", "block");
    }


    if ($(window).width() >= 1024) {
        $(".main-tab .container-tab").fadeIn();
    } else {
        $(".main-tab .container-tab").hide();
    }

    var $element = $(".quadrilater");
    var lastHeight = $(".container-tab").height();
    if ($("body").hasClass("malpensaStyle")) {
        if (getCookie('Contrasto') === "on") {
            $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px #a00000fa');
            $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
            $(".quadrilater").css('border-bottom-style', 'solid');
            $(".quadrilater").css('border-bottom-color', 'rgba(160,0,0,0.8)');

        } else {

            $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px #d0021bd9');
            $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
            $(".quadrilater").css('border-bottom-style', 'solid');
            $(".quadrilater").css('border-bottom-color', 'rgba(208,2,27,0.8)');
        }

    } else {
        setTimeout(function () {
            $(".quadrilater").css('border-bottom', 'solid ' + $(".container-tab").height() + 'px #0c683fd1');
            $(".quadrilater").css('border-bottom-width', +$(".container-tab").height() + 'px');
            $(".quadrilater").css('border-bottom-style', 'solid');
            $(".quadrilater").css('border-bottom-color', 'rgba(12,104,63,0.8)');
        }, 500);

    }
    if (!Trenord.utility.isMobile()) {
        $(".box-info-map #noovle-map").css("height", "auto");
        setTimeout(function () {
            $(".box-info-map #noovle-map").height($(".box-info-mob-map").height());

        }, 200);
    } else {

    }

    if (Trenord.utility.isMobile() || Trenord.utility.isTablet() && $(".sticky-station").length) {
        $("#sticky-div,.container-image-sticky").prependTo(".container-sticky");
    } else {
        $("#sticky-div,.container-image-sticky").prependTo(".container-sticky");
    }

    if (Trenord.utility.isMobile() || Trenord.utility.isTablet() && $(".position-bonus").length) {

        $(".container-box-sticky").insertAfter($(" .position-bonus"));
    } else {
        $("#sticky-div").prepend($(".container-box-sticky"));
    }


    $(".multiple-carnet:visible ").find("ul").css("height", "auto");
    $(".multiple-carnet:visible ").find("li").css("height", "auto");
    $(".multiple-carnet:visible").each(function (index) {


        var i = 1;
        var numUl = $(this).find("ul").length;
        var numLi = $(this).find("ul").find("li").length / numUl;
        var max = 0;
        for (i = 0; i < numLi; i++) {
            max = 0;
            $(this).find("ul").each(function (index) {
                if ($(this).children().eq(i).height() > max) {
                    max = $(this).children().eq(i).height();
                }
            });


            $(this).find("ul").each(function (index) {
                $(this).children().eq(i).height(max);
            });
        }


    });

    if ($(window).width() > 768 && $(window).width() < 1024) {

        $("body.malpensaStyle .train-home.archivio-dettaglio .container-train .train .select-result .content-visible .buy").each(function (index) {
            var par = $(this).parent().parent();
            $(this).appendTo(par);
        });

    } else {

        $("body.malpensaStyle .train-home.archivio-dettaglio .container-train .train .select-result .train .buy").each(function (index) {
            var par = $(this).parent().find(".content-visible");
            $(this).appendTo(par);
        });


    }


    $(".modal-content").each(function (index) {
        var h = $(this).find(".modal-header").outerHeight();
        $(this).find(".modal-body").css("top", h);
    });

    var h1 = 0;
    var h2 = 0;
    $(".organi-societari").each(function (index) {
        $(this).find("li").css("height", "auto");
        $(this).find(".first li").each(function (numli) {

            h1 = $(this).height();
            h2 = $(this).parent().parent().parent().find(".second li:eq(" + numli + ")").height();

            if (h1 > h2) {
                $(this).parent().parent().parent().find(".second li:eq(" + numli + ")").height(h1);
            } else {
                $(this).height(h2);
            }
        });
    });

    Trenord.ui.menu();
    Trenord.ui.carouselDoubleColumn();
    Trenord.utility.resizeSliderHome();
    Trenord.utility.multipleTab();
    Trenord.ui.tabFooterTop();
    Trenord.ui.inEvidenza();
    Trenord.utility.setCssAuto();
    Trenord.utility.resizeTriangleMobile();
    Trenord.utility.resizeHeightWidget();
    Trenord.ui.laNostraOfferta();
    Trenord.utility.Tab();
    Trenord.ui.carouselAppTrenord();
    Trenord.ui.carosuelMobileGreenCard();
    Trenord.ui.formGruppi();
    Trenord.utility.VediAncheHover();
    Trenord.utility.tornaSu();


    setTimeout(function () {

        var h1 = 0;
        var h2 = 0;
        $(".organi-societari").each(function (index) {
            $(this).find(li).css("height", "auto");
            $(this).find(".first li").each(function (numli) {

                h1 = $(this).height();
                h2 = $(this).parent().parent().parent().find(".second li:eq(" + numli + ")").height();

                if (h1 > h2) {
                    $(this).parent().parent().parent().find(".second li:eq(" + numli + ")").height(h1);
                } else {
                    $(this).height(h2);
                }
            });
        });


        $(".modal-content").each(function (index) {

            var modText = $(this).find(".content-text-modal").length;

            if ($(this).find(".modal-note").length) {
                $(this).find(".modal-note").addClass("column" + modText + "");
                if (Trenord.utility.isMobile() || Trenord.utility.isTablet()) {
                    $(this).find(".content-text-modal").css("padding-bottom", "0");
                    setTimeout(function () {
                        /*
                                                $(this).find(".content-text-modal:last-child").css("padding-bottom",$(this).find(".modal-note").outerHeight());
                        */
                    }, 200);
                    /*
                                        $(this).find(".content-text-modal:last-child").css("padding-bottom", $(this).find(".modal-note").outerHeight());
                    */

                } else {
                    /*
                                        $(this).find(".content-text-modal").css("padding-bottom", $(this).find(".modal-note").outerHeight());
                    */
                }

            }

        });
        $("#discovery-catalog .container-idv").css("heigth", "auto");
        var maxHeight = Math.max.apply(null, $("#discovery-catalog .container-idv").map(function () {

            return $(this).height();
        }).get());

        $("#discovery-catalog .container-idv").height(maxHeight);

        Trenord.ui.menu();
        Trenord.ui.carouselDoubleColumn();
        Trenord.utility.VediAncheHover();
        Trenord.utility.resizeSliderHome();
        Trenord.utility.multipleTab();
        Trenord.ui.tabFooterTop();
        Trenord.ui.inEvidenza();
        Trenord.utility.resizeHeight();
        Trenord.utility.resizeHeightWidget();
        Trenord.ui.laNostraOfferta();
        Trenord.ui.carouselAppTrenord();
        Trenord.ui.carosuelMobileGreenCard();
        Trenord.utility.tornaSu();
        Trenord.utility.widgetTool();
        Trenord.ui.initPassengerShoulder();


    }, 0);
});


$(window).scroll(function (event) {


    Trenord.ui.cookie.accept();
});

function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}


function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    setCookie(name, "", -1);
}


/**
 *
 *
 * @author Jerry Bendy <jerry@icewingcc.com>
 * @licence MIT
 *
 */

(function (self) {
    'use strict';

    var nativeURLSearchParams = (function () {
            // #41 Fix issue in RN
            try {
                if (self.URLSearchParams && (new self.URLSearchParams('foo=bar')).get('foo') === 'bar') {
                    return self.URLSearchParams;
                }
            } catch (e) {
            }
            return null;
        })(),
        isSupportObjectConstructor = nativeURLSearchParams && (new nativeURLSearchParams({a: 1})).toString() === 'a=1',
        // There is a bug in safari 10.1 (and earlier) that incorrectly decodes `%2B` as an empty space and not a plus.
        decodesPlusesCorrectly = nativeURLSearchParams && (new nativeURLSearchParams('s=%2B').get('s') === '+'),
        __URLSearchParams__ = "__URLSearchParams__",
        // Fix bug in Edge which cannot encode ' &' correctly
        encodesAmpersandsCorrectly = nativeURLSearchParams ? (function () {
            var ampersandTest = new nativeURLSearchParams();
            ampersandTest.append('s', ' &');
            return ampersandTest.toString() === 's=+%26';
        })() : true,
        prototype = URLSearchParamsPolyfill.prototype,
        iterable = !!(self.Symbol && self.Symbol.iterator);

    if (nativeURLSearchParams && isSupportObjectConstructor && decodesPlusesCorrectly && encodesAmpersandsCorrectly) {
        return;
    }


    /**
     * Make a URLSearchParams instance
     *
     * @param {object|string|URLSearchParams} search
     * @constructor
     */
    function URLSearchParamsPolyfill(search) {
        search = search || "";

        // support construct object with another URLSearchParams instance
        if (search instanceof URLSearchParams || search instanceof URLSearchParamsPolyfill) {
            search = search.toString();
        }
        this [__URLSearchParams__] = parseToDict(search);
    }


    /**
     * Appends a specified key/value pair as a new search parameter.
     *
     * @param {string} name
     * @param {string} value
     */
    prototype.append = function (name, value) {
        appendTo(this [__URLSearchParams__], name, value);
    };

    /**
     * Deletes the given search parameter, and its associated value,
     * from the list of all search parameters.
     *
     * @param {string} name
     */
    prototype['delete'] = function (name) {
        delete this [__URLSearchParams__] [name];
    };

    /**
     * Returns the first value associated to the given search parameter.
     *
     * @param {string} name
     * @returns {string|null}
     */
    prototype.get = function (name) {
        var dict = this [__URLSearchParams__];
        return this.has(name) ? dict[name][0] : null;
    };

    /**
     * Returns all the values association with a given search parameter.
     *
     * @param {string} name
     * @returns {Array}
     */
    prototype.getAll = function (name) {
        var dict = this [__URLSearchParams__];
        return this.has(name) ? dict [name].slice(0) : [];
    };

    /**
     * Returns a Boolean indicating if such a search parameter exists.
     *
     * @param {string} name
     * @returns {boolean}
     */
    prototype.has = function (name) {
        return hasOwnProperty(this [__URLSearchParams__], name);
    };

    /**
     * Sets the value associated to a given search parameter to
     * the given value. If there were several values, delete the
     * others.
     *
     * @param {string} name
     * @param {string} value
     */
    prototype.set = function set(name, value) {
        this [__URLSearchParams__][name] = ['' + value];
    };

    /**
     * Returns a string containg a query string suitable for use in a URL.
     *
     * @returns {string}
     */
    prototype.toString = function () {
        var dict = this[__URLSearchParams__], query = [], i, key, name, value;
        for (key in dict) {
            name = encode(key);
            for (i = 0, value = dict[key]; i < value.length; i++) {
                query.push(name + '=' + encode(value[i]));
            }
        }
        return query.join('&');
    };

    // There is a bug in Safari 10.1 and `Proxy`ing it is not enough.
    var forSureUsePolyfill = !decodesPlusesCorrectly;
    var useProxy = (!forSureUsePolyfill && nativeURLSearchParams && !isSupportObjectConstructor && self.Proxy);
    /*
     * Apply polifill to global object and append other prototype into it
     */
    Object.defineProperty(self, 'URLSearchParams', {
        value: (useProxy ?
            // Safari 10.0 doesn't support Proxy, so it won't extend URLSearchParams on safari 10.0
            new Proxy(nativeURLSearchParams, {
                construct: function (target, args) {
                    return new target((new URLSearchParamsPolyfill(args[0]).toString()));
                }
            }) :
            URLSearchParamsPolyfill)
    });

    var USPProto = self.URLSearchParams.prototype;

    USPProto.polyfill = true;

    /**
     *
     * @param {function} callback
     * @param {object} thisArg
     */
    USPProto.forEach = USPProto.forEach || function (callback, thisArg) {
        var dict = parseToDict(this.toString());
        Object.getOwnPropertyNames(dict).forEach(function (name) {
            dict[name].forEach(function (value) {
                callback.call(thisArg, value, name, this);
            }, this);
        }, this);
    };

    /**
     * Sort all name-value pairs
     */
    USPProto.sort = USPProto.sort || function () {
        var dict = parseToDict(this.toString()), keys = [], k, i, j;
        for (k in dict) {
            keys.push(k);
        }
        keys.sort();

        for (i = 0; i < keys.length; i++) {
            this['delete'](keys[i]);
        }
        for (i = 0; i < keys.length; i++) {
            var key = keys[i], values = dict[key];
            for (j = 0; j < values.length; j++) {
                this.append(key, values[j]);
            }
        }
    };

    /**
     * Returns an iterator allowing to go through all keys of
     * the key/value pairs contained in this object.
     *
     * @returns {function}
     */
    USPProto.keys = USPProto.keys || function () {
        var items = [];
        this.forEach(function (item, name) {
            items.push(name);
        });
        return makeIterator(items);
    };

    /**
     * Returns an iterator allowing to go through all values of
     * the key/value pairs contained in this object.
     *
     * @returns {function}
     */
    USPProto.values = USPProto.values || function () {
        var items = [];
        this.forEach(function (item) {
            items.push(item);
        });
        return makeIterator(items);
    };

    /**
     * Returns an iterator allowing to go through all key/value
     * pairs contained in this object.
     *
     * @returns {function}
     */
    USPProto.entries = USPProto.entries || function () {
        var items = [];
        this.forEach(function (item, name) {
            items.push([name, item]);
        });
        return makeIterator(items);
    };


    if (iterable) {
        USPProto[self.Symbol.iterator] = USPProto[self.Symbol.iterator] || USPProto.entries;
    }


    function encode(str) {
        var replace = {
            '!': '%21',
            "'": '%27',
            '(': '%28',
            ')': '%29',
            '~': '%7E',
            '%20': '+',
            '%00': '\x00'
        };
        return encodeURIComponent(str).replace(/[!'\(\)~]|%20|%00/g, function (match) {
            return replace[match];
        });
    }

    function decode(str) {
        return str
            .replace(/[ +]/g, '%20')
            .replace(/(%[a-f0-9]{2})+/ig, function (match) {
                return decodeURIComponent(match);
            });
    }

    function makeIterator(arr) {
        var iterator = {
            next: function () {
                var value = arr.shift();
                return {done: value === undefined, value: value};
            }
        };

        if (iterable) {
            iterator[self.Symbol.iterator] = function () {
                return iterator;
            };
        }

        return iterator;
    }

    function parseToDict(search) {
        var dict = {};

        if (typeof search === "object") {
            // if `search` is an array, treat it as a sequence
            if (isArray(search)) {
                for (var i = 0; i < search.length; i++) {
                    var item = search[i];
                    if (isArray(item) && item.length === 2) {
                        appendTo(dict, item[0], item[1]);
                    } else {
                        throw new TypeError("Failed to construct 'URLSearchParams': Sequence initializer must only contain pair elements");
                    }
                }

            } else {
                for (var key in search) {
                    if (search.hasOwnProperty(key)) {
                        appendTo(dict, key, search[key]);
                    }
                }
            }

        } else {
            // remove first '?'
            if (search.indexOf("?") === 0) {
                search = search.slice(1);
            }

            var pairs = search.split("&");
            for (var j = 0; j < pairs.length; j++) {
                var value = pairs [j],
                    index = value.indexOf('=');

                if (-1 < index) {
                    appendTo(dict, decode(value.slice(0, index)), decode(value.slice(index + 1)));

                } else {
                    if (value) {
                        appendTo(dict, decode(value), '');
                    }
                }
            }
        }

        return dict;
    }

    function appendTo(dict, name, value) {
        var val = typeof value === 'string' ? value : (
            value !== null && value !== undefined && typeof value.toString === 'function' ? value.toString() : JSON.stringify(value)
        );

        // #47 Prevent using `hasOwnProperty` as a property name
        if (hasOwnProperty(dict, name)) {
            dict[name].push(val);
        } else {
            dict[name] = [val];
        }
    }

    function isArray(val) {
        return !!val && '[object Array]' === Object.prototype.toString.call(val);
    }

    function hasOwnProperty(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    }

})(typeof global !== 'undefined' ? global : (typeof window !== 'undefined' ? window : this));
Trenord.ui.menu = function () {


    $(".container-submenu .submenu ").show();

    var timeoutContent = null, /*  time mousleave submenu */
        timeoutSelection = null, /*  time selection submenu */
        timeoutMenu = null, /*  time to open submenu */
        currentItem = "", /* current item */
    open = 0;

    $(".submenu .content").mouseover(function () {
        clearTimeout(timeoutContent); /*  reset timeout submenu */
    });

    $(".container-menu #menu .item").mouseover(function () {


        var idItem = $(this).attr("id").replace("item-menu-home", "");

        var HeightImage = 0;
        var HeightRight = 0;

        var imageList = 0;

        Trenord.utility.setCssAuto($("#subMenu" + idItem));

        setTimeout(function () {
            Trenord.utility.resizeHeight($("#subMenu" + idItem));
        }, 50);


        clearTimeout(timeoutContent); /*  reset timeout submenu */
        $("#item-menu-home"+idItem+"").addClass("active");
        $("#subMenu" + idItem + "").show();
        timeoutSelection = setTimeout(function () {
            if (currentItem != idItem) {
                $(".container-menu").addClass("no-shadow");
                $("#menu li a").removeClass("active");
                $(".container-submenu #subMenu" + currentItem + " .content").removeClass(" show-item-content").height(0); /* close submenu */
                $(".mdd-image").hide();
                $("#menu .item-triangle").removeClass(" triangle-active"); /*  remove triangle */
                setTimeout(function () { /*  close old submenu active */

                    HeightRight = Trenord.utility.getMaxofClass(".container-submenu #subMenu" + idItem + " .content .item-submenu ul") +
                        Trenord.utility.getMaxofClass(".container-submenu #subMenu" + idItem + " .content .item-submenu p") +
                        Trenord.utility.getMaxofClass(".container-submenu #subMenu" + idItem + " .content .item-submenu .divider");
                    imageList = $("#subMenu" + idItem + " .content .item-submenu.images .image .overlay").length;
                    if (imageList == 0) {
                        HeightImage = 0;
                    } else {
                        HeightImage = Trenord.utility.sumHeight("#subMenu" + idItem + " .content .item-submenu.images .image");

                    }

                    if (HeightRight < HeightImage) {
                        HeightRight = HeightImage;
                    }
                    open = 1;

                    $("#item-menu-home"+idItem+"").addClass("active");


                    if($("body").hasClass("malpensaStyle")){
                        $(".mdd-image").fadeIn();
                        $(".container-submenu #subMenu" + idItem + " .content").addClass(" show-item-content").height(HeightRight + 200); /* open current submenu */

                    }else{
                        $(".container-submenu #subMenu" + idItem + " .content").addClass(" show-item-content").height(HeightRight + 100); /* open current submenu */

                    }


                    if ($('.container-menu').hasClass('menu-sticky')) {
                        $(".container-menu").addClass(" border-active-menu-sticky");
                    } else {
                        $(".container-menu").addClass(" border-active-menu");
                    }


                    $(".container-menu #menu #item-menu-home" + idItem + "").next("span").addClass(" triangle-active");
                    currentItem = idItem; /* update item */
                }, 150);
            }
        }, 150);
    }).mouseleave(function () {

        clearTimeout(timeoutSelection); /*  stop  opening submenu */
        timeoutMenu = setTimeout(function () {
            open = 0;
            $("#menu li a").removeClass("active");
            $(".container-menu").removeClass("no-shadow");
            $(".container-submenu .submenu .content").removeClass(" show-item-content").height(0);
            $(".mdd-image").hide();
            $("#menu .item-triangle").removeClass(" triangle-active");
            currentItem = "";
            if ($('.container-menu').hasClass('menu-sticky')) {
                $(".container-menu").removeClass(" border-active-menu-sticky");
            } else {
                $(".container-menu").removeClass(" border-active-menu");
            }
            currentItem = "";
        }, 270);
    });
    $(".container-submenu .submenu .content").mouseover(function () {
        clearTimeout(timeoutMenu); /*  stop  closing submenu */
        open = 1;
    }).mouseleave(function () {
        timeoutContent = setTimeout(function () { /*  close submenu */
            open = 0;
            $("#menu li a").removeClass("active");
            $(".container-menu").removeClass("no-shadow");
            $(".container-submenu .submenu .content").removeClass(" show-item-content").height(0);
            $(".mdd-image").hide();
            if ($('.container-menu').hasClass('menu-sticky')) {
                $(".container-menu").removeClass(" border-active-menu-sticky");
            } else {
                $(".container-menu").removeClass(" border-active-menu");
            }
            $("#menu .item-triangle").removeClass(" triangle-active");
            currentItem = "";
        }, 300);
    });

    $(window).scroll(function (event) {
        var scroll = $(window).scrollTop();
        if(Trenord.utility.isTablet() || Trenord.utility.isMobile()){
            var scrollMobile =   $(window).scrollTop();

              if (scrollMobile > 80) {
                  $(".header-top .background-top").css("position","fixed").css("top","0");
              }else{
                  $(".header-top .background-top").css("position","relative").css("top","0");
              }

              if(scrollMobile == 0){
                  $(".header-top .background-top").css("position","relative").css("top","0");

              }

          }else{
              /* $(".header-top .background-top").css("position","relative").css("top","0").hide(); */
          }


        if ($(".container-alert").length > 0) {
          if (scroll > $(".container-alert").height() + 50 ) {
            $(".logo-sticky").css("display", "inline-block");

            if (open == 1) {
                $(".container-menu").removeClass(" border-active-menu");
                $(".container-menu").addClass(" border-active-menu-sticky");
            } else {
                $(".container-menu").removeClass(" border-active-menu");
                $(".container-menu").removeClass(" border-active-menu-sticky");
            }

            $(".container-menu").addClass("menu-sticky");
            $(".container-submenu").addClass("submenu-sticky");
            $("#menu li a").addClass("sticky");
            $("#menu li a").addClass("sticky");
            $(".item-triangle").addClass("sticky");


            $("#user-icon-desk path").css({fill: "#ffffff"});
            $("#search-icon-desk path").css({fill: "#ffffff"});


            if(Trenord.utility.isTablet() || Trenord.utility.isMobile()){
              var scrollMobile =   $(window).scrollTop();

                if (scrollMobile > 80) {
                    $(".header-top .background-top").css("position","fixed").css("top","0");
                }else{
                    $(".header-top .background-top").css("position","relative").css("top","0");
                }

                if(scrollMobile == 0){
                    $(".header-top .background-top").css("position","relative").css("top","0");

                }

            }else{
                /* $(".header-top .background-top").css("position","relative").css("top","0").hide(); */
            }


        } else {

            if(Math.max(document.documentElement.clientWidth, window.innerWidth || 0) > 1024){
                $(".header-top .background-top").css("position","relative").css("top","0").show();
            }

            $(".logo-sticky").css("display", "none");

            if (open == 1) {
                $(".container-menu").addClass(" border-active-menu");
                $(".container-menu").removeClass(" border-active-menu-sticky");
            } else {
                $(".container-menu").removeClass(" border-active-menu");
                $(".container-menu").removeClass(" border-active-menu-sticky");
            }

            $("#user-icon-desk path").css({fill: "#333333"});
            $("#search-icon-desk path").css({fill: "#333333"});

            $("#menu li a").removeClass("sticky");
            $(".item-triangle").removeClass("sticky");
            $(".container-menu").removeClass("menu-sticky");
            $(".container-submenu").removeClass("submenu-sticky");

        }
        } else {
               if (scroll > 70) {
            $(".logo-sticky").css("display", "inline-block");

            if (open == 1) {
                $(".container-menu").removeClass(" border-active-menu");
                $(".container-menu").addClass(" border-active-menu-sticky");
            } else {
                $(".container-menu").removeClass(" border-active-menu");
                $(".container-menu").removeClass(" border-active-menu-sticky");
            }

            $(".container-menu").addClass("menu-sticky");
            $(".container-submenu").addClass("submenu-sticky");
            $("#menu li a").addClass("sticky");
            $("#menu li a").addClass("sticky");
            $(".item-triangle").addClass("sticky");


            $("#user-icon-desk path").css({fill: "#ffffff"});
            $("#search-icon-desk path").css({fill: "#ffffff"});


            if(Trenord.utility.isTablet() || Trenord.utility.isMobile()){
              var scrollMobile =   $(window).scrollTop();

                if (scrollMobile > 80) {
                    $(".header-top .background-top").css("position","fixed").css("top","0");
                }else{
                    $(".header-top .background-top").css("position","relative").css("top","0");
                }

                if(scrollMobile == 0){
                    $(".header-top .background-top").css("position","relative").css("top","0");

                }

            }else{
                /* $(".header-top .background-top").css("position","relative").css("top","0").hide(); */
            }


        } else {

            if(Math.max(document.documentElement.clientWidth, window.innerWidth || 0) > 1024){
                $(".header-top .background-top").css("position","relative").css("top","0").show();
            }

            $(".logo-sticky").css("display", "none");

            if (open == 1) {
                $(".container-menu").addClass(" border-active-menu");
                $(".container-menu").removeClass(" border-active-menu-sticky");
            } else {
                $(".container-menu").removeClass(" border-active-menu");
                $(".container-menu").removeClass(" border-active-menu-sticky");
            }

            $("#user-icon-desk path").css({fill: "#333333"});
            $("#search-icon-desk path").css({fill: "#333333"});

            $("#menu li a").removeClass("sticky");
            $(".item-triangle").removeClass("sticky");
            $(".container-menu").removeClass("menu-sticky");
            $(".container-submenu").removeClass("submenu-sticky");

        }
        }

     
    });


    $(".submenu .content .item-submenu.images .image .overlay")
        .mouseover(function () {
            $(this).prev().prev().css("filter", "grayscale(100%)");
        })
        .mouseout(function () {
            $(this).prev().prev().css("filter", "grayscale(0%)");
        });

    $(".submenu .content .item-submenu.images .image .title")
        .mouseover(function () {
            $(this).prev().css("filter", "grayscale(100%)");
        })
        .mouseout(function () {
            $(this).prev().css("filter", "grayscale(0%)");
        });

    $(".submenu .content .item-submenu.images .image .arrow-next")
        .mouseover(function () {
            $(this).prev().prev().prev().css("filter", "grayscale(100%)");
        })
        .mouseout(function () {
            $(this).prev().prev().prev().css("filter", "grayscale(0%)");
        });

} /*  menuHome */

Trenord.ui.carouselNews = function() {
  var currnetel = null;
  $(".news-carousel").on("changed.owl.carousel", function(property) {
    if (property.item.index === 0) {
      $(".slider_nav .next_news").removeClass("hidden");
      $(".slider_nav .next_news").show();
      $(".slider_nav .prev_news").addClass("hidden");
      $(".slider_nav .prev_news").hide();
    } else {
      currnetel = property.item.index + property.page.size;
      // last element
      if (currnetel === property.item.count) {
        $(".slider_nav .next_news").addClass("hidden");
        $(".slider_nav .next_news").hide();
      } else {
        $(".slider_nav .next_news").removeClass("hidden");
        $(".slider_nav .next_news").show();
      }
    }

    if (property.item.index > 0) {
      $(".slider_nav .prev_news").removeClass("hidden");
      $(".slider_nav .prev_news").show();
    }
  });

  $(".news-carousel-container-fluid").hover(
    function() {
      if ($(".news-carousel .item").length > 3) {
        $(".slider_nav .next_news").show();
        $(".slider_nav .prev_news").show();
        $(".slider_nav .next_news").css("opacity", "1");
        $(".slider_nav .prev_news").css("opacity", "1");
      }
    },
    function() {
      $(".slider_nav .next_news").hide();
      $(".slider_nav .prev_news").hide();
      $(".slider_nav .next_news").css("opacity", "0");
      $(".slider_nav .prev_news").css("opacity", "0");
    }
  );

  $(".news-carousel")
    .on(
      "initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel",
      function(event) {
        var item = 0;
        var activeItem = 0;

        $(".news-carousel .owl-item").each(function() {
          item++;
        });

        $(".news-carousel .owl-item.active").each(function() {
          activeItem++;
        });

        if (item === activeItem) {
          $(".next_news").hide();
          $(".prev_news").hide();
        } else {
          $(".next_news").show();
          $(".prev_news").show();
        }
      }
    )
    .owlCarousel({
      items: 3,
      loop: false,
      mousedrag: true,
      margin: 65,
      dots: true,
      center: false,
      nav: false,
      responsiveClass: true,
      responsive: {
        0: {
          mousedrag: true,
          margin: 0,
          loop: false,
          items: 1,
          stagePadding: 60
        },

        400: {
          mousedrag: true,
          margin: 0,
          loop: false,
          items: 1,
          stagePadding: 80
        },

        600: {
          mousedrag: true,
          margin: 0,
          loop: false,
          items: 1,
          stagePadding: 100
        },

        767: {
          mouseDrag: true,
          items: 1,
          margin: 10,
          stagePadding: 40,
          loop: false
        },
        768: {
          mouseDrag: true,
          items: 3,
          margin: 20,
          stagePadding: 0,
          loop: false
        },
        1024: {
          mousedrag: true,
          items: 3,
          margin: 10,
          dots: true,
          loop: false
        },
        1280: {
          mousedrag: true,
          items: 3,
          margin: 10,
          dots: true,
          loop: false
        },
        1440: {
          mousedrag: true,
          items: 3,
          margin: 10,
          dots: true,
          loop: false
        },
        1680: {
          mousedrag: true,
          items: 3,
          margin: 10,
          dots: true,
          loop: false
        },
        2800: {
          mousedrag: true,
          items: 3,
          margin: 20,
          dots: true,
          loop: false
        }
      }
    });

  /*
var item =0;
var activeItem = 0;

    $(".news-carousel .owl-item").each(function() {
        item++;
    });

    $(".news-carousel .owl-item.active").each(function() {
        activeItem++;
    });

    if(item == activeItem){
        $(".next_news").hide();
        $(".prev_news").hide();
    }else{
        $(".next_news").show();
        $(".prev_news").show();
    }
*/

  //collegamnento prev e next news

  var carousel_news = $(".news-carousel");

  carousel_news.owlCarousel();
  //Custom Navigation Events
  $(".next_news").click(function() {
    carousel_news.trigger("next.owl.carousel");
  });
  $(".prev_news").click(function() {
    carousel_news.trigger("prev.owl.carousel");
  });
};

Trenord.ui.carouselPartners = function () {



    $(".partner-carousel").on('changed.owl.carousel', function (property) {
        if (property.item.index == 0) {

            $(".slider_nav .prev_partner").addClass("hidden");
            $(".slider_nav .next_partner").removeClass("hidden");

        } else {

            var currnetel = property.item.index + property.page.size;
            // last element
            if (currnetel == property.item.count) {
                $(".slider_nav .next_partner").addClass("hidden");
                $(".slider_nav .prev_partner").removeClass("hidden");


            } else {
                $(".slider_nav .next_partner").removeClass("hidden");
                $(".slider_nav .prev_partner").removeClass("hidden");

            }
        }
    });

    $(".container-carousel-partner").hover(
        function () {
            $(".slider_nav .next_partner").css("opacity", "1");
            $(".slider_nav .prev_partner").css("opacity", "1");
        }, function () {
            $(".slider_nav .next_partner").css("opacity", "0");
            $(".slider_nav .prev_partner").css("opacity", "0");

        }
    );

    $(".partner-carousel").on('initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel', function (event) {
        var item =0;
        var activeItem = 0;

        $(".partner-carousel .owl-item").each(function() {
            item++;
        });

        $(".partner-carousel .owl-item.active").each(function() {
            activeItem++;
        });

        if(item == activeItem){
            $(".next_partner").hide();
            $(".prev_partner").hide();
        }else{
            $(".next_partner").show();
            $(".prev_partner").show();
        }
    }).owlCarousel({
        items: 3,
        loop: false,
        dots: false,
        center: true,
        mousedrag:true,
        nav: false,
        responsive: {
            0: {
                items: 2,
                margin: 40,
                mousedrag:true,
                stagePadding: 50,

            },
            600: {
                items: 4,
                margin: 40,
                mousedrag:true,
                stagePadding: 50,
            },
            768: {
                items: 4,
                margin: 40,
                mousedrag:true,
                stagePadding: 50,
            },
            1024: {
                items: 5,
                loop: false,
                margin: 50,

                center: false,
                responsive: false,
                responsiveClass: false,
                stagePadding: 0
            },
            2800: {
                items: 6,
                loop: false,
                margin: 50,

                center: false,
                responsive: false,
                responsiveClass: false,
                stagePadding: 0
            }
        }
    });
    //collegamnento prev e next partner
    var partner = $(".partner-carousel");
    partner.owlCarousel();
    //Custom Navigation Events
    $(".next_partner").click(function () {
        partner.trigger('next.owl.carousel');
    });
    $(".prev_partner").click(function () {
        partner.trigger('prev.owl.carousel');
    });

}

Trenord.ui.inEvidenza = function () {

    if (window.innerWidth <= 1023) {
        $(".moveable").appendTo(".container-grid .grid3 .columns2");
    }

    if (window.innerWidth >= 1024) {
        $(".moveable").appendTo(".container-grid .grid3 .columns1");
    }

    var currentClass = true;

    $('.filter-wrap').owlCarousel({
        loop: false,
        margin: 20,
        dots: false,
        center: false,
        nav: false,
        navigation: false,
        responsiveClass: true,
        items: 5,
        mouseDrag: true,
        autoWidth: true,
        pullDrag: false,
        freeDrag: false,
        rewind: false,
        dragEndSpeed: false
    });


}



Trenord.ui.searchNav = {

    currentPage: 0,
    sections: [],
    sword: "",
    searchType: 1,
    sortOrder: "rank_flag",
    resultCount: 0,
    suggestInterval: null,

    initEvents: function () {

        $("#list-select-serp-mobile").click(function () {
            $(".container-box-order").fadeIn();
        });

        $(".container-box-order .opacity, .container-box-order .list-order ul li,.close-list-order").click(function () {
            $(".container-box-order").fadeOut();
        });

        $('#search-term-mobile').bind('input', function () {
            $("#search-term").val($(this).val());
        });

        $(".search-filter").click(function () {


            var filterVal = $(this).attr('id');

            Trenord.ui.searchNav.toggleSection(filterVal);

            Trenord.ui.searchNav.updateResult();

        });

        $("#search-order").on("change", function () {
            Trenord.ui.searchNav.sortOrder = $(this).val();
            Trenord.ui.searchNav.updateResult();
        });

        var isMalpensa = false;
        if(window.location.hostname && (window.location.hostname.includes("malpensaexpress.it")  || window.location.hostname.includes("malpensaexpress-upgrade")) ) {
            isMalpensa = true;
        }

        if(!isMalpensa) {
            $(".yext-search-element").css("display", "block");
            $("#openSearchNav").css("display", "none");
            $(".container-user.container-search").addClass("yext-search-container");

            $("#openSearchNavMob").click(function () {
                $(".yext-search-element-mob.yxt-SearchBar-wrapper").addClass("c-active");
                $("#openSearchNavMob").css("display", "none");
                $("#closeSearchBarMob").css("display", "block");
            });
    
            $("#closeSearchBarMob").click(function () {
                $(".yext-search-element-mob.yxt-SearchBar-wrapper").removeClass("c-active");
                $("#closeSearchBarMob").css("display", "none");
                $("#openSearchNavMob").css("display", "block");
            });
        } else {
            $("#openSearchNav").css("display", "inline-block");
            $(".yext-search-element").css("display", "none");


            $("#openSearchNav , #openSearchNavMob ").click(function () {
                Trenord.ui.searchNav.loadUserRecent();
    
                $("#Search").fadeIn(300);
                $("body,html").css("overflow", "hidden");
                $("#search-term-mobile").focus();
            })
        }

        $("#closeSearchNav").click(function () {
            $("#Search").fadeOut(300);
            $("body,html").css("overflow", "auto");
        });

        $('#search-term, #search-term-mobile').on('keyup', function (e) {

            var searchTerm = $(this).val();
            clearTimeout(Trenord.ui.searchNav.suggestInterval);

            Trenord.ui.searchNav.suggestInterval = setTimeout(function () {

                if (e.keyCode == 13) {
                    Trenord.ui.searchNav.sendForm();
                    clearTimeout(Trenord.ui.searchNav.suggestInterval);
                } else {
                    Trenord.ui.searchNav.suggest(searchTerm);
                }

            }, 350);


        });

        $('#search-term-mobile').on('keyup', function (e) {

            //todo: da implementare parte mobile
            Trenord.ui.searchNav.suggest($(this).val());
        });


        $(".close-search-mobile").click(function () {
            $("#Search").fadeOut(300);
            $("body,html").css("overflow", "auto");
        });

        $(".reset-search").click(function () {
            $('#search-term-mobile').val("");
            $(".reset-search").hide(200);
            $(".search-items-mobile .item").fadeOut(200);
            $(".recent-items-mobile").fadeIn(300);
            $(".no-result-mobile ").hide(200);
        });

    },

    suggest: function (string) {

        Trenord.ui.searchNav.sword = string;

        if (string.length > 2) {

            Trenord.ui.searchNav.startSuggestion();

            $.get('/rest/render/suggest',
                {
                    sword: string,
                    searchType: Trenord.ui.searchNav.searchType,
                    L: Trenord.globals.currentLanguage
                },
                function (data) {



                    Trenord.ui.searchNav.showSuggestionResult(data);

                });


        } else {
            Trenord.ui.searchNav.notStartSuggestion();
        }

    },

    updateResult: function (append) {

        if (!append) {
            $("#search-result").hide();
            Trenord.ui.searchNav.currentPage = 0;
        }

        $("#search-skeleton").show();

        $.get('/rest/render/search',
            {
                sword: Trenord.ui.searchNav.sword,
                pointer: Trenord.ui.searchNav.currentPage,
                sections: Trenord.ui.searchNav.sections,
                searchType: Trenord.ui.searchNav.searchType,
                sortOrder: Trenord.ui.searchNav.sortOrder,
                L: Trenord.globals.currentLanguage

            },

            function (data) {

                if (append) {

                    $("#search-result").append(data.message);

                    if ((Trenord.ui.searchNav.currentPage + 1) >= (Trenord.ui.searchNav.resultCount / 10)) {
                        $(".container-mostra-altri").fadeOut();
                    } else {
                        $(".container-mostra-altri").fadeIn();
                    }

                } else {

                    //viene aggiornato il valore dei risultati
                    //la variabile viene usata nel template serch del content serpform

                    $("#search-result").html(data.message);

                    if (Trenord.ui.searchNav.resultCount <= 10) {
                        $(".container-mostra-altri").hide();
                    } else {
                        $(".container-mostra-altri").show();
                    }
                }

                $(".search-result-count").html(Trenord.ui.searchNav.resultCount);
                $("#search-result").show();
                $("#search-skeleton").hide();

            }
        );


    },

    nextPage: function () {

        Trenord.ui.searchNav.currentPage++;
        Trenord.ui.searchNav.updateResult(true);
    },

    sendForm: function (section) {

        if (section != "" && section != null) {
            $("#search-form-section").val(section);
        }

        $("#search-form").submit();
    },

    toggleSection: function (section) {

        if (Trenord.ui.searchNav.sections.indexOf(section) >= 0) {
            Trenord.ui.searchNav.sections.splice($.inArray(section, Trenord.ui.searchNav.sections), 1);
        } else {

            if (section != "" && section != null && section != undefined) {
                Trenord.ui.searchNav.sections.push(section);
            }
        }

    },

    loadUserRecent: function () {

        if (Trenord.user.isLogged()) {

            var bookmarkUrl = Trenord.utility.urlParam('bookmark');

            //questa configurazione non è ottimale ma comprende id=1 trenord e id=2 malpensaexpress
            //todo: rimodulare con define dei domini recuperati da BE
            if (bookmarkUrl && $.isNumeric(Trenord.globals.currentPid) && Trenord.globals.currentPid > 2) {
                Trenord.ui.bookmarks.toggle('page', Trenord.globals.currentPid, false, 'page');
            }

            Trenord.ui.searchNav.startSuggestion();

            $.get("/rest/render/user-recent-search", function (data) {

                Trenord.ui.searchNav.showSuggestionResult(data);

            });
        }

    },

    startSuggestion: function () {

        if (Trenord.utility.isTablet() || Trenord.utility.isMobile()) {
            $(".search-items-mobile").hide();
            $("#suggest-search-skeleton-mobile").show();
        } else {
            $("#suggest-search-result").hide();
            $("#suggest-search-skeleton").show();

        }


        $("#info-search-bar").fadeIn("300");
        $(".arrow-search").show(200);
        $(".recent-items").fadeOut(200);
    },


    notStartSuggestion: function () {

        $(".arrow-search").hide(200);
        $("#info-search-bar").fadeOut("300");
        $(".search-items .item").fadeOut(200);
        $(".recent-items").fadeIn(300);
        $(".no-result ").fadeOut(200);
    },

    showSuggestionResult: function (data) {
       var term = $("#search-term").val();

        if (Trenord.utility.isTablet() || Trenord.utility.isMobile()) {
            $(".search-items-mobile").show();
            $("#suggest-search-skeleton-mobile").hide();
            $(".search-items-mobile").html(data.message);

            $(".search-items-mobile a").click(function() {
                dataLayer.push({
                    'event': 'searchSuggestion',
                    'sWord': term
                });
            })
        } else {
            $("#suggest-search-result").show();
            $("#suggest-search-skeleton").hide();
            $("#suggest-search-result").html(data.message);

            $("#suggest-search-result a").click(function() {
                dataLayer.push({
                    'event': 'searchSuggestion',
                    'sWord': term
                });
            })
        }
    }
}



Trenord.ui.sideNav = function () {

  $("#openNav").click(function () {
    $("#Sidenav").fadeIn(300);
    $("body,html").css("overflow", "hidden");
    $("body").css("position", "fixed");

  });


  $("#closeNav").click(function () {
    $("#Sidenav").fadeOut(300);
    $("body").css("position", "initial");
 $("body,html").css("overflow", "initial");
  });



  var idItem = "";
  var lastItem = "";
  $(".content-sidenav .title-item, .content-sidenav .icon-container .icon").click(function () {
    $("#closeNav").fadeOut();
    setTimeout(function () {
      $("#backNav").fadeIn();
    }, 100);
    var idItem = "";

    if ($(this).hasClass('title-item')) {
      idItem = $(this).attr("id").split("title-sidenav");
    } else {
      idItem = $(this).attr("id").split("icon-sidenav");
    }

    if ($('#submenu-sidenav' + idItem[1] + ':visible').length == 0) {
      $(".content-sidenav .icon-container .icon").css("pointer-events", "none");
      $(".submenu-sidenav").fadeOut();

      $(".content-sidenav .title-container").addClass(" submenu-active");
      $(".content-sidenav .title-item").fadeOut(100);
      $(".content-sidenav  .title-profile").fadeOut(100);
      $(".content-sidenav .icon-container .icon").removeClass("icon-active");
      $("#icon-sidenav" + idItem[1] + "").addClass("icon-active");
      $(".content-sidenav .icon-container .icon svg").removeClass("img-active");
      $("#icon-sidenav" + idItem[1] + "").find("svg").addClass("img-active");
      $("#icon-sidenav" + idItem[1] + "").find("svg").removeClass("img-opacity");
      $(".content-sidenav .icon-container .icon ").each(function (index) {
        var idLoop = $(this).attr("id").split("icon-sidenav");
        if (idLoop != idItem[1]) {
          $(this).find("svg").addClass("img-opacity");
        }
      });
      setTimeout(function () {
        $("#submenu-sidenav" + idItem[1] + "").fadeIn(100);
        $(".content-sidenav .icon-container .icon").css("pointer-events", "auto");
      }, 400);

    }
    lastItem = idItem[1];

  });

  $("#backNav").click(function () {
    $("#backNav").fadeOut();
    setTimeout(function () {
      $("#closeNav").fadeIn();
    }, 100);
    var idItem = "";
    $(".submenu-sidenav").css("display", "none");
    $(".content-sidenav .icon-container .icon").removeClass("icon-active");
    $(".content-sidenav .title-container").removeClass("submenu-active");
    $(".content-sidenav .icon-container .icon svg").removeClass("img-active");
    $(".content-sidenav .icon-container .icon svg").removeClass("img-opacity");
    $(".content-sidenav .title-container, .content-sidenav .title-item, .content-sidenav .title-container .title-profile ").fadeIn(200);
  });
}

Trenord.ui.sliderHome = function() {
  var owl = $("#slider-home");
  owl.on("changed.owl.carousel", function(e) {
    var indexMobileCaption = e.item.index + 1;
    $("#slider-home").trigger("to.owl.carousel", e.item.index);
    $(".container-caption-mobile .caption")
      .removeClass(" open-caption")
      .addClass("hide-caption");
    $(".container-caption-mobile #caption" + indexMobileCaption + "")
      .removeClass("hide-caption")
      .addClass("open-caption");
  });

  var idDot = 0;
  //swipe

  var maxTime = 1000,
    // allow movement if < 1000 ms (1 sec)
    maxDistance = 50,
    // swipe movement of 50 pixels triggers the swipe
    target = $(".container-caption-mobile"),
    startX = 0,
    startTime = 0,
    touch = "ontouchend" in document,
    startEvent = touch ? "touchstart" : "mousedown",
    moveEvent = touch ? "touchmove" : "mousemove",
    endEvent = touch ? "touchend" : "mouseup";
  /*
  target.bind(startEvent, function(e) {
      // prevent image drag (Firefox)
      e.preventDefault();
      startTime = e.timeStamp;
      startX = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX;
  }).bind(endEvent, function(e) {
      startTime = 0;
      startX = 0;
  }).bind(moveEvent, function(e) {
      e.preventDefault();
      var currentX = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX,
          currentDistance = (startX === 0) ? 0 : Math.abs(currentX - startX),
          // allow if movement < 1 sec
          currentTime = e.timeStamp;
      if (startTime !== 0 && currentTime - startTime < maxTime && currentDistance > maxDistance) {
          if (currentX < startX) {
              // swipe left code here
              $('#slider-home').trigger('to.owl.carousel', idDot - 1);
          }
          if (currentX > startX) {
              // swipe right code here
              $('#slider-home').trigger('to.owl.carousel', idDot + 1);
          }
          startTime = 0;
          startX = 0;
      }
  }); */

  //show first
  $(".container-tab .tab:first-child a").addClass("active");
  $("#carousel-custom-dots li:first-child i")
    .removeClass(" fa-circle-o")
    .addClass(" fa-circle");
  $(".container-caption-mobile div:first-child").removeClass("hide-caption");

  //init slider home
  $("#slider-home").owlCarousel({
    animateOut: "fadeOut",
    animateIn: "fadeIn",
    items: 1,
    autoPlay: false,
    autoWidth: false,
    autoplayHoverPause: false,
    navigation: false,
    moumouseDrag: false,
    loop: false,
    dotsContainer: "#carousel-custom-dots"
  });

  if ($(window).width() >= 1024) {
    $(".main-tab .container-tab").fadeIn("50");
  }

  //nascondo se c'è solo un elemento
  if ($("#slider-home .owl-item").length === 1) {
    //There is one image
    $("#carousel-custom-dots").hide();
  }

  $(".floating-button").click(function() {
    $("html, body").animate(
      {
        scrollTop: $(".container-ticket").offset().top - 100
      },
      300
    );
  });

  //dots mobile
  $("#carousel-custom-dots li i").click(function() {
    $("#carousel-custom-dots li i").css("pointer-events", "none");
    idDot = $(this)
      .attr("id")
      .replace("dot", "");

    if ($(".container-tab .container-caption .caption").length == 3) {
         $("#slider-home").trigger("to.owl.carousel", idDot - 1 );
      } else {
        if ($(".container-tab .tab:first-child a").attr("id").replace("tab", "") == idDot) {
             $("#slider-home").trigger("to.owl.carousel", 0 );
        } else {
           $("#slider-home").trigger("to.owl.carousel", 1 );
          }
      }
    $("#carousel-custom-dots li i")
      .removeClass("fa-circle")
      .addClass("fa-circle-o");
    $(this)
      .removeClass("fa-circle-o")
      .addClass("fa-circle");
    //desk tab
    $(".container-tab .tab a").removeClass("active");
    $(".container-tab .tab #tab" + idDot + "").addClass("active");
    if (Trenord.globals.TabControlMobile != idDot) {
      $("#caption" + Trenord.globals.TabControlMobile + "")
        .removeClass(" open-caption")
        .addClass("hide-caption"); //desk
      $(
        ".container-caption-mobile #caption" +
          Trenord.globals.TabControlMobile +
          ""
      )
        .removeClass(" open-caption")
        .addClass("hide-caption");
      setTimeout(function() {
        // close old submenu active
        $("#caption" + idDot + "")
          .removeClass("hide-caption")
          .addClass("open-caption"); //desk
        $(".container-caption-mobile #caption" + idDot + "")
          .removeClass("hide-caption")
          .addClass("open-caption");
        $("#carousel-custom-dots li i")
          .css("pointer-events", "auto")
          .css("pointer-events", "initial");
      }, 300);
      Trenord.globals.TabControlMobile = idDot;
      Trenord.globals.TabControl = idDot;
    } else {
      $("#carousel-custom-dots li i")
        .css("pointer-events", "auto")
        .css("pointer-events", "initial");
    }
  });

  //mostro il primo
  $(".container-caption .caption:first-child").removeClass(" hide-caption");
  $(".container-caption .caption:first-child").addClass(" open-caption");
  $(".container-caption-mobile div:first-child").removeClass(" hide-caption");
  //init height slider
  $(".container-tab").ready(function() {
    /*       var heightContainerSlider = $(".owl-stage-outer").height();
            $(".container-tab").height(heightContainerSlider);
            $(".owl-height").height(heightContainerSlider);*/
  });

  //tab slider
  $(".container-tab .tab a").click(function() {
    var hCaption = $(
      ".container-tab .container-caption .open-caption"
    ).height();
    //   $(".container-tab .container-caption").height(hCaption);

    $(".container-tab .tab a").removeClass("active");
    $(this).addClass("active");
    var idTab = $(this)
      .attr("id")
      .replace("tab", "");
    //mob dot
    $("#carousel-custom-dots li i")
      .removeClass("fa-circle")
      .addClass("fa-circle-o");
    $("#carousel-custom-dots li #dot" + idTab + "")
      .removeClass("fa-circle-o")
      .addClass("fa-circle");
    if (Trenord.globals.TabControl != idTab) {
      setTimeout(function() {
        //mob
        $(".container-caption-mobile .caption")
          .removeClass(" open-caption")
          .addClass("hide-caption"); //mob

        $(
          ".container-caption-mobile #caption" +
            Trenord.globals.TabControlMobile +
            ""
        )
          .removeClass(" open-caption")
          .addClass("hide-caption"); //mob

        //desk

        $("#caption" + Trenord.globals.TabControl + "")
          .removeClass(" open-caption")
          .addClass("hide-caption");
        Trenord.globals.TabControl = idTab;
        Trenord.globals.TabControlMobile = idTab;
      }, 200);
      setTimeout(function() {
        //mob
        $(".container-caption-mobile #caption" + idTab + "")
          .removeClass("hide-caption")
          .addClass("open-caption");
        //desk
        $(".container-tab .container-caption #caption" + idTab + "")
          .removeClass("hide-caption")
          .addClass("open-caption");
      }, 200);



      if ($(".container-tab .container-caption .caption").length == 3) {
         $("#slider-home").trigger("to.owl.carousel", idTab - 1 );
      } else {
        if ($(".container-tab .tab:first-child a").attr("id").replace("tab", "") == idTab) {
             $("#slider-home").trigger("to.owl.carousel", 0 );
        } else {
           $("#slider-home").trigger("to.owl.carousel", 1 );
          }
      }

      
      
/*       switch (idTab) {
  case "0":
   
    break;
  case "1":
    $("#slider-home").trigger("to.owl.carousel", idTab - 1 );
    break;
  case "2":
    $("#slider-home").trigger("to.owl.carousel", idTab - 1  );
    break;
  case "3":
    $("#slider-home").trigger("to.owl.carousel", idTab - 1 );
    break;
} */

    
      /*      $(".container-tab .container-caption .caption").addClass("hide-caption", function() {
                          $(".container-tab .container-caption  .caption").hide("", function() {

                          });
                        });*/
    }
  });

  /* covid disclaimer popup on Home Page
  var cleanedHref = window.location.href.replace('/en/','/');
  if(cleanedHref.endsWith("/")) {
      cleanedHref = cleanedHref.slice(0,-1);
  } 
  if(cleanedHref === "https://test.trenord.it" || 
      cleanedHref === "https://stg.trenord.it" ||
      cleanedHref === "https://www.trenord.it" ||
      cleanedHref === "https://local.trenord.it:8443"
  ) {
    Trenord.popUpMessage.openWithBackgroundTransparent("covid", "Attenzione", "Per le assenze di personale dovute alla pandemia, le soluzioni proposte possono subire variazioni o cancellazioni. Segui l’andamento Real Time sull’App Trenord (<a href=\"https://play.google.com/store/apps/details?id=it.nordcom.app\">Android</a> e <a href=\"https://apps.apple.com/it/app/trenord/id973483529\">iOS</a>).");
  }*/
};

Trenord.ui.tabFooterTop = function() {

  if($(window).width() >= 768){
      $(".container-top-list .row .icon-list").css('display', '');
      $(".container-top-list .row .title-list ").css('display', '');
      $(".container-top-list .row .container-list").css('display', '');

  }

  var lastIdFooterTab = 2;
  $(".icon-list").click(function() {
    idList = $(this).attr("id").replace("icon-list", "");
    if (idList != lastIdFooterTab) {


      heightCont = $("#list" + lastIdFooterTab + "").outerHeight();
      $(".min-margin-list").css("min-height", heightCont);
      $("#title-list" + lastIdFooterTab + "").hide(50);
      $("#list" + lastIdFooterTab + "").hide(50);
      $(".container-top-list .row #icon-list" + lastIdFooterTab + " img").removeClass("opacity-active").addClass("opacity-disable");
      setTimeout(function() { /*  close old submenu active */
        $(".container-top-list .row #icon-list" + idList + " img").removeClass("opacity-disable").addClass("opacity-active");
        $("#title-list" + idList + "").show();
        $("#list" + idList + "").show();
      }, 100);
      lastIdFooterTab = idList;
    }
  });
}

Trenord.ui.carosuelAgevolazioniSupplementi = function () {



    $(".agevolazioni-supplementi-carousel").on('changed.owl.carousel', function (property) {
        if (property.item.index == 0) {

            $(".slider_nav .prev_agevolazioni_supplementi").addClass("hidden");
            $(".slider_nav .next_agevolazioni_supplementi").removeClass("hidden");

        } else {

            var currnetel = property.item.index + property.page.size;
            // last element
            if (currnetel == property.item.count) {
                $(".slider_nav .next_agevolazioni_supplementi").addClass("hidden");
                $(".slider_nav .prev_agevolazioni_supplementi").removeClass("hidden");


            } else {
                $(".slider_nav .next_agevolazioni_supplementi").removeClass("hidden");
                $(".slider_nav .prev_agevolazioni_supplementi").removeClass("hidden");

            }
        }
    });

    $(".agevolazioni-supplementi-carousel").on('initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel', function (event) {
        var item =0;
        var activeItem = 0;


        $(".container-agevolazioni-supplementi").hover(
            function () {
                $(".slider_nav .next_agevolazioni_supplementi").css("opacity", "1");
                $(".slider_nav .prev_agevolazioni_supplementi").css("opacity", "1");
            }, function () {
                $(".slider_nav .next_agevolazioni_supplementi").css("opacity", "0");
                $(".slider_nav .prev_agevolazioni_supplementi").css("opacity", "0");

            }
        );



        $(".agevolazioni-supplementi-carousel .owl-item").each(function() {
            item++;

        });

        $(".agevolazioni-supplementi-carousel .owl-item.active").each(function() {
            activeItem++;

        });


        if (item === activeItem){
            $(".next_agevolazioni_supplementi").hide();
            $(".prev_agevolazioni_supplementi").hide();
        }else{
            $(".next_agevolazioni_supplementi").show();
            $(".prev_agevolazioni_supplementi").show();
        }


    }).owlCarousel({
        items: 3,
        loop: false,
        margin: 65,
        dots: true,
        center: false,
        nav: false,
        mousedrag:true,
        responsiveClass: true,
        responsive: {
            320: {
                mousedrag:true,
                margin: 0,
                loop: false,
                items: 1,
                stagePadding: 60
            },

            600: {
                mousedrag:true,
                margin: 0,
                loop: false,
                items: 1,
                stagePadding: 100
            },
            768: {
                mousedrag:true,
                items: 2,
                margin: 4,
                stagePadding: 0
            },
            1024: {
                mousedrag:true,
                items: 2,
                margin: 4,
                stagePadding: 20,
                dots: true
            },
            1280: {
                mousedrag:true,
                items: 3,
                margin: 4,
                stagePadding: 0,
                dots: true
            },
            1440: {
                mousedrag:true,
                items: 3,
                margin: 4,
                stagePadding: 0,
                dots: true,
            },
            1680: {
                mousedrag:true,
                items: 3,
                margin: 4,
                stagePadding: 0,
                dots: true,
            },
            3000: {
                mousedrag:true,
                items: 3,
                margin: 4,
                stagePadding: 0,
                dots: true,
            },



        }
    });

    //collegamnento prev e next news
    var carousel_news = $(".agevolazioni-supplementi-carousel");
    if($('.agevolazioni-supplementi-carousel').hasClass('no-carousel')){
        $(".next_agevolazioni_supplementi").hide();
        $(".prev_agevolazioni_supplementi").hide();
        carousel_news.trigger('destroy.owl.carousel');
    }else{
        carousel_news.owlCarousel();
    }

    //Custom Navigation Events
    $(".next_agevolazioni_supplementi").click(function () {
        carousel_news.trigger('next.owl.carousel');
    });
    $(".prev_agevolazioni_supplementi").click(function () {
        carousel_news.trigger('prev.owl.carousel');
    });
}

Trenord.ui.laNostraOfferta = function () {

    if ($("body").hasClass("malpensaStyle")) {


        if ($(window).width() < 768) {
            $(function () {
                var $content = $('.grid-nostra-offerta');
                $content.imagesLoaded(function () {
                    $content.masonry({
                        itemSelector: '.grid-item',
                        columnWidth: '.grid-sizer',
                        gutter: 10,
                        isAnimated: true,
                        percentPosition: true,
                        isResizable: true,


                    });
                });
            });

        } else {

            $(function () {
                var $content = $('.grid-nostra-offerta');
                $content.imagesLoaded(function () {
                    $content.masonry({
                        itemSelector: '.grid-item',
                        columnWidth: '.grid-sizer',
                        gutter: 20,
                        isAnimated: true,
                        percentPosition: true,
                        isResizable: true,

                    });
                });
            });

        }

    } else {
        if ($(window).width() < 768) {
            $(function () {
                var $content = $('.grid-nostra-offerta');
                $content.imagesLoaded(function () {
                    $content.masonry({
                        itemSelector: '.grid-item',
                        columnWidth: '.grid-sizer',
                        gutter: 10,
                        isAnimated: true,
                        percentPosition: true,
                        horizontalOrder: true,
                        isResizable: true

                    });
                });
            });

        } else {

            $(function () {
                var $content = $('.grid-nostra-offerta');
                $content.imagesLoaded(function () {
                    $content.masonry({
                        itemSelector: '.grid-item',
                        columnWidth: '.grid-sizer',
                        gutter: 20,
                        horizontalOrder: true,
                        isAnimated: true,
                        percentPosition: true,
                        isResizable: true
                    });
                });
            });

        }
    }


    var id = "";


    $(".grid-nostra-offerta .grid-item .caption .title-container")
        .mouseenter(function () {
            if ($(window).width() > 768) {
                id = $(this).attr("id").split("card");
                $("#title" + id[1] + "").css("opacity", "0");
                $("#caption-hover" + id[1] + "").fadeIn(50);
            }
        })
        .mouseleave(function () {
            if ($(window).width() > 768) {
                $("#title" + id[1] + "").css("opacity", "1");
                $("#caption-hover" + id[1] + "").fadeOut(50);
            }
        });


}

Trenord.utility.GeoProj = null;


Trenord.utility.widgetTool = function (elements) {

    if ($(window).width() < 1024) {
        $(".container-ticket").insertAfter(".container-slider-mobile");
    } else {
        $(".container-ticket").prependTo(".main-tab .layout-limit");
    }
}
Trenord.utility.changeStyleInPage = function () {


}


Trenord.utility.GATrenord = function (elements) {
    //trenord
    var srcGTM = "https://www.googletagmanager.com/ns.html?id=GTM-TXFVDRT&gtm_auth=rJ1qNHsKRdq_e7sQGfQA5A&gtm_preview=env-2&gtm_cookies_win=x";
    //    Google Tag Manager
    (function (w, d, s, l, i) {
        w[l] = w[l] || [];
        w[l].push({
            'gtm.start':
                new Date().getTime(), event: 'gtm.js'
        });
        var f = d.getElementsByTagName(s)[0],
            j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : '';
        j.async = true;
        j.src =
            'https://www.googletagmanager.com/gtm.js?id=' + i + dl + '&gtm_auth=rJ1qNHsKRdq_e7sQGfQA5A&gtm_preview=env-2&gtm_cookies_win=x';
        f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', 'GTM-TXFVDRT');
    // End Google Tag Manager
    // Google Tag Manager (noscript)

    if($("#gtm-trenord").attr("src") ==""){
        $("#gtm-trenord").attr("src", srcGTM);
    }
};


Trenord.utility.checkCookie = function (name) {

        var dc = document.cookie;
        var prefix = name + "=";
        var begin = dc.indexOf("; " + prefix);
        if (begin == -1) {
            begin = dc.indexOf(prefix);
            if (begin != 0) return null;
        }
        else
        {
            begin += 2;
            var end = document.cookie.indexOf(";", begin);
            if (end == -1) {
                end = dc.length;
            }
        }
        // because unescape has been deprecated, replaced with decodeURI
        //return unescape(dc.substring(begin + prefix.length, end));
        return decodeURI(dc.substring(begin + prefix.length, end));

};

Trenord.utility.GAMalpensa = function (elements) {
    var idGTM = 'GTM-KCHL8WG'; // prod
    if (window.location.host.includes('test')) {
        idGTM = 'GTM-PMDHGR5'; // test
    }
    var srcGTM = `https://www.googletagmanager.com/ns.html?id=${idGTM}`
    window.dataLayer = window.dataLayer || [];

    (function (w, d, s, l, i) {
      w[l] = w[l] || [];
      w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
      var f = d.getElementsByTagName(s)[0],
        j = d.createElement(s),
        dl = l != 'dataLayer' ? '&l=' + l : '';
      j.async = true;
      j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
      f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', idGTM);
    
    $('#gtm-malpensa').attr('src', srcGTM);
};


Trenord.utility.tornaSu = function (elements) {
    //torna su
    $(window).scroll(function () {
        if ($(this).scrollTop() < 500) {
            $('.torna-su').fadeOut();
        } else {
            $('.torna-su').fadeIn();
        }
    });

    //torna su
    $(".torna-su > svg").click(function () {
        $('html, body').animate({
            scrollTop: 0
        }, 800);
    });
}

/**
 * inizializza gli env con definito l'oggetto userAgent
 *
 * @param elements
 * @return string con all'interno i valori windows phone | android | ios | others | desktop
 */
Trenord.utility.mobileDetector = function (elements) {

    Trenord.globals.userAgent = navigator.userAgent || navigator.vendor || window.opera;

    if (Trenord.utility.isMobile() || Trenord.utility.isTablet()) {

        // Windows Phone must come first because its UA also contains "Android"
        if (/windows phone/i.test(Trenord.globals.userAgent)) {
            Trenord.globals.userAgent = "windows-phone";
        }
        else if (/android/i.test(Trenord.globals.userAgent)) {
            Trenord.globals.userAgent = "android";
        }
        else if (/iPad|iPhone|iPod/.test(Trenord.globals.userAgent) && !window.MSStream) {
            // iOS detection from: http://stackoverflow.com/a/9039885/177710
            Trenord.globals.userAgent = "ios";
        }
        else if (/Huawei Store App/i.test(Trenord.globals.userAgent)){
            Trenord.globals.userAgent = "huawei-store";
        }
        else {
            Trenord.globals.userAgent = "others";
        } 
    }
    else if (/Huawei Store App/i.test(Trenord.globals.userAgent)){
        Trenord.globals.userAgent = "huawei-store";
    }
    else {
        Trenord.globals.userAgent = "desktop";
    }


}


Trenord.utility.alert = function (elements) {
    $(".container-alert .alert .close-alert svg, .container-alert .alert .close-alert a").click(function () {
        $(".container-alert").slideUp("slow");
    });
}


Trenord.utility.VediAncheHover = function (elements) {

    $(".container-grid .grid .item,container-caption,.container-button").mouseenter(function () {
        if ($(window).width() > 1280) {
            $(this).find(".container-button").addClass("active");
        }

    });
    $(".container-grid .grid .item").mouseleave(function () {
        if ($(window).width() > 1280) {
            $(this).find(".container-button").removeClass("active");
        }
    });
}


Trenord.utility.alert = function (elements) {
    $(".container-alert .alert .close-alert svg, .container-alert .alert .close-alert a").click(function () {
        $(".container-alert").slideUp("slow");
    });
}


Trenord.utility.resizeSliderHome = function (elements) {
    setTimeout(function () {
        var heightContainerSlider = $("#slider-home .owl-item.active").height();
        $(".container-tab").height(heightContainerSlider);
    }, 100);
}


Trenord.utility.resizeHeight = function (elements) {


    $(".container-mostra-altri.avvisi .link").click(function () {


        $(".container-archive-news.avvisi .container-news.hidden").each(function (index) {
            if (index > 10) {
                $(".container-mostra-altri.avvisi").show();
            } else {
                $(".container-mostra-altri.avvisi").hide();
                $(this).removeClass("hidden");
            }
        });


    });


    if ($(".container-double-column .object-item-2").length > 0 && !Trenord.utility.isMobile()) {
        var max = 0;
        $(".container-double-column .object-item-2").css("height", "auto");
        $(".container-double-column .object-item-2").each(function (index) {
            if ($(this).innerHeight() > max) {
                max = $(this).innerHeight();
            }

        });

        $(".container-double-column .object-item-2").css("height", max);
    }

    if ($(".card-sanzioni-container")) {
        var max = 0;
        $(".card-sanzioni-container").css("height", "auto");
        $(".card-sanzioni-container").each(function (index) {
            if ($(this).innerHeight() > max) {
                max = $(this).innerHeight();
            }

        });

        $(".card-sanzioni-container").css("height", max);
    }


    var titNews = 0;
    var subNews = 0;

    /*    $(".news-carousel .item .caption-container .caption").css("height", "auto");
        $(".news-carousel .item .caption-container .sub-caption.text").css("height", "auto");

        setTimeout(function () {
            $(".news-carousel .item .caption-container .caption").each(function (index) {
                if ($(this).height() > titNews) {
                    titNews = $(this).height();
                }

            });


            $(".news-carousel .item .caption-container .sub-caption.text").each(function (index) {
                if ($(this).height() > subNews) {
                    subNews = $(this).height();
                }

            });


            $(".news-carousel .item .caption-container .caption").height(titNews);
            if ($(window).width() > 768) {
                $(".news-carousel .item .caption-container .sub-caption.text").height(subNews + 46);
            } else {
                $(".news-carousel .item .caption-container .sub-caption.text").height(subNews);
            }

        }, 100);*/


    if (elements == undefined || elements == null)
        elements = $(".tn-utilty-resizeHeight");
    else
        elements = elements.find(".tn-utilty-resizeHeight");

    //recupero tutti i container
    var elements = $(".tn-utilty-resizeHeight");

    //recupero i singoli contenitori
    $(elements).each(function (index, container) {

        var inLineElements = $(container).hasClass('tn-utilty-resizeHeight-inline');
        var children = $(container).find('.tn-utilty-resizeHeight-item');

        //recupero le classi
        var max = Trenord.utility.getMaxOfChildren(children);

        //contaGlielementi
        var childrenCount = children.length;


        if ((children % 2) != 0 && !inLineElements) {
            //dispari

            if (Trenord.utility.isTablet()) {

                $(children[0]).css("height", "auto");
                for (var i = 1; i < childrenCount; i++) {
                    $(children[i]).outerHeight(max);
                }
            } else if (Trenord.utility.isMobile()) {
                $(children).css("height", "auto");
            } else {
                //desktop
                $(children).outerHeight(max);
            }

        } else {

            //pari
            $(children).outerHeight(max);
        }

    });

    var maxHeightMod = 0;
    var maxHeightCard = 0;
    $(".container-modalita-acquisto .item .title").each(function (index, child) {
        $(".container-modalita-acquisto .item .title").css("height", "auto");
        if ($(this).height() > maxHeightMod) {
            maxHeightMod = $(this).height();
        }
    });

    $(".container-modalita-acquisto .item .title ").height(maxHeightMod);


    $(".container-agevolazioni-supplementi .agevolazioni-supplementi-carousel .item .caption .title").each(function (index, child) {
        $(".container-agevolazioni-supplementi .agevolazioni-supplementi-carousel .item .caption .title").css("height", "auto");
        if ($(this).height() > maxHeightCard) {
            maxHeightCard = $(this).height();
        }
    });

    setTimeout(function () {
        $(".container-agevolazioni-supplementi .agevolazioni-supplementi-carousel .item .caption .title").height(maxHeightCard);
    }, 70);

}


Trenord.utility.getMaxOfChildren = function (children) {

    //ricerca della max altezza
    var max = -1;
    var heightItem = -1;

    $(children).each(function (index, child) {

        heightItem = $(child).outerHeight();

        if (max < heightItem) {
            max = heightItem;
        }
    });

    return max;
}

Trenord.utility.getMaxofClass = function (elementClass) {
    var max = Math.max.apply(Math, $(elementClass).map(function () {
        return $(this).height();
    }))
    return max;
}

Trenord.utility.resizeTriangleMobile = function (elementClass) {
    var containerSliderWidth = $(".container-slider-mobile").width();
    $(".triangle-slider-mobile").css("border-width", "0 0 20vw " + containerSliderWidth + "px");
}

Trenord.utility.setCssAuto = function (obj) {

    if (obj == undefined || obj == null)
        obj = $(".tn-utility-setCssAuto");
    else
        obj = obj.find(".tn-utility-setCssAuto");

    obj.css("height", "auto");
}

Trenord.utility.sumHeight = function (elementClass) {
    var height = 0;
    $("" + elementClass + "").each(function (index) {
        height = height + $(this).outerHeight();

    });
    return height;
}


Trenord.utility.resizeHeightWidget = function () {
    var height = 0;
    height = $(".tn-cms__search-container").height();
    $(".container-ticket").height(height + 30); // + 30 per lo spazio  del container ticket
}

Trenord.utility.isTablet = function () {
    return $(window).width() <= Trenord.breakpoint.tablet.maxWidth && $(window).width() >= Trenord.breakpoint.tablet.minWidth;
}

Trenord.utility.isMobile = function () {
    return $(window).width() <= Trenord.breakpoint.mobile.maxWidth && $(window).width() >= Trenord.breakpoint.mobile.minWidth;
}


Trenord.utility.Accordion = function () {

    $('.container-toggle .accordion').on('show.bs.collapse', function () {
        setTimeout(function () {
            $(".multiple-carnet").each(function (index) {
                var i = 1;
                var numUl = $(this).find("ul").length;
                var numLi = $(this).find("ul").find("li").length / numUl;
                var max = 0;
                for (i = 0; i < numLi; i++) {
                    max = 0;
                    $(this).find("ul").each(function (index) {

                        if ($(this).children().eq(i).height() > max) {
                            max = $(this).children().eq(i).height();

                        }
                    });

                    $(this).find("ul").each(function (index) {

                        $(this).children().eq(i).height(max);
                    });


                }

            });
        }, 200);

        var id = $(this).attr("id").split("accordion");
        $('.link-accordion-on-show.action-collapse' + id[1] + '').fadeIn(300).css('display', 'block');
        $('.link-accordion-on-hide.action-collapse' + id[1] + '').fadeOut(300);
        $('.arrow-accordion.arrow' + id[1] + '').addClass(" rotate-arrow-accordion");

        $('html,body').animate({
            scrollTop: window.pageYOffset + 100
        }, 500, 'swing');
    });

    $('.container-toggle .accordion').on('hide.bs.collapse', function () {
        $('[data-toggle="tooltip"], .tooltip').tooltip("hide");

        var id = $(this).attr("id").split("accordion");
        $('.link-accordion-on-show.action-collapse' + id[1] + '').fadeOut(300);
        $('.link-accordion-on-hide.action-collapse' + id[1] + '').fadeIn(300).css('display', 'block');
        $('.arrow-accordion.arrow' + id[1] + '').removeClass(" rotate-arrow-accordion");

        var panel = $(this).find('.in');
        setTimeout(function () {

            $('html,body').animate({
                scrollTop: panel.offset().top - 170
            }, 500, 'swing');
        }, 320);

    });
}


Trenord.utility.Tooltip = function () {


    $('.tooltip-action').click(function () {


        var id = $(this).attr("id").split("tooltip");

        $(this).tooltip({
            animated: 'fade',
            placement: 'top',
            trigger: 'click ',
            html: true,
            title: $("#text-tooltip" + id[1] + "").html(),
        });
        checkMobile(id);
    }).click();

    function checkMobile(id) {
        if (Trenord.utility.isMobile()) {
            setTimeout(function () {
                $("#tooltip" + id[1] + "").next().css("top", "0");
            }, 10);
        }
    }


    $('[data-toggle="tooltip"]').on('shown.bs.tooltip', function (e) {

        $(this).find(".svg-tooltip-active").show();
        $(this).find(".svg-tooltip-not-active").hide();

        var idOpenTooltip = "close-" + $(this).attr("id") + "";

        $(".tooltip.in").each(function (index) {

            if ($(this).find(".close-tooltip").attr("id") !== idOpenTooltip) {
                var id = $(this).find(".close-tooltip").attr("id");
                $("#" + id + "").click();
            }
        });

        $('.tooltip-inner').children().each(function () {
            if ($(this).attr("class") !== "close-tooltip") {
                $(this).click(false);

            }
        })
    });


    $(document).on('click', function (e) {
        var classElement = $(e.target).parent().attr("class");

        if ($(".tooltip.fade").length) {
            if (Trenord.utility.isMobile()) {
                setTimeout(function () {
                    $(".tooltip.fade").css("top", "0");
                }, 10);
            }
        }

        if (classElement !== "close-tooltip" && classElement !== "tooltip fade top in" && classElement !== "svg-tooltip" && classElement !== "tooltip-container" && classElement !== "tooltip-action" && classElement !== "tooltip-inner") {
            $(".tooltip.in").find(".close-tooltip").click();
            $(this).find(".svg-tooltip-active").hide();
            $(this).find(".svg-tooltip-not-active").show();
        }

    });


    $(document).on('click', '.close-tooltip', function () {

        $(this).find(".svg-tooltip-active").hide();
        $(this).find(".svg-tooltip-not-active").show();


        var id = $(this).attr("id").split("close-tooltip");

        /*   var id = $(this).parent().parent().attr("id");
           $("#" + id + "").tooltip('destroy');*/


        $("#tooltip" + id[1] + "").click();
        $("#tooltip" + id[1] + "").find(".svg-tooltip-active").hide();
        $("#tooltip" + id[1] + "").find(".svg-tooltip-not-active").show();


    });
}


Trenord.utility.Tab = function () {


    var lastTab;
    var switchTab;
    $(".switch .tab").click(function () {
        clearTimeout(switchTab);
        var idSwitch = $(this).parent().attr("id").split("switch");
        var idTab = $(this).attr("id").split("tab-title");

        if (lastTab != idTab[1]) {
            $("#switch" + idSwitch[1] + " .tab  p").removeClass("active");
            if (idTab[1] == 2) {
                $("#switch" + idSwitch[1] + " #tab-title" + idTab[1] + " p").addClass("active");
                $(" .line-tab .line-green").addClass("line-green-right");
                $("#container-tab-content" + idSwitch[1] + " #content-tab1").addClass("fadeOut");
                setTimeout(function () {
                    $("#container-tab-content" + idSwitch[1] + " #content-tab1").addClass("hidden-tab-switch");
                    $("#container-tab-content" + idSwitch[1] + " #content-tab2").removeClass("hidden-tab-switch").removeClass("fadeOut");
                }, 450);
            } else {
                $("#switch" + idSwitch[1] + " #tab-title" + idTab[1] + " p").addClass("active");
                $(" .line-tab .line-green").removeClass("line-green-right");
                $("#container-tab-content" + idSwitch[1] + " #content-tab2").addClass("fadeOut");
                setTimeout(function () {
                    $("#container-tab-content" + idSwitch[1] + " #content-tab2").addClass("hidden-tab-switch");
                    $("#container-tab-content" + idSwitch[1] + " #content-tab1").removeClass("hidden-tab-switch").removeClass("fadeOut");
                    ;
                }, 450);
            }
        }
    });

};

Trenord.utility.Modal = function () {


    if ($(".myModal").length > 0) {
        $(".myModal").each(function (index) {
            $("#main").prepend($(this));
        });

    }


    $(".modal-content").each(function (index) {
        if ($(this).find(".modal-note").length) {
            var h = $(this).find(".modal-note").outerHeight();
            $(this).find(".modal-body").css("height", "calc( 100% - " + h + "px )")
        }
    });


    if ($(".modal table").length) {
        $(".modal table").wrap("<div class='table-responsive'></div>");

    }

    $(".modal-dialog.form .close-modal").click(function () {
        $(".modal.form").modal().hide();
    });

    $('.modal-body').on('click', 'a', function (event) {

        if (!$(event.target).hasClass("accordion-toggle") && !$(event.target).hasClass("internal-link") && !$(event.target).attr('href') == "_blank") {
            window.open($(this).attr('href'), '_blank');
        }

    });

    $(document).on('show.bs.modal', '.myModal', function () {

        setTimeout(function () {

            $(".modal-content").each(function (index) {


                if ($(this).find(".modal-note:visible").length) {

                    $(this).find(".content-text-modal").css("padding-bottom", $(this).find(".modal-note").outerHeight())
                }


            });
        }, 300);

        $("body,html").css("overflow", "hidden");
        $(".modal-content").each(function (index) {
            if ($(this).find(".modal-note").length) {
                var h = $(this).find(".modal-note").outerHeight();
                $(this).find(".modal-body").css("height", "calc( 100% - " + h + "px )")
            }
        });

        setTimeout(function () {
            $(".modal-content").each(function (index) {
                if ($(this).find(".modal-note").length) {
                    var h = $(this).find(".modal-note").outerHeight();
                    $(this).find(".modal-body").css("height", "calc( 100% - " + h + "px )")
                }
            });
        }, 300);
    });

    $(document).on('hide.bs.modal', '.myModal', function () {
        $("body,html").css("overflow", "initial");
        $("body,html").css("overflow-x", "hidden");
    });

    $(".modal-content").perfectScrollbar('update');

    $(".myModal  *").click(function (event) {


        if ($(event.target).attr("class") === "modal-dialog" || $(event.target).attr("class") === "close-modal" || $(event.target).parent().attr("class") === "close-modal") {

            if ($(this).parents(".video-modal").length > 0) {
                var iframePlayer = $(this).parents(".video-modal").find('iframe');
                $(iframePlayer).attr('src', $(iframePlayer).attr('src'));
            }

            $(".myModal").modal("hide");
        }
    });

    $(".modal-content").each(function (index) {
        var h = $(this).find(".modal-header").outerHeight();
        $(this).find(".modal-body").css("top", h);

    });


    $(".modal-body .container-content .list-text-modal").each(function (index) {
        var numItem = $(this).find(".content-text-modal").length;


        if (numItem === 1) {

            $(this).parents(".modal-body").perfectScrollbar();
            $(this).find(".content-text-modal").each(function (index) {
                $(this).parent().addClass("col-xs-12 col-md-10 no-padding ");
                $(this).addClass(" col-xs-12 col-md-7 ");
                $(this).parents(".modal-content").find(".modal-header").addClass("two");
            })
        }

        if (numItem === 2) {
            $(this).parents(".modal-body").perfectScrollbar();
            $(this).find(".content-text-modal").each(function (index) {
                $(this).parent().addClass(" col-xs-12 col-md-10 no-padding");
                $(this).addClass(" col-xs-12 col-md-6 n");
                $(this).parents(".modal-content").find(".modal-header").addClass("two");
            })
        }

        if (numItem === 3) {
            $(this).parents(".modal-body").perfectScrollbar();


            $(this).find(".content-text-modal").each(function (index) {
                $(this).addClass(" col-xs-12 col-md-4 ");
                $(this).parents(".modal-content").find(".modal-header").addClass("tre-elementi");
            })
        }
    });


    $(".modal-link").each(function (index) {

        var hrefModal = $(this).attr("href").split("#");
        var numberModal = hrefModal[1].replace("c", "");
        $(this).attr('data-toggle', 'modal');
        $(this).attr('data-target', "#modal-content-item-" + numberModal + "");
    });


    $('.myModal').on('shown.bs.modal', function () {

        $(".modal-content").each(function (index) {
            var h = $(this).find(".modal-header").outerHeight();
            $(this).find(".modal-body").css("top", h);
            $(this).find(".modal-body").css("max-height", "calc(100% - " + h + "px)");
        });
        var id = $(this).attr("id");
        document.getElementById(id).style.removeProperty('padding-right');
        var h = $(this).parent().height();

        $(".modal-content").each(function (index) {

            var modText = $(this).find(".content-text-modal").length;

            if ($(this).find(".modal-note").length) {
                $(this).find(".modal-note").addClass("column" + modText + "");
                if (Trenord.utility.isMobile() || Trenord.utility.isTablet()) {
                    $(this).find(".content-text-modal").css("padding-bottom", "0");
                    setTimeout(function () {
                        /*
                                                $(this).find(".content-text-modal:last-child").css("padding-bottom",$(this).find(".modal-note").outerHeight());
                        */
                    }, 200);
                    /*
                                        $(this).find(".content-text-modal:last-child").css("padding-bottom", $(this).find(".modal-note").outerHeight());
                    */

                } else {
                    /*   $(this).find(".content-text-modal").css("padding-bottom", $(this).find(".modal-note").outerHeight());*/
                }

            }

        });


    });


};

/*
Trenord.utility.resizeHeightModal = function () {

    $( ".modal-body .container-content .content-text-modal" ).each(function( index ) {
        var h  =   $(this).parent().height();
        $(this).height(h);
    });


};
*/


Trenord.utility.Faq = {


    initEvents: function () {

        $(".horizontal-scrollable-tabs").find(".scroller").each(function (index) {
            if (!$(this).hasClass("hidden")) {
                $(this).css("opacity", "0");
            }
        });


        $(".horizontal-scrollable-tabs").mouseenter(function () {
            $(this).find(".scroller").each(function (index) {
                if (!$(this).hasClass("hidden")) {
                    $(this).css("opacity", "1");
                }
            });
        });
        $(".horizontal-scrollable-tabs").mouseleave(function () {
            $(this).find(".scroller").each(function (index) {
                if (!$(this).hasClass("hidden")) {
                    $(this).css("opacity", "0");
                }
            });
        });


        $(".container-faq .accordion .accordion-group .accordion-heading .accordion-toggle").hover(
            function () {
                $(this).parent().css("background-color", "#ffffff");
            }, function () {
                $(this).parent().css("background-color", "#ffffff");
            }
        );


        $('.container-faq .accordion').on('show.bs.collapse', function () {
            if ($("#" + $(this).attr("id") + " .accordion-body.collapse.in ").length) {

                var idArrow = $("#" + $(this).attr("id") + " .accordion-body.collapse.in ").attr("id").split("-faq");
                $("#arrow-" + idArrow[0] + "-" + idArrow[1] + "").toggleClass("active-arrow-faq");
            }

            $("#" + $(this).attr("id") + " .accordion-body.collapse.in ").collapse('hide');
        });


        $(".faq-answer").click(function () {
            var idAccordion = $(this).attr("id");
            var idFaq = $(this).attr("href").split("faq");
            $("#arrow-" + idAccordion + "-" + idFaq[1] + "").toggleClass("active-arrow-faq");
        });


        $('.question-box input[type=radio]').on('change', function () {

            var radioName = $(this).attr("name");
            var idAccordion = $(this).attr("id").split("-");
            $(":radio[name='" + radioName + "']").attr("disabled", true);

            Trenord.utility.Faq.registerAnswer(idAccordion[0], idAccordion[1], idAccordion[2]);
        });
    },

    registerAnswer: function (answer, accordionId, faqId) {


        $.get('/rest/cta/faq', {
            faqId: faqId.replace("faq", ""),
            answer: answer,
            L: Trenord.globals.currentLanguage
        }, function (data) {

            if (data === true) {

                if (answer == "yes") {
                    $("#" + accordionId + "-" + faqId + " .question-box .box-answer-yes").fadeIn("slow");
                } else {
                    $("#" + accordionId + "-" + faqId + " .question-box .box-answer-no").fadeIn("slow");
                }

            } else {

                Trenord.console.log("errore nell'operazione");
            }

        });
    }
};

Trenord.utility.multipleTab = function () {

    if ($(".nav-tabs-horizontal").length) {
        (function ($) {

            $.fn.horizontalTabs = function () {
                // Variable creation
                var $elem = $(this),
                    widthOfReducedList = $elem.find('.nav-tabs-horizontal').width(),
                    widthOfList = 0,
                    currentPos = 0,
                    adjustScroll = function () {
                        widthOfList = 0;
                        $elem.find('.nav-tabs-horizontal li').each(function (index, item) {
                            widthOfList += $(item).width();
                        });

                        widthAvailale = $elem.width();

                        if (widthOfList > widthAvailale) {
                            $elem.find('.scroller').show();
                            updateArrowStyle(currentPos);
                            widthOfReducedList = $elem.find('.nav-tabs-horizontal').width();
                        } else {
                            $elem.find('.scroller').hide();
                        }
                    },
                    scrollLeft = function () {
                        if (currentPos - widthOfReducedList > 0) {
                            currentPos -= widthOfReducedList;
                        } else {
                            currentPos = 0;
                        }
                        $elem.find('.nav-tabs-horizontal').animate({
                            scrollLeft: currentPos + 1
                        }, 50, 'swing');
                        $(".container-bar .bar").removeClass("bar-transition");
                        setTimeout(function () {
                            $(".container-bar .bar").removeClass("bar-transition");

                        }, 150);

                        setTimeout(function () {
                            var leftItem = $(".nav-tabs.nav-tabs-horizontal>li.active>a").offset();

                            $(".container-bar .bar").css("left", leftItem.left - $(".container-bar").offset().left);
                        }, 100);


                    },

                    scrollRight = function () {
                        if ((currentPos + widthOfReducedList) < (widthOfList - widthOfReducedList)) {
                            currentPos += widthOfReducedList;

                        } else {
                            currentPos = (widthOfList - widthOfReducedList);

                        }

                        $elem.find('.nav-tabs-horizontal').animate({
                            scrollLeft: currentPos + 1
                        }, 50, 'swing');
                        $(".container-bar .bar").removeClass("bar-transition");
                        setTimeout(function () {
                            $(".container-bar .bar").removeClass("bar-transition");

                        }, 150);

                        setTimeout(function () {
                            var leftItem = $(".nav-tabs.nav-tabs-horizontal>li.active>a").offset();

                            $(".container-bar .bar").css("left", leftItem.left - $(".container-bar").offset().left);
                        }, 100);

                    },
                    manualScroll = function () {
                        currentPos = $elem.find('.nav-tabs-horizontal').scrollLeft();

                        updateArrowStyle(currentPos);
                    },
                    updateArrowStyle = function (position) {


                        if (position <= 10) {
                            $(".nav-tabs.nav-tabs-horizontal").addClass("no-left");
                        } else {
                            $(".nav-tabs.nav-tabs-horizontal").removeClass("no-left");
                        }

                        if (position >= Math.floor(widthOfList - widthOfReducedList)) {
                            $(".nav-tabs.nav-tabs-horizontal").addClass("no-right");
                        } else {
                            $(".nav-tabs.nav-tabs-horizontal").removeClass("no-right");
                        }


                        if (position >= (widthOfList - widthOfReducedList)) {
                            $elem.find('.arrow-right').addClass('hidden');
                        } else {
                            $elem.find('.arrow-right').removeClass('hidden');
                            if ($($elem).is(":hover")) {
                                $elem.find('.arrow-right').css("opacity", "1");
                            }

                        }

                        if (position <= 1) {
                            $elem.find('.arrow-left').addClass('hidden');
                        } else {
                            $elem.find('.arrow-left').removeClass('hidden');
                            if ($($elem).is(":hover")) {
                                $elem.find('.arrow-left').css("opacity", "1");
                            }
                        }

                    };

                // Event binding
                $(window).resize(function () {
                    adjustScroll();
                });

                $elem.find('.arrow-left').on('click.horizontalTabs', function () {
                    scrollLeft();
                });

                $elem.find('.arrow-right').on('click.horizontalTabs', function () {
                    scrollRight();
                });

                $elem.find('.nav-tabs-horizontal').scroll(function () {
                    manualScroll();

                });

                // Initial Call
                adjustScroll();

                return this;
            }

        }(window.jQuery));

        //init
        $("#js_image_selection").horizontalTabs();

        var activeItemWidth = $(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal > li.active").width();
        $(".container-bar .bar").width(activeItemWidth);
        var offsetResize = $(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal > li.active").offset();

        if ($(window).width() > 1920) {
            $(".container-bar .bar").css("left", offsetResize.left - $(".container-bar").offset().left);
        } else {
            $(".container-bar .bar").css("left", offsetResize.left);
        }


        $(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal > li > a").click(function () {
            var elem = $(this);

            if (Trenord.utility.isMobile()) {
                if ($(this).parent().parent().hasClass("volo")) {
                    $(".container-bar .bar").addClass("bar-transition");
                    var offset = $(this).offset();
                    elem.parent().parent().parent().next().find(".bar").css("left", offset.left - $(".container-bar").offset().left);
                } else {
                    $(".container-bar .bar").addClass("bar-transition");
                    var myScrollPos = $(this).offset().left + $(this).outerWidth(true) / 2 + $('.horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal').scrollLeft() - $('.horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal').width() / 2;
                    $('.horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal').animate({scrollLeft: myScrollPos}, 200, "swing");
                    setTimeout(function () {
                        var offsetResize = $(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal > li.active").offset();
                        elem.parent().parent().parent().next().find(".bar").css("left", offsetResize.left);
                    }, 200);
                }
            } else {
                $(".container-bar .bar").addClass("bar-transition");
                var offset = $(this).offset();
                elem.parent().parent().parent().next().find(".bar").css("left", offset.left - $(".container-bar").offset().left);
            }


            // $(".container-bar .bar").css("left",offset.left);
        });

        if ($(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal").length > 10) {

            $('.horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal').on('touchmove', function (event) {
                $(".container-bar .bar").removeClass("bar-transition");
                var offsetResize = $(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal > li.active").offset();
                $(".container-bar .bar").css("left", offsetResize.left);
                event.preventDefault();
            });


            $(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal ").mousewheel(function (event, delta) {
                this.scrollLeft -= (delta * 20);
                event.preventDefault();

                $(".container-bar .bar").removeClass("bar-transition");
                var offsetResize = $(".horizontal-scrollable-tabs .horizontal-tabs .nav-tabs-horizontal > li.active").offset();
                $(".container-bar .bar").css("left", offsetResize.left);

            });

        }


    }
}

Trenord.utility.waitAndRedirect404 = function () {

    var timeCount = 1;
    var maxTimeCount = 10;
    var timeSeconds = 1000;

    var timeInterval = setInterval(function () {

        if (timeCount == maxTimeCount) {
            window.location.href = "/";
            clearInterval(timeInterval);

        } else {
            $(".container-404 .right .box-link .counter-number p").css("left", "-6px");
            //per settare la parte grafica
            Trenord.ui.counter404.setTime(maxTimeCount - timeCount);
            timeCount++;
        }

    }, timeSeconds);

}

Trenord.utility.locationSearchToObject = function () {

    var pairs = window.location.search.substring(1).split("&"),
        obj = {},
        pair,
        i;

    for (i in pairs) {
        if (pairs[i] === "") continue;

        pair = pairs[i].split("=");
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }

    return obj;

}

/**
 * recupera il dominio alternativo rispetto a quello di navigazione
 */
Trenord.utility.otherDomain = function () {

    var currentDomain = window.location.origin;

    if (currentDomain.indexOf('trenord.it') >= 0) {
        otherDomain = currentDomain.replace('trenord', 'malpensaexpress');
    } else {
        otherDomain = currentDomain.replace('malpensaexpress', 'trenord');
    }

    return otherDomain;
}

Trenord.utility.urlParam = function (name) {

    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
        .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

/**
 * inizializza correttamente i dati di sso
 * ma ad essegnarli sono le funzioni esterne
 * il flusso può avvenire in due modi
 *
 * 1. leggo il cookie dal browser e imposto correttamente i valori
 * 2. leggo i dati direttamente dalla login.
 */
Trenord.user = {

    checkSso: false,
    sso:   Cookies.get('sso')  == "null"  ? "undefined":   Cookies.get('sso') ,
    enableLogin: true,
    updateAvatar: function () {

        if (Trenord.user.isLogged() && Trenord.user.sso.Id != undefined) {

            $.get('/rest/user/avatar', {user_id: Trenord.user.sso.Id}, function (response) {
                Trenord.user.sso.avatar = response;
                Trenord.ui.login.setLoggedUser();
            });
        }
    },

    init: function () {


        if (Trenord.user.sso != "" && Trenord.user.sso != undefined) {

            try {
                Trenord.user.sso = JSON.parse(Trenord.user.sso);
                Trenord.user.checkSso = true;

            } catch (e) {
                //ulteriore check di consistenza dell'oggetto ricevuto
                Trenord.user.checkSso = Trenord.user.sso.IsAuthenticated != undefined;
            }


            //se il parsing non è avvenuto correttamente non posso loggare
            if (Trenord.user.checkSso && Trenord.user.sso.IsAuthenticated) {

                Trenord.user.sso.DisplayName = decodeURI(Trenord.user.sso.DisplayName).replace(/\+/g, ' ')

                //update avatar
                Trenord.user.updateAvatar();

            } else {
                Trenord.ui.login.setNotLoggedUser();
            }

        }else{
            //bozza test login trigger

            var queryString = window.location.search;
            var urlParams = new URLSearchParams(queryString);
            var login = urlParams.get('login');
            if(login == 'y' || login == 'Y'){
                setTimeout(function(){
                    $("#user-icon-desk").trigger("click");

                    $('input:-webkit-autofill').each(function(){

                        $(this).after(this.outerHTML).remove();
                    });


                    $('input:-webkit-autofill').each(function(){

                        $(this).after(this.outerHTML).remove();
                    });
                },600);





            }
        }
    },

    /**
     * permette la login in SSO di un utente
     * che specifica username e passowrd
     * @param username
     * @param password
     */
    login: function (username, password) {

        var emailValidator = /^\w+[\w-+\.]*\@\w+([-\.]\w+)*\.[a-zA-Z]{2,}$/;

        if (Trenord.user.enableLogin) {

            $(".error-volo-codice.password-errata").fadeOut();
            $(".error-volo-codice.login-email-wrong").fadeOut();

            if (username == "" || password == "" || !username.match(emailValidator)) {


                if (username === "") {
                    $(".error-volo-codice.login-email").fadeIn();

                } else {
                    if (!username.match(emailValidator)) {
                        $(".error-volo-codice.login-email").fadeIn();

                    } else {
                        $(".error-volo-codice.login-email").fadeOut();

                    }

                }


                if (password === "") {
                    $(".error-volo-codice.login-password").fadeIn();

                } else {
                    $(".error-volo-codice.login-password").fadeOut();

                }


            } else {


                Trenord.user.enableLogin = false;
                Trenord.ui.login.disable();


                $.post("/rest/user/login", {username: username, password: password}, function (data) {

                    //recupero i dati dal server
                    Trenord.user.sso = data;

                    //inizializzo correttamente i dati
                    Trenord.user.init()

                    if (Trenord.user.checkSso && Trenord.user.sso.IsAuthenticated) {


                        Trenord.ui.login.close();

                        var loginCookie = getCookie("sso");
                        loginCookie = decodeURIComponent(loginCookie);
                        loginCookie = JSON.parse(loginCookie.replace(/%2C/g, ","));
                        const userType = loginCookie.ProfileLevel === 1 ? 'full' : 'light';
                        dataLayer.push({
                            "event": "login",
                            "customerId": loginCookie.Id,
                            "RegistrationType": userType
                        })

                        Trenord.user.crossCookieSet(false);

                        Trenord.events.trigger("userLogged");

                    } else {

                        switch (Trenord.user.sso.AuthenticationFailureReason) {
                            case 2:
                                $(".error-volo-codice.login-email-wrong").fadeIn();
                                break;
                            case 3:
                                $(".error-volo-codice.password-errata").fadeIn();
                                break;
                            case 5:
                                window.location.href = "/store/#/it/sso/registration-pending?email=" + username;
                                return;
                            default:
                                Trenord.console.log(Trenord.user.sso);

                        }
                    }

                    Trenord.user.enableLogin = true;
                    Trenord.ui.login.enable();


                });
            }
        }

    },


    logout: function () {

        if (Trenord.user.checkSso) {

            Trenord.ui.login.setNotLoggedUser();
            Trenord.user.crossCookieSet(true);

            Trenord.events.trigger('userLogout');
        }

    },

    crossCookieSet: function (logout) {

        var currentDomain = window.location.origin;
        var otherDomain = Trenord.utility.otherDomain();


        //pulisco il dominio per la corretta assegnazione
        currentDomain = window.location.hostname

        var ssoData = "";

        if (logout) {

            Trenord.user.sso = "";
            Cookies.remove('sso', {path: '/'});

        } else {

            Cookies.remove('sso', {path: '/'});
            ssoData = JSON.stringify(Trenord.user.sso);

            Cookies.set('sso', ssoData, {expires: 30});
        }

        $("#cross-cookie").attr('src', otherDomain + '/rest/user/saveLoggedUser?sso=' + ssoData + "&logout=" + logout + "&no_cache=1");
    },

    acceptCookie: function () {    },

    haveAcceptedCookie: function () {

        return Trenord.user.isAcceptedCookie;
    },

    isLogged: function () {
        if (Trenord.user.sso != undefined && Trenord.user.sso != null && Trenord.user.sso != "") {

            try {

                return true
            } catch (e) {
                console.log(e)
            }

        }
        return false
    }
}

Trenord.ui.login = {

    initEvents: function () {

        $('#password,#username').keypress(function (event) {
            if (event.keyCode == 13) {
                Trenord.user.login($('#username').val(), $('#password').val());
            }
        });

        $('#username').bind('input', function () {
            $(".error-volo-codice.login-email").fadeOut();
        });
        $('#password').bind('input', function () {
            $(".error-volo-codice.login-password").fadeOut();
        });

        $(".open-login-form").click(function () {
            Trenord.ui.login.open();
            $("#password, #username").val("");
        });


        $(".close-login-form").click(function () {
            Trenord.ui.login.close();
        });


        $(".container-box-login .overlay").click(function () {
            Trenord.ui.login.close();
        });

    },

    open: function () {
        $(".container-box-login").fadeIn("");
        $("body,html").css("overflow", "hidden");

        Trenord.events.trigger('open-login');
    },

    close: function () {

        $(".container-box-login").fadeOut("");
        $("input, select, textarea").val("");
        $("body,html").css("overflow", "auto");

        Trenord.events.trigger('close-login');
    },

    setLoggedUser: function () {

        $(".user-not-logged").hide();
        //mobile
        $(".content-sidenav .user-logged").removeClass("hidden");
        $(".content-sidenav .user-not-logged").hide();

        //inserisco i dati dell'utente nelle varie parti della pagina
        var nameSplit = Trenord.user.sso.DisplayName.split(" ");

        if ($("body").hasClass("malpensaStyle")) {
            $(".user-logged .logged-user-name").html(Trenord.user.sso.DisplayName);
        } else {
            $(".user-logged .logged-user-name").html(nameSplit[0]);
        }


        if (Trenord.user.sso.avatar != undefined && Trenord.user.sso.avatar.url != "" && Trenord.user.sso.avatar.url != undefined) {
            $(".container-search .user-logged .logged-user-name").prepend("<img alt='avatar' class='lozad' style='width:35px; height: 35px; border-radius:50%; margin-right: 10px' src='" + Trenord.user.sso.avatar.url + "'/>");
            //mobile
            $(".content-sidenav .icon-container .icon-profile .not-logged").hide();
            $(".content-sidenav .icon-container .icon-profile .logged").prepend("<img alt='avatar' class='lozad'  src='" + Trenord.user.sso.avatar.url + "'>").removeClass("hidden");

        } else {
            $(".container-search .user-logged .logged-user-name").prepend("<img alt='icona_logged_desktop' style='width:35px; height: 35px; border-radius:50%; margin-right: 10px' src='/fileadmin/templates/img/login/logged-desktop.png'/>");
            //mobile, da verificare se l'immagine è uguale anche nel desktop
            $(".content-sidenav .icon-container .icon-profile .not-logged").hide();
            $(".content-sidenav .icon-container .icon-profile .logged").removeClass("hidden").show();
            $(".content-sidenav .icon-container .icon-profile .logged").prepend("<img  alt='icona_logged_mobile' class='lozad' src='/fileadmin/templates/img/login/logged-mobile.png'>");
            //immagine desktop

        }
        $(".user-logged .user-avatar").remove();
        $(".user-logged-dropdown #user-logged-email").html(Trenord.user.sso.UserName);

        $(".user-logged").show();
        $(".container-box-login").fadeOut();

    },

    setNotLoggedUser: function () {


        //todo: da migliorare il comportamento di hide/show della linguetta login
        $(".dropdown-menu").hide();

        $(".user-logged").hide();
        $(".user-logged .logged-user-name").html();
        $(".user-not-logged").show();
        //mobile
        $(".content-sidenav .icon-container .icon-profile .not-logged").show();
        $(".content-sidenav .icon-container .icon-profile .logged").hide();
        $(".content-sidenav .user-logged").hide();
        $(".content-sidenav .user-not-logged").removeClass("hidden");


    },

    enable: function () {

        $("#form-login-button").removeClass('disableButton');
        $(".box-login").show();
        Trenord.popUpMessage.hideModalBox();
    },

    disable: function () {

        $("#form-login-button").addClass('disableButton');
        $(".box-login").hide();
        Trenord.spinner.show();
        Trenord.popUpMessage.waitResponse();
    }


}


Trenord.ui.unbindPassengerShoulder = function () {

    $(".cta-ticket-malpensa").unbind();
    $(".container-malpnesa-widget .malpensa-widget .header .close, .container-malpnesa-widget .overlay").unbind();

}


Trenord.ui.initPassengerShoulder = function (id) {

    //unbind di sicurezza
    $(".cta-ticket-malpensa").unbind();
    $(".container-malpnesa-widget .malpensa-widget .header .close, .container-malpnesa-widget .overlay").unbind()

    $(".container-malpnesa-widget .malpensa-widget .header .close, .container-malpnesa-widget .overlay").click(function () {
        $(".container-malpnesa-widget .malpensa-widget").addClass("right-out");
        setTimeout(function () {
            $(".container-malpnesa-widget").addClass('hidden');
        }, 400);
        $("html").css("overflow", "initial");
    });
}


/**
 * la logica è che tutti gli elementi sono inizialmente nascosti
 * poi la classe visibility-[string] dove string è l'elemento da visualizzare, agiusce di conseguenza
 * la stringa dell'user agent deve essere disposta nelle pagine con lo stesso formato con cui la variabile
 * usata in globals viene utilizzata.
 */
Trenord.ui.elementsVisibilityFromUserAgent = function () {


    Trenord.utility.mobileDetector();

    switch (Trenord.globals.userAgent) {
        case 'others':
        case 'desktop':
            $(".visible-android").removeClass('hidden');
            $(".visible-ios").removeClass('hidden');
            break;

        case 'huawei-store':
            $(".footer-bottom").find(".container-list").last().hide();
            break;

        default:
            $(".visible-" + Trenord.globals.userAgent).removeClass('hidden');
    }

}

Trenord.ui.shoulderLines = {


    parameters: {
        originPath: window.location.path
    },

    initLineEvent: function () {


        $(".close-alert").click(function () {
            var alertHeight = $(".container-alert").outerHeight();
            var headerHeight = $(".header-top").outerHeight();
            var boxHeight = $(".sidebar .all-lines .title").outerHeight();
            var boxHeightFull = $(".sidebar .line-details:visible").outerHeight();
            var boxInitial = $(".sidebar .all-lines .title").outerHeight();
            if ((".map-box.linee-orari").length > 0) {
                $("#map-box").css("height", "calc(100vh - " + headerHeight + "px  )");

                if (Trenord.utility.isMobile()) {
                    $(".sidebar .list").css("height", "calc(100vh - " + headerHeight + "px - " + boxHeight + "px - 42px  )");
                } else {
                    $(".sidebar .list").css("height", "calc(100vh - " + headerHeight + "px - " + boxHeight + "px  )");

                    $(".sidebar").css("height", "calc(100vh  - " + headerHeight + "px - " + boxHeightFull + "px )");
                }

            }
        });

        if ($(".container-alert:visible").length > 0) {
            var alertHeight = $(".container-alert").outerHeight();
            var headerHeight = $(".header-top").outerHeight();
            var boxHeight = $(".sidebar .all-lines .title").outerHeight();
            var boxHeightFull = $(".sidebar .line-details:visible").outerHeight();
            var boxInitial = $(".sidebar .all-lines .title").outerHeight();

            if (Trenord.utility.isMobile()) {
                $(".sidebar .list").css("height", "calc(100vh - " + alertHeight + "px - " + headerHeight + "px - " + boxHeight + "px - 42px  )");
            } else {
                $(".sidebar .list").css("height", "calc(100vh - " + alertHeight + "px - " + headerHeight + "px - " + boxHeight + "px   )");
            }

            $("#map-box").css("height", "calc(100vh - " + alertHeight + "px - " + headerHeight + "px  )");


        } else {

            var alertHeight = $(".container-alert").outerHeight();
            var headerHeight = $(".header-top").outerHeight();
            var boxInitial = $(".sidebar .all-lines .title").outerHeight();

            $("#map-box").css("height", "calc(100vh  - " + headerHeight + "px )");
            setTimeout(function () {
                $(".sidebar .list").css("height", "calc(100vh  - " + headerHeight + "px - " + boxInitial + "px - 42px  )");
            }, 500);


        }


        $(".line-detail-click").click(function (object) {

            Trenord.shoulderLines.lineDetail($(this).data('code'), false);

            var code = $(this).data('code');

            if (!$("body").hasClass("malpensaStyle")) {
                window.history.pushState("object or string", "Title", ""+window.location.pathname +"?code=" + code + "&line=" + $(this).data('name') + "");


                $("#" + $(this).data('name') + " .caption").removeClass("hidden");
                $("#" + $(this).data('name') + "").prependTo(".sidebar");
            }
            $("#noovle-map").addClass("active");


            $("#map-box.linee-orari .sidebar").addClass("active");
            if ($(window).width() < 768) {
                var alertHeight = $(".container-alert:visible").outerHeight();

                $(".sidebar.active").css("height", "auto");
                $(".linee-orari #noovle-map.active").css("height", "calc(100vh - 198px - " + alertHeight + "px)");
            } else {
                var boxHeight = $(".sidebar .all-lines .title:visible").outerHeight();
                var boxHeightFull = $(".sidebar .line-details:visible").outerHeight();
                var alertHeight = $(".container-alert:visible").outerHeight();
                var headerHeight = $(".header-top").outerHeight();
                var descriptionMalpensa = $(".description-line").outerHeight();

                if (alertHeight) {
                    $(".sidebar").css("height", "calc(100vh  - " + alertHeight + "px    -  " + boxHeightFull + "px - " + headerHeight + "px  )");
                } else {
                    $(".sidebar").css("height", "calc(100vh    - " + headerHeight + "px - " + boxHeightFull + "px )");
                }


                    if($("body").hasClass("malpensaStyle")){
                        $(".sidebar").css("height", "calc(100vh    - 206px - "+headerHeight+"px");
                    }



            }


            var boxHeight = $(".sidebar .all-lines .title:visible").outerHeight();
            var boxHeightFull = $(".sidebar .line-details:visible").outerHeight();


        });

    },

    goBackToLine: function (s) {
        var mxp = window.location.hostname.indexOf("malpensaexpress.it") > -1;
        Trenord.shoulderLines.allLines(mxp);
        showAllLines();
        if (!$("body").hasClass("malpensaStyle")) {
            history.go(-1);
        }

        $(".line-details .caption").addClass("hidden");
        $(".specific-line.result").addClass("hidden");
        $(".all-lines").removeClass("hidden");
        $(".specific-line.result").html("");
        $(".specific-line.skeleton").removeClass("hidden");
        $(window).scroll(function (event) {
            var scroll = $(window).scrollTop();
            var h = $("#noovle-map").css("height", "100%");


        });
        if ($(window).width() < 768) {
            var headerHeight = $(".header-top").outerHeight();
            var boxInitial = $(" #map-box .sidebar .title").outerHeight();
            $("#noovle-map").removeClass("active");
            $(".sidebar").css("height", "100%");
        } else {
            $(".sidebar").css("height", "100%");
        }

    }
}

Trenord.ui.counter404 = {
    setTime: function (time) {
        $(".counter-number p").html("" + time + "");
    }
}

Trenord.ui.infoMobilita = {


    initEvents: function () {

        $(".next-stations").click(function (e) {

            var Element = $(this);
            var listContainer = $(this).parent().find(".children-station");
            var list = $(this).parent().find(".children-station").find("li");
            countStations = parseInt($(this).parent().find(".children-station").attr("data-children"));
            poScroll = parseInt($(this).parent().find(".children-station").attr("data-scroll"));

            e.preventDefault();
            $(listContainer).height("444px");

            if (poScroll !== countStations) {
                poScroll += 6;
                listContainer.attr("data-scroll", "" + poScroll + "");
            }

            if (poScroll > countStations || poScroll === countStations || (countStations - poScroll) < 6) {
                listContainer.scrollTo(list[countStations - 1].offsetTop - 40, "0");
                $(this).fadeOut();
                poScroll = countStations;
                listContainer.attr("data-scroll", "" + poScroll + "");
            } else {
                listContainer.scrollTo(list[poScroll].offsetTop - 20, "0");
            }

            if (poScroll == 6 || poScroll > 6) {
                Element.parent().find(".previous-stations").fadeIn().css("display", "inline-block");
            }


        });


        $(".previous-stations").click(function (e) {
            var Element = $(this);
            var listContainer = $(this).parent().find(".children-station");
            var list = $(this).parent().find(".children-station").find("li");
            countStations = parseInt($(this).parent().find(".children-station").attr("data-children"));
            poScroll = parseInt($(this).parent().find(".children-station").attr("data-scroll"));

            listContainer.height("444px");
            e.preventDefault();

            if (poScroll !== 0) {
                if (poScroll == countStations) {
                    poScroll -= 11;
                    listContainer.attr("data-scroll", "" + poScroll + "");
                } else {
                    poScroll -= 6;
                    listContainer.attr("data-scroll", "" + poScroll + "");
                }

            }

            if (poScroll < 0 || poScroll == 0) {
                Element.parent().find(".previous-stations").fadeOut();
                listContainer.scrollTo(list[0].offsetTop - 40, "0");
                $(this).fadeOut();
                poScroll = 0;
                listContainer.attr("data-scroll", "" + poScroll + "");
            } else {
                listContainer.scrollTo(list[poScroll].offsetTop - 20, "0");
            }

            if (poScroll == 0 || poScroll < 0) {
                Element.parent().find(".previous-stations").fadeOut();
                listContainer.height("464px");
            }


            if (poScroll < countStations) {
                Element.parent().find(".next-stations").fadeIn().css("display", "inline-block");
            }


        });

    },

    closeAll: function () {
        $(".infomob .train.prossimi-treni .accordion-desk.close-accordion-info-mob ").each(function (index) {
            $(this).parent().parent().parent().parent().find(".content-accordion").hide();
            $(this).parent().parent().parent().parent().find(".titolo-dettaglio-viaggio").hide();
            $(this).parent().parent().parent().parent().find(".accordion-desk.infomob").show();
            $(this).parent().parent().parent().parent().parent().find(".icon-train-prossimi").show();
            $(this).parent().parent().parent().parent().parent().find(".text-train-prossimi").show();

            //  $(this).parent().parent().parent().parent().parent().find(".time").show();

            if ($(this).parents("#ricerca-stazione")) {

                $(this).parents(".hidden-mobile ").find(" .content-visible ").find(".time.hidden-mobile").show();

                if (Trenord.utility.isMobile()) {
                    $(this).parent().parent().parent().find(".time.hidden-mobile").hide();
                    $(this).parents(".content-visible").find(".container-link").show();
                    $(this).parent().parent().parent().parent().find(".content-visible .accordion-train .container-link").show();

                } else {
                    $(this).parents(".hidden-mobile ").find(" .content-visible ").find(".time.hidden-mobile").show();

                    $(this).parent().parent().parent().parent().find(".content-visible .accordion-train").show();

                    $(this).parent().parent().parent().parent().find(".content-visible .accordion-train .container-link").show();
                }
            }
        });
    },


    initTrainDetailsEvent: function () {


        $(".infomob .train.prossimi-treni .accordion-desk.close-accordion-info-mob ").click(function (e) {

            $(".infomob .train.prossimi-treni .accordion-desk.close-accordion-info-mob ").each(function (index) {
                $(this).parent().parent().parent().parent().find(".content-accordion").hide();
                $(this).parent().parent().parent().parent().find(".titolo-dettaglio-viaggio").hide();
                $(this).parent().parent().parent().parent().find(".accordion-desk.infomob").show();
                $(this).parent().parent().parent().parent().parent().find(".icon-train-prossimi").show();
                $(this).parent().parent().parent().parent().parent().find(".text-train-prossimi").show();

                //  $(this).parent().parent().parent().parent().parent().find(".time").show();

                if ($(this).parents("#ricerca-stazione")) {

                    $(this).parents(".hidden-mobile ").find(" .content-visible ").find(".time.hidden-mobile").show();

                    if (Trenord.utility.isMobile()) {
                        $(this).parent().parent().parent().find(".time.hidden-mobile").hide();
                        $(this).parents(".content-visible").find(".container-link").show();
                        $(this).parent().parent().parent().parent().find(".content-visible .accordion-train .container-link").show();

                    } else {
                        $(this).parents(".hidden-mobile ").find(" .content-visible ").find(".time.hidden-mobile").show();

                        $(this).parent().parent().parent().parent().find(".content-visible .accordion-train").show();

                        $(this).parent().parent().parent().parent().find(".content-visible .accordion-train .container-link").show();
                    }
                }
            });

        });

        $(".infomob .train.prossimi-treni .accordion-desk ").click(function (e) {
            var elem = $(this);
            if (!elem.hasClass("infomob-mob")) {
                if (!elem.hasClass("close-accordion-info-mob")) {
                    Trenord.ui.infoMobilita.closeAll();
                    setTimeout(function () {


                        if (elem.parents("#ricerca-stazione")) {
                            if (Trenord.utility.isMobile()) {
                                //       $(this).parent().parent().parent().find(".time.hidden-mobile").hide();
                                elem.parents(".content-visible").find(".container-link").hide();
                                elem.parent().parent().parent().parent().find(".content-accordion  .specific-detail").removeClass("hidden");
                            } else {
                                elem.parent().parent().parent().parent().find(".content-accordion .specific-detail").removeClass("hidden");

                                elem.parent().parent().parent().find(".time").hide();
                            }
                        }
                        elem.parent().parent().parent().parent().find(".content-accordion").fadeIn();
                        elem.parent().parent().parent().find(".time").hide();
                        elem.parent().parent().parent().find(".icon-train-prossimi").hide();
                        elem.parent().parent().parent().find(".text-train-prossimi").hide();
                        if (elem.parents(".train-history-result")) {
                            elem.parent().parent().parent().find(".specific-detail").html(" ");
                        }


                        elem.parent().parent().parent().find(".specific-detail.visible").hide();
                        elem.parent().parent().parent().find(".accordion-desk.infomob").hide();
                        elem.parent().parent().parent().find(".titolo-dettaglio-viaggio").show();
                    }, 200);
                }


            } else {
                $(this).parent().parent().parent().parent().find(".content-accordion").fadeIn();
                $(this).parent().parent().parent().find(".time").hide();
                $(this).parent().parent().parent().find(".accordion-train-close").hide();
                $(this).parent().parent().parent().find(".icon-train-prossimi").hide();
                $(this).parent().parent().parent().find(".text-train-prossimi").hide();
                $(this).parent().parent().parent().find(".specific-detail.visible").hide();
                $(this).parent().parent().parent().find(".accordion-desk.infomob").hide();
                $(this).parent().parent().parent().find(".titolo-dettaglio-viaggio").show();
                //   $(this).parent().parent().parent().find(".time.accordion").show();

            }

            Trenord.ui.carouselLine()
        });
    }
}

Trenord.ui.cookie = {

    initEvents: function () {

        $(".close-cookie-banner").click(function () {
            $(".box-cookie").fadeOut();

            if($("body").hasClass("malpensaStyle")){
                Trenord.utility.GAMalpensa();
            }else{
                Trenord.utility.GATrenord();
            }
        });


        $(document).mouseup(function (e) {

            var container = $(".box-cookie");

            if (!container.is(e.target) && container.has(e.target).length === 0) {
                container.fadeOut();
            }

        });

        if (!Trenord.user.haveAcceptedCookie()) {
            $(".box-cookie").fadeIn();
        }
    },

    accept: function () {

        if (!Trenord.user.haveAcceptedCookie()) {

            var scroll = $(window).scrollTop();

            if (scroll >= 8) {

                $(".box-cookie").fadeOut();

                Trenord.user.acceptCookie();

                if($("body").hasClass("malpensaStyle")){
                    Trenord.utility.GAMalpensa();
                }else{
                    Trenord.utility.GATrenord();
                }

            }
        }
    }
}

Trenord.ui.bookmarks = {

    canLoadHistory: true,
    canRegisterEvent: true,

    /**
     * questa funzione viene eseguita una volta sola
     */
    initEvents: function () {


        Trenord.ui.bookmarks.registerUserLoggedLoadHistory('station');
        Trenord.ui.bookmarks.registerUserLoggedLoadHistory('train');

        Trenord.events.register('userLogout', {type: 'station'}, function (event) {

            Trenord.ui.bookmarks.unregisterUserLoggedEvents();
            Trenord.ui.bookmarks.registerUserLoggedLoadHistory(event.data.type);
            Trenord.infoMobilita.loadHistory(event.data.type);

        });

        Trenord.events.register('close-login', [], function (event) {


            if (!Trenord.ui.bookmarks.canRegisterEvent && !Trenord.user.isLogged()) {
                Trenord.ui.bookmarks.unregisterUserLoggedEvents();
            }
        });

    },

    setStarStatus: function (code, favourite) {

        if (favourite) {
            $(".star.star-empty." + code).hide();
            $(".star.star-filled." + code).show();
        } else {
            $(".star.star-empty." + code).show();
            $(".star.star-filled." + code).hide();
        }
    },

    toggle: function (type, code, favourite, scenario, additionalData) {


        var params = {
            type: type,
            code: code,
            favourite: favourite,
            scenario: scenario
        };

        if((type === 'station' || type === 'train') && favourite == 'false') {
            dataLayer.push({
                event: 'add_to_preferred',
                evtCat: 'preferred',
                evtAction: `preferred_${type}`,
                evtLabel: additionalData
            });
        } 

        if (Trenord.user.isLogged()) {

            switch (scenario) {

                case 'stationDetail':
                case 'infomob':
                case 'discovery-catalog':
                    Trenord.popUpMessage.waitResponse();
                    break;

            }


            $.post('/rest/cta/bookmarks', params, function (data) {

                switch (scenario) {

                    case 'stationHistory':

                        if (data) {
                            //non devo fare niente
                            Trenord.infoMobilita.loadHistory(type);

                        } else {

                            //devo rimuovere
                            $(".star." + code).parent().parent().parent().remove();

                            if ($(".station-history-result .train-ricerca-stazione").length == 0) {
                                Trenord.infoMobilita.loadHistory(type);
                            }
                        }

                        //allla fine del giro devo sempre rimuovere l'evento altrimenti ad ogni login avrò queto problema
                        Trenord.ui.bookmarks.unregisterUserLoggedEvents();
                        Trenord.ui.bookmarks.registerUserLoggedLoadHistory(type);

                        break;


                    case 'infomob':
                    case 'stationDetail':
                    case 'discovery-catalog':

                        Trenord.popUpMessage.hideModalBox();
                        Trenord.ui.bookmarks.setStarStatus(code, data);

                        break;

                    case 'map':

                        var params = {
                            htmlIcon: additionalData,
                            mirCode: code,
                            favourite: data
                        }

                        $(document).trigger("togglePreferredStationMap", params);

                        break;

                }


            });

        } else {

            switch (scenario) {

                case 'stationHistory':
                case 'stationDetail':
                case 'infomob':
                case 'map':
                case 'discovery-catalog':

                    //ho bisogno di reagire quando l'utente si logga a seguito di quella attività
                    //questa funzione viene registrata più volte, quindi devo controllare
                    Trenord.ui.bookmarks.registerUserStatusEvent(params);

                    //apro la login perchè
                    //devo salvare l'operazione che devo fare
                    Trenord.ui.login.open();

                    break;
            }

        }
    },

    registerUserLoggedLoadHistory: function (type) {


        Trenord.events.register('userLogged', {type: type}, function (event) {
            if (Trenord.ui.bookmarks.canLoadHistory)
                Trenord.infoMobilita.loadHistory(event.data.type);
        });

    },


    registerUserStatusEvent: function (params) {


        if (Trenord.ui.bookmarks.canRegisterEvent && !Trenord.user.isLogged()) {

            Trenord.ui.bookmarks.canRegisterEvent = false;
            Trenord.ui.bookmarks.canLoadHistory = false;

            Trenord.events.register('userLogged', params, function (event) {

                //provo ad aspettare un attimo perchè lo stato di logged deve essere certo sul server
                //altrimenti non avremo i dati da loggato
                setTimeout(function () {
                    Trenord.ui.bookmarks.toggle(event.data.type, event.data.code, event.data.favourite, event.data.scenario);
                }, 100);

            });
        }
    },

    unregisterUserLoggedEvents: function () {

        //non si può gestire in questo punto questa istruzione altrimenti si abilità
        //l'esecuzione degli eventi in qualunque caso
        //Trenord.ui.bookmarks.canRegisterEvent = false;

        Trenord.events.remove('userLogged');
        Trenord.ui.bookmarks.canRegisterEvent = true;
        Trenord.ui.bookmarks.canLoadHistory = true;
    }
}

Trenord.ui.searchRealTimeFromParams = function () {

    var params = Trenord.utility.locationSearchToObject();

    var activateStation = function () {

        $("#ric-stazione").trigger("click");
        eval($("#station-option-" + params.station).attr('href'));

    };

    if (params.train && params.station) {
        console.log(params.stationName);
        setTimeout(activateStation, 1500);
        $('#station-search').val(params.stationName);
        Trenord.infoMobilita.stationDetails(params.station);


    } else if (params.train) {
        $('#train-search').val(params.train);
        Trenord.infoMobilita.trainDetail(params.train);
    } else if (params.station) {


        console.log(params.stationName);
        setTimeout(activateStation, 1500);
        setTimeout(function () {
            $('#station-search').val(params.stationName);
        },1700)

        Trenord.infoMobilita.stationDetails(params.station);
    }
}

Trenord.ui.searchStation = function (container, result, template) {

    var instance = this;

    instance.searchWait = 250;
    instance.searchInterval = null;

    instance.container = " " + container + " ";
    instance.input = " input ";
    instance.result = " " + result + " ";
    instance.template = template;

    instance.search = function (query) {

        var params = {
            query: query,
            template: instance.template
        };


        $.get('/rest/render/stationsList', params, function (result) {

            $(instance.container + instance.result).html(result.message);
            instance.initStationDropDownEvents();
        })
    }

    instance.initStationDropDownEvents = function () {


        $(instance.container + " .dropdown-station ul li").click(function () {

            $(instance.container + " .dropdown-station ul li").removeClass("selected");
            $(this).addClass("selected");
            $(instance.container + instance.input).val($(this).find("span").html()).addClass("text-capitalize");
            $(instance.container + " .dropdown-station").removeClass("active");
        });
    }

    instance.init = function () {

        //ricerca spalletta
        $(instance.container + instance.input).on('change keyup keydown paste cut', function () {

            var val = $(this).val();

            clearTimeout(instance.searchInterval);

            instance.searchInterval = setTimeout(function () {

                instance.search(val);

            }, instance.searchWait);

        });

        $(instance.container + " .dropdown-station .close-ticket").click(function () {

            if ($(instance.container + instance.input).val()) {
                $(instance.container + instance.input).parent().next().addClass("active");
            } else {
                $(instance.container + instance.input).parent().next().removeClass("active");
            }

            $(instance.container + ".dropdown-station").removeClass("active");
        });


        $(instance.container + instance.input).focus(function () {
            $(".close-ticket").trigger("click");
            $(this).parent().parent().find(".dropdown-station").addClass("active");
        });

        $("input.generic-input").focus(function () {
            $(this).next().addClass("active");
            $(this).parent().next().addClass("active");
        });

        $("input.generic-input").blur(function () {


            if (!$(".ticket-passenger-container").hasClass("active") || !$(".dropdown-station").hasClass("active") || $(this).val() != "") {

            } else {

                $(this).parent().next().removeClass("active");
            }

            if (!$(this).parent().next().hasClass("active")) {

            } else {
                $(this).next().removeClass("active");
            }
        });

        if ($("input.generic-input").val()) {
            $(this).parent().next().addClass("active");
            $(this).next().removeClass("active");
        }

    }

}


Trenord.ui.ideeDiViaggio = {

    visible: 8,
    increment: 8,
    total: $(".discovery-card").length,
    page: 1,


    init: function () {
        
        $(".header-idv-mobile a").click(function () {
            $("#switch-map-idv").trigger("click");
        })

        $("#discovery-catalog .container-idv").css("heigth", "auto");
        var maxHeight = Math.max.apply(null, $("#discovery-catalog .container-idv").map(function () {
            return $(this).height();
        }).get());

        $("#discovery-catalog .container-idv").height(maxHeight);


        var searchStation = new Trenord.ui.searchStation("#discovery-shoulder", '.station-list-result', 'discovery');
        searchStation.init();
        //faccio una ricerca delle stazioni di default in pagina per evitare caricamenti successivi
        searchStation.search("");

        $(".button-filter-border button").click(function () {


            if( $(".button-content ul li:first-child.hidden").length !==  $(".button-content ul").length){
                $(".remove-filter-container").removeClass("hidden");
            }else{
                $(".remove-filter-container").addClass("hidden");
            }

            if ($(this).parent().next().hasClass("hidden")) {
                $(this).addClass("active");
                $(this).parent().prev().removeClass("hidden");
                $(this).parent().next().removeClass("hidden");
            } else {
                $(this).removeClass("active");
                $(this).parent().prev().addClass("hidden");
                $(this).parent().next().addClass("hidden");
            }
        });

        $(".button-content .close-ticket").click(function () {
            $(this).parent().parent().prev().find("button").removeClass("active");
            $(this).parent().parent().prev().prev().addClass("hidden");
            $(".button-content").addClass("hidden");
        });

        $(".overlay-button-content").click(function () {
            $(".button-content:visible .close-ticket").trigger('click');

        });

        $(".overlay-ticket,.search-box-widget.full-overlay .right-shoulder .close-widget").click(function () {
            $(".close-ticket").trigger("click");
        });


        Trenord.ui.ideeDiViaggio.initFilters();
        Trenord.ui.ideeDiViaggio.total = $(".discovery-card").length;

    },

    nextPage: function () {

        $(".discovery-card").addClass('hidden');

        //calcolo la nuova pagina
        Trenord.ui.ideeDiViaggio.page++;
        Trenord.ui.ideeDiViaggio.visible = Trenord.ui.ideeDiViaggio.increment * Trenord.ui.ideeDiViaggio.page;

        $(".discovery-card").each(function (index, value) {
            if (index < Trenord.ui.ideeDiViaggio.visible) {
                $(value).removeClass('hidden');
            }
        })

        if (Trenord.ui.ideeDiViaggio.visible >= Trenord.ui.ideeDiViaggio.total) {
            $(".catalog-button").hide();
        }
    },


    highlightTravelIdeaMarker: function (id) {

        //da funzionalità della mappa noovle
        highlightTravelIdeaMarker(id);
    },

    onClickFilterValues: function (obj) {

        var count = $(obj).find(".count").remove();
        var buttonContent = $(obj).parents('.button-content')

        $(buttonContent).prev().find("button").text($(obj).text());

        $(obj).append(count);

        $(buttonContent).find("ul li ").removeClass("hidden");

        $(obj).parent().addClass("hidden");

        $(buttonContent).find(".close-ticket").trigger('click');

    },

    initFilters: function () {

        var currnetel = null;
        var last = null;
        $(".idee_carousel").on('changed.owl.carousel', function (property) {

            currnetel = property.item.index + property.page.size;
            last = property.item.count;
            if (currnetel === 1) {
                $(".slider_nav .prev_idee").hide();
                $(".slider_nav .prev_idee").css("opacity", "0");
                $(".slider_nav .prev_idee").addClass("hidden");
            }

            if (currnetel > 1) {
                $(".slider_nav .prev_idee").show();
                $(".slider_nav .prev_idee").css("opacity", "1");
                $(".slider_nav .prev_idee").removeClass("hidden");
            }
            if (currnetel === property.item.count) {
                $(".slider_nav .prev_idee").show();
                $(".slider_nav .prev_idee").css("opacity", "1");
                $(".slider_nav .prev_idee").removeClass("hidden")

                $(".slider_nav .next_idee").hide();
                $(".slider_nav .next_idee").css("opacity", "0");
                $(".slider_nav .next_idee").addClass("hidden");
            }

            if (currnetel < property.item.count) {
                $(".slider_nav .next_idee").show();
                $(".slider_nav .next_idee").css("opacity", "1");
                $(".slider_nav .next_idee").removeClass("hidden");
            }


        });


        $(".idee_carousel-container-fluid").hover(
            function () {

                $(".slider_nav .next_idee").show();
                $(".slider_nav .prev_idee").show();
                $(".slider_nav .next_idee").css("opacity", "1");
                $(".slider_nav .prev_idee").css("opacity", "1");
            }, function () {
                $(".slider_nav .next_idee").hide();
                $(".slider_nav .prev_idee").hide();
                $(".slider_nav .next_idee").css("opacity", "0");
                $(".slider_nav .prev_idee").css("opacity", "0");

            }
        );

        $(".idee_carousel").on('initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel', function (event) {
            var item = 0;
            var activeItem = 0;

            $(".idee_carousel .owl-item").each(function () {
                item++;
            });

            $(".idee_carousel .owl-item.active").each(function () {
                activeItem++;
            });

            if ($(".idee-container-fluid .idee_carousel .owl-item").hasClass("active")) {
                $(".idee-container-fluid .slider_nav a ").addClass("hidden");
            }


        }).owlCarousel({
            items: 1,
            loop: false,
            mouseDrag: true,

            dots: true,
            center: true,
            nav: false,
            responsiveClass: true,
            responsive: {
                0: {
                    mouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true
                },

                400: {
                    mouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true
                },

                600: {
                    mouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true
                },

                767: {
                    mouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true

                },
                768: {
                    mouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true

                },
                1024: {
                    mouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true
                },
                1280: {
                    moumouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true
                },
                1440: {
                    moumouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true
                },
                1680: {
                    moumouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    autoWidth: true
                },
                2800: {
                    moumouseDrag: true,
                    items: 1,
                    margin: 5,
                    dots: false,
                    loop: false,
                },

            }
        });

        var carousel_news = $(".idee_carousel");

        carousel_news.owlCarousel();
        //Custom Navigation Events
        $(".next_idee").click(function () {
            carousel_news.trigger('next.owl.carousel');
        });
        $(".prev_idee").click(function () {
            carousel_news.trigger('prev.owl.carousel');
        });


        $(".idee_carousel .item").click(function () {
            $(this).toggleClass("active");

            if ($(".idee_carousel .item.active").length >= 2) {
                $(".remove-filter-container").fadeIn().css("display", "inline-block");
            } else {
                $(".remove-filter-container").fadeOut();
            }
        });

        $(".remove-filter-container").click(function () {

            $(".idee_carousel .item").removeClass("active");
            //$(".remove-filter-container").fadeOut();

            $("[data-filter-value='default']").each(function (index, value) {
                
                    var hasVisible = !$(value).parent().hasClass('hidden');

                    if (hasVisible) {
                        $(value).trigger('click');
                    }
                })
            $(".overlay-button-content").addClass("hidden");
            $(".button-filter-border button.active").removeClass("active");
        });

    }

}
Trenord.ui.malpensaVoli = {


    h: 0,
    d: 0,
    limitElementVisible: 5,
    currentHours: 0,
    finalHours: 1440,
    currentMinutes: 0,
    numberError: 0,
    finalMinutes: 59,
    searchingAirports: false,
    airportApiRequest: null,
    multipleRequest: false,
    timeToWait: 250,
    datePickerObject: null,
    sliderObject: null,
    sliderFunction: null,


    initSlider: function () {


        function getQueryVariable(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) {
                    return pair[1];
                }
            }

        }

        var param1var = getQueryVariable("codiceVolo");
        if (param1var) {

            setTimeout(function () {
                $("#ricerca-treno-codice").show();
                $("#volo1").css("height", "auto");
            }, 500);
        }
        /* triggero la tab se ho nell'url la variabile codiceVolo */


        document.onkeypress = function (e) {
            e = e || window.event;
            if (e.key == "Enter" && $("#aereoporto-partenza").is(":focus")) {
                $(".menu-dropdown-voli.andata .default.list-andata li:first-child ").click();
                $(".menu-dropdown-voli.andata").fadeOut();
            }

            if (e.key == "Enter" && $("#aereoporto-arrivo").is(":focus")) {
                $(".menu-dropdown-voli.arrivo .default.list-arrivo li:first-child ").click();
                $(".menu-dropdown-voli.arrivo").fadeOut();
            }
        };


        $("#js-date-voli-aereo").click(function () {
            if (Trenord.utility.isMobile()) {
                setTimeout(function () {
                    $(".datepicker-dropdown.dropdown-menu.ricerca-voli").addClass("importantLeft");
                    $('html, body').animate({
                        scrollTop: $("#js-date-voli-aereo").offset().top - 100
                    }, 300);
                }, 50);
            } else {
                setTimeout(function () {
                    $(".datepicker-dropdown.dropdown-menu.ricerca-voli").removeClass("importantLeft");
                }, 50);
            }
        });


        if (Trenord.ui.malpensaVoli.currentMinutes >= 30) {
            console.log($(this));

            if (Trenord.ui.malpensaVoli.currentMinutes === 30) {
                Trenord.ui.malpensaVoli.currentMinutes = "30";
                Trenord.ui.malpensaVoli.currentHours = Trenord.ui.malpensaVoli.currentHours;
                $('.slider-time,.slider_time_ritorno').html(parseInt(Trenord.ui.malpensaVoli.currentHours / 60) + ':' + Trenord.ui.malpensaVoli.currentMinutes);
            } else {
                Trenord.ui.malpensaVoli.currentMinutes = "00";

                Trenord.ui.malpensaVoli.currentHours = Trenord.ui.malpensaVoli.currentHours;
                $('.slider-time,.slider_time_ritorno').html(parseInt(Trenord.ui.malpensaVoli.currentHours / 60) + ':' + Trenord.ui.malpensaVoli.currentMinutes);
            }

        } else {
            Trenord.ui.malpensaVoli.currentMinutes = "00";


            $('.slider-time,.slider_time_ritorno').html(parseInt(Trenord.ui.malpensaVoli.currentHours / 60) + ':' + Trenord.ui.malpensaVoli.currentMinutes);
        }


        if (Trenord.ui.malpensaVoli.finalMinutes === 59) {
            Trenord.ui.malpensaVoli.finalMinutes = "59";
            $('.slider-time2').html(parseInt(Trenord.ui.malpensaVoli.finalHours / 60 - 1) + ':' + Trenord.ui.malpensaVoli.finalMinutes);
        } else {

            if (Trenord.ui.malpensaVoli.finalMinutes >= 30) {

                if (Trenord.ui.malpensaVoli.finalMinutes === 30) {
                    Trenord.ui.malpensaVoli.finalMinutes = "30";
                    Trenord.ui.malpensaVoli.finalHours = Trenord.ui.malpensaVoli.finalHours;
                    $('.slider-time2').html(parseInt(Trenord.ui.malpensaVoli.finalHours / 60) + ':' + Trenord.ui.malpensaVoli.finalMinutes);
                } else {
                    Trenord.ui.malpensaVoli.finalMinutes = "00";
                    Trenord.ui.malpensaVoli.finalHours = Trenord.ui.malpensaVoli.finalHours;
                    $('.slider-time2').html(parseInt(Trenord.ui.malpensaVoli.finalHours / 60) + ':' + Trenord.ui.malpensaVoli.finalMinutes);
                }

            } else {
                Trenord.ui.malpensaVoli.finalMinutes = "00";
                $('.slider-time2').html(parseInt(Trenord.ui.malpensaVoli.finalHours / 60) + ':' + Trenord.ui.malpensaVoli.finalMinutes);
            }
        }


        if ($(".slider-range").length) {

            if (Trenord.ui.malpensaVoli.sliderFunction == undefined || Trenord.ui.malpensaVoli.sliderFunction == null) {

                Trenord.ui.malpensaVoli.sliderFunction = function (e, ui) {


                    if (ui.values[0] + 19 >= ui.values[1]) {
                        return false;
                    } else {

                        var hours1 = Math.floor(ui.values[0] / 60);
                        var minutes1 = ui.values[0] - (hours1 * 60);
                        if (hours1.length == 1) hours1 = '0' + hours1;
                        if (minutes1.length == 1) minutes1 = '0' + minutes1;
                        if (minutes1 == 0) minutes1 = '00';
                        if (hours1 >= 12) {
                            if (hours1 == 12) {
                                hours1 = hours1;
                                minutes1 = minutes1 + " ";
                            } else {
                                hours1 = hours1;
                                minutes1 = minutes1 + " ";
                            }
                        } else {
                            hours1 = hours1;
                            minutes1 = minutes1 + " ";
                        }
                        if (hours1 == 0) {
                            hours1 = 00;
                            minutes1 = minutes1;
                        }

                    }

                    if ($(this).attr('id') == 'slider-range-ritorno') {
                        $('.slider_time_ritorno').html(hours1 + ':' + minutes1);
                        $('#orario1_ritorno').val(hours1 + ':' + minutes1);

                    } else {

                        $('.slider-time').html(hours1 + ':' + minutes1);
                        $('#orario1').val(hours1 + ':' + minutes1);
                    }


                    var hours2 = Math.floor(ui.values[1] / 60);
                    var minutes2 = ui.values[1] - (hours2 * 60);

                    if (hours2.length == 1) hours2 = '0' + hours2;
                    if (minutes2.length == 1) minutes2 = '0' + minutes2;
                    if (minutes2 == 0) minutes2 = '00';
                    if (hours2 >= 12) {
                        if (hours2 == 12) {
                            hours2 = hours2;
                            minutes2 = minutes2 + "";
                        } else if (hours2 == 24) {
                            hours2 = 23;
                            minutes2 = "59 ";
                        } else {
                            hours2 = hours2;
                            minutes2 = minutes2 + " ";
                        }
                    } else {
                        hours2 = hours2;
                        minutes2 = minutes2 + " ";
                    }


                    if ($(this).attr('id') == 'slider-range-ritorno') {
                        $('.slider_time2_ritorno').html(hours2 + ':' + minutes2);
                        $('#orario2_ritorno').val(hours2 + ':' + minutes2);
                    } else {
                        $('.slider-time2').html(hours2 + ':' + minutes2);
                        $('#orario2').val(hours2 + ':' + minutes2);
                    }


                    if ($(this).parent().parent().hasClass("form-slider-range")) {
                        if ($(this).attr('id') == 'slider-range-ritorno') {
                            var dateInput = $("#ritorno_form_gruppi").val().split("Tra");

                            $('#ritorno_form_gruppi').val("").datepicker("update");


                            if (dateInput !== " ") {
                                $("#ritorno_form_gruppi").datepicker("setDate", dateInput[0]);
                            }

                            if (dateInput == "") {
                                $("#ritorno_form_gruppi").datepicker("setDate", new Date());
                            }

                            var time1 = $("#time-range-ritorno .slider_time_ritorno").html();
                            var time2 = $("#time-range-ritorno .slider_time2_ritorno").html();
                            $("#ritorno_form_gruppi").val("" + dateInput[0].replace(/\s/g, "") + " Tra le " + time1 + " e le " + time2 + "");
                        } else {
                            if ($(".fatture").length > 0) {

if( !$("#data_fattura").parent().find("label").hasClass("active")){
 $("#data_fattura").parent().find("label").addClass("active");
}                               

                
                               
                              $(".copy-time").val( $(".slider-time").text() );
                            if ($("#orario1").val() !== "") {

                                if ($("#data_fattura").val() !== "") {
                            var dateInput = $("#data_fattura").val().split("Alle");
                            $("#data_fattura").val("" + dateInput[0].replace(/\s/g, "")  + " Alle " + $("#orario1").val() + "");
                        } else {

                             $("#data_fattura").val(" ");
                            $("#data_fattura").val(" Alle " + $("#orario1").val() + "");

                        }
                    }

                            } else {
                                var dateInput = $("#andata_form_gruppi").val().split("Tra");

                                $('#andata_form_gruppi').val("").datepicker("update");


                                var time1 = $("#time-range .slider-time").html();
                                var time2 = $("#time-range .slider-time2").html();
                               
                                $("#andata_form_gruppi").val("" + dateInput[0].replace(/\s/g, "") + " Tra le " + time1 + " e le " + time2 + "");
                            }

                        }


                    } else {
                        var dateInput = $("#js-date-voli-aereo").val().split("Tra");

                        $('#js-date-voli-aereo').val("").datepicker("update");

                        if (dateInput !== " ") {
                            $("#js-date-voli-aereo").datepicker("setDate", dateInput[0]);
                        }

                        if (dateInput == "") {
                            $("#js-date-voli-aereo").datepicker("setDate", new Date());
                        }


                        var time1 = $("#time-range .slider-time").html();
                        var time2 = $("#time-range .slider-time2").html();
                        $("#js-date-voli-aereo").val("" + dateInput[0].replace(/\s/g, "") + " Tra le " + time1 + " e le " + time2 + "");
                    }

                };

            }


            Trenord.ui.malpensaVoli.sliderObject = $(".slider-range").slider({
                range: true,
                min: 0,
                max: 1440,
                step: 30,
                values: [Trenord.ui.malpensaVoli.currentHours, Trenord.ui.malpensaVoli.finalHours],
                slide: Trenord.ui.malpensaVoli.sliderFunction
            });
        }
    },


    initCalendar: function () {


        /* data per ricerca voli */


        $("#js-date-voli-aereo, #andata_form_gruppi").on("changeDate", function (e) {

            var dateInput = $(this).val().split("Tra");
            $('#data').val(dateInput[0]);
            $("label.date").css("color", "#212121");
            $(this).css("border-bottom", "1px solid #212121");
            $(this).html("");
            var time1 = $("#time-range .slider-time").html();
            var time2 = $("#time-range .slider-time2").html();
            $("#orario1").val(time1);
            $("#orario2").val(time2);
            $(this).val("" + dateInput + ", Tra le " + time1 + " e le " + time2 + "");
            $("label.date").css("top", "-10px");
            $("label.date").css("font-size", "0.7222rem");
            $("label.date").css("color", "#212121");
        });

        if ($('#js-date-voli-aereo').length) {
            Trenord.ui.malpensaVoli.datePickerObject = $('.container-voli-input .md-input.date .md-form-control').datepicker({
                onSelect: function (dateText, inst) {

                },

                startDate: new Date(),
                maxViewMode: 0,
                language: 'IT',
                forceParse: false,
                format: 'dd-mm-yyyy',
                orientation: 'auto bottom',
                todayHighlight: true,
                changeMonth: false,
                changeYear: false,
                onClose: function (date, datepicker) {
                    if (date != "") {

                    }
                }
            }).on("show", function (e) {

                var timeRange = $("#time-range");
                timeRange.show();
                if ($("#aereoporto-partenza").val() === Trenord.globals.mxpAirportLabel) {
                    $(".switch-malpensa").html("" + Trenord.lang.flightCalendar.takesOff + "");

                } else {
                    $(".switch-malpensa").html("" + Trenord.lang.flightCalendar.titleLeft + "");
                }
                $(" .datepicker .prev, .datepicker .next").empty();

                if (!$(".datepicker-dropdown h4").length) {
                    $(".datepicker-dropdown").prepend("<h4>" + Trenord.lang.flightCalendar.titleCalendar + "</h4>");
                    $(".datepicker-dropdown").prepend("<img  alt='icona_chiudi_calendario' class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");
                    $(".datepicker-dropdown").append(timeRange);
                } else {
                    var timeRange = $("#time-range");
                    timeRange.show();
                    $(".datepicker-dropdown").append(timeRange);
                }
                $(".datepicker-dropdown .close-datepicker,.datepicker-dropdown .button-container").click(function () {
                    $('.datepicker').hide();
                    $("label.date").css("top", "-10px");
                    $("label.date").css("font-size", " 0.7222rem");

                });

                $(".datepicker-dropdown").addClass("ricerca-voli");

                $("label.date").addClass("active-date-label");
                $(".datepicker-dropdown .button-container").show();
                if (Trenord.utility.isMobile() && !$(".datepicker-dropdown .button-container").length) {

                    $(".datepicker-dropdown").append("<div class='button-container'><div class='button  white-trenordplus'> " + Trenord.lang.flightCalendar.sumbit + "</div></div>")


                }
            }).attr('readonly', 'readonly');
        }
    },
    initEvents: function () {


        toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": false,
            "positionClass": "toast-container",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        };

        Trenord.ui.malpensaVoli.h = 0;
        Trenord.ui.malpensaVoli.d = new Date();
        Trenord.ui.malpensaVoli.currentHours = Math.floor(Trenord.ui.malpensaVoli.d.getHours() * 60);
        Trenord.ui.malpensaVoli.finalHours = Trenord.ui.malpensaVoli.finalHours;
        Trenord.ui.malpensaVoli.currentMinutes = Trenord.ui.malpensaVoli.d.getMinutes();
        Trenord.ui.malpensaVoli.finalMinutes = Trenord.ui.malpensaVoli.finalMinutes;

        Trenord.ui.malpensaVoli.initSlider();
        Trenord.ui.malpensaVoli.initCalendar();


        $("#aereoporto-partenza,#aereoporto-arrivo,#compagnia-aerea").focus(function () {
            if (Trenord.utility.isMobile()) {

            }
        });

        $("#submit-ricerca-volo-codice").click(function () {
            if ($("#codice-volo").val() === "") {
                $(".error-volo-codice").fadeIn();
            } else {

                if ($("#codice-volo").val().replace(/\s/g, '').match(/^[a-zA-Z]{2}[0-9]{4}$/i)) {

                    $("#form-cerca-tramite-codice").submit();

                } else {
                    $(".error-volo-codice").fadeIn();
                }
            }
        });


        $('#codice-volo').on('keyup', function () {
            if ($("#codice-volo").val().replace(/\s/g, '').match(/^[a-zA-Z]{2}[0-9]{4}$/i)) {
                $(".error-volo-codice").fadeOut();
            }
        });

        $(document).on('click', '.container-select button', function () {

            var eleme = $(this);

            setTimeout(function () {
                if (eleme.parent().find(".dropdown-menu").hasClass("open")) {
                    eleme.parent().parent().find("label").addClass("active-label-voli");

                } else {
                }
            }, 50);
        });


        $('#from_airport_iata').on('input', function () {
            if ($(this).val() !== "") {
                $(".error-volo-codice.andata").fadeOut();
            }
        });


        $("#submit-ricerca-volo").click(function () {

            /*  se vuoti */

            Trenord.ui.malpensaVoli.numberError = 0;


            /*  controlli  partenza */

            if ($("#aereoporto-partenza").val() == "") {
                $(".label-partenza").css("color", "#ff0000");
                $("#aereoporto-partenza").css("border-bottom", "1px solid #ff0000");
                Trenord.ui.malpensaVoli.numberError += 1;
            }
            /*  controlli  arrivo */

            if ($("#aereoporto-arrivo").val() == "") {
                $(".label-arrivo").css("color", "#ff0000");
                $("#aereoporto-arrivo").css("border-bottom", "1px solid #ff0000");
                Trenord.ui.malpensaVoli.numberError += 1;
            }
            /*  controlli  data */

            if (!$("#js-date-voli-aereo").datepicker("getDate")) {
                $("label.date").css("color", "#ff0000");
                $("#js-date-voli-aereo").css("border-bottom", "1px solid #ff0000");
                Trenord.ui.malpensaVoli.numberError += 1;
            }


            /*  alert campi obbligatori */
            if (Trenord.ui.malpensaVoli.numberError !== 0) {
                $(".container-error-box").fadeIn();
                setTimeout(function () {


                    $(".container-error-box").fadeOut();
                }, 2000);
            }


            /*  controllo iata from */
            if ($("#from_airport_iata").val() == "" && $("#aereoporto-partenza").val() !== "") {
                $(".error-volo-codice.andata").fadeIn();
            }

            if ($("#from_airport_iata").val() == "" && $("#aereoporto-partenza").val() == "") {
                $(".error-volo-codice.andata").fadeOut();
            }

            /*  controllo iata tp */
            if ($("#to_airport_iata").val() == "" && $("#aereoporto-arrivo").val() !== "") {
                $(".error-volo-codice.arrivo").fadeIn();
            }

            if ($("#to_airport_iata").val() == "" && $("#aereoporto-arrivo").val() == "") {
                $(".error-volo-codice.arrivo").fadeOut();
            }


            /*  controllo iata flight */
            if ($("#flight_company_iata").val() == "" && $("#compagnia-aerea").val() !== "") {
                $(".error-volo-codice.compagnia").fadeIn();
            }

            if ($("#flight_company_iata").val() == "" && $("#compagnia-aerea").val() == "") {
                $(".error-volo-codice.compagnia").fadeOut();
            }


            if ($("#from_airport_iata").val() !== "" && $("#to_airport_iata").val() !== "" && $("#aereoporto-partenza").val() !== "" && $("#aereoporto-arrivo").val() !== "" && $("#js-date-voli-aereo").datepicker("getDate")) {


                if ($("#compagnia-aerea").val() !== "" && $("#flight_company_iata").val() !== "") {
                    $("#cerca-treno-con-volo").submit();
                }


                if ($("#compagnia-aerea").val() == "" && $("#flight_company_iata").val() == "") {
                    $("#cerca-treno-con-volo").submit();
                }


            }


        });

        $('#aereoporto-arrivo').on('focus', function () {

            if ($('#aereoporto-arrivo').val() !== "") {

                $('#aereoporto-arrivo').trigger('keyup', {
                    resetInput: 'no'
                });
            }

            $('.menu-dropdown-voli.arrivo .default.list-arrivo').removeClass("hidden").addClass("show-item");


        }).on('blur', function () {
            $(".menu-dropdown-voli.arrivo").fadeOut("");
        });

        $('#aereoporto-partenza').on('focus', function () {

            if ($('#aereoporto-partenza').val() !== "") {

                $('#aereoporto-partenza').trigger('keyup', {
                    resetInput: 'no'
                });
            }

            $(".menu-dropdown-voli.andata .default.list-andata").removeClass("hidden").addClass("show-item");


        }).on('blur', function () {
            $(".menu-dropdown-voli.andata").fadeOut("");
        });


        $('#compagnia-aerea').on('focus', function () {

            if ($('#compagnia-aerea').val() !== "") {

                $('#compagnia-aerea').trigger('keyup', {
                    resetInput: 'no'
                });
            }

            $('.menu-dropdown-voli.compagnia .default.list-compagnia').removeClass("hidden").addClass("show-item");


        }).on('blur', function () {
            $(".menu-dropdown-voli.compagnia").fadeOut("");
        });


        $('#aereoporto-arrivo').on('keyup', {
            inputClass: 'arrivo',
            resetInput: 'si',

        }, Trenord.ui.malpensaVoli.autocompleteAirports);

        $('#aereoporto-partenza').on('keyup', {
            inputClass: 'andata',
            resetInput: 'si',

        }, Trenord.ui.malpensaVoli.autocompleteAirports);

        $('#compagnia-aerea').on('keyup', {
            inputClass: 'compagnia',
            resetInput: 'si',

        }, Trenord.ui.malpensaVoli.autocompleteAirlines);


        $(".nav-tabs-horizontal.volo li").click(function () {

            $("#direzione").val($(this).attr("data-value"));
            $("#direzione-codice").val($(this).attr("data-value"));

            if ($(this).data("value") == "from-malpensa") {

                /* questo contollo mi serve perchè non è detto che vada cambiato il contenuto */
                /* degli aereporti, per esempio in ricerca voli vengono settati da un altra procedura */
                if (Trenord.globals.checkAiport) {

                    setTimeout(function () {
                        $("#aereoporto-arrivo").val(Trenord.globals.mxpAirportLabel);
                        $("#to_airport_iata").val("MXP");
                        $("#aereoporto-partenza").val("");
                        $("#from_airport_iata").val("");

                        $("#aereoporto-partenza").trigger("focus");


                    }, 50);

                } else {
                    Trenord.globals.checkAiport = true;
                }


            } else {

                /* questo contollo mi serve perchè non è detto che vada cambiato il contenuto */
                /* degli aereporti, per esempio in ricerca voli vengono settati da un altra procedura */
                if (Trenord.globals.checkAiport) {

                    setTimeout(function () {

                        $("#aereoporto-partenza").val(Trenord.globals.mxpAirportLabel);
                        $("#to_airport_iata").val("");
                        $("#aereoporto-arrivo").val("");
                        $("#from_airport_iata").val("MXP");

                        $("#aereoporto-arrivo").trigger("focus");


                    }, 50);
                } else {
                    /* è un semaforo che si deve riattivare */
                    Trenord.globals.checkAiport = true;
                }

            }
        });


        $("#switch-to-code-train").click(function () {

            $('#ricerca-treno-volo').animate({
                opacity: 0
            });
            $("#volo1").height($("#volo1").height());
            $('#ricerca-treno-volo').fadeOut();
            setTimeout(function () {
                $('#ricerca-treno-volo').addClass("height-tool").fadeIn();
                if ($('#ricerca-treno-codice').height() !== 0) {
                    h = $('#ricerca-treno-codice').height();
                    showCodice(h);
                }

                $('#ricerca-treno-codice').hide().removeClass("height-tool");

            }, 200);

            function showCodice(showHeigth) {

                setTimeout(function () {
                    $('#volo1').animate({
                        height: showHeigth + 90
                    });
                    $('#ricerca-treno-codice').fadeIn("slow");
                    $('#ricerca-treno-codice').animate({
                        opacity: 1
                    });
                }, 300);

            }

        });


        $("#switch-to-flight").click(function () {

            $('#ricerca-treno-codice').animate({
                opacity: 0
            });
            $("#volo1").height($("#volo1").height());
            $('#ricerca-treno-codice').fadeOut();
            setTimeout(function () {
                $('#ricerca-treno-codice').addClass("height-tool").fadeIn();
                if ($('#ricerca-treno-volo').height() !== 0) {
                    h = $('#ricerca-treno-volo').height();
                }


                $('#ricerca-treno-volo').hide().removeClass("height-tool");


                showCodice(h);


            }, 200);

            function showCodice(showHeigth) {

                setTimeout(function () {
                    $('#volo1').animate({
                        height: showHeigth + 90
                    });
                    $('#ricerca-treno-volo').fadeIn().show();
                    $('#ricerca-treno-volo').animate({
                        opacity: 1
                    });
                }, 300);

            }

        });

    },

    autocompleteAirports: function (event, resetInput) {


        var searchTerm = $(this).val().toLowerCase().replace(/\(.*?\)/g, "").trim();
        var inputClass = event.data.inputClass;
        var resetInput = (resetInput == undefined ? event.data.resetInput : resetInput);


        if (resetInput == 'si') {
            switch (inputClass) {
                case "andata":
                    $("#from_airport_iata").val("");
                    break;
                case "arrivo":
                    $("#to_airport_iata").val("");
                    break;
            }
        }

        /* se per caso è necessario fare più chiamate posso disabilitare il semaforo */
        if (Trenord.ui.malpensaVoli.airportApiRequest != null && !Trenord.ui.malpensaVoli.multipleRequest) {
            clearTimeout(Trenord.ui.malpensaVoli.airportApiRequest);
        }

        if (searchTerm.length > 1) {


            Trenord.ui.malpensaVoli.airportApiRequest = setTimeout(function () {


                $.get('/rest/render/airportsList', {
                    query: searchTerm
                }, function (data) {
                    $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass).html("");
                    if (data.message == "") {
                        $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").html("");
                        $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").hide();
                        $(".menu-dropdown-voli." + inputClass + " .no-result").show();
                        setTimeout(function () {
                            $(".menu-dropdown-voli." + inputClass + "").fadeIn();
                        }, 50);
                    } else {
                        $(".menu-dropdown-voli." + inputClass + " .no-result").hide();
                        $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").show();


                        var splitFlight = data.message.split("</li>");
                        var countFlight = 0;
                        var numberFlight = Trenord.utility.isMobile() ? 4 : 5;
                        splitFlight.forEach(function (index) {

                            if (countFlight < numberFlight) {
                                $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass).append(index);
                            }
                            countFlight++;
                        });


                        setTimeout(function () {
                            $(".menu-dropdown-voli." + inputClass + "").fadeIn();
                        }, 50);

                        Trenord.ui.malpensaVoli.initAirportsInputEvents();
                    }

                });


            }, Trenord.ui.malpensaVoli.timeToWait);
        } else {
            $(".menu-dropdown-voli." + inputClass + "").fadeOut();
            $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").html("");
        }


    },

    initAirportsInputEvents: function () {

        $(".arrivo .lista-aereoporti li, .arrivo  .default li").click(function () {

            $(".error-volo-codice.arrivo").fadeOut();
            $("#second-step").fadeIn();
            $("#volo1").css("height", "auto");
            $("#aereoporto-arrivo").val($(this).attr('data-search-term').replace(/\s+/g, ' ').trim());
            $("#to_airport_iata").val($(this).attr('data-iata'));
            $(".label-arrivo").css("color", "#4a4a4a");
            $("#aereoporto-arrivo").css("border-bottom", "1px solid #4a4a4a");
            var elementRight = $(this).attr('data-search-term').replace(/\s+/g, ' ').trim();

            if (elementRight === Trenord.globals.mxpAirportLabel && $("#aereoporto-partenza").val() === Trenord.globals.mxpAirportLabel) {
                $("#aereoporto-partenza").val("");
                $("#from_airport_iata").val("");
                $(".error-volo-codice.andata").fadeOut();
                $("#aereoporto-partenza").trigger("focus");
                $(".label-partenza").css("color", "#4a4a4a");
                $("#aereoporto-partenza").css("border-bottom", "1px solid #4a4a4a");


            }

            if ($("#aereoporto-partenza").val() === elementRight) {
                $("#aereoporto-partenza").val("");
                $("#from_airport_iata").val("");
            }


            if (elementRight !== Trenord.globals.mxpAirportLabel && $("#aereoporto-partenza").val() !== Trenord.globals.mxpAirportLabel) {

                $("#aereoporto-partenza").val(Trenord.globals.mxpAirportLabel);
                $("#from_airport_iata").val("MXP");
                $("#second-step").fadeIn();
                $(".label-partenza").css("color", "#4a4a4a");
                $("#aereoporto-partenza").css("border-bottom", "1px solid #4a4a4a");
                $(".error-volo-codice.andata").fadeOut();

            }


        });

        $(".andata .lista-aereoporti li, .andata  .default li").click(function () {

            $("#aereoporto-partenza").val($(this).attr('data-search-term').replace(/\s+/g, ' ').trim());
            $("#from_airport_iata").val($(this).attr('data-iata'));
            $("#second-step").fadeIn();
            $(".error-volo-codice.andata").fadeOut();
            $(".label-partenza").css("color", "#4a4a4a");
            $("#aereoporto-partenza").css("border-bottom", "1px solid #4a4a4a");

            $(".label-partenza").css("color", "#4a4a4a");
            $("#aereoporto-partenza").css("border-bottom", "1px solid #4a4a4a");
            var elementRight = $(this).attr('data-search-term').replace(/\s+/g, ' ').trim();

            if (elementRight === Trenord.globals.mxpAirportLabel && $("#aereoporto-arrivo").val() === Trenord.globals.mxpAirportLabel) {
                $("#aereoporto-arrivo").val("");
                $("#to_airport_iata").val("");
            }

            if (elementRight !== Trenord.globals.mxpAirportLabel && $("#aereoporto-arrivo").val() !== Trenord.globals.mxpAirportLabel) {
                $("#aereoporto-arrivo").val(Trenord.globals.mxpAirportLabel);
                $("#to_airport_iata").val("MXP");
                $(".label-arrivo").css("color", "#4a4a4a");
                $(".error-volo-codice.arrivo").fadeOut();
                $("#aereoporto-arrivo").css("border-bottom", "1px solid #4a4a4a");

            }


            if ($("#aereoporto-arrivo").val() === elementRight) {
                $("#aereoporto-arrivo").val("");
                $("#to_airport_iata").val("");
            }


            $("#second-step").fadeIn();
            $("#volo1").css("height", "auto");


        });


    },

    initAirlinesInputEvent: function () {

        $(".default.list-compagnia li").click(function () {

            $("#compagnia-aerea").val($(this).attr('data-search-term').replace(/\s+/g, ' ').trim());
            $("#flight_company_iata").val($(this).attr('data-iata'));
            $(".menu-dropdown-voli.compagnia").hide();

        });


    },


    autocompleteAirlines: function (event, resetInput) {


        var searchTerm = $(this).val().toLowerCase().replace(/\(.*?\)/g, "").trim();
        var inputClass = event.data.inputClass;
        var resetInput = (resetInput == undefined ? event.data.resetInput : resetInput);

        if (resetInput == 'si') {
            $("#flight_company_iata").val("");
        }

        /* se per caso è necessario fare più chiamate posso disabilitare il semaforo */
        if (Trenord.ui.malpensaVoli.airportApiRequest != null && !Trenord.ui.malpensaVoli.multipleRequest) {
            clearTimeout(Trenord.ui.malpensaVoli.airportApiRequest);
        }

        if (searchTerm.length > 1) {


            Trenord.ui.malpensaVoli.airportApiRequest = setTimeout(function () {

                $.get('/rest/render/airlinesList', {
                    query: searchTerm
                }, function (data) {

                    $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass).html("");

                    if (data.message == "") {

                        $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").html("");
                        $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").hide();
                        $(".menu-dropdown-voli." + inputClass + " .no-result").show();

                        setTimeout(function () {
                            $(".menu-dropdown-voli." + inputClass + "").fadeIn();
                        }, 50);

                    } else {

                        $(".menu-dropdown-voli." + inputClass + " .no-result").hide();
                        $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").show();

                        var splitFlight = data.message.split("</li>");
                        var countFlight = 0;
                        var numberFlight = Trenord.utility.isMobile() ? 4 : 5;

                        splitFlight.forEach(function (index) {

                            if (countFlight < numberFlight) {
                                $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass).append(index);
                            }
                            countFlight++;
                        });


                        setTimeout(function () {
                            $(".menu-dropdown-voli." + inputClass + "").fadeIn();
                        }, 50);


                        Trenord.ui.malpensaVoli.initAirlinesInputEvent();
                    }

                });


            }, Trenord.ui.malpensaVoli.timeToWait);
        } else {
            $(".menu-dropdown-voli." + inputClass + "").fadeOut();
            $(".menu-dropdown-voli." + inputClass + " .default.list-" + inputClass + "").html("");
        }


    }


}
Trenord.ui.malpensaWidget = {

    setForm: function () {

        $(".ticket-from").val(Trenord.passengersWidget.from);
        $(".ticket-to").val(Trenord.passengersWidget.to);
        $(".ticket-date").val(Trenord.passengersWidget.date);
        $(".ticket-time").val(Trenord.passengersWidget.time);
        $(".ticket-adulti").val(Trenord.passengersWidget.travellers.adults);
        $(".ticket-bambini").val(Trenord.passengersWidget.travellers.children);
        $(".ticket-senior").val(Trenord.passengersWidget.travellers.seniors);
        $(".ticket-family").val(Trenord.passengersWidget.travellers.family);

    },

    initEvents: function () {


        $(".container-malpnesa-widget .malpensa-widget .body .item .add-remove .add").click(function () {


            //questa modalità per non duplicare codice
            Trenord.passengersWidget.triggerPositive();
            Trenord.ui.malpensaWidget.onClick(this);

        });

        $(".container-malpnesa-widget .malpensa-widget .body .item .add-remove .remove").click(function () {

            //questa modalità per non duplicare codice
            Trenord.passengersWidget.triggerNegative();
            Trenord.ui.malpensaWidget.onClick(this);

        })

        //inizializzazione degli oggetti in pagina con i valoridi default
        //di passengerWidget
        $(".container-malpnesa-widget .malpensa-widget .body .item .number.adulti ").html(Trenord.passengersWidget.travellers.adults);
        $(".container-malpnesa-widget .malpensa-widget .body .item .number.bambini ").html(Trenord.passengersWidget.travellers.children + "</h1>");
        $(".container-malpnesa-widget .malpensa-widget .body .item .number.senior ").html(Trenord.passengersWidget.travellers.seniors + "</h1>");
        $(".container-malpnesa-widget .malpensa-widget .body .item .number.family ").html(Trenord.passengersWidget.travellers.family + "</h1>");

    },

    onClick: function (obj) {


        var cat = $(obj).data("cat");

        switch (cat) {
            case "adulti":
                Trenord.passengersWidget.addAdults();
                $(".container-malpnesa-widget .malpensa-widget .body .item .number.adulti ").html(Trenord.passengersWidget.travellers.adults);

                break;
            case "bambini":
                Trenord.passengersWidget.addChildren();
                $(".container-malpnesa-widget .malpensa-widget .body .item .number.bambini ").html(Trenord.passengersWidget.travellers.children);

                break;
            case "senior":
                Trenord.passengersWidget.addSenior();
                $(".container-malpnesa-widget .malpensa-widget .body .item .number.senior ").html(Trenord.passengersWidget.travellers.seniors);

                break;
            case "family":
                Trenord.passengersWidget.addFamily();
                $(".container-malpnesa-widget .malpensa-widget .body .item .number.family ").html(Trenord.passengersWidget.travellers.family);

                break;
        }

        Trenord.ui.malpensaWidget.setForm();

    },

    loadMalpensaVisualization: function () {
        $("#ticket-shoulder .malpensa-visualization").show();
        $("#ticket-shoulder .trenord-visualization").hide();

        $("#ticket-shoulder .ticket-family").prop('disabled', false);
        $("#ticket-shoulder .ticket-senior").prop('disabled', true);

    },

    loadTrenordVisualization: function () {
        $("#ticket-shoulder .malpensa-visualization").hide();
        $("#ticket-shoulder .trenord-visualization").show();

        $("#ticket-shoulder .ticket-family").prop('disabled', true);
        $("#ticket-shoulder .ticket-senior").prop('disabled', false);
    }


}

Trenord.ui.carouselGeneric = function () {



    $(".generic-carousel").on('changed.owl.carousel', function (property) {
        if (property.item.index == 0) {

            $(".slider_nav .genericCarouselprev").addClass("hidden");
            $(".slider_nav .genericCarouselnext").removeClass("hidden");

        } else {

            var currnetel = property.item.index + property.page.size;
            // last element
            if (currnetel == property.item.count) {
                $(".slider_nav .genericCarouselnext").addClass("hidden");
                $(".slider_nav .genericCarouselprev").removeClass("hidden");


            } else {
                $(".slider_nav .genericCarouselnext").removeClass("hidden");
                $(".slider_nav .genericCarouselprev").removeClass("hidden");

            }
        }
    });

    $(".generic-carousel").on('initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel', function (event) {
        var item = 0;
        var activeItem = 0;
        var currentindex = event.item.index;


        $(".generic-carousel .owl-item").each(function () {
            item++;
        });


        if (currentindex === item) {
            $(".slider_nav .genericCarouselnext").css("opacity", "0");
            $(".slider_nav .genericCarouselnext").hide();
        }

        $(".generic-carousel .owl-item.active").each(function () {
            activeItem++;

        });

        if (item == activeItem) {
            $(".slider_nav .genericCarouselnext").hide();
            $(".slider_nav .genericCarouselprev").hide();
            $(".slider_nav *").hide();
        } else {
            $(".slider_nav .genericCarouselnext").show();
            $(".slider_nav .genericCarouselprev").show();
            $(".slider_nav *").show();
        }


        $(".box-hover-generic-carousel").hover(
            function () {
                $(".slider_nav .genericCarouselnext").css("opacity", "1");
                $(".slider_nav .genericCarouselprev").css("opacity", "1");
            }, function () {
                $(".slider_nav .genericCarouselnext").css("opacity", "0");
                $(".slider_nav .genericCarouselprev").css("opacity", "0");

            }
        );


        /*
                if(Trenord.utility.isMobile()){
                    $(".genericCarouselnext").hide();
                    $(".genericCarouselprev").hide();
                }else{
                    $(".genericCarouselnext").show();
                    $(".genericCarouselprev").show();
                }*/

    }).owlCarousel({
        items: 3,
        loop: false,
        dots: true,
        center: false,
        nav: false,
        moumouseDrag: true,
        responsiveClass: true,
        responsive: {
            0: {
                moumouseDrag: true,
                items: 1,
                center:true

            },
            768: {
                moumouseDrag: true,
                items: 2,
                margin: 50,
                center:false

            },
            1024: {
                moumouseDrag: true,
                items: 2,
                margin: 50,
                dots: true
            },
            1280: {
                moumouseDrag: true,
                items: 3,
                margin: 50,
                dots: true
            },
            1440: {
                moumouseDrag: true,
                items: 3,
                margin: 270,
                dots: true,
            },
            1680: {
                moumouseDrag: true,
                items: 3,
                margin: 0,
                dots: true,
            },
            2800: {
                moumouseDrag: true,
                items: 3,
                margin: 0,
                dots: true,
                loop: false,
            },

        }
    });



    //collegamnento prev e next news


    var genericCarousel = $(".generic-carousel");

    genericCarousel.owlCarousel();
    //Custom Navigation Events
    $(".genericCarouselnext").click(function () {
        genericCarousel.trigger('next.owl.carousel');
    });
    $(".genericCarouselprev").click(function () {
        genericCarousel.trigger('prev.owl.carousel');
    });


}

Trenord.ui.carouselAppTrenord = function () {



    $(".carouselAppTrenord").on('initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel', function (event) {
        var item =0;
        var activeItem = 0;

        $(".carouselAppTrenord .owl-item").each(function() {
            item++;

        });

        $(".carouselAppTrenord .owl-item.active").each(function() {
            activeItem++;

        });



        if(Trenord.utility.isMobile()){
            $(".carouselAppTrenordnext").hide();
            $(".carouselAppTrenordprev").hide();
        }else{
            $(".carouselAppTrenordnext").show();
            $(".carouselAppTrenordprev").show();
        }

    }).owlCarousel({
        items: 1,
        center: true,
        loop: true,
        nav: true,
        responsive: {
            0: {
                mousedrag:true,
                items: 1,

            },
            768: {
                mousedrag:true,
                items: 1,

            },
            1024: {
                mousedrag:true,
                items: 1,
                dots: true
            },
            1280: {
                mousedrag:true,
                items: 1,
                dots: true
            },
            1440: {
                mousedrag:true,
                items: 1,
                dots: true,
            },
            1680: {
                mousedrag:true,
                items: 1,
                dots: true,
            },
            2800: {
                mousedrag:true,
                items: 1,
                dots: true,
                loop: true,
            },

        }
    });






    var carouselAppTrenord =     $(".carouselAppTrenord");

    carouselAppTrenord.owlCarousel();
    //Custom Navigation Events
    $(".slider_nav_app a.genericCarouselnext").click(function () {
        carouselAppTrenord.trigger('next.owl.carousel');
    });
    $(".slider_nav_app a.genericCarouselprev").click(function () {
        carouselAppTrenord.trigger('prev.owl.carousel');
    });
}

Trenord.ui.carosuelMobileGreenCard = function () {




    var carouselMobile = $(".carousel-mobile-green-card");

    if (Trenord.utility.isMobile()) {
        $(".carousel-mobile-green-card").on('initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel', function (event) {


        }).owlCarousel({
            items: 3,
            loop: false,
            margin: 65,
            dots: true,
            center: false,
            nav: false,
            mousedrag:true,
            responsiveClass: true,
            responsive: {
                320: {
                    mousedrag:true,
                    margin: 20,
                    loop: true,
                    items: 1,
                    stagePadding: 60
                },

                600: {
                    mousedrag:true,
                    margin: 20,
                    loop: true,
                    items: 1,
                    stagePadding: 100
                },
                768: {
                    mousedrag:true,
                    items: 2,
                    margin: 50

                }
            }
        });


        //collegamnento prev e next news

        carouselMobile.owlCarousel();
    }else{
        carouselMobile.owlCarousel('destroy')
    }
}

Trenord.ui.carouselLine = function () {


    $(".carousel-line").on('changed.owl.carousel', function (property) {
        if (property.item.index === 0) {
            $(".slider_nav .next_news").removeClass("hidden");
            $(".slider_nav .next_news").show();
            $(".slider_nav .prev_news").addClass("hidden");
            $(".slider_nav .prev_news").hide();
        } else {
            var currnetel = property.item.index + property.page.size;
            // last element
            if (currnetel === property.item.count) {
                $(".slider_nav .next_news").addClass("hidden");
                $(".slider_nav .next_news").hide();

            } else {
                $(".slider_nav .next_news").removeClass("hidden");
                $(".slider_nav .next_news").show();
            }
        }

        if (property.item.index > 0) {
            $(".slider_nav .prev_news").removeClass("hidden");
            $(".slider_nav .prev_news").show();
        }
    });

    $(".carousel-line-container-fluid").hover(
        function () {
            $(".slider_nav .next_news").show();
            $(".slider_nav .prev_news").show();
            $(".slider_nav .next_news").css("opacity", "1");
            $(".slider_nav .prev_news").css("opacity", "1");
        }, function () {
            $(".slider_nav .next_news").hide();
            $(".slider_nav .prev_news").hide();
            $(".slider_nav .next_news").css("opacity", "0");
            $(".slider_nav .prev_news").css("opacity", "0");

        }
    );

    $(".carousel-line").on('initialized.owl.carousel changed.owl.carousel refreshed.owl.carousel', function (event) {
        var item = 0;
        var activeItem = 0;

        $(".carousel-line .owl-item").each(function () {
            item++;
        });

        $(".carousel-line.owl-item.active").each(function () {
            activeItem++;
        });

        if (item === activeItem) {
            $(".next_news").hide();
            $(".prev_news").hide();
        } else {
            $(".next_news").show();
            $(".prev_news").show();
        }
    }).owlCarousel({
        items: 3,
        loop: false,
        moumouseDrag: true,
        margin: 65,
        dots: true,
        center: false,
        nav: false,
        responsiveClass: true,
        responsive: {
            0: {
                moumouseDrag: true,
                margin: 10,
                loop: false,
                items: 1,
                stagePadding: 20
            },

            400: {
                moumouseDrag: true,
                loop: false,
                items: 1,
                stagePadding: 40,
                margin: 10,
            },

            600: {
                moumouseDrag: true,
                loop: false,
                items: 1,
                stagePadding: 60,
                margin: 10
            },

            767: {
                loop: false,
                mouseDrag: true,
                items: 1,
                stagePadding: 60,
                margin: 10,

            },
            768: {
                loop: false,
                mouseDrag: true,
                items: 1,
                stagePadding: 60,
                margin: 10,

            },
            1024: {
                loop: false,
                moumouseDrag: true,
                items: 1,
                dots: true,
                stagePadding: 80,
                margin: 10
            },
            1280: {
                loop: false,
                moumouseDrag: true,
                items: 1,
                dots: true,
                stagePadding: 80,
                margin: 10
            },
            1440: {
                loop: false,
                moumouseDrag: true,
                items: 1,
                dots: true,
                stagePadding: 80,
                margin: 10
            },
            1680: {
                loop: false,
                moumouseDrag: true,
                items: 1,
                dots: true,
                stagePadding: 50,
                margin: 20
            },
            2800: {
                loop: false,
                moumouseDrag: true,
                items: 1,
                dots: true,

                stagePadding: 120
            },

        }
    });

    var carousel_news = $(".carousel-line");

    carousel_news.owlCarousel();
    //Custom Navigation Events
    $(".next_news").click(function () {
        carousel_news.trigger('next.owl.carousel');
    });
    $(".prev_news").click(function () {
        carousel_news.trigger('prev.owl.carousel');
    });


    $(".carousel-line .item .body-text").each(function (index) {
        console.log($(this).height());
        if ($(this).height() > 150) {
            $(this).css("height", "160px");
        } else {
            $(this).css("height", "160px");
            $(this).parent().find(".read_more").remove();
        }
    });

    $('.read_more').unbind("click");
    $('.read_more').click(function () {

        if ($(this).hasClass("increase")) {
            $(this).parent().addClass("reduce_state");
            $(this).removeClass("increase");
            $(this).addClass("reduce");
            $(this).find("a").text("Riduci");
        } else {
            $(this).parent().removeClass("reduce_state");
            $(this).parent().css("height", "160px");
            $(this).addClass("increase");
            $(this).removeClass("reduce");
            $(this).find("a").text("Leggi di più");
        }

    });
}

Trenord.ui.serp = function () {

    $("#open-filter-mobile").click(function () {
        $(".box-modal-filter").fadeIn();
        $("body,html").css("overflow","hidden");
    });

    $("#close-serp-mobile").click(function () {
        $(".box-modal-filter").fadeOut();
        $("body,html").css("overflow","initial");
    });
    $(".container-filter-serp .filter").click(function () {
        var Element = $(this);

        if ($("body").hasClass("malpensaStyle")) {
            if (Element.hasClass("active")) {
            }
             else {
                /* $(".container-filter-serp .filter").removeClass("active"); */

                if (Element.hasClass("partenza")) {
                    $(".container-filter-serp .container-filter.partenza .filter").removeClass("active");
                }

                if (Element.hasClass("arrivo")) {
                    $(".container-filter-serp .container-filter.arrivo .filter").removeClass("active");
                }

            }

            setTimeout(function () {
                Element.toggleClass("active");
                if ($(this).parents("container-filter-serp")) {
                    if ($(".container-filter-serp .filter.active").length > 1) {
                        $(".container-filter-serp .container-header-news #remove-filter").fadeIn().css("display", "block");
                    } else {
                        $(".container-filter-serp .container-header-news #remove-filter").fadeOut();
                    }
                }
            }, 100);
        } else {
            Element.toggleClass("active");
            if ($(".container-filter-serp .filter.active").length > 1) {
                $(".container-filter-serp .container-header-news #remove-filter").fadeIn().css("display", "block");
            } else {
                $(".container-filter-serp .container-header-news #remove-filter").fadeOut();
            }
        }

    });

    $(".container-filter-serp .container-header-news #remove-filter").click(function () {
        $(".container-filter-serp .filter.active").each(function(){ $(this).trigger("click")});
        $(".container-filter-serp .container-header-news #remove-filter").fadeOut();
    });


    /* datepicker */
    if ($('#js-date-dal').length) {
        $('#js-date-dal').datepicker({
            language: 'IT',
            format: 'dd/mm/yyyy',
            orientation: 'auto bottom',
        }).on("show", function (e) {
            $(" .datepicker .prev, .datepicker .next").empty();

            if (!$(".datepicker-dropdown h4").length) {
                $(".datepicker-dropdown").prepend("<h4>filtra per data</h4>");
                $(".datepicker-dropdown").prepend("<img alt='icona-chiudi-calendario' class='lozad' class='close-datepicker' src='/fileadmin/templates/img/news/close.png'>");
            }

            $(".datepicker-dropdown .close-datepicker").click(function () {
                $(".datepicker-dropdown").remove();
            });

        });
    }

    /* datepicker mobile dal */
    if ($('#js-date-dal-mobile').length) {
        $('#js-date-dal-mobile').datepicker({
            language: 'IT',
            format: 'dd/mm/yyyy',
            orientation: 'auto bottom',
        }).on("show", function (e) {
            $(" .datepicker .prev, .datepicker .next").empty();

            $(".datepicker-dropdown").addClass("mobile-date");
            $(".datepicker-dropdown .close-datepicker").click(function () {
                $(".datepicker-dropdown").remove();
            });

        });
    }

    /* datepicker mobile al */
    if ($('#js-date-al-mobile').length) {
        $('#js-date-al-mobile').datepicker({
            language: 'IT',
            format: 'dd/mm/yyyy',
            orientation: 'auto bottom',
        }).on("show", function (e) {
            $(" .datepicker .prev, .datepicker .next").empty();

            $(".datepicker-dropdown").addClass("mobile-date-al");
            $(".datepicker-dropdown .close-datepicker").click(function () {
                $(".datepicker-dropdown").remove();
            });

        });
    }

    /* datepicker */
    if ($('#js-date-al').length) {
        $('#js-date-al').datepicker({
            language: 'IT',
            format: 'dd/mm/yyyy',
            orientation: 'auto bottom',
        }).on("show", function (e) {
            $(" .datepicker .prev, .datepicker .next").empty();

            if (!$(".datepicker-dropdown h4").length) {
                $(".datepicker-dropdown").prepend("<h4>filtra per data</h4>");
                $(".datepicker-dropdown").prepend("<img  alt='icona_chiudi_news' class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");
            }

            $(".datepicker-dropdown .close-datepicker").click(function () {
                $(".datepicker-dropdown").remove();
            });

        });
    }
}

Trenord.ui.malpensaTreni = {

    filterActive: [],
    countDa: 0,
    countPer: 0,


    initEvents: function () {

        $(".container-filter  .filter").click(function () {


            var direzione = $(this).data("direzione");

            /*        var currentTabId = "#tab-train-from-malpensa ";
                    if (direzione.indexOf("da") > -1) {
                        currentTabId = "#tab-train-to-malpensa ";
                    } else if (direzione.indexOf("per") > -1) {
                        currentTabId = "#tab-train-from-malpensa ";
                    }

                    $(currentTabId + ".train.prossimi-treni").removeClass("hidden");
                    $(currentTabId + ".train.prossimi-treni").addClass("hidden");

                    var directionPos = jQuery.inArray(direzione, Trenord.ui.malpensaTreni.filterActive);

                    if (directionPos !== -1) {
                        Trenord.ui.malpensaTreni.filterActive.splice(directionPos, 1);
                    } else {
                        Trenord.ui.malpensaTreni.filterActive.push(direzione);
                    }

                    $(Trenord.ui.malpensaTreni.filterActive).each(function (index, value) {
                        $(currentTabId + ".train[data-direzione='" + value + "']").removeClass("hidden");
                    });

                    return;*/

            var direzione = $(this).data("direzione");
            var direzione2 = $(this).find(".title-filter").data("direzione");

            var count = 0;


            var centrale = $(".per-milano-centrale").hasClass("active");
            var cadorna = $(".per-milano-cadorna").hasClass("active");

            //per milano per cadorna
            if ($(this).data("direzione") === "per-milano-centrale" || $(this).data("direzione") === "per-milano-cadorna") {
                setTimeout(function () {
                    var centrale = $(".per-milano-centrale").hasClass("active");
                    var cadorna = $(".per-milano-cadorna").hasClass("active");
                    if (centrale == true && cadorna == false) {
                        var count = 0;
                        $(" #tab-train-from-malpensa .train.prossimi-treni").addClass("hidden");
                        $("#tab-train-from-malpensa  .train.prossimi-treni").each(function (index) {
                            if ($(this).data("direzione") === "per-milano-centrale" && count <= 4) {
                                $(this).removeClass("hidden");
                                count++;
                            } else {

                            }


                        });
                    }


                    if (centrale == false && cadorna == true) {
                        var count = 0;
                        $(" #tab-train-from-malpensa .train.prossimi-treni").addClass("hidden");
                        $("#tab-train-from-malpensa  .train.prossimi-treni").each(function (index) {
                            if ($(this).data("direzione") === "per-milano-cadorna" && count <= 4) {
                                $(this).removeClass("hidden");
                                count++;
                            } else {

                            }


                        });
                    }

                    if ((centrale == true && cadorna == true) || (centrale == false && cadorna == false)) {
                        var count = 0;
                        $(" #tab-train-from-malpensa .train.prossimi-treni").addClass("hidden");
                        $("#tab-train-from-malpensa  .train.prossimi-treni").each(function (index) {
                            if (count <= 4) {
                                $(this).removeClass("hidden");
                                count++;
                            } else {

                            }


                        });
                    }

                }, 500);

            } else {
                //da milano da cadorna
                setTimeout(function () {
                    var centrale = $(".da-milano-centrale").hasClass("active");
                    var cadorna = $(".da-milano-cadorna").hasClass("active");

                    if (centrale == true && cadorna == false) {
                        var count = 0;
                        $(" #tab-train-to-malpensa .train.prossimi-treni").addClass("hidden");
                        $("#tab-train-to-malpensa  .train.prossimi-treni").each(function (index) {
                            if ($(this).data("direzione") === "da-milano-centrale" && count <= 4) {
                                $(this).removeClass("hidden");
                                count++;
                            } else {

                            }


                        });
                    }


                    if (centrale == false && cadorna == true) {
                        var count = 0;
                        $(" #tab-train-to-malpensa .train.prossimi-treni").addClass("hidden");
                        $("#tab-train-to-malpensa  .train.prossimi-treni").each(function (index) {
                            if ($(this).data("direzione") === "da-milano-cadorna" && count <= 4) {
                                $(this).removeClass("hidden");
                                count++;
                            } else {

                            }


                        });
                    }

                    if ((centrale == true && cadorna == true) || (centrale == false && cadorna == false)) {
                        var count = 0;
                        $(" #tab-train-to-malpensa .train.prossimi-treni").addClass("hidden");
                        $("#tab-train-to-malpensa  .train.prossimi-treni").each(function (index) {
                            if (count <= 4) {
                                $(this).removeClass("hidden");
                                count++;
                            } else {

                            }


                        });
                    }

                }, 500);
            }


            /*     $(".train-home .container-train .train.prossimi-treni").each(function (index) {
                     if ($(this).data("direzione") === direzione2) {
                         $(this).removeClass("hidden");
                     } else {
                         $(this).addClass("hidden");
                     }
                 });
     */

            /*        if ($(this).hasClass("active")) {
                        var count = 0;
                        $(".train-home .container-train .train.prossimi-treni").removeClass("hidden");
                        $(".train-home .container-train .train.prossimi-treni").each(function(index){


                            if(count  > 4){
                                $(this).addClass("hidden");
                            }
                            count++;
                        });

                    }else {
                        if (direzione2 == "per-milano-cadorna") {
                            $(".train-home .container-train .train.prossimi-treni").each(function (index) {
                                if ($(this).data("direzione") === direzione2) {
                                    $(this).removeClass("hidden");
                                } else {
                                    $(this).addClass("hidden");
                                }
                            });
                        }

                        if (direzione2 == "da-milano-cadorna") {
                            $(".train-home .container-train .train.prossimi-treni").each(function (index) {
                                if ($(this).data("direzione") === direzione2) {
                                    $(this).removeClass("hidden");
                                } else {
                                    $(this).addClass("hidden");
                                }
                            });
                        }

                        if (direzione2 == "per-milano-centrale") {
                            $(".train-home .container-train .train.prossimi-treni").each(function (index) {
                                if ($(this).data("direzione") === direzione2) {
                                    $(this).removeClass("hidden");
                                } else {
                                    $(this).addClass("hidden");
                                }
                            });
                        }

                        if (direzione2 == "da-milano-centrale") {
                            $(".train-home .container-train .train.prossimi-treni").each(function (index) {
                                if ($(this).data("direzione") === direzione2) {
                                    $(this).removeClass("hidden");
                                } else {
                                    $(this).addClass("hidden");
                                }
                            });
                        }

                    }
        */
            if ($(this).hasClass("active")) {

                if ($(this).hasClass("partenza")) {
                    $(".container-train.partenza .train").show();

                } else {

                    $(".container-train.arrivo .train").show();
                }


            } else {


                if ($(this).hasClass("partenza")) {

                    $(".container-train.partenza .train").each(function (i, obj) {
                        if ($(this).data("direzione") === direzione) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                } else {
                    $(".container-train.arrivo .train").each(function (i, obj) {
                        if ($(this).data("direzione") === direzione) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                }

            }
        });


        $("body.malpensaStyle .container-train .train .accordion-train ").click(function () {

            if (!$(this).hasClass("dettaglio") && !$(this).hasClass("dettaglio-prossimi") && !$(this).hasClass("infomob")) {

                if ($(this).parent().parent().find(".content-accordion").is(":visible")) {
                    $(this).parent().parent().find(".content-accordion").slideUp();
                    $(this).parent().find(".image-train img").fadeIn();
                    $(this).parent().find(".title  h4").fadeIn();
                    $(this).parent().find(".time *").fadeIn();
                    $(this).parent().find(".title  .title-accordion-open").hide();
                    $(this).parent().find(".delay .delay-home").fadeIn();

                } else {
                    $(this).parent().parent().find(".content-accordion").slideDown();
                    $(this).parent().find(".image-train img").hide();
                    $(this).parent().find(".title  h4").hide();
                    $(this).parent().find(".title  .title-accordion-open").fadeIn();
                    $(this).parent().find(".time *").hide();
                    $(this).parent().find(".delay .delay-home").hide();

                }
            }

        });


        $("body.malpensaStyle .container-train .train .accordion-train.dettaglio ").click(function () {

            $(this).find("img").toggleClass("rotate");
            if ($(this).parent().parent().find(".content-accordion").is(":visible")) {
                $(this).parent().parent().find(".content-accordion").slideUp();
            } else {
                $(this).parent().parent().find(".content-accordion").slideDown();
            }

        });

        /*    var selected = "";
            $('.select').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
                selected = $(e.currentTarget).val();
                if (selected) {
                    $("label#label-motivo").css("top", "37px");
                    $("label#label-motivo").css("font-size", "14px");
                    $("p#label-motivo").removeClass("error-input");
                    $("label#label-motivo").removeClass("error-input");
                }
            });*/

        $(".edit-widget-volo").click(function () {
            $(".container-widget-cta").fadeIn();
            $("html").css("overflow", "hidden");
            $(".container-widget-cta .widget-cta").css("right", "0");
        });


        $(".container-widget-cta .overlay, .container-widget-cta .title-container svg").click(function () {
            $(".container-widget-cta").fadeOut();
            $("html").css("overflow", "initial");
            $(".container-widget-cta .widget-cta").css("right", "-100%");
        });

    },

    getTrains: function (divId) {

        //direzione del treno
        var direction = $("#" + divId + " .direction").val();
        var movement = $("#" + divId + " .movement").val();

        //l'api riceve il testo della stazione non il codice
        var selectedStation = $("#" + divId + " #motivo-form-contatti-train option:selected").text().trim();

        //setto di default la stazione di partenza, attenzione che ci sono due dati in pagina quindi ne prendo 1
        var malpensaStation = $("#" + divId + " .time .departure .station")[0].innerText
        //per recuperare la stazione corretta devo anche dove arriva il volo

        //se non trovo malpensa dentro l'ereoporto di partenza
        if (malpensaStation.toLocaleLowerCase().indexOf("malpensa") < 0) {
            //lo setto dall'aereoporto di arrivo
            malpensaStation = $("#" + divId + " .time .arrival .station")[0].innerText
        }

        var trainData = {
            orig: direction == "from-malpensa" ? malpensaStation : selectedStation,
            dest: direction == "to-malpensa" ? malpensaStation : selectedStation,
            departure_date: $("#" + divId + " .departure_date").val(),
            departure_hour: $("#" + divId + " .departure_hour").val(),
            direction: direction,
            movement: movement
        };

        //devo impostare la spalla di acquisto con i dati
        Trenord.passengersWidget.from = trainData.orig;
        Trenord.passengersWidget.to = trainData.dest;
        Trenord.passengersWidget.date = trainData.departure_date;
        Trenord.passengersWidget.time = trainData.departure_hour;

        $("#" + divId + " .select-result.real-result").html("");
        $("#" + divId + " .select-result.skeleton-result").removeClass('hidden');

        $.post('/rest/render/trains', trainData, function (data) {

            $("#" + divId + " .select-result.real-result").html(data.message);
            $("#" + divId + " .select-result.skeleton-result").addClass('hidden');
            Trenord.ui.initPassengerShoulder();
        })


    }
}

Trenord.ui.malpensaProssimiTreni = {

    nextTrainSemaphore: {
        formMalpensa: true,
        toMalpensa: true
    },

    initEvents: function () {

        $(".train.prossimi-treni").click(function (event) {

            if ($(event.target).attr('class') == "tooltip-action" || $(event.target).attr('class') == "button" || $(event.target).attr('class') == "undefined" || $(event.target).attr('class') == "button red" || $(event.target).parent().attr('class') == "button red" || $(event.target).attr('class') == "svg-tooltip" || $(event.target).attr('class') == "time-accordion" || $(event.target).attr('class') == "modal-link") {

            } else {
                if (Trenord.utility.isMobile()) {
                    $(this).find(".hidden-desktop").find(" .accordion-train.dettaglio-prossimi ").triggerHandler('click');
                } else {
                    $(this).find(".hidden-mobile").find(".accordion-train.dettaglio-prossimi-desktop ").triggerHandler('click');
                }
            }
            //  $(this).find(".hidden-mobile").find(".accordion-train.dettaglio-prossimi-desktop ").triggerHandler('click');
            //   event.preventDefault();
        });

        $("body.malpensaStyle  .train.prossimi-treni .accordion-train.dettaglio-prossimi-desktop ").unbind();
        var currentlyAnimating = false;
        $("body.malpensaStyle  .train.prossimi-treni .accordion-train.dettaglio-prossimi ").click(function (e) {
            if (currentlyAnimating) {
                return;
            }

            currentlyAnimating = true;
            var element = $(this);
            e.stopPropagation();
            e.stopImmediatePropagation();
            e.preventDefault();

            if ($(this).parent().parent().find(".content-accordion").is(":visible") && $(this).parent().parent().find(".content-accordion").filter(":not(:animated)")) {
                element.parent().parent().find(".content-accordion").fadeOut();

                setTimeout(function () {
                    element.find("img").toggleClass("rotate");
                    $(element).parent().find(".accordion-train-close").fadeIn();
                    currentlyAnimating = false;
                }, 200);

            } else {

                $(element).parent().find(".accordion-train-close").fadeOut();
                setTimeout(function () {
                    element.find("img").toggleClass("rotate");
                    currentlyAnimating = false;
                    element.parent().parent().find(".content-accordion").fadeIn();
                }, 200);
            }

        });

        $("body.malpensaStyle  .train.prossimi-treni .accordion-train.dettaglio-prossimi-desktop ").unbind();
        var currentlyAnimating = false;
        $("body.malpensaStyle  .train.prossimi-treni .accordion-train.dettaglio-prossimi-desktop ").click(function (e) {
            if (!$(this).hasClass("infomob")) {
                if (currentlyAnimating) {
                    return;
                }

                currentlyAnimating = true;

                var element = $(this);
                $(this).find("img").toggleClass("rotate");
                if ($(this).parent().parent().parent().find(".content-accordion").is(":visible") && $(this).parent().parent().parent().find(".content-accordion").filter(":not(:animated)")) {
                    element.parent().parent().find(".titolo-dettaglio-viaggio").fadeOut("fast");
                    element.parent().parent().parent().find(".content-accordion").fadeOut().slideUp();

                    setTimeout(function () {

                        element.parent().parent().find(".icon-train-prossimi").fadeIn();
                        element.parent().parent().find(".text-train-prossimi").fadeIn();
                        element.parent().parent().find(".time").fadeIn();
                        element.parent().parent().find(".text-delay").fadeIn();
                        currentlyAnimating = false;
                    }, 200);

                } else {
                    element.parent().parent().parent().find(".content-accordion").fadeIn().slideDown().css("display", "inline-block");
                    element.parent().parent().find(".icon-train-prossimi").hide();
                    element.parent().parent().find(".text-train-prossimi").hide();
                    element.parent().parent().find(".time").hide();
                    element.parent().parent().find(".text-delay").hide();
                    setTimeout(function () {
                        currentlyAnimating = false;
                        element.parent().parent().find(".titolo-dettaglio-viaggio").fadeIn("fast");
                    }, 200);


                }
            }
        }
        );

    },

    /**
     * carica le soluzioni di vaggio da o per malpensa
     * e da o per milano cadorna e milano centrale
     * verificando che la chiamata venga erogata una sola volta
     * nell'arco di una navigazione
     * @param direction
     * @return {boolean}
     */
    loadNextTrains: function (direction) {

        //controllo di unicità della chiamata
        if (
            Trenord.ui.malpensaProssimiTreni.nextTrainSemaphore.formMalpensa
            && direction == "from-malpensa"
        ) {
            Trenord.ui.malpensaProssimiTreni.nextTrainSemaphore.formMalpensa = false;
        } else if (Trenord.ui.malpensaProssimiTreni.nextTrainSemaphore.toMalpensa
            && direction == "to-malpensa") {
            Trenord.ui.malpensaProssimiTreni.nextTrainSemaphore.toMalpensa = false;
        } else {

            return false;
        }

        var trains_filter = {
            "direction": direction,
            "trainDescription": Trenord.globals.static.trainDescription,
            "L": '0' //Trenord.globals.currentLanguage
        }

        //lo spazio serve per non inserirlo in ogni chiamata all'oggetto sottostante
        var id = "#tab-train-" + direction + " ";


        $(id + ".container-train.next-train-result").hide();
        $(id + ".container-train.next-train-result").html("");
        $(id + ".container-train.skeleton-result").show();


        $.post('/rest/render/next-trains', trains_filter, function (data) {

            $(id + ".container-train.skeleton-result").hide();
            $(id + ".container-train.next-train-result").html(data.message);
            $(id + ".container-train.next-train-result").show();

            Trenord.ui.malpensaProssimiTreni.initEvents();
            Trenord.ui.initPassengerShoulder();
            Trenord.utility.Modal();

            $('[data-toggle="tooltip"]').tooltip('destroy');
            $('.tooltip-action').unbind();
            $('.tooltip-action').mouseenter(function (event) {

                if (Trenord.utility.isMobile()) {
                    var id = $(this).attr("id").split("mtooltip");
                    var text = $("#text-mtooltip" + id[1] + "").html();
                } else {
                    var id = $(this).attr("id").split("tooltip");
                    var text = $("#text-tooltip" + id[1] + "").html();
                }

                $(this).unbind();

                $(this).tooltip({
                    animated: 'fade',
                    placement: 'top',
                    trigger: 'click',
                    html: true,
                    title: text,
                });

                checkMobile(id);
            });

            function checkMobile(id) {

                if (Trenord.utility.isMobile()) {
                    setTimeout(function () {
                        $("#mtooltip" + id[1] + "").next().css("top", "0");
                    }, 100);
                }
            }

            //      $('[data-toggle="tooltip"]').unbind();
            $('[data-toggle="tooltip"]').on('hidden.bs.tooltip', function (event) {
                if (Trenord.utility.isMobile()) {
                    $("body,html").css("overflow", "initial");

                }

            });

            //    $('[data-toggle="tooltip"]').unbind();
            $('[data-toggle="tooltip"]').on('shown.bs.tooltip', function (event) {

                if (Trenord.utility.isMobile()) {
                    $("body,html").css("overflow", "hidden");
                }

                if (Trenord.utility.isMobile()) {

                    if ($(this).attr("id").split("m").length > 1) {

                        var idOpenTooltip = "close-" + $(this).attr("id") + "";
                    }
                } else {
                    var idOpenTooltip = "close-" + $(this).attr("id") + "";
                }


                $(".tooltip.in").each(function (event) {

                    if ($(this).find(".close-tooltip").attr("id") !== idOpenTooltip) {
                        var id = $(this).find(".close-tooltip").attr("id");
                        $("#" + id + "").click();
                    }
                });

                $('.tooltip-inner').children().each(function () {
                    if ($(this).attr("class") !== "close-tooltip") {
                        $(this).click(false);
                    }
                });


            });


            $(document).on('click', function (e) {
                var classElement = $(e.target).parent().attr("class");

                if (classElement !== "close-tooltip" && classElement !== "tooltip fade top in" && classElement !== "svg-tooltip" && classElement !== "tooltip-container" && classElement !== "tooltip-action" && classElement !== "tooltip-inner") {
                    $(".tooltip.in").find(".close-tooltip").click();
                }

            });

        });

    },

    openTicketShoulders: function (divId) {

        //devo impostare la spalla di acquisto con i dati
        Trenord.passengersWidget.from = $("#" + divId + " .hidden-mobile .departure .station:first").text().trim();
        Trenord.passengersWidget.to = $("#" + divId + " .hidden-mobile .arrival .station:first").text().trim();
        Trenord.passengersWidget.date = new Date();
        Trenord.passengersWidget.time = $("#" + divId + " .hidden-mobile .departure .dep_time:first").text().trim();
    },

    goToStep2: function(train) {

        if(!train) {
            return;
        }

        var solution = JSON.parse(train);
        var defaultProduct = solution.products.find(product =>  
            product.class === "1" && (product.tariff_type.includes("adulto") || product.tariff_type === "standard") &&
            product.category !== "mxpar")
        
        if(!solution || !defaultProduct) {
            return;
        }

        var objToSetInSessionStorage = {
            solution: solution,
            product: defaultProduct
        }

        // clear session storage
        sessionStorage.removeItem("malpensa-shopping-cart-information");
        sessionStorage.removeItem("malpensa-outward-items");
        sessionStorage.removeItem("malpensa-inward-items");
        sessionStorage.removeItem("malpensa-outward-cs-items");
        sessionStorage.removeItem("malpensa-inward-cs-items");
        sessionStorage.removeItem("malpensa-outward-solution");
        sessionStorage.removeItem("malpensa-inward-solution");

        // set selected solution in session storage
        sessionStorage.setItem("malpensa-outward-solution", JSON.stringify(objToSetInSessionStorage));

        var lang = "it";
        var path = window.location.pathname;
        if(path && path.startsWith("/en/")) {
            lang = "en"
        }

        window.location.href = `/store/#/${lang}/booking/step2`;
    }

}


Trenord.ui.payGo = function () {

    $(".container-mostra-altri.payGo .mostra-altri .link").click(function () {
        var lastRowVisible = $('.table-ricevute table tr:visible').length;
        var rowToShow = lastRowVisible + 10;
        for (i = lastRowVisible; i <= rowToShow; i++) {
            $(".table-ricevute table tr:nth-child(" + i + ")").fadeIn();
        }


        if ($('.table-ricevute table tr:hidden').length == 0) {
            $(".container-mostra-altri.payGo").hide();
        }
    });

    $('input').keyup(function () {
        $(this).parent().find("label").removeClass("error-input")
    });
    $('input').change(function () {
        $(this).parent().find("label").removeClass("error-input")
    });


    $('#js-date-next-train-end').datepicker({
        language: 'IT',
        format: 'dd/mm/yyyy',
        weekStart:1,
        orientation: 'auto bottom',
        todayHighlight: true,
        minDate: 0,
        maxViewMode: 0,
    }).on("show", function (e) {
        $(" .datepicker .prev, .datepicker .next").empty();

        $(".datepicker-dropdown .close-datepicker").click(function () {
            $(".datepicker-dropdown").remove();
        });

        $(".datepicker-dropdown").addClass("paygo").addClass("endDate");
        if (!$(".datepicker-dropdown h4").length) {

            $(".datepicker-dropdown").prepend("<h4>" + Trenord.lang.calendar.title + "</h4>");
            $(".datepicker-dropdown").prepend("<img alt='icona_chiudi' class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");

        }

    }).on('changeDate', function (selectedDate) {

        $('#js-date-next-train-start').datepicker('setEndDate', $(this).datepicker('getDate'));
        $(".datepicker-dropdown").remove();
    });


    $('#js-date-next-train-start').datepicker({
        language: 'IT',
        format: 'dd/mm/yyyy',
        weekStart:1,
        orientation: 'auto bottom',
        todayHighlight: true,
        maxViewMode: 0,
    }).on("show", function (e) {
        $(" .datepicker .prev, .datepicker .next").empty();

        $(".datepicker-dropdown .close-datepicker").click(function () {
            $(".datepicker-dropdown").remove();
        });

        $(".datepicker-dropdown").addClass("paygo").addClass("startDate");

        if (!$(".datepicker-dropdown h4").length) {
            $(".datepicker-dropdown").prepend("<h4>" + Trenord.lang.calendar.title + "</h4>");
            $(".datepicker-dropdown").prepend("<img alt='icona_chiudi' class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");

        }

    }).on('changeDate', function (ev) {

        $('#js-date-next-train-start').datepicker("hide");
        setTimeout(function () {
            $('#js-date-next-train-end').datepicker("show");
        }, 200);
        $('#js-date-next-train-end').datepicker('setStartDate', $(this).datepicker('getDate'));
    });


    $("#js-date-next-train-start,#js-date-next-train-end").click(function () {
        if (Trenord.utility.isMobile()) {
            setTimeout(function () {
                $(".datepicker-dropdown.dropdown-menu").addClass("importantLeft");
            }, 50);
        } else {
            setTimeout(function () {
                $(".datepicker-dropdown.dropdown-menu").removeClass("importantLeft");
            }, 50);
        }
    });

    $("#verificaPaygo").click(function () {
        $(".pay-go-close").hide();
        $(".pay-go-open").slideDown();
    });

    $("#visualizzaRicevutePaygo").click(function () {

        var primeCifre = $("#prime-cifre");
        var ultimeCifre = $("#ultime-cifre");
        var dataInizio = $("#js-date-next-train-start");
        var dataFine = $("#js-date-next-train-end");

        if (dataInizio.val() === "" && dataFine.val() === "") {
            $("#data-inizio-label").addClass("error-input");
            $("#data-fine-label").addClass("error-input");
            $(".error-input-text.date-input-paygo").fadeIn();
        } else {
            $(".error-input-text.date-input-paygo").fadeOut();
        }


        if (dataInizio.val() === "") {
            $("#data-inizio-label").addClass("error-input");


        } else {
            $(".error-input-text.date-input-paygo").fadeOut();
        }


        if (dataFine.val() === "") {
            $("#data-fine-label").addClass("error-input");


        } else {
            $(".error-input-text.date-input-paygo").fadeOut();
        }


        if (primeCifre.val() === "" || primeCifre.val().length !== 6) {
            $("#prime-cifre-label").addClass("error-input");
            $(".error-input-text.credit-input-paygo").fadeIn();
        } else {
            $(".error-input-text.credit-input-paygo").fadeOut();
        }


        if (ultimeCifre.val() === "" || ultimeCifre.val().length !== 4) {
            $("#ultime-cifre-label").addClass("error-input");
            $(".error-input-text.credit-input-paygo").fadeIn();
        } else {
            $(".error-input-text.credit-input-paygo").fadeOut();
        }

        $("#js-date-voli-aereo");

        if (primeCifre.val().length == 6 && ultimeCifre.val().length == 4 && $("#js-date-next-train-start").val() !== "" && $("#js-date-next-train-end").val() !== "") {
            Trenord.payGo.verify();
        }

    });
}
Trenord.ui.lineeMappeOrari = {

    filterStationType: {
        biglietti: true,
        distributori: true
    },


    initEvents: function () {

        if($( window ).width() < 768){
            var alertHeight = $(".container-alert:visible").outerHeight();
            var boxHeightFull = $(".sidebar .line-details:visible").outerHeight();
            var headerHeight = $(".header-top").outerHeight();
            $(".sidebar.active").css("height","auto");

            setTimeout(function () {
                if ($(".sidebar .all-lines:visible").length > 0) {

                    $(".linee-orari #noovle-map").removeClass("active");
                }else{
                    $(".linee-orari #noovle-map").addClass("active");
                }
            },400);




            $(".linee-orari #noovle-map.active").css("height","calc(100vh - 198px - "+alertHeight+"px)");

        }else{

            $(".linee-orari #noovle-map.active").css("height","calc(100%");

            setTimeout(function () {
                var alertHeight = $(".container-alert:visible").outerHeight();
                var boxHeightFull = $(".sidebar .line-details:visible").outerHeight();
                var headerHeight = $(".header-top").outerHeight();
                if(alertHeight){
                    $(".sidebar").css("height", "calc(100vh  - " + alertHeight + "px    -  "+boxHeightFull+"px - "+headerHeight+"px )");
                }else{
                    $(".sidebar").css("height", "calc(100vh    - "+headerHeight+"px - "+boxHeightFull+"px )");
                }
            }, 700)

        }


        $(".idee_carousel .item.distributori").click(function () {

            var carousel = $(".idee_carousel");
            carousel.trigger("to.owl.carousel", [1, 500, true]);

        });

        $(".scroll-specific-line").perfectScrollbar();
        $(".all-lines").perfectScrollbar();


        setTimeout(function () {
            $('.linee-text-media .sidebar .all-lines').perfectScrollbar('destroy');

            if (Trenord.utility.isTablet() || Trenord.utility.isMobile()) {
                $(".scroll-specific-line").perfectScrollbar('destroy');
            }
            if (!Trenord.utility.isTablet() || !Trenord.utility.isMobile()) {
                $(".all-lines").perfectScrollbar('destroy');
            }

        }, 300);


    }


}


Trenord.ui.filterLine = function () {

    $(".line .idee_carousel .item").click(function () {

            var typeStation = $(this).data('type-station') == 'biglietteria' ? "tickets" : "distributors";




            setTimeout(function () {


                Trenord.ui.lineeMappeOrari.filterStationType.biglietti = $(".idee_carousel .item.biglietti").hasClass("active");
                Trenord.ui.lineeMappeOrari.filterStationType.distributori = $(".idee_carousel .item.distributori").hasClass("active");


                if ((Trenord.ui.lineeMappeOrari.filterStationType.biglietti && Trenord.ui.lineeMappeOrari.filterStationType.distributori) ||(
                        !Trenord.ui.lineeMappeOrari.filterStationType.biglietti && !Trenord.ui.lineeMappeOrari.filterStationType.distributori)){
                    $(".station-type li").fadeIn();}
                else {

                    if (Trenord.ui.lineeMappeOrari.filterStationType.biglietti) {
                        $(".station-type li").hide();
                        $(".station-type li").each(function (index) {
                            if ($(this).data('type-station-biglietteria') == true) {
                                $(this).fadeIn();
                            }
                        });
                    }

                    if (Trenord.ui.lineeMappeOrari.filterStationType.distributori) {
                        $(".station-type li").hide();
                        $(".station-type li").each(function (index) {
                            if ($(this).data('type-station-distributori') == true) {
                                $(this).fadeIn();
                            }
                        });


                    }
                }

                if (Trenord.ui.lineeMappeOrari.filterStationType.biglietti && Trenord.ui.lineeMappeOrari.filterStationType.distributori) {
                    resetStations();
                } else if (!Trenord.ui.lineeMappeOrari.filterStationType.biglietti && !Trenord.ui.lineeMappeOrari.filterStationType.distributori) {
                    resetStations();
                } else {
                    showStations(lastLoadedShoulderLineCode, typeStation);
                }





            }, 200);
        }
    )
    ;
}

Trenord.ui.timeCircle = {
    initEvents: function () {


        var countdownNumberEl = document.getElementById('countdown-number');
        if(countdownNumberEl){
            var countdown = 10;

            countdownNumberEl.textContent = countdown;

            setInterval(function() {
                countdown = --countdown <= 0 ? 10 : countdown;

                countdownNumberEl.textContent = countdown;
            }, 1000);
        }

    }
}
Trenord.infoMobilita = {

    isHome: window.location.pathname == "/",

    lastStation: "",

    initEvents: function () {


        $(".train-ricerca-stazione .star.star-empty svg").click(function () {
            $(this).hide();
            $(this).parent().next().show();
        });

        $(".train-ricerca-stazione .star.star-filled svg").click(function () {
            $(this).hide();
            $(this).parent().prev().find("svg").show();
        });

        $(".dropdown-menu.ricerca-infomob li").click(function () {
            $(".dropdown-menu.ricerca-infomob").hide();
        });

        $('body').on('click', '.open-description-details', function () {
            $(this).parent().parent().parent().parent().parent().find(".description-train").fadeIn();
            $(".children-station:visible").perfectScrollbar();
            $("body,html").css("overflow", "hidden");
        });
        $('body').on('click', '.header-list-station img', function () {
            $(this).parents(".description-train").fadeOut();
            $("body,html").css("overflow", "initial");
        });

        $("#train-search").on('keyup', function (e) {
            if (e.keyCode == 13) {
                dataLayer.push({
                    'event': 'search',
                    'researchType': 'treno',
                    'departureStation': '',
                    'arrivalStation': '',
                    'searchedStation':'',
                    'searchedTrain':$('#train-search').val(),
                    'evtCat': 'ricerca',
                    'evtAction': 'invio',
                    'evtLabel' : 'treno'
                });
                Trenord.infoMobilita.trainDetail($('#train-search').val());
            }
        });
    },

    clearResult: function (trainId) {
        //$(".train-sub-details-" + trainId).html("");
    },

    loadHistory: function (type) {

        //questo controllo mi serve per sapere in che stato sono
        //se ho un parametro valido nella query, non posso lanciare la history
        //perchè partono le chiamate per la ricerca
        var params = Trenord.utility.locationSearchToObject();

        if ((params.train != undefined && params.train != "undefined" && params.train != "")
            ||
            (params.station != undefined && params.station != "undefined" && params.station != "")) {

            //nascono lo skeleton perchè effetto collaterale di questo processo
            $("." + type + "-history-skeleton").hide();
            return;
        }

        //altrimenti procedo con la history
        var params = {
            type: type
        };


        $(".container-result-infomob").addClass('hidden');
        $(".container-box-info-mob-map").hide();
        $("." + type + "-history-skeleton").show();
        $("." + type + "-history-result").hide();

        $.get('/rest/render/infomob-' + type + '-history', params, function (data) {

            if (type === 'train') {
                $("." + type + "-history-result").empty();
                data.forEach(element => {
                    $("." + type + "-history-result").append(element);
                });
                Trenord.ui.infoMobilita.initEvents();
                Trenord.ui.infoMobilita.initTrainDetailsEvent();
                Trenord.ui.carouselLine();
            } else {
                $("." + type + "-history-result").html(data.message);    
            }

            $("." + type + "-history-skeleton").hide();
            $("." + type + "-history-result").show();
        });

    },


    searchTrain: function (event) {

        if (event.currentTarget.value.trim().length > 2) {

            var mxp = window.location.hostname.indexOf('malpensaexpress.it') > -1;

            $.get('/rest/render/search-train-list', {query: event.currentTarget.value, mpx: mxp}, function (data) {

                if (data.message != "") {
                    $(".ricerca-infomob.no-result").fadeOut();
                    $(".ricerca-infomob.result").html(data.message);
                    $(".ricerca-infomob.result").fadeIn();

                } else {
                    $(".ricerca-infomob.result").fadeOut();
                    $(".ricerca-infomob.no-result").fadeIn();
                }

            });
        }

    }
    ,

    trainDetail: function (trainId) {

        if (Trenord.infoMobilita.isHome) {

            window.location.href = GLOBALS_REALTIME_PAGE + "?train=" + trainId;

        } else {
            var html = '<tn-wc-train-info class="train-info" train=' + trainId + '></tn-wc-train-info>'
            $(".container-train.partenza.results").empty();
            $(".container-train.partenza.results").append(html);
        }
    }
    ,

    /**
     * dettaglio stazioni
     * @param mirCode
     * @param label
     */
    stationDetails: function (mirCode, label) {

        if (Trenord.infoMobilita.isHome) {

            window.location.href = GLOBALS_REALTIME_PAGE + "?station=" + mirCode;

        } else {

            var mxp = window.location.hostname.indexOf('malpensaexpress.it') > -1;

            $("#station-search").val(label);

            $(".station-history-result").hide();

            $(".container-result-infomob").removeClass('hidden');
            $(".container-train.skeleton").show();
            $(".container-train.result").hide();
            $(".container-box-info-mob-map").hide();

            Trenord.infoMobilita.lastStation = mirCode;


            $.get('/rest/render/station-details', {
                mirCode: mirCode,
                mxp: mxp,
                L: Trenord.globals.currentLanguage,
                map_zoom: MAP_ZOOM
            }, function (data) {

                $(".container-train.result.partenza").html(data.partenza);
                $(".container-train.result.partenza .train").each(function (index) {
                        if(index >= 5){
                            $(this).addClass("hidden");
                        }
                });
                var mostraAltriPartenza = '<div class="container no-margin"><div class="mostra-altri d treni-partenza"><img id="" class="arrow mostra link link-mostra lozad" alt="immagine" data-src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png" src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png"><a class="link link-mostra treni-partenza">Mostra altri</a><img id="" class="arrow mostra link-mostra lozad" alt="immagine" data-src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png" src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png"></div></div>'
                $(".container-train.result.partenza").append(mostraAltriPartenza);
                $('body').on('click', 'a.link-mostra.treni-partenza', function() {

                        $(".container-train.result.partenza .train.hidden").each(function (index) {
                            if(index <= 5){
                                $(this).removeClass("hidden");
                            }
                        });

                        if($(".container-train.result.partenza .train.hidden").length == 0){
                            $(".mostra-altri.treni-partenza").addClass("hidden");
                        }
                    });

                if($(".container-train.result.partenza .train.hidden").length == 0){
                    $(".mostra-altri.treni-partenza").addClass("hidden");
                }



                $(".container-train.result.arrivo").html(data.arrivo);
                $(".container-train.result.arrivo .train").each(function (index) {
                    if(index >= 5){
                        $(this).addClass("hidden");
                    }
                });

                var mostraAltriArrivo = '<div class="container no-margin"><div class="mostra-altri d treni-arrivo"><img id="" class="arrow mostra link link-mostra lozad" alt="immagine" data-src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png" src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png"><a class="link link-mostra treni-arrivo">Mostra altri</a><img id="" class="arrow mostra link-mostra lozad" alt="immagine" data-src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png" src="https://trenord-europe-trenord-endpoint-prd.azureedge.net/fileadmin/templates/img/news/arrow-up.png"></div></div>'
                $(".container-train.result.arrivo").append(mostraAltriArrivo);

                $('body').on('click', 'a.link-mostra.treni-arrivo', function() {

                    $(".container-train.result.arrivo .train.hidden").each(function (index) {
                        if(index <= 5){
                            $(this).removeClass("hidden");
                        }
                    });

                    if($(".container-train.result.arrivo .train.hidden").length == 0){
                        $(".mostra-altri.treni-arrivo").addClass("hidden");
                    }
                });

                if($(".container-train.result.arrivo .train.hidden").length == 0){
                    $(".mostra-altri.treni-arrivo").addClass("hidden");
                }

                $(".container-box-info-mob-map").html(data.stationMap);

                $(".container-train.skeleton").hide();
                $(".container-train.result").show();
                $(".container-box-info-mob-map").show();

                Trenord.ui.infoMobilita.initEvents();
                Trenord.ui.infoMobilita.initTrainDetailsEvent();
                Trenord.ui.carouselLine();

                //codice duplicato per la determinazione dei parametri
                //scenario back
                var params = Trenord.utility.locationSearchToObject();
                if (params.train && params.station) {
                    $("#train-detail-open-" + params.train).trigger('click');

                    $('html, body').animate({
                        scrollTop: $("#train-detail-open-" + params.train).parents(".train.prossimi-treni").offset().top - 50
                    }, 700);

                }
            });
        }
    },

    /**
     * aggiorna la history del browser per gestire la casistica di back
     * @param train_id
     * @param station_id
     */
    updateHistory: function (station_id, train_id) {

        if (train_id != undefined && train_id != "") {

            var skeletonImg = '<img style="width: 100%" class="animate-flicker" src="/fileadmin/templates/img/skeleton_img.png">';
            $(".train-sub-details-" + train_id).html(skeletonImg);

            var trimmedTrainId = new String(train_id).slice(-5).replace(/^0+/, '') // remove leading zeros

            $.get('/rest/render/train-sub-detail', {trainId: trimmedTrainId}, function (details) {
                for (var transportCode in details) {
                    $(".train-sub-details-" + transportCode).html(details[transportCode]);
                }
            
                Trenord.ui.infoMobilita.initEvents();
                Trenord.ui.infoMobilita.initTrainDetailsEvent();
                Trenord.ui.carouselLine();
            })
        }

        //in caso di ritorno da scenario "ricerca stazione"
        if (train_id != undefined && train_id != "" && station_id != undefined && station_id != "") {
            history.pushState(null, null, window.location.origin + window.location.pathname + "?station=" + station_id + "&stationName="+$("#station-search").val());
            return true;
        }

        if (station_id != undefined && station_id != "") {
            history.pushState(null, null, window.location.origin + window.location.pathname + "?station=" + station_id+"&stationName="+$("#station-search").val()+"");
            return true;
        }

        //in casi di ritorno da scenario "ricerca treno"
        if (train_id != undefined && train_id != "") {
            history.pushState(null, null, window.location.origin + window.location.pathname + "?train=" + trimmedTrainId);
            return true;
        }


        //in caso di parametri inconsistenti
        return false;
    }
}
Trenord.ui.accessibilita = function () {

    if (getCookie("Font-size") === "") {
        $(".container-link .dropdown-menu.access-text li a > span.normal").addClass("active");
    }

    if (getCookie("Font-size") === "normal") {
        $(".container-link .dropdown-menu.access-text li a > span").removeClass("active");
        setTimeout(function () {
            $(".container-link .dropdown-menu.access-text li a > span.normal").addClass("active");
        }, 20);
    }

    if (getCookie("Font-size") === "big") {
        setTimeout(function () {
            $(".container-link .dropdown-menu.access-text li a > span.big")[0].click();
        }, 100);
    }


    if (getCookie("Font-size") === "small") {
        setTimeout(function () {
            $(".container-link .dropdown-menu.access-text li a > span.small")[0].click();
        }, 100);

    }


    $(".container-link .dropdown-menu.access-text li a").click(function () {
        var activeElement = $(".container-link .dropdown-menu.access-text li a .active").attr("id");

    });


    $('a,p,ul,h1,h2,h3,h4,label').each(function (index) {
        var fontSizeElement = $(this).css("font-size");
        var res = fontSizeElement.replace(/\D/g, "");
        var numFont = parseInt(res) - numDiff + "px";
        $(this).css({ 'font-size': numFont });
    });

    function setCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        } else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        setCookie(name, "", -1);
    }


    $("#contrastoElevato").click(function () {

        if (!$(this).hasClass("active")) {

            $(".triangle-slider-mobile").css("border-color", "transparent transparent #a00000 transparent;");

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(0, 102, 51)';
            }).each(function () {
                $(this).css('background-color', 'rgb(0, 80, 0)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(0, 102, 51)';
            }).each(function () {
                $(this).css('color', 'rgb(0, 80, 0)');
            });

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(210, 0, 25)';
            }).each(function () {
                $(this).css('background-color', 'rgb(160, 0, 0)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(210, 0, 25)';
            }).each(function () {
                $(this).css('color', 'rgb(160, 0, 0)');
            });

            $('*').filter(function () {
                return $(this).css('fill') == 'rgb(210, 0, 25)';
            }).each(function () {
                $(this).css('fill', 'rgb(160, 0, 0)');
            });


            $('*').filter(function () {
                return $(this).css('fill') == 'rgb(0, 102, 51)';
            }).each(function () {
                $(this).css('fill', 'rgb(0, 80, 0)');
            });

            $('.container-tab').css('background-image', 'url(/fileadmin/templates/img/slider-home/fill_access.png)');

            $(this).toggleClass("active");
        } else {
            $(".triangle-slider-mobile").css("border-color", "transparent transparent #d20019 transparent;");

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(0, 80, 0)';
            }).each(function () {
                $(this).css('background-color', 'rgb(0, 102, 51)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(0, 80, 0)';
            }).each(function () {
                $(this).css('color', 'rgb(0, 102, 51)');
            });

            $('*').filter(function () {
                return $(this).css('background-color') == 'rgb(160, 0, 0)';
            }).each(function () {
                $(this).css('background-color', 'rgb(210, 0, 25)');
            });

            $('*').filter(function () {
                return $(this).css('color') == 'rgb(160, 0, 0)';
            }).each(function () {
                $(this).css('color', 'rgb(210, 0, 25)');
            });

            $('*').filter(function () {
                return $(this).css('fill') == ' rgb(160, 0, 0)';
            }).each(function () {
                $(this).css('fill', 'rgb(210, 0, 25)');
            });


            $('*').filter(function () {
                return $(this).css('fill') == ' rgb(0, 80, 0)';
            }).each(function () {
                $(this).css('fill', 'rgb(0, 102, 51)');
            });

            $('.container-tab').css('background-image', 'url(/fileadmin/templates/img/slider-home/fill.png)');
            $(this).toggleClass("active");
        }
    });


    function contrastoOff() {
        $(".triangle-slider-mobile").css("border-color", "transparent transparent #d20019 transparent;");

        eraseCookie('Contrasto')
        $("#contrastoElevato").removeClass("active");
        setCookie('Contrasto', 'off', 1);

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(0, 80, 0)';
        }).each(function () {
            $(this).css('background-color', 'rgb(0, 102, 51)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(0, 80, 0)';
        }).each(function () {
            $(this).css('color', 'rgb(0, 102, 51)');
        });

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(160, 0, 0)';
        }).each(function () {
            $(this).css('background-color', 'rgb(210, 0, 25)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(160, 0, 0)';
        }).each(function () {
            $(this).css('color', 'rgb(210, 0, 25)');
        });


        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(160, 0, 0)';
        }).each(function () {
            $(this).css('fill', 'rgb(210, 0, 25)');
        });


        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(0, 80, 0)';
        }).each(function () {
            $(this).css('fill', 'rgb(0, 102, 51)');
        });

        if ($("body").hasClass("malpensaStyle")) {
            $('.container-tab').css('background-image', 'url(/fileadmin/templates/img/slider-home/fill-red.png)');
        } else {
            $('.container-tab').css('background-image', 'url(/fileadmin/templates/img/slider-home/fill.png)');
        }

        $("#contrastoElevato").removeClass("active");
    }



    function contrastoOn() {
        $(".triangle-slider-mobile").css("border-color", "transparent transparent #a00000 transparent;");

        eraseCookie('Contrasto')
        $("#contrastoElevato").removeClass("active");
        setCookie('Contrasto', 'on', 1);

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(0, 102, 51)';
        }).each(function () {
            $(this).css('background-color', 'rgb(0, 80, 0)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(0, 102, 51)';
        }).each(function () {
            $(this).css('color', 'rgb(0, 80, 0)');
        });

        $('*').filter(function () {
            return $(this).css('background-color') == 'rgb(210, 0, 25)';
        }).each(function () {
            $(this).css('background-color', 'rgb(160, 0, 0)');
        });

        $('*').filter(function () {
            return $(this).css('color') == 'rgb(210, 0, 25)';
        }).each(function () {
            $(this).css('color', 'rgb(160, 0, 0)');
        });

        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(210, 0, 25)';
        }).each(function () {
            $(this).css('fill', 'rgb(160, 0, 0)');
        });


        $('*').filter(function () {
            return $(this).css('fill') == 'rgb(0, 102, 51)';
        }).each(function () {
            $(this).css('fill', 'rgb(0, 80, 0)');
        });




        $("#contrastoElevato").addClass("active");
    }


};
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/*!***************************************************
* mark.js v9.0.0
* https://markjs.io/
* Copyright (c) 2014–2018, Julian Kühnel
* Released under the MIT license https://git.io/vwTVl
*****************************************************/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],t):e.Mark=t(e.jQuery)}(this,function(e){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}e=e&&e.hasOwnProperty("default")?e.default:e;var a=
/* */
function(){function e(t){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:5e3;n(this,e),this.ctx=t,this.iframes=r,this.exclude=o,this.iframesTimeout=i}return o(e,[{key:"getContexts",value:function(){var e=[];return(void 0!==this.ctx&&this.ctx?NodeList.prototype.isPrototypeOf(this.ctx)?Array.prototype.slice.call(this.ctx):Array.isArray(this.ctx)?this.ctx:"string"==typeof this.ctx?Array.prototype.slice.call(document.querySelectorAll(this.ctx)):[this.ctx]:[]).forEach(function(t){var n=e.filter(function(e){return e.contains(t)}).length>0;-1!==e.indexOf(t)||n||e.push(t)}),e}},{key:"getIframeContents",value:function(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){};try{var o=e.contentWindow;if(n=o.document,!o||!n)throw new Error("iframe inaccessible")}catch(e){r()}n&&t(n)}},{key:"isIframeBlank",value:function(e){var t="about:blank",n=e.getAttribute("src").trim();return e.contentWindow.location.href===t&&n!==t&&n}},{key:"observeIframeLoad",value:function(e,t,n){var r=this,o=!1,i=null,a=function a(){if(!o){o=!0,clearTimeout(i);try{r.isIframeBlank(e)||(e.removeEventListener("load",a),r.getIframeContents(e,t,n))}catch(e){n()}}};e.addEventListener("load",a),i=setTimeout(a,this.iframesTimeout)}},{key:"onIframeReady",value:function(e,t,n){try{"complete"===e.contentWindow.document.readyState?this.isIframeBlank(e)?this.observeIframeLoad(e,t,n):this.getIframeContents(e,t,n):this.observeIframeLoad(e,t,n)}catch(e){n()}}},{key:"waitForIframes",value:function(e,t){var n=this,r=0;this.forEachIframe(e,function(){return!0},function(e){r++,n.waitForIframes(e.querySelector("html"),function(){--r||t()})},function(e){e||t()})}},{key:"forEachIframe",value:function(t,n,r){var o=this,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},a=t.querySelectorAll("iframe"),s=a.length,c=0;a=Array.prototype.slice.call(a);var u=function(){--s<=0&&i(c)};s||u(),a.forEach(function(t){e.matches(t,o.exclude)?u():o.onIframeReady(t,function(e){n(t)&&(c++,r(e)),u()},u)})}},{key:"createIterator",value:function(e,t,n){return document.createNodeIterator(e,t,n,!1)}},{key:"createInstanceOnIframe",value:function(t){return new e(t.querySelector("html"),this.iframes)}},{key:"compareNodeIframe",value:function(e,t,n){if(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING){if(null===t)return!0;if(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)return!0}return!1}},{key:"getIteratorNode",value:function(e){var t=e.previousNode();return{prevNode:t,node:null===t?e.nextNode():e.nextNode()&&e.nextNode()}}},{key:"checkIframeFilter",value:function(e,t,n,r){var o=!1,i=!1;return r.forEach(function(e,t){e.val===n&&(o=t,i=e.handled)}),this.compareNodeIframe(e,t,n)?(!1!==o||i?!1===o||i||(r[o].handled=!0):r.push({val:n,handled:!0}),!0):(!1===o&&r.push({val:n,handled:!1}),!1)}},{key:"handleOpenIframes",value:function(e,t,n,r){var o=this;e.forEach(function(e){e.handled||o.getIframeContents(e.val,function(e){o.createInstanceOnIframe(e).forEachNode(t,n,r)})})}},{key:"iterateThroughNodes",value:function(e,t,n,r,o){for(var i,a,s,c=this,u=this.createIterator(t,e,r),l=[],h=[];s=void 0,s=c.getIteratorNode(u),a=s.prevNode,i=s.node;)this.iframes&&this.forEachIframe(t,function(e){return c.checkIframeFilter(i,a,e,l)},function(t){c.createInstanceOnIframe(t).forEachNode(e,function(e){return h.push(e)},r)}),h.push(i);h.forEach(function(e){n(e)}),this.iframes&&this.handleOpenIframes(l,e,n,r),o()}},{key:"forEachNode",value:function(e,t,n){var r=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},i=this.getContexts(),a=i.length;a||o(),i.forEach(function(i){var s=function(){r.iterateThroughNodes(e,i,t,n,function(){--a<=0&&o()})};r.iframes?r.waitForIframes(i,s):s()})}}],[{key:"matches",value:function(e,t){var n="string"==typeof t?[t]:t,r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector;if(r){var o=!1;return n.every(function(t){return!r.call(e,t)||(o=!0,!1)}),o}return!1}}]),e}(),s=
/* */
function(){function e(t){n(this,e),this.opt=i({},{diacritics:!0,synonyms:{},accuracy:"partially",caseSensitive:!1,ignoreJoiners:!1,ignorePunctuation:[],wildcards:"disabled"},t)}return o(e,[{key:"create",value:function(e){return"disabled"!==this.opt.wildcards&&(e=this.setupWildcardsRegExp(e)),e=this.escapeStr(e),Object.keys(this.opt.synonyms).length&&(e=this.createSynonymsRegExp(e)),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),this.opt.diacritics&&(e=this.createDiacriticsRegExp(e)),e=this.createMergedBlanksRegExp(e),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.createJoinersRegExp(e)),"disabled"!==this.opt.wildcards&&(e=this.createWildcardsRegExp(e)),e=this.createAccuracyRegExp(e),new RegExp(e,"gm".concat(this.opt.caseSensitive?"":"i"))}},{key:"sortByLength",value:function(e){return e.sort(function(e,t){return e.length===t.length?e>t?1:-1:t.length-e.length})}},{key:"escapeStr",value:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}},{key:"createSynonymsRegExp",value:function(e){var t=this,n=this.opt.synonyms,r=this.opt.caseSensitive?"":"i",o=this.opt.ignoreJoiners||this.opt.ignorePunctuation.length?"\0":"";for(var i in n)if(n.hasOwnProperty(i)){var a=Array.isArray(n[i])?n[i]:[n[i]];a.unshift(i),(a=this.sortByLength(a).map(function(e){return"disabled"!==t.opt.wildcards&&(e=t.setupWildcardsRegExp(e)),e=t.escapeStr(e)}).filter(function(e){return""!==e})).length>1&&(e=e.replace(new RegExp("(".concat(a.map(function(e){return t.escapeStr(e)}).join("|"),")"),"gm".concat(r)),o+"(".concat(a.map(function(e){return t.processSynonyms(e)}).join("|"),")")+o))}return e}},{key:"processSynonyms",value:function(e){return(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),e}},{key:"setupWildcardsRegExp",value:function(e){return(e=e.replace(/(?:\\)*\?/g,function(e){return"\\"===e.charAt(0)?"?":""})).replace(/(?:\\)*\*/g,function(e){return"\\"===e.charAt(0)?"*":""})}},{key:"createWildcardsRegExp",value:function(e){var t="withSpaces"===this.opt.wildcards;return e.replace(/\u0001/g,t?"[\\S\\s]?":"\\S?").replace(/\u0002/g,t?"[\\S\\s]*?":"\\S*")}},{key:"setupIgnoreJoinersRegExp",value:function(e){return e.replace(/[^(|)\\]/g,function(e,t,n){var r=n.charAt(t+1);return/[(|)\\]/.test(r)||""===r?e:e+"\0"})}},{key:"createJoinersRegExp",value:function(e){var t=[],n=this.opt.ignorePunctuation;return Array.isArray(n)&&n.length&&t.push(this.escapeStr(n.join(""))),this.opt.ignoreJoiners&&t.push("\\u00ad\\u200b\\u200c\\u200d"),t.length?e.split(/\u0000+/).join("[".concat(t.join(""),"]*")):e}},{key:"createDiacriticsRegExp",value:function(e){var t=this.opt.caseSensitive?"":"i",n=this.opt.caseSensitive?["aàáảãạăằắẳẵặâầấẩẫậäåāą","AÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ","cçćč","CÇĆČ","dđď","DĐĎ","eèéẻẽẹêềếểễệëěēę","EÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ","iìíỉĩịîïī","IÌÍỈĨỊÎÏĪ","lł","LŁ","nñňń","NÑŇŃ","oòóỏõọôồốổỗộơởỡớờợöøō","OÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ","rř","RŘ","sšśșş","SŠŚȘŞ","tťțţ","TŤȚŢ","uùúủũụưừứửữựûüůū","UÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ","yýỳỷỹỵÿ","YÝỲỶỸỴŸ","zžżź","ZŽŻŹ"]:["aàáảãạăằắẳẵặâầấẩẫậäåāąAÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ","cçćčCÇĆČ","dđďDĐĎ","eèéẻẽẹêềếểễệëěēęEÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ","iìíỉĩịîïīIÌÍỈĨỊÎÏĪ","lłLŁ","nñňńNÑŇŃ","oòóỏõọôồốổỗộơởỡớờợöøōOÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ","rřRŘ","sšśșşSŠŚȘŞ","tťțţTŤȚŢ","uùúủũụưừứửữựûüůūUÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ","yýỳỷỹỵÿYÝỲỶỸỴŸ","zžżźZŽŻŹ"],r=[];return e.split("").forEach(function(o){n.every(function(n){if(-1!==n.indexOf(o)){if(r.indexOf(n)>-1)return!1;e=e.replace(new RegExp("[".concat(n,"]"),"gm".concat(t)),"[".concat(n,"]")),r.push(n)}return!0})}),e}},{key:"createMergedBlanksRegExp",value:function(e){return e.replace(/[\s]+/gim,"[\\s]+")}},{key:"createAccuracyRegExp",value:function(e){var t=this,n=this.opt.accuracy,r="string"==typeof n?n:n.value,o="string"==typeof n?[]:n.limiters,i="";switch(o.forEach(function(e){i+="|".concat(t.escapeStr(e))}),r){case"partially":default:return"()(".concat(e,")");case"complementary":return i="\\s"+(i||this.escapeStr("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~¡¿")),"()([^".concat(i,"]*").concat(e,"[^").concat(i,"]*)");case"exactly":return"(^|\\s".concat(i,")(").concat(e,")(?=$|\\s").concat(i,")")}}}]),e}(),c=
/* */
function(){function e(t){n(this,e),this.ctx=t,this.ie=!1;var r=window.navigator.userAgent;(r.indexOf("MSIE")>-1||r.indexOf("Trident")>-1)&&(this.ie=!0)}return o(e,[{key:"log",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"debug",r=this.opt.log;this.opt.debug&&"object"===t(r)&&"function"==typeof r[n]&&r[n]("mark.js: ".concat(e))}},{key:"getSeparatedKeywords",value:function(e){var t=this,n=[];return e.forEach(function(e){t.opt.separateWordSearch?e.split(" ").forEach(function(e){e.trim()&&-1===n.indexOf(e)&&n.push(e)}):e.trim()&&-1===n.indexOf(e)&&n.push(e)}),{keywords:n.sort(function(e,t){return t.length-e.length}),length:n.length}}},{key:"isNumeric",value:function(e){return Number(parseFloat(e))==e}},{key:"checkRanges",value:function(e){var t=this;if(!Array.isArray(e)||"[object Object]"!==Object.prototype.toString.call(e[0]))return this.log("markRanges() will only accept an array of objects"),this.opt.noMatch(e),[];var n=[],r=0;return e.sort(function(e,t){return e.start-t.start}).forEach(function(e){var o=t.callNoMatchOnInvalidRanges(e,r),i=o.start,a=o.end;o.valid&&(e.start=i,e.length=a-i,n.push(e),r=a)}),n}},{key:"callNoMatchOnInvalidRanges",value:function(e,t){var n,r,o=!1;return e&&void 0!==e.start?(r=(n=parseInt(e.start,10))+parseInt(e.length,10),this.isNumeric(e.start)&&this.isNumeric(e.length)&&r-t>0&&r-n>0?o=!0:(this.log("Ignoring invalid or overlapping range: "+"".concat(JSON.stringify(e))),this.opt.noMatch(e))):(this.log("Ignoring invalid range: ".concat(JSON.stringify(e))),this.opt.noMatch(e)),{start:n,end:r,valid:o}}},{key:"checkWhitespaceRanges",value:function(e,t,n){var r,o=!0,i=n.length,a=t-i,s=parseInt(e.start,10)-a;return(r=(s=s>i?i:s)+parseInt(e.length,10))>i&&(r=i,this.log("End range automatically set to the max value of ".concat(i))),s<0||r-s<0||s>i||r>i?(o=!1,this.log("Invalid range: ".concat(JSON.stringify(e))),this.opt.noMatch(e)):""===n.substring(s,r).replace(/\s+/g,"")&&(o=!1,this.log("Skipping whitespace only range: "+JSON.stringify(e)),this.opt.noMatch(e)),{start:s,end:r,valid:o}}},{key:"getTextNodes",value:function(e){var t=this,n="",r=[];this.iterator.forEachNode(NodeFilter.SHOW_TEXT,function(e){r.push({start:n.length,end:(n+=e.textContent).length,node:e})},function(e){return t.matchesExclude(e.parentNode)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},function(){e({value:n,nodes:r})})}},{key:"matchesExclude",value:function(e){return a.matches(e,this.opt.exclude.concat(["script","style","title","head","html"]))}},{key:"wrapRangeInTextNode",value:function(e,t,n){var r=this.opt.element?this.opt.element:"mark",o=e.splitText(t),i=o.splitText(n-t),a=document.createElement(r);return a.setAttribute("data-markjs","true"),this.opt.className&&a.setAttribute("class",this.opt.className),a.textContent=o.textContent,o.parentNode.replaceChild(a,o),i}},{key:"wrapRangeInMappedTextNode",value:function(e,t,n,r,o){var i=this;e.nodes.every(function(a,s){var c=e.nodes[s+1];if(void 0===c||c.start>t){if(!r(a.node))return!1;var u=t-a.start,l=(n>a.end?a.end:n)-a.start,h=e.value.substr(0,a.start),f=e.value.substr(l+a.start);if(a.node=i.wrapRangeInTextNode(a.node,u,l),e.value=h+f,e.nodes.forEach(function(t,n){n>=s&&(e.nodes[n].start>0&&n!==s&&(e.nodes[n].start-=l),e.nodes[n].end-=l)}),n-=l,o(a.node.previousSibling,a.start),!(n>a.end))return!1;t=a.end}return!0})}},{key:"wrapGroups",value:function(e,t,n,r){return r((e=this.wrapRangeInTextNode(e,t,t+n)).previousSibling),e}},{key:"separateGroups",value:function(e,t,n,r,o){for(var i=t.length,a=1;a<i;a++){var s=e.textContent.indexOf(t[a]);t[a]&&s>-1&&r(t[a],e)&&(e=this.wrapGroups(e,s,t[a].length,o))}return e}},{key:"wrapMatches",value:function(e,t,n,r,o){var i=this,a=0===t?0:t+1;this.getTextNodes(function(t){t.nodes.forEach(function(t){var o;for(t=t.node;null!==(o=e.exec(t.textContent))&&""!==o[a];){if(i.opt.separateGroups)t=i.separateGroups(t,o,a,n,r);else{if(!n(o[a],t))continue;var s=o.index;if(0!==a)for(var c=1;c<a;c++)s+=o[c].length;t=i.wrapGroups(t,s,o[a].length,r)}e.lastIndex=0}}),o()})}},{key:"wrapMatchesAcrossElements",value:function(e,t,n,r,o){var i=this,a=0===t?0:t+1;this.getTextNodes(function(t){for(var s;null!==(s=e.exec(t.value))&&""!==s[a];){var c=s.index;if(0!==a)for(var u=1;u<a;u++)c+=s[u].length;var l=c+s[a].length;i.wrapRangeInMappedTextNode(t,c,l,function(e){return n(s[a],e)},function(t,n){e.lastIndex=n,r(t)})}o()})}},{key:"wrapRangeFromIndex",value:function(e,t,n,r){var o=this;this.getTextNodes(function(i){var a=i.value.length;e.forEach(function(e,r){var s=o.checkWhitespaceRanges(e,a,i.value),c=s.start,u=s.end;s.valid&&o.wrapRangeInMappedTextNode(i,c,u,function(n){return t(n,e,i.value.substring(c,u),r)},function(t){n(t,e)})}),r()})}},{key:"unwrapMatches",value:function(e){for(var t=e.parentNode,n=document.createDocumentFragment();e.firstChild;)n.appendChild(e.removeChild(e.firstChild));t.replaceChild(n,e),this.ie?this.normalizeTextNode(t):t.normalize()}},{key:"normalizeTextNode",value:function(e){if(e){if(3===e.nodeType)for(;e.nextSibling&&3===e.nextSibling.nodeType;)e.nodeValue+=e.nextSibling.nodeValue,e.parentNode.removeChild(e.nextSibling);else this.normalizeTextNode(e.firstChild);this.normalizeTextNode(e.nextSibling)}}},{key:"markRegExp",value:function(e,t){var n=this;this.opt=t,this.log('Searching with expression "'.concat(e,'"'));var r=0,o="wrapMatches";this.opt.acrossElements&&(o="wrapMatchesAcrossElements"),this[o](e,this.opt.ignoreGroups,function(e,t){return n.opt.filter(t,e,r)},function(e){r++,n.opt.each(e)},function(){0===r&&n.opt.noMatch(e),n.opt.done(r)})}},{key:"mark",value:function(e,t){var n=this;this.opt=t;var r=0,o="wrapMatches",i=this.getSeparatedKeywords("string"==typeof e?[e]:e),a=i.keywords,c=i.length;this.opt.acrossElements&&(o="wrapMatchesAcrossElements"),0===c?this.opt.done(r):function e(t){var i=new s(n.opt).create(t),u=0;n.log('Searching with expression "'.concat(i,'"')),n[o](i,1,function(e,o){return n.opt.filter(o,t,r,u)},function(e){u++,r++,n.opt.each(e)},function(){0===u&&n.opt.noMatch(t),a[c-1]===t?n.opt.done(r):e(a[a.indexOf(t)+1])})}(a[0])}},{key:"markRanges",value:function(e,t){var n=this;this.opt=t;var r=0,o=this.checkRanges(e);o&&o.length?(this.log("Starting to mark with the following ranges: "+JSON.stringify(o)),this.wrapRangeFromIndex(o,function(e,t,r,o){return n.opt.filter(e,t,r,o)},function(e,t){r++,n.opt.each(e,t)},function(){n.opt.done(r)})):this.opt.done(r)}},{key:"unmark",value:function(e){var t=this;this.opt=e;var n=this.opt.element?this.opt.element:"*";n+="[data-markjs]",this.opt.className&&(n+=".".concat(this.opt.className)),this.log('Removal selector "'.concat(n,'"')),this.iterator.forEachNode(NodeFilter.SHOW_ELEMENT,function(e){t.unwrapMatches(e)},function(e){var r=a.matches(e,n),o=t.matchesExclude(e);return!r||o?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},this.opt.done)}},{key:"opt",set:function(e){this._opt=i({},{element:"",className:"",exclude:[],iframes:!1,iframesTimeout:5e3,separateWordSearch:!0,acrossElements:!1,ignoreGroups:0,each:function(){},noMatch:function(){},filter:function(){return!0},done:function(){},debug:!1,log:window.console},e)},get:function(){return this._opt}},{key:"iterator",get:function(){return new a(this.ctx,this.opt.iframes,this.opt.exclude,this.opt.iframesTimeout)}}]),e}();return e.fn.mark=function(e,t){return new c(this.get()).mark(e,t),this},e.fn.markRegExp=function(e,t){return new c(this.get()).markRegExp(e,t),this},e.fn.markRanges=function(e,t){return new c(this.get()).markRanges(e,t),this},e.fn.unmark=function(e){return new c(this.get()).unmark(e),this},e});

/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery);
Trenord.ui.formGruppi = function () {

    //array radio
    var arrRadio = [];
    $.each($('input:radio'), function () {
        var myname = this.name;
        if ($.inArray(myname, arrRadio) < 0) {
            arrRadio.push(myname);
        }

    });

$('#station-select-partenza-andata').on('change', function(e){
 
    $(".label-station-select-partenza-andata").addClass("active");
});
    
    $('#station-select-arrivo-andata').on('change', function(e){
 
    $(".label-station-select-arrivo-andata").addClass("active");
    });
    

        $('#station-select-arrivo-ritorno').on('change', function(e){
 
    $(".label-station-select-arrivo-ritorno").addClass("active");
        });
    
    $('#station-select-partenza-ritorno').on('change', function(e){
 
    $(".label-station-select-partenza-ritorno").addClass("active");
});

    //validation email

    function isValidEmailAddress(emailAddress) {
        var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
        return pattern.test(emailAddress);
    }

    //error count
    var countError = 0;



//checkradiobox
    function checkRadio(elem) {
        if ($('input[type=radio][name*=' + elem + ']').is(":checked")) {
            $('input[type=radio][name*=' + elem + ']').each(function (index) {
                $(this).next().css("color", "#4b4b4b");
            });
            return true;
        } else {
            $('input[type=radio][name*=' + elem + ']').each(function (index) {
                $(this).next().css("color", "red");
            });
            countError += 1;
        }

    }



    $('input[type=radio]').on("change", function () {

        var elemName = $(this).attr("name");
        if (elemName == "ritiro-biglietti") {

            $('input[type=radio][name=modalita-pagamento]').each(function (index) {
                $(this).next().css("color", "#4b4b4b");
            });
        }

        $('input[type=radio][name*=' + elemName + ']').each(function (index) {
            $(this).next().css("color", "#4b4b4b");
        });
    });



//check and sumbit form 
    $("#sumbit-form-gruppi").click(function (e) {
        e.preventDefault();


//check radio
        arrRadio.map(function (index, item) {



         checkRadio(index);

        });


        //check select

        if ($("#station-select-partenza-andata").val() == null) {

            $(".label-station-select-partenza-andata").css("color", "red");

            countError += 1;
        } else {
            $(".label-station-select-partenza-andata").css("color", "#4b4b4b");
        }

        if ($("#station-select-arrivo-andata").val() == null) {

            $(".label-station-select-arrivo-andata").css("color", "red");

            countError += 1;
        } else {
            $(".label-station-select-arrivo-andata").css("color", "#4b4b4b");
        }
        if ($("#adulti").val() > 0) {
            $(".label-adulti").css("color", "#4b4b4b");
        } else {
            countError += 1;
            $(".label-adulti").css("color", "red");

        }

        // check input



        $(".obb").each(function () {
            if ($(this).val() == "") {
                countError += 1;
                $(this).parent().find("label").css("color", "red");
            } else {
                $(this).parent().find("label").css("color", "#4b4b4b");
            }
        });



        if (!isValidEmailAddress($("#email_referente").val())) {
            console.log($("#email_referente").val())
            $("#email_referente").parent().find("label").css("color", "red");
            countError += 1;

        } else {
            $("#email_referente").parent().find("label").css("color", "#4b4b4b");
        }

        if ($("#email_gruppo").val()) {
            if (!isValidEmailAddress($("#email_gruppo").val())) {
                console.log($("#email_gruppo").val())
                $("#email_gruppo").parent().find("label").css("color", "red");
                countError += 1;

            } else {
                $("#email_gruppo").parent().find("label").css("color", "#4b4b4b");
            }
        }

  


        if (countError == 0) {
            $("#form-gruppi").submit();
            $(".container-error-contatti").hide();
        } else {
            $(".container-error-contatti").show();
        }

        countError = 0;
    });






    $("#andata_form_gruppi").blur(function () {
        $("#andata_form_gruppi").val() !== "" ? $("#label-date-andata").addClass("active") : $("#label-date-andata").removeClass("active");
    });

    $("#ritorno_form_gruppi").blur(function () {
        $("#ritorno_form_gruppi").val() !== "" ? $("#label-date-ritorno").addClass("active") : $("#label-date-ritorno").removeClass("active");
    });




    //calcolo partecipatni e blocco numerico

    (function ($) {
        $.fn.inputFilter = function (inputFilter) {
            return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function () {
                if (inputFilter(this.value)) {
                    this.oldValue = this.value;
                    this.oldSelectionStart = this.selectionStart;
                    this.oldSelectionEnd = this.selectionEnd;
                } else if (this.hasOwnProperty("oldValue")) {
                    this.value = this.oldValue;
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                } else {
                    this.value = "";
                }
            });
        };
    }(jQuery));

    $(".only-number").inputFilter(function (value) {
        return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 800);
    });


    $("input.only-number.tot-part").on('input', function () {
        var sum = 0;
        var sum_paganti = 0;

        $('.only-number').each(function () {
            var val = $.trim($(this).val());

            if (val) {
                val = parseInt(val);

                sum += !isNaN(val) ? val : 0;
            }
        });

        sum_paganti = (!isNaN(parseInt($("#adulti").val())) ? parseInt($("#adulti").val()) : 0) + (!isNaN(parseInt($("#ragazzi").val())) ? parseInt($("#ragazzi").val()) : 0);

        $(".totale-partecipanti b span").text(sum);
        $(".totale-paganti b span").text(sum_paganti);
    });



    //gestione pagamenti online e biglietteria
    $('input[type=radio][name=ritiro-biglietti]').change(function () {


        if (this.value == 'biglietteria') {
            $(".select-biglietterie").removeClass("hidden");

            $('input[name="modalita-pagamento"][value="contanti"]').prop('checked', true)
        } else {
            $(".select-biglietterie").addClass("hidden");
            $('input[name="modalita-pagamento"][value="bonifico"]').prop('checked', true)
        }
    });


    $('input[type=radio][name=modalita-pagamento]').change(function () {


        if (this.value == 'bonifico') {
            $(".select-biglietterie").addClass("hidden");

            $('input[name="ritiro-biglietti"][value="biglietti-online"]').prop('checked', true);
        } else {
            $(".select-biglietterie").removeClass("hidden");
            $('input[name="ritiro-biglietti"][value="biglietteria"]').prop('checked', true);
        }
    });



    if ($('#andata_form_gruppi').length) {
        $('#andata_form_gruppi').datepicker({
            language: 'IT',
            format: 'dd/mm/yyyy',
            orientation: 'auto bottom',
        }).on('changeDate', function (ev) {
            $('#ritorno_form_gruppi').datepicker('setStartDate', $(this).datepicker('getDate'));
        }).on("show", function (e) {
            var timeRange = $("#time-range");
            timeRange.show();
            $(" .datepicker .prev, .datepicker .next").empty();

            if (!$(".datepicker-dropdown h4").length) {

                $(".datepicker-dropdown").prepend("<h4>Andata</h4>");
                $(".datepicker-dropdown").prepend("<img alt='icona_chiudi_calendario'  class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");
                $(".datepicker-dropdown").append(timeRange);
            } else {
                var timeRange = $("#time-range");
                timeRange.show();
                $(".datepicker-dropdown").append(timeRange);
            }

            $(".datepicker-dropdown .close-datepicker").click(function () {
                $('.datepicker').hide();
            });


        }).on('hide', function (date) {



            if ($("#orario1").val() !== "") {

                if ($("#data").val() !== "") {
                    $("#andata_form_gruppi").val("" + $("#data").val() + " Tra le " + $("#orario1").val() + "e le " + $("#orario2").val() + "");
                } else {
                    $("#andata_form_gruppi").val(" Tra le " + $("#orario1").val() + "e le " + $("#orario2").val() + "");

                }
            }

        }).attr('readonly', 'readonly');
    }

    if ($('#ritorno_form_gruppi').length) {

        $("#ritorno_form_gruppi").on("changeDate", function (e) {

            var dateInput = $(this).val().split("Tra");
            $('#data_ritorno').val(dateInput[0]);
            $("#label-date-ritorno").css("color", "#212121");
            $(this).css("border-bottom", "1px solid #212121");
            $(this).html("");
            var time1 = $("#time-range-ritorno .slider_time_ritorno").html();
            var time2 = $("#time-range-ritorno .slider_time2_ritorno").html();
            $("#orario1_ritorno").val(time1);
            $("#orario2_ritorno").val(time2);
            $(this).val("" + dateInput + ", Tra le " + time1 + " e le " + time2 + "");
            $("#label-date-ritorno").css("top", "-10px");
            $("#label-date-ritorno").css("font-size", "0.7222rem");
            $("#label-date-ritorno").css("color", "#212121");;
        });

        $('#ritorno_form_gruppi').datepicker({
            language: 'IT',
            format: 'dd/mm/yyyy',
            orientation: 'auto bottom',
        }).on("show", function (e) {
            var timeRange = $("#time-range-ritorno");
            timeRange.show();
            $(" .datepicker .prev, .datepicker .next").empty();

            if (!$(".datepicker-dropdown h4").length) {

                $(".datepicker-dropdown").prepend("<h4>Ritorno</h4>");
                $(".datepicker-dropdown").prepend("<img alt='icona_chiudi_calendario'  class='close-datepicker lozad' src='/fileadmin/templates/img/news/close.png'>");
                $(".datepicker-dropdown").append(timeRange);
            } else {
                var timeRange = $("#time-range-ritorno");
                timeRange.show();
                $(".datepicker-dropdown").append(timeRange);
            }

            $(".datepicker-dropdown .close-datepicker").click(function () {
                $('.datepicker').hide();
            });
        }).on('hide', function (date) {



            if ($("#orario1_ritorno").val() !== "") {

                if ($("#data_ritorno").val() !== "") {
                    $("#ritorno_form_gruppi").val("" + $("#data_ritorno").val() + " Tra le " + $("#orario1_ritorno").val() + "e le " + $("#orario2_ritorno").val() + "");
                } else {
                    $("#ritorno_form_gruppi").val(" Tra le " + $("#orario1_ritorno").val() + "e le " + $("#orario2_ritorno").val() + "");

                }
            }

        }).attr('readonly', 'readonly');
    }
};