/* Minification failed. Returning unminified contents.
(13158,13,13170,14): run-time error JS1314: Implicit property name must be identifier: confirm(isOccasionChosen) {
                if (isOccasionChosen) {
                    LocationFirst.panel.occasion.setOccassion('btLocationFirstOccasion', 'ddLocationFirstOccasion');
                }
                if (!LocationFirst.panel.validateAddress()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstOccasion', 'ddLocationFirstAddressSearch');
                } else if (!LocationFirst.panel.validateDate()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstOccasion', 'ddLocationFirstDeliveryDate');
                } else {
                    LocationFirst.searchProducts();
                    LocationFirst.panel.popup.close('ddLocationFirstOccasion');
                }
            }
 */
/*! jQuery v2.1.4 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){
return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ia={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,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qa[0].contentDocument,b.write(),b.close(),c=sa(a,b),qa.detach()),ra[a]=c),c}var ua=/^margin/,va=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wa=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};function xa(a,b,c){var d,e,f,g,h=a.style;return c=c||wa(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),va.test(g)&&ua.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function ya(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),f.removeChild(c),b}})}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var za=/^(none|table(?!-c[ea]).+)/,Aa=new RegExp("^("+Q+")(.*)$","i"),Ba=new RegExp("^([+-])=("+Q+")","i"),Ca={position:"absolute",visibility:"hidden",display:"block"},Da={letterSpacing:"0",fontWeight:"400"},Ea=["Webkit","O","Moz","ms"];function Fa(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Ea.length;while(e--)if(b=Ea[e]+c,b in a)return b;return d}function Ga(a,b,c){var d=Aa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Ha(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ia(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wa(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xa(a,b,f),(0>e||null==e)&&(e=a.style[b]),va.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Ha(a,b,c||(g?"border":"content"),d,f)+"px"}function Ja(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",ta(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xa(a,"opacity");return""===c?"1":c}}}},cssNumber:{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:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fa(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Ba.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fa(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xa(a,b,d)),"normal"===e&&b in Da&&(e=Da[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?za.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Ca,function(){return Ia(a,b,d)}):Ia(a,b,d):void 0},set:function(a,c,d){var e=d&&wa(a);return Ga(a,c,d?Ha(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=ya(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ua.test(a)||(n.cssHooks[a+b].set=Ga)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wa(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Ja(this,!0)},hide:function(){return Ja(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Ka(a,b,c,d,e){return new Ka.prototype.init(a,b,c,d,e)}n.Tween=Ka,Ka.prototype={constructor:Ka,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ka.propHooks[this.prop];return a&&a.get?a.get(this):Ka.propHooks._default.get(this)},run:function(a){var b,c=Ka.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ka.propHooks._default.set(this),this}},Ka.prototype.init.prototype=Ka.prototype,Ka.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Ka.propHooks.scrollTop=Ka.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Ka.prototype.init,n.fx.step={};var La,Ma,Na=/^(?:toggle|show|hide)$/,Oa=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pa=/queueHooks$/,Qa=[Va],Ra={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Oa.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Oa.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sa(){return setTimeout(function(){La=void 0}),La=n.now()}function Ta(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ua(a,b,c){for(var d,e=(Ra[b]||[]).concat(Ra["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Va(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||ta(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Na.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?ta(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ua(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wa(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xa(a,b,c){var d,e,f=0,g=Qa.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=La||Sa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:La||Sa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wa(k,j.opts.specialEasing);g>f;f++)if(d=Qa[f].call(j,a,k,j.opts))return d;return n.map(k,Ua,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(Xa,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Ra[c]=Ra[c]||[],Ra[c].unshift(b)},prefilter:function(a,b){b?Qa.unshift(a):Qa.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xa(this,n.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pa.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Ta(b,!0),a,d,e)}}),n.each({slideDown:Ta("show"),slideUp:Ta("hide"),slideToggle:Ta("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(La=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),La=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ma||(Ma=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Ma),Ma=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Ya,Za,$a=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Za:Ya)),
void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Za={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_a.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ab=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cb=n.now(),db=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var eb=/#.*$/,fb=/([?&])_=[^&]*/,gb=/^(.*?):[ \t]*([^\r\n]*)$/gm,hb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,ib=/^(?:GET|HEAD)$/,jb=/^\/\//,kb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,lb={},mb={},nb="*/".concat("*"),ob=a.location.href,pb=kb.exec(ob.toLowerCase())||[];function qb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function rb(a,b,c,d){var e={},f=a===mb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function sb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function tb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function ub(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ob,type:"GET",isLocal:hb.test(pb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":nb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?sb(sb(a,n.ajaxSettings),b):sb(n.ajaxSettings,a)},ajaxPrefilter:qb(lb),ajaxTransport:qb(mb),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=gb.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||ob)+"").replace(eb,"").replace(jb,pb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=kb.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===pb[1]&&h[2]===pb[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(pb[3]||("http:"===pb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),rb(lb,k,b,v),2===t)return v;i=n.event&&k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!ib.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(db.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=fb.test(d)?d.replace(fb,"$1_="+cb++):d+(db.test(d)?"&":"?")+"_="+cb++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+nb+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=rb(mb,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=tb(k,v,f)),u=ub(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var vb=/%20/g,wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&").replace(vb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Bb=0,Cb={},Db={0:200,1223:204},Eb=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Cb)Cb[a]()}),k.cors=!!Eb&&"withCredentials"in Eb,k.ajax=Eb=!!Eb,n.ajaxTransport(function(a){var b;return k.cors||Eb&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Bb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Cb[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Db[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Cb[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Fb=[],Gb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Fb.pop()||n.expando+"_"+cb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Gb.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Gb,"$1"+e):b.jsonp!==!1&&(b.url+=(db.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Fb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Hb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Hb)return Hb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Ib=a.document.documentElement;function Jb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Jb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Ib;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ib})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Jb(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=ya(k.pixelPosition,function(a,c){return c?(c=xa(a,b),va.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Kb=a.jQuery,Lb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Lb),b&&a.jQuery===n&&(a.jQuery=Kb),n},typeof b===U&&(a.jQuery=a.$=n),n});
//# sourceMappingURL=jquery.min.map;
/*! jQuery v3.4.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(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}k.fn=k.prototype={jquery:f,constructor:k,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=k.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return k.each(this,e)},map:function(n){return this.pushStack(k.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.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(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},k.extend=k.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||m(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(k.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||k.isPlainObject(n)?n:{},i=!1,a[t]=k.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},k.extend({expando:"jQuery"+(f+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]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=v.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t){b(e,{nonce:t&&t.nonce})},each:function(e,t){var n,r=0;if(d(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(p,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(d(Object(e))?k.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.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=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(d(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g.apply([],a)},guid:1,support:y}),"function"==typeof Symbol&&(k.fn[Symbol.iterator]=t[Symbol.iterator]),k.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var h=function(n){var e,d,b,o,i,h,f,g,w,u,l,T,C,a,E,v,s,c,y,k="sizzle"+1*new Date,m=n.document,S=0,r=0,p=ue(),x=ue(),N=ue(),A=ue(),D=function(e,t){return e===t&&(l=!0),0},j={}.hasOwnProperty,t=[],q=t.pop,L=t.push,H=t.push,O=t.slice,P=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",I="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",W="\\["+M+"*("+I+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+I+"))|)"+M+"*\\]",$=":("+I+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+W+")*)|.*)\\)|)",F=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=new RegExp("^"+M+"*,"+M+"*"),z=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),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("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=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)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(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 de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){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[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.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},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="<a id='"+k+"'></a><select id='"+k+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.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 l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(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?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0<se(t,C,null,[e]).length},se.contains=function(e,t){return(e.ownerDocument||e)!==C&&T(e),y(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!==C&&T(e);var n=b.attrHandle[t.toLowerCase()],r=n&&j.call(b.attrHandle,t.toLowerCase())?n(e,t,!E):void 0;return void 0!==r?r:d.attributes||!E?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},se.escape=function(e){return(e+"").replace(re,ie)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],r=0,i=0;if(l=!d.detectDuplicates,u=!d.sortStable&&e.slice(0),e.sort(D),l){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return u=null,e},o=se.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else while(t=e[r++])n+=o(t);return n},(b=se.selectors={cacheLength:50,createPseudo:le,match:G,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(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===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]||se.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]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(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(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace(F," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(h,e,t,g,v){var y="nth"!==h.slice(0,3),m="last"!==h.slice(-4),x="of-type"===e;return 1===g&&0===v?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u,l=y!==m?"nextSibling":"previousSibling",c=e.parentNode,f=x&&e.nodeName.toLowerCase(),p=!n&&!x,d=!1;if(c){if(y){while(l){a=e;while(a=a[l])if(x?a.nodeName.toLowerCase()===f:1===a.nodeType)return!1;u=l="only"===h&&!u&&"nextSibling"}return!0}if(u=[m?c.firstChild:c.lastChild],m&&p){d=(s=(r=(i=(o=(a=c)[k]||(a[k]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===S&&r[1])&&r[2],a=s&&c.childNodes[s];while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if(1===a.nodeType&&++d&&a===e){i[h]=[S,s,d];break}}else if(p&&(d=s=(r=(i=(o=(a=e)[k]||(a[k]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===S&&r[1]),!1===d)while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if((x?a.nodeName.toLowerCase()===f:1===a.nodeType)&&++d&&(p&&((i=(o=a[k]||(a[k]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]=[S,d]),a===e))break;return(d-=v)===g||d%g==0&&0<=d/g}}},PSEUDO:function(e,o){var t,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return a[k]?a(o):1<a.length?(t=[e,e,"",o],b.setFilters.hasOwnProperty(e.toLowerCase())?le(function(e,t){var n,r=a(e,o),i=r.length;while(i--)e[n=P(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:le(function(e){var r=[],i=[],s=f(e.replace(B,"$1"));return s[k]?le(function(e,t,n,r){var i,o=s(e,null,r,[]),a=e.length;while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:le(function(t){return function(e){return 0<se(t,e).length}}),contains:le(function(t){return t=t.replace(te,ne),function(e){return-1<(e.textContent||o(e)).indexOf(t)}}),lang:le(function(n){return V.test(n||"")||se.error("unsupported lang: "+n),n=n.replace(te,ne).toLowerCase(),function(e){var t;do{if(t=E?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===a},focus:function(e){return e===C.activeElement&&(!C.hasFocus||C.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:ge(!1),disabled:ge(!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!b.pseudos.empty(e)},header:function(e){return J.test(e.nodeName)},input:function(e){return Q.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:ve(function(){return[0]}),last:ve(function(e,t){return[t-1]}),eq:ve(function(e,t,n){return[n<0?n+t:n]}),even:ve(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:ve(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:ve(function(e,t,n){for(var r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:ve(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=b.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[e]=de(e);for(e in{submit:!0,reset:!0})b.pseudos[e]=he(e);function me(){}function xe(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function be(s,e,t){var u=e.dir,l=e.next,c=l||u,f=t&&"parentNode"===c,p=r++;return e.first?function(e,t,n){while(e=e[u])if(1===e.nodeType||f)return s(e,t,n);return!1}:function(e,t,n){var r,i,o,a=[S,p];if(n){while(e=e[u])if((1===e.nodeType||f)&&s(e,t,n))return!0}else while(e=e[u])if(1===e.nodeType||f)if(i=(o=e[k]||(e[k]={}))[e.uniqueID]||(o[e.uniqueID]={}),l&&l===e.nodeName.toLowerCase())e=e[u]||e;else{if((r=i[c])&&r[0]===S&&r[1]===p)return a[2]=r[2];if((i[c]=a)[2]=s(e,t,n))return!0}return!1}}function we(i){return 1<i.length?function(e,t,n){var r=i.length;while(r--)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Te(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 Ce(d,h,g,v,y,e){return v&&!v[k]&&(v=Ce(v)),y&&!y[k]&&(y=Ce(y,e)),le(function(e,t,n,r){var i,o,a,s=[],u=[],l=t.length,c=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)se(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),f=!d||!e&&h?c:Te(c,s,d,n,r),p=g?y||(e?d:l||v)?[]:t:f;if(g&&g(f,p,n,r),v){i=Te(p,u),v(i,[],n,r),o=i.length;while(o--)(a=i[o])&&(p[u[o]]=!(f[u[o]]=a))}if(e){if(y||d){if(y){i=[],o=p.length;while(o--)(a=p[o])&&i.push(f[o]=a);y(null,p=[],i,r)}o=p.length;while(o--)(a=p[o])&&-1<(i=y?P(e,a):s[o])&&(e[i]=!(t[i]=a))}}else p=Te(p===t?p.splice(l,p.length):p),y?y(null,t,p,r):H.apply(t,p)})}function Ee(e){for(var i,t,n,r=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,u=be(function(e){return e===i},a,!0),l=be(function(e){return-1<P(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!==w)||((i=t).nodeType?u(e,t,n):l(e,t,n));return i=null,r}];s<r;s++)if(t=b.relative[e[s].type])c=[be(we(c),t)];else{if((t=b.filter[e[s].type].apply(null,e[s].matches))[k]){for(n=++s;n<r;n++)if(b.relative[e[n].type])break;return Ce(1<s&&we(c),1<s&&xe(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(B,"$1"),t,s<n&&Ee(e.slice(s,n)),n<r&&Ee(e=e.slice(n)),n<r&&xe(e))}c.push(t)}return we(c)}return me.prototype=b.filters=b.pseudos,b.setFilters=new me,h=se.tokenize=function(e,t){var n,r,i,o,a,s,u,l=x[e+" "];if(l)return t?0:l.slice(0);a=e,s=[],u=b.preFilter;while(a){for(o in n&&!(r=_.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=z.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace(B," ")}),a=a.slice(n.length)),b.filter)!(r=G[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?se.error(e):x(e,s).slice(0)},f=se.compile=function(e,t){var n,v,y,m,x,r,i=[],o=[],a=N[e+" "];if(!a){t||(t=h(e)),n=t.length;while(n--)(a=Ee(t[n]))[k]?i.push(a):o.push(a);(a=N(e,(v=o,m=0<(y=i).length,x=0<v.length,r=function(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],p=w,d=e||x&&b.find.TAG("*",i),h=S+=null==p?1:Math.random()||.1,g=d.length;for(i&&(w=t===C||t||i);l!==g&&null!=(o=d[l]);l++){if(x&&o){a=0,t||o.ownerDocument===C||(T(o),n=!E);while(s=v[a++])if(s(o,t||C,n)){r.push(o);break}i&&(S=h)}m&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,m&&l!==u){a=0;while(s=y[a++])s(c,f,t,n);if(e){if(0<u)while(l--)c[l]||f[l]||(f[l]=q.call(r));f=Te(f)}H.apply(r,f),i&&!e&&0<f.length&&1<u+y.length&&se.uniqueSort(r)}return i&&(S=h,w=p),c},m?le(r):r))).selector=e}return a},g=se.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&h(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&E&&b.relative[o[1].type]){if(!(t=(b.find.ID(a.matches[0].replace(te,ne),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}i=G.needsContext.test(e)?0:o.length;while(i--){if(a=o[i],b.relative[s=a.type])break;if((u=b.find[s])&&(r=u(a.matches[0].replace(te,ne),ee.test(o[0].type)&&ye(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&xe(o)))return H.apply(n,r),n;break}}}return(l||f(e,c))(r,t,!E,n,!t||ee.test(e)&&ye(t.parentNode)||t),n},d.sortStable=k.split("").sort(D).join("")===k,d.detectDuplicates=!!l,T(),d.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(C.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),d.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||fe(R,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),se}(C);k.find=h,k.expr=h.selectors,k.expr[":"]=k.expr.pseudos,k.uniqueSort=k.unique=h.uniqueSort,k.text=h.getText,k.isXMLDoc=h.isXML,k.contains=h.contains,k.escapeSelector=h.escape;var T=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&k(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},N=k.expr.match.needsContext;function A(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var D=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1<i.call(n,e)!==r}):k.filter(n,e,r)}k.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?k.find.matchesSelector(r,e)?[r]:[]:k.find.matches(e,k.grep(t,function(e){return 1===e.nodeType}))},k.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(k(e).filter(function(){for(t=0;t<r;t++)if(k.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)k.find(e,i[t],n);return 1<r?k.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&&N.test(e)?k(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(k.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&k(e);if(!N.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&k.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?k.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?i.call(k(e),this[0]):i.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(k.uniqueSort(k.merge(this.get(),k(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),k.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return T(e,"parentNode")},parentsUntil:function(e,t,n){return T(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return T(e,"nextSibling")},prevAll:function(e){return T(e,"previousSibling")},nextUntil:function(e,t,n){return T(e,"nextSibling",n)},prevUntil:function(e,t,n){return T(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return"undefined"!=typeof e.contentDocument?e.contentDocument:(A(e,"template")&&(e=e.content||e),k.merge([],e.childNodes))}},function(r,i){k.fn[r]=function(e,t){var n=k.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=k.filter(t,n)),1<this.length&&(O[r]||k.uniqueSort(n),H.test(r)&&n.reverse()),this.pushStack(n)}});var R=/[^\x20\t\r\n\f]+/g;function M(e){return e}function I(e){throw e}function W(e,t,n,r){var i;try{e&&m(i=e.promise)?i.call(e).done(t).fail(n):e&&m(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}k.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},k.each(e.match(R)||[],function(e,t){n[t]=!0}),n):k.extend({},r);var i,t,o,a,s=[],u=[],l=-1,c=function(){for(a=a||r.once,o=i=!0;u.length;l=-1){t=u.shift();while(++l<s.length)!1===s[l].apply(t[0],t[1])&&r.stopOnFalse&&(l=s.length,t=!1)}r.memory||(t=!1),i=!1,a&&(s=t?[]:"")},f={add:function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){k.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this},remove:function(){return k.each(arguments,function(e,t){var n;while(-1<(n=k.inArray(t,s,n)))s.splice(n,1),n<=l&&l--}),this},has:function(e){return e?-1<k.inArray(e,s):0<s.length},empty:function(){return s&&(s=[]),this},disable:function(){return a=u=[],s=t="",this},disabled:function(){return!s},lock:function(){return a=u=[],t||i||(s=t=""),this},locked:function(){return!!a},fireWith:function(e,t){return a||(t=[e,(t=t||[]).slice?t.slice():t],u.push(t),i||c()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},k.extend({Deferred:function(e){var o=[["notify","progress",k.Callbacks("memory"),k.Callbacks("memory"),2],["resolve","done",k.Callbacks("once memory"),k.Callbacks("once memory"),0,"resolved"],["reject","fail",k.Callbacks("once memory"),k.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},"catch":function(e){return a.then(null,e)},pipe:function(){var i=arguments;return k.Deferred(function(r){k.each(o,function(e,t){var n=m(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&m(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,m(t)?s?t.call(e,l(u,o,M,s),l(u,o,I,s)):(u++,t.call(e,l(u,o,M,s),l(u,o,I,s),l(u,o,M,o.notifyWith))):(a!==M&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){k.Deferred.exceptionHook&&k.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==I&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(k.Deferred.getStackHook&&(t.stackTrace=k.Deferred.getStackHook()),C.setTimeout(t))}}return k.Deferred(function(e){o[0][3].add(l(0,e,m(r)?r:M,e.notifyWith)),o[1][3].add(l(0,e,m(t)?t:M)),o[2][3].add(l(0,e,m(n)?n:I))}).promise()},promise:function(e){return null!=e?k.extend(e,a):a}},s={};return k.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){var n=arguments.length,t=n,r=Array(t),i=s.call(arguments),o=k.Deferred(),a=function(t){return function(e){r[t]=this,i[t]=1<arguments.length?s.call(arguments):e,--n||o.resolveWith(r,i)}};if(n<=1&&(W(e,o.done(a(t)).resolve,o.reject,!n),"pending"===o.state()||m(i[t]&&i[t].then)))return o.then();while(t--)W(i[t],a(t),o.reject);return o.promise()}});var $=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;k.Deferred.exceptionHook=function(e,t){C.console&&C.console.warn&&e&&$.test(e.name)&&C.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},k.readyException=function(e){C.setTimeout(function(){throw e})};var F=k.Deferred();function B(){E.removeEventListener("DOMContentLoaded",B),C.removeEventListener("load",B),k.ready()}k.fn.ready=function(e){return F.then(e)["catch"](function(e){k.readyException(e)}),this},k.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--k.readyWait:k.isReady)||(k.isReady=!0)!==e&&0<--k.readyWait||F.resolveWith(E,[k])}}),k.ready.then=F.then,"complete"===E.readyState||"loading"!==E.readyState&&!E.documentElement.doScroll?C.setTimeout(k.ready):(E.addEventListener("DOMContentLoaded",B),C.addEventListener("load",B));var _=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===w(n))for(s in i=!0,n)_(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,m(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(k(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},z=/^-ms-/,U=/-([a-z])/g;function X(e,t){return t.toUpperCase()}function V(e){return e.replace(z,"ms-").replace(U,X)}var G=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function Y(){this.expando=k.expando+Y.uid++}Y.uid=1,Y.prototype={cache:function(e){var t=e[this.expando];return t||(t={},G(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[V(t)]=n;else for(r in t)i[V(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][V(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(V):(t=V(t))in r?[t]:t.match(R)||[]).length;while(n--)delete r[t[n]]}(void 0===t||k.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&&!k.isEmptyObject(t)}};var Q=new Y,J=new Y,K=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Z=/[A-Z]/g;function ee(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(Z,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+""?+i:K.test(i)?JSON.parse(i):i)}catch(e){}J.set(e,t,n)}else n=void 0;return n}k.extend({hasData:function(e){return J.hasData(e)||Q.hasData(e)},data:function(e,t,n){return J.access(e,t,n)},removeData:function(e,t){J.remove(e,t)},_data:function(e,t,n){return Q.access(e,t,n)},_removeData:function(e,t){Q.remove(e,t)}}),k.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0===n){if(this.length&&(i=J.get(o),1===o.nodeType&&!Q.get(o,"hasDataAttrs"))){t=a.length;while(t--)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=V(r.slice(5)),ee(o,r,i[r]));Q.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof n?this.each(function(){J.set(this,n)}):_(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=J.get(o,n))?t:void 0!==(t=ee(o,n))?t:void 0;this.each(function(){J.set(this,n,e)})},null,e,1<arguments.length,null,!0)},removeData:function(e){return this.each(function(){J.remove(this,e)})}}),k.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Q.get(e,t),n&&(!r||Array.isArray(n)?r=Q.access(e,t,k.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=k.queue(e,t),r=n.length,i=n.shift(),o=k._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){k.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Q.get(e,n)||Q.access(e,n,{empty:k.Callbacks("once memory").add(function(){Q.remove(e,[t+"queue",n])})})}}),k.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?k.queue(this[0],t):void 0===n?this:this.each(function(){var e=k.queue(this,t,n);k._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&k.dequeue(this,t)})},dequeue:function(e){return this.each(function(){k.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=k.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=Q.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var te=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ne=new RegExp("^(?:([+-])=|)("+te+")([a-z%]*)$","i"),re=["Top","Right","Bottom","Left"],ie=E.documentElement,oe=function(e){return k.contains(e.ownerDocument,e)},ae={composed:!0};ie.getRootNode&&(oe=function(e){return k.contains(e.ownerDocument,e)||e.getRootNode(ae)===e.ownerDocument});var se=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&oe(e)&&"none"===k.css(e,"display")},ue=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];for(o in i=n.apply(e,r||[]),t)e.style[o]=a[o];return i};function le(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return k.css(e,t,"")},u=s(),l=n&&n[3]||(k.cssNumber[t]?"":"px"),c=e.nodeType&&(k.cssNumber[t]||"px"!==l&&+u)&&ne.exec(k.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)k.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,k.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 ce={};function fe(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=Q.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&se(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ce[s])||(o=a.body.appendChild(a.createElement(s)),u=k.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ce[s]=u)))):"none"!==n&&(l[c]="none",Q.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}k.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(){se(this)?k(this).show():k(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,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n<r;n++)Q.set(e[n],"globalEval",!t||Q.get(t[n],"globalEval"))}ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;var me,xe,be=/<|&#?\w+;/;function we(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"===w(o))k.merge(p,o.nodeType?[o]:o);else if(be.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+k.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;k.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&-1<k.inArray(o,r))i&&i.push(o);else if(l=oe(o),a=ve(f.appendChild(o),"script"),l&&ye(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}me=E.createDocumentFragment().appendChild(E.createElement("div")),(xe=E.createElement("input")).setAttribute("type","radio"),xe.setAttribute("checked","checked"),xe.setAttribute("name","t"),me.appendChild(xe),y.checkClone=me.cloneNode(!0).cloneNode(!0).lastChild.checked,me.innerHTML="<textarea>x</textarea>",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(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=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.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,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t<arguments.length;t++)u[t]=arguments[t];if(s.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,s)){a=k.event.handlers.call(this,s,l),t=0;while((i=a[t++])&&!s.isPropagationStopped()){s.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!s.isImmediatePropagationStopped())s.rnamespace&&!1!==o.namespace&&!s.rnamespace.test(o.namespace)||(s.handleObj=o,s.data=o.data,void 0!==(r=((k.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,u))&&!1===(s.result=r)&&(s.preventDefault(),s.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,s),s.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&&1<=e.button))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?-1<k(i,this).index(l):k.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(t,e){Object.defineProperty(k.Event.prototype,t,{enumerable:!0,configurable:!0,get:m(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[k.expando]?e:new k.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&De(t,"click",ke),!1},trigger:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&De(t,"click"),!0},_default:function(e){var t=e.target;return pe.test(t.type)&&t.click&&A(t,"input")&&Q.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},k.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},k.Event=function(e,t){if(!(this instanceof k.Event))return new k.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?ke:Se,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&&k.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[k.expando]=!0},k.Event.prototype={constructor:k.Event,isDefaultPrevented:Se,isPropagationStopped:Se,isImmediatePropagationStopped:Se,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=ke,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=ke,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=ke,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},k.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,code:!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&&Te.test(e.type)?null!=e.charCode?e.charCode:e.keyCode:!e.which&&void 0!==t&&Ce.test(e.type)?1&t?1:2&t?3:4&t?2:0:e.which}},k.event.addProp),k.each({focus:"focusin",blur:"focusout"},function(e,t){k.event.special[e]={setup:function(){return De(this,e,Ne),!1},trigger:function(){return De(this,e),!0},delegateType:t}}),k.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){k.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||k.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),k.fn.extend({on:function(e,t,n,r){return Ae(this,e,t,n,r)},one:function(e,t,n,r){return Ae(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,k(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=Se),this.each(function(){k.event.remove(this,e,n,t)})}});var je=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/<script|<style|<link/i,Le=/checked\s*(?:[^=]|=\s*.checked.)/i,He=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n<r;n++)k.event.add(t,i,l[i][n]);J.hasData(e)&&(s=J.access(e),u=k.extend({},s),J.set(t,u))}}function Ie(n,r,i,o){r=g.apply([],r);var e,t,a,s,u,l,c=0,f=n.length,p=f-1,d=r[0],h=m(d);if(h||1<f&&"string"==typeof d&&!y.checkClone&&Le.test(d))return n.each(function(e){var t=n.eq(e);h&&(r[0]=d.call(this,e,t.html())),Ie(t,r,i,o)});if(f&&(t=(e=we(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=k.map(ve(e,"script"),Pe)).length;c<f;c++)u=e,c!==p&&(u=k.clone(u,!0,!0),s&&k.merge(a,ve(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,k.map(a,Re),c=0;c<s;c++)u=a[c],he.test(u.type||"")&&!Q.access(u,"globalEval")&&k.contains(l,u)&&(u.src&&"module"!==(u.type||"").toLowerCase()?k._evalUrl&&!u.noModule&&k._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")}):b(u.textContent.replace(He,""),u,l))}return n}function We(e,t,n){for(var r,i=t?k.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||k.cleanData(ve(r)),r.parentNode&&(n&&oe(r)&&ye(ve(r,"script")),r.parentNode.removeChild(r));return e}k.extend({htmlPrefilter:function(e){return e.replace(je,"<$1></$2>")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r<i;r++)s=o[r],u=a[r],void 0,"input"===(l=u.nodeName.toLowerCase())&&pe.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||ve(e),a=a||ve(c),r=0,i=o.length;r<i;r++)Me(o[r],a[r]);else Me(e,c);return 0<(a=ve(c,"script")).length&&ye(a,!f&&ve(e,"script")),c},cleanData:function(e){for(var t,n,r,i=k.event.special,o=0;void 0!==(n=e[o]);o++)if(G(n)){if(t=n[Q.expando]){if(t.events)for(r in t.events)i[r]?k.event.remove(n,r):k.removeEvent(n,r,t.handle);n[Q.expando]=void 0}n[J.expando]&&(n[J.expando]=void 0)}}}),k.fn.extend({detach:function(e){return We(this,e,!0)},remove:function(e){return We(this,e)},text:function(e){return _(this,function(e){return void 0===e?k.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 Ie(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Oe(this,e).appendChild(e)})},prepend:function(){return Ie(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Oe(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Ie(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Ie(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&&(k.cleanData(ve(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return k.clone(this,e,t)})},html:function(e){return _(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&&!qe.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=k.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(k.cleanData(ve(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return Ie(this,arguments,function(e){var t=this.parentNode;k.inArray(this,n)<0&&(k.cleanData(ve(this)),t&&t.replaceChild(e,this))},n)}}),k.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){k.fn[e]=function(e){for(var t,n=[],r=k(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),k(r[o])[a](t),u.apply(n,t.get());return this.pushStack(n)}});var $e=new RegExp("^("+te+")(?!px)[a-z%]+$","i"),Fe=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=C),t.getComputedStyle(e)},Be=new RegExp(re.join("|"),"i");function _e(e,t,n){var r,i,o,a,s=e.style;return(n=n||Fe(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||oe(e)||(a=k.style(e,t)),!y.pixelBoxStyles()&&$e.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 ze(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}!function(){function e(){if(u){s.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",u.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",ie.appendChild(s).appendChild(u);var e=C.getComputedStyle(u);n="1%"!==e.top,a=12===t(e.marginLeft),u.style.right="60%",o=36===t(e.right),r=36===t(e.width),u.style.position="absolute",i=12===t(u.offsetWidth/3),ie.removeChild(s),u=null}}function t(e){return Math.round(parseFloat(e))}var n,r,i,o,a,s=E.createElement("div"),u=E.createElement("div");u.style&&(u.style.backgroundClip="content-box",u.cloneNode(!0).style.backgroundClip="",y.clearCloneStyle="content-box"===u.style.backgroundClip,k.extend(y,{boxSizingReliable:function(){return e(),r},pixelBoxStyles:function(){return e(),o},pixelPosition:function(){return e(),n},reliableMarginLeft:function(){return e(),a},scrollboxSize:function(){return e(),i}}))}();var Ue=["Webkit","Moz","ms"],Xe=E.createElement("div").style,Ve={};function Ge(e){var t=k.cssProps[e]||Ve[e];return t||(e in Xe?e:Ve[e]=function(e){var t=e[0].toUpperCase()+e.slice(1),n=Ue.length;while(n--)if((e=Ue[n]+t)in Xe)return e}(e)||e)}var Ye=/^(none|table(?!-c[ea]).+)/,Qe=/^--/,Je={position:"absolute",visibility:"hidden",display:"block"},Ke={letterSpacing:"0",fontWeight:"400"};function Ze(e,t,n){var r=ne.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function et(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+=k.css(e,n+re[a],!0,i)),r?("content"===n&&(u-=k.css(e,"padding"+re[a],!0,i)),"margin"!==n&&(u-=k.css(e,"border"+re[a]+"Width",!0,i))):(u+=k.css(e,"padding"+re[a],!0,i),"padding"!==n?u+=k.css(e,"border"+re[a]+"Width",!0,i):s+=k.css(e,"border"+re[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u}function tt(e,t,n){var r=Fe(e),i=(!y.boxSizingReliable()||n)&&"border-box"===k.css(e,"boxSizing",!1,r),o=i,a=_e(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if($e.test(a)){if(!n)return a;a="auto"}return(!y.boxSizingReliable()&&i||"auto"===a||!parseFloat(a)&&"inline"===k.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===k.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+et(e,t,n||(i?"border":"content"),o,r,a)+"px"}function nt(e,t,n,r,i){return new nt.prototype.init(e,t,n,r,i)}k.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=_e(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!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=V(t),u=Qe.test(t),l=e.style;if(u||(t=Ge(s)),a=k.cssHooks[t]||k.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=ne.exec(n))&&i[1]&&(n=le(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(k.cssNumber[s]?"":"px")),y.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=V(t);return Qe.test(t)||(t=Ge(s)),(a=k.cssHooks[t]||k.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=_e(e,t,r)),"normal"===i&&t in Ke&&(i=Ke[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),k.each(["height","width"],function(e,u){k.cssHooks[u]={get:function(e,t,n){if(t)return!Ye.test(k.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?tt(e,u,n):ue(e,Je,function(){return tt(e,u,n)})},set:function(e,t,n){var r,i=Fe(e),o=!y.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===k.css(e,"boxSizing",!1,i),s=n?et(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-et(e,u,"border",!1,i)-.5)),s&&(r=ne.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=k.css(e,u)),Ze(0,t,s)}}}),k.cssHooks.marginLeft=ze(y.reliableMarginLeft,function(e,t){if(t)return(parseFloat(_e(e,"marginLeft"))||e.getBoundingClientRect().left-ue(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),k.each({margin:"",padding:"",border:"Width"},function(i,o){k.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+re[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(k.cssHooks[i+o].set=Ze)}),k.fn.extend({css:function(e,t){return _(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Fe(e),i=t.length;a<i;a++)o[t[a]]=k.css(e,t[a],!1,r);return o}return void 0!==n?k.style(e,t,n):k.css(e,t)},e,t,1<arguments.length)}}),((k.Tween=nt).prototype={constructor:nt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||k.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(k.cssNumber[n]?"":"px")},cur:function(){var e=nt.propHooks[this.prop];return e&&e.get?e.get(this):nt.propHooks._default.get(this)},run:function(e){var t,n=nt.propHooks[this.prop];return this.options.duration?this.pos=t=k.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):nt.propHooks._default.set(this),this}}).init.prototype=nt.prototype,(nt.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=k.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){k.fx.step[e.prop]?k.fx.step[e.prop](e):1!==e.elem.nodeType||!k.cssHooks[e.prop]&&null==e.elem.style[Ge(e.prop)]?e.elem[e.prop]=e.now:k.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=nt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},k.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},k.fx=nt.prototype.init,k.fx.step={};var rt,it,ot,at,st=/^(?:toggle|show|hide)$/,ut=/queueHooks$/;function lt(){it&&(!1===E.hidden&&C.requestAnimationFrame?C.requestAnimationFrame(lt):C.setTimeout(lt,k.fx.interval),k.fx.tick())}function ct(){return C.setTimeout(function(){rt=void 0}),rt=Date.now()}function ft(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=re[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function pt(e,t,n){for(var r,i=(dt.tweeners[t]||[]).concat(dt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function dt(o,e,t){var n,a,r=0,i=dt.prefilters.length,s=k.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=rt||ct(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:k.extend({},e),opts:k.extend(!0,{specialEasing:{},easing:k.easing._default},t),originalProperties:e,originalOptions:t,startTime:rt||ct(),duration:t.duration,tweens:[],createTween:function(e,t){var n=k.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=V(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=k.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=dt.prefilters[r].call(l,o,c,l.opts))return m(n.stop)&&(k._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return k.map(c,pt,l),m(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),k.fx.timer(k.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}k.Animation=k.extend(dt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return le(n.elem,e,ne.exec(t),n),n}]},tweener:function(e,t){m(e)?(t=e,e=["*"]):e=e.match(R);for(var n,r=0,i=e.length;r<i;r++)n=e[r],dt.tweeners[n]=dt.tweeners[n]||[],dt.tweeners[n].unshift(t)},prefilters:[function(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&&se(e),v=Q.get(e,"fxshow");for(r in n.queue||(null==(a=k._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--,k.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],st.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!v||void 0===v[r])continue;g=!0}d[r]=v&&v[r]||k.style(e,r)}if((u=!k.isEmptyObject(t))||!k.isEmptyObject(d))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=v&&v.display)&&(l=Q.get(e,"display")),"none"===(c=k.css(e,"display"))&&(l?c=l:(fe([e],!0),l=e.style.display||l,c=k.css(e,"display"),fe([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===k.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,d)u||(v?"hidden"in v&&(g=v.hidden):v=Q.access(e,"fxshow",{display:l}),o&&(v.hidden=!g),g&&fe([e],!0),p.done(function(){for(r in g||fe([e]),Q.remove(e,"fxshow"),d)k.style(e,r,d[r])})),u=pt(g?v[r]:0,r,p),r in v||(v[r]=u.start,g&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?dt.prefilters.unshift(e):dt.prefilters.push(e)}}),k.speed=function(e,t,n){var r=e&&"object"==typeof e?k.extend({},e):{complete:n||!n&&t||m(e)&&e,duration:e,easing:n&&t||t&&!m(t)&&t};return k.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in k.fx.speeds?r.duration=k.fx.speeds[r.duration]:r.duration=k.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){m(r.old)&&r.old.call(this),r.queue&&k.dequeue(this,r.queue)},r},k.fn.extend({fadeTo:function(e,t,n,r){return this.filter(se).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){var i=k.isEmptyObject(t),o=k.speed(e,n,r),a=function(){var e=dt(this,k.extend({},t),o);(i||Q.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(i,e,o){var a=function(e){var t=e.stop;delete e.stop,t(o)};return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&!1!==i&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=k.timers,r=Q.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&ut.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||k.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=Q.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=k.timers,o=n?n.length:0;for(t.finish=!0,k.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),k.each(["toggle","show","hide"],function(e,r){var i=k.fn[r];k.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(ft(r,!0),e,t,n)}}),k.each({slideDown:ft("show"),slideUp:ft("hide"),slideToggle:ft("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){k.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),k.timers=[],k.fx.tick=function(){var e,t=0,n=k.timers;for(rt=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||k.fx.stop(),rt=void 0},k.fx.timer=function(e){k.timers.push(e),k.fx.start()},k.fx.interval=13,k.fx.start=function(){it||(it=!0,lt())},k.fx.stop=function(){it=null},k.fx.speeds={slow:600,fast:200,_default:400},k.fn.delay=function(r,e){return r=k.fx&&k.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=C.setTimeout(e,r);t.stop=function(){C.clearTimeout(n)}})},ot=E.createElement("input"),at=E.createElement("select").appendChild(E.createElement("option")),ot.type="checkbox",y.checkOn=""!==ot.value,y.optSelected=at.selected,(ot=E.createElement("input")).value="t",ot.type="radio",y.radioValue="t"===ot.value;var ht,gt=k.expr.attrHandle;k.fn.extend({attr:function(e,t){return _(this,k.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){k.removeAttr(this,e)})}}),k.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?k.prop(e,t,n):(1===o&&k.isXMLDoc(e)||(i=k.attrHooks[t.toLowerCase()]||(k.expr.match.bool.test(t)?ht:void 0)),void 0!==n?null===n?void k.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=k.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!y.radioValue&&"radio"===t&&A(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(R);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),ht={set:function(e,t,n){return!1===t?k.removeAttr(e,n):e.setAttribute(n,n),n}},k.each(k.expr.match.bool.source.match(/\w+/g),function(e,t){var a=gt[t]||k.find.attr;gt[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=gt[o],gt[o]=r,r=null!=a(e,t,n)?o:null,gt[o]=i),r}});var vt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;function mt(e){return(e.match(R)||[]).join(" ")}function xt(e){return e.getAttribute&&e.getAttribute("class")||""}function bt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(R)||[]}k.fn.extend({prop:function(e,t){return _(this,k.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[k.propFix[e]||e]})}}),k.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&k.isXMLDoc(e)||(t=k.propFix[t]||t,i=k.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=k.find.attr(e,"tabindex");return t?parseInt(t,10):vt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),y.optSelected||(k.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)}}),k.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){k.propFix[this.toLowerCase()]=this}),k.fn.extend({addClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){k(this).addClass(t.call(this,e,xt(this)))});if((e=bt(t)).length)while(n=this[u++])if(i=xt(n),r=1===n.nodeType&&" "+mt(i)+" "){a=0;while(o=e[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=mt(r))&&n.setAttribute("class",s)}return this},removeClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){k(this).removeClass(t.call(this,e,xt(this)))});if(!arguments.length)return this.attr("class","");if((e=bt(t)).length)while(n=this[u++])if(i=xt(n),r=1===n.nodeType&&" "+mt(i)+" "){a=0;while(o=e[a++])while(-1<r.indexOf(" "+o+" "))r=r.replace(" "+o+" "," ");i!==(s=mt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(i,t){var o=typeof i,a="string"===o||Array.isArray(i);return"boolean"==typeof t&&a?t?this.addClass(i):this.removeClass(i):m(i)?this.each(function(e){k(this).toggleClass(i.call(this,e,xt(this),t),t)}):this.each(function(){var e,t,n,r;if(a){t=0,n=k(this),r=bt(i);while(e=r[t++])n.hasClass(e)?n.removeClass(e):n.addClass(e)}else void 0!==i&&"boolean"!==o||((e=xt(this))&&Q.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",e||!1===i?"":Q.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&-1<(" "+mt(xt(n))+" ").indexOf(t))return!0;return!1}});var wt=/\r/g;k.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=m(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,k(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=k.map(t,function(e){return null==e?"":e+""})),(r=k.valHooks[this.type]||k.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=k.valHooks[t.type]||k.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(wt,""):null==e?"":e:void 0}}),k.extend({valHooks:{option:{get:function(e){var t=k.find.attr(e,"value");return null!=t?t:mt(k.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||!A(n.parentNode,"optgroup"))){if(t=k(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=k.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=-1<k.inArray(k.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),k.each(["radio","checkbox"],function(){k.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<k.inArray(k(e).val(),t)}},y.checkOn||(k.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),y.focusin="onfocusin"in C;var Tt=/^(?:focusinfocus|focusoutblur)$/,Ct=function(e){e.stopPropagation()};k.extend(k.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,p=[n||E],d=v.call(e,"type")?e.type:e,h=v.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||E,3!==n.nodeType&&8!==n.nodeType&&!Tt.test(d+k.event.triggered)&&(-1<d.indexOf(".")&&(d=(h=d.split(".")).shift(),h.sort()),u=d.indexOf(":")<0&&"on"+d,(e=e[k.expando]?e:new k.Event(d,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:k.makeArray(t,[e]),c=k.event.special[d]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!x(n)){for(s=c.delegateType||d,Tt.test(s+d)||(o=o.parentNode);o;o=o.parentNode)p.push(o),a=o;a===(n.ownerDocument||E)&&p.push(a.defaultView||a.parentWindow||C)}i=0;while((o=p[i++])&&!e.isPropagationStopped())f=o,e.type=1<i?s:c.bindType||d,(l=(Q.get(o,"events")||{})[e.type]&&Q.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&G(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=d,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(p.pop(),t)||!G(n)||u&&m(n[d])&&!x(n)&&((a=n[u])&&(n[u]=null),k.event.triggered=d,e.isPropagationStopped()&&f.addEventListener(d,Ct),n[d](),e.isPropagationStopped()&&f.removeEventListener(d,Ct),k.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=k.extend(new k.Event,n,{type:e,isSimulated:!0});k.event.trigger(r,null,t)}}),k.fn.extend({trigger:function(e,t){return this.each(function(){k.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return k.event.trigger(e,t,n,!0)}}),y.focusin||k.each({focus:"focusin",blur:"focusout"},function(n,r){var i=function(e){k.event.simulate(r,e.target,k.event.fix(e))};k.event.special[r]={setup:function(){var e=this.ownerDocument||this,t=Q.access(e,r);t||e.addEventListener(n,i,!0),Q.access(e,r,(t||0)+1)},teardown:function(){var e=this.ownerDocument||this,t=Q.access(e,r)-1;t?Q.access(e,r,t):(e.removeEventListener(n,i,!0),Q.remove(e,r))}}});var Et=C.location,kt=Date.now(),St=/\?/;k.parseXML=function(e){var t;if(!e||"string"!=typeof e)return null;try{t=(new C.DOMParser).parseFromString(e,"text/xml")}catch(e){t=void 0}return t&&!t.getElementsByTagName("parsererror").length||k.error("Invalid XML: "+e),t};var Nt=/\[\]$/,At=/\r?\n/g,Dt=/^(?:submit|button|image|reset|file)$/i,jt=/^(?:input|select|textarea|keygen)/i;function qt(n,e,r,i){var t;if(Array.isArray(e))k.each(e,function(e,t){r||Nt.test(n)?i(n,t):qt(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i)});else if(r||"object"!==w(e))i(n,e);else for(t in e)qt(n+"["+t+"]",e[t],r,i)}k.param=function(e,t){var n,r=[],i=function(e,t){var n=m(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!k.isPlainObject(e))k.each(e,function(){i(this.name,this.value)});else for(n in e)qt(n,e[n],t,i);return r.join("&")},k.fn.extend({serialize:function(){return k.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=k.prop(this,"elements");return e?k.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!k(this).is(":disabled")&&jt.test(this.nodeName)&&!Dt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=k(this).val();return null==n?null:Array.isArray(n)?k.map(n,function(e){return{name:t.name,value:e.replace(At,"\r\n")}}):{name:t.name,value:n.replace(At,"\r\n")}}).get()}});var Lt=/%20/g,Ht=/#.*$/,Ot=/([?&])_=[^&]*/,Pt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Rt=/^(?:GET|HEAD)$/,Mt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Ft=E.createElement("a");function Bt(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(R)||[];if(m(t))while(n=i[r++])"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function _t(t,i,o,a){var s={},u=t===Wt;function l(e){var r;return s[e]=!0,k.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function zt(e,t){var n,r,i=k.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&k.extend(!0,e,r),e}Ft.href=Et.href,k.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Et.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Et.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":k.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,k.ajaxSettings),t):zt(k.ajaxSettings,e)},ajaxPrefilter:Bt(It),ajaxTransport:Bt(Wt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,p,n,d,r,h,g,i,o,v=k.ajaxSetup({},t),y=v.context||v,m=v.context&&(y.nodeType||y.jquery)?k(y):k.event,x=k.Deferred(),b=k.Callbacks("once memory"),w=v.statusCode||{},a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n){n={};while(t=Pt.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?p:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(v.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(x.promise(T),v.url=((e||v.url||Et.href)+"").replace(Mt,Et.protocol+"//"),v.type=t.method||t.type||v.method||v.type,v.dataTypes=(v.dataType||"*").toLowerCase().match(R)||[""],null==v.crossDomain){r=E.createElement("a");try{r.href=v.url,r.href=r.href,v.crossDomain=Ft.protocol+"//"+Ft.host!=r.protocol+"//"+r.host}catch(e){v.crossDomain=!0}}if(v.data&&v.processData&&"string"!=typeof v.data&&(v.data=k.param(v.data,v.traditional)),_t(It,v,t,T),h)return T;for(i in(g=k.event&&v.global)&&0==k.active++&&k.event.trigger("ajaxStart"),v.type=v.type.toUpperCase(),v.hasContent=!Rt.test(v.type),f=v.url.replace(Ht,""),v.hasContent?v.data&&v.processData&&0===(v.contentType||"").indexOf("application/x-www-form-urlencoded")&&(v.data=v.data.replace(Lt,"+")):(o=v.url.slice(f.length),v.data&&(v.processData||"string"==typeof v.data)&&(f+=(St.test(f)?"&":"?")+v.data,delete v.data),!1===v.cache&&(f=f.replace(Ot,"$1"),o=(St.test(f)?"&":"?")+"_="+kt+++o),v.url=f+o),v.ifModified&&(k.lastModified[f]&&T.setRequestHeader("If-Modified-Since",k.lastModified[f]),k.etag[f]&&T.setRequestHeader("If-None-Match",k.etag[f])),(v.data&&v.hasContent&&!1!==v.contentType||t.contentType)&&T.setRequestHeader("Content-Type",v.contentType),T.setRequestHeader("Accept",v.dataTypes[0]&&v.accepts[v.dataTypes[0]]?v.accepts[v.dataTypes[0]]+("*"!==v.dataTypes[0]?", "+$t+"; q=0.01":""):v.accepts["*"]),v.headers)T.setRequestHeader(i,v.headers[i]);if(v.beforeSend&&(!1===v.beforeSend.call(y,T,v)||h))return T.abort();if(u="abort",b.add(v.complete),T.done(v.success),T.fail(v.error),c=_t(Wt,v,t,T)){if(T.readyState=1,g&&m.trigger("ajaxSend",[T,v]),h)return T;v.async&&0<v.timeout&&(d=C.setTimeout(function(){T.abort("timeout")},v.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,d&&C.clearTimeout(d),c=void 0,p=r||"",T.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(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]}(v,T,n)),s=function(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}}(v,s,T,i),i?(v.ifModified&&((u=T.getResponseHeader("Last-Modified"))&&(k.lastModified[f]=u),(u=T.getResponseHeader("etag"))&&(k.etag[f]=u)),204===e||"HEAD"===v.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),T.status=e,T.statusText=(t||l)+"",i?x.resolveWith(y,[o,l,T]):x.rejectWith(y,[T,l,a]),T.statusCode(w),w=void 0,g&&m.trigger(i?"ajaxSuccess":"ajaxError",[T,v,i?o:a]),b.fireWith(y,[T,l]),g&&(m.trigger("ajaxComplete",[T,v]),--k.active||k.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return k.get(e,t,n,"json")},getScript:function(e,t){return k.get(e,void 0,t,"script")}}),k.each(["get","post"],function(e,i){k[i]=function(e,t,n,r){return m(t)&&(r=r||n,n=t,t=void 0),k.ajax(k.extend({url:e,type:i,dataType:r,data:t,success:n},k.isPlainObject(e)&&e))}}),k._evalUrl=function(e,t){return k.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){k.globalEval(e,t)}})},k.fn.extend({wrapAll:function(e){var t;return this[0]&&(m(e)&&(e=e.call(this[0])),t=k(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(n){return m(n)?this.each(function(e){k(this).wrapInner(n.call(this,e))}):this.each(function(){var e=k(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=m(t);return this.each(function(e){k(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){k(this).replaceWith(this.childNodes)}),this}}),k.expr.pseudos.hidden=function(e){return!k.expr.pseudos.visible(e)},k.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},k.ajaxSettings.xhr=function(){try{return new C.XMLHttpRequest}catch(e){}};var Ut={0:200,1223:204},Xt=k.ajaxSettings.xhr();y.cors=!!Xt&&"withCredentials"in Xt,y.ajax=Xt=!!Xt,k.ajaxTransport(function(i){var o,a;if(y.cors||Xt&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(Ut[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&C.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),k.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),k.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 k.globalEval(e),e}}}),k.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),k.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=k("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=mt(e.slice(s)),e=e.slice(0,s)),m(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&k.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?k("<div>").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.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"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.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,n){k.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}}),k.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),k.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)}}),k.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),m(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||k.guid++,i},k.holdReady=function(e){e?k.readyWait++:k.ready(!0)},k.isArray=Array.isArray,k.parseJSON=JSON.parse,k.nodeName=A,k.isFunction=m,k.isWindow=x,k.camelCase=V,k.type=w,k.now=Date.now,k.isNumeric=function(e){var t=k.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return k});var Qt=C.jQuery,Jt=C.$;return k.noConflict=function(e){return C.$===k&&(C.$=Jt),e&&C.jQuery===k&&(C.jQuery=Qt),k},e||(C.jQuery=C.$=k),k});
;
/*! jQuery UI - v1.12.1 - 2021-08-11
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, keycode.js, scroll-parent.js, unique-id.js, widgets/autocomplete.js, widgets/datepicker.js, widgets/menu.js, widgets/mouse.js, effect.js, effects/effect-transfer.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.ui = $.ui || {};

var version = $.ui.version = "1.12.1";


/*!
 * jQuery UI Widget 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/



var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;

$.cleanData = ( function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
			try {

				// Only trigger remove when necessary to save time
				events = $._data( elem, "events" );
				if ( events && events.remove ) {
					$( elem ).triggerHandler( "remove" );
				}

			// Http://bugs.jquery.com/ticket/8235
			} catch ( e ) {}
		}
		orig( elems );
	};
} )( $.cleanData );

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

	var namespace = name.split( "." )[ 0 ];
	name = name.split( "." )[ 1 ];
	var fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	if ( $.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

	// Create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

	// We need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = ( function() {
			function _super() {
				return base.prototype[ prop ].apply( this, arguments );
			}

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	} );

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string";
		var args = widgetSlice.call( arguments, 1 );
		var returnValue = this;

		if ( isMethodCall ) {

			// If this is an empty collection, we need to have the instance method
			// return undefined instead of the jQuery instance
			if ( !this.length && options === "instance" ) {
				returnValue = undefined;
			} else {
				this.each( function() {
					var methodValue;
					var instance = $.data( this, fullName );

					if ( options === "instance" ) {
						returnValue = instance;
						return false;
					}

					if ( !instance ) {
						return $.error( "cannot call methods on " + name +
							" prior to initialization; " +
							"attempted to call method '" + options + "'" );
					}

					if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
						return $.error( "no such method '" + options + "' for " + name +
							" widget instance" );
					}

					methodValue = instance[ options ].apply( instance, args );

					if ( methodValue !== instance && methodValue !== undefined ) {
						returnValue = methodValue && methodValue.jquery ?
							returnValue.pushStack( methodValue.get() ) :
							methodValue;
						return false;
					}
				} );
			}
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat( args ) );
			}

			this.each( function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			} );
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;
		var parts;
		var curOption;
		var i;

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

			// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

		// If the widget is becoming disabled, then nothing is interactive
		if ( value ) {
			this._removeClass( this.hoverable, null, "ui-state-hover" );
			this._removeClass( this.focusable, null, "ui-state-focus" );
		}
	},

	enable: function() {
		return this._setOptions( { disabled: false } );
	},

	disable: function() {
		return this._setOptions( { disabled: true } );
	},

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i < classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					current = $( $.unique( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption && options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		this._on( options.element, {
			"remove": "_untrackClassesElement"
		} );

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_untrackClassesElement: function( event ) {
		var that = this;
		$.each( that.classesElementLookup, function( key, value ) {
			if ( $.inArray( event.target, value ) !== -1 ) {
				that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
			}
		} );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement;
		var instance = this;

		// No suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// No element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

				// Allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
						$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// Copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

	_off: function( element, eventName ) {
		eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.off( eventName ).off( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
			},
			mouseleave: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
			}
		} );
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
			},
			focusout: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
			}
		} );
	},

	_trigger: function( type, event, data ) {
		var prop, orig;
		var callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// Copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

var widget = $.widget;


/*!
 * jQuery UI Position 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */

//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/


( function() {
var cachedScrollbarWidth,
	max = Math.max,
	abs = Math.abs,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function getDimensions( elem ) {
	var raw = elem[ 0 ];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( $.isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div " +
				"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
				"<div style='height:100px;width:auto;'></div></div>" ),
			innerDiv = div.children()[ 0 ];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[ 0 ].clientWidth;
		}

		div.remove();

		return ( cachedScrollbarWidth = w1 - w2 );
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isWindow = $.isWindow( withinElement[ 0 ] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
			hasOffset = !isWindow && !isDocument;
		return {
			element: withinElement,
			isWindow: isWindow,
			isDocument: isDocument,
			offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),
			width: withinElement.outerWidth(),
			height: withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// Make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
		target = $( options.of ),
		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[ 0 ].preventDefault ) {

		// Force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;

	// Clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// Force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1 ) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// Calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// Reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	} );

	// Normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each( function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
				scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
				scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				} );
			}
		} );

		if ( options.using ) {

			// Adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	} );
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// Element is wider than within
			if ( data.collisionWidth > outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;

			// Too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;

			// Adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// Element is taller than within
			if ( data.collisionHeight > outerHeight ) {

				// Element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;

			// Too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;

			// Adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
					outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
					atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
					outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
					offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

} )();

var position = $.ui.position;


/*!
 * jQuery UI :data 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/


var data = $.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo( function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		} ) :

		// Support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		}
} );

/*!
 * jQuery UI Disable Selection 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/

// This file is deprecated


var disableSelection = $.fn.extend( {
	disableSelection: ( function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.on( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			} );
		};
	} )(),

	enableSelection: function() {
		return this.off( ".ui-disableSelection" );
	}
} );


/*!
 * jQuery UI Keycode 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/


var keycode = $.ui.keyCode = {
	BACKSPACE: 8,
	COMMA: 188,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	LEFT: 37,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SPACE: 32,
	TAB: 9,
	UP: 38
};


/*!
 * jQuery UI Scroll Parent 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/



var scrollParent = $.fn.scrollParent = function( includeHidden ) {
	var position = this.css( "position" ),
		excludeStaticParent = position === "absolute",
		overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
		scrollParent = this.parents().filter( function() {
			var parent = $( this );
			if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
				return false;
			}
			return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
				parent.css( "overflow-x" ) );
		} ).eq( 0 );

	return position === "fixed" || !scrollParent.length ?
		$( this[ 0 ].ownerDocument || document ) :
		scrollParent;
};


/*!
 * jQuery UI Unique ID 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/



var uniqueId = $.fn.extend( {
	uniqueId: ( function() {
		var uuid = 0;

		return function() {
			return this.each( function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			} );
		};
	} )(),

	removeUniqueId: function() {
		return this.each( function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		} );
	}
} );



var safeActiveElement = $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
	try {
		activeElement = document.activeElement;
	} catch ( error ) {
		activeElement = document.body;
	}

	// Support: IE 9 - 11 only
	// IE may return null instead of an element
	// Interestingly, this only seems to occur when NOT in an iframe
	if ( !activeElement ) {
		activeElement = document.body;
	}

	// Support: IE 11 only
	// IE11 returns a seemingly empty object in some cases when accessing
	// document.activeElement from an <iframe>
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};


/*!
 * jQuery UI Menu 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Menu
//>>group: Widgets
//>>description: Creates nestable menus.
//>>docs: http://api.jqueryui.com/menu/
//>>demos: http://jqueryui.com/menu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/menu.css
//>>css.theme: ../../themes/base/theme.css



var widgetsMenu = $.widget( "ui.menu", {
	version: "1.12.1",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-caret-1-e"
		},
		items: "> *",
		menus: "ul",
		position: {
			my: "left top",
			at: "right top"
		},
		role: "menu",

		// Callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.attr( {
				role: this.options.role,
				tabIndex: 0
			} );

		this._addClass( "ui-menu", "ui-widget ui-widget-content" );
		this._on( {

			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .ui-menu-item": function( event ) {
				event.preventDefault();
			},
			"click .ui-menu-item": function( event ) {
				var target = $( event.target );
				var active = $( $.ui.safeActiveElement( this.document[ 0 ] ) );
				if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) &&
							active.closest( ".ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": function( event ) {

				// Ignore mouse events while typeahead is active, see #10458.
				// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
				// is over an item in the menu
				if ( this.previousFilter ) {
					return;
				}

				var actualTarget = $( event.target ).closest( ".ui-menu-item" ),
					target = $( event.currentTarget );

				// Ignore bubbled events on parent items, see #11641
				if ( actualTarget[ 0 ] !== target[ 0 ] ) {
					return;
				}

				// Remove ui-state-active class from siblings of the newly focused menu item
				// to avoid a jump caused by adjacent elements both having a class with a border
				this._removeClass( target.siblings().children( ".ui-state-active" ),
					null, "ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {

				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.find( this.options.items ).eq( 0 );

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay( function() {
					var notContained = !$.contains(
						this.element[ 0 ],
						$.ui.safeActiveElement( this.document[ 0 ] )
					);
					if ( notContained ) {
						this.collapseAll( event );
					}
				} );
			},
			keydown: "_keydown"
		} );

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		} );
	},

	_destroy: function() {
		var items = this.element.find( ".ui-menu-item" )
				.removeAttr( "role aria-disabled" ),
			submenus = items.children( ".ui-menu-item-wrapper" )
				.removeUniqueId()
				.removeAttr( "tabIndex role aria-haspopup" );

		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " +
					"tabIndex" )
				.removeUniqueId()
				.show();

		submenus.children().each( function() {
			var elem = $( this );
			if ( elem.data( "ui-menu-submenu-caret" ) ) {
				elem.remove();
			}
		} );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			skip = false;

			// Support number pad values
			character = event.keyCode >= 96 && event.keyCode <= 105 ?
				( event.keyCode - 96 ).toString() : String.fromCharCode( event.keyCode );

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip && match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay( function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.children( "[aria-haspopup='true']" ).length ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items, newSubmenus, newItems, newWrappers,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this._toggleClass( "ui-menu-icons", null, !!this.element.find( ".ui-icon" ).length );

		// Initialize nested menus
		newSubmenus = submenus.filter( ":not(.ui-menu)" )
			.hide()
			.attr( {
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			} )
			.each( function() {
				var menu = $( this ),
					item = menu.prev(),
					submenuCaret = $( "<span>" ).data( "ui-menu-submenu-caret", true );

				that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon );
				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCaret );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			} );

		this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" );

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".ui-menu-item" ).each( function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				that._addClass( item, "ui-menu-divider", "ui-widget-content" );
			}
		} );

		// Don't refresh list items that are already adapted
		newItems = items.not( ".ui-menu-item, .ui-menu-divider" );
		newWrappers = newItems.children()
			.not( ".ui-menu" )
				.uniqueId()
				.attr( {
					tabIndex: -1,
					role: this._itemRole()
				} );
		this._addClass( newItems, "ui-menu-item" )
			._addClass( newWrappers, "ui-menu-item-wrapper" );

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icons = this.element.find( ".ui-menu-icon" );
			this._removeClass( icons, null, this.options.icons.submenu )
				._addClass( icons, null, value.submenu );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", String( value ) );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	focus: function( event, item ) {
		var nested, focused, activeParent;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();

		focused = this.active.children( ".ui-menu-item-wrapper" );
		this._addClass( focused, null, "ui-state-active" );

		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		activeParent = this.active
			.parent()
				.closest( ".ui-menu-item" )
					.children( ".ui-menu-item-wrapper" );
		this._addClass( activeParent, null, "ui-state-active" );

		if ( event && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay( function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
			this._startOpening( nested );
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this._removeClass( this.active.children( ".ui-menu-item-wrapper" ),
			null, "ui-state-active" );

		this._trigger( "blur", event, { item: this.active } );
		this.active = null;
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the caret icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay( function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend( {
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay( function() {

			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event && event.target ).closest( this.element.find( ".ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all
			// sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );

			// Work around active item staying active after menu is blurred
			this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" );

			this.activeMenu = currentMenu;
		}, this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu.find( ".ui-menu" )
			.hide()
			.attr( "aria-hidden", "true" )
			.attr( "aria-expanded", "false" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &&
			this.active
				.children( ".ui-menu " )
					.find( this.options.items )
						.first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay( function() {
				this.focus( event, newItem );
			} );
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	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( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.eq( -1 );
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.eq( 0 );
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this.activeMenu.find( this.options.items )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.nextAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.prevAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
	},

	select: function( event ) {

		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function( character ) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

				// Only match on items, not dividers or other content (#10571)
				.filter( ".ui-menu-item" )
					.filter( function() {
						return regex.test(
							$.trim( $( this ).children( ".ui-menu-item-wrapper" ).text() ) );
					} );
	}
} );


/*!
 * jQuery UI Autocomplete 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Autocomplete
//>>group: Widgets
//>>description: Lists suggested words as the user is typing.
//>>docs: http://api.jqueryui.com/autocomplete/
//>>demos: http://jqueryui.com/autocomplete/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/autocomplete.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.autocomplete", {
	version: "1.12.1",
	defaultElement: "<input>",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,

	_create: function() {

		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		// Textareas are always multi-line
		// Inputs are always single-line, even if inside a contentEditable element
		// IE also treats inputs as contentEditable
		// All other element types are determined by whether or not they're contentEditable
		this.isMultiLine = isTextarea || !isInput && this._isContentEditable( this.element );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this._addClass( "ui-autocomplete-input" );
		this.element.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:

					// when menu is open and has focus
					if ( this.menu.active ) {

						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );

						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;

					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// Replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				if ( this.cancelBlur ) {
					delete this.cancelBlur;
					return;
				}

				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		} );

		this._initSource();
		this.menu = $( "<ul>" )
			.appendTo( this._appendTo() )
			.menu( {

				// disable ARIA support, the live region takes care of that
				role: null
			} )
			.hide()
			.menu( "instance" );

		this._addClass( this.menu.element, "ui-autocomplete", "ui-front" );
		this._on( this.menu.element, {
			mousedown: function( event ) {

				// prevent moving focus out of the text field
				event.preventDefault();

				// IE doesn't prevent moving focus even with event.preventDefault()
				// so we set a flag to know when we should ignore the blur event
				this.cancelBlur = true;
				this._delay( function() {
					delete this.cancelBlur;

					// Support: IE 8 only
					// Right clicking a menu item or selecting text from the menu items will
					// result in focus moving out of the input. However, we've already received
					// and ignored the blur event because of the cancelBlur flag set above. So
					// we restore focus to ensure that the menu closes properly based on the user's
					// next actions.
					if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
						this.element.trigger( "focus" );
					}
				} );
			},
			menufocus: function( event, ui ) {
				var label, item;

				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						} );

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {

					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label && $.trim( label ).length ) {
					this.liveRegion.children().hide();
					$( "<div>" ).text( label ).appendTo( this.liveRegion );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "ui-autocomplete-item" ),
					previous = this.previous;

				// Only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
					this.element.trigger( "focus" );
					this.previous = previous;

					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay( function() {
						this.previous = previous;
						this.selectedItem = item;
					} );
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}

				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		} );

		this.liveRegion = $( "<div>", {
			role: "status",
			"aria-live": "assertive",
			"aria-relevant": "additions"
		} )
			.appendTo( this.document[ 0 ].body );

		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		// Turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		} );
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_isEventTargetInWidget: function( event ) {
		var menuElement = this.menu.element[ 0 ];

		return event.target === this.element[ 0 ] ||
			event.target === menuElement ||
			$.contains( menuElement, event.target );
	},

	_closeOnClickOutside: function( event ) {
		if ( !this._isEventTargetInWidget( event ) ) {
			this.close();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front, dialog" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax( {
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response( [] );
					}
				} );
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay( function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// Always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this._addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return $.proxy( function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this._removeClass( "ui-autocomplete-loading" );
			}
		}, this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {

			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {

		// Remove the handler that closes the menu on outside clicks
		this._off( this.document, "mousedown" );

		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {

		// assume all items have the right format when the first item is complete
		if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			} );
		} );
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// Size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend( {
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}

		// Listen for interactions outside of the widget (#6642)
		this._on( this.document, {
			mousedown: "_closeOnClickOutside"
		} );
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(

			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "<li>" )
			.append( $( "<div>" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
				this.menu.isLastItem() && /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// Prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	},

	// Support: Chrome <=50
	// We should be able to just use this.element.prop( "isContentEditable" )
	// but hidden elements always report false in Chrome.
	// https://code.google.com/p/chromium/issues/detail?id=313082
	_isContentEditable: function( element ) {
		if ( !element.length ) {
			return false;
		}

		var editable = element.prop( "contentEditable" );

		if ( editable === "inherit" ) {
		  return this._isContentEditable( element.parent() );
		}

		return editable === "true";
	}
} );

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		} );
	}
} );

// Live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
	options: {
		messages: {
			noResults: "No search results.",
			results: function( amount ) {
				return amount + ( amount > 1 ? " results are" : " result is" ) +
					" available, use up and down arrow keys to navigate.";
			}
		}
	},

	__response: function( content ) {
		var message;
		this._superApply( arguments );
		if ( this.options.disabled || this.cancelSearch ) {
			return;
		}
		if ( content && content.length ) {
			message = this.options.messages.results( content.length );
		} else {
			message = this.options.messages.noResults;
		}
		this.liveRegion.children().hide();
		$( "<div>" ).text( message ).appendTo( this.liveRegion );
	}
} );

var widgetsAutocomplete = $.ui.autocomplete;


// jscs:disable maximumLineLength
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
/*!
 * jQuery UI Datepicker 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Datepicker
//>>group: Widgets
//>>description: Displays a calendar from an input or inline for selecting dates.
//>>docs: http://api.jqueryui.com/datepicker/
//>>demos: http://jqueryui.com/datepicker/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/datepicker.css
//>>css.theme: ../../themes/base/theme.css



$.extend( $.ui, { datepicker: { version: "1.12.1" } } );

var datepicker_instActive;

function datepicker_getZindex( elem ) {
	var position, value;
	while ( elem.length && elem[ 0 ] !== document ) {

		// Ignore z-index if position is set to a value where z-index is ignored by the browser
		// This makes behavior of this function consistent across browsers
		// WebKit always returns auto if the element is positioned
		position = elem.css( "position" );
		if ( position === "absolute" || position === "relative" || position === "fixed" ) {

			// IE returns 0 when zIndex is not specified
			// other browsers return a string
			// we ignore the case of nested elements with an explicit value of 0
			// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
			value = parseInt( elem.css( "zIndex" ), 10 );
			if ( !isNaN( value ) && value !== 0 ) {
				return value;
			}
		}
		elem = elem.parent();
	}

	return 0;
}
/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
	this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
	this._appendClass = "ui-datepicker-append"; // The name of the append marker class
	this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
	this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
	this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
	this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
	this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
	this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[ "" ] = { // Default regional settings
		closeText: "Done", // Display text for close link
		prevText: "Prev", // Display text for previous month link
		nextText: "Next", // Display text for next month link
		currentText: "Today", // Display text for current month link
		monthNames: [ "January","February","March","April","May","June",
			"July","August","September","October","November","December" ], // Names of months for drop-down and formatting
		monthNamesShort: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // For formatting
		dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // For formatting
		dayNamesShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // For formatting
		dayNamesMin: [ "Su","Mo","Tu","We","Th","Fr","Sa" ], // Column headings for days starting at Sunday
		weekHeader: "Wk", // Column header for week of the year
		dateFormat: "mm/dd/yy", // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: "" // Additional text to append to the year in the month headers
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: "focus", // "focus" for popup on focus,
			// "button" for trigger button, or "both" for either
		showAnim: "fadeIn", // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: "", // Display text following the input box, e.g. showing the format
		buttonText: "...", // Text for trigger button
		buttonImage: "", // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: "c-10:c+10", // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: "+10", // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with "+" for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: "fast", // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: "", // Selector for an alternate field to store selected dates into
		altFormat: "", // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false, // True to size the input for the date format, false to leave as is
		disabled: false // The initial disabled state
	};
	$.extend( this._defaults, this.regional[ "" ] );
	this.regional.en = $.extend( true, {}, this.regional[ "" ] );
	this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
	this.dpDiv = datepicker_bindHover( $( "<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) );
}

$.extend( Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: "hasDatepicker",

	//Keep track of the maximum number of rows displayed (see #7043)
	maxRows: 4,

	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	 * @param  settings  object - the new settings to use as defaults (anonymous object)
	 * @return the manager object
	 */
	setDefaults: function( settings ) {
		datepicker_extendRemove( this._defaults, settings || {} );
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
	 */
	_attachDatepicker: function( target, settings ) {
		var nodeName, inline, inst;
		nodeName = target.nodeName.toLowerCase();
		inline = ( nodeName === "div" || nodeName === "span" );
		if ( !target.id ) {
			this.uuid += 1;
			target.id = "dp" + this.uuid;
		}
		inst = this._newInst( $( target ), inline );
		inst.settings = $.extend( {}, settings || {} );
		if ( nodeName === "input" ) {
			this._connectDatepicker( target, inst );
		} else if ( inline ) {
			this._inlineDatepicker( target, inst );
		}
	},

	/* Create a new instance object. */
	_newInst: function( target, inline ) {
		var id = target[ 0 ].id.replace( /([^A-Za-z0-9_\-])/g, "\\\\$1" ); // escape jQuery meta chars
		return { id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: ( !inline ? this.dpDiv : // presentation div
			datepicker_bindHover( $( "<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) ) ) };
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function( target, inst ) {
		var input = $( target );
		inst.append = $( [] );
		inst.trigger = $( [] );
		if ( input.hasClass( this.markerClassName ) ) {
			return;
		}
		this._attachments( input, inst );
		input.addClass( this.markerClassName ).on( "keydown", this._doKeyDown ).
			on( "keypress", this._doKeyPress ).on( "keyup", this._doKeyUp );
		this._autoSize( inst );
		$.data( target, "datepicker", inst );

		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
	},

	/* Make attachments based on settings. */
	_attachments: function( input, inst ) {
		var showOn, buttonText, buttonImage,
			appendText = this._get( inst, "appendText" ),
			isRTL = this._get( inst, "isRTL" );

		if ( inst.append ) {
			inst.append.remove();
		}
		if ( appendText ) {
			inst.append = $( "<span class='" + this._appendClass + "'>" + appendText + "</span>" );
			input[ isRTL ? "before" : "after" ]( inst.append );
		}

		input.off( "focus", this._showDatepicker );

		if ( inst.trigger ) {
			inst.trigger.remove();
		}

		showOn = this._get( inst, "showOn" );
		if ( showOn === "focus" || showOn === "both" ) { // pop-up date picker when in the marked field
			input.on( "focus", this._showDatepicker );
		}
		if ( showOn === "button" || showOn === "both" ) { // pop-up date picker when button clicked
			buttonText = this._get( inst, "buttonText" );
			buttonImage = this._get( inst, "buttonImage" );
			inst.trigger = $( this._get( inst, "buttonImageOnly" ) ?
				$( "<img/>" ).addClass( this._triggerClass ).
					attr( { src: buttonImage, alt: buttonText, title: buttonText } ) :
				$( "<button type='button'></button>" ).addClass( this._triggerClass ).
					html( !buttonImage ? buttonText : $( "<img/>" ).attr(
					{ src:buttonImage, alt:buttonText, title:buttonText } ) ) );
			input[ isRTL ? "before" : "after" ]( inst.trigger );
			inst.trigger.on( "click", function() {
				if ( $.datepicker._datepickerShowing && $.datepicker._lastInput === input[ 0 ] ) {
					$.datepicker._hideDatepicker();
				} else if ( $.datepicker._datepickerShowing && $.datepicker._lastInput !== input[ 0 ] ) {
					$.datepicker._hideDatepicker();
					$.datepicker._showDatepicker( input[ 0 ] );
				} else {
					$.datepicker._showDatepicker( input[ 0 ] );
				}
				return false;
			} );
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function( inst ) {
		if ( this._get( inst, "autoSize" ) && !inst.inline ) {
			var findMax, max, maxI, i,
				date = new Date( 2009, 12 - 1, 20 ), // Ensure double digits
				dateFormat = this._get( inst, "dateFormat" );

			if ( dateFormat.match( /[DM]/ ) ) {
				findMax = function( names ) {
					max = 0;
					maxI = 0;
					for ( i = 0; i < names.length; i++ ) {
						if ( names[ i ].length > max ) {
							max = names[ i ].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth( findMax( this._get( inst, ( dateFormat.match( /MM/ ) ?
					"monthNames" : "monthNamesShort" ) ) ) );
				date.setDate( findMax( this._get( inst, ( dateFormat.match( /DD/ ) ?
					"dayNames" : "dayNamesShort" ) ) ) + 20 - date.getDay() );
			}
			inst.input.attr( "size", this._formatDate( inst, date ).length );
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function( target, inst ) {
		var divSpan = $( target );
		if ( divSpan.hasClass( this.markerClassName ) ) {
			return;
		}
		divSpan.addClass( this.markerClassName ).append( inst.dpDiv );
		$.data( target, "datepicker", inst );
		this._setDate( inst, this._getDefaultDate( inst ), true );
		this._updateDatepicker( inst );
		this._updateAlternate( inst );

		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}

		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
		// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
		inst.dpDiv.css( "display", "block" );
	},

	/* Pop-up the date picker in a "dialog" box.
	 * @param  input element - ignored
	 * @param  date	string or Date - the initial date to display
	 * @param  onSelect  function - the function to call when a date is selected
	 * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	 * @param  pos int[2] - coordinates for the dialog's position within the screen or
	 *					event - with x/y coordinates or
	 *					leave empty for default (screen centre)
	 * @return the manager object
	 */
	_dialogDatepicker: function( input, date, onSelect, settings, pos ) {
		var id, browserWidth, browserHeight, scrollX, scrollY,
			inst = this._dialogInst; // internal instance

		if ( !inst ) {
			this.uuid += 1;
			id = "dp" + this.uuid;
			this._dialogInput = $( "<input type='text' id='" + id +
				"' style='position: absolute; top: -100px; width: 0px;'/>" );
			this._dialogInput.on( "keydown", this._doKeyDown );
			$( "body" ).append( this._dialogInput );
			inst = this._dialogInst = this._newInst( this._dialogInput, false );
			inst.settings = {};
			$.data( this._dialogInput[ 0 ], "datepicker", inst );
		}
		datepicker_extendRemove( inst.settings, settings || {} );
		date = ( date && date.constructor === Date ? this._formatDate( inst, date ) : date );
		this._dialogInput.val( date );

		this._pos = ( pos ? ( pos.length ? pos : [ pos.pageX, pos.pageY ] ) : null );
		if ( !this._pos ) {
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[ ( browserWidth / 2 ) - 100 + scrollX, ( browserHeight / 2 ) - 150 + scrollY ];
		}

		// Move input on screen for focus, but hidden behind dialog
		this._dialogInput.css( "left", ( this._pos[ 0 ] + 20 ) + "px" ).css( "top", this._pos[ 1 ] + "px" );
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass( this._dialogClass );
		this._showDatepicker( this._dialogInput[ 0 ] );
		if ( $.blockUI ) {
			$.blockUI( this.dpDiv );
		}
		$.data( this._dialogInput[ 0 ], "datepicker", inst );
		return this;
	},

	/* Detach a datepicker from its control.
	 * @param  target	element - the target input field or division or span
	 */
	_destroyDatepicker: function( target ) {
		var nodeName,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData( target, "datepicker" );
		if ( nodeName === "input" ) {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass( this.markerClassName ).
				off( "focus", this._showDatepicker ).
				off( "keydown", this._doKeyDown ).
				off( "keypress", this._doKeyPress ).
				off( "keyup", this._doKeyUp );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			$target.removeClass( this.markerClassName ).empty();
		}

		if ( datepicker_instActive === inst ) {
			datepicker_instActive = null;
		}
	},

	/* Enable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_enableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = false;
			inst.trigger.filter( "button" ).
				each( function() { this.disabled = false; } ).end().
				filter( "img" ).css( { opacity: "1.0", cursor: "" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().removeClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", false );
		}
		this._disabledInputs = $.map( this._disabledInputs,
			function( value ) { return ( value === target ? null : value ); } ); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_disableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = true;
			inst.trigger.filter( "button" ).
				each( function() { this.disabled = true; } ).end().
				filter( "img" ).css( { opacity: "0.5", cursor: "default" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().addClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", true );
		}
		this._disabledInputs = $.map( this._disabledInputs,
			function( value ) { return ( value === target ? null : value ); } ); // delete entry
		this._disabledInputs[ this._disabledInputs.length ] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	 * @param  target	element - the target input field or division or span
	 * @return boolean - true if disabled, false if enabled
	 */
	_isDisabledDatepicker: function( target ) {
		if ( !target ) {
			return false;
		}
		for ( var i = 0; i < this._disabledInputs.length; i++ ) {
			if ( this._disabledInputs[ i ] === target ) {
				return true;
			}
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	 * @param  target  element - the target input field or division or span
	 * @return  object - the associated instance data
	 * @throws  error if a jQuery problem getting data
	 */
	_getInst: function( target ) {
		try {
			return $.data( target, "datepicker" );
		}
		catch ( err ) {
			throw "Missing instance data for this datepicker";
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 * @param  name	object - the new settings to update or
	 *				string - the name of the setting to change or retrieve,
	 *				when retrieving also "all" for all instance settings or
	 *				"defaults" for all global defaults
	 * @param  value   any - the new value for the setting
	 *				(omit if above is an object or to retrieve a value)
	 */
	_optionDatepicker: function( target, name, value ) {
		var settings, date, minDate, maxDate,
			inst = this._getInst( target );

		if ( arguments.length === 2 && typeof name === "string" ) {
			return ( name === "defaults" ? $.extend( {}, $.datepicker._defaults ) :
				( inst ? ( name === "all" ? $.extend( {}, inst.settings ) :
				this._get( inst, name ) ) : null ) );
		}

		settings = name || {};
		if ( typeof name === "string" ) {
			settings = {};
			settings[ name ] = value;
		}

		if ( inst ) {
			if ( this._curInst === inst ) {
				this._hideDatepicker();
			}

			date = this._getDateDatepicker( target, true );
			minDate = this._getMinMaxDate( inst, "min" );
			maxDate = this._getMinMaxDate( inst, "max" );
			datepicker_extendRemove( inst.settings, settings );

			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if ( minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined ) {
				inst.settings.minDate = this._formatDate( inst, minDate );
			}
			if ( maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined ) {
				inst.settings.maxDate = this._formatDate( inst, maxDate );
			}
			if ( "disabled" in settings ) {
				if ( settings.disabled ) {
					this._disableDatepicker( target );
				} else {
					this._enableDatepicker( target );
				}
			}
			this._attachments( $( target ), inst );
			this._autoSize( inst );
			this._setDate( inst, date );
			this._updateAlternate( inst );
			this._updateDatepicker( inst );
		}
	},

	// Change method deprecated
	_changeDatepicker: function( target, name, value ) {
		this._optionDatepicker( target, name, value );
	},

	/* Redraw the date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 */
	_refreshDatepicker: function( target ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._updateDatepicker( inst );
		}
	},

	/* Set the dates for a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  date	Date - the new date
	 */
	_setDateDatepicker: function( target, date ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._setDate( inst, date );
			this._updateDatepicker( inst );
			this._updateAlternate( inst );
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  noDefault boolean - true if no default date is to be used
	 * @return Date - the current date
	 */
	_getDateDatepicker: function( target, noDefault ) {
		var inst = this._getInst( target );
		if ( inst && !inst.inline ) {
			this._setDateFromField( inst, noDefault );
		}
		return ( inst ? this._getDate( inst ) : null );
	},

	/* Handle keystrokes. */
	_doKeyDown: function( event ) {
		var onSelect, dateStr, sel,
			inst = $.datepicker._getInst( event.target ),
			handled = true,
			isRTL = inst.dpDiv.is( ".ui-datepicker-rtl" );

		inst._keyEvent = true;
		if ( $.datepicker._datepickerShowing ) {
			switch ( event.keyCode ) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: sel = $( "td." + $.datepicker._dayOverClass + ":not(." +
									$.datepicker._currentClass + ")", inst.dpDiv );
						if ( sel[ 0 ] ) {
							$.datepicker._selectDay( event.target, inst.selectedMonth, inst.selectedYear, sel[ 0 ] );
						}

						onSelect = $.datepicker._get( inst, "onSelect" );
						if ( onSelect ) {
							dateStr = $.datepicker._formatDate( inst );

							// Trigger custom callback
							onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );
						} else {
							$.datepicker._hideDatepicker();
						}

						return false; // don't submit the form
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							-$.datepicker._get( inst, "stepBigMonths" ) :
							-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							+$.datepicker._get( inst, "stepBigMonths" ) :
							+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // next month/year on page down/+ ctrl
				case 35: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._clearDate( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._gotoToday( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? +1 : -1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// -1 day on ctrl or command +left
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								-$.datepicker._get( inst, "stepBigMonths" ) :
								-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +left on Mac
						break;
				case 38: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, -7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? -1 : +1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// +1 day on ctrl or command +right
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								+$.datepicker._get( inst, "stepBigMonths" ) :
								+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +right
						break;
				case 40: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, +7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		} else if ( event.keyCode === 36 && event.ctrlKey ) { // display the date picker on ctrl+home
			$.datepicker._showDatepicker( this );
		} else {
			handled = false;
		}

		if ( handled ) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function( event ) {
		var chars, chr,
			inst = $.datepicker._getInst( event.target );

		if ( $.datepicker._get( inst, "constrainInput" ) ) {
			chars = $.datepicker._possibleChars( $.datepicker._get( inst, "dateFormat" ) );
			chr = String.fromCharCode( event.charCode == null ? event.keyCode : event.charCode );
			return event.ctrlKey || event.metaKey || ( chr < " " || !chars || chars.indexOf( chr ) > -1 );
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function( event ) {
		var date,
			inst = $.datepicker._getInst( event.target );

		if ( inst.input.val() !== inst.lastVal ) {
			try {
				date = $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
					( inst.input ? inst.input.val() : null ),
					$.datepicker._getFormatConfig( inst ) );

				if ( date ) { // only if valid
					$.datepicker._setDateFromField( inst );
					$.datepicker._updateAlternate( inst );
					$.datepicker._updateDatepicker( inst );
				}
			}
			catch ( err ) {
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	 * If false returned from beforeShow event handler do not show.
	 * @param  input  element - the input field attached to the date picker or
	 *					event - if triggered by focus
	 */
	_showDatepicker: function( input ) {
		input = input.target || input;
		if ( input.nodeName.toLowerCase() !== "input" ) { // find from button/image trigger
			input = $( "input", input.parentNode )[ 0 ];
		}

		if ( $.datepicker._isDisabledDatepicker( input ) || $.datepicker._lastInput === input ) { // already here
			return;
		}

		var inst, beforeShow, beforeShowSettings, isFixed,
			offset, showAnim, duration;

		inst = $.datepicker._getInst( input );
		if ( $.datepicker._curInst && $.datepicker._curInst !== inst ) {
			$.datepicker._curInst.dpDiv.stop( true, true );
			if ( inst && $.datepicker._datepickerShowing ) {
				$.datepicker._hideDatepicker( $.datepicker._curInst.input[ 0 ] );
			}
		}

		beforeShow = $.datepicker._get( inst, "beforeShow" );
		beforeShowSettings = beforeShow ? beforeShow.apply( input, [ input, inst ] ) : {};
		if ( beforeShowSettings === false ) {
			return;
		}
		datepicker_extendRemove( inst.settings, beforeShowSettings );

		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField( inst );

		if ( $.datepicker._inDialog ) { // hide cursor
			input.value = "";
		}
		if ( !$.datepicker._pos ) { // position below input
			$.datepicker._pos = $.datepicker._findPos( input );
			$.datepicker._pos[ 1 ] += input.offsetHeight; // add the height
		}

		isFixed = false;
		$( input ).parents().each( function() {
			isFixed |= $( this ).css( "position" ) === "fixed";
			return !isFixed;
		} );

		offset = { left: $.datepicker._pos[ 0 ], top: $.datepicker._pos[ 1 ] };
		$.datepicker._pos = null;

		//to avoid flashes on Firefox
		inst.dpDiv.empty();

		// determine sizing offscreen
		inst.dpDiv.css( { position: "absolute", display: "block", top: "-1000px" } );
		$.datepicker._updateDatepicker( inst );

		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset( inst, offset, isFixed );
		inst.dpDiv.css( { position: ( $.datepicker._inDialog && $.blockUI ?
			"static" : ( isFixed ? "fixed" : "absolute" ) ), display: "none",
			left: offset.left + "px", top: offset.top + "px" } );

		if ( !inst.inline ) {
			showAnim = $.datepicker._get( inst, "showAnim" );
			duration = $.datepicker._get( inst, "duration" );
			inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
			$.datepicker._datepickerShowing = true;

			if ( $.effects && $.effects.effect[ showAnim ] ) {
				inst.dpDiv.show( showAnim, $.datepicker._get( inst, "showOptions" ), duration );
			} else {
				inst.dpDiv[ showAnim || "show" ]( showAnim ? duration : null );
			}

			if ( $.datepicker._shouldFocusInput( inst ) ) {
				inst.input.trigger( "focus" );
			}

			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function( inst ) {
		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
		datepicker_instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append( this._generateHTML( inst ) );
		this._attachHandlers( inst );

		var origyearshtml,
			numMonths = this._getNumberOfMonths( inst ),
			cols = numMonths[ 1 ],
			width = 17,
			activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );

		if ( activeCell.length > 0 ) {
			datepicker_handleMouseover.apply( activeCell.get( 0 ) );
		}

		inst.dpDiv.removeClass( "ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4" ).width( "" );
		if ( cols > 1 ) {
			inst.dpDiv.addClass( "ui-datepicker-multi-" + cols ).css( "width", ( width * cols ) + "em" );
		}
		inst.dpDiv[ ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-multi" );
		inst.dpDiv[ ( this._get( inst, "isRTL" ) ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-rtl" );

		if ( inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
			inst.input.trigger( "focus" );
		}

		// Deffered render of the years select (to avoid flashes on Firefox)
		if ( inst.yearshtml ) {
			origyearshtml = inst.yearshtml;
			setTimeout( function() {

				//assure that inst.yearshtml didn't change.
				if ( origyearshtml === inst.yearshtml && inst.yearshtml ) {
					inst.dpDiv.find( "select.ui-datepicker-year:first" ).replaceWith( inst.yearshtml );
				}
				origyearshtml = inst.yearshtml = null;
			}, 0 );
		}
	},

	// #6694 - don't focus the input if it's already focused
	// this breaks the change event in IE
	// Support: IE and jQuery <1.9
	_shouldFocusInput: function( inst ) {
		return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function( inst, offset, isFixed ) {
		var dpWidth = inst.dpDiv.outerWidth(),
			dpHeight = inst.dpDiv.outerHeight(),
			inputWidth = inst.input ? inst.input.outerWidth() : 0,
			inputHeight = inst.input ? inst.input.outerHeight() : 0,
			viewWidth = document.documentElement.clientWidth + ( isFixed ? 0 : $( document ).scrollLeft() ),
			viewHeight = document.documentElement.clientHeight + ( isFixed ? 0 : $( document ).scrollTop() );

		offset.left -= ( this._get( inst, "isRTL" ) ? ( dpWidth - inputWidth ) : 0 );
		offset.left -= ( isFixed && offset.left === inst.input.offset().left ) ? $( document ).scrollLeft() : 0;
		offset.top -= ( isFixed && offset.top === ( inst.input.offset().top + inputHeight ) ) ? $( document ).scrollTop() : 0;

		// Now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= Math.min( offset.left, ( offset.left + dpWidth > viewWidth && viewWidth > dpWidth ) ?
			Math.abs( offset.left + dpWidth - viewWidth ) : 0 );
		offset.top -= Math.min( offset.top, ( offset.top + dpHeight > viewHeight && viewHeight > dpHeight ) ?
			Math.abs( dpHeight + inputHeight ) : 0 );

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function( obj ) {
		var position,
			inst = this._getInst( obj ),
			isRTL = this._get( inst, "isRTL" );

		while ( obj && ( obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden( obj ) ) ) {
			obj = obj[ isRTL ? "previousSibling" : "nextSibling" ];
		}

		position = $( obj ).offset();
		return [ position.left, position.top ];
	},

	/* Hide the date picker from view.
	 * @param  input  element - the input field attached to the date picker
	 */
	_hideDatepicker: function( input ) {
		var showAnim, duration, postProcess, onClose,
			inst = this._curInst;

		if ( !inst || ( input && inst !== $.data( input, "datepicker" ) ) ) {
			return;
		}

		if ( this._datepickerShowing ) {
			showAnim = this._get( inst, "showAnim" );
			duration = this._get( inst, "duration" );
			postProcess = function() {
				$.datepicker._tidyDialog( inst );
			};

			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
				inst.dpDiv.hide( showAnim, $.datepicker._get( inst, "showOptions" ), duration, postProcess );
			} else {
				inst.dpDiv[ ( showAnim === "slideDown" ? "slideUp" :
					( showAnim === "fadeIn" ? "fadeOut" : "hide" ) ) ]( ( showAnim ? duration : null ), postProcess );
			}

			if ( !showAnim ) {
				postProcess();
			}
			this._datepickerShowing = false;

			onClose = this._get( inst, "onClose" );
			if ( onClose ) {
				onClose.apply( ( inst.input ? inst.input[ 0 ] : null ), [ ( inst.input ? inst.input.val() : "" ), inst ] );
			}

			this._lastInput = null;
			if ( this._inDialog ) {
				this._dialogInput.css( { position: "absolute", left: "0", top: "-100px" } );
				if ( $.blockUI ) {
					$.unblockUI();
					$( "body" ).append( this.dpDiv );
				}
			}
			this._inDialog = false;
		}
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function( inst ) {
		inst.dpDiv.removeClass( this._dialogClass ).off( ".ui-datepicker-calendar" );
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function( event ) {
		if ( !$.datepicker._curInst ) {
			return;
		}

		var $target = $( event.target ),
			inst = $.datepicker._getInst( $target[ 0 ] );

		if ( ( ( $target[ 0 ].id !== $.datepicker._mainDivId &&
				$target.parents( "#" + $.datepicker._mainDivId ).length === 0 &&
				!$target.hasClass( $.datepicker.markerClassName ) &&
				!$target.closest( "." + $.datepicker._triggerClass ).length &&
				$.datepicker._datepickerShowing && !( $.datepicker._inDialog && $.blockUI ) ) ) ||
			( $target.hasClass( $.datepicker.markerClassName ) && $.datepicker._curInst !== inst ) ) {
				$.datepicker._hideDatepicker();
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function( id, offset, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}
		this._adjustInstDate( inst, offset +
			( period === "M" ? this._get( inst, "showCurrentAtPos" ) : 0 ), // undo positioning
			period );
		this._updateDatepicker( inst );
	},

	/* Action for current link. */
	_gotoToday: function( id ) {
		var date,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._get( inst, "gotoCurrent" ) && inst.currentDay ) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function( id, select, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		inst[ "selected" + ( period === "M" ? "Month" : "Year" ) ] =
		inst[ "draw" + ( period === "M" ? "Month" : "Year" ) ] =
			parseInt( select.options[ select.selectedIndex ].value, 10 );

		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a day. */
	_selectDay: function( id, month, year, td ) {
		var inst,
			target = $( id );

		if ( $( td ).hasClass( this._unselectableClass ) || this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}

		inst = this._getInst( target[ 0 ] );
		inst.selectedDay = inst.currentDay = $( "a", td ).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate( id, this._formatDate( inst,
			inst.currentDay, inst.currentMonth, inst.currentYear ) );
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function( id ) {
		var target = $( id );
		this._selectDate( target, "" );
	},

	/* Update the input field with the selected date. */
	_selectDate: function( id, dateStr ) {
		var onSelect,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		dateStr = ( dateStr != null ? dateStr : this._formatDate( inst ) );
		if ( inst.input ) {
			inst.input.val( dateStr );
		}
		this._updateAlternate( inst );

		onSelect = this._get( inst, "onSelect" );
		if ( onSelect ) {
			onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );  // trigger custom callback
		} else if ( inst.input ) {
			inst.input.trigger( "change" ); // fire the change event
		}

		if ( inst.inline ) {
			this._updateDatepicker( inst );
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[ 0 ];
			if ( typeof( inst.input[ 0 ] ) !== "object" ) {
				inst.input.trigger( "focus" ); // restore focus
			}
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function( inst ) {
		var altFormat, date, dateStr,
			altField = this._get( inst, "altField" );

		if ( altField ) { // update alternate field too
			altFormat = this._get( inst, "altFormat" ) || this._get( inst, "dateFormat" );
			date = this._getDate( inst );
			dateStr = this.formatDate( altFormat, date, this._getFormatConfig( inst ) );
			$( altField ).val( dateStr );
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	 * @param  date  Date - the date to customise
	 * @return [boolean, string] - is this date selectable?, what is its CSS class?
	 */
	noWeekends: function( date ) {
		var day = date.getDay();
		return [ ( day > 0 && day < 6 ), "" ];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	 * @param  date  Date - the date to get the week for
	 * @return  number - the number of the week within the year that contains this date
	 */
	iso8601Week: function( date ) {
		var time,
			checkDate = new Date( date.getTime() );

		// Find Thursday of this week starting on Monday
		checkDate.setDate( checkDate.getDate() + 4 - ( checkDate.getDay() || 7 ) );

		time = checkDate.getTime();
		checkDate.setMonth( 0 ); // Compare with Jan 1
		checkDate.setDate( 1 );
		return Math.floor( Math.round( ( time - checkDate ) / 86400000 ) / 7 ) + 1;
	},

	/* Parse a string value into a date object.
	 * See formatDate below for the possible formats.
	 *
	 * @param  format string - the expected format of the date
	 * @param  value string - the date in the above format
	 * @param  settings Object - attributes include:
	 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  Date - the extracted date value or null if value is blank
	 */
	parseDate: function( format, value, settings ) {
		if ( format == null || value == null ) {
			throw "Invalid arguments";
		}

		value = ( typeof value === "object" ? value.toString() : value + "" );
		if ( value === "" ) {
			return null;
		}

		var iFormat, dim, extra,
			iValue = 0,
			shortYearCutoffTemp = ( settings ? settings.shortYearCutoff : null ) || this._defaults.shortYearCutoff,
			shortYearCutoff = ( typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
				new Date().getFullYear() % 100 + parseInt( shortYearCutoffTemp, 10 ) ),
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,
			year = -1,
			month = -1,
			day = -1,
			doy = -1,
			literal = false,
			date,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Extract a number from the string value
			getNumber = function( match ) {
				var isDoubled = lookAhead( match ),
					size = ( match === "@" ? 14 : ( match === "!" ? 20 :
					( match === "y" && isDoubled ? 4 : ( match === "o" ? 3 : 2 ) ) ) ),
					minSize = ( match === "y" ? size : 1 ),
					digits = new RegExp( "^\\d{" + minSize + "," + size + "}" ),
					num = value.substring( iValue ).match( digits );
				if ( !num ) {
					throw "Missing number at position " + iValue;
				}
				iValue += num[ 0 ].length;
				return parseInt( num[ 0 ], 10 );
			},

			// Extract a name from the string value and convert to an index
			getName = function( match, shortNames, longNames ) {
				var index = -1,
					names = $.map( lookAhead( match ) ? longNames : shortNames, function( v, k ) {
						return [ [ k, v ] ];
					} ).sort( function( a, b ) {
						return -( a[ 1 ].length - b[ 1 ].length );
					} );

				$.each( names, function( i, pair ) {
					var name = pair[ 1 ];
					if ( value.substr( iValue, name.length ).toLowerCase() === name.toLowerCase() ) {
						index = pair[ 0 ];
						iValue += name.length;
						return false;
					}
				} );
				if ( index !== -1 ) {
					return index + 1;
				} else {
					throw "Unknown name at position " + iValue;
				}
			},

			// Confirm that a literal character matches the string value
			checkLiteral = function() {
				if ( value.charAt( iValue ) !== format.charAt( iFormat ) ) {
					throw "Unexpected literal at position " + iValue;
				}
				iValue++;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					checkLiteral();
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d":
						day = getNumber( "d" );
						break;
					case "D":
						getName( "D", dayNamesShort, dayNames );
						break;
					case "o":
						doy = getNumber( "o" );
						break;
					case "m":
						month = getNumber( "m" );
						break;
					case "M":
						month = getName( "M", monthNamesShort, monthNames );
						break;
					case "y":
						year = getNumber( "y" );
						break;
					case "@":
						date = new Date( getNumber( "@" ) );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "!":
						date = new Date( ( getNumber( "!" ) - this._ticksTo1970 ) / 10000 );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if ( lookAhead( "'" ) ) {
							checkLiteral();
						} else {
							literal = true;
						}
						break;
					default:
						checkLiteral();
				}
			}
		}

		if ( iValue < value.length ) {
			extra = value.substr( iValue );
			if ( !/^\s+/.test( extra ) ) {
				throw "Extra/unparsed characters found in date: " + extra;
			}
		}

		if ( year === -1 ) {
			year = new Date().getFullYear();
		} else if ( year < 100 ) {
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				( year <= shortYearCutoff ? 0 : -100 );
		}

		if ( doy > -1 ) {
			month = 1;
			day = doy;
			do {
				dim = this._getDaysInMonth( year, month - 1 );
				if ( day <= dim ) {
					break;
				}
				month++;
				day -= dim;
			} while ( true );
		}

		date = this._daylightSavingAdjust( new Date( year, month - 1, day ) );
		if ( date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day ) {
			throw "Invalid date"; // E.g. 31/02/00
		}
		return date;
	},

	/* Standard date formats. */
	ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
	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", // RFC 822
	TICKS: "!",
	TIMESTAMP: "@",
	W3C: "yy-mm-dd", // ISO 8601

	_ticksTo1970: ( ( ( 1970 - 1 ) * 365 + Math.floor( 1970 / 4 ) - Math.floor( 1970 / 100 ) +
		Math.floor( 1970 / 400 ) ) * 24 * 60 * 60 * 10000000 ),

	/* Format a date object into a string value.
	 * The format can be combinations of the following:
	 * d  - day of month (no leading zero)
	 * dd - day of month (two digit)
	 * o  - day of year (no leading zeros)
	 * oo - day of year (three digit)
	 * D  - day name short
	 * DD - day name long
	 * m  - month of year (no leading zero)
	 * mm - month of year (two digit)
	 * M  - month name short
	 * MM - month name long
	 * y  - year (two digit)
	 * yy - year (four digit)
	 * @ - Unix timestamp (ms since 01/01/1970)
	 * ! - Windows ticks (100ns since 01/01/0001)
	 * "..." - literal text
	 * '' - single quote
	 *
	 * @param  format string - the desired format of the date
	 * @param  date Date - the date value to format
	 * @param  settings Object - attributes include:
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  string - the date in the above format
	 */
	formatDate: function( format, date, settings ) {
		if ( !date ) {
			return "";
		}

		var iFormat,
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Format a number, with leading zero if necessary
			formatNumber = function( match, value, len ) {
				var num = "" + value;
				if ( lookAhead( match ) ) {
					while ( num.length < len ) {
						num = "0" + num;
					}
				}
				return num;
			},

			// Format a name, short or long as requested
			formatName = function( match, value, shortNames, longNames ) {
				return ( lookAhead( match ) ? longNames[ value ] : shortNames[ value ] );
			},
			output = "",
			literal = false;

		if ( date ) {
			for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
				if ( literal ) {
					if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
						literal = false;
					} else {
						output += format.charAt( iFormat );
					}
				} else {
					switch ( format.charAt( iFormat ) ) {
						case "d":
							output += formatNumber( "d", date.getDate(), 2 );
							break;
						case "D":
							output += formatName( "D", date.getDay(), dayNamesShort, dayNames );
							break;
						case "o":
							output += formatNumber( "o",
								Math.round( ( new Date( date.getFullYear(), date.getMonth(), date.getDate() ).getTime() - new Date( date.getFullYear(), 0, 0 ).getTime() ) / 86400000 ), 3 );
							break;
						case "m":
							output += formatNumber( "m", date.getMonth() + 1, 2 );
							break;
						case "M":
							output += formatName( "M", date.getMonth(), monthNamesShort, monthNames );
							break;
						case "y":
							output += ( lookAhead( "y" ) ? date.getFullYear() :
								( date.getFullYear() % 100 < 10 ? "0" : "" ) + date.getFullYear() % 100 );
							break;
						case "@":
							output += date.getTime();
							break;
						case "!":
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if ( lookAhead( "'" ) ) {
								output += "'";
							} else {
								literal = true;
							}
							break;
						default:
							output += format.charAt( iFormat );
					}
				}
			}
		}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function( format ) {
		var iFormat,
			chars = "",
			literal = false,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					chars += format.charAt( iFormat );
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d": case "m": case "y": case "@":
						chars += "0123456789";
						break;
					case "D": case "M":
						return null; // Accept anything
					case "'":
						if ( lookAhead( "'" ) ) {
							chars += "'";
						} else {
							literal = true;
						}
						break;
					default:
						chars += format.charAt( iFormat );
				}
			}
		}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function( inst, name ) {
		return inst.settings[ name ] !== undefined ?
			inst.settings[ name ] : this._defaults[ name ];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function( inst, noDefault ) {
		if ( inst.input.val() === inst.lastVal ) {
			return;
		}

		var dateFormat = this._get( inst, "dateFormat" ),
			dates = inst.lastVal = inst.input ? inst.input.val() : null,
			defaultDate = this._getDefaultDate( inst ),
			date = defaultDate,
			settings = this._getFormatConfig( inst );

		try {
			date = this.parseDate( dateFormat, dates, settings ) || defaultDate;
		} catch ( event ) {
			dates = ( noDefault ? "" : dates );
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = ( dates ? date.getDate() : 0 );
		inst.currentMonth = ( dates ? date.getMonth() : 0 );
		inst.currentYear = ( dates ? date.getFullYear() : 0 );
		this._adjustInstDate( inst );
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function( inst ) {
		return this._restrictMinMax( inst,
			this._determineDate( inst, this._get( inst, "defaultDate" ), new Date() ) );
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function( inst, date, defaultDate ) {
		var offsetNumeric = function( offset ) {
				var date = new Date();
				date.setDate( date.getDate() + offset );
				return date;
			},
			offsetString = function( offset ) {
				try {
					return $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
						offset, $.datepicker._getFormatConfig( inst ) );
				}
				catch ( e ) {

					// Ignore
				}

				var date = ( offset.toLowerCase().match( /^c/ ) ?
					$.datepicker._getDate( inst ) : null ) || new Date(),
					year = date.getFullYear(),
					month = date.getMonth(),
					day = date.getDate(),
					pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
					matches = pattern.exec( offset );

				while ( matches ) {
					switch ( matches[ 2 ] || "d" ) {
						case "d" : case "D" :
							day += parseInt( matches[ 1 ], 10 ); break;
						case "w" : case "W" :
							day += parseInt( matches[ 1 ], 10 ) * 7; break;
						case "m" : case "M" :
							month += parseInt( matches[ 1 ], 10 );
							day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
							break;
						case "y": case "Y" :
							year += parseInt( matches[ 1 ], 10 );
							day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
							break;
					}
					matches = pattern.exec( offset );
				}
				return new Date( year, month, day );
			},
			newDate = ( date == null || date === "" ? defaultDate : ( typeof date === "string" ? offsetString( date ) :
				( typeof date === "number" ? ( isNaN( date ) ? defaultDate : offsetNumeric( date ) ) : new Date( date.getTime() ) ) ) );

		newDate = ( newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate );
		if ( newDate ) {
			newDate.setHours( 0 );
			newDate.setMinutes( 0 );
			newDate.setSeconds( 0 );
			newDate.setMilliseconds( 0 );
		}
		return this._daylightSavingAdjust( newDate );
	},

	/* Handle switch to/from daylight saving.
	 * Hours may be non-zero on daylight saving cut-over:
	 * > 12 when midnight changeover, but then cannot generate
	 * midnight datetime, so jump to 1AM, otherwise reset.
	 * @param  date  (Date) the date to check
	 * @return  (Date) the corrected date
	 */
	_daylightSavingAdjust: function( date ) {
		if ( !date ) {
			return null;
		}
		date.setHours( date.getHours() > 12 ? date.getHours() + 2 : 0 );
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function( inst, date, noChange ) {
		var clear = !date,
			origMonth = inst.selectedMonth,
			origYear = inst.selectedYear,
			newDate = this._restrictMinMax( inst, this._determineDate( inst, date, new Date() ) );

		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ( ( origMonth !== inst.selectedMonth || origYear !== inst.selectedYear ) && !noChange ) {
			this._notifyChange( inst );
		}
		this._adjustInstDate( inst );
		if ( inst.input ) {
			inst.input.val( clear ? "" : this._formatDate( inst ) );
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function( inst ) {
		var startDate = ( !inst.currentYear || ( inst.input && inst.input.val() === "" ) ? null :
			this._daylightSavingAdjust( new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
			return startDate;
	},

	/* Attach the onxxx handlers.  These are declared statically so
	 * they work with static code transformers like Caja.
	 */
	_attachHandlers: function( inst ) {
		var stepMonths = this._get( inst, "stepMonths" ),
			id = "#" + inst.id.replace( /\\\\/g, "\\" );
		inst.dpDiv.find( "[data-handler]" ).map( function() {
			var handler = {
				prev: function() {
					$.datepicker._adjustDate( id, -stepMonths, "M" );
				},
				next: function() {
					$.datepicker._adjustDate( id, +stepMonths, "M" );
				},
				hide: function() {
					$.datepicker._hideDatepicker();
				},
				today: function() {
					$.datepicker._gotoToday( id );
				},
				selectDay: function() {
					$.datepicker._selectDay( id, +this.getAttribute( "data-month" ), +this.getAttribute( "data-year" ), this );
					return false;
				},
				selectMonth: function() {
					$.datepicker._selectMonthYear( id, this, "M" );
					return false;
				},
				selectYear: function() {
					$.datepicker._selectMonthYear( id, this, "Y" );
					return false;
				}
			};
			$( this ).on( this.getAttribute( "data-event" ), handler[ this.getAttribute( "data-handler" ) ] );
		} );
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function( inst ) {
		var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
			controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
			monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
			selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
			cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
			printDate, dRow, tbody, daySettings, otherMonth, unselectable,
			tempDate = new Date(),
			today = this._daylightSavingAdjust(
				new Date( tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate() ) ), // clear time
			isRTL = this._get( inst, "isRTL" ),
			showButtonPanel = this._get( inst, "showButtonPanel" ),
			hideIfNoPrevNext = this._get( inst, "hideIfNoPrevNext" ),
			navigationAsDateFormat = this._get( inst, "navigationAsDateFormat" ),
			numMonths = this._getNumberOfMonths( inst ),
			showCurrentAtPos = this._get( inst, "showCurrentAtPos" ),
			stepMonths = this._get( inst, "stepMonths" ),
			isMultiMonth = ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ),
			currentDate = this._daylightSavingAdjust( ( !inst.currentDay ? new Date( 9999, 9, 9 ) :
				new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) ),
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			drawMonth = inst.drawMonth - showCurrentAtPos,
			drawYear = inst.drawYear;

		if ( drawMonth < 0 ) {
			drawMonth += 12;
			drawYear--;
		}
		if ( maxDate ) {
			maxDraw = this._daylightSavingAdjust( new Date( maxDate.getFullYear(),
				maxDate.getMonth() - ( numMonths[ 0 ] * numMonths[ 1 ] ) + 1, maxDate.getDate() ) );
			maxDraw = ( minDate && maxDraw < minDate ? minDate : maxDraw );
			while ( this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 ) ) > maxDraw ) {
				drawMonth--;
				if ( drawMonth < 0 ) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;

		prevText = this._get( inst, "prevText" );
		prevText = ( !navigationAsDateFormat ? prevText : this.formatDate( prevText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth - stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		prev = ( this._canAdjustMonth( inst, -1, drawYear, drawMonth ) ?
			"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
			" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w" ) + "'>" + prevText + "</span></a>" :
			( hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w" ) + "'>" + prevText + "</span></a>" ) );

		nextText = this._get( inst, "nextText" );
		nextText = ( !navigationAsDateFormat ? nextText : this.formatDate( nextText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth + stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		next = ( this._canAdjustMonth( inst, +1, drawYear, drawMonth ) ?
			"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
			" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e" ) + "'>" + nextText + "</span></a>" :
			( hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e" ) + "'>" + nextText + "</span></a>" ) );

		currentText = this._get( inst, "currentText" );
		gotoDate = ( this._get( inst, "gotoCurrent" ) && inst.currentDay ? currentDate : today );
		currentText = ( !navigationAsDateFormat ? currentText :
			this.formatDate( currentText, gotoDate, this._getFormatConfig( inst ) ) );

		controls = ( !inst.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( inst, "closeText" ) + "</button>" : "" );

		buttonPanel = ( showButtonPanel ) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + ( isRTL ? controls : "" ) +
			( this._isInRange( inst, gotoDate ) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
			">" + currentText + "</button>" : "" ) + ( isRTL ? "" : controls ) + "</div>" : "";

		firstDay = parseInt( this._get( inst, "firstDay" ), 10 );
		firstDay = ( isNaN( firstDay ) ? 0 : firstDay );

		showWeek = this._get( inst, "showWeek" );
		dayNames = this._get( inst, "dayNames" );
		dayNamesMin = this._get( inst, "dayNamesMin" );
		monthNames = this._get( inst, "monthNames" );
		monthNamesShort = this._get( inst, "monthNamesShort" );
		beforeShowDay = this._get( inst, "beforeShowDay" );
		showOtherMonths = this._get( inst, "showOtherMonths" );
		selectOtherMonths = this._get( inst, "selectOtherMonths" );
		defaultDate = this._getDefaultDate( inst );
		html = "";

		for ( row = 0; row < numMonths[ 0 ]; row++ ) {
			group = "";
			this.maxRows = 4;
			for ( col = 0; col < numMonths[ 1 ]; col++ ) {
				selectedDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, inst.selectedDay ) );
				cornerClass = " ui-corner-all";
				calender = "";
				if ( isMultiMonth ) {
					calender += "<div class='ui-datepicker-group";
					if ( numMonths[ 1 ] > 1 ) {
						switch ( col ) {
							case 0: calender += " ui-datepicker-group-first";
								cornerClass = " ui-corner-" + ( isRTL ? "right" : "left" ); break;
							case numMonths[ 1 ] - 1: calender += " ui-datepicker-group-last";
								cornerClass = " ui-corner-" + ( isRTL ? "left" : "right" ); break;
							default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
						}
					}
					calender += "'>";
				}
				calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
					( /all|left/.test( cornerClass ) && row === 0 ? ( isRTL ? next : prev ) : "" ) +
					( /all|right/.test( cornerClass ) && row === 0 ? ( isRTL ? prev : next ) : "" ) +
					this._generateMonthYearHeader( inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort ) + // draw month headers
					"</div><table class='ui-datepicker-calendar'><thead>" +
					"<tr>";
				thead = ( showWeek ? "<th class='ui-datepicker-week-col'>" + this._get( inst, "weekHeader" ) + "</th>" : "" );
				for ( dow = 0; dow < 7; dow++ ) { // days of the week
					day = ( dow + firstDay ) % 7;
					thead += "<th scope='col'" + ( ( dow + firstDay + 6 ) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "" ) + ">" +
						"<span title='" + dayNames[ day ] + "'>" + dayNamesMin[ day ] + "</span></th>";
				}
				calender += thead + "</tr></thead><tbody>";
				daysInMonth = this._getDaysInMonth( drawYear, drawMonth );
				if ( drawYear === inst.selectedYear && drawMonth === inst.selectedMonth ) {
					inst.selectedDay = Math.min( inst.selectedDay, daysInMonth );
				}
				leadDays = ( this._getFirstDayOfMonth( drawYear, drawMonth ) - firstDay + 7 ) % 7;
				curRows = Math.ceil( ( leadDays + daysInMonth ) / 7 ); // calculate the number of rows to generate
				numRows = ( isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows ); //If multiple months, use the higher number of rows (see #7043)
				this.maxRows = numRows;
				printDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 - leadDays ) );
				for ( dRow = 0; dRow < numRows; dRow++ ) { // create date picker rows
					calender += "<tr>";
					tbody = ( !showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
						this._get( inst, "calculateWeek" )( printDate ) + "</td>" );
					for ( dow = 0; dow < 7; dow++ ) { // create date picker days
						daySettings = ( beforeShowDay ?
							beforeShowDay.apply( ( inst.input ? inst.input[ 0 ] : null ), [ printDate ] ) : [ true, "" ] );
						otherMonth = ( printDate.getMonth() !== drawMonth );
						unselectable = ( otherMonth && !selectOtherMonths ) || !daySettings[ 0 ] ||
							( minDate && printDate < minDate ) || ( maxDate && printDate > maxDate );
						tbody += "<td class='" +
							( ( dow + firstDay + 6 ) % 7 >= 5 ? " ui-datepicker-week-end" : "" ) + // highlight weekends
							( otherMonth ? " ui-datepicker-other-month" : "" ) + // highlight days from other months
							( ( printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent ) || // user pressed key
							( defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime() ) ?

							// or defaultDate is current printedDate and defaultDate is selectedDate
							" " + this._dayOverClass : "" ) + // highlight selected day
							( unselectable ? " " + this._unselectableClass + " ui-state-disabled" : "" ) +  // highlight unselectable days
							( otherMonth && !showOtherMonths ? "" : " " + daySettings[ 1 ] + // highlight custom dates
							( printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "" ) + // highlight selected day
							( printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "" ) ) + "'" + // highlight today (if different)
							( ( !otherMonth || showOtherMonths ) && daySettings[ 2 ] ? " title='" + daySettings[ 2 ].replace( /'/g, "&#39;" ) + "'" : "" ) + // cell title
							( unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'" ) + ">" + // actions
							( otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
							( unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
							( printDate.getTime() === today.getTime() ? " ui-state-highlight" : "" ) +
							( printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "" ) + // highlight selected day
							( otherMonth ? " ui-priority-secondary" : "" ) + // distinguish dates from other months
							"' href='#'>" + printDate.getDate() + "</a>" ) ) + "</td>"; // display selectable date
						printDate.setDate( printDate.getDate() + 1 );
						printDate = this._daylightSavingAdjust( printDate );
					}
					calender += tbody + "</tr>";
				}
				drawMonth++;
				if ( drawMonth > 11 ) {
					drawMonth = 0;
					drawYear++;
				}
				calender += "</tbody></table>" + ( isMultiMonth ? "</div>" +
							( ( numMonths[ 0 ] > 0 && col === numMonths[ 1 ] - 1 ) ? "<div class='ui-datepicker-row-break'></div>" : "" ) : "" );
				group += calender;
			}
			html += group;
		}
		html += buttonPanel;
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function( inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort ) {

		var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
			changeMonth = this._get( inst, "changeMonth" ),
			changeYear = this._get( inst, "changeYear" ),
			showMonthAfterYear = this._get( inst, "showMonthAfterYear" ),
			html = "<div class='ui-datepicker-title'>",
			monthHtml = "";

		// Month selection
		if ( secondary || !changeMonth ) {
			monthHtml += "<span class='ui-datepicker-month'>" + monthNames[ drawMonth ] + "</span>";
		} else {
			inMinYear = ( minDate && minDate.getFullYear() === drawYear );
			inMaxYear = ( maxDate && maxDate.getFullYear() === drawYear );
			monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
			for ( month = 0; month < 12; month++ ) {
				if ( ( !inMinYear || month >= minDate.getMonth() ) && ( !inMaxYear || month <= maxDate.getMonth() ) ) {
					monthHtml += "<option value='" + month + "'" +
						( month === drawMonth ? " selected='selected'" : "" ) +
						">" + monthNamesShort[ month ] + "</option>";
				}
			}
			monthHtml += "</select>";
		}

		if ( !showMonthAfterYear ) {
			html += monthHtml + ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" );
		}

		// Year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = "";
			if ( secondary || !changeYear ) {
				html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
			} else {

				// determine range of years to display
				years = this._get( inst, "yearRange" ).split( ":" );
				thisYear = new Date().getFullYear();
				determineYear = function( value ) {
					var year = ( value.match( /c[+\-].*/ ) ? drawYear + parseInt( value.substring( 1 ), 10 ) :
						( value.match( /[+\-].*/ ) ? thisYear + parseInt( value, 10 ) :
						parseInt( value, 10 ) ) );
					return ( isNaN( year ) ? thisYear : year );
				};
				year = determineYear( years[ 0 ] );
				endYear = Math.max( year, determineYear( years[ 1 ] || "" ) );
				year = ( minDate ? Math.max( year, minDate.getFullYear() ) : year );
				endYear = ( maxDate ? Math.min( endYear, maxDate.getFullYear() ) : endYear );
				inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
				for ( ; year <= endYear; year++ ) {
					inst.yearshtml += "<option value='" + year + "'" +
						( year === drawYear ? " selected='selected'" : "" ) +
						">" + year + "</option>";
				}
				inst.yearshtml += "</select>";

				html += inst.yearshtml;
				inst.yearshtml = null;
			}
		}

		html += this._get( inst, "yearSuffix" );
		if ( showMonthAfterYear ) {
			html += ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" ) + monthHtml;
		}
		html += "</div>"; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function( inst, offset, period ) {
		var year = inst.selectedYear + ( period === "Y" ? offset : 0 ),
			month = inst.selectedMonth + ( period === "M" ? offset : 0 ),
			day = Math.min( inst.selectedDay, this._getDaysInMonth( year, month ) ) + ( period === "D" ? offset : 0 ),
			date = this._restrictMinMax( inst, this._daylightSavingAdjust( new Date( year, month, day ) ) );

		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if ( period === "M" || period === "Y" ) {
			this._notifyChange( inst );
		}
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function( inst, date ) {
		var minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			newDate = ( minDate && date < minDate ? minDate : date );
		return ( maxDate && newDate > maxDate ? maxDate : newDate );
	},

	/* Notify change of month/year. */
	_notifyChange: function( inst ) {
		var onChange = this._get( inst, "onChangeMonthYear" );
		if ( onChange ) {
			onChange.apply( ( inst.input ? inst.input[ 0 ] : null ),
				[ inst.selectedYear, inst.selectedMonth + 1, inst ] );
		}
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function( inst ) {
		var numMonths = this._get( inst, "numberOfMonths" );
		return ( numMonths == null ? [ 1, 1 ] : ( typeof numMonths === "number" ? [ 1, numMonths ] : numMonths ) );
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function( inst, minMax ) {
		return this._determineDate( inst, this._get( inst, minMax + "Date" ), null );
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function( year, month ) {
		return 32 - this._daylightSavingAdjust( new Date( year, month, 32 ) ).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function( year, month ) {
		return new Date( year, month, 1 ).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function( inst, offset, curYear, curMonth ) {
		var numMonths = this._getNumberOfMonths( inst ),
			date = this._daylightSavingAdjust( new Date( curYear,
			curMonth + ( offset < 0 ? offset : numMonths[ 0 ] * numMonths[ 1 ] ), 1 ) );

		if ( offset < 0 ) {
			date.setDate( this._getDaysInMonth( date.getFullYear(), date.getMonth() ) );
		}
		return this._isInRange( inst, date );
	},

	/* Is the given date in the accepted range? */
	_isInRange: function( inst, date ) {
		var yearSplit, currentYear,
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			minYear = null,
			maxYear = null,
			years = this._get( inst, "yearRange" );
			if ( years ) {
				yearSplit = years.split( ":" );
				currentYear = new Date().getFullYear();
				minYear = parseInt( yearSplit[ 0 ], 10 );
				maxYear = parseInt( yearSplit[ 1 ], 10 );
				if ( yearSplit[ 0 ].match( /[+\-].*/ ) ) {
					minYear += currentYear;
				}
				if ( yearSplit[ 1 ].match( /[+\-].*/ ) ) {
					maxYear += currentYear;
				}
			}

		return ( ( !minDate || date.getTime() >= minDate.getTime() ) &&
			( !maxDate || date.getTime() <= maxDate.getTime() ) &&
			( !minYear || date.getFullYear() >= minYear ) &&
			( !maxYear || date.getFullYear() <= maxYear ) );
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function( inst ) {
		var shortYearCutoff = this._get( inst, "shortYearCutoff" );
		shortYearCutoff = ( typeof shortYearCutoff !== "string" ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt( shortYearCutoff, 10 ) );
		return { shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get( inst, "dayNamesShort" ), dayNames: this._get( inst, "dayNames" ),
			monthNamesShort: this._get( inst, "monthNamesShort" ), monthNames: this._get( inst, "monthNames" ) };
	},

	/* Format the given date for display. */
	_formatDate: function( inst, day, month, year ) {
		if ( !day ) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = ( day ? ( typeof day === "object" ? day :
			this._daylightSavingAdjust( new Date( year, month, day ) ) ) :
			this._daylightSavingAdjust( new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
		return this.formatDate( this._get( inst, "dateFormat" ), date, this._getFormatConfig( inst ) );
	}
} );

/*
 * Bind hover events for datepicker elements.
 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function datepicker_bindHover( dpDiv ) {
	var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
	return dpDiv.on( "mouseout", selector, function() {
			$( this ).removeClass( "ui-state-hover" );
			if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-prev-hover" );
			}
			if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-next-hover" );
			}
		} )
		.on( "mouseover", selector, datepicker_handleMouseover );
}

function datepicker_handleMouseover() {
	if ( !$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? datepicker_instActive.dpDiv.parent()[ 0 ] : datepicker_instActive.input[ 0 ] ) ) {
		$( this ).parents( ".ui-datepicker-calendar" ).find( "a" ).removeClass( "ui-state-hover" );
		$( this ).addClass( "ui-state-hover" );
		if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-prev-hover" );
		}
		if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-next-hover" );
		}
	}
}

/* jQuery extend now ignores nulls! */
function datepicker_extendRemove( target, props ) {
	$.extend( target, props );
	for ( var name in props ) {
		if ( props[ name ] == null ) {
			target[ name ] = props[ name ];
		}
	}
	return target;
}

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
					Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function( options ) {

	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}

	/* Initialise the date picker. */
	if ( !$.datepicker.initialized ) {
		$( document ).on( "mousedown", $.datepicker._checkExternalClick );
		$.datepicker.initialized = true;
	}

	/* Append datepicker main container to body if not exist. */
	if ( $( "#" + $.datepicker._mainDivId ).length === 0 ) {
		$( "body" ).append( $.datepicker.dpDiv );
	}

	var otherArgs = Array.prototype.slice.call( arguments, 1 );
	if ( typeof options === "string" && ( options === "isDisabled" || options === "getDate" || options === "widget" ) ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	if ( options === "option" && arguments.length === 2 && typeof arguments[ 1 ] === "string" ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	return this.each( function() {
		typeof options === "string" ?
			$.datepicker[ "_" + options + "Datepicker" ].
				apply( $.datepicker, [ this ].concat( otherArgs ) ) :
			$.datepicker._attachDatepicker( this, options );
	} );
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.12.1";

var widgetsDatepicker = $.datepicker;




// This file is deprecated
var ie = $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

/*!
 * jQuery UI Mouse 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/



var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
} );

var widgetsMouse = $.widget( "ui.mouse", {
	version: "1.12.1",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on( "mousedown." + this.widgetName, function( event ) {
				return that._mouseDown( event );
			} )
			.on( "click." + this.widgetName, function( event ) {
				if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
					$.removeData( event.target, that.widgetName + ".preventClickEvent" );
					event.stopImmediatePropagation();
					return false;
				}
			} );

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off( "." + this.widgetName );
		if ( this._mouseMoveDelegate ) {
			this.document
				.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
				.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
		}
	},

	_mouseDown: function( event ) {

		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		( this._mouseStarted && this._mouseUp( event ) );

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = ( event.which === 1 ),

			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
				$( event.target ).closest( this.options.cancel ).length : false );
		if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if ( !this.mouseDelayMet ) {
			this._mouseDelayTimer = setTimeout( function() {
				that.mouseDelayMet = true;
			}, this.options.delay );
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted = ( this._mouseStart( event ) !== false );
			if ( !this._mouseStarted ) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
			$.removeData( event.target, this.widgetName + ".preventClickEvent" );
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function( event ) {
			return that._mouseMove( event );
		};
		this._mouseUpDelegate = function( event ) {
			return that._mouseUp( event );
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {

			// IE mouseup check - mouseup happened when mouse was out of window
			if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
					!event.button ) {
				return this._mouseUp( event );

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {

				// Support: Safari <=8 - 9
				// Safari sets which to 0 if you press any of the following keys
				// during a drag (#14461)
				if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
						event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
					this.ignoreMissingWhich = true;
				} else if ( !this.ignoreMissingWhich ) {
					return this._mouseUp( event );
				}
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if ( this._mouseStarted ) {
			this._mouseDrag( event );
			return event.preventDefault();
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted =
				( this._mouseStart( this._mouseDownEvent, event ) !== false );
			( this._mouseStarted ? this._mouseDrag( event ) : this._mouseUp( event ) );
		}

		return !this._mouseStarted;
	},

	_mouseUp: function( event ) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if ( this._mouseStarted ) {
			this._mouseStarted = false;

			if ( event.target === this._mouseDownEvent.target ) {
				$.data( event.target, this.widgetName + ".preventClickEvent", true );
			}

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

	_mouseDistanceMet: function( event ) {
		return ( Math.max(
				Math.abs( this._mouseDownEvent.pageX - event.pageX ),
				Math.abs( this._mouseDownEvent.pageY - event.pageY )
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function( /* event */ ) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function( /* event */ ) {},
	_mouseDrag: function( /* event */ ) {},
	_mouseStop: function( /* event */ ) {},
	_mouseCapture: function( /* event */ ) { return true; }
} );


/*!
 * jQuery UI Effects 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Effects Core
//>>group: Effects
// jscs:disable maximumLineLength
//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/category/effects-core/
//>>demos: http://jqueryui.com/effect/



var dataSpace = "ui-effects-",
	dataSpaceStyle = "ui-effects-style",
	dataSpaceAnimated = "ui-effects-animated",

	// Create a local jQuery because jQuery Color relies on it and the
	// global may not exist with AMD and a custom build (#10199)
	jQuery = $;

$.effects = {
	effect: {}
};

/*!
 * jQuery Color Animations v2.1.2
 * https://github.com/jquery/jquery-color
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Wed Jan 16 08:47:09 2013 -0600
 */
( function( jQuery, undefined ) {

	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
		"borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	// Plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,

	// A set of RE's that can match strings and generate color tuples.
	stringParsers = [ {
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {

			// This regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 )
				];
			}
		}, {

			// This regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		} ],

	// JQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		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"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},
	support = color.support = {},

	// Element for support tests
	supportElem = jQuery( "<p>" )[ 0 ],

	// Colors = jQuery.Color.names
	colors,

	// Local aliases of functions called often
	each = jQuery.each;

// Determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;

// Define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
	space.cache = "_" + spaceName;
	space.props.alpha = {
		idx: 3,
		type: "percent",
		def: 1
	};
} );

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return ( allowEmpty || !prop.def ) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	// IE will pass in empty strings as value for alpha,
	// which will hit this case
	if ( isNaN( value ) ) {
		return prop.def;
	}

	if ( type.mod ) {

		// We add mod before modding to make sure that negatives values
		// get converted properly: -10 -> 350
		return ( value + type.mod ) % type.mod;
	}

	// For now all property types without mod have min and max
	return 0 > value ? 0 : type.max < value ? type.max : value;
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// If this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// Exit each( stringParsers ) here because we matched
			return false;
		}
	} );

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// If this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// Named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = jQuery.type( red ),
			rgba = this._rgba = [];

		// More than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			} );
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				} );
			} else {
				each( spaces, function( spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// If the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// If the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// This is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					} );

					// Everything defined but alpha?
					if ( inst[ cache ] &&
							jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {

						// Use the default of 1
						inst[ cache ][ 3 ] = 1;
						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				} );
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if ( isCache ) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				} );
			}
			return same;
		} );
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		} );
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// If null, don't override start value
			if ( endValue === null ) {
				return;
			}

			// If null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		} );
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {

		// If we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		} ) );
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				return v == null ? ( i > 2 ? 1 : 0 ) : v;
			} );

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join() + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// Catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			} );

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join() + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// Default to 0 when nulls exist
			v = ( v || 0 ).toString( 16 );
			return v.length === 1 ? "0" + v : v;
		} ).join( "" );
	},
	toString: function() {
		return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
	}
} );
color.fn.parse.prototype = color.fn;

// Hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

function hue2rgb( p, q, h ) {
	h = ( h + 1 ) % 1;
	if ( h * 6 < 1 ) {
		return p + ( q - p ) * h * 6;
	}
	if ( h * 2 < 1 ) {
		return q;
	}
	if ( h * 3 < 2 ) {
		return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
	}
	return p;
}

spaces.hsla.to = function( rgba ) {
	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
		return [ null, null, null, rgba[ 3 ] ];
	}
	var r = rgba[ 0 ] / 255,
		g = rgba[ 1 ] / 255,
		b = rgba[ 2 ] / 255,
		a = rgba[ 3 ],
		max = Math.max( r, g, b ),
		min = Math.min( r, g, b ),
		diff = max - min,
		add = max + min,
		l = add * 0.5,
		h, s;

	if ( min === max ) {
		h = 0;
	} else if ( r === max ) {
		h = ( 60 * ( g - b ) / diff ) + 360;
	} else if ( g === max ) {
		h = ( 60 * ( b - r ) / diff ) + 120;
	} else {
		h = ( 60 * ( r - g ) / diff ) + 240;
	}

	// Chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
	// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
	if ( diff === 0 ) {
		s = 0;
	} else if ( l <= 0.5 ) {
		s = diff / add;
	} else {
		s = diff / ( 2 - add );
	}
	return [ Math.round( h ) % 360, s, l, a == null ? 1 : a ];
};

spaces.hsla.from = function( hsla ) {
	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
		return [ null, null, null, hsla[ 3 ] ];
	}
	var h = hsla[ 0 ] / 360,
		s = hsla[ 1 ],
		l = hsla[ 2 ],
		a = hsla[ 3 ],
		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
		p = 2 * l - q;

	return [
		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
		Math.round( hue2rgb( p, q, h ) * 255 ),
		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
		a
	];
};

each( spaces, function( spaceName, space ) {
	var props = space.props,
		cache = space.cache,
		to = space.to,
		from = space.from;

	// Makes rgba() and hsla()
	color.fn[ spaceName ] = function( value ) {

		// Generate a cache for this space if it doesn't exist
		if ( to && !this[ cache ] ) {
			this[ cache ] = to( this._rgba );
		}
		if ( value === undefined ) {
			return this[ cache ].slice();
		}

		var ret,
			type = jQuery.type( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		} );

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// Makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {

		// Alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var vtype = jQuery.type( value ),
				fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
				local = this[ fn ](),
				cur = local[ prop.idx ],
				match;

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = jQuery.type( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	} );
} );

// Add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed, curElem,
					backgroundColor = "";

				if ( value !== "transparent" && ( jQuery.type( value ) !== "string" ||
						( parsed = stringParse( value ) ) ) ) {
					value = color( parsed || value );
					if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
						curElem = hook === "backgroundColor" ? elem.parentNode : elem;
						while (
							( backgroundColor === "" || backgroundColor === "transparent" ) &&
							curElem && curElem.style
						) {
							try {
								backgroundColor = jQuery.css( curElem, "backgroundColor" );
								curElem = curElem.parentNode;
							} catch ( e ) {
							}
						}

						value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
							backgroundColor :
							"_default" );
					}

					value = value.toRgbaString();
				}
				try {
					elem.style[ hook ] = value;
				} catch ( e ) {

					// Wrapped to prevent IE from throwing errors on "invalid" values like
					// 'auto' or 'inherit'
				}
			}
		};
		jQuery.fx.step[ hook ] = function( fx ) {
			if ( !fx.colorInit ) {
				fx.start = color( fx.elem, hook );
				fx.end = color( fx.end );
				fx.colorInit = true;
			}
			jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
		};
	} );

};

color.hook( stepHooks );

jQuery.cssHooks.borderColor = {
	expand: function( value ) {
		var expanded = {};

		each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
			expanded[ "border" + part + "Color" ] = value;
		} );
		return expanded;
	}
};

// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {

	// 4.1. Basic color keywords
	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",

	// 4.2.3. "transparent" color keyword
	transparent: [ null, null, null, 0 ],

	_default: "#ffffff"
};

} )( jQuery );

/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
( function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each(
	[ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ],
	function( _, prop ) {
		$.fx.step[ prop ] = function( fx ) {
			if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
				jQuery.style( fx.elem, prop, fx.end );
				fx.setAttr = true;
			}
		};
	}
);

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView ?
			elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
			elem.currentStyle,
		styles = {};

	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
		len = style.length;
		while ( len-- ) {
			key = style[ len ];
			if ( typeof style[ key ] === "string" ) {
				styles[ $.camelCase( key ) ] = style[ key ];
			}
		}

	// Support: Opera, IE <9
	} else {
		for ( key in style ) {
			if ( typeof style[ key ] === "string" ) {
				styles[ key ] = style[ key ];
			}
		}
	}

	return styles;
}

function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

// Support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// Map the animated objects to store the original styles.
		allAnimations = allAnimations.map( function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		} );

		// Apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function( i, action ) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			} );
		};
		applyClassChange();

		// Map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map( function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		} );

		// Apply original class
		animated.attr( "class", baseClass );

		// Map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map( function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend( {}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				} );

			this.el.animate( this.diff, opts );
			return dfd.promise();
		} );

		// Once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done( function() {

			// Set the final class
			applyClassChange();

			// For each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function( key ) {
					el.css( key, "" );
				} );
			} );

			// This is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		} );
	} );
};

$.fn.extend( {
	addClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.addClass ),

	removeClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.removeClass ),

	toggleClass: ( function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {

					// Without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						( force ? { add: classNames } : { remove: classNames } ),
						speed, easing, callback );
				}
			} else {

				// Without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	} )( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback ) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
} );

} )();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

( function() {

if ( $.expr && $.expr.filters && $.expr.filters.animated ) {
	$.expr.filters.animated = ( function( orig ) {
		return function( elem ) {
			return !!$( elem ).data( dataSpaceAnimated ) || orig( elem );
		};
	} )( $.expr.filters.animated );
}

if ( $.uiBackCompat !== false ) {
	$.extend( $.effects, {

		// Saves a set of properties in a data storage
		save: function( element, set ) {
			var i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
				}
			}
		},

		// Restores a set of previously saved properties from a data storage
		restore: function( element, set ) {
			var val, i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					val = element.data( dataSpace + set[ i ] );
					element.css( set[ i ], val );
				}
			}
		},

		setMode: function( el, mode ) {
			if ( mode === "toggle" ) {
				mode = el.is( ":hidden" ) ? "show" : "hide";
			}
			return mode;
		},

		// Wraps the element around a wrapper that copies position properties
		createWrapper: function( element ) {

			// If the element is already wrapped, return it
			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				return element.parent();
			}

			// Wrap the element
			var props = {
					width: element.outerWidth( true ),
					height: element.outerHeight( true ),
					"float": element.css( "float" )
				},
				wrapper = $( "<div></div>" )
					.addClass( "ui-effects-wrapper" )
					.css( {
						fontSize: "100%",
						background: "transparent",
						border: "none",
						margin: 0,
						padding: 0
					} ),

				// Store the size in case width/height are defined in % - Fixes #5245
				size = {
					width: element.width(),
					height: element.height()
				},
				active = document.activeElement;

			// Support: Firefox
			// Firefox incorrectly exposes anonymous content
			// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
			try {
				active.id;
			} catch ( e ) {
				active = document.body;
			}

			element.wrap( wrapper );

			// Fixes #7595 - Elements lose focus when wrapped.
			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
				$( active ).trigger( "focus" );
			}

			// Hotfix for jQuery 1.4 since some change in wrap() seems to actually
			// lose the reference to the wrapped element
			wrapper = element.parent();

			// Transfer positioning properties to the wrapper
			if ( element.css( "position" ) === "static" ) {
				wrapper.css( { position: "relative" } );
				element.css( { position: "relative" } );
			} else {
				$.extend( props, {
					position: element.css( "position" ),
					zIndex: element.css( "z-index" )
				} );
				$.each( [ "top", "left", "bottom", "right" ], function( i, pos ) {
					props[ pos ] = element.css( pos );
					if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
						props[ pos ] = "auto";
					}
				} );
				element.css( {
					position: "relative",
					top: 0,
					left: 0,
					right: "auto",
					bottom: "auto"
				} );
			}
			element.css( size );

			return wrapper.css( props ).show();
		},

		removeWrapper: function( element ) {
			var active = document.activeElement;

			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				element.parent().replaceWith( element );

				// Fixes #7595 - Elements lose focus when wrapped.
				if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
					$( active ).trigger( "focus" );
				}
			}

			return element;
		}
	} );
}

$.extend( $.effects, {
	version: "1.12.1",

	define: function( name, mode, effect ) {
		if ( !effect ) {
			effect = mode;
			mode = "effect";
		}

		$.effects.effect[ name ] = effect;
		$.effects.effect[ name ].mode = mode;

		return effect;
	},

	scaledDimensions: function( element, percent, direction ) {
		if ( percent === 0 ) {
			return {
				height: 0,
				width: 0,
				outerHeight: 0,
				outerWidth: 0
			};
		}

		var x = direction !== "horizontal" ? ( ( percent || 100 ) / 100 ) : 1,
			y = direction !== "vertical" ? ( ( percent || 100 ) / 100 ) : 1;

		return {
			height: element.height() * y,
			width: element.width() * x,
			outerHeight: element.outerHeight() * y,
			outerWidth: element.outerWidth() * x
		};

	},

	clipToBox: function( animation ) {
		return {
			width: animation.clip.right - animation.clip.left,
			height: animation.clip.bottom - animation.clip.top,
			left: animation.clip.left,
			top: animation.clip.top
		};
	},

	// Injects recently queued functions to be first in line (after "inprogress")
	unshift: function( element, queueLength, count ) {
		var queue = element.queue();

		if ( queueLength > 1 ) {
			queue.splice.apply( queue,
				[ 1, 0 ].concat( queue.splice( queueLength, count ) ) );
		}
		element.dequeue();
	},

	saveStyle: function( element ) {
		element.data( dataSpaceStyle, element[ 0 ].style.cssText );
	},

	restoreStyle: function( element ) {
		element[ 0 ].style.cssText = element.data( dataSpaceStyle ) || "";
		element.removeData( dataSpaceStyle );
	},

	mode: function( element, mode ) {
		var hidden = element.is( ":hidden" );

		if ( mode === "toggle" ) {
			mode = hidden ? "show" : "hide";
		}
		if ( hidden ? mode === "hide" : mode === "show" ) {
			mode = "none";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	getBaseline: function( origin, original ) {
		var y, x;

		switch ( origin[ 0 ] ) {
		case "top":
			y = 0;
			break;
		case "middle":
			y = 0.5;
			break;
		case "bottom":
			y = 1;
			break;
		default:
			y = origin[ 0 ] / original.height;
		}

		switch ( origin[ 1 ] ) {
		case "left":
			x = 0;
			break;
		case "center":
			x = 0.5;
			break;
		case "right":
			x = 1;
			break;
		default:
			x = origin[ 1 ] / original.width;
		}

		return {
			x: x,
			y: y
		};
	},

	// Creates a placeholder element so that the original element can be made absolute
	createPlaceholder: function( element ) {
		var placeholder,
			cssPosition = element.css( "position" ),
			position = element.position();

		// Lock in margins first to account for form elements, which
		// will change margin if you explicitly set height
		// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
		// Support: Safari
		element.css( {
			marginTop: element.css( "marginTop" ),
			marginBottom: element.css( "marginBottom" ),
			marginLeft: element.css( "marginLeft" ),
			marginRight: element.css( "marginRight" )
		} )
		.outerWidth( element.outerWidth() )
		.outerHeight( element.outerHeight() );

		if ( /^(static|relative)/.test( cssPosition ) ) {
			cssPosition = "absolute";

			placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {

				// Convert inline to inline block to account for inline elements
				// that turn to inline block based on content (like img)
				display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
					"inline-block" :
					"block",
				visibility: "hidden",

				// Margins need to be set to account for margin collapse
				marginTop: element.css( "marginTop" ),
				marginBottom: element.css( "marginBottom" ),
				marginLeft: element.css( "marginLeft" ),
				marginRight: element.css( "marginRight" ),
				"float": element.css( "float" )
			} )
			.outerWidth( element.outerWidth() )
			.outerHeight( element.outerHeight() )
			.addClass( "ui-effects-placeholder" );

			element.data( dataSpace + "placeholder", placeholder );
		}

		element.css( {
			position: cssPosition,
			left: position.left,
			top: position.top
		} );

		return placeholder;
	},

	removePlaceholder: function( element ) {
		var dataKey = dataSpace + "placeholder",
				placeholder = element.data( dataKey );

		if ( placeholder ) {
			placeholder.remove();
			element.removeData( dataKey );
		}
	},

	// Removes a placeholder if it exists and restores
	// properties that were modified during placeholder creation
	cleanUp: function( element ) {
		$.effects.restoreStyle( element );
		$.effects.removePlaceholder( element );
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		} );
		return value;
	}
} );

// Return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// Allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// Convert to an object
	effect = { effect: effect };

	// Catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// Catch (effect, callback)
	if ( $.isFunction( options ) ) {
		callback = options;
		speed = null;
		options = {};
	}

	// Catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// Catch (effect, options, callback)
	if ( $.isFunction( speed ) ) {
		callback = speed;
		speed = null;
	}

	// Add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {

	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( $.isFunction( option ) ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend( {
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			effectMethod = $.effects.effect[ args.effect ],
			defaultMode = effectMethod.mode,
			queue = args.queue,
			queueName = queue || "fx",
			complete = args.complete,
			mode = args.mode,
			modes = [],
			prefilter = function( next ) {
				var el = $( this ),
					normalizedMode = $.effects.mode( el, mode ) || defaultMode;

				// Sentinel for duck-punching the :animated psuedo-selector
				el.data( dataSpaceAnimated, true );

				// Save effect mode for later use,
				// we can't just call $.effects.mode again later,
				// as the .show() below destroys the initial state
				modes.push( normalizedMode );

				// See $.uiBackCompat inside of run() for removal of defaultMode in 1.13
				if ( defaultMode && ( normalizedMode === "show" ||
						( normalizedMode === defaultMode && normalizedMode === "hide" ) ) ) {
					el.show();
				}

				if ( !defaultMode || normalizedMode !== "none" ) {
					$.effects.saveStyle( el );
				}

				if ( $.isFunction( next ) ) {
					next();
				}
			};

		if ( $.fx.off || !effectMethod ) {

			// Delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, complete );
			} else {
				return this.each( function() {
					if ( complete ) {
						complete.call( this );
					}
				} );
			}
		}

		function run( next ) {
			var elem = $( this );

			function cleanup() {
				elem.removeData( dataSpaceAnimated );

				$.effects.cleanUp( elem );

				if ( args.mode === "hide" ) {
					elem.hide();
				}

				done();
			}

			function done() {
				if ( $.isFunction( complete ) ) {
					complete.call( elem[ 0 ] );
				}

				if ( $.isFunction( next ) ) {
					next();
				}
			}

			// Override mode option on a per element basis,
			// as toggle can be either show or hide depending on element state
			args.mode = modes.shift();

			if ( $.uiBackCompat !== false && !defaultMode ) {
				if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, done );
				}
			} else {
				if ( args.mode === "none" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, cleanup );
				}
			}
		}

		// Run prefilter on all elements first to ensure that
		// any showing or hiding happens before placeholder creation,
		// which ensures that any layout changes are correctly captured.
		return queue === false ?
			this.each( prefilter ).each( run ) :
			this.queue( queueName, prefilter ).queue( queueName, run );
	},

	show: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "show";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.show ),

	hide: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "hide";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.hide ),

	toggle: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "toggle";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.toggle ),

	cssUnit: function( key ) {
		var style = this.css( key ),
			val = [];

		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
			if ( style.indexOf( unit ) > 0 ) {
				val = [ parseFloat( style ), unit ];
			}
		} );
		return val;
	},

	cssClip: function( clipObj ) {
		if ( clipObj ) {
			return this.css( "clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " +
				clipObj.bottom + "px " + clipObj.left + "px)" );
		}
		return parseClip( this.css( "clip" ), this );
	},

	transfer: function( options, done ) {
		var element = $( this ),
			target = $( options.to ),
			targetFixed = target.css( "position" ) === "fixed",
			body = $( "body" ),
			fixTop = targetFixed ? body.scrollTop() : 0,
			fixLeft = targetFixed ? body.scrollLeft() : 0,
			endPosition = target.offset(),
			animation = {
				top: endPosition.top - fixTop,
				left: endPosition.left - fixLeft,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = element.offset(),
			transfer = $( "<div class='ui-effects-transfer'></div>" )
				.appendTo( "body" )
				.addClass( options.className )
				.css( {
					top: startPosition.top - fixTop,
					left: startPosition.left - fixLeft,
					height: element.innerHeight(),
					width: element.innerWidth(),
					position: targetFixed ? "fixed" : "absolute"
				} )
				.animate( animation, options.duration, options.easing, function() {
					transfer.remove();
					if ( $.isFunction( done ) ) {
						done();
					}
				} );
	}
} );

function parseClip( str, element ) {
		var outerWidth = element.outerWidth(),
			outerHeight = element.outerHeight(),
			clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,
			values = clipRegex.exec( str ) || [ "", 0, outerWidth, outerHeight, 0 ];

		return {
			top: parseFloat( values[ 1 ] ) || 0,
			right: values[ 2 ] === "auto" ? outerWidth : parseFloat( values[ 2 ] ),
			bottom: values[ 3 ] === "auto" ? outerHeight : parseFloat( values[ 3 ] ),
			left: parseFloat( values[ 4 ] ) || 0
		};
}

$.fx.step.clip = function( fx ) {
	if ( !fx.clipInit ) {
		fx.start = $( fx.elem ).cssClip();
		if ( typeof fx.end === "string" ) {
			fx.end = parseClip( fx.end, fx.elem );
		}
		fx.clipInit = true;
	}

	$( fx.elem ).cssClip( {
		top: fx.pos * ( fx.end.top - fx.start.top ) + fx.start.top,
		right: fx.pos * ( fx.end.right - fx.start.right ) + fx.start.right,
		bottom: fx.pos * ( fx.end.bottom - fx.start.bottom ) + fx.start.bottom,
		left: fx.pos * ( fx.end.left - fx.start.left ) + fx.start.left
	} );
};

} )();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

( function() {

// Based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

var baseEasings = {};

$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
	baseEasings[ name ] = function( p ) {
		return Math.pow( p, i + 2 );
	};
} );

$.extend( baseEasings, {
	Sine: function( p ) {
		return 1 - Math.cos( p * Math.PI / 2 );
	},
	Circ: function( p ) {
		return 1 - Math.sqrt( 1 - p * p );
	},
	Elastic: function( p ) {
		return p === 0 || p === 1 ? p :
			-Math.pow( 2, 8 * ( p - 1 ) ) * Math.sin( ( ( p - 1 ) * 80 - 7.5 ) * Math.PI / 15 );
	},
	Back: function( p ) {
		return p * p * ( 3 * p - 2 );
	},
	Bounce: function( p ) {
		var pow2,
			bounce = 4;

		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
	}
} );

$.each( baseEasings, function( name, easeIn ) {
	$.easing[ "easeIn" + name ] = easeIn;
	$.easing[ "easeOut" + name ] = function( p ) {
		return 1 - easeIn( 1 - p );
	};
	$.easing[ "easeInOut" + name ] = function( p ) {
		return p < 0.5 ?
			easeIn( p * 2 ) / 2 :
			1 - easeIn( p * -2 + 2 ) / 2;
	};
} );

} )();

var effect = $.effects;


/*!
 * jQuery UI Effects Transfer 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Transfer Effect
//>>group: Effects
//>>description: Displays a transfer effect from one element to another.
//>>docs: http://api.jqueryui.com/transfer-effect/
//>>demos: http://jqueryui.com/effect/



var effect;
if ( $.uiBackCompat !== false ) {
	effect = $.effects.define( "transfer", function( options, done ) {
		$( this ).transfer( options, done );
	} );
}
var effectsEffectTransfer = effect;




}));;
// Unobtrusive Ajax support library for jQuery
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// @version v3.2.6
// 
// Microsoft grants you the right to use these script files for the sole
// purpose of either: (i) interacting through your browser with the Microsoft
// website or online service, subject to the applicable licensing or use
// terms; or (ii) using the files as included with a Microsoft product subject
// to that product's license terms. Microsoft reserves all other rights to the
// files not expressly granted by Microsoft, whether by implication, estoppel
// or otherwise. Insofar as a script file is dual licensed under GPL,
// Microsoft neither took the code under GPL nor distributes it thereunder but
// under the terms set out in this paragraph. All notices and licenses
// below are for informational purposes only.
!function(t){function a(t,a){for(var e=window,r=(t||"").split(".");e&&r.length;)e=e[r.shift()];return"function"==typeof e?e:(a.push(t),Function.constructor.apply(null,a))}function e(t){return"GET"===t||"POST"===t}function r(t,a){e(a)||t.setRequestHeader("X-HTTP-Method-Override",a)}function n(a,e,r){var n;r.indexOf("application/x-javascript")===-1&&(n=(a.getAttribute("data-ajax-mode")||"").toUpperCase(),t(a.getAttribute("data-ajax-update")).each(function(a,r){switch(n){case"BEFORE":t(r).prepend(e);break;case"AFTER":t(r).append(e);break;case"REPLACE-WITH":t(r).replaceWith(e);break;default:t(r).html(e)}}))}function i(i,u){var o,c,d,s;if(o=i.getAttribute("data-ajax-confirm"),!o||window.confirm(o)){c=t(i.getAttribute("data-ajax-loading")),s=parseInt(i.getAttribute("data-ajax-loading-duration"),10)||0,t.extend(u,{type:i.getAttribute("data-ajax-method")||void 0,url:i.getAttribute("data-ajax-url")||void 0,cache:"true"===(i.getAttribute("data-ajax-cache")||"").toLowerCase(),beforeSend:function(t){var e;return r(t,d),e=a(i.getAttribute("data-ajax-begin"),["xhr"]).apply(i,arguments),e!==!1&&c.show(s),e},complete:function(){c.hide(s),a(i.getAttribute("data-ajax-complete"),["xhr","status"]).apply(i,arguments)},success:function(t,e,r){n(i,t,r.getResponseHeader("Content-Type")||"text/html"),a(i.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(i,arguments)},error:function(){a(i.getAttribute("data-ajax-failure"),["xhr","status","error"]).apply(i,arguments)}}),u.data.push({name:"X-Requested-With",value:"XMLHttpRequest"}),d=u.type.toUpperCase(),e(d)||(u.type="POST",u.data.push({name:"X-HTTP-Method-Override",value:d}));var p=t(i);if(p.is("form")&&"multipart/form-data"==p.attr("enctype")){var f=new FormData;t.each(u.data,function(t,a){f.append(a.name,a.value)}),t("input[type=file]",p).each(function(){var a=this;t.each(a.files,function(t,e){f.append(a.name,e)})}),t.extend(u,{processData:!1,contentType:!1,data:f})}t.ajax(u)}}function u(a){var e=t(a).data(d);return!e||!e.validate||e.validate()}var o="unobtrusiveAjaxClick",c="unobtrusiveAjaxClickTarget",d="unobtrusiveValidation";t(document).on("click","a[data-ajax=true]",function(t){t.preventDefault(),i(this,{url:this.href,type:"GET",data:[]})}),t(document).on("click","form[data-ajax=true] input[type=image]",function(a){var e=a.target.name,r=t(a.target),n=t(r.parents("form")[0]),i=r.offset();n.data(o,[{name:e+".x",value:Math.round(a.pageX-i.left)},{name:e+".y",value:Math.round(a.pageY-i.top)}]),setTimeout(function(){n.removeData(o)},0)}),t(document).on("click","form[data-ajax=true] :submit",function(a){var e=a.currentTarget.name,r=t(a.target),n=t(r.parents("form")[0]);n.data(o,e?[{name:e,value:a.currentTarget.value}]:[]),n.data(c,r),setTimeout(function(){n.removeData(o),n.removeData(c)},0)}),t(document).on("submit","form[data-ajax=true]",function(a){var e=t(this).data(o)||[],r=t(this).data(c),n=r&&(r.hasClass("cancel")||void 0!==r.attr("formnovalidate"));a.preventDefault(),(n||u(this))&&i(this,{url:this.action,type:this.method||"GET",data:e.concat(t(this).serializeArray())})})}(jQuery);;
/*! jQuery Validation Plugin - v1.17.0 - 7/29/2017
 * https://jqueryvalidation.org/
 * Copyright (c) 2017 Jörn Zaefferer; Licensed MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){a.extend(a.fn,{validate:function(b){if(!this.length)return void(b&&b.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.on("click.validate",":submit",function(b){c.submitButton=b.currentTarget,a(this).hasClass("cancel")&&(c.cancelSubmit=!0),void 0!==a(this).attr("formnovalidate")&&(c.cancelSubmit=!0)}),this.on("submit.validate",function(b){function d(){var d,e;return c.submitButton&&(c.settings.submitHandler||c.formSubmitted)&&(d=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),!c.settings.submitHandler||(e=c.settings.submitHandler.call(c,c.currentForm,b),d&&d.remove(),void 0!==e&&e)}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c,d;return a(this[0]).is("form")?b=this.validate().form():(d=[],b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b,b||(d=d.concat(c.errorList))}),c.errorList=d),b},rules:function(b,c){var d,e,f,g,h,i,j=this[0];if(null!=j&&(!j.form&&j.hasAttribute("contenteditable")&&(j.form=this.closest("form")[0],j.name=this.attr("name")),null!=j.form)){if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(a,b){i[b]=f[b],delete f[b]}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g)),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}}),a.extend(a.expr.pseudos||a.expr[":"],{blank:function(b){return!a.trim(""+a(b).val())},filled:function(b){var c=a(b).val();return null!==c&&!!a.trim(""+c)},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:void 0===c?b:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",pendingClass:"pending",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(b,c){var d=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===c.which&&""===this.elementValue(b)||a.inArray(c.keyCode,d)!==-1||(b.name in this.submitted||b.name in this.invalid)&&this.element(b)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}."),step:a.validator.format("Please enter a multiple of {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){!this.form&&this.hasAttribute("contenteditable")&&(this.form=a(this).closest("form")[0],this.name=a(this).attr("name"));var c=a.data(this.form,"validator"),d="on"+b.type.replace(/^validate/,""),e=c.settings;e[d]&&!a(this).is(e.ignore)&&e[d].call(c,this,b)}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){d[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox'], [contenteditable], [type='button']",b).on("click.validate","select, option, [type='radio'], [type='checkbox']",b),this.settings.invalidHandler&&a(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c,d,e=this.clean(b),f=this.validationTargetFor(e),g=this,h=!0;return void 0===f?delete this.invalid[e.name]:(this.prepareElement(f),this.currentElements=a(f),d=this.groups[f.name],d&&a.each(this.groups,function(a,b){b===d&&a!==f.name&&(e=g.validationTargetFor(g.clean(g.findByName(a))),e&&e.name in g.invalid&&(g.currentElements.push(e),h=g.check(e)&&h))}),c=this.check(f)!==!1,h=h&&c,c?this.invalid[f.name]=!1:this.invalid[f.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),a(b).attr("aria-invalid",!c)),h},showErrors:function(b){if(b){var c=this;a.extend(this.errorMap,b),this.errorList=a.map(this.errorMap,function(a,b){return{message:a,element:c.findByName(b)[0]}}),this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.invalid={},this.submitted={},this.prepareForm(),this.hideErrors();var b=this.elements().removeData("previousValue").removeAttr("aria-invalid");this.resetElements(b)},resetElements:function(a){var b;if(this.settings.unhighlight)for(b=0;a[b];b++)this.settings.unhighlight.call(this,a[b],this.settings.errorClass,""),this.findByName(a[b].name).removeClass(this.settings.validClass);else a.removeClass(this.settings.errorClass).removeClass(this.settings.validClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)void 0!==a[b]&&null!==a[b]&&a[b]!==!1&&c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){var d=this.name||a(this).attr("name");return!d&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.hasAttribute("contenteditable")&&(this.form=a(this).closest("form")[0],this.name=d),!(d in c||!b.objectLength(a(this).rules()))&&(c[d]=!0,!0)})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},resetInternals:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([])},reset:function(){this.resetInternals(),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d,e=a(b),f=b.type;return"radio"===f||"checkbox"===f?this.findByName(b.name).filter(":checked").val():"number"===f&&"undefined"!=typeof b.validity?b.validity.badInput?"NaN":e.val():(c=b.hasAttribute("contenteditable")?e.text():e.val(),"file"===f?"C:\\fakepath\\"===c.substr(0,12)?c.substr(12):(d=c.lastIndexOf("/"),d>=0?c.substr(d+1):(d=c.lastIndexOf("\\"),d>=0?c.substr(d+1):c)):"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f,g=a(b).rules(),h=a.map(g,function(a,b){return b}).length,i=!1,j=this.elementValue(b);if("function"==typeof g.normalizer?f=g.normalizer:"function"==typeof this.settings.normalizer&&(f=this.settings.normalizer),f){if(j=f.call(b,j),"string"!=typeof j)throw new TypeError("The normalizer should return a string value.");delete g.normalizer}for(d in g){e={method:d,parameters:g[d]};try{if(c=a.validator.methods[d].call(this,j,b,e.parameters),"dependency-mismatch"===c&&1===h){i=!0;continue}if(i=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(k){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",k),k instanceof TypeError&&(k.message+=".  Exception occurred when checking element "+b.id+", check the '"+e.method+"' method."),k}}if(!i)return this.objectLength(g)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(void 0!==arguments[a])return arguments[a]},defaultMessage:function(b,c){"string"==typeof c&&(c={method:c});var d=this.findDefined(this.customMessage(b.name,c.method),this.customDataMessage(b,c.method),!this.settings.ignoreTitle&&b.title||void 0,a.validator.messages[c.method],"<strong>Warning: No message defined for "+b.name+"</strong>"),e=/\$?\{(\d+)\}/g;return"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),d},formatAndAdd:function(a,b){var c=this.defaultMessage(a,b);this.errorList.push({message:c,element:a,method:b.method}),this.errorMap[a.name]=c,this.submitted[a.name]=c},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g,h=this.errorsFor(b),i=this.idOrName(b),j=a(b).attr("aria-describedby");h.length?(h.removeClass(this.settings.validClass).addClass(this.settings.errorClass),h.html(c)):(h=a("<"+this.settings.errorElement+">").attr("id",i+"-error").addClass(this.settings.errorClass).html(c||""),d=h,this.settings.wrapper&&(d=h.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement.call(this,d,a(b)):d.insertAfter(b),h.is("label")?h.attr("for",i):0===h.parents("label[for='"+this.escapeCssMeta(i)+"']").length&&(f=h.attr("id"),j?j.match(new RegExp("\\b"+this.escapeCssMeta(f)+"\\b"))||(j+=" "+f):j=f,a(b).attr("aria-describedby",j),e=this.groups[b.name],e&&(g=this,a.each(g.groups,function(b,c){c===e&&a("[name='"+g.escapeCssMeta(b)+"']",g.currentForm).attr("aria-describedby",h.attr("id"))})))),!c&&this.settings.success&&(h.text(""),"string"==typeof this.settings.success?h.addClass(this.settings.success):this.settings.success(h,b)),this.toShow=this.toShow.add(h)},errorsFor:function(b){var c=this.escapeCssMeta(this.idOrName(b)),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+this.escapeCssMeta(d).replace(/\s+/g,", #")),this.errors().filter(e)},escapeCssMeta:function(a){return a.replace(/([\\!"#$%&'()*+,.\/:;<=>?@\[\]^`{|}~])/g,"\\$1")},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+this.escapeCssMeta(b)+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return!this.dependTypes[typeof a]||this.dependTypes[typeof a](a,b)},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(b){this.pending[b.name]||(this.pendingRequest++,a(b).addClass(this.settings.pendingClass),this.pending[b.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],a(b).removeClass(this.settings.pendingClass),c&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.submitButton&&a("input:hidden[name='"+this.submitButton.name+"']",this.currentForm).remove(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b,c){return c="string"==typeof c&&c||"remote",a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,{method:c})})},destroy:function(){this.resetForm(),a(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},normalizeAttributeRule:function(a,b,c,d){/min|max|step/.test(c)&&(null===b||/number|range|text/.test(b))&&(d=Number(d),isNaN(d)&&(d=void 0)),d||0===d?a[c]=d:b===c&&"range"!==b&&(a[c]=!0)},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),this.normalizeAttributeRule(e,g,c,d);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),this.normalizeAttributeRule(e,g,c,d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0===e.param||e.param:(a.data(c.form,"validator").resetElements(a(c)),delete b[d])}}),a.each(b,function(d,e){b[d]=a.isFunction(e)&&"normalizer"!==d?e(c):e}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var c;b[this]&&(a.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(c=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(c[0]),Number(c[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:b.length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[\/?#]\S*)?$/i.test(a)},date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a).toString())},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e<=d},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||a<=c},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},step:function(b,c,d){var e,f=a(c).attr("type"),g="Step attribute on input type "+f+" is not supported.",h=["text","number","range"],i=new RegExp("\\b"+f+"\\b"),j=f&&!i.test(h.join()),k=function(a){var b=(""+a).match(/(?:\.(\d+))?$/);return b&&b[1]?b[1].length:0},l=function(a){return Math.round(a*Math.pow(10,e))},m=!0;if(j)throw new Error(g);return e=k(d),(k(b)>e||l(b)%l(d)!==0)&&(m=!1),this.optional(c)||m},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.not(".validate-equalTo-blur").length&&e.addClass("validate-equalTo-blur").on("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d,e){if(this.optional(c))return"dependency-mismatch";e="string"==typeof e&&e||"remote";var f,g,h,i=this.previousValue(c,e);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),i.originalMessage=i.originalMessage||this.settings.messages[c.name][e],this.settings.messages[c.name][e]=i.message,d="string"==typeof d&&{url:d}||d,h=a.param(a.extend({data:b},d.data)),i.old===h?i.valid:(i.old=h,f=this,this.startRequest(c),g={},g[c.name]=b,a.ajax(a.extend(!0,{mode:"abort",port:"validate"+c.name,dataType:"json",data:g,context:f.currentForm,success:function(a){var d,g,h,j=a===!0||"true"===a;f.settings.messages[c.name][e]=i.originalMessage,j?(h=f.formSubmitted,f.resetInternals(),f.toHide=f.errorsFor(c),f.formSubmitted=h,f.successList.push(c),f.invalid[c.name]=!1,f.showErrors()):(d={},g=a||f.defaultMessage(c,{method:e,parameters:b}),d[c.name]=i.message=g,f.invalid[c.name]=!0,f.showErrors(d)),i.valid=j,f.stopRequest(c,j)}},d)),"pending")}}});var b,c={};return a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,d){var e=a.port;"abort"===a.mode&&(c[e]&&c[e].abort(),c[e]=d)}):(b=a.ajax,a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return"abort"===e?(c[f]&&c[f].abort(),c[f]=b.apply(this,arguments),c[f]):b.apply(this,arguments)}),a});;
// Unobtrusive validation support library for jQuery and jQuery Validate
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// @version v3.2.11
!function(a){"function"==typeof define&&define.amd?define("jquery.validate.unobtrusive",["jquery-validation"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery-validation")):jQuery.validator.unobtrusive=a(jQuery)}(function(a){function e(a,e,n){a.rules[e]=n,a.message&&(a.messages[e]=a.message)}function n(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function t(a){return a.replace(/([!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function r(a){return a.substr(0,a.lastIndexOf(".")+1)}function i(a,e){return 0===a.indexOf("*.")&&(a=a.replace("*.",e)),a}function o(e,n){var r=a(this).find("[data-valmsg-for='"+t(n[0].name)+"']"),i=r.attr("data-valmsg-replace"),o=i?a.parseJSON(i)!==!1:null;r.removeClass("field-validation-valid").addClass("field-validation-error"),e.data("unobtrusiveContainer",r),o?(r.empty(),e.removeClass("input-validation-error").appendTo(r)):e.hide()}function d(e,n){var t=a(this).find("[data-valmsg-summary=true]"),r=t.find("ul");r&&r.length&&n.errorList.length&&(r.empty(),t.addClass("validation-summary-errors").removeClass("validation-summary-valid"),a.each(n.errorList,function(){a("<li />").html(this.message).appendTo(r)}))}function s(e){var n=e.data("unobtrusiveContainer");if(n){var t=n.attr("data-valmsg-replace"),r=t?a.parseJSON(t):null;n.addClass("field-validation-valid").removeClass("field-validation-error"),e.removeData("unobtrusiveContainer"),r&&n.empty()}}function l(e){var n=a(this),t="__jquery_unobtrusive_validation_form_reset";if(!n.data(t)){n.data(t,!0);try{n.data("validator").resetForm()}finally{n.removeData(t)}n.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors"),n.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}}function u(e){var n=a(e),t=n.data(v),r=a.proxy(l,e),i=f.unobtrusive.options||{},u=function(n,t){var r=i[n];r&&a.isFunction(r)&&r.apply(e,t)};return t||(t={options:{errorClass:i.errorClass||"input-validation-error",errorElement:i.errorElement||"span",errorPlacement:function(){o.apply(e,arguments),u("errorPlacement",arguments)},invalidHandler:function(){d.apply(e,arguments),u("invalidHandler",arguments)},messages:{},rules:{},success:function(){s.apply(e,arguments),u("success",arguments)}},attachValidation:function(){n.off("reset."+v,r).on("reset."+v,r).validate(this.options)},validate:function(){return n.validate(),n.valid()}},n.data(v,t)),t}var m,f=a.validator,v="unobtrusiveValidation";return f.unobtrusive={adapters:[],parseElement:function(e,n){var t,r,i,o=a(e),d=o.parents("form")[0];d&&(t=u(d),t.options.rules[e.name]=r={},t.options.messages[e.name]=i={},a.each(this.adapters,function(){var n="data-val-"+this.name,t=o.attr(n),s={};void 0!==t&&(n+="-",a.each(this.params,function(){s[this]=o.attr(n+this)}),this.adapt({element:e,form:d,message:t,params:s,rules:r,messages:i}))}),a.extend(r,{__dummy__:!0}),n||t.attachValidation())},parse:function(e){var n=a(e),t=n.parents().addBack().filter("form").add(n.find("form")).has("[data-val=true]");n.find("[data-val=true]").each(function(){f.unobtrusive.parseElement(this,!0)}),t.each(function(){var a=u(this);a&&a.attachValidation()})}},m=f.unobtrusive.adapters,m.add=function(a,e,n){return n||(n=e,e=[]),this.push({name:a,params:e,adapt:n}),this},m.addBool=function(a,n){return this.add(a,function(t){e(t,n||a,!0)})},m.addMinMax=function(a,n,t,r,i,o){return this.add(a,[i||"min",o||"max"],function(a){var i=a.params.min,o=a.params.max;i&&o?e(a,r,[i,o]):i?e(a,n,i):o&&e(a,t,o)})},m.addSingleVal=function(a,n,t){return this.add(a,[n||"val"],function(r){e(r,t||a,r.params[n])})},f.addMethod("__dummy__",function(a,e,n){return!0}),f.addMethod("regex",function(a,e,n){var t;return!!this.optional(e)||(t=new RegExp(n).exec(a),t&&0===t.index&&t[0].length===a.length)}),f.addMethod("nonalphamin",function(a,e,n){var t;return n&&(t=a.match(/\W/g),t=t&&t.length>=n),t}),f.methods.extension?(m.addSingleVal("accept","mimtype"),m.addSingleVal("extension","extension")):m.addSingleVal("extension","extension","accept"),m.addSingleVal("regex","pattern"),m.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url"),m.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range"),m.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength"),m.add("equalto",["other"],function(n){var o=r(n.element.name),d=n.params.other,s=i(d,o),l=a(n.form).find(":input").filter("[name='"+t(s)+"']")[0];e(n,"equalTo",l)}),m.add("required",function(a){"INPUT"===a.element.tagName.toUpperCase()&&"CHECKBOX"===a.element.type.toUpperCase()||e(a,"required",!0)}),m.add("remote",["url","type","additionalfields"],function(o){var d={url:o.params.url,type:o.params.type||"GET",data:{}},s=r(o.element.name);a.each(n(o.params.additionalfields||o.element.name),function(e,n){var r=i(n,s);d.data[r]=function(){var e=a(o.form).find(":input").filter("[name='"+t(r)+"']");return e.is(":checkbox")?e.filter(":checked").val()||e.filter(":hidden").val()||"":e.is(":radio")?e.filter(":checked").val()||"":e.val()}}),e(o,"remote",d)}),m.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&e(a,"minlength",a.params.min),a.params.nonalphamin&&e(a,"nonalphamin",a.params.nonalphamin),a.params.regex&&e(a,"regex",a.params.regex)}),m.add("fileextensions",["extensions"],function(a){e(a,"extension",a.params.extensions)}),a(function(){f.unobtrusive.parse(document)}),f.unobtrusive});;
(function ($) {
    var defaultOptions = {
        errorClass: 'has-error',
        validClass: 'has-success',
        highlight: function (element, errorClass, validClass) {
            $(element).closest(".form-group, .checkbox, .mn-select")
                .addClass(errorClass)
                .removeClass(validClass);
            var __id = $(element).closest(".tab-pane.form-group").attr("id");
            $("[data-tab='#" + __id + "']").closest(".tab-head")
                .addClass(errorClass)
                .removeClass(validClass);
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).closest(".form-group, .checkbox, .mn-select")
                .removeClass(errorClass)
                .addClass(validClass);
            var __id = $(element).closest(".tab-pane.form-group").attr("id");
            $("[data-tab='#" + __id + "']").closest(".tab-head")
                .removeClass(errorClass)
                .addClass(validClass);
        },
        ignore: ':not(select:hidden, select, input:visible, textarea:visible), .ignore, #adyenPaymentPanel select, #adyenPaymentPanel input, #adyenPaymentPanel textarea'
    };

    $.validator.setDefaults(defaultOptions);
    $.validator.methods["date"] = function (value, element) { return true; }
    //disable default email-type based validation
    $.validator.methods.email = function (value, element) {
        return true;
    }
    $.validator.unobtrusive.options = {
        errorClass: defaultOptions.errorClass,
        validClass: defaultOptions.validClass
    };
})(jQuery);

(function ($) {
    $.validator.unobtrusive.addValidation = function (selector) {
        //get the relevant form
        var form = $(selector);
        // delete validator in case someone called form.validate()
        $(form).removeData("validator");
        $.validator.unobtrusive.parse(form);
    }
})(jQuery);

jQuery.validator.unobtrusive.adapters.add("brequired", function (options) {
    //b-required for checkboxes
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        //setValidationValues(options, "required", true);
        options.rules["brequired"] = true;
        if (options.message) {
            options.messages["brequired"] = options.message;
        }
    }
});

$.validator.addMethod("custompricerangevalid", function (value, element, params) {
    if (!$(element).val() == "") {
        var inputValue = parseFloat($(element).val());
        var minPrice = parseFloat($(params[0]).val());
        var maxPrice = parseFloat($(params[1]).val());

        return inputValue >= minPrice && inputValue <= maxPrice;
    }
    return true;
});
$.validator.addMethod("custompricenotemptyvalid", function (value, element, params) {
    return !($(element).parents(".radio-list").find(".custom input[type='radio']").is(":checked") && $(element).val() == "");
});

jQuery.validator.unobtrusive.adapters.add("custompricerangevalid", ['minpricefield', 'maxpricefield'], function (options) {
    options.rules["custompricerangevalid"] = ["#" + options.params.minpricefield, '#' + options.params.maxpricefield];
    options.messages["custompricerangevalid"] = [options.message];
});
jQuery.validator.unobtrusive.adapters.add("custompricenotemptyvalid", function (options) {
    options.rules["custompricenotemptyvalid"] = [];
    options.messages["custompricenotemptyvalid"] = [options.message];
});

// #region  -------------birthdate validation for KlarnaPrivatePayment--------------
$.validator.addMethod("klarnaprivatebirthdatenotemptyvalid", function (value, element, params) {
    var isKlarnaPrivate = params[0].toLowerCase() == 'true';

    if (isKlarnaPrivate) {
        if (!$(element).val() == "") {
            return true;
        }

        return false;
    }
    else {
        return true;
    }
});

$.validator.unobtrusive.adapters.add("klarnaprivatebirthdatenotemptyvalid", ['isklarnaprivateproperty'], function (options) {
    options.rules["klarnaprivatebirthdatenotemptyvalid"] = [options.params.isklarnaprivateproperty];
    options.messages["klarnaprivatebirthdatenotemptyvalid"] = [options.message];
});

$.validator.addMethod("klarnaprivatebirthdateformatvalid", function (value, element, params) {
    var isKlarnaPrivate = params[0].toLowerCase() == 'true';
    if (isKlarnaPrivate) {
        if (!$(element).val() == "") {
            var inputValue = $(element).val();
            var pattern = new RegExp(params[1], 'i');

            var n = inputValue.search(pattern);
            if (n == 0) {
                try {
                    jQuery.datepicker.parseDate('ddmmyy', inputValue);
                    return true;
                }
                catch (err) { }
            }
        }

        return false;
    }
    else {
        return true;
    }
});

$.validator.unobtrusive.adapters.add("klarnaprivatebirthdateformatvalid", ['isklarnaprivateproperty', 'patternproperty'], function (options) {
    options.rules["klarnaprivatebirthdateformatvalid"] = [options.params.isklarnaprivateproperty, options.params.patternproperty];
    options.messages["klarnaprivatebirthdateformatvalid"] = [options.message];
});
// #endregion ------------- end of birthdate validation for KlarnaPrivatePayment--------------

$.validator.addMethod("klarnaprivatefieldnotemptyvalid", function (value, element, params) {
    var isKlarnaPrivate = params[0].toLowerCase() == 'true';
    return (!isKlarnaPrivate || !$(element).val() == "");
});

$.validator.unobtrusive.adapters.add("klarnaprivatefieldnotemptyvalid", ['isklarnaprivateproperty'], function (options) {
    options.rules["klarnaprivatefieldnotemptyvalid"] = [options.params.isklarnaprivateproperty];
    options.messages["klarnaprivatefieldnotemptyvalid"] = [options.message];
});
// #region ------payment rule validation ------//

$.validator.addMethod("paymentrulenotempty", function (value, element, params) {
    return $(element).prop("checked");
});

$.validator.unobtrusive.adapters.add("paymentrulenotempty", function (options) {
    options.rules["paymentrulenotempty"] = [];
    options.messages["paymentrulenotempty"] = [options.message];
});

// #endregion------end of payment rule validation------//

// #region-------------recipient's post code validation--------------
$.validator.addMethod("recipientpostcodenotempty", function (value, element, params) {
    return (!$(element).val() == "")
});

$.validator.unobtrusive.adapters.add("recipientpostcodenotempty", function (options) {
    options.rules["recipientpostcodenotempty"] = [];
    options.messages["recipientpostcodenotempty"] = [options.message];
});

$.validator.addMethod("recipientpostcodevalid", function (value, element, params) {
    var inputValue = $(element).val();
    var pattern = new RegExp(params[0], 'i');

    var n = inputValue.search(pattern);

    if (n == 0)
        window.dispatchEvent(new CustomEvent('sendPostCodeEvent', { 'detail': inputValue }));

    return n == 0;
});

$.validator.addMethod("recipientpostcodcontactvalid", function (value, element, params) {
    var inputValue = $(element).val();
    var pattern = new RegExp(params[0], 'i');

    var n = inputValue.search(pattern);
    return n == 0;
});

$.validator.unobtrusive.adapters.add("recipientpostcodevalid", ['patternproperty'], function (options) {
    options.rules["recipientpostcodevalid"] = [options.params.patternproperty];
    options.messages["recipientpostcodevalid"] = [options.message];
});

$.validator.addMethod("recipientpostcodemaxlengthcampaign", function (value, element, params) {
    return $(element).val().length <= params[0];
});
$.validator.addMethod("recipientpostcodemaxlength", function (value, element, params) {
    return $(element).val().length <= params[0];
});

$.validator.addMethod("recipientpostcodeminlength", function (value, element, params) {
    return $(element).val().length >= params[0];
});
$.validator.unobtrusive.adapters.add("recipientpostcodemaxlengthcampaign", ['maxlengthcampaign'], function (options) {
    options.rules["recipientpostcodemaxlengthcampaign"] = [options.params.maxlengthcampaign];
    options.messages["recipientpostcodemaxlengthcampaign"] = [options.message];
});
$.validator.unobtrusive.adapters.add("recipientpostcodemaxlength", ['maxlengthnormal'], function (options) {
    options.rules["recipientpostcodemaxlength"] = [options.params.maxlengthnormal];
    options.messages["recipientpostcodemaxlength"] = [options.message];
});
$.validator.unobtrusive.adapters.add("recipientpostcodeminlength", ['minlengthnormal'], function (options) {
    options.rules["recipientpostcodeminlength"] = [options.params.minlengthnormal];
    options.messages["recipientpostcodeminlength"] = [options.message];
});

$.validator.unobtrusive.adapters.add("recipientpostcodcontactvalid", ['postcodevalid'], function (options) {
    options.rules["recipientpostcodevalid"] = [options.params.postcodevalid];
    options.messages["recipientpostcodevalid"] = [options.message];
});
// #endregion ------------- end of recipient's post code validation--------------

// #region------------- sender's telephone validation--------------
$.validator.addMethod("telephonenotempty", function (value, element, params) {
    return (value != "");
});

$.validator.unobtrusive.adapters.add("telephonenotempty", function (options) {
    options.rules["telephonenotempty"] = [];
    options.messages["telephonenotempty"] = [options.message];
});

$.validator.addMethod("telephonevalid", function (value, element, params) {
    var maxLength = parseInt(params[0]);

    return (value.length <= maxLength);
});

$.validator.unobtrusive.adapters.add("telephonevalid", ['maxlengthproperty'], function (options) {
    options.rules["telephonevalid"] = [options.params.maxlengthproperty];
    options.messages["telephonevalid"] = [options.message];
});

$.validator.addMethod("telephonepattern", function (value, element, params) {
    phoneType = params[0].PhoneType;
    var pattern;

    switch (phoneType) {
        case "Landline":
            pattern = params[0].Landline;
            break;
        case "Mobile":
            pattern = params[0].Mobile;
            break;
    }

    var regexp = new RegExp(pattern, "i");
    var result = value.search(regexp);
    return result == 0;
});

jQuery.validator.unobtrusive.adapters.add("telephonepattern", ['telephonepatterns'], function (options) {
    options.rules["telephonepattern"] = [JSON.parse(options.params.telephonepatterns)];
    options.messages["telephonepattern"] = [options.message];
});
// #endregion------------- end of sender's telephone validation--------------

// #region-------------FloristBoxFieldLenghtValidator--------------
$.validator.addMethod("floristboxfieldlenght", function (value, element, params) {
    var maxLength = parseInt(params[0]);

    return (value.length <= maxLength);
});

$.validator.addMethod("specialcharactersinaddressvalid", function (value, element, params) {
    var pattern = "\\*!|^!|\\|";
    var regex = RegExp(pattern);
    return !regex.test(value);
});

$.validator.unobtrusive.adapters.add("floristboxfieldlenght", ['maxlengthproperty'], function (options) {
    options.rules["floristboxfieldlenght"] = [options.params.maxlengthproperty];
    options.messages["floristboxfieldlenght"] = [options.message];
});

$.validator.unobtrusive.adapters.add("specialcharactersinaddressvalid", ['patternproperty'], function (options) {
    options.rules["specialcharactersinaddressvalid"] = [options.params.maxlengthproperty];
    options.messages["specialcharactersinaddressvalid"] = [options.message];
});
// #endregion------------- end of FloristBoxFieldLenghtValidator--------------

$.validator.addMethod("specialcharactersvalid", function (value, element, params) {
    var pattern = "\\*!|^!|\\|";
    var regex = RegExp(pattern);
    return !regex.test(value);
});

$.validator.unobtrusive.adapters.add("specialcharactersvalid", ['patternproperty'], function (options) {
    options.rules["specialcharactersvalid"] = [options.params.maxlengthproperty];
    options.messages["specialcharactersvalid"] = [options.message];
});

$.validator.addMethod("cardtextspecialcharactersvalid", function (value, element, params) {
    var pattern = "\\*!|^!|\\*|\\|";
    var regex = RegExp(pattern);
    return !regex.test(value);
});

$.validator.unobtrusive.adapters.add("cardtextspecialcharactersvalid", ['patternproperty'], function (options) {
    options.rules["cardtextspecialcharactersvalid"] = [options.params.maxlengthproperty];
    options.messages["cardtextspecialcharactersvalid"] = [options.message];
});

// #region------------- PersonalNumberValidator --------------
$.validator.addMethod("personalnumberrule", function (value, element, params) {
    var currentDomain = params[0];

    switch (currentDomain) {
        case 'No':
            if (value.length === 11 && isFinite(value)) {
                var day = value.substr(0, 2);
                var month = value.substr(2, 2);
                var year = value.substr(4, 2);

                return (day > 0 && month > 0 && day < 32 && month < 13);
            }
            break;
        case 'Se':
            var regex = new RegExp('[0-9]{6,8}-?[0-9]{4}');

            if (regex.test(value) == false) {
                break;
            }

            var isLongDate = value.length > 11;
            var dateStr = value.substr(0, isLongDate ? 8 : 6);

            try {
                var dd = $.datepicker.parseDate((isLongDate ? 'yy' : 'y') + 'mmdd', dateStr);
                return true;
            }
            catch (ex) { }

            break;
        default:
            return true;
    }

    return false;
});

$.validator.unobtrusive.adapters.add("personalnumberrule", ['currentdomainproperty'], function (options) {
    options.rules["personalnumberrule"] = [options.params.currentdomainproperty];
    options.messages["personalnumberrule"] = [options.message];
});
// #endregion------------- end of PersonalNumberValidator --------------

// #region--------Password and ConfirmationPassword Validator--------

//Password
$.validator.addMethod("passwordprovided", function (value, element, params) {
    var inputValue = $(element).val();
    var iwanttoregisterfieldChecked = (params[0] != "" && params[0] != "#") ? $(params[0]).prop("checked") : true;

    return ((iwanttoregisterfieldChecked && inputValue != "") || (!iwanttoregisterfieldChecked));
});

$.validator.addMethod("passwordlengthvalid", function (value, element, params) {
    var inputValue = $(element).val();
    if (inputValue != "") {
        var minLength = parseInt(params[0]);
        var maxLength = parseInt(params[1]);

        return inputValue.length >= minLength && inputValue.length <= maxLength;
    }
    return true;
});

$.validator.addMethod("passwordcomplexitymatched", function (value, element, params) {
    var inputValue = $(element).val();
    if (inputValue != "") {
        var result = true;
        $.each(params[0], function (index, _value) {
            var r = new RegExp(_value);
            result &= r.test(inputValue);
        });
        return result;
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.add("passwordprovided", ['iwanttoregisterfield'], function (options) {
    options.rules["passwordprovided"] = ["#" + options.params.iwanttoregisterfield];
    options.messages["passwordprovided"] = [options.message];
});

jQuery.validator.unobtrusive.adapters.add("passwordlengthvalid", ['passwordminlength', 'passwordmaxlength'], function (options) {
    options.rules["passwordlengthvalid"] = [options.params.passwordminlength, options.params.passwordmaxlength];
    options.messages["passwordlengthvalid"] = [options.message];
});

jQuery.validator.unobtrusive.adapters.add("passwordcomplexitymatched", [], function (options) {
    var array = [];
    var i = 0;
    $(options.element).filter(function () {
        for (var property in $(this).data()) {
            if (property.indexOf('valPasswordcomplexitymatchedPasswordregex') == 0) {
                i++;
            }
        }
    })

    for (var j = 0; j < i; j++) {
        array.push($(options.element).data("val-" + "passwordcomplexitymatched" + "-" + "passwordregex" + j));
    }
    options.rules["passwordcomplexitymatched"] = [array];
    options.messages["passwordcomplexitymatched"] = [options.message];
});

//ConfirmationPassword
$.validator.addMethod("confirmationpasswordprovided", function (value, element, params) {
    var inputValue = $(element).val();
    var iwanttoregisterfieldChecked = (params[0] != "" && params[0] != "#") ? $(params[0]).prop("checked") : true;//.toUpperCase == "TRUE";

    return ((iwanttoregisterfieldChecked && inputValue != "") || (!iwanttoregisterfieldChecked));
});

$.validator.addMethod("confirmationpasswordmatched", function (value, element, params) {
    var inputValue = $(element).val();
    if (inputValue != "") {
        var passwordFieldValue = $(element).closest("form").find("#tb" + params[0] + ", #tbR" + params[0]).val();
        return inputValue === passwordFieldValue;
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.add("confirmationpasswordprovided", ['iwanttoregisterfield'], function (options) {
    options.rules["confirmationpasswordprovided"] = ["#" + options.params.iwanttoregisterfield];
    options.messages["confirmationpasswordprovided"] = [options.message];
});

jQuery.validator.unobtrusive.adapters.add("confirmationpasswordmatched", ['passwordfield'], function (options) {
    options.rules["confirmationpasswordmatched"] = [options.params.passwordfield];
    options.messages["confirmationpasswordmatched"] = [options.message];
});
// #endregion----end of Password and ConfirmationPassword Validator-----

// #region-------KlarnaPrivateFormatValidator------
$.validator.addMethod("klarnaformatvalid", function (value, element, params) {
    var inputValue = $(element).val();
    var pattern = new RegExp(params[0], 'i');

    var n = inputValue.search(pattern);
    return n == 0;
});
jQuery.validator.unobtrusive.adapters.add("klarnaformatvalid", ['patternproperty'], function (options) {
    options.rules["klarnaformatvalid"] = [options.params.patternproperty];
    options.messages["klarnaformatvalid"] = [options.message];
});
// #endregion---end of KlarnaPrivateFormatValidator---

// #region---SenderTelephoneValidator---
$.validator.addMethod("sendertelephonevalid", function (value, element, params) {
    var phoneTypeInput = $('input[name="Sender.ChoosenPhoneType"]:checked');
    var phoneType = phoneTypeInput.length > 0 ? phoneTypeInput.val() : $("#Sender_ChoosenPhoneType").val();
    var choosenPaymentMethod = $('input[name="ChosenPaymentMethod"]:checked').val();
    choosenPaymentMethod = choosenPaymentMethod || $('input[name="payment-method"]:checked').data('paymentmethodname');

    if (params[0].PaymentMethods.indexOf(choosenPaymentMethod) == -1)
        return true;

    if (phoneType === undefined)
        phoneType = "Landline";

    if (phoneType != params[0].PhoneType || params[0].EnhancedValidation == false) {
        return !((phoneType == "Landline" || phoneType == undefined) && value == "");
    }
    else {
        var pattern;

        switch (phoneType) {
            case "Landline":
                pattern = params[0].Landline;
                break;
            case "Mobile":
                pattern = params[0].Mobile;
                break;
        }

        var regexp = new RegExp(pattern, "i");
        var result = value.search(regexp);

        return result == 0;
    }
});
jQuery.validator.unobtrusive.adapters.add("sendertelephonevalid", ['sendertelephonepatterns'], function (options) {
    options.rules["sendertelephonevalid"] = [JSON.parse(options.params.sendertelephonepatterns)];
    options.messages["sendertelephonevalid"] = [options.message];
});
// #endregion

// #region CustomEmailValidator
$.validator.addMethod("customemail", function (value, element, params) {
    var pattern = params[0];
    var regex = new RegExp(pattern);
    return regex.test(value);
});
$.validator.unobtrusive.adapters.add("customemail", ['patternproperty'], function (options) {
    options.rules["customemail"] = [options.params.patternproperty];
    options.messages["customemail"] = [options.message];
});

// #endregion

//Quantity
$.validator.unobtrusive.adapters.add("minvalue", function (options) {
    options.rules["minvalue"] = [];
    options.messages["minvalue"] = [options.message];
});

$.validator.addMethod("quantityvalid", function (value, element, params) {

    return parseInt($(element).val()) > 0;
});

$.validator.unobtrusive.adapters.add("quantityvalid", ['minvalue'], function (options) {
    options.rules["quantityvalid"] = [options.params.minvalue];
    options.messages["quantityvalid"] = [options.message];
});

$.validator.unobtrusive.addValidation('form#fSearch');
$.validator.unobtrusive.addValidation('#logIn');
$.validator.unobtrusive.addValidation('#productDetailForm');

// #region RecipientExt telephone pattern

$.validator.addMethod("recipientexttelephonepattern", function (value, element, params) {
	var pattern = params[0];
	var regex = new RegExp(pattern);
	return regex.test(value);
});
$.validator.unobtrusive.adapters.add("recipientexttelephonepattern", ['patternproperty'], function (options) {
	options.rules["recipientexttelephonepattern"] = [options.params.patternproperty];
	options.messages["recipientexttelephonepattern"] = [options.message];
});

// #endregion

// #region Swish telephon pattern

$.validator.addMethod("swishtelephonevalid", function (value, element, params) {
    var pattern = params[0].slice(1, -1);
    var regex = new RegExp(pattern);
    return regex.test(value);
});
$.validator.unobtrusive.adapters.add("swishtelephonevalid", ["swishtelephonepattern"], function (options) {
    options.rules["swishtelephonevalid"] = [options.params.swishtelephonepattern];
    options.messages["swishtelephonevalid"] = [options.message];
});

// #endregion

$.validator.addMethod("itemFromArray", function (value, element, list) {
    return list.includes(value);
});;
function closestPolyfill() {
    if (!Element.prototype.matches) {
        Element.prototype.matches = Element.prototype.msMatchesSelector ||
            Element.prototype.webkitMatchesSelector;
    }

    if (!Element.prototype.closest) {
        Element.prototype.closest = function (s) {
            var el = this;

            do {
                if (el.matches(s)) return el;
                el = el.parentElement || el.parentNode;
            } while (el !== null && el.nodeType === 1);
            return null;
        };
    }
}

(function () {

    if (typeof window.CustomEvent === "function") return false;

    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;

    closestPolyfill();
})();
;
(function (window, factory) {
    var lazySizes = factory(window, window.document);
    window.lazySizes = lazySizes;
    if (typeof module == 'object' && module.exports) {
        module.exports = lazySizes;
    } else if (typeof define == 'function' && define.amd) {
        define(lazySizes);
    }
}(window, function (window, document) {
    'use strict';
    /*jshint eqnull:true */
    if (!document.getElementsByClassName) { return; }

    var lazySizesConfig;

    var docElem = document.documentElement;

    var addEventListener = window.addEventListener;

    var setTimeout = window.setTimeout;

    var rAF = window.requestAnimationFrame || setTimeout;

    var setImmediate = window.setImmediate || setTimeout;

    var regPicture = /^picture$/i;

    var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];

    var hasClass = function (ele, cls) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        return ele.className.match(reg) && reg;
    };

    var addClass = function (ele, cls) {
        if (!hasClass(ele, cls)) {
            ele.className += ' ' + cls;
        }
    };

    var removeClass = function (ele, cls) {
        var reg;
        if ((reg = hasClass(ele, cls))) {
            ele.className = ele.className.replace(reg, ' ');
        }
    };

    var addRemoveLoadEvents = function (dom, fn, add) {
        var action = add ? 'addEventListener' : 'removeEventListener';
        if (add) {
            addRemoveLoadEvents(dom, fn);
        }
        loadEvents.forEach(function (evt) {
            dom[action](evt, fn);
        });
    };

    var triggerEvent = function (elem, name, detail, noBubbles, noCancelable) {
        var event = document.createEvent('CustomEvent');

        event.initCustomEvent(name, !noBubbles, !noCancelable, detail || {});

        elem.dispatchEvent(event);
        return event;
    };

    var updatePolyfill = function (el, full) {
        var polyfill;
        if (!window.HTMLPictureElement) {
            if ((polyfill = (window.picturefill || window.respimage || lazySizesConfig.pf))) {
                polyfill({ reevaluate: true, elements: [el] });
            } else if (full && full.src) {
                el.src = full.src;
            }
        }
    };

    var getCSS = function (elem, style) {
        return (getComputedStyle(elem, null) || {})[style];
    };

    var getWidth = function (elem, parent, width) {
        width = width || elem.offsetWidth;

        while (width < lazySizesConfig.minSize && parent && !elem._lazysizesWidth) {
            width = parent.offsetWidth;
            parent = parent.parentNode;
        }

        return width;
    };

    var throttle = function (fn) {
        var running;
        var lastTime = 0;
        var Date = window.Date;
        var run = function () {
            running = false;
            lastTime = Date.now();
            fn();
        };
        var afterAF = function () {
            setImmediate(run);
        };
        var getAF = function () {
            rAF(afterAF);
        };

        return function () {
            if (running) {
                return;
            }
            var delay = lazySizesConfig.throttle - (Date.now() - lastTime);

            running = true;

            if (delay < 6) {
                delay = 6;
            }
            setTimeout(getAF, delay);
        };
    };

    var loader = (function () {
        var lazyloadElems, preloadElems, isCompleted, resetPreloadingTimer, loadMode;

        var eLvW, elvH, eLtop, eLleft, eLright, eLbottom;

        var defaultExpand, preloadExpand;

        var regImg = /^img$/i;
        var regIframe = /^iframe$/i;

        var supportScroll = ('onscroll' in window) && !(/glebot/.test(navigator.userAgent));

        var shrinkExpand = 0;
        var currentExpand = 0;

        var isLoading = 0;
        var lowRuns = 0;

        var resetPreloading = function (e) {
            isLoading--;
            if (e && e.target) {
                addRemoveLoadEvents(e.target, resetPreloading);
            }

            if (!e || isLoading < 0 || !e.target) {
                isLoading = 0;
            }
        };

        var isNestedVisible = function (elem, elemExpand) {
            var outerRect;
            var parent = elem;
            var visible = getCSS(elem, 'visibility') != 'hidden';

            eLtop -= elemExpand;
            eLbottom += elemExpand;
            eLleft -= elemExpand;
            eLright += elemExpand;

            while (visible && (parent = parent.offsetParent)) {
                visible = ((getCSS(parent, 'opacity') || 1) > 0);

                if (visible && getCSS(parent, 'overflow') != 'visible') {
                    outerRect = parent.getBoundingClientRect();
                    visible = eLright > outerRect.left &&
                        eLleft < outerRect.right &&
                        eLbottom > outerRect.top - 1 &&
                        eLtop < outerRect.bottom + 1
                        ;
                }
            }

            return visible;
        };

        var checkElements = function () {
            var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal, beforeExpandVal;

            if ((loadMode = lazySizesConfig.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)) {

                i = 0;

                lowRuns++;

                if (currentExpand < preloadExpand && isLoading < 1 && lowRuns > 3 && loadMode > 2) {
                    currentExpand = preloadExpand;
                    lowRuns = 0;
                } else if (currentExpand != defaultExpand && loadMode > 1 && lowRuns > 2 && isLoading < 6) {
                    currentExpand = defaultExpand;
                } else {
                    currentExpand = shrinkExpand;
                }

                for (; i < eLlen; i++) {

                    if (!lazyloadElems[i] || lazyloadElems[i]._lazyRace) { continue; }

                    if (!supportScroll) { unveilElement(lazyloadElems[i]); continue; }

                    if (!(elemExpandVal = lazyloadElems[i].getAttribute('data-expand')) || !(elemExpand = elemExpandVal * 1)) {
                        elemExpand = currentExpand;
                    }

                    if (beforeExpandVal !== elemExpand) {
                        eLvW = innerWidth + elemExpand;
                        elvH = innerHeight + elemExpand;
                        elemNegativeExpand = elemExpand * -1;
                        beforeExpandVal = elemExpand;
                    }

                    rect = lazyloadElems[i].getBoundingClientRect();

                    if ((eLbottom = rect.bottom) >= elemNegativeExpand &&
                        (eLtop = rect.top) <= elvH &&
                        (eLright = rect.right) >= elemNegativeExpand &&
                        (eLleft = rect.left) <= eLvW &&
                        (eLbottom || eLright || eLleft || eLtop) &&
                        ((isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4)) || isNestedVisible(lazyloadElems[i], elemExpand))) {
                        unveilElement(lazyloadElems[i], rect.width);
                        loadedSomething = true;
                        if (isLoading > 9) { break; }
                    } else if (!loadedSomething && isCompleted && !autoLoadElem &&
                        isLoading < 3 && lowRuns < 4 && loadMode > 2 &&
                        (preloadElems[0] || lazySizesConfig.preloadAfterLoad) &&
                        (preloadElems[0] || (!elemExpandVal && ((eLbottom || eLright || eLleft || eLtop) || lazyloadElems[i].getAttribute(lazySizesConfig.sizesAttr) != 'auto')))) {
                        autoLoadElem = preloadElems[0] || lazyloadElems[i];
                    }
                }

                if (autoLoadElem && !loadedSomething) {
                    unveilElement(autoLoadElem);
                }
            }
        };

        var throttledCheckElements = throttle(checkElements);

        var switchLoadingClass = function (e) {
            addClass(e.target, lazySizesConfig.loadedClass);
            removeClass(e.target, lazySizesConfig.loadingClass);
            addRemoveLoadEvents(e.target, switchLoadingClass);
        };

        var changeIframeSrc = function (elem, src) {
            try {
                elem.contentWindow.location.replace(src);
            } catch (e) {
                elem.setAttribute('src', src);
            }
        };

        var rafBatch = (function () {
            var isRunning;
            var batch = [];
            var runBatch = function () {
                while (batch.length) {
                    (batch.shift())();
                }
                isRunning = false;
            };
            return function (fn) {
                batch.push(fn);
                if (!isRunning) {
                    isRunning = true;
                    rAF(runBatch);
                }
            };
        })();

        var unveilElement = function (elem, width) {
            var sources, i, len, sourceSrcset, src, srcset, parent, isPicture, event, firesLoad, customMedia;

            var isImg = regImg.test(elem.nodeName);

            //allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
            var sizes = isImg && (elem.getAttribute(lazySizesConfig.sizesAttr) || elem.getAttribute('sizes'));
            var isAuto = sizes == 'auto';

            if ((isAuto || !isCompleted) && isImg && (elem.src || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesConfig.errorClass)) { return; }

            elem._lazyRace = true;
            isLoading++;

            rafBatch(function lazyUnveil() {

                if (elem._lazyRace) {
                    delete elem._lazyRace;
                }

                removeClass(elem, lazySizesConfig.lazyClass);

                if (!(event = triggerEvent(elem, 'lazybeforeunveil')).defaultPrevented) {

                    if (sizes) {
                        if (isAuto) {
                            autoSizer.updateElem(elem, true, width);
                            addClass(elem, lazySizesConfig.autosizesClass);
                        } else {
                            elem.setAttribute('sizes', sizes);
                        }
                    }

                    srcset = elem.getAttribute(lazySizesConfig.srcsetAttr);
                    src = elem.getAttribute(lazySizesConfig.srcAttr);

                    if (isImg) {
                        parent = elem.parentNode;
                        isPicture = parent && regPicture.test(parent.nodeName || '');
                    }

                    firesLoad = event.detail.firesLoad || (('src' in elem) && (srcset || src || isPicture));

                    event = { target: elem };

                    if (firesLoad) {
                        addRemoveLoadEvents(elem, resetPreloading, true);
                        clearTimeout(resetPreloadingTimer);
                        resetPreloadingTimer = setTimeout(resetPreloading, 2500);

                        addClass(elem, lazySizesConfig.loadingClass);
                        addRemoveLoadEvents(elem, switchLoadingClass, true);
                    }

                    if (isPicture) {
                        sources = parent.getElementsByTagName('source');
                        for (i = 0, len = sources.length; i < len; i++) {
                            if ((customMedia = lazySizesConfig.customMedia[sources[i].getAttribute('data-media') || sources[i].getAttribute('media')])) {
                                sources[i].setAttribute('media', customMedia);
                            }
                            sourceSrcset = sources[i].getAttribute(lazySizesConfig.srcsetAttr);
                            if (sourceSrcset) {
                                sources[i].setAttribute('srcset', sourceSrcset);
                            }
                        }
                    }

                    if (srcset) {
                        elem.setAttribute('srcset', srcset);
                    } else if (src) {
                        if (regIframe.test(elem.nodeName)) {
                            changeIframeSrc(elem, src);
                        } else {
                            elem.setAttribute('src', src);
                        }
                    }

                    if (srcset || isPicture) {
                        updatePolyfill(elem, { src: src });
                    }
                }

                if (!firesLoad || elem.complete) {
                    if (firesLoad) {
                        resetPreloading(event);
                    } else {
                        isLoading--;
                    }
                    switchLoadingClass(event);
                }
            });
        };

        var onload = function () {
            var scrollTimer;
            var afterScroll = function () {
                lazySizesConfig.loadMode = 3;
                throttledCheckElements();
            };

            isCompleted = true;
            lowRuns += 8;

            lazySizesConfig.loadMode = 3;

            addEventListener('scroll', function () {
                if (lazySizesConfig.loadMode == 3) {
                    lazySizesConfig.loadMode = 2;
                }
                clearTimeout(scrollTimer);
                scrollTimer = setTimeout(afterScroll, 99);
            }, true);
        };

		/*
		var onload = function(){
			var scrollTimer, timestamp;
			var wait = 99;
			var afterScroll = function(){
				var last = (Date.now()) - timestamp;
				// if the latest call was less that the wait period ago
				// then we reset the timeout to wait for the difference
				if (last < wait) {
					scrollTimer = setTimeout(afterScroll, wait - last);
					// or if not we can null out the timer and run the latest
				} else {
					scrollTimer = null;
					lazySizesConfig.loadMode = 3;
					throttledCheckElements();
				}
			};
			isCompleted = true;
			lowRuns += 8;
			lazySizesConfig.loadMode = 3;
			addEventListener('scroll', function(){
				timestamp = Date.now();
				if(!scrollTimer){
					lazySizesConfig.loadMode = 2;
					scrollTimer = setTimeout(afterScroll, wait);
				}
			}, true);
		};
		*/

        return {
            _: function () {

                lazyloadElems = document.getElementsByClassName(lazySizesConfig.lazyClass);
                preloadElems = document.getElementsByClassName(lazySizesConfig.lazyClass + ' ' + lazySizesConfig.preloadClass);

                defaultExpand = lazySizesConfig.expand;
                preloadExpand = Math.round(defaultExpand * lazySizesConfig.expFactor);

                addEventListener('scroll', throttledCheckElements, true);

                addEventListener('resize', throttledCheckElements, true);

                if (window.MutationObserver) {
                    new MutationObserver(throttledCheckElements).observe(docElem, { childList: true, subtree: true, attributes: true });
                } else {
                    docElem.addEventListener('DOMNodeInserted', throttledCheckElements, true);
                    docElem.addEventListener('DOMAttrModified', throttledCheckElements, true);
                    setInterval(throttledCheckElements, 999);
                }

                addEventListener('hashchange', throttledCheckElements, true);

                //, 'fullscreenchange'
                ['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend', 'webkitAnimationEnd'].forEach(function (name) {
                    document.addEventListener(name, throttledCheckElements, true);
                });

                if ((/d$|^c/.test(document.readyState))) {
                    onload();
                } else {
                    addEventListener('load', onload);
                    document.addEventListener('DOMContentLoaded', throttledCheckElements);
                }

                throttledCheckElements();
            },
            checkElems: throttledCheckElements,
            unveil: unveilElement
        };
    })();


    var autoSizer = (function () {
        var autosizesElems;

        var sizeElement = function (elem, dataAttr, width) {
            var sources, i, len, event;
            var parent = elem.parentNode;

            if (parent) {
                width = getWidth(elem, parent, width);
                event = triggerEvent(elem, 'lazybeforesizes', { width: width, dataAttr: !!dataAttr });

                if (!event.defaultPrevented) {
                    width = event.detail.width;

                    if (width && width !== elem._lazysizesWidth) {
                        elem._lazysizesWidth = width;
                        width += 'px';
                        elem.setAttribute('sizes', width);

                        if (regPicture.test(parent.nodeName || '')) {
                            sources = parent.getElementsByTagName('source');
                            for (i = 0, len = sources.length; i < len; i++) {
                                sources[i].setAttribute('sizes', width);
                            }
                        }

                        if (!event.detail.dataAttr) {
                            updatePolyfill(elem, event.detail);
                        }
                    }
                }
            }
        };

        var updateElementsSizes = function () {
            var i;
            var len = autosizesElems.length;
            if (len) {
                i = 0;

                for (; i < len; i++) {
                    sizeElement(autosizesElems[i]);
                }
            }
        };

        var throttledUpdateElementsSizes = throttle(updateElementsSizes);

        return {
            _: function () {
                autosizesElems = document.getElementsByClassName(lazySizesConfig.autosizesClass);
                addEventListener('resize', throttledUpdateElementsSizes);
            },
            checkElems: throttledUpdateElementsSizes,
            updateElem: sizeElement
        };
    })();

    var init = function () {
        if (!init.i) {
            init.i = true;
            autoSizer._();
            loader._();
        }
    };

    (function () {
        var prop;
        var lazySizesDefaults = {
            lazyClass: 'lazyload',
            loadedClass: 'lazyloaded',
            loadingClass: 'lazyloading',
            preloadClass: 'lazypreload',
            errorClass: 'lazyerror',
            autosizesClass: 'lazyautosizes',
            srcAttr: 'data-src',
            srcsetAttr: 'data-srcset',
            sizesAttr: 'data-sizes',
            //preloadAfterLoad: false,
            minSize: 40,
            customMedia: {},
            init: true,
            expFactor: 2,
            expand: 200,
            loadMode: 2,
            throttle: 125
        };

        lazySizesConfig = window.lazySizesConfig || window.lazysizesConfig || {};

        for (prop in lazySizesDefaults) {
            if (!(prop in lazySizesConfig)) {
                lazySizesConfig[prop] = lazySizesDefaults[prop];
            }
        }

        window.lazySizesConfig = lazySizesConfig;

        setTimeout(function () {
            if (lazySizesConfig.init) {
                init();
            }
        });
    })();

    return {
        cfg: lazySizesConfig,
        autoSizer: autoSizer,
        loader: loader,
        init: init,
        uP: updatePolyfill,
        aC: addClass,
        rC: removeClass,
        hC: hasClass,
        fire: triggerEvent,
        gW: getWidth
    };
}));;
var page = 0,
    inCallback = false,
    hasReachedEndOfInfiniteScroll = false;

var scrollHandler = function () {
    if (hasReachedEndOfInfiniteScroll == false &&
            ($(window).scrollTop() == $(document).height() - $(window).height())) {
        loadMoreToInfiniteScrollTable(moreRowsUrl);
    }
}

var ulScrollHandler = function () {
    if (hasReachedEndOfInfiniteScroll == false &&
            ($(window).scrollTop() == $(document).height() - $(window).height())) {
        loadMoreToInfiniteScrollUl(moreRowsUrl);
    }
}

function loadMoreToInfiniteScrollUl(loadMoreRowsUrl) {
    if (page > -1 && !inCallback) {
        inCallback = true;
        page++;
        $("div#loading").show();
        $.ajax({
            type: 'GET',
            url: loadMoreRowsUrl,
            data: "pageNum=" + page,
            success: function (data, textstatus) {
                if (data != '') {
                    $("ul.infinite-scroll").append(data);
                }
                else {
                    page = -1;
                }

                inCallback = false;
                $("div#loading").hide();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
}

function loadMoreToInfiniteScrollTable(loadMoreRowsUrl) {
    if (page > -1 && !inCallback) {
        inCallback = true;
        page++;
        $("div#loading").show();
        $.ajax({
            type: 'GET',
            url: loadMoreRowsUrl,
            data: "pageNum=" + page,
            success: function (data, textstatus) {
                if (data != '') {
                    $("table.infinite-scroll > tbody").append(data);
                    $("table.infinite-scroll > tbody > tr:even").addClass("alt-row-class");
                    $("table.infinite-scroll > tbody > tr:odd").removeClass("alt-row-class");
                }
                else {
                    page = -1;
                }

                inCallback = false;
                $("div#loading").hide();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
}

function showNoMoreRecords() {
    hasReachedEndOfInfiniteScroll = true;
};
/*!
 * Bootstrap v3.4.0 (https://getbootstrap.com/)
 * Copyright 2011-2018 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");!function(t){"use strict";var e=jQuery.fn.jquery.split(" ")[0].split(".");if(e[0]<2&&e[1]<9||1==e[0]&&9==e[1]&&e[2]<1||3<e[0])throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(),function(n){"use strict";n.fn.emulateTransitionEnd=function(t){var e=!1,i=this;n(this).one("bsTransitionEnd",function(){e=!0});return setTimeout(function(){e||n(i).trigger(n.support.transition.end)},t),this},n(function(){n.support.transition=function o(){var t=document.createElement("bootstrap"),e={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var i in e)if(t.style[i]!==undefined)return{end:e[i]};return!1}(),n.support.transition&&(n.event.special.bsTransitionEnd={bindType:n.support.transition.end,delegateType:n.support.transition.end,handle:function(t){if(n(t.target).is(this))return t.handleObj.handler.apply(this,arguments)}})})}(jQuery),function(s){"use strict";var e='[data-dismiss="alert"]',a=function(t){s(t).on("click",e,this.close)};a.VERSION="3.4.0",a.TRANSITION_DURATION=150,a.prototype.close=function(t){var e=s(this),i=e.attr("data-target");i||(i=(i=e.attr("href"))&&i.replace(/.*(?=#[^\s]*$)/,"")),i="#"===i?[]:i;var o=s(document).find(i);function n(){o.detach().trigger("closed.bs.alert").remove()}t&&t.preventDefault(),o.length||(o=e.closest(".alert")),o.trigger(t=s.Event("close.bs.alert")),t.isDefaultPrevented()||(o.removeClass("in"),s.support.transition&&o.hasClass("fade")?o.one("bsTransitionEnd",n).emulateTransitionEnd(a.TRANSITION_DURATION):n())};var t=s.fn.alert;s.fn.alert=function o(i){return this.each(function(){var t=s(this),e=t.data("bs.alert");e||t.data("bs.alert",e=new a(this)),"string"==typeof i&&e[i].call(t)})},s.fn.alert.Constructor=a,s.fn.alert.noConflict=function(){return s.fn.alert=t,this},s(document).on("click.bs.alert.data-api",e,a.prototype.close)}(jQuery),function(s){"use strict";var n=function(t,e){this.$element=s(t),this.options=s.extend({},n.DEFAULTS,e),this.isLoading=!1};function i(o){return this.each(function(){var t=s(this),e=t.data("bs.button"),i="object"==typeof o&&o;e||t.data("bs.button",e=new n(this,i)),"toggle"==o?e.toggle():o&&e.setState(o)})}n.VERSION="3.4.0",n.DEFAULTS={loadingText:"loading..."},n.prototype.setState=function(t){var e="disabled",i=this.$element,o=i.is("input")?"val":"html",n=i.data();t+="Text",null==n.resetText&&i.data("resetText",i[o]()),setTimeout(s.proxy(function(){i[o](null==n[t]?this.options[t]:n[t]),"loadingText"==t?(this.isLoading=!0,i.addClass(e).attr(e,e).prop(e,!0)):this.isLoading&&(this.isLoading=!1,i.removeClass(e).removeAttr(e).prop(e,!1))},this),0)},n.prototype.toggle=function(){var t=!0,e=this.$element.closest('[data-toggle="buttons"]');if(e.length){var i=this.$element.find("input");"radio"==i.prop("type")?(i.prop("checked")&&(t=!1),e.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==i.prop("type")&&(i.prop("checked")!==this.$element.hasClass("active")&&(t=!1),this.$element.toggleClass("active")),i.prop("checked",this.$element.hasClass("active")),t&&i.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var t=s.fn.button;s.fn.button=i,s.fn.button.Constructor=n,s.fn.button.noConflict=function(){return s.fn.button=t,this},s(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(t){var e=s(t.target).closest(".btn");i.call(e,"toggle"),s(t.target).is('input[type="radio"], input[type="checkbox"]')||(t.preventDefault(),e.is("input,button")?e.trigger("focus"):e.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(t){s(t.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(t.type))})}(jQuery),function(p){"use strict";var c=function(t,e){this.$element=p(t),this.$indicators=this.$element.find(".carousel-indicators"),this.options=e,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",p.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",p.proxy(this.pause,this)).on("mouseleave.bs.carousel",p.proxy(this.cycle,this))};function r(n){return this.each(function(){var t=p(this),e=t.data("bs.carousel"),i=p.extend({},c.DEFAULTS,t.data(),"object"==typeof n&&n),o="string"==typeof n?n:i.slide;e||t.data("bs.carousel",e=new c(this,i)),"number"==typeof n?e.to(n):o?e[o]():i.interval&&e.pause().cycle()})}c.VERSION="3.4.0",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(t){if(!/input|textarea/i.test(t.target.tagName)){switch(t.which){case 37:this.prev();break;case 39:this.next();break;default:return}t.preventDefault()}},c.prototype.cycle=function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(p.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(t){return this.$items=t.parent().children(".item"),this.$items.index(t||this.$active)},c.prototype.getItemForDirection=function(t,e){var i=this.getItemIndex(e);if(("prev"==t&&0===i||"next"==t&&i==this.$items.length-1)&&!this.options.wrap)return e;var o=(i+("prev"==t?-1:1))%this.$items.length;return this.$items.eq(o)},c.prototype.to=function(t){var e=this,i=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(t>this.$items.length-1||t<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){e.to(t)}):i==t?this.pause().cycle():this.slide(i<t?"next":"prev",this.$items.eq(t))},c.prototype.pause=function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&p.support.transition&&(this.$element.trigger(p.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(t,e){var i=this.$element.find(".item.active"),o=e||this.getItemForDirection(t,i),n=this.interval,s="next"==t?"left":"right",a=this;if(o.hasClass("active"))return this.sliding=!1;var r=o[0],l=p.Event("slide.bs.carousel",{relatedTarget:r,direction:s});if(this.$element.trigger(l),!l.isDefaultPrevented()){if(this.sliding=!0,n&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var h=p(this.$indicators.children()[this.getItemIndex(o)]);h&&h.addClass("active")}var d=p.Event("slid.bs.carousel",{relatedTarget:r,direction:s});return p.support.transition&&this.$element.hasClass("slide")?(o.addClass(t),"object"==typeof o&&o.length&&o[0].offsetWidth,i.addClass(s),o.addClass(s),i.one("bsTransitionEnd",function(){o.removeClass([t,s].join(" ")).addClass("active"),i.removeClass(["active",s].join(" ")),a.sliding=!1,setTimeout(function(){a.$element.trigger(d)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(i.removeClass("active"),o.addClass("active"),this.sliding=!1,this.$element.trigger(d)),n&&this.cycle(),this}};var t=p.fn.carousel;p.fn.carousel=r,p.fn.carousel.Constructor=c,p.fn.carousel.noConflict=function(){return p.fn.carousel=t,this};var e=function(t){var e=p(this),i=e.attr("href");i&&(i=i.replace(/.*(?=#[^\s]+$)/,""));var o=e.attr("data-target")||i,n=p(document).find(o);if(n.hasClass("carousel")){var s=p.extend({},n.data(),e.data()),a=e.attr("data-slide-to");a&&(s.interval=!1),r.call(n,s),a&&n.data("bs.carousel").to(a),t.preventDefault()}};p(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),p(window).on("load",function(){p('[data-ride="carousel"]').each(function(){var t=p(this);r.call(t,t.data())})})}(jQuery),function(a){"use strict";var r=function(t,e){this.$element=a(t),this.options=a.extend({},r.DEFAULTS,e),this.$trigger=a('[data-toggle="collapse"][href="#'+t.id+'"],[data-toggle="collapse"][data-target="#'+t.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};function n(t){var e,i=t.attr("data-target")||(e=t.attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"");return a(document).find(i)}function l(o){return this.each(function(){var t=a(this),e=t.data("bs.collapse"),i=a.extend({},r.DEFAULTS,t.data(),"object"==typeof o&&o);!e&&i.toggle&&/show|hide/.test(o)&&(i.toggle=!1),e||t.data("bs.collapse",e=new r(this,i)),"string"==typeof o&&e[o]()})}r.VERSION="3.4.0",r.TRANSITION_DURATION=350,r.DEFAULTS={toggle:!0},r.prototype.dimension=function(){return this.$element.hasClass("width")?"width":"height"},r.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var t,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(t=e.data("bs.collapse"))&&t.transitioning)){var i=a.Event("show.bs.collapse");if(this.$element.trigger(i),!i.isDefaultPrevented()){e&&e.length&&(l.call(e,"hide"),t||e.data("bs.collapse",null));var o=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[o](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var n=function(){this.$element.removeClass("collapsing").addClass("collapse in")[o](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return n.call(this);var s=a.camelCase(["scroll",o].join("-"));this.$element.one("bsTransitionEnd",a.proxy(n,this)).emulateTransitionEnd(r.TRANSITION_DURATION)[o](this.$element[0][s])}}}},r.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var t=a.Event("hide.bs.collapse");if(this.$element.trigger(t),!t.isDefaultPrevented()){var e=this.dimension();this.$element[e](this.$element[e]())[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 i=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};if(!a.support.transition)return i.call(this);this.$element[e](0).one("bsTransitionEnd",a.proxy(i,this)).emulateTransitionEnd(r.TRANSITION_DURATION)}}},r.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},r.prototype.getParent=function(){return a(document).find(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(t,e){var i=a(e);this.addAriaAndCollapsedClass(n(i),i)},this)).end()},r.prototype.addAriaAndCollapsedClass=function(t,e){var i=t.hasClass("in");t.attr("aria-expanded",i),e.toggleClass("collapsed",!i).attr("aria-expanded",i)};var t=a.fn.collapse;a.fn.collapse=l,a.fn.collapse.Constructor=r,a.fn.collapse.noConflict=function(){return a.fn.collapse=t,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(t){var e=a(this);e.attr("data-target")||t.preventDefault();var i=n(e),o=i.data("bs.collapse")?"toggle":e.data();l.call(i,o)})}(jQuery),function(a){"use strict";var r='[data-toggle="dropdown"]',o=function(t){a(t).on("click.bs.dropdown",this.toggle)};function l(t){var e=t.attr("data-target");e||(e=(e=t.attr("href"))&&/#[A-Za-z]/.test(e)&&e.replace(/.*(?=#[^\s]*$)/,""));var i=e&&a(document).find(e);return i&&i.length?i:t.parent()}function s(o){o&&3===o.which||(a(".dropdown-backdrop").remove(),a(r).each(function(){var t=a(this),e=l(t),i={relatedTarget:this};e.hasClass("open")&&(o&&"click"==o.type&&/input|textarea/i.test(o.target.tagName)&&a.contains(e[0],o.target)||(e.trigger(o=a.Event("hide.bs.dropdown",i)),o.isDefaultPrevented()||(t.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",i)))))}))}o.VERSION="3.4.0",o.prototype.toggle=function(t){var e=a(this);if(!e.is(".disabled, :disabled")){var i=l(e),o=i.hasClass("open");if(s(),!o){"ontouchstart"in document.documentElement&&!i.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",s);var n={relatedTarget:this};if(i.trigger(t=a.Event("show.bs.dropdown",n)),t.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),i.toggleClass("open").trigger(a.Event("shown.bs.dropdown",n))}return!1}},o.prototype.keydown=function(t){if(/(38|40|27|32)/.test(t.which)&&!/input|textarea/i.test(t.target.tagName)){var e=a(this);if(t.preventDefault(),t.stopPropagation(),!e.is(".disabled, :disabled")){var i=l(e),o=i.hasClass("open");if(!o&&27!=t.which||o&&27==t.which)return 27==t.which&&i.find(r).trigger("focus"),e.trigger("click");var n=i.find(".dropdown-menu li:not(.disabled):visible a");if(n.length){var s=n.index(t.target);38==t.which&&0<s&&s--,40==t.which&&s<n.length-1&&s++,~s||(s=0),n.eq(s).trigger("focus")}}}};var t=a.fn.dropdown;a.fn.dropdown=function e(i){return this.each(function(){var t=a(this),e=t.data("bs.dropdown");e||t.data("bs.dropdown",e=new o(this)),"string"==typeof i&&e[i].call(t)})},a.fn.dropdown.Constructor=o,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=t,this},a(document).on("click.bs.dropdown.data-api",s).on("click.bs.dropdown.data-api",".dropdown form",function(t){t.stopPropagation()}).on("click.bs.dropdown.data-api",r,o.prototype.toggle).on("keydown.bs.dropdown.data-api",r,o.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",o.prototype.keydown)}(jQuery),function(a){"use strict";var s=function(t,e){this.options=e,this.$body=a(document.body),this.$element=a(t),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.fixedContent=".navbar-fixed-top, .navbar-fixed-bottom",this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};function r(o,n){return this.each(function(){var t=a(this),e=t.data("bs.modal"),i=a.extend({},s.DEFAULTS,t.data(),"object"==typeof o&&o);e||t.data("bs.modal",e=new s(this,i)),"string"==typeof o?e[o](n):i.show&&e.show(n)})}s.VERSION="3.4.0",s.TRANSITION_DURATION=300,s.BACKDROP_TRANSITION_DURATION=150,s.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},s.prototype.toggle=function(t){return this.isShown?this.hide():this.show(t)},s.prototype.show=function(i){var o=this,t=a.Event("show.bs.modal",{relatedTarget:i});this.$element.trigger(t),this.isShown||t.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(){o.$element.one("mouseup.dismiss.bs.modal",function(t){a(t.target).is(o.$element)&&(o.ignoreBackdropClick=!0)})}),this.backdrop(function(){var t=a.support.transition&&o.$element.hasClass("fade");o.$element.parent().length||o.$element.appendTo(o.$body),o.$element.show().scrollTop(0),o.adjustDialog(),t&&o.$element[0].offsetWidth,o.$element.addClass("in"),o.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:i});t?o.$dialog.one("bsTransitionEnd",function(){o.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(s.TRANSITION_DURATION):o.$element.trigger("focus").trigger(e)}))},s.prototype.hide=function(t){t&&t.preventDefault(),t=a.Event("hide.bs.modal"),this.$element.trigger(t),this.isShown&&!t.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(s.TRANSITION_DURATION):this.hideModal())},s.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(t){document===t.target||this.$element[0]===t.target||this.$element.has(t.target).length||this.$element.trigger("focus")},this))},s.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(t){27==t.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},s.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},s.prototype.hideModal=function(){var t=this;this.$element.hide(),this.backdrop(function(){t.$body.removeClass("modal-open"),t.resetAdjustments(),t.resetScrollbar(),t.$element.trigger("hidden.bs.modal")})},s.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},s.prototype.backdrop=function(t){var e=this,i=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var o=a.support.transition&&i;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+i).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(t){this.ignoreBackdropClick?this.ignoreBackdropClick=!1:t.target===t.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide())},this)),o&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!t)return;o?this.$backdrop.one("bsTransitionEnd",t).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION):t()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var n=function(){e.removeBackdrop(),t&&t()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",n).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION):n()}else t&&t()},s.prototype.handleUpdate=function(){this.adjustDialog()},s.prototype.adjustDialog=function(){var t=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&t?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!t?this.scrollbarWidth:""})},s.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},s.prototype.checkScrollbar=function(){var t=window.innerWidth;if(!t){var e=document.documentElement.getBoundingClientRect();t=e.right-Math.abs(e.left)}this.bodyIsOverflowing=document.body.clientWidth<t,this.scrollbarWidth=this.measureScrollbar()},s.prototype.setScrollbar=function(){var t=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"";var n=this.scrollbarWidth;this.bodyIsOverflowing&&(this.$body.css("padding-right",t+n),a(this.fixedContent).each(function(t,e){var i=e.style.paddingRight,o=a(e).css("padding-right");a(e).data("padding-right",i).css("padding-right",parseFloat(o)+n+"px")}))},s.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad),a(this.fixedContent).each(function(t,e){var i=a(e).data("padding-right");a(e).removeData("padding-right"),e.style.paddingRight=i||""})},s.prototype.measureScrollbar=function(){var t=document.createElement("div");t.className="modal-scrollbar-measure",this.$body.append(t);var e=t.offsetWidth-t.clientWidth;return this.$body[0].removeChild(t),e};var t=a.fn.modal;a.fn.modal=r,a.fn.modal.Constructor=s,a.fn.modal.noConflict=function(){return a.fn.modal=t,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(t){var e=a(this),i=e.attr("href"),o=e.attr("data-target")||i&&i.replace(/.*(?=#[^\s]+$)/,""),n=a(document).find(o),s=n.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(i)&&i},n.data(),e.data());e.is("a")&&t.preventDefault(),n.one("show.bs.modal",function(t){t.isDefaultPrevented()||n.one("hidden.bs.modal",function(){e.is(":visible")&&e.trigger("focus")})}),r.call(n,s,this)})}(jQuery),function(g){"use strict";var m=function(t,e){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",t,e)};m.VERSION="3.4.0",m.TRANSITION_DURATION=150,m.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}},m.prototype.init=function(t,e,i){if(this.enabled=!0,this.type=t,this.$element=g(e),this.options=this.getOptions(i),this.$viewport=this.options.viewport&&g(document).find(g.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 o=this.options.trigger.split(" "),n=o.length;n--;){var s=o[n];if("click"==s)this.$element.on("click."+this.type,this.options.selector,g.proxy(this.toggle,this));else if("manual"!=s){var a="hover"==s?"mouseenter":"focusin",r="hover"==s?"mouseleave":"focusout";this.$element.on(a+"."+this.type,this.options.selector,g.proxy(this.enter,this)),this.$element.on(r+"."+this.type,this.options.selector,g.proxy(this.leave,this))}}this.options.selector?this._options=g.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},m.prototype.getDefaults=function(){return m.DEFAULTS},m.prototype.getOptions=function(t){return(t=g.extend({},this.getDefaults(),this.$element.data(),t)).delay&&"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),t},m.prototype.getDelegateOptions=function(){var i={},o=this.getDefaults();return this._options&&g.each(this._options,function(t,e){o[t]!=e&&(i[t]=e)}),i},m.prototype.enter=function(t){var e=t instanceof this.constructor?t:g(t.currentTarget).data("bs."+this.type);if(e||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e)),t instanceof g.Event&&(e.inState["focusin"==t.type?"focus":"hover"]=!0),e.tip().hasClass("in")||"in"==e.hoverState)e.hoverState="in";else{if(clearTimeout(e.timeout),e.hoverState="in",!e.options.delay||!e.options.delay.show)return e.show();e.timeout=setTimeout(function(){"in"==e.hoverState&&e.show()},e.options.delay.show)}},m.prototype.isInStateTrue=function(){for(var t in this.inState)if(this.inState[t])return!0;return!1},m.prototype.leave=function(t){var e=t instanceof this.constructor?t:g(t.currentTarget).data("bs."+this.type);if(e||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e)),t instanceof g.Event&&(e.inState["focusout"==t.type?"focus":"hover"]=!1),!e.isInStateTrue()){if(clearTimeout(e.timeout),e.hoverState="out",!e.options.delay||!e.options.delay.hide)return e.hide();e.timeout=setTimeout(function(){"out"==e.hoverState&&e.hide()},e.options.delay.hide)}},m.prototype.show=function(){var t=g.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(t);var e=g.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(t.isDefaultPrevented()||!e)return;var i=this,o=this.tip(),n=this.getUID(this.type);this.setContent(),o.attr("id",n),this.$element.attr("aria-describedby",n),this.options.animation&&o.addClass("fade");var s="function"==typeof this.options.placement?this.options.placement.call(this,o[0],this.$element[0]):this.options.placement,a=/\s?auto?\s?/i,r=a.test(s);r&&(s=s.replace(a,"")||"top"),o.detach().css({top:0,left:0,display:"block"}).addClass(s).data("bs."+this.type,this),this.options.container?o.appendTo(g(document).find(this.options.container)):o.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var l=this.getPosition(),h=o[0].offsetWidth,d=o[0].offsetHeight;if(r){var p=s,c=this.getPosition(this.$viewport);s="bottom"==s&&l.bottom+d>c.bottom?"top":"top"==s&&l.top-d<c.top?"bottom":"right"==s&&l.right+h>c.width?"left":"left"==s&&l.left-h<c.left?"right":s,o.removeClass(p).addClass(s)}var f=this.getCalculatedOffset(s,l,h,d);this.applyPlacement(f,s);var u=function(){var t=i.hoverState;i.$element.trigger("shown.bs."+i.type),i.hoverState=null,"out"==t&&i.leave(i)};g.support.transition&&this.$tip.hasClass("fade")?o.one("bsTransitionEnd",u).emulateTransitionEnd(m.TRANSITION_DURATION):u()}},m.prototype.applyPlacement=function(t,e){var i=this.tip(),o=i[0].offsetWidth,n=i[0].offsetHeight,s=parseInt(i.css("margin-top"),10),a=parseInt(i.css("margin-left"),10);isNaN(s)&&(s=0),isNaN(a)&&(a=0),t.top+=s,t.left+=a,g.offset.setOffset(i[0],g.extend({using:function(t){i.css({top:Math.round(t.top),left:Math.round(t.left)})}},t),0),i.addClass("in");var r=i[0].offsetWidth,l=i[0].offsetHeight;"top"==e&&l!=n&&(t.top=t.top+n-l);var h=this.getViewportAdjustedDelta(e,t,r,l);h.left?t.left+=h.left:t.top+=h.top;var d=/top|bottom/.test(e),p=d?2*h.left-o+r:2*h.top-n+l,c=d?"offsetWidth":"offsetHeight";i.offset(t),this.replaceArrow(p,i[0][c],d)},m.prototype.replaceArrow=function(t,e,i){this.arrow().css(i?"left":"top",50*(1-t/e)+"%").css(i?"top":"left","")},m.prototype.setContent=function(){var t=this.tip(),e=this.getTitle();t.find(".tooltip-inner")[this.options.html?"html":"text"](e),t.removeClass("fade in top bottom left right")},m.prototype.hide=function(t){var e=this,i=g(this.$tip),o=g.Event("hide.bs."+this.type);function n(){"in"!=e.hoverState&&i.detach(),e.$element&&e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),t&&t()}if(this.$element.trigger(o),!o.isDefaultPrevented())return i.removeClass("in"),g.support.transition&&i.hasClass("fade")?i.one("bsTransitionEnd",n).emulateTransitionEnd(m.TRANSITION_DURATION):n(),this.hoverState=null,this},m.prototype.fixTitle=function(){var t=this.$element;(t.attr("title")||"string"!=typeof t.attr("data-original-title"))&&t.attr("data-original-title",t.attr("title")||"").attr("title","")},m.prototype.hasContent=function(){return this.getTitle()},m.prototype.getPosition=function(t){var e=(t=t||this.$element)[0],i="BODY"==e.tagName,o=e.getBoundingClientRect();null==o.width&&(o=g.extend({},o,{width:o.right-o.left,height:o.bottom-o.top}));var n=window.SVGElement&&e instanceof window.SVGElement,s=i?{top:0,left:0}:n?null:t.offset(),a={scroll:i?document.documentElement.scrollTop||document.body.scrollTop:t.scrollTop()},r=i?{width:g(window).width(),height:g(window).height()}:null;return g.extend({},o,a,r,s)},m.prototype.getCalculatedOffset=function(t,e,i,o){return"bottom"==t?{top:e.top+e.height,left:e.left+e.width/2-i/2}:"top"==t?{top:e.top-o,left:e.left+e.width/2-i/2}:"left"==t?{top:e.top+e.height/2-o/2,left:e.left-i}:{top:e.top+e.height/2-o/2,left:e.left+e.width}},m.prototype.getViewportAdjustedDelta=function(t,e,i,o){var n={top:0,left:0};if(!this.$viewport)return n;var s=this.options.viewport&&this.options.viewport.padding||0,a=this.getPosition(this.$viewport);if(/right|left/.test(t)){var r=e.top-s-a.scroll,l=e.top+s-a.scroll+o;r<a.top?n.top=a.top-r:l>a.top+a.height&&(n.top=a.top+a.height-l)}else{var h=e.left-s,d=e.left+s+i;h<a.left?n.left=a.left-h:d>a.right&&(n.left=a.left+a.width-d)}return n},m.prototype.getTitle=function(){var t=this.$element,e=this.options;return t.attr("data-original-title")||("function"==typeof e.title?e.title.call(t[0]):e.title)},m.prototype.getUID=function(t){for(;t+=~~(1e6*Math.random()),document.getElementById(t););return t},m.prototype.tip=function(){if(!this.$tip&&(this.$tip=g(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},m.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},m.prototype.enable=function(){this.enabled=!0},m.prototype.disable=function(){this.enabled=!1},m.prototype.toggleEnabled=function(){this.enabled=!this.enabled},m.prototype.toggle=function(t){var e=this;t&&((e=g(t.currentTarget).data("bs."+this.type))||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e))),t?(e.inState.click=!e.inState.click,e.isInStateTrue()?e.enter(e):e.leave(e)):e.tip().hasClass("in")?e.leave(e):e.enter(e)},m.prototype.destroy=function(){var t=this;clearTimeout(this.timeout),this.hide(function(){t.$element.off("."+t.type).removeData("bs."+t.type),t.$tip&&t.$tip.detach(),t.$tip=null,t.$arrow=null,t.$viewport=null,t.$element=null})};var t=g.fn.tooltip;g.fn.tooltip=function e(o){return this.each(function(){var t=g(this),e=t.data("bs.tooltip"),i="object"==typeof o&&o;!e&&/destroy|hide/.test(o)||(e||t.data("bs.tooltip",e=new m(this,i)),"string"==typeof o&&e[o]())})},g.fn.tooltip.Constructor=m,g.fn.tooltip.noConflict=function(){return g.fn.tooltip=t,this}}(jQuery),function(n){"use strict";var s=function(t,e){this.init("popover",t,e)};if(!n.fn.tooltip)throw new Error("Popover requires tooltip.js");s.VERSION="3.4.0",s.DEFAULTS=n.extend({},n.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>'}),((s.prototype=n.extend({},n.fn.tooltip.Constructor.prototype)).constructor=s).prototype.getDefaults=function(){return s.DEFAULTS},s.prototype.setContent=function(){var t=this.tip(),e=this.getTitle(),i=this.getContent();t.find(".popover-title")[this.options.html?"html":"text"](e),t.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof i?"html":"append":"text"](i),t.removeClass("fade top bottom left right in"),t.find(".popover-title").html()||t.find(".popover-title").hide()},s.prototype.hasContent=function(){return this.getTitle()||this.getContent()},s.prototype.getContent=function(){var t=this.$element,e=this.options;return t.attr("data-content")||("function"==typeof e.content?e.content.call(t[0]):e.content)},s.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var t=n.fn.popover;n.fn.popover=function e(o){return this.each(function(){var t=n(this),e=t.data("bs.popover"),i="object"==typeof o&&o;!e&&/destroy|hide/.test(o)||(e||t.data("bs.popover",e=new s(this,i)),"string"==typeof o&&e[o]())})},n.fn.popover.Constructor=s,n.fn.popover.noConflict=function(){return n.fn.popover=t,this}}(jQuery),function(s){"use strict";function n(t,e){this.$body=s(document.body),this.$scrollElement=s(t).is(document.body)?s(window):s(t),this.options=s.extend({},n.DEFAULTS,e),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",s.proxy(this.process,this)),this.refresh(),this.process()}function e(o){return this.each(function(){var t=s(this),e=t.data("bs.scrollspy"),i="object"==typeof o&&o;e||t.data("bs.scrollspy",e=new n(this,i)),"string"==typeof o&&e[o]()})}n.VERSION="3.4.0",n.DEFAULTS={offset:10},n.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},n.prototype.refresh=function(){var t=this,o="offset",n=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),s.isWindow(this.$scrollElement[0])||(o="position",n=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var t=s(this),e=t.data("target")||t.attr("href"),i=/^#./.test(e)&&s(e);return i&&i.length&&i.is(":visible")&&[[i[o]().top+n,e]]||null}).sort(function(t,e){return t[0]-e[0]}).each(function(){t.offsets.push(this[0]),t.targets.push(this[1])})},n.prototype.process=function(){var t,e=this.$scrollElement.scrollTop()+this.options.offset,i=this.getScrollHeight(),o=this.options.offset+i-this.$scrollElement.height(),n=this.offsets,s=this.targets,a=this.activeTarget;if(this.scrollHeight!=i&&this.refresh(),o<=e)return a!=(t=s[s.length-1])&&this.activate(t);if(a&&e<n[0])return this.activeTarget=null,this.clear();for(t=n.length;t--;)a!=s[t]&&e>=n[t]&&(n[t+1]===undefined||e<n[t+1])&&this.activate(s[t])},n.prototype.activate=function(t){this.activeTarget=t,this.clear();var e=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',i=s(e).parents("li").addClass("active");i.parent(".dropdown-menu").length&&(i=i.closest("li.dropdown").addClass("active")),i.trigger("activate.bs.scrollspy")},n.prototype.clear=function(){s(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var t=s.fn.scrollspy;s.fn.scrollspy=e,s.fn.scrollspy.Constructor=n,s.fn.scrollspy.noConflict=function(){return s.fn.scrollspy=t,this},s(window).on("load.bs.scrollspy.data-api",function(){s('[data-spy="scroll"]').each(function(){var t=s(this);e.call(t,t.data())})})}(jQuery),function(r){"use strict";var a=function(t){this.element=r(t)};function e(i){return this.each(function(){var t=r(this),e=t.data("bs.tab");e||t.data("bs.tab",e=new a(this)),"string"==typeof i&&e[i]()})}a.VERSION="3.4.0",a.TRANSITION_DURATION=150,a.prototype.show=function(){var t=this.element,e=t.closest("ul:not(.dropdown-menu)"),i=t.data("target");if(i||(i=(i=t.attr("href"))&&i.replace(/.*(?=#[^\s]*$)/,"")),!t.parent("li").hasClass("active")){var o=e.find(".active:last a"),n=r.Event("hide.bs.tab",{relatedTarget:t[0]}),s=r.Event("show.bs.tab",{relatedTarget:o[0]});if(o.trigger(n),t.trigger(s),!s.isDefaultPrevented()&&!n.isDefaultPrevented()){var a=r(document).find(i);this.activate(t.closest("li"),e),this.activate(a,a.parent(),function(){o.trigger({type:"hidden.bs.tab",relatedTarget:t[0]}),t.trigger({type:"shown.bs.tab",relatedTarget:o[0]})})}}},a.prototype.activate=function(t,e,i){var o=e.find("> .active"),n=i&&r.support.transition&&(o.length&&o.hasClass("fade")||!!e.find("> .fade").length);function s(){o.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),t.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),n?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu").length&&t.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),i&&i()}o.length&&n?o.one("bsTransitionEnd",s).emulateTransitionEnd(a.TRANSITION_DURATION):s(),o.removeClass("in")};var t=r.fn.tab;r.fn.tab=e,r.fn.tab.Constructor=a,r.fn.tab.noConflict=function(){return r.fn.tab=t,this};var i=function(t){t.preventDefault(),e.call(r(this),"show")};r(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',i).on("click.bs.tab.data-api",'[data-toggle="pill"]',i)}(jQuery),function(l){"use strict";var h=function(t,e){this.options=l.extend({},h.DEFAULTS,e);var i=this.options.target===h.DEFAULTS.target?l(this.options.target):l(document).find(this.options.target);this.$target=i.on("scroll.bs.affix.data-api",l.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",l.proxy(this.checkPositionWithEventLoop,this)),this.$element=l(t),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};function i(o){return this.each(function(){var t=l(this),e=t.data("bs.affix"),i="object"==typeof o&&o;e||t.data("bs.affix",e=new h(this,i)),"string"==typeof o&&e[o]()})}h.VERSION="3.4.0",h.RESET="affix affix-top affix-bottom",h.DEFAULTS={offset:0,target:window},h.prototype.getState=function(t,e,i,o){var n=this.$target.scrollTop(),s=this.$element.offset(),a=this.$target.height();if(null!=i&&"top"==this.affixed)return n<i&&"top";if("bottom"==this.affixed)return null!=i?!(n+this.unpin<=s.top)&&"bottom":!(n+a<=t-o)&&"bottom";var r=null==this.affixed,l=r?n:s.top;return null!=i&&n<=i?"top":null!=o&&t-o<=l+(r?a:e)&&"bottom"},h.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(h.RESET).addClass("affix");var t=this.$target.scrollTop(),e=this.$element.offset();return this.pinnedOffset=e.top-t},h.prototype.checkPositionWithEventLoop=function(){setTimeout(l.proxy(this.checkPosition,this),1)},h.prototype.checkPosition=function(){if(this.$element.is(":visible")){var t=this.$element.height(),e=this.options.offset,i=e.top,o=e.bottom,n=Math.max(l(document).height(),l(document.body).height());"object"!=typeof e&&(o=i=e),"function"==typeof i&&(i=e.top(this.$element)),"function"==typeof o&&(o=e.bottom(this.$element));var s=this.getState(n,t,i,o);if(this.affixed!=s){null!=this.unpin&&this.$element.css("top","");var a="affix"+(s?"-"+s:""),r=l.Event(a+".bs.affix");if(this.$element.trigger(r),r.isDefaultPrevented())return;this.affixed=s,this.unpin="bottom"==s?this.getPinnedOffset():null,this.$element.removeClass(h.RESET).addClass(a).trigger(a.replace("affix","affixed")+".bs.affix")}"bottom"==s&&this.$element.offset({top:n-t-o})}};var t=l.fn.affix;l.fn.affix=i,l.fn.affix.Constructor=h,l.fn.affix.noConflict=function(){return l.fn.affix=t,this},l(window).on("load",function(){l('[data-spy="affix"]').each(function(){var t=l(this),e=t.data();e.offset=e.offset||{},null!=e.offsetBottom&&(e.offset.bottom=e.offsetBottom),null!=e.offsetTop&&(e.offset.top=e.offsetTop),i.call(t,e)})})}(jQuery);;
/*!
 * Bootstrap-select v1.7.2 (http://silviomoreto.github.io/bootstrap-select)
 *
 * Copyright 2013-2015 bootstrap-select
 * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
 */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module unless amdModuleId is set
        define(["jquery"], function (a0) {
            return (factory(a0));
        });
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory(require("jquery"));
    } else {
        factory(jQuery);
    }
}(this, function () {

    (function ($) {
        'use strict';

        //<editor-fold desc="Shims">
        if (!String.prototype.includes) {
            (function () {
                'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
                var toString = {}.toString;
                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 indexOf = ''.indexOf;
                var includes = function (search) {
                    if (this == null) {
                        throw TypeError();
                    }
                    var string = String(this);
                    if (search && toString.call(search) == '[object RegExp]') {
                        throw 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;
                    }
                    return indexOf.call(string, searchString, pos) != -1;
                };
                if (defineProperty) {
                    defineProperty(String.prototype, 'includes', {
                        'value': includes,
                        'configurable': true,
                        'writable': true
                    });
                } else {
                    String.prototype.includes = includes;
                }
            }());
        }

        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 TypeError();
                    }
                    var string = String(this);
                    if (search && toString.call(search) == '[object RegExp]') {
                        throw 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
            };
        }
        //</editor-fold>

        // Case insensitive contains search
        $.expr[':'].icontains = function (obj, index, meta) {
            var $obj = $(obj);
            var haystack = ($obj.data('tokens') || $obj.text()).toUpperCase();
            return haystack.includes(meta[3].toUpperCase());
        };

        // Case insensitive begins search
        $.expr[':'].ibegins = function (obj, index, meta) {
            var $obj = $(obj);
            var haystack = ($obj.data('tokens') || $obj.text()).toUpperCase();
            return haystack.startsWith(meta[3].toUpperCase());
        };

        // Case and accent insensitive contains search
        $.expr[':'].aicontains = function (obj, index, meta) {
            var $obj = $(obj);
            var haystack = ($obj.data('tokens') || $obj.data('normalizedText') || $obj.text()).toUpperCase();
            return haystack.includes(meta[3].toUpperCase());
        };

        // Case and accent insensitive begins search
        $.expr[':'].aibegins = function (obj, index, meta) {
            var $obj = $(obj);
            var haystack = ($obj.data('tokens') || $obj.data('normalizedText') || $obj.text()).toUpperCase();
            return haystack.startsWith(meta[3].toUpperCase());
        };

        /**
         * 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.replace(this.re, this.ch);
            });
            return text;
        }


        function htmlEscape(html) {
            var escapeMap = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#x27;',
                '`': '&#x60;'
            };
            var source = '(?:' + Object.keys(escapeMap).join('|') + ')',
                testRegexp = new RegExp(source),
                replaceRegexp = new RegExp(source, 'g'),
                string = html == null ? '' : '' + html;
            return testRegexp.test(string) ? string.replace(replaceRegexp, function (match) {
                return escapeMap[match];
            }) : string;
        }

        var Selectpicker = function (element, options, e) {
            if (e) {
                e.stopPropagation();
                e.preventDefault();
            }

            this.$element = $(element);
            this.$newElement = null;
            this.$button = null;
            this.$menu = null;
            this.$lis = null;
            this.options = options;

            // 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');
            }

            //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.remove;
            this.remove = Selectpicker.prototype.remove;
            this.show = Selectpicker.prototype.show;
            this.hide = Selectpicker.prototype.hide;

            this.init();
        };

        Selectpicker.VERSION = '1.7.2';

        // 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: 'btn-default form-control',
            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',
            maxOptions: false,
            mobile: false,
            selectOnTab: false,
            dropdownAlignRight: false
        };

        Selectpicker.prototype = {

            constructor: Selectpicker,

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

                this.$element.addClass('bs-select-hidden');
                // store originalIndex (key) and newIndex (value) in this.liObj for fast accessibility
                // allows us to do this.$lis.eq(that.liObj[index]) instead of this.$lis.filter('[data-original-index="' + index + '"]')
                this.liObj = {};
                this.multiple = this.$element.prop('multiple');
                this.autofocus = this.$element.prop('autofocus');
                this.$newElement = this.createView();
                this.$element.after(this.$newElement);
                this.$button = this.$newElement.children('button');
                this.$menu = this.$newElement.children('.dropdown-menu');
                this.$menuInner = this.$menu.children('.inner');
                this.$searchbox = this.$menu.find('input');

                if (this.options.dropdownAlignRight)
                    this.$menu.addClass('dropdown-menu-right');

                if (typeof id !== 'undefined') {
                    this.$button.attr('data-id', id);
                    $('label[for="' + id + '"]').click(function (e) {
                        e.preventDefault();
                        that.$button.focus();
                    });
                }

                this.checkDisabled();
                this.clickListener();
                if (this.options.liveSearch) this.liveSearchListener();
                this.render();
                this.setStyle();
                this.setWidth();
                if (this.options.container) this.selectPosition();
                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.$element.trigger('hide.bs.select', e);
                });

                this.$newElement.on('hidden.bs.dropdown', function (e) {
                    that.$element.trigger('hidden.bs.select', e);
                });

                this.$newElement.on('show.bs.dropdown', function (e) {
                    that.$element.trigger('show.bs.select', e);
                });

                this.$newElement.on('shown.bs.dropdown', function (e) {
                    that.$element.trigger('shown.bs.select', e);
                });

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

            createDropdown: function () {
                // Options
                // If we are multiple, then add the show-tick class by default
                var multiple = this.multiple ? ' show-tick' : '',
                    inputGroup = this.$element.parent().hasClass('input-group') ? ' input-group-btn' : '',
                    autofocus = this.autofocus ? ' autofocus' : '';
                // Elements
                var header = this.options.header ? '<div class="popover-title"><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) + '"') + '>' +
                '</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 btn-default">' +
                this.options.selectAllText +
                '</button>' +
                '<button type="button" class="actions-btn bs-deselect-all btn btn-default">' +
                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 btn-default">' +
                this.options.doneButtonText +
                '</button>' +
                '</div>' +
                '</div>'
                    : '';
                var drop =
                    '<div class="btn-group bootstrap-select' + multiple + inputGroup + '">' +
                    '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" data-toggle="dropdown"' + autofocus + '>' +
                    '<span class="filter-option pull-left"></span>&nbsp;' +
                    '<span class="caret"></span>' +
                    '</button>' +
                    '<div class="dropdown-menu open">' +
                    header +
                    searchbox +
                    actionsbox +
                    '<ul class="dropdown-menu inner" role="menu">' +
                    '</ul>' +
                    donebutton +
                    '</div>' +
                    '</div>';

                return $(drop);
            },

            createView: function () {
                var $drop = this.createDropdown(),
                    li = this.createLi();

                $drop.find('ul')[0].innerHTML = li;
                return $drop;
            },

            reloadLi: function () {
                //Remove all children.
                this.destroyLi();
                //Re build
                var li = this.createLi();
                this.$menuInner[0].innerHTML = li;
            },

            destroyLi: function () {
                this.$menu.find('li').remove();
            },

            createLi: function () {
                var that = this,
                    _li = [],
                    optID = 0,
                    titleOption = document.createElement('option'),
                    liIndex = -1; // increment liIndex whenever a new <li> element is created to ensure liObj is correct

                // Helper functions
                /**
                 * @param content
                 * @param [index]
                 * @param [classes]
                 * @param [optgroup]
                 * @returns {string}
                 */
                var generateLI = function (content, index, classes, optgroup) {
                    return '<li' +
                        ((typeof classes !== 'undefined' & '' !== classes) ? ' class="' + classes + '"' : '') +
                        ((typeof index !== 'undefined' & null !== index) ? ' data-original-index="' + index + '"' : '') +
                        ((typeof optgroup !== 'undefined' & null !== optgroup) ? 'data-optgroup="' + optgroup + '"' : '') +
                        '>' + content + '</li>';
                };

                /**
                 * @param text
                 * @param [classes]
                 * @param [inline]
                 * @param [tokens]
                 * @returns {string}
                 */
                var generateA = function (text, classes, inline, tokens) {
                    return '<a tabindex="0"' +
                        (typeof classes !== 'undefined' ? ' class="' + classes + '"' : '') +
                        (typeof inline !== 'undefined' ? ' style="' + inline + '"' : '') +
                        (that.options.liveSearchNormalize ? ' data-normalized-text="' + normalizeToBase(htmlEscape(text)) + '"' : '') +
                        (typeof tokens !== 'undefined' || tokens !== null ? ' data-tokens="' + tokens + '"' : '') +
                        '>' + text +
                        '<span class="' + that.options.iconBase + ' ' + that.options.tickIcon + ' check-mark"></span>' +
                        '</a>';
                };

                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 liObj is recalculated on every refresh, liIndex needs to be decreased even if the titleOption is already appended
                    liIndex--;

                    if (!this.$element.find('.bs-title-option').length) {
                        // Use native JS to prepend option (faster)
                        var element = this.$element[0];
                        titleOption.className = 'bs-title-option';
                        titleOption.appendChild(document.createTextNode(this.options.title));
                        titleOption.value = '';
                        element.insertBefore(titleOption, element.firstChild);
                        // Check if selected attribute is already set on an option. If not, select the titleOption option.
                        if (element.options[element.selectedIndex].getAttribute('selected') === null) titleOption.selected = true;
                    }
                }

                this.$element.find('option').each(function (index) {
                    var $this = $(this);

                    liIndex++;

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

                    // Get the class and text for the option
                    var optionClass = this.className || '',
                        inline = this.style.cssText,
                        text = $this.data('content') ? $this.data('content') : $this.html(),
                        tokens = $this.data('tokens') ? $this.data('tokens') : null,
                        subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="text-muted">' + $this.data('subtext') + '</small>' : '',
                        icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
                        isDisabled = this.disabled || this.parentElement.tagName === 'OPTGROUP' && this.parentElement.disabled;

                    if (icon !== '' && isDisabled) {
                        icon = '<span>' + icon + '</span>';
                    }

                    if (that.options.hideDisabled && isDisabled) {
                        liIndex--;
                        return;
                    }

                    if (!$this.data('content')) {
                        // Prepend any icon and append any subtext to the main text.
                        text = icon + '<span class="text">' + text + subtext + '</span>';
                    }

                    if (this.parentElement.tagName === 'OPTGROUP' && $this.data('divider') !== true) {
                        if ($this.index() === 0) { // Is it the first option of the optgroup?
                            optID += 1;

                            // Get the opt group label
                            var label = this.parentElement.label,
                                labelSubtext = typeof $this.parent().data('subtext') !== 'undefined' ? '<small class="text-muted">' + $this.parent().data('subtext') + '</small>' : '',
                                labelIcon = $this.parent().data('icon') ? '<span class="' + that.options.iconBase + ' ' + $this.parent().data('icon') + '"></span> ' : '',
                                optGroupClass = ' ' + this.parentElement.className || '';

                            label = labelIcon + '<span class="text">' + label + labelSubtext + '</span>';

                            if (index !== 0 && _li.length > 0) { // Is it NOT the first option of the select && are there elements in the dropdown?
                                liIndex++;
                                _li.push(generateLI('', null, 'divider', optID + 'div'));
                            }
                            liIndex++;
                            _li.push(generateLI(label, null, 'dropdown-header' + optGroupClass, optID));
                        }
                        _li.push(generateLI(generateA(text, 'opt ' + optionClass + optGroupClass, inline, tokens), index, '', optID));
                    } else if ($this.data('divider') === true) {
                        _li.push(generateLI('', index, 'divider'));
                    } else if ($this.data('hidden') === true) {
                        _li.push(generateLI(generateA(text, optionClass, inline, tokens), index, 'hidden is-hidden'));
                    } else {
                        if (this.previousElementSibling && this.previousElementSibling.tagName === 'OPTGROUP') {
                            liIndex++;
                            _li.push(generateLI('', null, 'divider', optID + 'div'));
                        }
                        _li.push(generateLI(generateA(text, optionClass, inline, tokens), index));
                    }

                    that.liObj[index] = liIndex;
                });

                //If we are not multiple, we don't have a selected item, and we don't have a title, select the first element so something is set in the button
                if (!this.multiple && this.$element.find('option:selected').length === 0 && !this.options.title) {
                    this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected');
                }

                return _li.join('');
            },

            findLis: function () {
                if (this.$lis == null) this.$lis = this.$menu.find('li');
                return this.$lis;
            },

            /**
             * @param [updateLi] defaults to true
             */
            render: function (updateLi) {
                var that = this,
                    notDisabled;

                //Update the LI to match the SELECT
                if (updateLi !== false) {
                    this.$element.find('option').each(function (index) {
                        var $lis = that.findLis().eq(that.liObj[index]);

                        that.setDisabled(index, this.disabled || this.parentElement.tagName === 'OPTGROUP' && this.parentElement.disabled, $lis);
                        that.setSelected(index, this.selected, $lis);
                    });
                }

                this.tabIndex();

                var selectedItems = this.$element.find('option').map(function () {
                    if (this.selected) {
                        if (that.options.hideDisabled && (this.disabled || this.parentElement.tagName === 'OPTGROUP' && this.parentElement.disabled)) return false;

                        var $this = $(this),
                            icon = $this.data('icon') && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></i> ' : '',
                            subtext;

                        if (that.options.showSubtext && $this.data('subtext') && !that.multiple) {
                            subtext = ' <small class="text-muted">' + $this.data('subtext') + '</small>';
                        } else {
                            subtext = '';
                        }
                        if (typeof $this.attr('title') !== 'undefined') {
                            return $this.attr('title');
                        } else if ($this.data('content') && that.options.showContent) {
                            return $this.data('content');
                        } else {
                            return icon + $this.html() + subtext;
                        }
                    }
                }).toArray();

                //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 ? selectedItems[0] : selectedItems.join(this.options.multipleSeparator);

                //If this is multi select, and the selectText type is count, the 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)) {
                        notDisabled = this.options.hideDisabled ? ', [disabled]' : '';
                        var totalCount = this.$element.find('option').not('[data-divider="true"], [data-hidden="true"]' + notDisabled).length,
                            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) {
                    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
                this.$button.attr('title', $.trim(title.replace(/<[^>]*>?/g, '')));
                this.$button.children('.filter-option').html(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|form-control|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;

                var newElement = document.createElement('div'),
                    menu = document.createElement('div'),
                    menuInner = document.createElement('ul'),
                    divider = document.createElement('li'),
                    li = document.createElement('li'),
                    a = document.createElement('a'),
                    text = document.createElement('span'),
                    header = this.options.header ? this.$menu.find('.popover-title')[0].cloneNode(true) : null,
                    search = this.options.liveSearch ? document.createElement('div') : null,
                    actions = this.options.actionsBox && this.multiple ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
                    doneButton = this.options.doneButton && this.multiple ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null;

                text.className = 'text';
                newElement.className = this.$menu[0].parentNode.className + ' open';
                menu.className = 'dropdown-menu open';
                menuInner.className = 'dropdown-menu inner';
                divider.className = 'divider';

                text.appendChild(document.createTextNode('Inner text'));
                a.appendChild(text);
                li.appendChild(a);
                menuInner.appendChild(li);
                menuInner.appendChild(divider);
                if (header) menu.appendChild(header);
                if (search) {
                    // create a span instead of input as creating an input element is slower
                    var input = document.createElement('span');
                    search.className = 'bs-searchbox';
                    input.className = 'form-control';
                    search.appendChild(input);
                    menu.appendChild(search);
                }
                if (actions) menu.appendChild(actions);
                menu.appendChild(menuInner);
                if (doneButton) menu.appendChild(doneButton);
                newElement.appendChild(menu);

                document.body.appendChild(newElement);

                var liHeight = a.offsetHeight,
                    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 = getComputedStyle ? getComputedStyle(menu) : false,
                    $menu = menuStyle ? $(menu) : null,
                    menuPadding = parseInt(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
                                  parseInt(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
                                  parseInt(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
                                  parseInt(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
                    menuExtras = menuPadding +
                                  parseInt(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
                                  parseInt(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2;

                document.body.removeChild(newElement);

                this.sizeInfo = {
                    liHeight: liHeight,
                    headerHeight: headerHeight,
                    searchHeight: searchHeight,
                    actionsHeight: actionsHeight,
                    doneButtonHeight: doneButtonHeight,
                    dividerHeight: dividerHeight,
                    menuPadding: menuPadding,
                    menuExtras: menuExtras
                };
            },

            setSize: function () {
                this.findLis();
                this.liHeight();
                var that = this,
                    $menu = this.$menu,
                    $menuInner = this.$menuInner,
                    $window = $(window),
                    selectHeight = this.$newElement[0].offsetHeight,
                    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'],
                    menuExtras = this.sizeInfo['menuExtras'],
                    notDisabled = this.options.hideDisabled ? '.disabled' : '',
                    menuHeight,
                    getHeight,
                    selectOffsetTop,
                    selectOffsetBot,
                    posVert = function () {
                        selectOffsetTop = that.$newElement.offset().top - $window.scrollTop();
                        selectOffsetBot = $window.height() - selectOffsetTop - selectHeight;
                    };

                posVert();

                if (this.options.header) $menu.css('padding-top', 0);

                if (this.options.size === 'auto') {
                    var getSize = function () {
                        var minHeight,
                            hasClass = function (className, include) {
                                return function (element) {
                                    if (include) {
                                        return (element.classList ? element.classList.contains(className) : $(element).hasClass(className));
                                    } else {
                                        return !(element.classList ? element.classList.contains(className) : $(element).hasClass(className));
                                    }
                                };
                            },
                            lis = that.$menuInner[0].getElementsByTagName('li'),
                            lisVisible = Array.prototype.filter ? Array.prototype.filter.call(lis, hasClass('hidden', false)) : that.$lis.not('.hidden'),
                            optGroup = Array.prototype.filter ? Array.prototype.filter.call(lisVisible, hasClass('dropdown-header', true)) : lisVisible.filter('.dropdown-header');

                        posVert();
                        menuHeight = selectOffsetBot - menuExtras;

                        if (that.options.container) {
                            if (!$menu.data('height')) $menu.data('height', $menu.height());
                            getHeight = $menu.data('height');
                        } else {
                            getHeight = $menu.height();
                        }

                        if (that.options.dropupAuto) {
                            that.$newElement.toggleClass('dropup', selectOffsetTop > selectOffsetBot && (menuHeight - menuExtras) < getHeight);
                        }
                        if (that.$newElement.hasClass('dropup')) {
                            menuHeight = selectOffsetTop - menuExtras;
                        }

                        if ((lisVisible.length + optGroup.length) > 3) {
                            minHeight = liHeight * 3 + menuExtras - 2;
                        } else {
                            minHeight = 0;
                        }

                        $menu.css({
                            'max-height': menuHeight + 'px',
                            'overflow': 'hidden',
                            'min-height': minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight + 'px'
                        });
                        $menuInner.css({
                            'max-height': menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding + 'px',
                            'overflow-y': 'auto',
                            'min-height': Math.max(minHeight - menuPadding, 0) + 'px'
                        });
                    };
                    getSize();
                    this.$searchbox.off('input.getSize propertychange.getSize').on('input.getSize propertychange.getSize', getSize);
                    $window.off('resize.getSize scroll.getSize').on('resize.getSize scroll.getSize', getSize);
                } else if (this.options.size && this.options.size != 'auto' && this.$lis.not(notDisabled).length > this.options.size) {
                    var optIndex = this.$lis.not('.divider').not(notDisabled).children().slice(0, this.options.size).last().parent().index(),
                        divLength = this.$lis.slice(0, optIndex + 1).filter('.divider').length;
                    menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding;

                    if (that.options.container) {
                        if (!$menu.data('height')) $menu.data('height', $menu.height());
                        getHeight = $menu.data('height');
                    } else {
                        getHeight = $menu.height();
                    }

                    if (that.options.dropupAuto) {
                        //noinspection JSUnusedAssignment
                        this.$newElement.toggleClass('dropup', selectOffsetTop > selectOffsetBot && (menuHeight - menuExtras) < getHeight);
                    }
                    $menu.css({
                        'max-height': menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight + 'px',
                        'overflow': 'hidden',
                        'min-height': ''
                    });
                    $menuInner.css({
                        'max-height': menuHeight - menuPadding + 'px',
                        'overflow-y': 'auto',
                        'min-height': ''
                    });
                }
            },

            setWidth: function () {
                if (this.options.width === 'auto') {
                    this.$menu.css('min-width', '0');

                    // Get correct width if element is hidden
                    var $selectClone = this.$menu.parent().clone().appendTo('body'),
                        $selectClone2 = this.options.container ? this.$newElement.clone().appendTo('body') : $selectClone,
                        ulWidth = $selectClone.children('.dropdown-menu').outerWidth(),
                        btnWidth = $selectClone2.css('width', 'auto').children('button').outerWidth();

                    $selectClone.remove();
                    $selectClone2.remove();

                    // Set width to whatever's larger, button title or longest option
                    this.$newElement.css('width', Math.max(ulWidth, btnWidth) + '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 () {
                var that = this,
                    drop = '<div />',
                    $drop = $(drop),
                    pos,
                    actualHeight,
                    getPlacement = function ($element) {
                        $drop.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass('dropup', $element.hasClass('dropup'));
                        pos = $element.offset();
                        actualHeight = $element.hasClass('dropup') ? 0 : $element[0].offsetHeight;
                        $drop.css({
                            'top': pos.top + actualHeight,
                            'left': pos.left,
                            'width': $element[0].offsetWidth,
                            'position': 'absolute'
                        });
                    };

                this.$newElement.on('click', function () {
                    if (that.isDisabled()) {
                        return;
                    }
                    getPlacement($(this));
                    $drop.appendTo(that.options.container);
                    $drop.toggleClass('open', !$(this).hasClass('open'));
                    $drop.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());
                    $drop.detach();
                });
            },

            setSelected: function (index, selected, $lis) {
                if (!$lis) {
                    var $lis = this.findLis().eq(this.liObj[index]);
                }

                $lis.toggleClass('selected', selected);
            },

            setDisabled: function (index, disabled, $lis) {
                if (!$lis) {
                    var $lis = this.findLis().eq(this.liObj[index]);
                }

                if (disabled) {
                    $lis.addClass('disabled').children('a').attr('href', '#').attr('tabindex', -1);
                } else {
                    $lis.removeClass('disabled').children('a').removeAttr('href').attr('tabindex', 0);
                }
            },

            isDisabled: function () {
                return this.$element[0].disabled;
            },

            checkDisabled: function () {
                var that = this;

                if (this.isDisabled()) {
                    this.$newElement.addClass('disabled');
                    this.$button.addClass('disabled').attr('tabindex', -1);
                } else {
                    if (this.$button.hasClass('disabled')) {
                        this.$newElement.removeClass('disabled');
                        this.$button.removeClass('disabled');
                    }

                    if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
                        this.$button.removeAttr('tabindex');
                    }
                }

                this.$button.click(function () {
                    return !that.isDisabled();
                });
            },

            tabIndex: function () {
                if (this.$element.is('[tabindex]')) {
                    this.$element.data('tabindex', this.$element.attr('tabindex'));
                    this.$button.attr('tabindex', this.$element.data('tabindex'));
                }
            },

            clickListener: function () {
                var that = this,
                    $document = $(document);

                this.$newElement.on('touchstart.dropdown', '.dropdown-menu', function (e) {
                    e.stopPropagation();
                });

                $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('click', function () {
                    that.setSize();
                    that.$element.on('shown.bs.select', function () {
                        if (!that.options.liveSearch && !that.multiple) {
                            that.$menu.find('.selected a').focus();
                        } else if (!that.multiple) {
                            var selectedIndex = that.liObj[that.$element[0].selectedIndex];

                            if (typeof selectedIndex !== 'number') return;

                            // scroll to selected option
                            var offset = that.$lis.eq(selectedIndex)[0].offsetTop - that.$menuInner[0].offsetTop;
                            offset = offset - that.$menuInner[0].offsetHeight / 2 + that.sizeInfo.liHeight / 2;
                            that.$menuInner[0].scrollTop = offset;
                        }
                    });
                });

                this.$menu.on('click', 'li a', function (e) {
                    var $this = $(this),
                        clickedIndex = $this.parent().data('originalIndex'),
                        prevValue = that.$element.val(),
                        prevIndex = that.$element.prop('selectedIndex');

                    // Don't close on multi choice menu
                    if (that.multiple) {
                        e.stopPropagation();
                    }

                    e.preventDefault();

                    //Don't run if we have been disabled
                    if (!that.isDisabled() && !$this.parent().hasClass('disabled')) {
                        var $options = that.$element.find('option'),
                            $option = $options.eq(clickedIndex),
                            state = $option.prop('selected'),
                            $optgroup = $option.parent('optgroup'),
                            maxOptions = that.options.maxOptions,
                            maxOptionsGrp = $optgroup.data('maxOptions') || false;

                        if (!that.multiple) { // Deselect all others if not multi select box
                            $options.prop('selected', false);
                            $option.prop('selected', true);
                            that.$menu.find('.selected').removeClass('selected');
                            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);
                                        that.$menu.find('.selected').removeClass('selected');
                                        that.setSelected(clickedIndex, true);
                                    } else if (maxOptionsGrp && maxOptionsGrp == 1) {
                                        $optgroup.find('option:selected').prop('selected', false);
                                        $option.prop('selected', true);
                                        var optgroupID = $this.parent().data('optgroup');
                                        that.$menu.find('[data-optgroup="' + optgroupID + '"]').removeClass('selected');
                                        that.setSelected(clickedIndex, true);
                                    } else {
                                        var maxOptionsArr = (typeof that.options.maxOptionsText === 'function') ?
                                                that.options.maxOptionsText(maxOptions, maxOptionsGrp) : that.options.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>'));
                                            that.$element.trigger('maxReached.bs.select');
                                        }

                                        if (maxOptionsGrp && maxReachedGrp) {
                                            $notify.append($('<div>' + maxTxtGrp + '</div>'));
                                            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.$button.focus();
                        } else if (that.options.liveSearch) {
                            that.$searchbox.focus();
                        }

                        // Trigger select 'change'
                        if ((prevValue != that.$element.val() && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
                            that.$element.change();
                            // $option.prop('selected') is current option state (selected/unselected). state is previous option state.
                            that.$element.trigger('changed.bs.select', [clickedIndex, $option.prop('selected'), state]);
                        }
                    }
                });

                this.$menu.on('click', 'li.disabled a, .popover-title, .popover-title :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.$menu.on('click', 'li.divider, li.dropdown-header', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (that.options.liveSearch) {
                        that.$searchbox.focus();
                    } else {
                        that.$button.focus();
                    }
                });

                this.$menu.on('click', '.popover-title .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();
                    }
                    that.$element.change();
                });

                this.$element.change(function () {
                    that.render(false);
                });
            },

            liveSearchListener: function () {
                var that = this,
                    $no_results = $('<li class="no-results"></li>');

                this.$newElement.on('click.dropdown.data-api touchstart.dropdown.data-api', function () {
                    that.$menuInner.find('.active').removeClass('active');
                    if (!!that.$searchbox.val()) {
                        that.$searchbox.val('');
                        that.$lis.not('.is-hidden').removeClass('hidden');
                        if (!!$no_results.parent().length) $no_results.remove();
                    }
                    if (!that.multiple) that.$menuInner.find('.selected').addClass('active');
                    setTimeout(function () {
                        that.$searchbox.focus();
                    }, 10);
                });

                this.$searchbox.on('click.dropdown.data-api focus.dropdown.data-api touchend.dropdown.data-api', function (e) {
                    e.stopPropagation();
                });

                this.$searchbox.on('input propertychange', function () {
                    if (that.$searchbox.val()) {
                        var $searchBase = that.$lis.not('.is-hidden').removeClass('hidden').children('a');
                        if (that.options.liveSearchNormalize) {
                            $searchBase = $searchBase.not(':a' + that._searchStyle() + '(' + normalizeToBase(that.$searchbox.val()) + ')');
                        } else {
                            $searchBase = $searchBase.not(':' + that._searchStyle() + '(' + that.$searchbox.val() + ')');
                        }
                        $searchBase.parent().addClass('hidden');

                        that.$lis.filter('.dropdown-header').each(function () {
                            var $this = $(this),
                                optgroup = $this.data('optgroup');

                            if (that.$lis.filter('[data-optgroup=' + optgroup + ']').not($this).not('.hidden').length === 0) {
                                $this.addClass('hidden');
                                that.$lis.filter('[data-optgroup=' + optgroup + 'div]').addClass('hidden');
                            }
                        });

                        var $lisVisible = that.$lis.not('.hidden');

                        // hide divider if first or last visible, or if followed by another divider
                        $lisVisible.each(function (index) {
                            var $this = $(this);

                            if ($this.hasClass('divider') && (
                              $this.index() === $lisVisible.eq(0).index() ||
                              $this.index() === $lisVisible.last().index() ||
                              $lisVisible.eq(index + 1).hasClass('divider'))) {
                                $this.addClass('hidden');
                            }
                        });

                        if (!that.$lis.not('.hidden, .no-results').length) {
                            if (!!$no_results.parent().length) {
                                $no_results.remove();
                            }
                            $no_results.html(that.options.noneResultsText.replace('{0}', '"' + htmlEscape(that.$searchbox.val()) + '"')).show();
                            that.$menuInner.append($no_results);
                        } else if (!!$no_results.parent().length) {
                            $no_results.remove();
                        }

                    } else {
                        that.$lis.not('.is-hidden').removeClass('hidden');
                        if (!!$no_results.parent().length) {
                            $no_results.remove();
                        }
                    }

                    that.$lis.filter('.active').removeClass('active');
                    that.$lis.not('.hidden, .divider, .dropdown-header').eq(0).addClass('active').children('a').focus();
                    $(this).focus();
                });
            },

            _searchStyle: function () {
                var style = 'icontains';
                switch (this.options.liveSearchStyle) {
                    case 'begins':
                    case 'startsWith':
                        style = 'ibegins';
                        break;
                    case 'contains':
                    default:
                        break; //no need to change the default
                }

                return style;
            },

            val: function (value) {
                if (typeof value !== 'undefined') {
                    this.$element.val(value);
                    this.render();

                    return this.$element;
                } else {
                    return this.$element.val();
                }
            },

            selectAll: function () {
                this.findLis();
                this.$element.find('option:enabled').not('[data-divider], [data-hidden]').prop('selected', true);
                this.$lis.not('.divider, .dropdown-header, .disabled, .hidden').addClass('selected');
                this.render(false);
            },

            deselectAll: function () {
                this.findLis();
                this.$element.find('option:enabled').not('[data-divider], [data-hidden]').prop('selected', false);
                this.$lis.not('.divider, .dropdown-header, .disabled, .hidden').removeClass('selected');
                this.render(false);
            },

            keydown: function (e) {
                var $this = $(this),
                    $parent = $this.is('input') ? $this.parent().parent() : $this.parent(),
                    $items,
                    that = $parent.data('this'),
                    index,
                    next,
                    first,
                    last,
                    prev,
                    nextPrev,
                    prevIndex,
                    isActive,
                    selector = ':not(.disabled, .hidden, .dropdown-header, .divider)',
                    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'
                    };

                if (that.options.liveSearch) $parent = $this.parent().parent();

                if (that.options.container) $parent = that.$menu;

                $items = $('[role=menu] li a', $parent);

                isActive = that.$menu.parent().hasClass('open');

                if (!isActive && (e.keyCode >= 48 && e.keyCode <= 57 || event.keyCode >= 65 && event.keyCode <= 90)) {
                    if (!that.options.container) {
                        that.setSize();
                        that.$menu.parent().addClass('open');
                        isActive = true;
                    } else {
                        that.$newElement.trigger('click');
                    }
                    that.$searchbox.focus();
                }

                if (that.options.liveSearch) {
                    if (/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && that.$menu.find('.active').length === 0) {
                        e.preventDefault();
                        that.$menu.parent().removeClass('open');
                        if (that.options.container) that.$newElement.removeClass('open');
                        that.$button.focus();
                    }
                    // $items contains li elements when liveSearch is enabled
                    $items = $('[role=menu] li:not(.disabled, .hidden, .dropdown-header, .divider)', $parent);
                    if (!$this.val() && !/(38|40)/.test(e.keyCode.toString(10))) {
                        if ($items.filter('.active').length === 0) {
                            $items = that.$newElement.find('li');
                            if (that.options.liveSearchNormalize) {
                                $items = $items.filter(':a' + that._searchStyle() + '(' + normalizeToBase(keyCodeMap[e.keyCode]) + ')');
                            } else {
                                $items = $items.filter(':' + that._searchStyle() + '(' + keyCodeMap[e.keyCode] + ')');
                            }
                        }
                    }
                }

                if (!$items.length) return;

                if (/(38|40)/.test(e.keyCode.toString(10))) {
                    index = $items.index($items.filter(':focus'));
                    first = $items.parent(selector).first().data('originalIndex');
                    last = $items.parent(selector).last().data('originalIndex');
                    next = $items.eq(index).parent().nextAll(selector).eq(0).data('originalIndex');
                    prev = $items.eq(index).parent().prevAll(selector).eq(0).data('originalIndex');
                    nextPrev = $items.eq(next).parent().prevAll(selector).eq(0).data('originalIndex');

                    if (that.options.liveSearch) {
                        $items.each(function (i) {
                            if (!$(this).hasClass('disabled')) {
                                $(this).data('index', i);
                            }
                        });
                        index = $items.index($items.filter('.active'));
                        first = $items.first().data('index');
                        last = $items.last().data('index');
                        next = $items.eq(index).nextAll().eq(0).data('index');
                        prev = $items.eq(index).prevAll().eq(0).data('index');
                        nextPrev = $items.eq(next).prevAll().eq(0).data('index');
                    }

                    prevIndex = $this.data('prevIndex');

                    if (e.keyCode == 38) {
                        if (that.options.liveSearch) index -= 1;
                        if (index != nextPrev && index > prev) index = prev;
                        if (index < first) index = first;
                        if (index == prevIndex) index = last;
                    } else if (e.keyCode == 40) {
                        if (that.options.liveSearch) index += 1;
                        if (index == -1) index = 0;
                        if (index != nextPrev && index < next) index = next;
                        if (index > last) index = last;
                        if (index == prevIndex) index = first;
                    }

                    $this.data('prevIndex', index);

                    if (!that.options.liveSearch) {
                        $items.eq(index).focus();
                    } else {
                        e.preventDefault();
                        if (!$this.hasClass('dropdown-toggle')) {
                            $items.removeClass('active').eq(index).addClass('active').children('a').focus();
                            $this.focus();
                        }
                    }

                } else if (!$this.is('input')) {
                    var keyIndex = [],
                        count,
                        prevKey;

                    $items.each(function () {
                        if (!$(this).parent().hasClass('disabled')) {
                            if ($.trim($(this).text().toLowerCase()).substring(0, 1) == keyCodeMap[e.keyCode]) {
                                keyIndex.push($(this).parent().index());
                            }
                        }
                    });

                    count = $(document).data('keycount');
                    count++;
                    $(document).data('keycount', count);

                    prevKey = $.trim($(':focus').text().toLowerCase()).substring(0, 1);

                    if (prevKey != keyCodeMap[e.keyCode]) {
                        count = 1;
                        $(document).data('keycount', count);
                    } else if (count >= keyIndex.length) {
                        $(document).data('keycount', 0);
                        if (count > keyIndex.length) count = 1;
                    }

                    $items.eq(keyIndex[count - 1]).focus();
                }

                // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
                if ((/(13|32)/.test(e.keyCode.toString(10)) || (/(^9$)/.test(e.keyCode.toString(10)) && that.options.selectOnTab)) && isActive) {
                    if (!/(32)/.test(e.keyCode.toString(10))) e.preventDefault();
                    if (!that.options.liveSearch) {
                        var elem = $(':focus');
                        elem.click();
                        // Bring back focus for multiselects
                        elem.focus();
                        // Prevent screen from scrolling if the user hit the spacebar
                        e.preventDefault();
                        // Fixes spacebar selection of dropdown items in FF & IE
                        $(document).data('spaceSelect', true);
                    } else if (!/(32)/.test(e.keyCode.toString(10))) {
                        that.$menu.find('.active a').click();
                        $this.focus();
                    }
                    $(document).data('keycount', 0);
                }

                if ((/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && (that.multiple || that.options.liveSearch)) || (/(27)/.test(e.keyCode.toString(10)) && !isActive)) {
                    that.$menu.parent().removeClass('open');
                    if (that.options.container) that.$newElement.removeClass('open');
                    that.$button.focus();
                }
            },

            mobile: function () {
                this.$element.addClass('mobile-device').appendTo(this.$newElement);
                if (this.options.container) this.$menu.hide();
            },

            refresh: function () {
                this.$lis = null;
                this.reloadLi();
                this.render();
                this.checkDisabled();
                this.liHeight(true);
                this.setStyle();
                this.setWidth();
                if (this.$lis) this.$searchbox.trigger('propertychange');

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

            hide: function () {
                this.$newElement.hide();
            },

            show: function () {
                this.$newElement.show();
            },

            remove: function () {
                this.$newElement.remove();
                this.$element.remove();
            }
        };

        // SELECTPICKER PLUGIN DEFINITION
        // ==============================
        function Plugin(option, event) {
            // 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,
                _event = event;
            [].shift.apply(args);

            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);
                        $this.data('selectpicker', (data = new Selectpicker(this, config, _event)));
                    } 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)
            .data('keycount', 0)
            .on('keydown', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="menu"], .bs-searchbox input', Selectpicker.prototype.keydown)
            .on('focusin.modal', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="menu"], .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);


}));
;
var GTM = {
    AddToCart: function (currency, productObj) {        
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'add',
            'ecommerce': {
                'currencyCode': currency,
                'add': {                                  // 'add' actionFieldObject measures.
                    'actionField': {
                        'list': productObj.List
                    },
                    'products': [{                        //  adding a product to a shopping cart.
                        'name': productObj.ProductName,
                        'id': productObj.ItemNo,
                        'price': productObj.PriceUS,
                        'brand': document.location.host,
                        'category': productObj.EnProductGroup,
                        'variant': productObj.VariantID,
                        'quantity': productObj.Quantity,
                        'coupon': productObj.OverlayImageFileName
                    }]
                }
            }
        });
        dataLayer = window.dataLayer;
    },
    Checkout: function (Products) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'checkout',
            'ecommerce': {
                'checkout': {
                    'actionField': { 'step': 1 },
                    'products': Products
                }
            }
        });
        dataLayer = window.dataLayer;
    },
    CheckoutOption: function (step, checkoutOption) {        
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'checkout option',
            'ecommerce': {
                'checkout_option': {
                    'actionField': { 'step': step, 'option': checkoutOption }
                }
            }
        });
        dataLayer = window.dataLayer;
    },
    RemoveFromCart: function (productObj) {        
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'remove',
            'ecommerce': {
                'remove': {                                 // 'remove' actionFieldObject measures.
                    'products': [{                          //  removing a product to a shopping cart.
                        'name': productObj.ProductName,
                        'id': productObj.ItemNo,
                        'price': productObj.PriceUS,
                        'brand': document.location.host,
                        'category': productObj.EnProductGroup,
                        'variant': productObj.VariantID,
                        'quantity': productObj.Quantity,
                        'coupon': productObj.OverlayImageFileName
                    }]
                }
            }
        });
        dataLayer = window.dataLayer;
    },
    HideAddonUpsell: function () {        
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'event_trigger',
            'eventCategory': 'checkout',
            'eventAction': 'go_back',
            'eventLabel': '/vpv/addon'
        });
        dataLayer = window.dataLayer;
    },
    AddAddon: function (step, itemNo) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'checkout option',
            'ecommerce': {
                'checkout_option': {
                    'actionField': { 'step': step, 'option': 'add_addon_' + itemNo }
                }
            }
        });
        dataLayer = window.dataLayer;
	},
	RemoveAddon: function (step, itemNo) {
		window.dataLayer = window.dataLayer || [];
		window.dataLayer.push({
			'event': 'checkout option',
			'ecommerce': {
				'checkout_option': {
					'actionField': { 'step': step, 'option': 'remove_addon_' + itemNo }
				}
			}
		});
		dataLayer = window.dataLayer;
	},
    NewsLetterSignedUp: function (source) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'userSignedUp',
            'newsletterSignUp': source
        });
        dataLayer = window.dataLayer;
    },
    CustomEvent: function (evntName, evntParameterName, evntParameterValue) {
        window.dataLayer = window.dataLayer || [];
        var eventObj = {};
        eventObj['event'] = evntName;
        eventObj[evntParameterName] = evntParameterValue;
        window.dataLayer.push(eventObj);
        dataLayer = window.dataLayer;
    },
    LoginPopupOpened: function () {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'loginPopupOpened'
        });
        dataLayer = window.dataLayer;
    },
    DropDownCollapse: function (obj) {
        if (obj.classList.contains("collapsed"))
        {
            obj.removeAttribute("data_category");
            obj.removeAttribute("data_action");
            obj.removeAttribute("data_label");
        }
        else
        {
            obj.setAttribute("data_category", "information");
            obj.setAttribute("data_action", "drop_down");
            obj.setAttribute("data_label", window.location.href);
        }
    },
    ContactClick: function (contactAction) {
        GTM.CustomEvent("contact", contactAction, window.location.href);
    },
    ProductClick: function (productObj) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'product click',
            'ecommerce': {
                'click': {                                 // 'remove' actionFieldObject measures.
                    'actionField': { 'list': productObj.List }, //where product has been clicked
                    'products': [{                          //  removing a product to a shopping cart.
                        'name': productObj.ProductName,
                        'id': productObj.ItemNo,
                        'price': productObj.PriceUS,
                        'brand': document.location.host,
                        'category': productObj.EnProductGroup,
                        'variant': productObj.VariantID,
                        'position': parseInt(productObj.Position),
                        'coupon': productObj.OverlayImageFileName
                    }]
                }
            }
        });
        dataLayer = window.dataLayer;
    },
    ProductView: function (productObj) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'product detail',
            'ecommerce': {
                'detail': {
                    'actionField': { 'list': productObj.list },
                    'products': [{
                        'name': productObj.name, // Name or ID is required.
                        'id': productObj.id,
                        'price': productObj.price,
                        'brand': document.location.host,
                        'category': productObj.category,
                        'variant': productObj.variant,
                        'coupon': productObj.OverlayImageFileName
                    }]
                }
            }
        });
        dataLayer = window.dataLayer;
    },
    PromoClick: function (promoObj) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'promo click',
            'ecommerce': {
                'promoClick': {
                    'promotions': [
                        {
                            'id': promoObj.id,                         // Name or ID is required.
                            'name': promoObj.name,
                            'creative': promoObj.creative,
                            'position': promoObj.pos
                        }]
                }
            },
            'eventCallback': function () {
                document.location = promoObj.destinationUrl;
            }
        });
        dataLayer = window.dataLayer;
    },
    lastPostCode: '',
    SubmitPostCode: function (eventName, postCode) {
        if (typeof postCode != 'undefined' && postCode != this.lastPostCode) {
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                'event': eventName,
                'postcode': postCode
            });
            dataLayer = window.dataLayer;
            this.lastPostCode = postCode;
        }
    },
    UserLoggedViaCheckoutPopup: function () {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'userLoggedViaCheckoutPopup'
        });
        dataLayer = window.dataLayer;
    },
    //--- CHECKOUT ERROR --- //
    SubmitCheckoutErrors: function (step, fields, errorCodes, revenue) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'manual_event',
            'eventCategory': 'checkout_error_step' + step,
            'eventAction': fields.join('|'),
            'eventLabel': errorCodes.join('|')
        });
        dataLayer = window.dataLayer;
    },
    //--- COOKIES AGREMENTS --- //
    AcceptCookiesAll: function () {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'ef_consent',
            'eventCategory': 'opt_in',
            'eventAction': '4',
            'eventLabel': new Date().toLocaleString()
        });
        dataLayer = window.dataLayer;
    },
    AcceptCookiesFunctional: function () {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'ef_consent',
            'eventCategory': 'opt_in',
            'eventAction': '1',
            'eventLabel': new Date().toLocaleString()
        });
        dataLayer = window.dataLayer;
    },
    AcceptCookiesTracking: function () {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'ef_consent',
            'eventCategory': 'opt_in',
            'eventAction': '3',
            'eventLabel': new Date().toLocaleString()
        });
        dataLayer = window.dataLayer;
    },
    AcceptCookiesAnalytics: function () {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'ef_consent',
            'eventCategory': 'opt_in',
            'eventAction': '2',
            'eventLabel': new Date().toLocaleString()
        });
        dataLayer = window.dataLayer;
    },
    FindGiftsAnalytics: function (location, postcode, deliveryDate, numberOfResults) {
        if (!(!!postcode) && !(!!deliveryDate)) {
            postcode = "";
            numberOfResults = "default";
        }

        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'manual event',
            'eventCategory': 'PCF gift tool',
            'eventAction': 'find',
            'eventLabel': location + '|' + postcode + '|' + numberOfResults
        });
        dataLayer = window.dataLayer;
    },
    //--- ADD ATTRIBUTES --- //
    AddGtmDataAttributes: function (obj, category, action, label, value) {
        //obj = document.getElementById("myAnchor")
        if (category)
            obj.setAttribute("data-event-category", category);
        if (action)
            obj.setAttribute("data-event-action", action);
        if (label)
            obj.setAttribute("data-event-label", label);
        if (value)
            obj.setAttribute("data-event-value", value);
    },

    AddPromotionalImpression: function (model) {
        window.dataLayer = window.dataLayer || [];
        var promotions = [];
        for (var i = 0; i < model.length; i++) {
            promotions.push({
                'name': model[i].FileName,         // Name or ID is required.
                'id': model[i].Id,
                'creative': 'homepagebanner',
                'position': model[i].OrderNo
            });
        }
        window.dataLayer.push({
            'event': 'promo view',
            'ecommerce': {
                'promoView': {
                    'promotions': promotions
                }
            }
        });
        dataLayer = window.dataLayer;
    },

    AddonsSliderLoaded: function(itemNos) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'AddonSlider',
            'eventCategory': 'Ecommerce',
            'eventAction': 'Addons Impressions Product Page',
            'eventLabel': (itemNos || []).join("|")
        });
        dataLayer = window.dataLayer;
    },

    AddonsSliderMoveForward: function (itemNos) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'AddonSlider',
            'eventCategory': 'Ecommerce',
            'eventAction': 'Addons Impression Move Forward',
            'eventLabel': (itemNos || []).join("|")
        });
        dataLayer = window.dataLayer;
    },

    AddonsSliderMoveBack: function (itemNos) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'AddonSlider',
            'eventCategory': 'Ecommerce',
            'eventAction': 'Addons Impression Move Back',
            'eventLabel': (itemNos || []).join("|")
        });
        dataLayer = window.dataLayer;
	},

	CheckoutErrorMessage: function (label, totalFee) {
		window.dataLayer = window.dataLayer || [];
		window.dataLayer.push({
			'event': 'manual_event',
			'eventCategory': 'Ecommerce',
            'eventAction': 'Checkout Error',
            'eventLabel': label,
            'eventValue': totalFee

		});
		dataLayer = window.dataLayer;
    },

    ProductNotAvailableForPostcode: function (postcode, popupType) {
        if (postcode !== undefined && postcode.length > 0) {
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                'event': 'manual_event',
                'eventCategory': 'Pop-up_message',
                'eventAction': popupType,
                'eventLabel': postcode
            });
            dataLayer = window.dataLayer;
        }
    },

    GetValidationErrors: function () {
        var self = this,
            validateElements = $('[data-validation-index]'),
            validationErrorCodes = [],
            validationErrorFields = [];

        validateElements.each(function () {
            if ($(this).hasClass('has-error')) {
                var validationMessage = $(this).find('.has-error').text(),
                    elementAttributes = $(this).children('.form-control').data();

                for (var attribute in elementAttributes) {
                    if (elementAttributes[attribute] === validationMessage) {
                        validationErrorFields.push($(this).data('validation-index'));
                        validationErrorCodes.push(self.GetValidationErrorCode(attribute));                       
                    }
                }
            }
        });

        if (validationErrorFields.length > 0)
            this.SubmitCheckoutErrors(1, validationErrorFields, validationErrorCodes, 0);
    },

    GetValidationErrorCode: function (error) {
        var validationTypeAttributes = {
            required: "valRequired",
            length: "valLength",
            maxLength: "valLength-max",
            numberFormatRequired: "valNumber",
            regex: "valRegex",
            emailFormat: "valCustomemail",
            minLength: "valLengthMin",
            boxFloristFieldLength: "valFloristboxfieldlenght",
            postcodeFormat: "valRecipientpostcodcontactvalid",
            postcodeMaxLength: "valRecipientpostcodemaxlength",
            postcodeRequired: "valRecipientpostcodenotempty",
            senderPhoneFormat: "valSendertelephonevalid"
        };

        if (error === validationTypeAttributes["required"] || error === validationTypeAttributes["numberFormatRequired"])
            return '001';
        if (error === validationTypeAttributes["maxLength"] || error === validationTypeAttributes["boxFloristFieldLength"] || error === validationTypeAttributes["postcodeMaxLength"])
            return '002';

        return '003';
    }
};
;
/*! Respond.js v1.4.2: min/max-width media query polyfill * Copyright 2013 Scott Jehl
 * Licensed under https://github.com/scottjehl/Respond/blob/master/LICENSE-MIT
 *  */

!function(a){"use strict";a.matchMedia=a.matchMedia||function(a){var b,c=a.documentElement,d=c.firstElementChild||c.firstChild,e=a.createElement("body"),f=a.createElement("div");return f.id="mq-test-1",f.style.cssText="position:absolute;top:-100em",e.style.background="none",e.appendChild(f),function(a){return f.innerHTML='&shy;<style media="'+a+'"> #mq-test-1 { width: 42px; }</style>',c.insertBefore(e,d),b=42===f.offsetWidth,c.removeChild(e),{matches:b,media:a}}}(a.document)}(this),function(a){"use strict";function b(){u(!0)}var c={};a.respond=c,c.update=function(){};var d=[],e=function(){var b=!1;try{b=new a.XMLHttpRequest}catch(c){b=new a.ActiveXObject("Microsoft.XMLHTTP")}return function(){return b}}(),f=function(a,b){var c=e();c&&(c.open("GET",a,!0),c.onreadystatechange=function(){4!==c.readyState||200!==c.status&&304!==c.status||b(c.responseText)},4!==c.readyState&&c.send(null))};if(c.ajax=f,c.queue=d,c.regex={media:/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,keyframes:/@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi,urls:/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,findStyles:/@media *([^\{]+)\{([\S\s]+?)$/,only:/(only\s+)?([a-zA-Z]+)\s?/,minw:/\([\s]*min\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/,maxw:/\([\s]*max\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/},c.mediaQueriesSupported=a.matchMedia&&null!==a.matchMedia("only all")&&a.matchMedia("only all").matches,!c.mediaQueriesSupported){var g,h,i,j=a.document,k=j.documentElement,l=[],m=[],n=[],o={},p=30,q=j.getElementsByTagName("head")[0]||k,r=j.getElementsByTagName("base")[0],s=q.getElementsByTagName("link"),t=function(){var a,b=j.createElement("div"),c=j.body,d=k.style.fontSize,e=c&&c.style.fontSize,f=!1;return b.style.cssText="position:absolute;font-size:1em;width:1em",c||(c=f=j.createElement("body"),c.style.background="none"),k.style.fontSize="100%",c.style.fontSize="100%",c.appendChild(b),f&&k.insertBefore(c,k.firstChild),a=b.offsetWidth,f?k.removeChild(c):c.removeChild(b),k.style.fontSize=d,e&&(c.style.fontSize=e),a=i=parseFloat(a)},u=function(b){var c="clientWidth",d=k[c],e="CSS1Compat"===j.compatMode&&d||j.body[c]||d,f={},o=s[s.length-1],r=(new Date).getTime();if(b&&g&&p>r-g)return a.clearTimeout(h),h=a.setTimeout(u,p),void 0;g=r;for(var v in l)if(l.hasOwnProperty(v)){var w=l[v],x=w.minw,y=w.maxw,z=null===x,A=null===y,B="em";x&&(x=parseFloat(x)*(x.indexOf(B)>-1?i||t():1)),y&&(y=parseFloat(y)*(y.indexOf(B)>-1?i||t():1)),w.hasquery&&(z&&A||!(z||e>=x)||!(A||y>=e))||(f[w.media]||(f[w.media]=[]),f[w.media].push(m[w.rules]))}for(var C in n)n.hasOwnProperty(C)&&n[C]&&n[C].parentNode===q&&q.removeChild(n[C]);n.length=0;for(var D in f)if(f.hasOwnProperty(D)){var E=j.createElement("style"),F=f[D].join("\n");E.type="text/css",E.media=D,q.insertBefore(E,o.nextSibling),E.styleSheet?E.styleSheet.cssText=F:E.appendChild(j.createTextNode(F)),n.push(E)}},v=function(a,b,d){var e=a.replace(c.regex.keyframes,"").match(c.regex.media),f=e&&e.length||0;b=b.substring(0,b.lastIndexOf("/"));var g=function(a){return a.replace(c.regex.urls,"$1"+b+"$2$3")},h=!f&&d;b.length&&(b+="/"),h&&(f=1);for(var i=0;f>i;i++){var j,k,n,o;h?(j=d,m.push(g(a))):(j=e[i].match(c.regex.findStyles)&&RegExp.$1,m.push(RegExp.$2&&g(RegExp.$2))),n=j.split(","),o=n.length;for(var p=0;o>p;p++)k=n[p],l.push({media:k.split("(")[0].match(c.regex.only)&&RegExp.$2||"all",rules:m.length-1,hasquery:k.indexOf("(")>-1,minw:k.match(c.regex.minw)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:k.match(c.regex.maxw)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}u()},w=function(){if(d.length){var b=d.shift();f(b.href,function(c){v(c,b.href,b.media),o[b.href]=!0,a.setTimeout(function(){w()},0)})}},x=function(){for(var b=0;b<s.length;b++){var c=s[b],e=c.href,f=c.media,g=c.rel&&"stylesheet"===c.rel.toLowerCase();e&&g&&!o[e]&&(c.styleSheet&&c.styleSheet.rawCssText?(v(c.styleSheet.rawCssText,e,f),o[e]=!0):(!/^([a-zA-Z:]*\/\/)/.test(e)&&!r||e.replace(RegExp.$1,"").split("/")[0]===a.location.host)&&("//"===e.substring(0,2)&&(e=a.location.protocol+e),d.push({href:e,media:f})))}w()};x(),c.update=x,c.getEmValue=t,a.addEventListener?a.addEventListener("resize",b,!1):a.attachEvent&&a.attachEvent("onresize",b)}}(this);;
/* globals define, module, jQuery */

/*
 * Mailcheck https://github.com/mailcheck/mailcheck
 * Author
 * Derrick Ko (@derrickko)
 *
 * Released under the MIT License.
 *
 * v 1.1.2
 */

var Mailcheck = {
    domainThreshold: 2,
    secondLevelThreshold: 2,
    topLevelThreshold: 2,

    defaultDomains: ['msn.com', 'bellsouth.net',
        'telus.net', 'comcast.net', 'optusnet.com.au',
        'earthlink.net', 'qq.com', 'sky.com', 'icloud.com',
        'mac.com', 'sympatico.ca', 'googlemail.com',
        'att.net', 'xtra.co.nz', 'web.de',
        'cox.net', 'gmail.com', 'ymail.com',
        'aim.com', 'rogers.com', 'verizon.net',
        'rocketmail.com', 'google.com', 'optonline.net',
        'sbcglobal.net', 'aol.com', 'me.com', 'btinternet.com',
        'charter.net', 'shaw.ca'],

    defaultSecondLevelDomains: ["yahoo", "hotmail", "mail", "live", "outlook", "gmx"],

    defaultTopLevelDomains: ["com", "com.au", "com.tw", "ca", "co.nz", "co.uk", "de",
        "fr", "it", "ru", "net", "org", "edu", "gov", "jp", "nl", "kr", "se", "eu",
        "ie", "co.il", "us", "at", "be", "dk", "hk", "es", "gr", "ch", "no", "cz",
        "in", "net", "net.au", "info", "biz", "mil", "co.jp", "sg", "hu", "uk"],

    run: function (opts) {
        opts.domains = opts.domains || Mailcheck.defaultDomains;
        opts.secondLevelDomains = opts.secondLevelDomains || Mailcheck.defaultSecondLevelDomains;
        opts.topLevelDomains = opts.topLevelDomains || Mailcheck.defaultTopLevelDomains;
        opts.distanceFunction = opts.distanceFunction || Mailcheck.sift4Distance;

        var defaultCallback = function (result) { return result; };
        var suggestedCallback = opts.suggested || defaultCallback;
        var emptyCallback = opts.empty || defaultCallback;

        var result = Mailcheck.suggest(Mailcheck.encodeEmail(opts.email), opts.domains, opts.secondLevelDomains, opts.topLevelDomains, opts.distanceFunction);

        return result ? suggestedCallback(result) : emptyCallback();
    },

    suggest: function (email, domains, secondLevelDomains, topLevelDomains, distanceFunction) {
        email = email.toLowerCase();

        var emailParts = this.splitEmail(email);

        if (secondLevelDomains && topLevelDomains) {
            // If the email is a valid 2nd-level + top-level, do not suggest anything.
            if (secondLevelDomains.indexOf(emailParts.secondLevelDomain) !== -1 && topLevelDomains.indexOf(emailParts.topLevelDomain) !== -1) {
                return false;
            }
        }

        var closestDomain = this.findClosestDomain(emailParts.domain, domains, distanceFunction, this.domainThreshold);

        if (closestDomain) {
            if (closestDomain == emailParts.domain) {
                // The email address exactly matches one of the supplied domains; do not return a suggestion.
                return false;
            } else {
                // The email address closely matches one of the supplied domains; return a suggestion
                return { address: emailParts.address, domain: closestDomain, full: emailParts.address + "@" + closestDomain };
            }
        }

        // The email address does not closely match one of the supplied domains
        var closestSecondLevelDomain = this.findClosestDomain(emailParts.secondLevelDomain, secondLevelDomains, distanceFunction, this.secondLevelThreshold);
        var closestTopLevelDomain = this.findClosestDomain(emailParts.topLevelDomain, topLevelDomains, distanceFunction, this.topLevelThreshold);

        if (emailParts.domain) {
            closestDomain = emailParts.domain;
            var rtrn = false;

            if (closestSecondLevelDomain && closestSecondLevelDomain != emailParts.secondLevelDomain) {
                // The email address may have a mispelled second-level domain; return a suggestion
                closestDomain = closestDomain.replace(emailParts.secondLevelDomain, closestSecondLevelDomain);
                rtrn = true;
            }

            if (closestTopLevelDomain && closestTopLevelDomain != emailParts.topLevelDomain && emailParts.secondLevelDomain !== '') {
                // The email address may have a mispelled top-level domain; return a suggestion
                closestDomain = closestDomain.replace(new RegExp(emailParts.topLevelDomain + "$"), closestTopLevelDomain);
                rtrn = true;
            }

            if (rtrn) {
                return { address: emailParts.address, domain: closestDomain, full: emailParts.address + "@" + closestDomain };
            }
        }

        /* The email address exactly matches one of the supplied domains, does not closely
         * match any domain and does not appear to simply have a mispelled top-level domain,
         * or is an invalid email address; do not return a suggestion.
         */
        return false;
    },

    findClosestDomain: function (domain, domains, distanceFunction, threshold) {
        threshold = threshold || this.topLevelThreshold;
        var dist;
        var minDist = Infinity;
        var closestDomain = null;

        if (!domain || !domains) {
            return false;
        }
        if (!distanceFunction) {
            distanceFunction = this.sift4Distance;
        }

        for (var i = 0; i < domains.length; i++) {
            if (domain === domains[i]) {
                return domain;
            }
            dist = distanceFunction(domain, domains[i]);
            if (dist < minDist) {
                minDist = dist;
                closestDomain = domains[i];
            }
        }

        if (minDist <= threshold && closestDomain !== null) {
            return closestDomain;
        } else {
            return false;
        }
    },

    sift4Distance: function (s1, s2, maxOffset) {
        // sift4: https://siderite.blogspot.com/2014/11/super-fast-and-accurate-string-distance.html
        if (maxOffset === undefined) {
            maxOffset = 5; //default
        }

        if (!s1 || !s1.length) {
            if (!s2) {
                return 0;
            }
            return s2.length;
        }

        if (!s2 || !s2.length) {
            return s1.length;
        }

        var l1 = s1.length;
        var l2 = s2.length;

        var c1 = 0;  //cursor for string 1
        var c2 = 0;  //cursor for string 2
        var lcss = 0;  //largest common subsequence
        var local_cs = 0; //local common substring
        var trans = 0;  //number of transpositions ('ab' vs 'ba')
        var offset_arr = [];  //offset pair array, for computing the transpositions

        while ((c1 < l1) && (c2 < l2)) {
            if (s1.charAt(c1) == s2.charAt(c2)) {
                local_cs++;
                var isTrans = false;
                //see if current match is a transposition
                var i = 0;
                while (i < offset_arr.length) {
                    var ofs = offset_arr[i];
                    if (c1 <= ofs.c1 || c2 <= ofs.c2) {
                        // when two matches cross, the one considered a transposition is the one with the largest difference in offsets
                        isTrans = Math.abs(c2 - c1) >= Math.abs(ofs.c2 - ofs.c1);
                        if (isTrans) {
                            trans++;
                        } else {
                            if (!ofs.trans) {
                                ofs.trans = true;
                                trans++;
                            }
                        }
                        break;
                    } else {
                        if (c1 > ofs.c2 && c2 > ofs.c1) {
                            offset_arr.splice(i, 1);
                        } else {
                            i++;
                        }
                    }
                }
                offset_arr.push({
                    c1: c1,
                    c2: c2,
                    trans: isTrans
                });
            } else {
                lcss += local_cs;
                local_cs = 0;
                if (c1 != c2) {
                    c1 = c2 = Math.min(c1, c2);  //using min allows the computation of transpositions
                }
                //if matching characters are found, remove 1 from both cursors (they get incremented at the end of the loop)
                //so that we can have only one code block handling matches 
                for (var j = 0; j < maxOffset && (c1 + j < l1 || c2 + j < l2); j++) {
                    if ((c1 + j < l1) && (s1.charAt(c1 + j) == s2.charAt(c2))) {
                        c1 += j - 1;
                        c2--;
                        break;
                    }
                    if ((c2 + j < l2) && (s1.charAt(c1) == s2.charAt(c2 + j))) {
                        c1--;
                        c2 += j - 1;
                        break;
                    }
                }
            }
            c1++;
            c2++;
            // this covers the case where the last match is on the last token in list, so that it can compute transpositions correctly
            if ((c1 >= l1) || (c2 >= l2)) {
                lcss += local_cs;
                local_cs = 0;
                c1 = c2 = Math.min(c1, c2);
            }
        }
        lcss += local_cs;
        return Math.round(Math.max(l1, l2) - lcss + trans); //add the cost of transpositions to the final result
    },

    splitEmail: function (email) {
        email = email !== null ? (email.replace(/^\s*/, '').replace(/\s*$/, '')) : ""; // trim() not exist in old IE!
        var parts = email.split('@');

        if (parts.length < 2) {
            return false;
        }

        for (var i = 0; i < parts.length; i++) {
            if (parts[i] === '') {
                return false;
            }
        }

        var domain = parts.pop();
        var domainParts = domain.split('.');
        var sld = '';
        var tld = '';

        if (domainParts.length === 0) {
            // The address does not have a top-level domain
            return false;
        } else if (domainParts.length == 1) {
            // The address has only a top-level domain (valid under RFC)
            tld = domainParts[0];
        } else {
            // The address has a domain and a top-level domain
            sld = domainParts[0];
            for (var j = 1; j < domainParts.length; j++) {
                tld += domainParts[j] + '.';
            }
            tld = tld.substring(0, tld.length - 1);
        }

        return {
            topLevelDomain: tld,
            secondLevelDomain: sld,
            domain: domain,
            address: parts.join('@')
        };
    },

    // Encode the email address to prevent XSS but leave in valid
    // characters, following this official spec:
    // http://en.wikipedia.org/wiki/Email_address#Syntax
    encodeEmail: function (email) {
        var result = encodeURI(email);
        result = result.replace('%20', ' ').replace('%25', '%').replace('%5E', '^')
            .replace('%60', '`').replace('%7B', '{').replace('%7C', '|')
            .replace('%7D', '}');
        return result;
    }
};

// Export the mailcheck object if we're in a CommonJS env (e.g. Node).
// Modeled off of Underscore.js.
if (typeof module !== 'undefined' && module.exports) {
    module.exports = Mailcheck;
}

// Support AMD style definitions
// Based on jQuery (see http://stackoverflow.com/a/17954882/1322410)
if (typeof define === "function" && define.amd) {
    define("mailcheck", [], function () {
        return Mailcheck;
    });
}

if (typeof window !== 'undefined' && window.jQuery) {
    (function ($) {
        $.fn.mailcheck = function (opts) {
            var self = this;
            if (opts.suggested) {
                var oldSuggested = opts.suggested;
                opts.suggested = function (result) {
                    oldSuggested(self, result);
                };
            }

            if (opts.empty) {
                var oldEmpty = opts.empty;
                opts.empty = function () {
                    oldEmpty.call(null, self);
                };
            }

            opts.email = this.val();
            Mailcheck.run(opts);
        };
    })(jQuery);
};
String.prototype.stripFromHtml = function stripFromHtml() {
    return this.replace(/<\/?[^>]+(>|$)/g, "");
};

$.fn.addDistinctClass = function (className) {
    if (!this.hasClass(className)) {
        this.addClass(className);
    }
};

$.fn.isEmpty = function () {
    return !$.trim(this.html());
};

$.fn.stripFromHtml = function () {
    return this.replace(/<\/?[^>]+(>|$)/g, "");
};

$.fn.readMore = function (length, labelResource, onlyForMobile, stripFromHtml) {
    onlyForMobile = onlyForMobile || false;
    var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent));
    if ((isMobile && onlyForMobile) || (!onlyForMobile)) {
        var _content = this.html();
        if (!!_content && _content.length > length) {
            //remove trailing spaces
            _content = _content.trim();
            //change non-breaking space 
            _content = _content.replace(/&nbsp;/g, ' ');

            var _c_Unstripped = _content.substr(0, length);
            var _h_Unstripped = _content.substr(length, _content.length - length);
            _content = stripFromHtml ? _content.stripFromHtml() : _content;
            var _c = _content.substr(0, length);
            //var _h = _content.substr(length, _content.length - length);
            var _html = _c + '<span class="readMore trigger">' + labelResource + '</span>';
            this.html(_html);
            this.click(function () {
                $(this).toggleClass("expanded");
                if ($(this).hasClass("expanded")) {
                    $(this).html(_c_Unstripped + _h_Unstripped);
                }
                else {
                    $(this).html(_html);
                }
            });
        }
    }
};

$.fn.isInViewPort = function () {
    var top = $(this).offsetTop;
    var left = $(this).offsetLeft;
    var width = $(this).offsetWidth;
    var height = $(this).offsetHeight;
    while ($(this).offsetParent) {
        $(this) = $(this).offsetParent;
        top += $(this).offsetTop;
        left += $(this).offsetLeft;
    }
    return (
        top < (window.pageYOffset + window.innerHeight) &&
        left < (window.pageXOffset + window.innerWidth) &&
        (top + height) > window.pageYOffset &&
        (left + width) > window.pageXOffset
    );
};

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$.fn.findOrCreate = function (selector, defaultTag) {
    defaultTag = defaultTag || 'div';
    var _element = $(this).find(selector);

    if (!_element.length) {
        if (selector.lastIndexOf('.', 0) === 0)
            _element = $(defaultTag).appendTo(this).addClass(selector.replace('.', ''));

        else if (selector.lastIndexOf('#', 0) === 0)
            _element = $(defaultTag).appendTo(this).attr('id', selector.replace('.', ''));
    }
    else
        _element = $(selector).appendTo(this);
    return _element;
};
$.fn.hasScrollBar = function (fullWindowMatch) {
    if (fullWindowMatch)
    {
        var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
        return this.height() > h;
    }
    else
        return this.get(0).scrollHeight > this.height();
};;
jQuery.fn.load = function (callback) { $(window).on("load", callback) };

function OverlayOn(parentSelector, permanent) {
    var overlayPosition = (parentSelector !== "body") ? "absolute" : "fixed";
    var spinnerTag = $('body').hasClass('rebranding-layout') ? '<i class="spinner"></i>' : '<span class="ajax-loader"></span>'

    var classes = 'overlay'
    if (permanent) {
        classes += ' permanent';
    }

    $(parentSelector).css({ position: "relative" });
    $("<div id='overlay' class='" + classes + "'></div>").css({
        position: overlayPosition,
        top: 0,
        left: 0,
        bottom: 0,
        right: 0,
        background: "rgba(255, 255, 255, 0.3)",
        zIndex: 1000000,
    }).html(spinnerTag)
        .appendTo($(parentSelector));
}

function OverlayOff() {
    $("#overlay:not(.permanent)").each(function () {
        $(this).fadeOut("fast", function () { $(this).remove(); });
    });
}

var AsynchronousPartialViewLoading =
{
    init: function (element) {
        $(element).each(function (index, item) {
            var url = $(item).data("url");
            if (url && url.length > 0) {
                $(item).load(url);
            }
        });
    }
};

function GetLanguagePrefix() {
    var langPrefix = '';
    var tempLang = getRouteValueAtIndex(3);

    if (tempLang !== undefined) {
        if (tempLang.indexOf('?') >= 0 && tempLang.substring(0, tempLang.indexOf('?') === 2)) {
            langPrefix = tempLang.substring(0, tempLang.indexOf('?')) + '/';
        }
        else if (tempLang.length == 2) {
            langPrefix = tempLang + '/';
        }
    }

    return langPrefix;
}

/* Post call to controller */
function CallController(controller, actionMethod, args, callback, options) {

    GetAntiForgeryToken(args);

    var def = {
        Overlay: false,
        OverlayParent: "body"
    };
    options = $.extend(def, options);
    var url = '/' + GetLanguagePrefix() + controller + '/' + actionMethod;

    if (args.Overlay || options.Overlay) {
        // Add Spinner
        OverlayOn(options.OverlayParent);
        window.OverlayCaller = url;
    }

    $.post(url, args)
        .done(function (response) {
            callback(response);
        }).fail(function (response) {
            var error = $(jQuery.parseHTML(response.responseText)).find("h2.text-danger").text();
            response.error = error;
            callback(response);
        }).always(function () {
            //Delete spinner
            if (window.OverlayCaller === this.url) {
                OverlayOff();
            }
        });
}

function GetController(controller, actionMethod, params, callback) {
    var url = '/' + GetLanguagePrefix() + controller + '/' + actionMethod;
    if (params)
        url = url + '?' + serialize(params);

    $.get(url)
        .done(function (response) {
            callback(response);
        }).fail(function (response) {
            var error = $(jQuery.parseHTML(response.responseText)).find("h2.text-danger").text();
            response.error = error;
            callback(response);
        });
}

var serialize = function (obj) {
    var str = [];
    for (var p in obj)
        if (obj.hasOwnProperty(p)) 
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
}

function GetAntiForgeryToken(args) {
    var tokenInput = $("input[name=__RequestVerificationToken]");
    if (tokenInput != undefined)
        args.__RequestVerificationToken = tokenInput.val();

}

var Ajax = {
    POST: function AjaxPOST(url, options) {
        options = options || {};

        $.ajax({
            url: "/" + GetLanguagePrefix() + url,
            method: "POST",
            data: options.data,
            success: options.success,
            error: options.error
        });
    }
}

//GetRouteParameter
function getRouteValueAtIndex(index) {
    var str = window.location.href;
    return str.split("/")[index];
}
//GetRouteParameterWithEndSlash
function getRouteValueAtIndexWithSlash(index) {
    if (getRouteValueAtIndex(index) !== undefined && getRouteValueAtIndex(index).length === 2) {
        return getRouteValueAtIndex(index) + '/';
    }
    else
        return "";
}

function GoTo(url) {
    window.document.location = url;
}

var InfoModal =
{
    Show: function (title, body, btnCloseText) {
        $('#infoModal').css('z-index', 99999999);

        $('#infoModal')
            .find('.modal-footer')
            .children('.yes-button')
            .hide();

        $('#infoModal').find('.modal-title').text(title);
        $('#infoModal').find('.modal-body').html(body);
        $('#infoModal').find('.modal-content').html(body);
        $('#infoModal').find('.modal-footer').children('.btn-default').text(btnCloseText);

        $('#infoModal').modal('show');
    },
    Confirm: function (title, body, btnConfirmText, btnCloseText, callback) {

        var modal = $('#infoModal').clone();

        modal.css('z-index', 99999999);
        modal.find('.modal-title').text(title);
        modal.find('.modal-body').html(body);
        modal.removeAttr('id');

        var cancelBtn = modal
            .find('.modal-footer')
            .children('.btn-default')
            .text(btnCloseText);

        var confirmBtn = modal
            .find('.modal-footer')
            .children('.yes-button')
            .text(btnConfirmText);

        confirmBtn.show();

        confirmBtn.on('click', function () {
            callback();
        });

        modal.on('hidden.bs.modal', function (e) {
            modal.remove();
        })
        modal.modal('show');
    },
    InfoBox: function (title, body) {
        var modal = $('#infoModal').clone(),
            closeHtml = modal.find('.close').prop('outerHTML');

        modal.css('z-index', 99999999);
        modal.find('.modal-footer').remove();
        modal.find('.modal-header').remove();

        modal.find('.modal-body').html(
            closeHtml
            + "<h3 style=\"margin-top:0;\">" + title + "</h3>"
            + body);

        modal.modal('show');

        modal.on('hidden.bs.modal', function (e) {
            modal.remove();
        })
    },

};

//=========== InfoPanel  ==============
function ShowInfoTooltip(infoText, messageType, hideTimeout) {
    $('#infoTooltip').find('.content').html(infoText);
    var classToSet = 'well well-' + messageType;
    $('#infoTooltip').find('.well').attr('class', classToSet);

    if ($('#infoTooltip').hasClass('modal')) {
        $('#infoTooltip').addClass('active');
    } else {
        $('#infoTooltip').collapse('show');
        if (hideTimeout > 0)
            setTimeout(function () { $('#infoTooltip').collapse('hide'); }, hideTimeout);
    }
}

function HideInfoTooltip(sender) {
    if ($('#infoTooltip').hasClass('modal')) {
        $('#infoTooltip').removeClass('active');
    } else {
        $(sender).parents('.collapse').collapse('hide');
    }

}

//=========== Discount and vouchers  ==============
function FocusAfterExpand() {
    if ($('#discountLabel').attr('aria-expanded') === 'false') {
        window.setTimeout(function () { document.getElementById('tbDiscount').focus(); }, 1);
    }
}

function TruncateProductDesc() {
    var $sender = $(".R_product_grid_description, .product-desc");
    $sender.each(function () {
        var p = $(this).find("p");
        $(p).text($(this).attr("title"));
        while ($(p).outerHeight() > $(this).height())
            $(p).text(function (index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
    });
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode !== 46 && charCode > 31
        && (charCode < 48 || charCode > 57) && charCode !== 44 && charCode !== 46)
        return false;

    return true;
}

//=========== GTM Ecommerce ==============
this.addEventListener('sendPostCodeEvent',
    function (arg) {
        GTM.SubmitPostCode('postCodeCheckout', arg.detail);
    }
);

function IsExpanded(element) {
    return $('#' + element).attr('aria-expanded') === 'false' ? 'Show' : 'Hide';
}


/****************** Product Sorting *********************/
var ProductSort = {
    SortingOrder: 0,
    SortingBy: 0,
    SortingAttribute: "",
    Sort: function (sender, productListParentSelector, isRebranding) {
        var $sender = $(sender),
            $products;
        if ($sender.find("option:selected").val() !== 0) {
            if (!isRebranding) {
                $('#ddlSort').each(function () {
                    $(this).selectpicker('val', $sender.find("option:selected").val());
                });

                $products = $(productListParentSelector).find(".product");
            } else {
                $products = $(productListParentSelector).find(".category-item");
            }

            this.SortingOrder = $sender.find("option:selected").data("sort-order");

            this.SortingBy = $sender.find("option:selected").data("sort-by");
            if (this.SortingBy === 0) {
                this.SortingAttribute = "sortPrice";
            }
            if (this.SortingBy === 1) {
                this.SortingAttribute = "sortName";
            }

            if (typeof this.SortingBy === "undefined" || this.SortingBy === null) {
                this.SortingAttribute = "sortPosition";
            }

            var $sortedDivs;

            $sortedDivs = this.ProductQuickSort($products);

            $(productListParentSelector).fadeOut("fast", function () {
                $(productListParentSelector).html($sortedDivs);
                $(productListParentSelector).fadeIn("fast");
            });
        }
    },
    ProductQuickSort: function (items, left, right) {
        var index;
        if (items.length > 1) {
            left = typeof left !== "number" ? 0 : left;
            right = typeof right !== "number" ? items.length - 1 : right;
            index = this.Partition(items, left, right);
            if (left < index - 1) {
                this.ProductQuickSort(items, left, index - 1);
            }
            if (index < right) {
                this.ProductQuickSort(items, index, right);
            }
        }
        return items;
    },
    Partition: function (items, left, right) {
        var pivot = items[Math.floor((right + left) / 2)],
            i = left,
            j = right;
        while (i <= j) {
            var $i = $(items[i]).find("[data-sort-type=" + this.SortingAttribute + "]").data("sort-val").toString().replace(",", ".");
            var $j = $(items[j]).find("[data-sort-type=" + this.SortingAttribute + "]").data("sort-val").toString().replace(",", ".");
            var $pivot = $(pivot).find("[data-sort-type=" + this.SortingAttribute + "]").data("sort-val").toString().replace(",", ".");
            if (this.SortingBy === 0) {
                $i = parseFloat($i);
                $j = parseFloat($j);
                $pivot = parseFloat($pivot);
            }
            if (this.SortingOrder === 0) {
                while ($i < $pivot) {
                    i++;
                    $i = $(items[i]).find("[data-sort-type=" + this.SortingAttribute + "]").data("sort-val").toString().replace(",", ".");
                    if (this.SortingBy === 0)
                        $i = parseFloat($i);
                }
                while ($j > $pivot) {
                    j--;
                    $j = $(items[j]).find("[data-sort-type=" + this.SortingAttribute + "]").data("sort-val").toString().replace(",", ".");
                    if (this.SortingBy === 0)
                        $j = parseFloat($j);
                }
            }
            else {
                while ($i > $pivot) {
                    i++;
                    $i = $(items[i]).find("[data-sort-type=" + this.SortingAttribute + "]").data("sort-val").toString().replace(",", ".");
                    if (this.SortingBy === 0)
                        $i = parseFloat($i);
                }
                while ($j < $pivot) {
                    j--;
                    $j = $(items[j]).find("[data-sort-type=" + this.SortingAttribute + "]").data("sort-val").toString().replace(",", ".");
                    if (this.SortingBy === 0)
                        $j = parseFloat($j);
                }
            }
            if (i <= j) {
                this.Swap(items, i, j);
                i++;
                j--;
            }
        }
        return i;
    },
    Swap: function (items, firstIndex, secondIndex) {
        var temp = items[firstIndex];
        items[firstIndex] = items[secondIndex];
        items[secondIndex] = temp;
    }
};

function FillAddonPopup(sender, popupSelector, canBeAdded, ExtendedDescriptionEnable) {
    canBeAdded = typeof canBeAdded === "undefined" || canBeAdded === null ? true : canBeAdded;
    ExtendedDescriptionEnable = typeof ExtendedDescriptionEnable === "undefined" || ExtendedDescriptionEnable === null ? false : ExtendedDescriptionEnable;
    var $popup = $(popupSelector);
    var $addon = $(sender).closest(".element");

    $popup.find("img:not(.close-icon)").prop("src", $addon.find(".hfAddonImage").val());
    $popup.find("img:not(.close-icon)").prop("alt", $addon.find(".hfAddonName").val());
    $popup.find(".name").text($addon.find(".hfAddonName").val());
    $popup.find(".buy").attr("onclick", "$('body').css('overflow', 'auto');" + $addon.find(".hfAddonClick").val());
    $popup.find(".price").text($addon.find(".hfAddonPrice").val());
    $popup.find(".desc").text($addon.find(".hfAddonDesc").val());
    $popup.find('.body').removeClass('hidden');
    $popup.find('.popup-extension').addClass('hidden');
    $popup.find(".popup-extension-show").addClass('hidden');

    if (ExtendedDescriptionEnable) {
        $popup.find(".extended-desc").html($addon.find(".hfAddonExtendedDesc").val());
        $popup.find(".popup-extension-show").removeClass("hidden");
    }

    if (canBeAdded) {
        $popup.find(".buy").removeAttr("disabled");
    } else {
        $popup.find(".buy").attr("disabled", "disabled");
    }
}

var Popup = {
    Show: function (popupSelector, lockScrolling, detach) {
        lockScrolling = typeof lockScrolling !== "undefined" ? lockScrolling : true;
        detach = typeof detach !== "undefined" ? detach : false;
        var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent));

        var $popup = $(popupSelector);
        if (detach) {
            $popup.detach();
            $popup.appendTo("body");
        }
        $popup.fadeTo(500, 1);
        $popup.show();
        if ($popup.hasClass('modal'))
            $popup.addClass('active');

        if (lockScrolling && $("body").hasScrollBar(true)) {
            if (!isMobile)
                $("body").css("margin-right", "17px");
        }
    },
    Populate: function (popupSelector, popupHeader, popupBody) {
        var $popup = $(popupSelector);
        var $h2 = $popup.findOrCreate('h2');
        $h2.text(popupHeader);
        $popup.append(popupBody);
    },
    Hide: function (popupSelector, callback) {
        var $popup = $(popupSelector);
        $popup.fadeTo(500, 0).promise().done(function () {
            $popup.hide();
        });
        $("body").css("margin-right", "0");
        $('body').removeClass('ios-bug-caret');
        setTimeout(callback, 1000);

        if ($popup.hasClass('modal'))
            $popup.removeClass('active');
    },
};

var MailCheck = {
    Check: function (sender, tbid, panelid, mailaclass) {
        $(sender).mailcheck({
            suggested: function (element, suggestion) {
                var panel = $('#' + panelid);
                var a = $('a[class="' + mailaclass + '"]');

                panel.show();
                a.on('click', function () {
                    MailCheck.HideAndFill(suggestion.full, tbid, panelid);
                });
                a.text(suggestion.full);
            },
            empty: function (element) {
                $('#' + panelid).hide();
            }
        });
    },
    HideAndFill: function (email, tbid, panelid) {
        $('#' + tbid).val(email);
        $('#' + panelid).hide();
    }
};

Date.prototype.addDays = function (days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function UpdateShippingFees(orderKey, deliveryDate, panelId, _callback) {
    //SaveOrder();

    _callback = _callback || function () {
        return true;
    };

    var callback = function (data) {
        $('#' + panelId).html(data);
        $('.selectpicker').selectpicker();
        $('.selectpicker').on('change', function () {
            var selected = $(this).find("option:selected");
            //SaveOrder();            
            ChangeBasketPreview({ orderKey: selected.data("orderkey"), pageUpdatePanel: selected.data("pageupdatepanel") }, '#' + selected.data("pageupdatepanel"));
        });
        _callback();
    };

    CallController("Checkout", "UpdateShippingFees", { orderKey: orderKey, deliveryDate: deliveryDate, panelId: "cartPreviewUpdatePanel" }, callback, null);
}

var Quantity = {
    timer: '',
    selector: '#Quantity',
    delayChangingQuantity: function (args, updatePanel) {
        clearTimeout(this.timer);
        this.updateQuantity(args, updatePanel)
    },
    updateQuantity: function (args, updatePanel) {
        var updateView = '';
        args.Quantity = parseInt($(this.selector).val());
        this.timer = setTimeout(function () {
            CallController('Checkout', 'UpdateProductQuantity', args, updateView);
        }, 700);

        updateView = function (data) {
            if (updatePanel !== undefined) {
                $('#' + updatePanel).html(data);
            }
        };
    },
    updateSpinner: function (obj) {
        var QuantityObj = document.getElementById("Quantity"),
            value = parseInt(QuantityObj.value);

        if (obj.id === "minus" && value > 1) {
            value--;
        }
        else if (obj.id === "plus") {
            if (value < 9999)
                value++;
        }
        if (isNaN(value)) {
            value = 1;
        }
        QuantityObj.value = value;
    }
};

function checkQuantityValue() {
    if ((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 95 && event.keyCode < 106) || event.keyCode == 8)
        return;
    else
        event.preventDefault();
}

function ChangeNewsletterAttribute(cb) {
    if ($(cb).attr('data-action') == 'opt_out') {
        $(cb).attr('data-action', 'opt_in');
    }
    else if ($(cb).attr('data-action') == 'opt_in') {
        $(cb).attr('data-action', 'opt_out');
    }
}

function GetDownloadContentButton() {
    if ($("#downloadBtnContainer")[0] != undefined) {
        var callback = function (data) {
            if (data !== false) {
                $("#downloadBtnContainer").html(data);
            }
        };

        CallController("ContentPage", "GetDownloadContentButton", { pageType: $("#PageType").val() }, callback, null);
    }
}

function LoginCallback(result) {
    if (result.success) {
        if (result.switchTypeNeeded) {
            setRedirectsOnCorpEnterPopup(result.url);
            Popup.Show('#corporate-enter-popup', true, true, true);
        }
        else
            window.location.replace(result.url);
    }
    else {
        $('#login-panel').html(result.view);
    }
}

function setRedirectsOnCorpEnterPopup(url) {
    $("#close-corp-enter, #btn-corp-enter").on('click', function () {
        window.location.replace(url);
    });
}

function UpdateContactDetails(args, updatePanel, showFields) {
    var callback = function (data) {
        if (data.error === undefined || data.error === null || data.error === "") {
            if (showFields)
                ShowRecipientDetailsFields();
            $('#tbRecipientAddress1').val(data.Address1);
            if (showFields && $('#tbRecipientAddress1').length > 0)
                $("#SaveContact").validate().element("#tbRecipientAddress1");

            $('#tbRecipientAddress2').val(data.Address2);
            if (showFields && $('#tbRecipientAddress2').length > 0)
                $("#SaveContact").validate().element("#tbRecipientAddress2");

            $('#tbRecipientPostCode').val(data.PostCode);
            if (showFields && $('#tbRecipientPostCode').length > 0)
                $("#SaveContact").validate().element("#tbRecipientPostCode");

            $('#tbRecipientCity').val(data.City);
            if (showFields && $('#tbRecipientCity').length > 0)
                $("#SaveContact").validate().element("#tbRecipientCity");

            $('#tbRecipientCounty').val(data.County);
            if (showFields && $('#tbRecipientCounty').length > 0)
                $("#SaveContact").validate().element("#tbRecipientCounty");

            $(updatePanel).empty();
        }
        else {
            ShowInfoTooltip(data.error, 'danger', 5000);
            ShowRecipientDetailsFields();
        }
    };

    CallController("Customer", "UpdateContactDetails", args, callback, null);
}

function LanguageChangedByUser(anchor, e) {
    e.preventDefault();
    var href = $(anchor).attr('href');
    CallController("Home", "LangChangedByUser", {}, function () {
        window.location.replace(href);
    });
    return false;
}


var ScrollPos = {
    cookieName: "scroll_pos",
    save: function () {
        Cookie.set(ScrollPos.cookieName, window.scrollY, 10);
    },

    load: function () {
        var pos = Cookie.get(ScrollPos.cookieName);
        if (!!pos) {
            window.scrollTo(0, pos);
        }

        Cookie.delete(ScrollPos.cookieName);
    }
};

function SubmitOnCallback(elem, funcWithCallback, e, addOverlay) {
    if (!!e) {
        e.preventDefault();
    }

    var submitCallback = function () {
        $(elem).closest("form").submit();
        GTM.GetValidationErrors();
    };

    if (addOverlay) {
        $(elem).closest("form").validate();
        var isFormValid = $(elem).closest("form").valid();
        if (!isFormValid) {
            GTM.GetValidationErrors();
            return false;
        }
        OverlayOn('body', true);
    }

    funcWithCallback(submitCallback);
}

function adjustBoxHeight() {
    var boxes = $('.p-desc'),
        height = 0,
        indexArray = 0,
        allHeight = [],
        allHeightSorted = [];

    boxes.each(function (index, element) {
        height = $(element).innerHeight();
        allHeight.push(height);
    });

    indexArray = allHeight.length - 1;
    allHeightSorted = allHeight.sort();
    $('.p-desc').height(allHeightSorted[indexArray]);
}

function removeTabsDatepicker(selector) {
    var tab = $(selector)
    for (var i = 0; i < tab.length; i++) {
        var element = tab[i];
        $(element).attr('tabindex', '-1');
    }
}

function getRouteType() {
    return $('body').data('route-type') || 0;
}

function getRecipientOptions(orderKey, selector) {
    $.ajax({
        url: "/" + GetLanguagePrefix() + "Checkout/GetRecipientOptions",
        data: { orderKey: orderKey, routeType: getRouteType },
        type: 'POST'
    }).done(function (data) {
        $('#' + selector).html(data);
    });
}

function getAddonSliderActiveItemNos() {
    var items = document.querySelectorAll(".addons-slider .slider .visible .hfItemNo");
    var itemNos = [];
    for (var i = 0; i < items.length; i++) {
        itemNos.push(items[i].value);
    }
    return itemNos;
}

$(document).on('click', '.content-page_video-poster', function (e) {
    e.preventDefault();
    var poster = $(this);
    var wrapper = poster.closest('.content-page_video');
    videoPlay(wrapper);
});

function videoPlay(wrapper) {
    var iframe = wrapper.find('.content-page_video-iframe');
    var src = iframe.data('src');
    wrapper.addClass('content-page_video-active');
    iframe.attr('src', src);
}

function isElementInViewport(el) {
    if (el !== typeof undefined && el.length > 0) {
        //special bonus for those using jQuery
        if (typeof jQuery === "function" && el instanceof jQuery) {
            el = el[0];
        }

        var rect = el.getBoundingClientRect();

        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }
}

function LogFatalError(message) {
    message = message + ". User agent: " + navigator.userAgent;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/Home/LogJsFatal', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("message=" + JSON.stringify(message));
}

function LogError(message) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/Home/LogJsError', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("message=" + JSON.stringify(message));
}

function UpdateGiftFinderOccassion() {

    var callback = function (result) {
        $('#hfGiftFinderCategoryUrl').val(result);
    };

    if ($('#ddlOccasions').valid()) {
        values = {
            ChosenOccassion: $('#ddlOccasions').val(),
            PageType: $('#hfPageType').val(),
            MainId: $('#hfCategoryId').val()
        };
        CallController("Product", "UpdateGiftFinderOccassion", values, callback, null);
    }
}

var ProductDetailPopup = {
    init: function (imageSelector, btnSelector, nameSelector, closeTranslation) {
        document.querySelector(imageSelector).addEventListener('click', function () {
            ProductDetailPopup.show(imageSelector, nameSelector, closeTranslation);
        });
        document.querySelector(btnSelector).addEventListener('click', function () {
            ProductDetailPopup.show(imageSelector, nameSelector, closeTranslation);
        });
    },
    show: function (imageSelector, nameSelector, closeTranslation) {
        var image = document.querySelector(imageSelector).querySelector('img').getAttribute('src'),
            name = document.querySelector(nameSelector).textContent,
            popup = document.createElement('div');

        if (!document.querySelector('#ProductDetailPopup')) {
            popup.classList.add('product-detail-popup');
            popup.id = 'ProductDetailPopup';
            popup.innerHTML = '<div class="product-detail-popup-nav"><span class="product-detail-popup-close" onclick="ProductDetailPopup.close();"><i class="icon-arrow-left"></i>' + closeTranslation + '</span><span class="product-detail-popup-name">' + name + '<span></div><div class="product-detail-popup-image"><img class="img-responsive" src="' + image + '"></div>';
            document.querySelector('body').appendChild(popup);
        }
    },
    close: function () {
        var popup = document.querySelector('#ProductDetailPopup');
        popup.parentNode.removeChild(popup);
    }
}

function LoginPopupCallbackRebranding(result, partsToReload) {
    try {
        if (result.success) {
            $('#closePopupLoginBtn').click();
            ReloadPanels();
            ReloadBasketPreview(partsToReload);
        }
        else {
            $("#logInPanel").html(result.updatePanel);
        }
    } catch (exception) {
        LogFatalError("Error on LoginPopupCallbackRebranding. Exception: " + exception.message);
    }
}

function removeWhitespaces(input) {
    var elem = $(input);
    if (elem.length !== 0) {
        elem.val(elem.val().replace(/\s/g, ''));
    }
}

function AdjustSortingDropdown() {
    if ($('.sort-dropdown').val() !== undefined) {
        if ($('#productListUpdatePanel').find(".product").length > 0) {
            $('.sort-dropdown').val(0);
            $('.sort-dropdown').selectpicker('refresh');
            $('.sort-dropdown').removeAttr('style');
        }
        else {
            $('.sort-dropdown').hide();
        }
    }
}

function HidePromoBanner() {
    if ($('#readMore').val() !== undefined) {

        if ($('#gfNoResult').val() !== undefined)
            $('#readMore').hide();
        else
            $('#readMore').show();
    }
}
;
function ExecuteJquery(script, executeAtDocumentReady) {
    executeAtDocumentReady = executeAtDocumentReady || false;

    if (typeof jQuery === "undefined" || typeof $.validator === 'undefined') {
        document.addEventListener('DOMContentLoaded', function () {
            script();
        });
    }
    else {
        if (executeAtDocumentReady) {
            $(document).ready(script);
        }
        else {
            script();
        }
    }
}

//TODO this is crap that has unresolved dependiencies to jquery based functions (i.e. GetLanguagePrefix)
var Request = (function () {
    function prepareRequest(type, controller, action, body, callback, options) {
        var request = new XMLHttpRequest(),
            url = '/' + GetLanguagePrefix() + controller + '/' + action;

        if (options.overlayParent) {
            Overlay.on(options.overlayParent, options.permanent);
        }

        request.open(type.toUpperCase(), url, true);
        request.onreadystatechange = function () {
            if (request.readyState === 4 && request.status === 200) {
                callback(request.responseText);
            } else {
                //var error =  $(jQuery.parseHTML(request.responseText)).find("h2.text-danger").text();
                //request.error = error;
                callback(request.statusText + ':' + request.status);
            }
        };

        request.send(body);
        Overlay.off();
    }

    return {
        post: function (controller, action, body, callback, options) {
            prepareRequest('post', controller, action, body, callback, options);
        },
        get: function (controller, action, callback, options) {
            prepareRequest('get', controller, action, null, callback, options);
        }
    };
})();

var Animation = (function () {
    function preparePortionValue(time) {
        time = time <= 10 ? 20 : time;
        return (1 / (time / 10));
    }

    return {
        fadeOut: function (el, time, callback) {
            el.style.opacity = 1;
            var portion = preparePortionValue(time);

            (function fade() {
                if ((el.style.opacity -= portion) <= 0) {
                    el.style.display = "none";
                } else {
                    requestAnimationFrame(fade);
                }
            })();

            if (callback) {
                callback();
            } 
        },
        fadeIn: function (el, display, time, callback) {
            el.style.opacity = 0;
            el.style.display = display || 'block';
            var portion = preparePortionValue(time);

            (function fade() {
                var val = parseFloat(el.style.opacity);
                if (!((val += portion) >= 1)) {
                    el.style.opacity = val;
                    requestAnimationFrame(fade);
                }
            })();

            if (callback) {
                callback();
            }
        }
    };
})();

var Overlay = {
    on: function (parentSelector, permanent) {
        var overlayPosition = parentSelector !== "body" ? "absolute" : "fixed",
            classes = 'overlay';

        if (permanent) {
            classes += ' permanent';
        } 
        
        var parent = document.querySelector(parentSelector);
        parent.position = 'relative';
        var overlay = document.createElement('div');
        overlay.className = classes;
        overlay.setAttribute('id', 'overlay');
        overlay.position = overlayPosition;
        var loader = document.createElement('span');
        loader.classList.add('ajax-loader');
        overlay.appendChild(loader);
        parent.appendChild(overlay);
    },
    off: function () {
        var overlays = document.querySelectorAll('.overlay:not(.permanent)');
        Array.prototype.forEach.call(overlays, function (element) {
            Animation.fadeOut(element, 200, function () { element.remove(); });
        });
    }
};

function ApplyReadMoreWrapper(idOfElementToWrap, length, labelResource, onlyForMobile, stripFromHtml) {
    onlyForMobile = onlyForMobile || false;
    var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent));
    if ((isMobile && onlyForMobile) || (!onlyForMobile)) {
        var elementToWrap = document.getElementById(idOfElementToWrap);
        var content = elementToWrap.innerHTML;
        if (!!content && content.length > length) {
            //remove trailing spaces
            content = content.trim();
            //change non-breaking space 
            content = content.replace(/&nbsp;/g, ' ');

            var visiblePartUnstripped = content.substr(0, length);
            var hiddenPartUnstripped = content.substr(length, content.length - length);
            content = stripFromHtml ? content.replace(/<\/?[^>]+(>|$)/g, "") : content;
            var visiblePart = content.substr(0, length);
            var html = visiblePart + '<span class="readMore trigger">' + labelResource + '</span>';
            elementToWrap.innerHTML = html;
            elementToWrap.addEventListener('click', function() {
                elementToWrap.classList.toggle("expanded");
                if (elementToWrap.classList.contains("expanded")) {
                    elementToWrap.innerHTML = visiblePartUnstripped + hiddenPartUnstripped;
                }
                else {
                    elementToWrap.innerHTML = html;
                }
            });
        }
    }
};
;
function getBaseRequest() {
	return {
		apiVersion: 2,
		apiVersionMinor: 0
	};
}

var allowedCardNetworks = ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"];
var allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];

function getTokenizationSpecification(gatewayMerchantId) {
	return {
		type: "PAYMENT_GATEWAY",
		parameters: {
			'gateway': "adyen",
			'gatewayMerchantId': gatewayMerchantId
		}
	};
};

function getBaseCardPaymentMethodConfig() {
	return {
		type: "CARD",
		parameters: {
			allowedAuthMethods: allowedCardAuthMethods,
			allowedCardNetworks: allowedCardNetworks,
			billingAddressRequired: false
		}
	};
}


var googlePayPaymentsClient = null;

function getGoogleIsReadyToPayRequest() {
	var request = getBaseRequest();
	request.allowedPaymentMethods = [getBaseCardPaymentMethodConfig()];

	return request;
}

function getGooglePaymentDataRequest(merchantId, gatewayMerchantId, currency, price) {
	var paymentDataRequest = getBaseRequest();

	var method = getBaseCardPaymentMethodConfig();
	method.tokenizationSpecification = getTokenizationSpecification(gatewayMerchantId);

	paymentDataRequest.allowedPaymentMethods = [method];
	paymentDataRequest.transactionInfo = getGoogleTransactionInfo(currency, price);
	paymentDataRequest.merchantInfo = {
		// @todo a merchant ID is available for a production environment after approval by Google
		// See {@link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist|Integration checklist}
		merchantId: merchantId,
		merchantName: "Euroflorist"
	};
	return paymentDataRequest;
}

function getGooglePaymentsClient(environment) { //TEST,PRODUCTION
	if (googlePayPaymentsClient === null) {
		googlePayPaymentsClient = new google.payments.api.PaymentsClient({ environment: environment });
	}
	return googlePayPaymentsClient;
}

function loadGooglePay(environment, callback) {
	var paymentsClient = getGooglePaymentsClient(environment);
	paymentsClient.isReadyToPay(getGoogleIsReadyToPayRequest())
		.then(function(response) {
			callback && callback(response.result);
		})
		.catch(function(err) {
			callback && callback(false);
			LogFatalError("Error on loading Google Pay: " + err);
		});
}

function getGoogleTransactionInfo(currency, price) {
	return {
		currencyCode: currency,
		totalPriceStatus: "FINAL",
		totalPrice: "" + price //as string '123.12'
	};
}

function payWithGoogle(merchantId, gatewayMerchantId, environment, currency, price, callback) {
	try {
		var paymentDataRequest = getGooglePaymentDataRequest(merchantId, gatewayMerchantId, currency, price);
		paymentDataRequest.transactionInfo = getGoogleTransactionInfo(currency, price);

		var paymentsClient = getGooglePaymentsClient(environment);
		paymentsClient.loadPaymentData(paymentDataRequest)
			.then(function(paymentData) {
				var token = paymentData.paymentMethodData.tokenizationData.token;
				$("#googlepaytoken").val(token);
				callback && callback();
			})
			.catch(function(err) {
				// show error in developer console for debugging
				var errorMsg = "Google Pay payment | " + JSON.stringify(err);
				if (err.statusCode === "DEVELOPER_ERROR") {
					LogFatalError(errorMsg);
				} else {
					LogError(errorMsg);
				}

				location.reload();
			});
	} catch (e) {
		LogFatalError("Error on Google Pay payment: " + JSON.stringify(e));
	}
};
$(document).on('click', '.bootstrap-select .dropdown-menu ul li', function () {
    var index = $(this).attr('data-original-index');
    var $select = $(this).closest(".form-group").find("select");
    $($select.children()[index]).prop('selected', true);
    if (IsRequired($select))
        $select.valid();
});
function IsRequired($field) {
    return !(!$field.attr('data-val-required')) || $field.attr('aria-required') || $field.prop('required');
}
document.addEventListener('DOMContentLoaded', function () {
    $("select[id$='DeliveryDate']").change(function () {
        var selectedIndex = $(this)[0].selectedIndex;
        var $selectElement = $($(this).children()[selectedIndex]);

        if (!!(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent))) {
            var deliveryText = $selectElement.attr("data-subtext");
            var $textPlacement = $(this).parents(".form-group").find(".delivery-text");
            if (deliveryText.length > 0) {

                $textPlacement.find("p").html(deliveryText);
                $textPlacement.attr("style", "display : block !important;");
            }
            else {
                $textPlacement.find("p").html("");
                $textPlacement.attr("style", "display : none !important;");
            }
        }
    });
});;
function PreventDefault(event) {
    if (event != null && typeof event !== "undefined")
        event.preventDefault();
};

function TruncateCategoryDesc() {
    var $sender = $(".R_category_desc");
    $sender.each(function () {
        var p = $(this).find("p")
        $(p).text($(this).attr("title"));
        while ($(p).outerHeight() > $(this).height())
            $(p).text(function (index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
    });
}

var SideMenu = {
    Init: function (btn, body) {
        this.MenuWidth = $(btn).data("menu-width");
        this.BindControls(btn, body);
    },
    BindControls: function (btn, body) {
        var self = this;
        $(".moonraker").on("click", btn,
            function (event) {
                SideMenu.Toggle(body, event);
                $('.navbar-moonraker').show(0);
            });
        $(".moonraker").on("swiperight", body, function (event) {
            if (self.getDomainMedia()) {
                SideMenu.Open(body, event, false);
                AnimatedMenu.changeStateOfHamburgerIcon(true);
            }
        });
        $(".moonraker").on("swipeleft", body, function (event) {
            if (self.getDomainMedia()) {
                SideMenu.Close(body, event, false);
                AnimatedMenu.changeStateOfHamburgerIcon(false);
            }
        });
        $(".overlay-mobile-menu").on("click", function (event) {
            if (self.getDomainMedia()) {
                    SideMenu.Close(body, event, false);
                    AnimatedMenu.changeStateOfHamburgerIcon(false);
            }
        });
    },
    getDomainMedia: function () {
        return getContentType() === "EuroWeb_v2" ? window.matchMedia("(max-width: 990px)").matches : window.matchMedia("(max-width: 767px)").matches;
    },
    MenuWidth: 0,
    Open: function (body, event, preventDef) {
        if (preventDef)
            PreventDefault(event);
        $(body).offset({ left: this.MenuWidth });
        $(body).find(".scroll-menu-wrapper").offset({ left: this.MenuWidth });
        $('.navbar-moonraker').addClass('active');
        window.AnimatedMenu.changeStateOfHamburgerIcon(true);
        this.Opened = true;
    },

    Close: function (body, event, preventDef) {
        if (preventDef)
            PreventDefault(event);
        $(body).offset({ left: 0 });
        $(body).find(".scroll-menu-wrapper").offset({ left: 0 });
        $('.navbar-moonraker').removeClass('active');
        window.AnimatedMenu.changeStateOfHamburgerIcon(false);
        this.Opened = false;
    },

    Toggle: function (body, event) {
        if (this.Opened)
            this.Close(body, event, true);
        else
            this.Open(body, event, true);
    },

    Opened: false
};


var AnimatedMenu = {
    Init: function () {
        var matchedDomainClass = this.checkDomainClass();
        if (matchedDomainClass.length !== 0) {
            this.showMenuOnScroll(matchedDomainClass);
        }
    },
    checkDomainClass: function () {
        var accepctedClasses = ["eflorist-en", "gdse-se", "primary-g2d", "primary-green", "ihampers-en"],
            bodyClassList = document.querySelector("body").classList,
            matchedClass = accepctedClasses.filter(function (n) {
                return bodyClassList.contains(n);
            });

        return matchedClass;
    },
    hamburgerIconInit: function (domainClass) {
        $('.' + domainClass + '.menu-trigger').click(function () {
            $('#nav-icon1').toggleClass('open');
        });
    },
    changeStateOfHamburgerIcon: function (isOpen) {
        if (isOpen) {
            $('#nav-icon1').addClass('open');
        } else {
            $('#nav-icon1').removeClass('open');
        }
    },
    showMenuOnScroll: function (domainClass) {
        var iScrollPos = 0,
            menuWrapper = $('body' + '.' + domainClass).find('.scroll-menu-wrapper'),
            posToShowMenu = $('body' + '.' + domainClass).find('.scroll-menu-wrapper').height(),
            moveUp = 0,
            moveDown = 0,
            tmpMenu = 0,
            initShow = true;

        $(window).scroll(function () {
            var iCurScrollPos = $(this).scrollTop();
            
            if (iCurScrollPos > posToShowMenu) {
                if (initShow) {
                    menuWrapper.addClass('hide-on-scroll hide-bottom-menu');
                    initShow = false;
                    moveDown = 0,
                        moveUp = 0;
                }

                if (iCurScrollPos > iScrollPos) {
                    ++moveDown,
                        moveUp = 0;
                    menuWrapper.addClass('hide-bottom-menu');

                    if (moveDown === 1) {
                        tmpMenu = iCurScrollPos;
                    }

                    if ((tmpMenu + posToShowMenu) < iCurScrollPos) {
                        menuWrapper.addClass('hide-on-scroll');
                    }
                    iScrollPos = iCurScrollPos;
                } else {
                    moveDown = 0,
                        ++moveUp;

                    if (moveUp === 1) {
                        tmpMenu = iCurScrollPos;
                    }

                    if ((tmpMenu - posToShowMenu) > iCurScrollPos) {
                        menuWrapper.removeClass('hide-bottom-menu');
                    }

                    if ((tmpMenu - posToShowMenu) === 0) {
                        menuWrapper.removeClass('hide-on-scroll hide-bottom-menu');
                    }
                    iScrollPos = iCurScrollPos;
                }
            } else {
                menuWrapper.removeClass('hide-on-scroll hide-bottom-menu');
                initShow = true;
            }
        });
    }
};

document.addEventListener('DOMContentLoaded', function () {
    SideMenu.Init(".navbar-toggle", ".mn-body");
    AnimatedMenu.Init();
    autoHideDropDown();
    ToggleSearch();

    $(document).on('focusin', 'input, textarea', function () {
        $('.mn-popup').addClass('unfixed');
    });
});

function autoHideDropDown() {
    var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent));
    if (isMobile)
        $(window).scroll(function () {
            $(".dropdown.open").removeClass("open");
        });

}

function ToggleSearch() {
    var searchForm = $('#fSearch');

    $('.euro-web-v2  #search-trigger').click(function (e) {
        var searchedValue = searchForm.find('input').val().trim();
        e.preventDefault();

        if (searchForm.hasClass('inactive'))
            searchForm.removeClass('inactive');
        else {
            if (searchedValue != '' && searchedValue.length > 0)
                searchForm.submit();
            else
                searchForm.addClass('inactive');
        }
    });
} 

var ShowCookie = {
    init: function (selectorHideMenu) {
        if (ShowCookie.is()) {
            ShowCookie.position();
            $(document).on('click', ShowCookie.removeStyle);
        }
        if (ShowCookie.is() || $('body').hasClass('de-de') || $('body').hasClass('de-en')) {
            $('.scroll-menu-wrapper').addClass('cookie-nav');
            ShowCookie.scrolling(selectorHideMenu);
        }
    },

    is: function () {
        var checking = ($('#cookieBar').length > 0) ? true : false;
        return checking;
    },

    height: function () {
        var heightBar = $('#cookieBar').height();
        return heightBar;
    },

    position: function () {
        var cookieBar = ShowCookie.height();
        $('.scroll-menu-wrapper').addClass('cookie-nav-down');
        $('.mn-body').addClass('cookie-body-page');
    },

    removeStyle: function (e) {
        $('.mn-body').removeClass('cookie-body-page');
        $('.scroll-menu-wrapper').removeClass('cookie-nav cookie-nav-down');
    },

    scrolling: function (selectorHideMenu) {

        $(window).scroll(function () {
            var scrollPos = $(this).scrollTop(),
                height = $('#cookieBar').height() !== undefined ? $('#cookieBar').height() : 0,
                widthBrowser = $(window).width(),
                heightMobile;

            if ($('#cookieBar').is(":visible"))
                heightMobile = $('#cookieBar').height() + $(selectorHideMenu).height();
            else
                heightMobile = $(selectorHideMenu).height();

            if ($('#cookieBar').is(":visible") || $('body').hasClass('de-de') || $('body').hasClass('de-en')) {
                if (widthBrowser > 768) {
                    if (scrollPos > height) {
                        $('.scroll-menu-wrapper').removeClass('cookie-nav');
                    } else {
                        $('.scroll-menu-wrapper').addClass('cookie-nav');
                    }
                } 
            }

            if (widthBrowser <= 768) {
                if (scrollPos > heightMobile) {
                    $('.scroll-menu-wrapper').removeClass('cookie-nav');
                } else {
                    $('.scroll-menu-wrapper').addClass('cookie-nav');
                }
            }
        });
    }
};

var CookieNavbar = {
    init: function () {
        CookieNavbar.animate();
    },

    animate: function () {
        $(window).scroll(function () {
            var scrollPos = $(this).scrollTop(),
                height = $('#cookieBar').height() + $('.scroll-menu-wrapper').height() + 30,
                widthBrowser = $(window).width();

            if (ShowCookie.is() && (widthBrowser <= 768)) {
                if (scrollPos < height) {
                    $('.scroll-menu-wrapper').addClass('cookie-animate');
                } else {
                    $('.scroll-menu-wrapper').removeClass('cookie-animate');
                }
            }
        });
    }
}

var TopLineInfo = {
    LINE_SELECTOR: '',
    HEADER_SELECTOR: '',
    CONTENT_SELECTOR: '',

    init: function (topLineSelector, headerSelector) {
        TopLineInfo.LINE_SELECTOR = topLineSelector;
        TopLineInfo.HEADER_SELECTOR = headerSelector;

        TopLineInfo.headerPosition(0);
        TopLineInfo.scrolling();
    },

    height: function () {
        var line = document.querySelector(TopLineInfo.LINE_SELECTOR);
        var height = parseFloat(getComputedStyle(line).height.replace("px", ""));

        return height ? height : 0;
    },

    headerPosition: function (scrollPosition) {
        var header = document.querySelector(TopLineInfo.HEADER_SELECTOR);
        var headerHgh = parseFloat(getComputedStyle(header).height.replace("px", ""));
        var line = document.querySelector(TopLineInfo.LINE_SELECTOR);

        if (scrollPosition < headerHgh) {
            header.style.top = TopLineInfo.height() + 'px';
            line.classList.remove('hide');
            if (window.matchMedia('(max-width: 991px)').matches) {
                header.querySelector('.header-section-nav').style.top = -TopLineInfo.height() + 'px';
            } else {
                header.querySelector('.header-section-nav').style.top = '';
            }
        }

        if (scrollPosition > headerHgh) {
            header.style.top = '';
            line.classList.add('hide');
            header.querySelector('.header-section-nav').style.top = '';
        }
    },

    scrolling: function () {
        window.addEventListener('scroll', function () {
            TopLineInfo.headerPosition(this.scrollY);
        });

        window.addEventListener("resize", function () {
            TopLineInfo.headerPosition(this.scrollY);
        })
    }
}

function getContentType() {
    var bodyClasses = document.querySelector('body').classList;
    if (bodyClasses.contains('euro-web-v2'))
        return 'EuroWeb_v2';

    return 'EuroWeb';
};
var Cookie = {
    get: function (name) {
        var b = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
        return b ? b.pop() : '';
    },

    set: function (key, value, expires /* seconds */) {
        var date = new Date();
        expires = expires || (60 * 60);
        date.setTime(+ date + (expires * 1000));

        document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";
    },

    delete: function (name) {
        document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; ';
    }
};

var CookieAgreements = {
    isExistCheckByModule: function (m) {
        if (m == 1 || m == 4 || m == 5 || m == 6 || m == 7 || m == 8 || m == 9) {
            return Cookie.get('FunctionalAgreement') != '';
        }
        else if (m == 2 || m == 10) {
            return Cookie.get('AnalyticsAgreement') != '';
        }
        else if (m == 3) {
            return Cookie.get('TrackingAgreement') != '';
        }
    },
    acceptCookiesAllRebranding: function () {
        var callback = function () {
            $("#cookieBar").hide();
        };

        CallController("Home", "SaveCookieTerms", {}, callback, null);
        GTM.AcceptCookiesAll();
    },
    acceptCookiesAll: function () {
        var callback = function () {
            $(".cookie-terms").hide();
        }
        CallController("Home", "SaveCookieTerms", {}, callback, null);
        GTM.AcceptCookiesAll();
    },
    acceptCookiesAllJs: function () {
        Cookie.set('FunctionalAgreement', true, 525600);
        Cookie.set('AnalyticsAgreement', true, 525600);
        Cookie.set('TrackingAgreement', true, 525600);
    },
    acceptCookieFunctionalJs: function () {
        Cookie.set('FunctionalAgreement', true, 525600);
    },
    acceptCookies: function (isAnalytics, isTracking) {
        var callback = function () {
            location.reload();
        };
        CallController("Home", "SaveCookieTermsExt", { isAnalyticsAgreement: isAnalytics, isTrackingAgreement: isTracking }, callback, null);
    },
    bindClickEvent: function () {
        $(document).on('click', AcceptOnClickFunction);
    },
    updateStatementsCheckboxes: function (type) {
        var isChecked = $('#cb' + type).is(':checked');
        $('input[data-cookietype="' + type + '"]').prop('checked', isChecked);
    },
    saveChanges: function () {
        var isAnalytics = $('#cbAnalytics').is(':checked');
        var isTracking = $('#cbTracking').is(':checked');

        if (isAnalytics && !isTracking)
            GTM.AcceptCookiesAnalytics();
        else if (!isAnalytics && isTracking)
            GTM.AcceptCookiesTracking();
        else if (!isAnalytics && !isTracking)
            GTM.AcceptCookiesFunctional();
        else if (isAnalytics && isTracking)
            GTM.AcceptCookiesAll();

        CookieAgreements.acceptCookies(isAnalytics, isTracking);
    },
    refuse: function () {
        GTM.AcceptCookiesFunctional();
        CookieAgreements.acceptCookies(false, false);
    },
    dontAcceptEvent: function () {
        CookieAgreements.acceptCookieFunctionalJs();
        GTM.AcceptCookiesFunctional();
    },
    moreInformationEvent: function () {
        CookieAgreements.acceptCookiesAllJs();
        GTM.AcceptCookiesAll();        
    }
};

var JavaScriptModules = {
    GTM: 1,
    Humany: 2,
    Facebook: 3,
    Convert: 4,
    ABtasty: 5,
    GA: 6,
    Sentient: 8,
    Optimize: 9,
    Analytics: 10
};

var AcceptOnClickFunction = function (e) {
    //e.preventDefault();
    if (e.currentTarget.activeElement.id != 'dontAcceptCookieButtonLink' && e.currentTarget.activeElement.id != 'moreInformationButtonLink') {
        CookieAgreements.acceptCookiesAllJs();
        $(".cookie-terms").hide();
        $(document).off('click', AcceptOnClickFunction);        
        GTM.AcceptCookiesAll();
    }
};

var ShowCookiesPopupCheckboxes = function (selectorIdToHide, selectorIdToShow) {
    document.getElementById(selectorIdToHide).style.display = 'none';
    document.getElementById(selectorIdToShow).style.display = 'block';
};
(function () {
    function Calendar (
        mainInputSelector,
        disabledArray,
        additionalInfoArray,
        dateFormat,
        monthNamesArray,
        dayNamesArray,
        daysAhead,
        minDate,
        systemDefaultDate,
        selectedDate,
        orderKey,
        updateShippingFeesOnChange,
        fireAddtionalMethodsOnChange,
        deliveryOptionId,
        onDateSelectCallback) {

        var _cal = this;
        _cal.AdditionalInfoArray = additionalInfoArray;
        _cal.DateFormat = dateFormat;
        _cal.DatePicker = [];
        _cal.DatePickerInput = $(mainInputSelector);
        _cal.DatePickerHidden = _cal.DatePickerInput.closest(".form-group").find("#hfDeliveryDate, #hfReminderDate, #hfDeliveryDateFrom, #hfDeliveryDateTo, .hfDeliveryDate");
        _cal.DatePickerInfoPlaceholder = $(mainInputSelector).closest(".form-group").find("#DeliveryDateInfoSpan");
        _cal.DatePickerSelector = _cal.DatePickerInput.closest(".form-group").find(".datepicker");
        _cal.DayNamesArray = dayNamesArray;
        _cal.DaysAhead = daysAhead;
        _cal.DisabledArray = disabledArray;
        _cal.FireAddtionalMethodsOnChange = fireAddtionalMethodsOnChange;
        _cal.MinDate = minDate;
        _cal.MonthNamesArray = monthNamesArray;
        _cal.Opened = false;
        _cal.ShowLabel = false;
        _cal.OrderKey = orderKey;
        _cal.SelectedDate = selectedDate;
        _cal.SystemDefaultDate = systemDefaultDate;
        _cal.UpdateShippingFeesOnChange = updateShippingFeesOnChange;
        _cal.isExtendedByDeliveryPrice = false;
        _cal.deliveryOptionId = deliveryOptionId;
        _cal.onDateSelectCallback = onDateSelectCallback;
    }
    Calendar.prototype.SelectDate = function (selected, array, dateFormat) {
        var _cal = this;
        var date = _cal.SystemDefaultDate;
        if (selected !== "undefined") {
            if (date < selected) {
                date = new Date(new Date(selected));
            }
        }
        while (array.indexOf(jQuery.datepicker.formatDate(dateFormat, date)) !== -1) {
            date.setDate(date.getDate() + 1);
        }
        return date;
    };
    Calendar.prototype.Open = function () {
        var _cal = this;
        if (!_cal.Opened) {
            _cal.UpdateHeight();
            _cal.Opened = true;
            _cal.UpdateDeliveryFeeStyle();
        }
    };
    Calendar.prototype.Close = function () {
        var _cal = this;
        if (_cal.Opened) {
            if (_cal.DatePickerInput.val() !== "" && !$(_cal.DatePickerInput).hasClass("ignore"))
                _cal.DatePickerInput.valid();
            _cal.UpdateHeight(0);
            _cal.DatePickerInfoPlaceholder.text("");
            _cal.Opened = false;
            _cal.UpdateDeliveryFeeStyle();
        }
    };
    Calendar.prototype.Toggle = function () {
        var _cal = this;
        if (!_cal.Opened) {
            _cal.Open();
        }
        else {
            _cal.Close();
        }
        _cal.DatePickerInput.blur();
    };
    Calendar.prototype.InitDateInfo = function (array, dateFormat) {
        var _cal = this;
        var inputPlaceholder = _cal.DatePickerInfoPlaceholder;
        if (array.length > 0) {
            _cal.DatePickerSelector.on('mouseenter focus', ".ui-datepicker-calendar tbody tr td", function (event) {
                var hDay = parseInt($(this).text());
                var hMonth = parseInt($(this).attr("data-month"));
                hDay = hDay < 10 ? "0" + hDay.toString() : hDay.toString();
                hMonth = hMonth < 10 ? "0" + hMonth.toString() : hMonth.toString();
                var hDate = jQuery.datepicker.formatDate(dateFormat, new Date($(this).attr("data-year"), hMonth, hDay));
                var text = array.filter(function (el) {
                    if (el.indexOf(hDate) !== -1)
                        return el;
                });
                inputPlaceholder.text("");

                if (typeof text[0] !== "undefined") {
                    inputPlaceholder.text(text[0][1]);
                } else
                    if (_cal.isExtendedByDeliveryPrice && !$(event.currentTarget).hasClass('ui-state-disabled')) {
                        var dateToCheck = jQuery.datepicker.formatDate('yy-mm-dd', new Date($(this).attr("data-year"), hMonth, hDay));
                        DeliveryFeeForProduct.GetByDeliveryDate(dateToCheck);
                    }

            });
        }
        /*Event attaching*/
        $(".calendar-icon").on("click", function () {
            _cal.Toggle();
        });
        _cal.DatePickerInput.on('focus', function () {
            _cal.Toggle();
        });

        $("[name='DeliveryDateFromString'],[name='DeliveryDateToString'],[name='DeliveryDateUniversal']").not(_cal.DatePickerInput).each(function (index) {
            $(this).on('focus', function () {
                if (_cal.Opened)
                    _cal.Close();
            });
        });
    };
    Calendar.prototype.Initiate = function (changeYear, isExtendedByDeliveryPrice, orderKey, isPcfCalendar, isDayPartDelivery) {
        var _cal = this;
        _cal.isExtendedByDeliveryPrice = isExtendedByDeliveryPrice;
        var defaultDate = _cal.SelectDate(_cal.SelectedDate, _cal.DisabledArray, _cal.DateFormat);
        _cal.DatePickerInput.val(jQuery.datepicker.formatDate(_cal.DateFormat, defaultDate));
        if (defaultDate !== null)
            _cal.DatePickerHidden.val(defaultDate.toDateString());

        var useLongRangeCallenrad = typeof changeYear !== typeof undefined && changeYear !== null && changeYear !== false;
        var customYearRange = "0:+1";
        if (useLongRangeCallenrad) {
            customYearRange = "-100:+0";
        }

        //TODO: This if can be removed after EuroWeb layout will be removed 
        if (isPcfCalendar) {
            _cal.DatePicker = _cal.DatePickerInput.datepicker(
                {
                    onSelect: function () {
                        _cal.DatePickerInput.val($(_cal.DatePicker).val());
                        _cal.DatePickerHidden.val($(_cal.DatePicker).datepicker('getDate').toDateString());
                        _cal.Close();
                        var orderKeyTb = $(document.getElementById("tbOrderKey")).val();
                        if (!!orderKeyTb && orderKeyTb != null) {
                            if (_cal.FireAddtionalMethodsOnChange) {
                                GetDeliveryDateInfo(_cal.DatePickerHidden.val(), orderKeyTb, _cal.deliveryOptionId);
                                GetDeliveryTimeForFunerals(_cal.DatePickerHidden.val(), orderKeyTb);
                            }

                            var orderSaved = function () {
                                ValidatePostCodeAndCity('danger', '7000');
                            };

                            UpdateShippingFees(orderKeyTb, _cal.DatePickerHidden.val(), "OrderDetailsUpdatePanel");
                        }
                        _cal.DatePickerInput.change();

                        if (!!isExtendedByDeliveryPrice)
                            DeliveryFeeForProduct.Init();

                        if (typeof orderKey !== typeof undefined)
                            DeliveryFeeForProduct.GetByOrderKey(orderKey);

                        if (typeof DisableDayPartsForSpecificDate !== "undefined")
                            DisableDayPartsForSpecificDate();

                        if (_cal.onDateSelectCallback)
                            _cal.onDateSelectCallback(new Date($(_cal.DatePicker).datepicker('getDate')));
                    },
                    dateFormat: _cal.DateFormat,
                    minDate: _cal.MinDate,
                    maxDate: _cal.DaysAhead !== null ? "+" + _cal.DaysAhead - 1 + "d" : null,
                    beforeShowDay: function (date) {
                        var string = jQuery.datepicker.formatDate(_cal.DateFormat, date);
                        return [_cal.DisabledArray.indexOf(string) === -1];
                    },
                    firstDay: 1,
                    monthNames: _cal.MonthNamesArray,
                    monthNamesShort: _cal.MonthNamesArray,
                    dayNamesMin: _cal.DayNamesArray,
                    defaultDate: defaultDate,
                    onChangeMonthYear: function (year, month, inst) {
                        var _timer;
                        _cal.onChangeMonthYearHandler(_timer);
                    },
                    changeYear: useLongRangeCallenrad,
                    changeMonth: useLongRangeCallenrad,
                    yearRange: customYearRange,
                    onClose: function () {
                        _cal.Opened = false;
                    },
                    beforeShow: function (input, inst) {
                        setTimeout(function () {
                            inst.dpDiv.css({
                                top: $(_cal.DatePickerInput).offset().top + $(_cal.DatePickerInput).height()
                            });
                        }, 0);

                        if (!$('.gift-finder-calendar').length) {
                            $('#ui-datepicker-div').addClass('gift-finder-calendar');
                        }
                    }
                })
                .on("show", function () {
                    _cal.Opened = true;
                })
                .on("hide", function () {
                    _cal.Opened = false;
                });

            _cal.DatePickerInput.on('click', function () {
                if (_cal.Opened) {
                    _cal.DatePickerInput.datepicker("hide");
                }
                else {
                    _cal.DatePickerInput.datepicker("show");
                    _cal.Opened = true;
                }
            });

        }
        else {
            _cal.DatePicker = _cal.DatePickerSelector.datepicker(
                {
                    onSelect: function () {
                        _cal.DatePickerInput.val($(_cal.DatePicker).val());
                        _cal.DatePickerHidden.val($(_cal.DatePicker).datepicker('getDate').toDateString());
                        _cal.Close();
                        var orderKeyTb = $(document.getElementById("tbOrderKey")).val();
                        if (!!orderKeyTb && orderKeyTb != null) {
                            if (_cal.FireAddtionalMethodsOnChange) {
                                GetDeliveryDateInfo(_cal.DatePickerHidden.val(), orderKeyTb, _cal.deliveryOptionId);
                                GetDeliveryTimeForFunerals(_cal.DatePickerHidden.val(), orderKeyTb);
                            }

                            var orderSaved = function () {
                                ValidatePostCodeAndCity('danger', '7000');
                            };

                            UpdateShippingFees(orderKeyTb, _cal.DatePickerHidden.val(), "OrderDetailsUpdatePanel");
                        }
                        _cal.DatePickerInput.change();

                        if (typeof isExtendedByDeliveryPrice != typeof undefined && isExtendedByDeliveryPrice !== false)
                            DeliveryFeeForProduct.Init();

                        if (typeof orderKey != typeof undefined)
                            DeliveryFeeForProduct.GetByOrderKey(orderKey);

                        if (typeof DisableDayPartsForSpecificDate !== "undefined")
                            DisableDayPartsForSpecificDate();

                        if (isDayPartDelivery) {
                            DisableDayParts.morning(+1, 1030);
                        }

                        if (_cal.onDateSelectCallback)
                            _cal.onDateSelectCallback(new Date($(_cal.DatePicker).datepicker('getDate')));
                    },
                    dateFormat: _cal.DateFormat,
                    minDate: _cal.MinDate,
                    maxDate: _cal.DaysAhead !== null ? "+" + _cal.DaysAhead - 1 + "d" : null,
                    beforeShowDay: function (date) {
                        var string = jQuery.datepicker.formatDate(_cal.DateFormat, date);
                        return [_cal.DisabledArray.indexOf(string) === -1];
                    },
                    firstDay: 1,
                    monthNames: _cal.MonthNamesArray,
                    monthNamesShort: _cal.MonthNamesArray,
                    dayNamesMin: _cal.DayNamesArray,
                    defaultDate: defaultDate,
                    nextText: '<i class="icon-arrow-right ui-icon"></i>',
                    prevText: '<i class="icon-arrow-left ui-icon"></i>',
                    onChangeMonthYear: function (year, month, inst) {
                        var _timer;
                        _cal.onChangeMonthYearHandler(_timer);
                    },
                    changeYear: useLongRangeCallenrad,
                    changeMonth: useLongRangeCallenrad,
                    yearRange: customYearRange
                });
        }
        if (defaultDate === null)
            _cal.DatePickerSelector.find(".ui-datepicker-current-day").removeClass("ui-datepicker-current-day");

        var orderKeyTb = $(document.getElementById("tbOrderKey")).val();
        if (!!orderKeyTb && orderKeyTb != null)
            GetDeliveryDateInfo(_cal.DatePickerHidden.val(), orderKeyTb, _cal.deliveryOptionId);

        if (!isPcfCalendar) {
            _cal.InitDateInfo(_cal.AdditionalInfoArray, _cal.DateFormat);
        }

        if (typeof DisableDayPartsForSpecificDate !== "undefined")
            DisableDayPartsForSpecificDate();

        $('.ui-datepicker').addClass('notranslate');
    };
    Calendar.prototype.onChangeMonthYearHandler = function (updateHeightTimer) {
        var delay = 50;
        var self = this;
        clearTimeout(updateHeightTimer);
        updateHeightTimer = setTimeout(function () {
            self.UpdateHeight();
        }, delay);
    };
    Calendar.prototype.UpdateHeight = function (height) {
        var _cal = this;
        var $_calendar = $(_cal.DatePickerSelector).children();
        var _height = typeof height !== "undefined" ? height : $_calendar.outerHeight(true);
        _cal.DatePickerSelector.css("max-height", _height + "px");
    };
    //for now, SetMaxDate and SetMinDate are used only with order history panel to update dynamically date selection limits
    Calendar.prototype.SetMaxDate = function (date) {
        var _cal = this;
        var maxDate = new Date(date);
        var _month = maxDate.getMonth();
        var _day = maxDate.getDate();
        var _year = maxDate.getFullYear();
        var newDate = new Date(_year, _month, _day);
        if ($(_cal.DatePicker).datepicker('getDate').getTime() > newDate.getTime()) {
            $(_cal.DatePicker).datepicker('setDate', newDate);
            _cal.DatePickerInput.val($(_cal.DatePicker).val());
            _cal.DatePickerHidden.val($(_cal.DatePicker).datepicker('getDate').toDateString());
        }
        _cal.DatePickerSelector.datepicker("option", "maxDate", newDate);
    };
    Calendar.prototype.SetMinDate = function (date) {
        var _cal = this;
        var minDate = new Date(date);
        var _month = minDate.getMonth();
        var _day = minDate.getDate();
        var _year = minDate.getFullYear();
        var newDate = new Date(_year, _month, _day);
        if ($(_cal.DatePicker).datepicker('getDate').getTime() < newDate.getTime()) {
            $(_cal.DatePicker).datepicker('setDate', newDate);
            _cal.DatePickerInput.val($(_cal.DatePicker).val());
            _cal.DatePickerHidden.val($(_cal.DatePicker).datepicker('getDate').toDateString());
        }
        _cal.DatePickerSelector.datepicker("option", "minDate", newDate);
    };

    Calendar.prototype.UpdateDeliveryFeeStyle = function () {
        var updatePanel = $("#deliveryFeeContainer");
        var focusElements = $('.datepicker-wrapper').find('a');
        if (updatePanel !== "undefined") {

            if (updatePanel.hasClass("delivery-fee-info-closed")) {
                updatePanel.removeAttr("class");
                updatePanel.addClass("delivery-fee-info");
                $('.datepicker-wrapper').addClass('active');
            }
            else {
                updatePanel.removeAttr("class");
                updatePanel.addClass("delivery-fee-info-closed");
                $('.datepicker-wrapper').removeClass('active');
            }
        }
    };

    window.Calendar = Calendar;
})(jQuery);

function GetDeliveryTimeForFunerals(deliveryDate, orderKey) {
    var callback = function (result) {
        $('#deliveryTimeUpdatePanel').html(result);
    };

    CallController("Checkout", "GetDeliveryTime", { deliveryDate: deliveryDate, orderKey: orderKey, firstAllowedDay: $('#firstAllowedDay').val() }, callback, null);
};
function PostcodeFirst(formId, updatePanelId, productUpdatePanelId, whitespotModalId, emailSelectorId) {
    var self = this;
    self.FormSelectorModal = '#' + formId + 'Modal';
    self.FormSelectorPanel = '#' + formId + 'Panel';
    self.FormSelectorWhiteSpotModal = '#' + formId + 'WhiteSpotModal';
    self.PanelContainer = '#' + updatePanelId;
    self.ProductListSelector = '#' + productUpdatePanelId;
    self.WhiteSpotModal = '#' + whitespotModalId;
    self.ModalSelector = [];
    self.EmailSelector = '#' + emailSelectorId;
}

PostcodeFirst.prototype.ShowWarningModal = function (values) {
    var self = this;
    var callback = function (data) {
        $("#whiteSpotModalPanel").html(data);
        $(self.WhiteSpotModal).fadeIn("fast");
    };

    CallController("Product", "GetPostCodeFirstNextAvailableDate", values, callback, null);
};

PostcodeFirst.prototype.UpdateFilter = function (isFromModal, isFromWhiteSpot) {
    var self = this;
    var values = $(self.FormSelectorPanel).serializeObject();

    if (isFromModal) {
        values = $(self.FormSelectorModal).serializeObject();
        if (isFromWhiteSpot)
            values = $(self.FormSelectorWhiteSpotModal).serializeObject();
        $(self.ModalSelector).fadeOut("fast");
        $(self.WhiteSpotModal).fadeOut("fast");
    }

    var productCallback = function (data) {

        $(self.ProductListSelector).fadeTo(500, 0, function () {
            $(self.ProductListSelector).html(data);
            AdjustSortingDropdown();
            AdjustSeoHeader();
            $(self.ProductListSelector).fadeTo(500, 100);
            HidePromoBanner();
        });

        GTM.FindGiftsAnalytics($("#tbLocationName").val(), $("#tbPostcode").val(), $("#tbDeliveryDate").val(), $("#filteredProductsCount").val());
        CallController("Product", "PreparePostcodeFirstPanel", values, mainCallback, null);
    };

    var mainCallback = function (data) {
        var $panel = $(self.PanelContainer).find(".collapse");
        if ($panel.hasClass("in")) {
            $panel.on('hidden.bs.collapse', function () {
                $(self.PanelContainer).fadeOut("fast", function () {
                    $(self.PanelContainer).html(data);
                    $(self.PanelContainer).fadeIn("fast");
                });
            });
        }
        else {
            $(self.PanelContainer).fadeOut("fast", function () {
                $(self.PanelContainer).html(data);
                $(self.PanelContainer).fadeIn("fast");
            });
        }
        $panel.collapse("hide");
        $panel.on('hidden.bs.collapse', null);
        AdjustSeoHeader();
    };

    if (!!$('#hfGiftFinderCategoryUrl').val()) {

        var categoryCallback = function () {
            window.location.href = $('#hfGiftFinderCategoryUrl').val();
        };

        CallController("Product", "StorePostcodeFirstInSession", values, categoryCallback, null);
    }
    else {
        CallController("Product", "PostcodeFirstUpdateFilter", values, productCallback, { Overlay: true });
    }
};

PostcodeFirst.prototype.ClearFilter = function (isFromModal, isExtended) {
    var self = this;
    var values;
    if (isFromModal) {
        values = $(self.FormSelectorModal).serializeObject();
        $(self.FormSelectorModal)[0].reset();
        $('#frmPostcodeFirstModal #tbPostCode').val('');
        $('#frmPostcodeFirstModal #hfDeliveryDate').val('');
        $(self.FormSelectorModal + " .form-group").removeClass("has-success");
    }
    else {
        values = $(self.FormSelectorPanel).serializeObject();
        $(self.FormSelectorPanel)[0].reset();
	}

	values["Postcode"] = null;
	values["DeliveryDateString"] = null;
	values["DeliveryDateUniversal"] = null;


    var productCallback = function (data) {
        $(self.PanelContainer).fadeOut("fast", function () {
            $(self.PanelContainer).html(data);
            if (!isFromModal) {
                var $panelReloaded = $(self.PanelContainer).find(".collapse");
                $panelReloaded.addDistinctClass("in");
                $(self.PanelContainer + " #postcodeFirstHeader").attr("aria-expanded", "true");
            }
            $(self.PanelContainer).fadeIn("fast");
            AdjustSeoHeader();
        });
    };

    var mainCallback = function (data) {
        if (isExtended) {
            return;
        }
        else {
            $(self.ProductListSelector).fadeTo(500, 0, function () {
                $(self.ProductListSelector).html(data);
                $(self.ProductListSelector).fadeTo(500, 100);
            });
            CallController("Product", "PreparePostcodeFirstPanel", { MainId: values.MainId, PageType: values.PageType }, productCallback, null);
        }
    };
    CallController("Product", "PostcodeFirstClearFilter", values, mainCallback, null);
};

PostcodeFirst.prototype.OpenModal = function (modalSelector) {
    this.ModalSelector = '#' + modalSelector;
    $('body').addClass('body-overflow')
    $(this.ModalSelector).show("fast");
};

PostcodeFirst.prototype.SaveStateToCookie = function () {
    var values = {};

    var callback = function () {};

    CallController("Product", "SaveStateToCookie", values, callback, null);
};

PostcodeFirst.prototype.SavePostcodeAndEmail = function () {
    var self = this;
    if (!$(self.FormSelectorModal).valid() || !$(self.EmailSelector).valid())
        return;
    var email = $(self.EmailSelector).serializeObject().Email;
    var postCode = $(self.FormSelectorModal).serializeObject().Postcode;
    var deliveryDate = $(self.FormSelectorModal).serializeObject().DeliveryDateUniversal;
    var values = {
        'Email': email,
        'Postcode': postCode,
        'DeliveryDateUniversal': deliveryDate
    }

    var callback = function (result) {
        if (result.isSuccessful) {
            GTM.CustomEvent('noAvailableProductsEmailSubmit', 'email', email);
            GTM.SubmitPostCode('noAvailableProducts', postCode);
            $(self.ModalSelector).fadeOut('fast');
            $('body').css('overflow', 'auto');
        }
    };
    CallController("Product", "PostcodeFirstSavePostcodeAndEmail", values, callback, null);
};

PostcodeFirst.prototype.CheckProductAvailability = function (params, product) {
    var self = this;
    GTM.SubmitPostCode('postCodeProductPopupSubmit', params.Postcode);

    var checkCallback = function (data) {
        switch (data.available) {
            case 'Available': {
                GTM.AddToCart(product.Currency, product);
                document.getElementById("productDetailForm").submit();
                break;
            }
            case 'TemporaryBlocked': {
                $(self.ModalSelector).fadeOut('fast');
                GTM.CustomEvent('popUpNextDeliveryDate', 'toggleVisibility', 'true');
                params.Products = [{
                    'ProductId': document.getElementById('ProductId').value,
                    'ProductGroupId': document.getElementById('ProductGroupId').value
                }];
                self.ShowWarningModal(params);
                break;
            }
            case 'Blocked':
            default:
                {
                    GTM.CustomEvent('noAvailableProductsShow', 'toggleVisibility', 'Show');
                    $(self.ModalSelector).find('.postcode-first-wrapper').addClass('no-products-popup-active');
                    break;
                }
        }
    };

    CallController("Product", "CheckIfProductAvailableForPostcode", { PostCode: params.Postcode, DeliveryDate: params.DeliveryDate, LocationName: params.LocationName, MainId: params.MainId }, checkCallback, { Overlay: true });
};

function AdjustSeoHeader() {
    var headerContainer = $('#seoHeader');

    if ($('#productListUpdatePanel').find(".product").length > 0) {
        var callback = function (data) {
            headerContainer.html(data);
            headerContainer.show();
        };

        if(headerContainer.length > 0)
            GetController('Home', 'getfirstpageh1', {}, callback);
    }
    else {
        if (headerContainer.is(':visible')) {
            headerContainer.hide();
        }
    }
}

function ValidateAndSubmitPcfFromOnTabPress(event) {
    var tabkey = 9;
    if (event.keyCode === tabkey) {
        ValidateAndSubmitPcfFormWithTabBtn($("#tbPostCodeLocationName").val());
        event.preventDefault();
        return false;
    }
}

function ValidateAndSubmitPcfForm() {
    if (ValidateFormPcf()) {
        if ($("#isLocationChosenFromList").val() == "true") {
            window._PostcodeFirst.UpdateFilter(false, false);
        }
        else {
            function checkCityCallback(data) {
                if (data.Status == 'NotExisting') {
                    var errors = { PostCodeLocationName: data.ValidationMessage };
                    $('#frmPostcodeFirstPanel').validate().showErrors(errors);
                }
                else if (data.Status == 'Available' || data.Status == 'Blocked' || data.Status == 'NotAvailableInPangea') {
                    SelectPostcodeFirstLocation(data.City, data.District, "");
                    window._PostcodeFirst.UpdateFilter(false, false);
                }
                else {
                    $("#isLocationChosenFromList").val('true');
                    SelectPostcodeFirstLocation(data.City, data.District, "");
                }
            }
            GetPostCodes($('#tbPostCodeLocationName').val(), $("#tbPostcode"), "", checkCityCallback);
        }
    }
    return false;
}

function ValidateAndSubmitPcfFormWithTabBtn(locationName) {
    function checkCityCallback(data) {
        if (data.Status == 'NotExisting') {
            var errors = { PostCodeLocationName: data.ValidationMessage };
            $('#frmPostcodeFirstPanel').validate().showErrors(errors);
        }
        else if (data.Status == 'Available' || data.Status == 'Blocked' || data.Status == 'NotAvailableInPangea') {
            SelectPostcodeFirstLocation(data.City, data.District, "");
            ValidateFormPcf();
            $('#tbDeliveryDate').focus();
        }
        else {
            $("#isLocationChosenFromList").val('true');
            SelectPostcodeFirstLocation(data.City, data.District, "");
        }
    }
    GetPostCodes(locationName, $("#tbPostcode"), $('#hfDistrict').val(), checkCityCallback);
}

function ValidateFormPcf() {
    var formValid = $('#frmPostcodeFirstPanel').valid(),
        dateFieldValid = $('#tbDeliveryDate').valid();

    if (formValid && dateFieldValid) {
        return true;
    } else {
        return false;
    }
}

function SelectPostcodeFirstLocation(city, district, postcode) {
    var label = city;

    if (district) {
        label = label + ', ' + district;
    }

    $("#tbPostCodeLocationName").val(label);
    $("#hfLocationName").val(city);
    $("#hfDistrict").val(district);
    if (postcode || postcode == "") {
        $("#tbPostcode").val(postcode);
    }
}

function GetPostCodes(city, postCode, district, checkCityCallback, isFromFocus) {
    var checkCallback = function (data) {
        $('#hfAvailbilityStatus').val(data.Status);

        var _district = data.District ? data.District : district; // it could be passed form controller or from js for regular select
        if (data.Status === 'PartialyBlocked') {
            if (data.City || _district) {
                GetController("product", "getpostcodefirstpostcodes", { City: data.City, District: _district }, postcodesCallback);
            }
            else {
                GetController("product", "getpostcodefirstpostcodes", { City: city, District: district }, postcodesCallback);
            }
        }
        else {
            $('#pcfContainer').removeClass('active');
            $('#pcfCity').removeClass('active');
            $('#tbPostcode').rules("remove");
            $('#tbPostcode').val(data.Postcode);
        }

        if (checkCityCallback != undefined) {
            checkCityCallback(data);
        }
    };

    var postcodesCallback = function (postcodes) {
        $('#pcfContainer').addClass('active');
        $('#tbPostcode').rules("add", {
            required: true,
            itemFromArray: postcodes
        });

        if (isFromFocus) {
            preparePostcodesToDisplay(postcodes);
        } else {
            $('#pcfCity').addClass('active').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function (event) {
                preparePostcodesToDisplay(postcodes);
                postCode.focus();
            });
        }

        if ($('.gift-finder-postcode').hasClass('active')) {
            $('.gift-finder-postcode').find('#tbPostcode').attr('tabindex', "0");
        }
    };

    var preparePostcodesToDisplay = function (data) {
        var postcodesList = [];
        var index = 0;
        $.each(data, function (i, item) {
            postcodesList[index++] = { label: item, value: item };
        });

        postCode.autocomplete();
        postCode.autocomplete("option", {
            source: postcodesList,
            minLength: 0,
            open: function (event, ui) {
                var acData = $(this).data('ui-autocomplete');
                acData
                    .menu
                    .element
                    .find('li')
                    .each(function () {
                        var me = $(this);
                        var keywords = acData.term.split(' ').join('|');
                        me.html(me.text().replace(new RegExp("(" + keywords + ")", "gi"), '<b>$1</b>'));
                    });
            },
            position: {
                my: "top+29",
            }
        }).data("ui-autocomplete")._renderItem = function (ul, item) {

            ul.addClass('gift-finder-list');

            return $("<li></li>")
                .addClass(item.customClass)
                .append("<a href='#'>" + item.label + "</a>")
                .data("ui-autocomplete-item", item)
                .appendTo(ul);
        };
        postCode.autocomplete("search", "");
    };

    var isChoosenFromList = $("#isLocationChosenFromList").val();
    GetController("product", "checkcityavailabilityforpcf", { city: city, district: district, isLocationChosenFromList: isChoosenFromList }, checkCallback);
}

(function () {
    PostcodeFirstAutocomplete = function (tbCity, tbPostcode, hfCity, hfDistrict) {
        var _auto = this;
        _auto.CityInput = $(tbCity);
        _auto.LocationName = $(hfCity);
        _auto.PostcodeInput = $(tbPostcode);
        _auto.District = $(hfDistrict);

        //close postcode input if city has been deleted
        _auto.CityInput.keyup(function () {
            if (!this.value) {
                _auto.CityInput.parent().removeClass('active');
                _auto.PostcodeInput.parent().parent().removeClass('active');
                _auto.PostcodeInput.removeClass('required');
                _auto.PostcodeInput.autocomplete();
                _auto.PostcodeInput.autocomplete('close');
            }
            $("#isLocationChosenFromList").val('false');
        });
    }

    PostcodeFirstAutocomplete.prototype.AutocompleteCity = function () {
        var _auto = this;
        _auto.TxtCity = _auto.CityInput.prop("autocomplete") !== "off" ? _auto.CityInput : null;
        if (!!_auto.TxtCity) {
            $(_auto.TxtCity).autocomplete({
                autoType: 1,
                minLength: $(_auto.TxtCity).prop("autocomplete-min-length"),
                select: function (event, ui) {
                    _auto.CityInput.val(ui.item.label.trim());
                    _auto.LocationName.val(ui.item.city.trim());
                    _auto.District.val(ui.item.district.trim());
                    _auto.PostcodeInput.val("");

                    SelectPostcodeFirstLocation(ui.item.city.trim(), ui.item.district.trim(), "");
                    $("#isLocationChosenFromList").val('true');
                    GetPostCodes(ui.item.city.trim(), _auto.PostcodeInput, ui.item.district.trim());
                },
                source: _auto.SourceCity,
                open: function (event, ui) {
                    var acData = $(this).data('ui-autocomplete');
                    acData
                        .menu
                        .element
                        .find('li')
                        .each(function () {
                            var me = $(this);
                            var keywords = acData.term.split(' ').join('|');
                            me.html(me.text().replace(new RegExp("(" + keywords + ")", "gi"), '<b>$1</b>'));
                        });
                },
                position: {
                    my: "left+0 top+5",
                }
            }).data("ui-autocomplete")._renderItem = function (ul, item) {

                ul.addClass('gift-finder-list gift-finder-list-city');

                return $("<li></li>")
                    .addClass(item.customClass)
                    .append("<a href='#'>" + item.label + "</a>")
                    .data("ui-autocomplete-item", item)
                    .appendTo(ul);
            };
            LocationAutoComplete.Type = 1;
        }
    };

    PostcodeFirstAutocomplete.prototype.SourceCity = function (request, response) {
        var _auto = this;
        var callback = function (data) {
            var citiesList = [];
            var index = 0;
            $.each(data, function (i, item) {
                var lab = item.IsCity ? item.City : item.City + ', ' + item.District;
                citiesList[index++] = { label: lab, city: item.City, district: item.District, isCity: item.IsCity };
            });
            response(citiesList);
        };
        GetController("product", "getpostcodefirstcitysuggestions", { query: request.term }, callback);
    };
})(jQuery);;
var LocationFirst = {
    panel: {
        address: {
            init: function (addressFilled) {
                if (addressFilled) {
                    ShowRecipientDetailsFields();
                }

                LocationFirst.panel.popup.init('ddLocationFirstAddressSearch', 'btnLocationFirstAddressSearch', function () {
                    var el = document.getElementById('tbAddressSearchQuery');
                    var iOS = ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform) || (navigator.userAgent.includes("Mac") && "ontouchend" in document);
                    if (el && !iOS && document.body.dataset.routeType !== "ProductDetail") {
                        el.focus();
                        jQuery('#tbAddressSearchQuery').on("blur", function () {
                            window.scroll(0, 0);
                        });
                    }
                    var vh = window.innerHeight * 0.01;
                    document.documentElement.style.setProperty('--vh', vh + 'px');
                    var address1 = $('#tbRecipientAddress1').val();
                    if (address1)
                        ShowRecipientDetailsFields();
                });
            },
            confirm: function () {
                if (!LocationFirst.panel.validateDate()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstAddressSearch', 'ddLocationFirstDeliveryDate');
                } else if (!LocationFirst.panel.validateOccassion()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstAddressSearch', 'ddLocationFirstOccasion');
                }else {
                    LocationFirst.searchProducts();
                    LocationFirst.panel.popup.close('ddLocationFirstDeliveryDate')
                }
            },
            firstSearchResultReference: null
        },
        deliveryDate: {
            init: function() {
                LocationFirst.panel.popup.init('ddLocationFirstDeliveryDate', 'btLocationFirstPanelDeliveryDate', null, LocationFirst.panel.deliveryDate.rewriteDateFromPanelToMobileDatepicker);
            },
            rewriteDateFromMobileDatepickerToPanel: function () {
                var chosenDeliveryDateString = $('#hfDdLocationFirstDeliveryDateString').val();
                if (chosenDeliveryDateString) {
                    $('#tbLocationFirstPanelDeliveryDateString').val(chosenDeliveryDateString);
                    $('#btLocationFirstPanelDeliveryDate').text(chosenDeliveryDateString);
                    $('#hfLocationFirstPanelDeliveryDateUniversal').val($('#locationFirstMobileDeliveryDatePicker').datepicker('getDate').toDateString());
                }
            },
            rewriteDateFromDesktopDatepickerToPanel: function () {
                $('#btLocationFirstPanelDeliveryDate').text($('#tbLocationFirstPanelDeliveryDateString').val());
            },
            rewriteDateFromPanelToMobileDatepicker: function () {
                var dateUniversalStringFromPanel = $('#hfLocationFirstPanelDeliveryDateUniversal').val();
                var dateFromPanel = dateUniversalStringFromPanel ? new Date(dateUniversalStringFromPanel) : null;
                LocationFirst.panel.deliveryDate.setDateOnMobileDatepicker(dateFromPanel);
                LocationFirst.panel.deliveryDate.setCheckedStateOnDeliveryDateOptions(dateFromPanel);
                if (!!dateFromPanel) {
                    $('#btnLocationFirstPopupDatepickerConfirm').prop("disabled", false);
                }
            },
            setDateOnMobileDatepicker: function (date) {
                $('#locationFirstMobileDeliveryDatePicker').datepicker('setDate', date);
                $('#hfDdLocationFirstDeliveryDateString').val(date ? $('#locationFirstMobileDeliveryDatePicker').datepicker().val() : '');
                $('#ddLocationFirstDeliveryDate .hfDeliveryDate').val(date ? $('#locationFirstMobileDeliveryDatePicker').datepicker('getDate').toDateString() : '');
            },
            setCheckedStateOnDeliveryDateOptions: function (date) {
                $("[name='deliveryDateOption']").each(function () {
                    this.checked = date ? new Date(this.value).getTime() === date.getTime() : false;
                });
            },
            confirm: function () {
                if (!LocationFirst.panel.validateOccassion()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstDeliveryDate', 'ddLocationFirstOccasion');
                } else if (!LocationFirst.panel.validateAddress()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstDeliveryDate', 'ddLocationFirstAddressSearch');
                } else {
                    LocationFirst.searchProducts();
                    LocationFirst.panel.popup.close('ddLocationFirstDeliveryDate')
                }
            }
        },
        occasion: {
            init: function() {
                LocationFirst.panel.popup.init('ddLocationFirstOccasion', 'btLocationFirstOccasion');
                if ($(window).width() > 768) {
                    $(document).mousedown(function (e) {
                        var ele = $(e.target);
                        if (ele.id !== 'ddLocationFirstOccasion' &&
                            ele.id !== 'btLocationFirstOccasion' &&
                            !$(ele).parent().parents('#ddLocationFirstOccasion').length) {
                            LocationFirst.panel.popup.close('ddLocationFirstOccasion');
                        }
                    });
                }
            },
            choose: function (selected, popupId, buttonId, onCloseCallback) {
                var occasions = document.getElementById(popupId).querySelectorAll('.dropdown-item');
                var occasion = selected.closest('.dropdown-item');
                document.getElementById("hfLocationFirstPanelChosenOccasion").value = occasion.value;
                for (var i = 0; i < occasions.length; i++) {
                    occasions[i].classList.remove('selected');
                }
                occasion.classList.add('selected');
                LocationFirst.panel.occasion.toggleBtn(popupId);
                if (window.innerWidth > 769) {
                    LocationFirst.panel.occasion.confirm(buttonId, popupId, onCloseCallback);
                }
            },
            setOccassion: function (buttonId, popupId, onCloseCallback) {
                if (window.innerWidth <= 769) {
                    document.getElementById("tbLocationFirstPostcode").value = document.getElementById("tbRecipientPostCode").value;
                    document.getElementById("btLocationFirstPanelDeliveryDate").value = document.getElementById("hfDdLocationFirstDeliveryDateString").value;
                }
                var occasions = document.getElementById(popupId).querySelectorAll('.dropdown-item');
                var button = document.getElementById(buttonId);
                var occasion;
                for (var i = 0; i < occasions.length; i++) {
                    if (occasions[i].classList.contains('selected'))
                        occasion = occasions[i].closest('.dropdown-item');
                }
                button.querySelector('.name').textContent = occasion.querySelector('a').textContent;
                button.dataset.value = occasion.querySelector('a').value;
            },
            cancel: function (popupId, onCloseCallback) {
                var occasions = document.getElementById(popupId).querySelectorAll('.dropdown-item');
                for (var i = 0; i < occasions.length; i++) {
                    occasions[i].classList.remove('selected');
                }
                LocationFirst.panel.occasion.toggleBtn(popupId);
                LocationFirst.panel.popup.close(popupId, onCloseCallback);
            },
            toggleBtn: function (popupId) {
                var occasions = document.getElementById(popupId).querySelectorAll('.dropdown-item');
                var confirmBtn = document.getElementById(popupId).querySelector('.confirm');
                var skipBtn = document.getElementById(popupId).querySelector('.skip');
                var isSelected = false;
                for (var i = 0; i < occasions.length; i++) {
                    if (occasions[i].classList.contains('selected'))
                        isSelected = true;
                }
                if (isSelected) {
                    skipBtn.style.display = 'none';
                    confirmBtn.style.display = 'block';
                } else {
                    skipBtn.style.display = 'block';
                    confirmBtn.style.display = 'none';
                }
            },
            confirm(isOccasionChosen) {
                if (isOccasionChosen) {
                    LocationFirst.panel.occasion.setOccassion('btLocationFirstOccasion', 'ddLocationFirstOccasion');
                }
                if (!LocationFirst.panel.validateAddress()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstOccasion', 'ddLocationFirstAddressSearch');
                } else if (!LocationFirst.panel.validateDate()) {
                    LocationFirst.panel.popup.goToNextPopup('ddLocationFirstOccasion', 'ddLocationFirstDeliveryDate');
                } else {
                    LocationFirst.searchProducts();
                    LocationFirst.panel.popup.close('ddLocationFirstOccasion');
                }
            }
        },
        validateForm: function () {
            var formValid = $('#LocationFirstPanelForm').valid(),
                dateFieldValid = $('#tbLocationFirstPanelDeliveryDateString').valid();

            return formValid && dateFieldValid;
        },
        validateDate: function () {
            return $('#tbLocationFirstPanelDeliveryDateString').valid();
        },
        validateAddress: function () {
            return $('#tbDesktopAddressSearchQuery').valid();
        },
        validateOccassion: function () {
            return $('#btLocationFirstOccasion').data('value') !== null;
        },
        clearFilter: function (updatePanelSelector, formSelector, productsListSelector) {
            var formValues = $(formSelector).serializeObject();
            formValues["Postcode"] = null;
            formValues["DeliveryDateString"] = null;
            formValues["DeliveryDateUniversal"] = null;
            
            var preparePanelCallback = function (data) {
                $(updatePanelSelector).fadeOut("fast", function () {
                    $(updatePanelSelector).html(data);
                    $(updatePanelSelector).fadeIn("fast");
                    AdjustSeoHeader();

                    LocationFirst.panel.address.init(false);
                    bindAddressSearchFields();
                    LocationFirst.panel.deliveryDate.init();
                    if (formValues.PageType !== "Category") {
                        LocationFirst.panel.occasion.init();
                    }
                });
            };

            var clearCallback = function (data) {
                if (data) {
                    $(productsListSelector).fadeTo(500, 0, function () {
                        $(productsListSelector).html(data);
                        $(productsListSelector).fadeTo(500, 100);
                    });
                }
                LocationFirst.panel.popup.allowScrollingBody();
                CallController("Product", "PrepareLocationFirstPanel", { PageType: formValues.PageType, categoryId: formValues.CategoryId }, preparePanelCallback, null);
            };
            CallController("Product", "LocationFirstClearFilter", formValues, clearCallback, null);
        },
        popup: {
            overlay: {},
            init: function (popupId, buttonId, onOpenCallback, onCloseCallback) {
                LocationFirst.panel.popup.buttonId = buttonId;
                var button = document.getElementById(buttonId);
                var options = document.getElementById(popupId).querySelectorAll('.dropdown-item');
                if (button) {
                    var closeButton = document.getElementById(popupId).querySelector('.close');
                    button.addEventListener('click', function () {
                        LocationFirst.panel.popup.toggle(popupId, onOpenCallback, onCloseCallback);
                        LocationFirst.panel.popup.setNoTransitions();
                    });
                    closeButton.addEventListener('click', function () {
                        LocationFirst.panel.popup.close(popupId, onCloseCallback);
                    });
                    window.addEventListener('resize',
                        function () {
                            if (window.innerWidth > 768) {
                                LocationFirst.panel.popup.close(popupId);
                            }
                        });
                }
                if (options.length) {
                    for (var i = 0; i < options.length; i++) {
                        options[i].addEventListener('click', function (e) {
                            e.preventDefault ? e.preventDefault() : e.returnValue = false;
                            LocationFirst.panel.occasion.choose(e.target, popupId, buttonId, onCloseCallback);
                        });
                    }
                }
            },
            toggle: function (popupId, onOpenCallback, onCloseCallback) {
                var dropdown = document.getElementById(popupId);
                dropdown.classList.contains('open') ?
                    LocationFirst.panel.popup.close(popupId, onCloseCallback) :
                    LocationFirst.panel.popup.open(popupId, onOpenCallback);
            },
            open: function (popupId, onOpenCallback) {
                var dropdown = document.getElementById(popupId);
                dropdown.classList.add('open');
                dropdown.querySelector('.dropdown-menu').classList.add('open');
                dropdown.querySelector('.dropdown-menu').setAttribute('aria-expanded', true);
                LocationFirst.panel.popup.addOverlay(popupId);
                LocationFirst.panel.popup.preventScrollingBody();
                if (onOpenCallback)
                    onOpenCallback();
            },
            close: function (popupId, onCloseCallback, isNextPopup) {
                isNextPopup = isNextPopup !== undefined;
                if (!isNextPopup) {
                    LocationFirst.panel.popup.removeNoTransitions();
                }
                var dropdown = document.getElementById(popupId);
                dropdown.classList.remove('open');
                dropdown.querySelector('.dropdown-menu').classList.remove('open');
                dropdown.querySelector('.dropdown-menu').setAttribute('aria-expanded', false);
                LocationFirst.panel.popup.removeOverlay(popupId);
                LocationFirst.panel.popup.allowScrollingBody();
                if (onCloseCallback)
                    onCloseCallback();
            },
            addOverlay: function (popupId) {
                var overlay = document.createElement('div');
                var dropdown = document.getElementById(popupId);
                overlay.classList.add('overlay');
                dropdown.prepend(overlay);
                setTimeout(function () {
                    overlay.classList.add('active');
                }, 0);
            },
            removeOverlay: function (popupId) {
                var overlay = document.getElementById(popupId).querySelector('.overlay');
                if (overlay) {
                    overlay.classList.remove('active');
                    setTimeout(function () {
                        overlay.remove();
                    },
                        150);
                }
            },
            goToNextPopup: function (popupId, nextPopupId, onOpenCallback, onCloseCallback) {
                document.getElementById(popupId).classList.add('left');
                setTimeout(function () {
                    LocationFirst.panel.popup.close(popupId, onCloseCallback, true);
                    LocationFirst.panel.popup.open(nextPopupId, onOpenCallback);
                    document.getElementById(popupId).classList.remove('left');
                }, 250);
            },
            goToPrevPopup: function (popupId, prevPopupId, onOpenCallback, onCloseCallback) {
                document.getElementById(prevPopupId).classList.add('left');
                setTimeout(function () {
                    LocationFirst.panel.popup.close(popupId, onCloseCallback, true);
                    LocationFirst.panel.popup.open(prevPopupId, onOpenCallback);
                    document.getElementById(prevPopupId).classList.remove('left');
                }, 250);
            },
            setNoTransitions: function () {
                if ($(window).width() <= 768) {
                    var elements = Array.from(document.querySelectorAll('.location-first-popup-list'))
                        .concat(Array.from(document.querySelectorAll('.location-first-popup')));
                    setTimeout(function () {
                        elements.forEach(function (el) {
                            el.classList.add('notransition');
                        });
                    }, 450);
                }
            },
            removeNoTransitions: function () {
                if ($(window).width() <= 768) {
                    var elements = Array.from(document.querySelectorAll('.location-first-popup-list'))
                        .concat(Array.from(document.querySelectorAll('.location-first-popup')));
                    elements.forEach(function (el) {
                        el.classList.remove('notransition');
                    });
                }
            },
            preventScrollingBody: function () {
                if ($(window).width() <= 768) {
                    document.body.style.overflow = "hidden";
                    document.body.style.height = "100%";
                }
            },
            allowScrollingBody: function () {
                if ($(window).width() <= 768) {
                    document.body.style.overflow = "auto";
                    document.body.style.height = "auto";
                }
            }
        }
    },
    pdp: {
        deliveryDate: {
            dayNames: [],
            monthsNames: [],
            init: function (date, dayNames, monthsNames) {
                LocationFirst.pdp.deliveryDate.dayNames = dayNames;
                LocationFirst.pdp.deliveryDate.monthsNames = monthsNames;
                LocationFirst.panel.popup.init('ddLocationFirstDeliveryDate', 'btLocationFirstPanelDeliveryDate', null, null);

                if (!!date) {
                    LocationFirst.pdp.deliveryDate.selectDeliveryOptionDateButton(date);
                    LocationFirst.pdp.showSection('LocationFirstProductDeliveryOption');
                }
            },
            setDateOnDatepicker: function (date) {
                var day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
                var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
                var deliveryDateString = day + "." + month + "." + date.getFullYear();
                var deliveryDateUniversal = date.toDateString();

                $('#tbLocationFirstPanelDeliveryDateString').val(date ? deliveryDateString : '');
                $('#hfLocationFirstPanelDeliveryDateUniversal').val(date ? deliveryDateUniversal : '');
                LocationFirst.pdp.showSection('LocationFirstProductDeliveryOption', true);
            },
            setDateOnDatepickerByPopup: function () {
                var date = new Date($('#hfDdLocationFirstDeliveryDateUniversal').val());
                LocationFirst.pdp.deliveryDate.setDateOnDatepicker(date);
            },
            setDateOnDatepickerByDeliveryOptionDateButton: function (date) {
                $('.location-first-date-option-item.calendar').removeClass('selected');
                LocationFirst.pdp.deliveryDate.setDateOnDatepicker(date);
            },
            setDateOnDatepickerByDesktopDatepicker: function () {
                var date = $('#locationFirstDesktopDeliveryDatePicker').datepicker('getDate');
                LocationFirst.pdp.deliveryDate.setDateOnDatepicker(date);
                LocationFirst.pdp.deliveryDate.rewriteDateInformationOnDeliveryOptionDateButton();
            },
            rewriteDateInformationOnDeliveryOptionDateButton: function (date) {
                date = !!date ? date : new Date($('#hfLocationFirstPanelDeliveryDateUniversal').val());
                $('.location-first-date-option-item.calendar').addClass('selected');
                $('.calendar .day-name').text(LocationFirst.pdp.deliveryDate.dayNames[date.getDay()]);
                $('.calendar .date').text(LocationFirst.pdp.deliveryDate.monthsNames[date.getMonth()] + ' ' + date.getDate());
            },
            selectDeliveryOptionDateButton: function (date) {
                var isDateOptionSelected = false;
                $("[name='deliveryDateOption']").each(function () {
                    if (new Date(this.value).getTime() === date.getTime()) {
                        this.checked = true;
                        isDateOptionSelected = true;
                    }
                });
                if (!isDateOptionSelected) {
                    LocationFirst.pdp.deliveryDate.rewriteDateInformationOnDeliveryOptionDateButton(date);
                }
            },
            clearChoosenDate: function () {
                var datepickerSelector = $(window).width() <= 768 ?
                    '#locationFirstMobileDeliveryDatePicker' :
                    '#locationFirstDesktopDeliveryDatePicker';

                $("[name='deliveryDateOption']").each(function () {
                    this.checked = false;
                });
                $(datepickerSelector).datepicker('setDate', null);
                $('#tbLocationFirstPanelDeliveryDateString').val(null);
                $('#hfLocationFirstPanelDeliveryDateUniversal').val(null);
                $('.location-first-date-option-item.calendar').removeClass('selected');
            }
        },
        clearFilter: function (updatePanelSelector) {
            var clearCallback = function (data) {
                $(updatePanelSelector).fadeTo(500, 0, function () {
                    $(updatePanelSelector).html(data);
                    $(updatePanelSelector).fadeTo(500, 100);

                    LocationFirst.panel.address.init(false);
                    bindAddressSearchFields();
                });
                LocationFirst.panel.popup.allowScrollingBody();
            };
            CallController("Product", "LocationFirstProductDetailClearFilter", { productId: $('#ProductId').val() }, clearCallback, null);
        },
        showSection: function (sectionId, isAnimation) {
            if (sectionId === 'LocationFirstProductDeliveryOption') {
                LocationFirst.pdp.reloadDeliveryOptionsSection();
            }
            if (document.getElementById('LocationFirstProductDeliveryOption').classList.contains('disabled') || !!isAnimation) {
                $('#' + sectionId).fadeTo(500, 0, function () {
                    document.getElementById(sectionId).classList.remove('disabled');
                    $('#' + sectionId).fadeTo(500, 100);
                });
            }
        },
        hideSection: function (sectionId) {
            if (!document.getElementById('LocationFirstProductDeliveryOption').classList.contains('disabled')) {
                $('#' + sectionId).fadeTo(500, 0, function () {
                    document.getElementById(sectionId).classList.add('disabled');
                    $('#' + sectionId).fadeTo(500, 100);
                });
            }
        },
        reloadDeliveryOptionsSection: function () {
            var callback = function (data) {
                $('#LocationFirstProductDeliveryOption').html(data);
            };

            CallController("Product", "PrepareLocationFirstProductDetailDeliveryOption", {
                productId: $('#ProductId').val(), postcode: $('#tbRecipientPostCode').val(), city: $('#tbRecipientCity').val(), deliveryDate: $('#hfLocationFirstPanelDeliveryDateUniversal').val()
            }, callback, null);

        }
    },
    checkProductAvailability: function (productId, locationFirstData) {
        var checkCallback = function (response) {
            if (response !== "") {
                if (response.Type == 'BlockedPopup') {
                    if (response.isWarning) {
                        ShowInfoTooltip(response.body, 'danger', 0);
                        GTM.ProductNotAvailableForPostcode(locationFirstData.PostCode, 'global_warning');
                    }
                    else {
                        InfoModal.Show(response.title, response.body, response.btnCloseText);
                        GTM.ProductNotAvailableForPostcode(locationFirstData.PostCode, 'global_blocked');
                    }
                }
                else {
                    $('#productsForBlockedPostcodeUpdatePanel').html(response);
                    Popup.Show('#productsForBlockedPostcodeModal');
                    $('#remove-caret').focus();
                    if (document.activeElement) {
                        document.activeElement.blur();
                    }
                    GTM.CustomEvent('availableProductsPopupShow', 'toggleVisibility', 'Show');
                    GTM.ProductNotAvailableForPostcode(locationFirstData.PostCode, 'available_products_pop-up');
                }
                LocationFirst.invalidateAddressFields('productDetailForm');
            }
            else if (response.cutoffCheckFail === true) {
                InfoModal.Show(response.title, response.body, response.btnCloseText);
                LocationFirst.invalidateAddressFields('productDetailForm');
                GTM.ProductNotAvailableForPostcode(locationFirstData.PostCode, 'global_blocked');
            }
            else {
                document.getElementById("productDetailForm").submit();
            }
            
        }
        CallController("Product", "CheckIfProductAvailableForLocation", { productId: productId, locationFirstData: locationFirstData }, checkCallback, { Overlay: true });
    },
    searchProducts: function () {
        if (LocationFirst.panel.validateForm()) {
            if (!!$('#tbLocationFirstCity').val()) {
                performSearch();
            } else {
                // if user started to search location but haven't selected any one, get the first suggested result
                // if there are no suggestions for the query (query is incorrect) then show validation error
                if (!!LocationFirst.panel.address.firstSearchResultReference) {
                    SetRecipientLocation({
                            addressReference: LocationFirst.panel.address.firstSearchResultReference,
                            addressBar: true,
                            version: locationFirstAddresSearchEngine,
                            phoneNumber: isPhoneNumer($("#tbDesktopAddressSearchQuery").val().trim())
                        },
                        '#addressSearchResultUpdatePanel',
                        true,
                        performSearch);
                } else {
                    $('#LocationFirstPanelForm').validate().showErrors({
                        'tbDesktopAddressSearchQuery': ''
                    });
                }
            }
        }

        function performSearch() {
            var data = {
                Address1: document.getElementById('tbRecipientAddress1').value,
                City: document.getElementById('tbLocationFirstCity').value,
                HouseNr: document.getElementById('tbRecipientHouseNr').value,
                Address2: document.getElementById('tbRecipientAddress2').value,
                PostCode: document.getElementById('tbLocationFirstPostcode').value,
                Country: document.getElementById('tbCountryName').value,
                DeliveryDateString: document.getElementById('tbLocationFirstPanelDeliveryDateString').value,
                DeliveryDateUniversal: document.getElementById('hfLocationFirstPanelDeliveryDateUniversal').value || document.getElementById('hfDdLocationFirstDeliveryDateUniversal').value,
                ChosenOccasion: document.getElementById('hfLocationFirstPanelChosenOccasion').value,
                PageType: document.getElementById('hfLocationFirstPanelPageType').value,
                CategoryId: (document.getElementById('hfLocationFirstPanelCategoryId') != null) ? document.getElementById('hfLocationFirstPanelCategoryId').value : null
            };

            var countyField = document.getElementById('tbRecipientCounty');
            if (countyField) {
                data.County = countyField.value;
            }

            var callback = function (response) {
                $('#locationFirstSearchButton').prop("disabled", false);
                if (response && response.Action == 'redirect' && response.ActionUrl)
                    window.location.href = response.ActionUrl;
                if (response && response.Action == 'updateProductPanel' && response.Html)
                    $('#' + response.UpdatePanel).html(response.Html);
                if (response && response.Action == 'showPopup')
                    LocationFirst.showNoProductsPopup();
            };

            $('#locationFirstSearchButton').prop("disabled", true);
            CallController("Product", "SearchProducts", data, callback, { Overlay: true, OverlayParent: '#productListContainerUpdatePanel' });
            LocationFirst.panel.address.firstSearchResultReference = null;
        }
    },

    showNoProductsPopup: function() {
        Popup.Show('#locationFirstNoAvailablePopup', true, true);
        GTM.ProductNotAvailableForPostcode($('#tbLocationFirstPostcode').val(), 'global_blocked');
    },

    closeNoProductsPopup: function() {
        Popup.Hide('#locationFirstNoAvailablePopup', true, true);
        LocationFirst.invalidateAddressFields('LocationFirstPanelForm');
    },

    invalidateAddressFields: function(formId) {
        $('#' + formId).validate().showErrors({
            'tbDesktopAddressSearchQuery': '',
            City: '',
            PostCode: ''
        });
        $('#btnLocationFirstAddressSearch').removeClass('has-success').addClass('has-error');
    },

    updateAddressSearchValidation: function() {
        if ($('#tbLocationFirstCity').valid())
            $('.form-group.address-search.relative.required').removeClass('has-error');
    }
}


document.addEventListener('DOMContentLoaded', function () {
    (function ($) {
        $.AddressSearch = function (elem, options, translation, onSelect) {
            var _IsIOS = (/iPhone|iPad|iPod/i.test(navigator.userAgent));
            var _Response = null;
            var _Open = function (event, ui) {
                if (_IsIOS) {
                    $('.ui-autocomplete').off('menufocus hover mouseover');
                }
                var resultListElement = $(options.resultListSelector);
                resultListElement.css("z-index", "1000000000");
                resultListElement.outerWidth($(elem).outerWidth());
                if (options.limitLength) {
                    var _height = $(resultListElement.children()[0]).outerHeight() * 10 + 11;
                    if (_height > 11)
                        resultListElement.css("max-height", _height + "px");
                    resultListElement.css("overflow-x", "auto");
                    resultListElement.addClass('address-search-list location-first-address-results');
                }
                if ($('.address-search-list').eq(0).find('.show-recipient-fields').length === 0 && (typeof translation !== 'undefined' && translation !== null)) {
                    $('.address-search-list').eq(0).append(
                        '<li class="ui-menu-item show-recipient-fields" onclick="ShowRecipientDetailsFields()" aria-label="' + translation + '">' +
                        translation +
                        '</li>');
                }
                var acData = $(this).data('ui-autocomplete');
                acData
                    .menu
                    .element
                    .find('li')
                    .each(function () {
                        var me = $(this);
                        var keywords = acData.term.split(' ').join('|');
                        me.html(me.text().replace(new RegExp("(" + keywords + ")", "gi"), '<b>$1</b>'));
                    });
            };
            var _Focus = function (event, ui) {
                if (options.preventDefaults)
                    event.preventDefault();
            };

            var _Source = function (request, response) {
                if (typeof response !== "undefined")
                    if (response !== null)
                        _Response = response;
                var query = elem.val().trim();
                if (isPhoneNumer(query)) {
                    var callback = function (data) {
                        var searchResults = _PrepareResultList(data);
                        LocationFirst.panel.address.firstSearchResultReference = !!searchResults && !!searchResults.length ? searchResults[0].value : null;
                        if (typeof _Response !== "undefined") {
                            if (_Response !== null) {
                                _Response(searchResults);
                            }
                        }
                        else {
                            response(searchResults);
                        }
                    };
                    CallController("Location", "GetAddressByPhone", { phoneNumber: query }, callback, null);
                }
                else {
                    var callback = function (data) {
                        var searchResults = _PrepareResultList(data);
                        LocationFirst.panel.address.firstSearchResultReference = !!searchResults && !!searchResults.length ? searchResults[0].value : null;
                        if (typeof _Response !== "undefined") {
                            if (_Response !== null)
                                _Response(searchResults);
                        }
                        else {
                            response(searchResults);
                        }
                    };
                    CallController("Location", "GetAddressSearchSuggestions", { query : query, container: "", version: locationFirstAddresSearchEngine }, callback, null);
                }
            };
            var _Hide = true;
            var _Select = onSelect.bind(this, elem, _Source, options);
            var _AppendTo = $(window).width() <= 768 ? $('#ddLocationFirstAddressSearch .location-first-popup-content') : $('body');
            var _PrepareResultList = function (data) {
                return Array.isArray(data) ? data.map(function (el) {
                    return {
                        label: el.PartialAddress,
                        value: el.Reference,
                        canStepIn: el.CanStepIn
                    };
                }) : [];
            };

            elem.autocomplete({
                minLength: options.minLength,
                select: _Select,
                source: _Source,
                focus: _Focus,
                open: _Open,
                close: function (event, ui) {
                    if (!_Hide && !$(options.resultListSelector).is(":visible")) {
                        $(options.resultListSelector).show();
                    }
                },
                create: function () {
                    $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
                        var _class = item.canStepIn ? "group ui-menu-item" : "ui-menu-item";
                        return $('<li class="' + _class + '">')
                            .append(item.label)
                            .appendTo(ul);
                    };
                },
                appendTo: _AppendTo
            });
        };
        $.fn.open = function () {
            this.autocomplete('search');
            this.focus();
        };
        // Default options
        $.AddressSearch.defaults = {
            'minLength': 3,
            'resultListSelector': '.ui-autocomplete',
            'preventDefaults': true,
            'matchInputWidth': false,
            'limitLength': true
        };
        $.fn.addressSearch = function (translation, options, onSelect) {
            options = $.extend({}, $.AddressSearch.defaults, options);
            return this.each(function () {
                new $.AddressSearch($(this), options, translation, onSelect);
            });
        };
    })(jQuery);

    clearAddressSearchField = function () {
        $("#tbAddressSearchQuery").val('').focus();
        $("#tbAddressSearchQuery").autocomplete('close');
    }

    bindAddressSearchFields();
});

function bindAddressSearchFields() {
    $("#tbAddressSearchQuery").addressSearch(null, null, onAddressSelect);
    $("#tbDesktopAddressSearchQuery").addressSearch(null, null, onAddressSelect);
};

function onAddressSelect(elem, _Source, options, event, ui) {
    if (typeof ui === 'undefined' || typeof ui.item === 'undefined') {
        if (options.preventDefaults)
            event.preventDefault();
        return;
    }
    if (ui.item.canStepIn) {
        _Hide = false;
        var callback = function (data) {
            data = _PrepareResultList(data);
            $(elem).autocomplete("option", { source: data, minLength: 0 });
            $(elem).autocomplete("search", "");
            _Hide = true;
            $(elem).autocomplete("option", { source: _Source, minLength: options.minLength });
        };
        CallController("Location", "GetAddressSearchSuggestions", { query: elem.val(), container: ui.item.value, version: locationFirstAddresSearchEngine }, callback, null);
    }
    else {
        _Hide = true;
        $(elem).autocomplete("option", { source: _Source, minLength: options.minLength });

        SetRecipientLocation({
                addressReference: ui.item.value,
                addressBar: options.addressBar,
                version: locationFirstAddresSearchEngine,
                phoneNumber: isPhoneNumer(elem.val().trim())
            },
            '#addressSearchResultUpdatePanel',
            true);
    }
    if (options.preventDefaults)
        event.preventDefault();
};

function isPhoneNumer(query) {
    return /^\d{3,}$/.test(query);
}

function SetRecipientLocation(args, updatePanel, showFields, afterExecutionCallback) {
    var callback = function (data) {
        if (data.error === undefined || data.error === null || data.error === "") {
            var allValid = true;

            $('#tbRecipientAddress1').val(data.Address1);

            $('#tbRecipientAddress2').val(data.Address2);

            $('#tbRecipientPostCode').val(data.PostCode);

            $('#tbRecipientCity').val(data.Town || data.City);

            $('#tbRecipientCounty').val(data.County);

            $('#tbLocationFirstPostcode').val(data.PostCode);

            $('#tbLocationFirstCity').val(data.Town || data.City);

            if (data.HouseNr !== undefined) {
                $('#tbRecipientHouseNr').val(data.HouseNr);
            }

            if (showFields && !args.addressBar) {
                ShowRecipientDetailsFields();
            }

            if (args.addressBar) {
                $('#address-bar-street').html(data.Address1);
                $('#address-bar-housenr').html(data.HouseNr || '');
                $('#address-bar-line2').html(data.Address2);
                $('#address-bar-city').html(data.Town || data.City);
                $('#address-bar-postcode').html(data.PostCode);
                $('#tbLocationFirstPostcode').html(data.Address1);
                $('#tbLocationFirstCity').html(data.HouseNr || '');

                ShowRecipientDetailsFields(allValid);
            }

            $(updatePanel).empty();
        }
        else {
            ShowInfoTooltip(data.error, 'danger', 5000);
            ShowRecipientDetailsFields();
        }

        if (!!afterExecutionCallback) {
            afterExecutionCallback();
        }
    };

    CallController("Location", "SetRecipientLocation", args, callback, null);
}

function ShowRecipientDetailsFields(showAddressBar) {
    $('#locationFillPanel').show();
    $('#btnLocationFirstClearFilter').show();
    $('.sub-link.clear').show();
    if (showAddressBar === true) {
        $(".address-bar").removeClass("hidden");
        $('.fill-panel.address-search').removeClass("extended");
    } else {
        $(".address-bar").addClass("hidden");
        $('.fill-panel.address-search').addDistinctClass("extended");
    }
    $('.country-label').addDistinctClass("has-success");
    $('.form-group.address-search').removeClass("extended");
    $('.address-search-list').css('display', 'none');
    $('#ddLocationFirstAddressSearch .dropdown-buttons').addClass("extended");
    if (document.body.dataset.routeType === 'ProductDetail') {
        LocationFirst.pdp.showSection('LocationFirstProductDatepicker');
        GetLocationFirstPanelAvailableDays();
    }
}

function GetLocationFirstPanelAvailableDays() {
    var populateAvailableDaysPanel = function (data) {
        $('#LocationFirstProductDatepicker').html(data);
    };

    CallController("Product", "GetLocationFirstPanelDatepicker", {
        productId: document.getElementById('ProductId').value,
        postcode: document.getElementById('tbLocationFirstPostcode').value,
        city: document.getElementById('tbLocationFirstCity').value
    }, populateAvailableDaysPanel, null);
}

function setStickyLocationFirstPanel() {
    var headerHeight = document.querySelector('[data-element="header"]').offsetHeight,
        promoHeight = document.body.dataset.routeType === 'Home' ?
            document.querySelector('.promotional-bar').offsetHeight - 105 :
            document.querySelector('.content-header').offsetHeight - 30;

    var height = headerHeight + promoHeight;

    window.addEventListener("scroll", function () {
        var currentPosition = window.pageYOffset;

        if (currentPosition > height) {
            document.getElementById('LocationFirstPanel').classList.add('sticky');
        } else {
            document.getElementById('LocationFirstPanel').classList.remove('sticky');
        }
    });
}

function validMobileAddressForm() {
    var mobileAddressForm = [
        document.getElementById('tbRecipientAddress1'),
        document.getElementById('tbRecipientHouseNr'),
        document.getElementById('tbRecipientAddress2'),
        document.getElementById('tbRecipientPostCode'),
        document.getElementById('tbRecipientCity'),
        document.getElementById('tbCountryName')
    ];

    var countyField = document.getElementById('tbRecipientCounty');
    if (countyField) {
        mobileAddressForm.push(countyField);
    }

    var isValid = true;

    for (var i = 0; i < mobileAddressForm.length; i++) {
        if (!$(mobileAddressForm[i]).valid()) {
            isValid = $(mobileAddressForm[i]).valid();
        }
    }

    return isValid;
}

function AdjustSeoHeader() {
    var headerContainer = $('#seoHeader');

    if ($('#productListUpdatePanel').find(".product").length > 0) {
        var callback = function (data) {
            headerContainer.html(data);
            headerContainer.show();
        };

        if (headerContainer.length > 0)
            GetController('Home', 'getfirstpageh1', {}, callback);
    }
    else {
        if (headerContainer.is(':visible')) {
            headerContainer.hide();
        }
    }
}
;
function UpdateProductVariants(args, updatePanel, updateDescriptionPanel) {
    var callback = function (data) {
        $(updatePanel).parent().attr("style", "height:" + $(updatePanel).parent().innerHeight() + "px");
        $(updatePanel).fadeOut("fast", function () {
            $(updatePanel).html(data);
            var $img = $(updatePanel).find("img");
            $img.hide(0);
            $img.on('load', function () {
                $(this).show('fast');
                $(updatePanel).fadeIn("fast", function () {
                    $(updatePanel).parent().removeAttr("style");
                    if ($('.additional-images-item').length === 0 ||
                        $('.additional-images-item').eq(0).find('a').hasClass('selected')) {
                        $(updatePanel).parent().find('.product-detail-image-overlay').fadeIn("fast");
                    }
                });

            });
        });
    };

    CallController("Product", "GetProductDetailImageOnVariantChange", args, callback, null);

    var callback2 = function (data) {
        var parser = new DOMParser();
        data = parser.parseFromString(data, 'text/html');
        $('#additionalImages').fadeOut("fast", function () {
            $('#additionalImages').html($(data).find('#additionalImages').html());
            $('#additionalImages').fadeIn("fast");
        });
    }
    CallController("Product", "GetProductAdditionalImages", args, callback2, null);

    var description;
    if (args.VariantId != $("#customPriceVariantId").val())
        description = document.getElementById("variantDescription_" + args.VariantId).value;
    else
        description = GetSmallestVariant();

    $(updateDescriptionPanel).fadeOut("fast", function () {
        $(updateDescriptionPanel).html(description);
        $(updateDescriptionPanel).fadeIn("fast", function () { });
    });
}

function UpdateExtendedProductVariant(args, updatePanel, updateDescriptionPanel) {
    UpdateProductVariants(args, updatePanel, updateDescriptionPanel);
    DeliveryFeeForProduct.Update(args);
}

function GetSmallestVariant() {
    var description = null;
    var variant = 1;
    while (description == null && variant <= 3) {
        description = document.getElementById("variantDescription_" + variant);
        variant++;
    }

    return description.value;
}

var initSlide;

function AddAccessoryProductDetail(args, updatePanel, animation) {
    var callback = function (data, event) {
        $(updatePanel).html(data);

        if (animation) {
            $('html, body').animate({
                scrollTop: $(updatePanel).offset().top
            }, 500);
        }
    };

    initSlide = $(".product-addons .tns-slide-active").first().index();
    initSlide = typeof initSlide !== 'undefined' ? initSlide : 0;

    CallController("Checkout", "AddAccessoryProductDetail", args, callback, { Overlay: true, OverlayParent: '#ProductDetailSliderUpdatePanel' });
}


function AddAccessoryProductDetailRebranding(args, updatePanel) {
    var callback = function (data, event) {
        $(updatePanel).html(data);
    };

    initSlide = $(".product-addons .tns-slide-active").first().index();
    initSlide = typeof initSlide !== 'undefined' ? initSlide : 0;

    CallController("Checkout", "AddAccessoryProductDetail", args, callback, { Overlay: true, OverlayParent: '#ProductDetailSliderUpdatePanel' });
}

function RemoveAccessoryProductDetail(args, updatePanel, partialSender) {
    var callback = function (data) {
        $(updatePanel).html(data);

        if (partialSender !== "AccessoriesSliderProductDetails_2") {
            $('html, body').animate({
                scrolltop: $(updatePanel).offset().top
            }, 500);
        }
    };

    initSlide = $(".product-addons .tns-slide-active").first().index();
    initSlide = typeof initSlide !== 'undefined' ? initSlide : 0;

    CallController("Checkout", "RemoveAccessoryProductDetail", args, callback, { Overlay: true, OverlayParent: '#ProductDetailSliderUpdatePanel' });
}

function SetDescriptionDisclaimerState(panelId)
{
    var isMobile = /iPad/.test(navigator.userAgent) ? true : /Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Silk/.test(navigator.userAgent) ? true : false;
    var anchorElement = $("#headingThreeDisclaimer").find("a");
    var descriptionContainer = $(panelId);

    if (isMobile) {
        anchorElement.attr("class", "collapsed title");
        anchorElement.attr("aria-expanded", "false");
        anchorElement.attr("data_category", "information");
        anchorElement.attr("data_action", "drop_down");
        anchorElement.attr("data_label", window.location.href);
        descriptionContainer.attr("class", "panel-collapse collapse no-padding-0");
    }
    else {
        anchorElement.attr("class", "title");
        anchorElement.attr("aria-expanded", "true");
        descriptionContainer.attr("class", "panel-collapse no-padding-0 collapse in");
    }
}

function SetProductInfoState(panelId)
{
    var anchorElement = $("#headingThree").find("a");
    var descriptionContainer = $(panelId);

        anchorElement.attr("class", "title");
        anchorElement.attr("aria-expanded", "true");
        descriptionContainer.attr("class", "panel-collapse collapse in");
}

function checkLabel(selector) {
    if ($(selector).find('input').prop("checked")) {
        $(selector).addClass('checked');
    } else {
        $(selector).removeClass('checked');
    }
}

function validateCustomPrice(selector) {
    var valid = $(selector).valid();

    if (!valid) {
        $('html, body').animate({
            scrollTop: ($('.has-error').offset().top - 200)
        }, 2000);
    }

}

var ProductImage = {
    Init: function (selector, picture, tag, attr) {
        $(selector).on('click', function () { ProductImage.Show(picture, tag, attr) });
    },
    Show: function (selector, tag, attr) {
        selector = (typeof selector !== 'undefined') ? selector : '#productDetailUpdatePanel';
        tag = (typeof tag !== 'undefined') ? tag : 'img';
        attr = (typeof attr !== 'undefined') ? attr : 'src';
        var image = $(selector).find('picture').find(tag).attr(attr);
        $('body').append('<div class="product-image-popup" id="productImagePopup"><div class="product-image-content"><img src="../../../Content/Default/Images/icon/close.svg" class="close" onclick="ProductImage.Close();"><img src="' + image + '" class="img-responsive" alt="product-image"/></div></div>');
    },
    Close: function () {
        $('#productImagePopup').detach();
    }
};

var DeliveryOptions = {
    id: 'ddChooseDeliveryOptions',
    overlay: {},
    init: function () {
        var button = document.getElementById(DeliveryOptions.id).querySelector('.dropdown-btn');
        var closeButton = document.getElementById(DeliveryOptions.id).querySelector('.close');
        var options = document.getElementById(DeliveryOptions.id).querySelectorAll('.dropdown-item');
        var confirmButton = document.getElementById(DeliveryOptions.id).querySelector('.confirm');
        button.addEventListener('click', DeliveryOptions.toggle);
        closeButton.addEventListener('click', DeliveryOptions.close);
        confirmButton.addEventListener('click', DeliveryOptions.confirm);
        for (var i = 0; i < options.length; i++) {
            options[i].addEventListener('click', function (e) {
                e.preventDefault ? e.preventDefault() : e.returnValue = false;
                DeliveryOptions.change(e.target);
            });
        }
    },
    open: function () {
        var dropdown = document.getElementById(DeliveryOptions.id);
        dropdown.classList.add('open');
        dropdown.querySelector('.dropdown-menu').classList.add('open');
        dropdown.querySelector('.dropdown-menu').setAttribute('aria-expanded', true);
        DeliveryOptions.addOverlay();
    },
    close: function () {
        var dropdown = document.getElementById(DeliveryOptions.id);
        dropdown.classList.remove('open');
        dropdown.querySelector('.dropdown-menu').classList.remove('open');
        dropdown.querySelector('.dropdown-menu').setAttribute('aria-expanded', false);
        DeliveryOptions.removeOverlay();
    },
    toggle: function () {
        var dropdown = document.getElementById(DeliveryOptions.id);
        dropdown.classList.contains('open') ?
        DeliveryOptions.close() :
        DeliveryOptions.open();
    },
    change: function (selected) {
        var button = document.getElementById(DeliveryOptions.id).querySelector('.dropdown-btn');
        var options = document.getElementById(DeliveryOptions.id).querySelectorAll('.dropdown-item');
        var option = selected.closest('.dropdown-item');

        for (var i = 0; i < options.length; i++) {
            options[i].classList.remove('selected');
        }

        option.classList.add('selected');
        button.innerHTML = '<img class="logo absolute" src="' + option.querySelector('.logo').getAttribute('src') + '"> <span class="name">' + option.querySelector('.name').innerText + '</span> - <span class="price">' + option.querySelector('.price').innerText + '</span>';
        if (window.innerWidth > 769) {
            DeliveryOptions.close();
        }
        
    },
    addOverlay: function () {
        if (window.innerWidth < 768) {
            var overlay = document.createElement('div');
            var dropdown = document.getElementById(DeliveryOptions.id);
            overlay.classList.add('overlay');
            dropdown.prepend(overlay);
            setTimeout(function () {
                overlay.classList.add('active');
            }, 0);
        }
    },
    removeOverlay: function () {
        if (window.innerWidth < 768) {
            var overlay = document.getElementById(DeliveryOptions.id).querySelector('.overlay');
            overlay.classList.remove('active');
            setTimeout(function () {
                overlay.remove();
            }, 150);
        }
    },
    confirm: function () {
        DeliveryOptions.close();
    }
};
var FilterState = {
    showFilters: true,
    init: function () {
        var filterButtons = $('.filter-dropdown'),
            flowersFilters = $('.flower-filters');

        flowersFilters.slideToggle();

        if (this.showFilters) {
            filterButtons.each(function () {
                $(this).addClass('show-state')
            });
            flowersFilters.slideDown();
            this.showFilters = false;
            GTM.CustomEvent("Filter", "toggleVisibility", "show");
        } else {
            filterButtons.each(function () {
                $(this).removeClass('show-state')
            });
            flowersFilters.slideUp();
            this.showFilters = true;
            GTM.CustomEvent("Filter", "toggleVisibility", "hide");
        }
    },
    toggle: function () {
        var flowersFilters = $('.flower-filters'),
            filterState = $('.filter-state'),
            toggleButton = $('.show-filters-toggle');
        

        if (this.showFilters) {
            filterState.each(function () {
                $(this).addClass('active');
            });

            toggleButton.each(function () {
                $(this).prop('checked', true);
            });

            flowersFilters.slideDown();
            this.showFilters = false;

        } else {
            filterState.each(function () {
                $(this).removeClass('active');
            });

            toggleButton.each(function () {
                $(this).prop('checked', false);
            });

            flowersFilters.slideUp();
            this.showFilters = true;
        }
    }
    
};

function CustomFilter(selector, query) {
    this.selector = selector;
    this.ids = [];
    this.previousIds = [];
    this.query = query;
};

CustomFilter.prototype.init = function (FilterManager) {
    var self = this;
    $(self.selector).on('changed.bs.select', function (e) {
        var selectedItems = $(self.selector).selectpicker('val');
        var noResultsEl = document.querySelector(".no-results");
        if(!noResultsEl.classList.contains("hidden"))
            noResultsEl.classList.add("hidden");

        clearInfiniteScrollState();

        self.ids = [];
        if (selectedItems) {
            for (var i = 0; i < selectedItems.length; i++) {
                var propertyId = $(self.selector).find('[value="' + selectedItems[i] + '"]').attr('data-tokens')

                if ($.inArray(propertyId, self.ids) === -1)
                    self.ids.push(propertyId);
            }
            self.previousIds = self.ids.slice(0);

            if (self.query) {
                sendFilteredData(e, self.query);
            } else {
                sendFilteredData(e);
            }
        } else {
            if (self.query && self.previousIds.length > 0) {
                sendFilteredData(e, self.query);
                self.previousIds = [];
            }

            if (self.previousIds.length > 0) {
                sendFilteredData(e);
                self.previousIds = [];
            }
        }
    });
};

CustomFilter.prototype.clearFilter = function () {
    $(this.selector).selectpicker('deselectAll');
    this.ids = [];
};


function FilterManager(
    ColorsFilter,
    TypesFilter,
    PriceRangesFilter,
    OccasionsFilter,
    BoxFloristFilter) {
    this.Colors = ColorsFilter;
    this.Types = TypesFilter;
    this.PriceRanges = PriceRangesFilter;
    this.Occasions = OccasionsFilter;
    this.BoxFlorist = BoxFloristFilter;
};

FilterManager.prototype.sendFilteredData = function (e, query) {
    SendGTMEvent(e);
    var args;
    if (query) {
        args = {
            Types: this.Types.ids,
            Colors: this.Colors.ids,
            PriceRanges: this.PriceRanges.ids,
            Occasions: this.Occasions.ids,
            BoxFlorist: this.BoxFlorist.ids,
            Query: query
        };

        CallController("Search", "FilterRequest", args, updateFilteredView, { Overlay: true });
    } else {
        var isAllProductsPage = $('#hfPageType').val() !== undefined && $('#hfPageType').val() == 'AllProducts';

        if (this.Types.ids.length > 0
            || this.Colors.ids.length > 0
            || this.PriceRanges.ids.length > 0
            || this.Occasions.ids.length > 0
            || this.BoxFlorist.ids.length  > 0) {

            args = {
                Types: this.Types.ids,
                Colors: this.Colors.ids,
                PriceRanges: this.PriceRanges.ids,
                Occasions: this.Occasions.ids,
                BoxFlorist: this.BoxFlorist.ids,
                CategoryId: $('#hfCategoryId').val(),
                Query: $('#SearchQuery').val(),
                IsAllProductsPage: isAllProductsPage
            };

            CallController("Search", "FilterRequest", args, updateFilteredView, { Overlay: true });
        }
        else if (this.Types.ids.length === 0
                && this.Colors.ids.length === 0
                && this.PriceRanges.ids.length === 0
                && this.Occasions.ids.length === 0
                && this.BoxFlorist.ids.length === 0) {
            args = {
                CategoryId: $('#hfCategoryId').val(),
                Query: $('#SearchQuery').val(),
                IsAllProductsPage: isAllProductsPage
            }
            CallController("Search", "FilterRequest", args, updateFilteredView, { Overlay: true });
        }
    }
};

function getFiltersObjects() {
    var isMobile = (/Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent)),
        isAllProductsPage = $('#hfPageType').val() !== undefined && $('#hfPageType').val() == 'AllProducts';

    if (isMobile && isAllProductsPage)
        return {
            Color: ColorFilterMobile,
            Types: TypeFilterMobile,
            PriceRanges: PriceFilterMobile,
            Occasions: OccasionFilterMobile,
            BoxFlorist: BoxFloristFilterMobile
        };
    else
        return {
            Color: ColorFilter,
            Types: TypeFilter,
            PriceRanges: PriceFilter,
            Occasions: OccasionFilter,
            BoxFlorist: BoxFloristFilter
        };
}

function sendFilteredData(e, query) {
    SendGTMEvent(e);
    var args,
        filters = getFiltersObjects();
    if (query) {
        args = {
            Types: filters.Types.ids,
            Colors: filters.Color.ids,
            PriceRanges: filters.PriceRanges.ids,
            Occasions: filters.Occasions.ids,
            BoxFlorist: filters.BoxFlorist.ids,
            Query: query            
        };

        CallController("Search", "FilterRequest", args, updateFilteredView, { Overlay: true });
    } else {
        var isAllProductsPage = $('#hfPageType').val() !== undefined && $('#hfPageType').val() == 'AllProducts';

        if (filters.Types.ids.length > 0
            || filters.Color.ids.length > 0
            || filters.PriceRanges.ids.length > 0
            || filters.Occasions.ids.length > 0
            || filters.BoxFlorist.ids.length > 0) {

            args = {
                Types: filters.Types.ids,
                Colors: filters.Color.ids,
                PriceRanges: filters.PriceRanges.ids,
                Occasions: filters.Occasions.ids,
                BoxFlorist: filters.BoxFlorist.ids,
                CategoryId: $('#hfCategoryId').val(),
                Query: $('#SearchQuery').val(),
                IsAllProductsPage: isAllProductsPage
            };

            CallController("Search", "FilterRequest", args, updateFilteredView, { Overlay: true });
        }
        else if (filters.Types.ids.length === 0
            && filters.Color.ids.length === 0
            && filters.PriceRanges.ids.length === 0
            && filters.Occasions.ids.length === 0
            && filters.BoxFlorist.ids.length === 0) {
            args = {
                CategoryId: $('#hfCategoryId').val(),
                Query: $('#SearchQuery').val(),
                IsAllProductsPage: isAllProductsPage
            };

            CallController("Search", "FilterRequest", args, updateFilteredView, { Overlay: true });
        }
    }
};

function getInfiniteScrollAllProductsArgs() {
    var args,
        filters = getFiltersObjects();

    if (filters.Types.ids.length > 0
        || filters.Color.ids.length > 0
        || filters.PriceRanges.ids.length > 0
        || filters.Occasions.ids.length > 0
        || filters.BoxFlorist.ids.length > 0) {
        args = {
            Types: filters.Types.ids, 
            Colors: filters.Color.ids,
            PriceRanges: filters.PriceRanges.ids,
            Occasions: filters.Occasions.ids,
            BoxFlorist: filters.BoxFlorist.ids,
            IsAllProductsPage: true,
            BlockNumber: BlockNumber,
            IsInfiniteScroll: true
        };
    }
    else if (filters.Types.ids.length === 0
        && filters.Color.ids.length === 0
        && filters.PriceRanges.ids.length === 0
        && filters.Occasions.ids.length === 0
        && filters.BoxFlorist.ids.length === 0) {
        args = {
            IsAllProductsPage: true,
            BlockNumber: BlockNumber,
            IsInfiniteScroll: true
        };
    }

    return args;
}

function clearFilters() {
    var noResultsEl = document.querySelector(".no-results");
    if (!("hidden" in noResultsEl.classList))
        noResultsEl.classList.add("hidden");
}

function SendGTMEvent(e) {
    if (typeof e != 'undefined' && e.target.nodeName === 'SELECT') {
        var _array = $("#" + e.target.id + " option:selected");
        var _arrayValues = _array
            .map(function (i) {
                return _array[i].value;
            });
        GTM.CustomEvent("Filter", e.target.id.split("-")[0], _arrayValues.toArray().join(", "));
    }
    else {
        GTM.CustomEvent("Filter", "reset", true);
    }
};

function updateFilteredView(response) {
    var updatePanel = '#productListContainerUpdatePanel';
    $(updatePanel).attr("style", "height:" + $(updatePanel).outerHeight(true) + "px");
    $(updatePanel).fadeOut('fast', function () {
        $(updatePanel).html(response);
        $(document).trigger('abt-loaded');
        $(updatePanel).fadeIn("fast", function () {
            $(updatePanel).removeAttr("style");
        });
    });
}

function calculateGapForInfiniteScroll() {
    if ($('.mn-footer').height() == null) {
        if (document.querySelector('footer') != null) {
            return document.querySelector('footer').clientHeight;
        }
        else {
            return 0;
        }
    }
    else {
        var result = 0;

        $('.mn-footer').each(function () {
            result += $(this).height();
        });

        $('.ef-footer').each(function () {
            result += $(this).height();
        });
        return result;
    }
}

function clearInfiniteScrollState() {
    if (typeof NoMoreData !== 'undefined') {
        NoMoreData = false;
    }
    if (typeof BlockNumber !== 'undefined') {
        BlockNumber = 2;
    }
}

function clearFilterObjects() {    
    ColorFilter.clearFilter();
    TypeFilter.clearFilter();
    PriceFilter.clearFilter();
    OccasionFilter.clearFilter();
    BoxFloristFilter.clearFilter();

    ColorFilterMobile.clearFilter();
    TypeFilterMobile.clearFilter();
    PriceFilterMobile.clearFilter();
    OccasionFilterMobile.clearFilter();
    BoxFloristFilterMobile.clearFilter();
}

var ColorFilter = new CustomFilter('.main-filters .color-filter', $('#search').val());
var TypeFilter = new CustomFilter('.main-filters .type-filter', $('#search').val());
var PriceFilter = new CustomFilter('.main-filters .price-filter', $('#search').val());
var OccasionFilter = new CustomFilter('.main-filters .occasion-filter', $('#search').val());
var BoxFloristFilter = new CustomFilter('.main-filters .box-filter', $('#search').val());

var ColorFilterMobile = new CustomFilter('.filters-mobile .color-filter', $('#search').val());
var TypeFilterMobile = new CustomFilter('.filters-mobile .type-filter', $('#search').val());
var PriceFilterMobile = new CustomFilter('.filters-mobile .price-filter', $('#search').val());
var OccasionFilterMobile = new CustomFilter('.filters-mobile .occasion-filter', $('#search').val());
var BoxFloristFilterMobile = new CustomFilter('.filters-mobile .box-filter', $('#search').val());

$(function () {
    ColorFilterMobile.init();
    TypeFilterMobile.init();
    PriceFilterMobile.init();
    OccasionFilterMobile.init();
    BoxFloristFilterMobile.init();

    ColorFilter.init();
    TypeFilter.init();
    PriceFilter.init();
    OccasionFilter.init();
    BoxFloristFilter.init();

    $('.clear-filters').on('click', function (e) {
        clearFilterObjects();
        sendFilteredData(e, $('#search').val());
        clearFilters();
    });
});;
//============== SEARCH FLORIST ==============

function SearchFlorist(query, updatePanelId) {
    var callback = function (view) {
        $('#' + updatePanelId).html(view);
        $('#tbSearchQuery').focus();
    };

    CallController('Florist', 'SearchFlorist', { SearchQuery: query }, callback, null);
}

var SearchFloristTypingTimer;
var SearchFloristDoneTypingInterval = 700;

//Detect keystroke and only execute after the user has finish typing
function SearchFloristWithDelay(query, updatePanelId) {
    if (query.length > 2) {
        clearTimeout(SearchFloristTypingTimer);
        SearchFloristTypingTimer = setTimeout(function () { SearchFlorist(query, updatePanelId); }, SearchFloristDoneTypingInterval);

        return true;
    }

    return false;
}

//============== SEARCH ==============

var typingTimer;
var doneTypingInterval = 700;

//Detect keystroke and only execute after the user has finish typing
function delayExecute() {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(
        function () { Search_OnChangeSearch(true); },
        doneTypingInterval
    );

    return true;
}

// Ext this if u need new query parameters
function SearchViewModel(query, country, order) {
    this.SearchQuery = query;
    this.SelectedSearchOrder = order;
    this.SelectedCountry = country;
}

function Search_OnChangeSearch(isTextBox) {
    var search = $("#tbSearchQuery");
    var searchOrder = $("#ddlSearchOrder");
    var searchCountry = $("#ddlSearchCountry");

    if (search.val().length > 2 || searchCountry.prop("selectedIndex") > 0) {
        var args = new SearchViewModel(search.val(), searchCountry.val(), searchOrder.val());

        var callback = function (response) {
            $("#searchProductsUpdatePanel").html(response);

            $("#tbSearchQuery").focus();
            var val = $("#tbSearchQuery").val(); //store the value of the element
            $("#tbSearchQuery").val(''); //clear the value of the element
            $("#tbSearchQuery").val(val); //set that value back.
        };
        search.blur();
        CallController("Search", "SearchFlower", args, callback, null);
    }
}

// Disable submit after press ENTER
function disableSubmit(e) {
    e = e || window.event;
    var key = e.keyCode;
    if (key === 13) //Enter
    {
        //return false; //return true to submit, false to do nothing
        Search_OnChangeSearch();
    }
};
var phoneTabs = {
    prevBody: '#senderPhone1',
    tabBody: '',
    init: function () {
        this.tabBody = $('.tab-head').find('input[name="Sender.ChoosenPhoneType"]:checked').attr('data-tab');
        $(this.tabBody).addClass('active');
        this.prevBody = this.tabBody;

        this.isMobileEntered();

        $(".tab-head").hover(
            function () {
                var $self = $(this);
                $input = $($self.find("input[type='radio']").attr("data-tab")).find(".form-control");
                $input.addClass("hover");
            },
            function () {
                var $self = $(this);
                $input = $($self.find("input[type='radio']").attr("data-tab")).find(".form-control");
                $input.removeClass("hover");
            }
        );

        $(".tab-body input.form-control").hover(
            function () {
                var $self = $(this),
                    $radioParent = $("input[data-tab='#" + $self.closest(".tab-pane").attr("id") + "']").closest(".tab-head");
                $radioParent.addClass("hover");
            },
            function () {
                var $self = $(this),
                    $radioParent = $("input[data-tab='#" + $self.closest(".tab-pane").attr("id") + "']").closest(".tab-head");
                $radioParent.removeClass("hover");
            }
        );
        $(".tab-body input.form-control").focusin(
            function () {
                var $self = $(this);
                $radioParent = $("input[data-tab='#" + $self.closest(".tab-pane").attr("id") + "']").closest(".tab-head");
                $radioParent.addClass("focus");
            }
        );
        $(".tab-body input.form-control").focusout(
            function () {
                var $self = $(this);
                $radioParent = $("input[data-tab='#" + $self.closest(".tab-pane").attr("id") + "']").closest(".tab-head");
                $radioParent.removeClass("focus");
            }
        );
    },
    updateTabs: function (event) {
        this.isMobileEntered();

        this.tabBody = $(event.currentTarget).attr('data-tab');
        $(this.tabBody).addClass('active');

        if (this.prevBody !== this.tabBody && this.tabBody !== undefined) {
            $(this.prevBody).removeClass('active');
        }
        this.prevBody = this.tabBody;
    },
    isMobileEntered: function () {
        $('#rbPhoneType_Mobile').is(':checked') ? $('#Sender_IsMobilePhoneEntered').val(true) : $('#Sender_IsMobilePhoneEntered').val(false);
    }
};;
function InitiateRegister() {
    var cbRegister = $("input:checkbox[id$='cbxRegisterAccount'],input:checkbox[id$='IWantToRegister']");
    var tbPassword = $("input:password[id$='tbPassword']");
    var tbConfirmPassword = $("input:password[id$='tbConfirmPassword']");
    var pnlPassword = $("div.passwordPanel");
    if (!$(cbRegister).prop("checked")) {
        pnlPassword.css({
            height: "0",
            display: "none"
        });
    }
    cbRegister.click(function () {
        if (!$(this).prop('checked')) {
            tbPassword.val('');
            tbConfirmPassword.val('');
            pnlPassword.css({
                height: "0",
                display: "none"
            }).removeClass('active');
        }
        else {
            pnlPassword.css({
                height: "auto",
                display: "block"
            }).addClass('active');

        }
    });
}

function OnChangeCbxTerms() {
    if ($('#cbxTerms').is(":checked"))
        $('#hCbxTerms').val('true');
    else
        $('#hCbxTerms').val('false');
}
;
//get all responsive videos
var responsiveVideos = document.querySelectorAll('video.responsive-mp4');

//add source to video tag
function addSourceToVideo(element, src) {
    var source = document.createElement('source');
    source.src = src;
    source.type = 'video/mp4';
    element.appendChild(source);

}

//determine screen size and select mobile or desktop video
function setProperVideoSource(element) {
    var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
    if (windowWidth > 768) {
        addSourceToVideo(element, element.dataset.desktopVid);
    } else {
        addSourceToVideo(element, element.dataset.mobileVid);
    }
}

//init only if page has videos
function setResponsiveVideosSources() {
    if (responsiveVideos !== undefined) {
        for (var i = 0; i < responsiveVideos.length; i++) {
            setProperVideoSource(responsiveVideos[i]);
        }
    }
}

setResponsiveVideosSources();;
var Favorite = (function () {
    var MAX_FAVORITE_PRODUCTS = 30;

    var Popup = {
        show: function (popupType) {
            $.ajax({
                url: "/" + GetLanguagePrefix() + "Product/GetFavoritePopup",
                method: "POST",
                data: { favoritePopup: popupType },
                success: function (popup) {
                    if ($('.favorite-popup').length === 0) {
                        $('body').append(popup);
                    }
                    setTimeout(function () {
                        $('#favoritePopup').detach();
                    }, 6000);
                }
            });
        }
    };

    var PopupType = {
        maxProducts: 0,
        noProducts: 1
    };

    var Product = {
        init: function () {
            var pageType = getRouteType();
            if (pageType == "ProductDetail") {
                var productId = $('#ProductId').attr('value');
                if (productId && Cookie.get("FavoriteProducts").split(',').indexOf(productId.toString()) != -1) {
                    $('.favorite-product-container > .favorite').addClass('added-product');
                }
            } else {
                var favoriteProducts = Cookie.get("FavoriteProducts").split(','),
                    products = $('.product');

                products.each(function () {
                    var productId = $(this).data('product-id').toString(),
                        favoriteProduct = $(this).find('.favorite');

                    favoriteProduct.addClass('active');
                    if (favoriteProducts.indexOf(productId) != -1)
                        favoriteProduct.addClass('added-product');
                });
            }
        },
        add: function (elem, productId) {
            if (Product.getQuantity() < MAX_FAVORITE_PRODUCTS) {
                var favoriteProducts = Cookie.get("FavoriteProducts"),
                    updatedProducts = favoriteProducts.length > 0 ? favoriteProducts + "," + productId : productId;

                Cookie.set("FavoriteProducts", updatedProducts, 60 * 60 * 24 * 365 * 3);
                $(elem).parent('.favorite').addClass('added-product');
                Counter.update(true);
            }
            else
                Popup.show(PopupType.maxProducts);          
        },
        remove: function (elem, productId) {
            var products = Cookie.get("FavoriteProducts").split(','),
                productIndex = products.indexOf(productId.toString());

            if (productIndex > -1) {
                products.splice(productIndex, 1);
                Cookie.set("FavoriteProducts", products, 60 * 60 * 24 * 365 * 3);
                $(elem).parent('.favorite').removeClass('added-product');
                Counter.update(false);
            }
        },
        getQuantity: function () {
            return Cookie.get("FavoriteProducts").length > 0 ? Cookie.get("FavoriteProducts").split(',').length : 0;
        }
    };

    var Counter = {
        init: function () {  
            var quantity = Product.getQuantity();
            $('.favorite-quantity').text(quantity);
            this.changeState(quantity);
        },
        update: function (isAdded) {
            var favoriteQuantity = window.parseInt($('.favorite-quantity').eq(0).text());

            if (isAdded) $('.favorite-quantity').text(favoriteQuantity += 1);
            else $('.favorite-quantity').text(favoriteQuantity -= 1);

            this.changeState(Product.getQuantity());
            FavoritesGTM.addAttributes();
        },
        changeState: function (quantity) {
            if (quantity === 0) {
                $('#favorite').attr("onclick", "event.preventDefault();");
                $('#favorite').on('click', function () {
                    Popup.show(PopupType.noProducts);
                });

                $('#favorite-mobile').attr("onclick", "event.preventDefault();");
                $('#favorite-mobile').on('click', function () {
                    Popup.show(PopupType.noProducts);
                });

                $('.favorite-quantity').removeClass('active');
            }
            else {
                $('#favorite').removeAttr('onclick');
                $('#favorite').off('click');

                $('#favorite-mobile').removeAttr('onclick');
                $('#favorite-mobile').off('click');

                $('.favorite-quantity').addClass('active');

                FavoritesGTM.addAttributes();
            }
        }
    };

    var FavoritesGTM = {
        addAttributes: function () {
            var obj = document.getElementById("favorite");
            GTM.AddGtmDataAttributes(obj, 'favorites', 'my favorites', Product.getQuantity());
        }
    };

    return {
        init: function () {
            Product.init();
            Counter.init();
        },
        add: Product.add,
        remove: Product.remove
    };
})();;
var CalendarView = {
    RecipientDetails: function () {
        if (typeof CalendarVM !== "undefined") {
            var calendar = new Calendar(
                CalendarVM.Selector,
                CalendarVM.NotAllowedDates,
                CalendarVM.DatesWithMessages,
                CalendarVM.DateFormat,
                CalendarVM.MonthsNames,
                CalendarVM.DayNames,
                CalendarVM.DateRange,
                CalendarVM.MinDate,
                CalendarVM.DefaultDate,
                CalendarVM.SelectedDate,
                CalendarVM.OrderKey,
                CalendarVM.UpdateShippingFeesOnChange,
                CalendarVM.FireAddtionalMethodsOnChange
            );
            calendar.Initiate();
        }
    }
};
;
var Alert = (function () {
    var Settings = {
        alertContainerSelector: '#alertContainer',
		alertContainerWidth: 0,
        alertHeight: 100,
        alertMarginBottom: 15,
        animationType: "linear",
        animationTime: 1200,
        notificationsTimeScheduler: 10
	};

    var AlertManager = {
        getNotifications: function () {
            var self = this;
            $.get("Notification/GetNotifications", function (alerts) {  
                if (alerts.length > 0) {

                    alerts.forEach(function (alert, index) {
                        var now = new Date().getTime(),
                            startDate = new Date(alert.StartDate).getTime(),
                            endDate = new Date(alert.EndDate).getTime();

                        if (now >= startDate && now <= endDate) 
                            AlertManager.createAlert(alert);
                    });
                }
            });
            setInterval(function () {
            }, Settings.notificationsTimeScheduler);
        },
		createAlert: function (alert) {
			this.addAlertContainer();
            var alert = new AlertItem(alert);
			alert.create();
		},
		addAlertContainer: function () {
            var alertContainer = document.querySelector(Settings.alertContainerSelector);
			if (alertContainer === null) {
				alertContainer = document.createElement('div');
				alertContainer.setAttribute('class', 'alert-container');
				alertContainer.setAttribute('id', 'alertContainer');
				document.body.appendChild(alertContainer);
			}
        },
        resizeContainerHeight: function (alertsCount) {
            var height = alertsCount * (Settings.alertHeight + Settings.alertMarginBottom);
            $(Settings.alertContainerSelector).css('height', height);
        },
        hideAlert: function (alertId) {
            $('#alert-' + alertId).animate({ opacity: 0, left: 415 },
                Settings.animationTime,
                Settings.animationType,
                function () {
                    $(this).detach();
                });
        }
	};

    function AlertItem(alert) {
        this.id = alert.Id;
        this.imgUrl = alert.ImageUrl;
        this.text = alert.DescriptionText;
        this.delayTime = alert.DelayOfShowingTime;
        this.disappearingTime = alert.DisappearingTime;
    }

    AlertItem.prototype.create = function () {
        this.wasShowed()
        this.show();
    }

    AlertItem.prototype.show = function () {
        var self = this;
        setTimeout(function () {
            var alert = document.createElement('div');
            self.imgUrl = self.imgUrl || 'Content/EuroWeb/Images/InfoIco@x2.png';
            alert.setAttribute('class', 'alert-item');
            alert.setAttribute('id', 'alert-' + self.id);
            alert.innerHTML = '<i class="close-alert" onclick="Alert.hide(' + self.id + ')">&#10006;</i><div class="img-container"><img class="alert-img" src="' + self.imgUrl + '" alt="alert-icon" /></div><div class="content-container"><p>' + self.text + '</p></div>';
            $(Settings.alertContainerSelector).prepend(alert);
            $('#alert-' + self.id).animate({ opacity: 1, left: 0 },
                Settings.animationTime,
                Settings.animationType
            );
            self.hide();
        }, (this.delayTime * 1000));
    }

    AlertItem.prototype.hide = function () {
        var self = this;
        setTimeout(function () {
            $('#alert-' + self.id).animate({ opacity: 0, left: 415 },
                Settings.animationTime,
                Settings.animationType,
                function () {
                    $(this).detach();
                });
        }, (this.disappearingTime * 1000));
    }

    AlertItem.prototype.wasShowed = function () {
        $.ajax({
            type: "POST",
            url: "Notification/SetNotificationShown",
            data: { id: this.id }
        });
    }

	return {
        get: AlertManager.getNotifications,
        hide: AlertManager.hideAlert
	};
})();

;
//============== CHECKOUT ==============
//Checking if ellipsis is needed for product name in RemainingItems view

function TrackFormHistory(selector) {
    var i;
    var checkSubmit = function () {
        i = window.dataLayer.length - 1;
        while (i > -1) {
            if (window.dataLayer[i]['event'] === 'gtm.formSubmit') {
                return true;
            }
            i--;
        }
    };

    var formSelector = '#' + selector;
    var attribute = 'name';
    var formhistory = [];
    window.addEventListener('beforeunload', function () {
        if (formhistory.length && !checkSubmit()) {
            window.dataLayer.push({
                'event': 'errorAll',
                'eventCategory': 'error',
                'eventAction': formhistory.join(' > '),
                'eventLabel': window.location.pathname,
                'eventValue': undefined
            });
        }
	});

	$(document).on('submit', formSelector, function () {
		var validate = $(this).validate();
		if (validate && validate.valid()) {
			window.dataLayer.push({
				'event': 'gtm.formSubmit'
			});
		}
		return true;
	});

    document.querySelector(formSelector).addEventListener('change', function (e) {
        formhistory.push(e['target'].getAttribute(attribute));
    });
}

function RemainingProductNameWidthFix() {
    var items = $(".items .item .name-wrapper");
    $(items).each(function () {
        var wrapperWidth = $(this).width();
        var imgWidth = $(this).find("img").outerWidth();
        var statusWidth = $(this).find(".formFillSuccess, .incomplete").outerWidth();
        var priceWidth = $(this).find(".price").outerWidth();
        var textWidth = wrapperWidth - (imgWidth + statusWidth + priceWidth + 20);
        var $textField = $(this).find(".nameEllipsis");

        $textField.attr("style", "");
        if (textWidth < $textField.width())
            $textField.width(textWidth);
    });
}

function UpdateCustomMessagesDropDown(sender, updatePanelId) {
    var ocId = $(sender).val();
    var updatePanel = $('#' + updatePanelId);

    if (ocId !== null && ocId !== "") {
        var callback = function (html) {
            updatePanel.html(html);

            $("#ddlCustomMessage").selectpicker('render').selectpicker('refresh').change();
        };

        CallController("Checkout", "UpdateCustomMessagesDropDown", { occasionId: ocId }, callback, null);
    }
}

function FillCustomMessagesDropDown() {
    $("#ddlCustomMessage").empty();
    var ocId = $("#ddlOccasion").val();

    if (ocId != null && ocId != "") {
        var callback = function (data) {
            if (data == null || data.length == 0) {
                $("#customMessageContainer").hide();
            }
            else {
                $("#customMessageContainer").show();
            }

            $.each(data, function (i, state) {
                $("#ddlCustomMessage").append('<option value="' + state.Value + '">' + state.Text + '</option>');
            });

            $("#ddlCustomMessage").selectpicker('render');
            $("#ddlCustomMessage").selectpicker('refresh');

            if ($("#tbDeliveryCardText").val() !== "") {
                $("#ddlCustomMessage").val($("#tbDeliveryCardText").val());
                $("#ddlCustomMessage").change();
            }
        };

        CallController("Checkout", "FillCustomMessagesDropDown", { occasionId: ocId }, callback, null);
    }
}

function UpdateCardMessage(sender, tbId) {
    var text = $(sender).val();
    if (text !== '') {
        $('#' + tbId).val(text);
    }
}

function GetCardMessage() {
    if ($("#ddlCustomMessage").val() !== null) {
        var text = $("#ddlCustomMessage").val();
        $("#tbDeliveryCardText").val(text);
    }
}

var _addressSeachTimer;
function GetAddressSearchResult(field, updatePanel, pageType, isFieldValidated, delay) {
    delay = typeof delay !== 'undefined' ? delay : 0;
    var actionField = $(field);

    if (isFieldValidated)
        actionField.valid();

    var callback = function (data) {
        $(updatePanel).html(data);
    };
    if (delay > 0) {
        clearTimeout(_addressSeachTimer);
        _addressSeachTimer = setTimeout(
            function () {
                CallController("Checkout", "PrepareAddressSearchResult", { pageType: pageType, searchQuery: actionField.val() }, callback, null);
            },
            delay);
    }
    else {
        CallController("Checkout", "PrepareAddressSearchResult", { pageType: pageType, searchQuery: actionField.val() }, callback, null);
    }
}

function GetPaymentRule(topOrder) {
    var callback = function (result) {
        $('#billingUpdatePanel').html(result);
    };

    CallController("Checkout", "GetPaymentRule", { topOrder: topOrder }, callback, null);
}

function FillRecipientFromContacts(updatePanel) {
    var contactId = $('#ddlRecipient').val();

    var callback = function (data) {
        $(updatePanel).html(data);
        SaveWholeCheckout(false);
        if ($('.checkout-info-icon').length) {
            Tippy('.checkout-info-icon');
        }
    };

    CallController("Checkout", "FillRecipientFromContacts", { contactId: contactId }, callback, null);
}

var _recipientSearchTimeout;
function GetPhoneSearchResult(field, updatePanel, pageType, isFieldValidated, delay) {
    delay = typeof delay !== 'undefined' ? delay : 0;

    var actionField = $(field);

    if (isFieldValidated)
        actionField.valid();

    if ($('#eniroSearchPersonalPanel').length > 0) {
        if (!(!!actionField.val())) {
            $('#eniroSearchPersonalPanel').addClass("has-error");
            $('#eniroSearchPersonalPanel').removeClass("has-success");
            return;
        }
        else {
            $('#eniroSearchPersonalPanel').removeClass("has-error");
            $('#eniroSearchPersonalPanel').addClass("has-success");
        }
    }

    var callback = function (data) {
        $(updatePanel).html(data);
    };
    if (delay > 0) {
        clearTimeout(_recipientSearchTimeout);
        _recipientSearchTimeout = setTimeout(
            function () {
                CallController("Checkout", "PreparePhoneSearchResult", { pageType: pageType, phoneNumber: actionField.val() }, callback, null);
            },
            delay);
    }
    else {
        CallController("Checkout", "PreparePhoneSearchResult", { pageType: pageType, phoneNumber: actionField.val() }, callback, null);
    }
}

function UpdateRecipientDetails(args, updatePanel, showFields) {
    var callback = function (data) {
        if (data.error === undefined || data.error === null || data.error === "") {
            if (showFields && !args.addressBar) {
                ShowRecipientDetailsFields();
            }
            var allValid = true;

            if (args.version === 3 && $('#tbRecipientHouseNr').length < 1 && data.AddressLine1) {
                $('#tbRecipientAddress1').val(data.AddressLine1 + (data.HouseNr ? (' ' + data.HouseNr) : ''));
            } else
                $('#tbRecipientAddress1').val(data.AddressLine1);
            if (showFields && $('#tbRecipientAddress1').length > 0) {
                $("form").validate().element("#tbRecipientAddress1");
                if(!$('#tbRecipientAddress1').valid()) allValid = false;
            }

            $('#tbRecipientAddress2').val(data.AddressLine2);
            if (showFields && $('#tbRecipientAddress2').length > 0) {
                $("form").validate().element("#tbRecipientAddress2");
                if(!$('#tbRecipientAddress2').valid()) allValid = false;
            }

            $('#tbRecipientPostCode').val(data.PostCode);
            if (showFields && $('#tbRecipientPostCode').length > 0) {
                $("form").validate().element("#tbRecipientPostCode");
                if(!$('#tbRecipientPostCode').valid()) allValid = false;
            }

            $('#tbRecipientCity').val(data.Town);
            if (showFields && $('#tbRecipientCity').length > 0) {
                $("form").validate().element("#tbRecipientCity");
                if(!$('#tbRecipientCity').valid()) allValid = false;
            }

            $('#tbRecipientCounty').val(data.County);
            if (showFields && $('#tbRecipientCounty').length > 0) {
                $("form").validate().element("#tbRecipientCounty");
                if(!$('#tbRecipientCounty').valid()) allValid = false;
            }

            if (data.HouseNr !== undefined) {
                $('#tbRecipientHouseNr').val(data.HouseNr);
                if (showFields && $('#tbRecipientHouseNr').length > 0) {
                    $("form").validate().element("#tbRecipientHouseNr");
                    if(!$('#tbRecipientHouseNr').valid()) allValid = false;
                }
            }

            if (args.addressBar) {
                $('#address-bar-street').html(data.AddressLine1);
                $('#address-bar-housenr').html(data.HouseNr || '');
                $('#address-bar-line2').html(data.AddressLine2);
                $('#address-bar-city').html(data.Town);
                $('#address-bar-postcode').html(data.PostCode);

                ShowRecipientDetailsFields(allValid);
            }

            $(updatePanel).empty();

            if (args.pageType !== 'MyAccount')
                ValidatePostCode('danger', '7000');
        }
        else {
            ShowInfoTooltip(data.error, 'danger', 5000);
            ShowRecipientDetailsFields();
        }
    };

    CallController("Checkout", "UpdateRecipientDetails", args, callback, null);
}

function ShowRecipientDetailsFields(showAddressBar) {
    $('.sub-link.manual').hide();
    $('.sub-link.clear').show();
    if(showAddressBar === true) {
        $(".address-bar").removeClass("hidden");
        $('.fill-panel.address-search').removeClass("extended");
    } else {
        $(".address-bar").addClass("hidden");
        $('.fill-panel.address-search').addDistinctClass("extended");
    }
    $('.country-label').addDistinctClass("has-success");
    $('.form-group.address-search').removeClass("extended");
    $('.address-search-list').css('display', 'none');
}

function ResetAddressSearch() {
    $('.sub-link.clear').hide();
    $('.sub-link.manual').show();
    $('.country-label').removeClass("has-success");
    $('.fill-panel.address-search').find("input").each(function () {
        $(this).val("");
        $(this).closest(".form-group").removeClass("has-success active");
    });
    $('.fill-panel.address-search').removeClass("extended");
    $('.address-search').removeClass("error has-success");
    $('.form-group.address-search').addDistinctClass("extended");
    $(".ui-autocomplete-input").val('').focus();
    $(".ui-autocomplete-input").parent().addClass('active');

    var element = document.querySelector('#tbRecipientAddressSearchQuery') || document.querySelector('#tbRecipientSearchQuery');
    if (element) {
        element.setAttribute("autocomplete", "new-password");
    }
}

function UpdateRecipientWithPhoneSearchDetails(args, updatePanel) {
    var callback = function (data) {
        
        // process the data coming back
        $('#tbRecipientFirstName').val(data.FirstName);
        $('#tbRecipientLastName').val(data.LastName);
        $('#tbRecipientAddress1').val(data.StreetAddress);
        $('#tbRecipientAddress2').val('');
        $('#tbRecipientPostCode').val(data.ZipCode);
        $('#tbRecipientCity').val(data.City);
        $('#tbRecipientCounty').val(data.County);
        if ($('#tbRecipientAddress2').length) {
            $('#tbRecipientAddress2').val('');
            $('#tbRecipientAddress2').parents('.form-group').removeClass('active');
        }
		if ($('#tbRecipientTelephone').length) {
			$('#tbRecipientTelephone').val(data.PhoneNumber);
		}
        ShowRecipientDetailsFields();

        $(updatePanel).empty();
    };

    args.orderKey = $('#tbOrderKey').val();

    CallController("Checkout", "UpdateRecipientWithPhoneSearchDetails", args, callback, null);
}

function UpdateSenderDetails(args, updatePanel) {
    var callback = function (data) {
        // process the data coming back
        $('#tbSenderAddress1').val(data.AddressLine1);
        $('#tbSenderAddress2').val(data.AddressLine2);
        $('#tbSenderPostCode').val(data.PostCode);
        $('#tbSenderCity').val(data.Town);
        $('#tbSenderCounty').val(data.County);
        $(updatePanel).empty();
    };

    CallController("Checkout", "UpdateRecipientDetails", args, callback, null);
}

function ChangeBasketPreview(args, updatePanel, blockGoToPaymentButtonDuringReloading) {
    if (blockGoToPaymentButtonDuringReloading) {
        SetIsGoToPaymentButtonLoading(true);
    }
    
    var callback = function (data) {
        if (data.PartsToReload) {
            ReloadCheckoutParts(data.PartsToReload);
        } else {
            $(updatePanel).html(data);
        }

        if (blockGoToPaymentButtonDuringReloading) {
            SetIsGoToPaymentButtonLoading(false);
        }

        try {
            Tippy('.checkout-info-icon');
        } catch (error) {
            return true;
        }

        CalendarView.RecipientDetails();
    };

    args.PartsToReload = CheckPartsToReload(args.PartsToReload);
    CallController("Checkout", "ChangeBasketPreview", args, callback, null);
}

function SetIsGoToPaymentButtonLoading(isLoading) {
    if ($('.remaining-items-list').length) {
        $("#btnGoToPayment").prop("disabled", isLoading);
        $("#btnGoToPayment").toggleClass("btn-loading", isLoading);
    }
}

function CopyOrder(args, updatePanel) {
    var callback = function (data) {
        if (data === null || data === "")
            location.reload();
        else
            $(updatePanel).html(data);
    };    

	var orderSaved = function () {
		CallController("Checkout", "CopyOrder", args, callback, null);
	};

	SaveOrder(orderSaved);
}

function RemoveOrder(args, updatePanel) {
    var callback = function (data) {
        if (data.PartsToReload) {
            ReloadCheckoutParts(data.PartsToReload);
            return;
        }

        if (updatePanel) {

            if (data === null || data === "")
                location.href = "/" + args.LanguageCode;
            else
                $(updatePanel).html(data);

            var headercallback = function (data) {
                $("#HeaderBasketUpdatePanel").html(data);
            };

            CallController("Home", "GetHeaderBasketFromSessionSSL", {}, headercallback, null);
        }
    };

    var orderSaved = function () {
        args.PartsToReload = CheckPartsToReload(args.PartsToReload);
		CallController("Checkout", "RemoveOrder", args, callback, null);
	};

	SaveOrder(orderSaved);    
}

function RemoveOrderByOrderKey(orderKey, url) {
    var callback = function () {
        var headercallback = function (data) {
            $("#HeaderBasketUpdatePanel").html(data);
            window.location.href = url;
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, headercallback, null);
    };

    var orderSaved = function () {
        CallController("Checkout", "RemoveOrderByOrderKey", { orderKey: orderKey }, callback, null);
    };

    SaveOrder(orderSaved);  
}

function AddAccessory(args, updatePanel) {
	var orderSaved = function () {

		var billingSaved = function () {

			var callback = function (data) {
				$(updatePanel).html(data);

				var callbackBasket2 = function (data) {
					$("#HeaderCartUpdatePanel").html(data);
				};

                CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
                CallController("Checkout", "GetAccessoriesForSlider", args, function() {}, null);
			};
            args.PartsToReload = CheckPartsToReload(args.PartsToReload);
			CallController("Checkout", "AddAccessory", args, callback, null);
		}
		SaveBilling(billingSaved);
	};

	SaveOrder(orderSaved);
}

function CheckPartsToReload(parts) {
    if (typeof parts === 'undefined' ||
        parts === null ||
        parts.length === 0) return [];
    
    for (var i = 0; i < parts.length; i++) {
        var partToReload = $('*[data-reloadable-part="' + parts[i] + '"]');
        if (partToReload.length === 0) {
            return [];
        }
    }

    return parts;
}

function ReloadCheckoutParts(parts) {
    if (typeof parts === 'undefined' ||
        parts === null ||
        parts.length === 0) return null;

    for (var i = 0; i < parts.length; i++) {
        var partToReload = $('*[data-reloadable-part="' + parts[i].Key + '"]');
        if (partToReload.length > 0) {
            partToReload.html(parts[i].Value);
        }
    }
}

function RemoveAccessoryFromBasket(args, updatePanel, element) {
    var callback = function (data) {
        $(updatePanel).html(data);

        var callbackBasket = function (data) {
            $("#HeaderBasketUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket, null);
    };
    CallController("Checkout", "RemoveAccessory", args, callback, null);
}

function CartValidationSuccess(result) {
    if (result.successUrl) {
        // if the server returned a JSON object containing an url property we redirect the browser to
        // that url
		$('body').html("");
		window.location.href = result.successUrl;
    }
}

function UpdateGiftCards(args, updatePanel) {
    var callback = function (data) {
        $(updatePanel).html(data);
    };

    CallController("Checkout", "GetGiftCards", $.extend(args, { OccasionId: $("#ddlCardOccasion").val() }), callback, null);
}

function AddGiftCard(args, updatePanel) {
    var callback = function (data) {
        $(updatePanel).html(data);
    };

    CallController("Checkout", "AddGiftCard", $.extend(args, { OccasionId: $("#ddlCardOccasion").val() }), callback, null);
}

function RemoveGiftCard(args, updatePanel) {
    var callback = function (data) {
        if (data.PartsToReload) {
            ReloadCheckoutParts(data.PartsToReload);
        } else {
            $(updatePanel).html(data);
        }
    };

    args.PartsToReload = CheckPartsToReload(args.PartsToReload);
    CallController("Checkout", "RemoveGiftCard", $.extend(args, { OccasionId: $("#ddlCardOccasion").val() }), callback, null);
}

function AddGiftAdddon(args, updatePanel) {
    var callback = function (data) {
        $(updatePanel).html(data);
    };

    CallController("Checkout", "AddGiftAdddon", args, callback, null);
}

function RemoveGiftAddon(args, updatePanel) {
    var callback = function (data) {
        if (data.PartsToReload) {
            ReloadCheckoutParts(data.PartsToReload);
        } else {
            $(updatePanel).html(data);
        }
    };


    if ($('body').hasClass('rebranding-layout')) {
        args.ChosenOrderKey = $('#OrderKey').val();
    }

    args.PartsToReload = CheckPartsToReload(args.PartsToReload);
    CallController("Checkout", "RemoveGiftAddon", args, callback, null);
}

function RemoveAccessory(args, updatePanel) {
    var orderSaved = function () {

        var billingSaved = function () {

            var callback = function (data) {
                if (data.PartsToReload) {
                    ReloadCheckoutParts(data.PartsToReload);
                } else {
                    $(updatePanel).html(data);
                }

                try {
                    Tippy('.checkout-info-icon');
                } catch (error) {
                    return true;
                }
            };

            if ($('body').hasClass('rebranding-layout')) {
                args.ChosenOrderKey = $('#OrderKey').val();
            }
            args.PartsToReload = CheckPartsToReload(args.PartsToReload);
            CallController("Checkout", "RemoveAccessory", args, callback, null);
        };

        SaveBilling(billingSaved);
    };

    SaveOrder(orderSaved);
}

function AddAccessoryAddon(args, updatePanel) {
    var callback = function (data) {
        $(updatePanel).html(data);
    };

    CallController("Checkout", "AddAccessoryAddon", args, callback, null);
}

function PaymentMethodChange(args, updatePanel, funcWithCallback) {
    var chosenPaymentMethod = getSelectedPaymentMethod();

    $('.selected-payment-method').removeClass('selected-payment-method');
    $('input[name=ChosenPaymentMethod]:checked')
        .closest('.payment-method-box')
        .addClass('selected-payment-method');

    //var step = (typeof args.step === typeof undefined) ? 3 : args.step;
    //GTM.SelectPaymentOption(step, chosenPaymentMethod); // Will be activated in near future to track each change of payment option

    var callback = function (data) {
        $(updatePanel).html(data);

        try {
            $.validator.unobtrusive.addValidation('form#senderForm');
            Tippy('.billing-phone-icon');
            if (document.querySelectorAll('.js-checkout-login')) {
                new Modal('.js-checkout-login');
            }
        } catch (error) {
            return true;
        }
    };
    
    funcWithCallback(function () {
        CallController(
            "Checkout",
            "PaymentMethodChange",
            $.extend(args, { chosenPaymentMethod: chosenPaymentMethod }),
            callback, null);
    });
}

function SelectPaymentOption(step) {
    var chosenPaymentMethod = $('input[name=ChosenPaymentMethod]:checked').val();
    GTM.CheckoutOption(step, chosenPaymentMethod);
}

function ValidateBasketDiscount(field, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var callback = function (data) {
        $(discountUpdatePanel).replaceWith(data);

        var callbackBasket = function (data) {
            $('#' + pageUpdatePanel).html(data);
        };

        CallController("Checkout", "GetBasketDetailView", {}, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderBasketUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
        initDiscountField();
    };

    CallController("Checkout", "ValidateDiscount", {
        discountCode: $(field).val(),
        pageUpdatePanel: pageUpdatePanel,
        orderKey: orderKey,
        captchaResponse: $('#hfGoogleResponse').val()
    }, callback, null);
}

function ValidateBasketDiscountRebranding(field, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var discountFieldIsOpen = $(discountUpdatePanel).hasClass('active');

    var callback = function (data) {
        $(discountUpdatePanel).replaceWith(data);

        if (discountFieldIsOpen) {
            CollapsePanel.init();
            CollapsePanel.open();
        }

        var callbackBasket = function (data) {
            $('#' + pageUpdatePanel).html(data);
        };

        CallController("Checkout", "GetBasketDetailView", {}, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderBasketUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
    };

    CallController("Checkout", "ValidateDiscount", {
        discountCode: $(field).val(),
        pageUpdatePanel: pageUpdatePanel,
        orderKey: orderKey,
        captchaResponse: $('#hfGoogleResponse').val()
    }, callback, null);
}

function ValidateCartDiscount(field, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var callback = function (data) {
        $(discountUpdatePanel).html(data);

        var callbackBasket = function (data) {
            $("#OrderDetailsUpdatePanel").html(data);
        };

        CallController("Checkout", "GetBasketFromSession", { ChosenOrderKey: orderKey, PageUpdatePanel: pageUpdatePanel, partialName: "_CartPreviewOrders" }, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderCartUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
        initDiscountField(); 
    };

    CallController("Checkout", "ValidateDiscount", { discountCode: $(field).val(), pageUpdatePanel: pageUpdatePanel, orderKey: orderKey, captchaResponse: $('#hfGoogleResponse').val() }, callback, null);
}

function ValidateCartDiscountRebranding(field, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var discountFieldIsOpen = $(discountUpdatePanel).hasClass('active');

    var callback = function (data) {
        $(discountUpdatePanel).html(data);

        if (discountFieldIsOpen) {
            CollapsePanel.init();
            CollapsePanel.open();
        }

        var callbackBasket = function (data) {
            $("#OrderDetailsUpdatePanel").html(data);
        };

        CallController("Checkout", "GetBasketFromSession", { ChosenOrderKey: orderKey, PageUpdatePanel: pageUpdatePanel, partialName: "_CartPreviewOrders" }, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderCartUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
    };

    CallController("Checkout", "ValidateDiscount", { discountCode: $(field).val(), pageUpdatePanel: pageUpdatePanel, orderKey: orderKey, captchaResponse: $('#hfGoogleResponse').val() }, callback, null);
}

function RemoveCartDiscount(field, fieldName, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var callback = function (data) {
        $(discountUpdatePanel).html(data);

        var callbackBasket = function (data) {
            $("#OrderDetailsUpdatePanel").html(data);
        };

        CallController("Checkout", "GetBasketFromSession", { ChosenOrderKey: orderKey, PageUpdatePanel: pageUpdatePanel, partialName: "_CartPreviewOrders" }, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderCartUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
    };

    CallController("Checkout", "RemoveDiscount", {
        discountCode: $(field).parent().parent().find('input[name=' + fieldName + ']').attr('id'),
        pageUpdatePanel: pageUpdatePanel,
        orderKey: orderKey
    }, callback, null);
}

function RemoveCartDiscountRebranding(field, fieldName, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var discountFieldIsOpen = $(discountUpdatePanel).hasClass('active');

    var callback = function (data) {
        $(discountUpdatePanel).html(data);

        if (discountFieldIsOpen) {
            CollapsePanel.init();
            CollapsePanel.open();
        }

        var callbackBasket = function (data) {
            $("#OrderDetailsUpdatePanel").html(data);
        };

        CallController("Checkout", "GetBasketFromSession", {
            ChosenOrderKey: orderKey,
            PageUpdatePanel: pageUpdatePanel,
            partialName: "_CartPreviewOrders"
        }, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderCartUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
    };

    CallController("Checkout", "RemoveDiscount", {
        discountCode: $('#discountId').data('discount-code'),
        pageUpdatePanel: pageUpdatePanel,
        orderKey: orderKey
    }, callback, null);
}

function RemoveBasketDiscountRebranding(field, fieldName, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var discountFieldIsOpen = $(discountUpdatePanel).hasClass('active');

    var callback = function (data) {
        $(discountUpdatePanel).html(data);

        if (discountFieldIsOpen) {
            CollapsePanel.init();
            CollapsePanel.open();
        }

        var callbackBasket = function (data) {
            $('#' + pageUpdatePanel).html(data);
        };

        CallController("Checkout", "GetBasketDetailView", {}, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderBasketUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
    };

    CallController("Checkout", "RemoveDiscount", {
        discountCode: $('#discountId').data('discount-code'),
        pageUpdatePanel: pageUpdatePanel,
        orderKey: orderKey
    }, callback, null);
}

function RemoveBasketDiscount(field, fieldName, discountUpdatePanel, orderKey, pageUpdatePanel) {
    var callback = function (data) {
        $(discountUpdatePanel).html(data);

        var callbackBasket = function (data) {
            $('#' + pageUpdatePanel).html(data);
        };

        CallController("Checkout", "GetBasketDetailView", {}, callbackBasket, null);

        var callbackBasket2 = function (data) {
            $("#HeaderBasketUpdatePanel").html(data);
        };

        CallController("Home", "GetHeaderBasketFromSessionSSL", {}, callbackBasket2, null);
    };

    CallController("Checkout", "RemoveDiscount", { discountCode: $(field).parent().siblings('input[name=' + fieldName + ']').attr('id'), pageUpdatePanel: pageUpdatePanel, orderKey: orderKey }, callback, null);
}

function ValidateSerialNumber(field, updatePanel, billingUpdatePanel, orderKey, panelType) {
    var callback = function (data) {
        $(updatePanel).html(data);

        var callbackBasket = function (data) {
            $(billingUpdatePanel).html(data);
        };

        CallController("Checkout", "GetBasketFromSession", { ChosenOrderKey: orderKey, PageUpdatePanel: panelType }, callbackBasket, null);
    };

    CallController("Checkout", "ValidateSerialNumber", { serialNumber: $(field).val(), voucherCode: $(field).parent().parent().parent().find('input').attr('id') }, callback, null);
}

function ValidateSerialNumberCart(field, updatePanel, billingUpdatePanel, orderKey, panelType, returnPartial) {
    var callback = function (data) {
        $(updatePanel).html(data);

        var callbackBasket = function (data) {
            $(billingUpdatePanel).html(data);
        };

        CallController("Checkout", "GetBasketView", { ChosenOrderKey: orderKey, PageUpdatePanel: panelType }, callbackBasket, null);
    };

    CallController("Checkout", "ValidateSerialNumber", { serialNumber: $(field).val(), voucherCode: $(field).parent().parent().parent().find('input').attr('id'), returnPartial: returnPartial }, callback, null);
}

function GiftCardChange(occastionPanel, ddlOccasionId, isFreeGiftCard) {
    if (isFreeGiftCard) {
        $(ddlOccasionId).append($('<option>', {
            value: 0,
            text: 'Not defined'
        }));
        $(ddlOccasionId).val(0);

        $(occastionPanel).hide();
    }
    else {
        $(occastionPanel).show();
        $(ddlOccasionId + " option[value='0']").remove();
    }
}

function makePayment(button, event, onePageCheckout) {
    try {
        if (event) {
            event.preventDefault();
        }

        var chosenPaymentMethod = getSelectedPaymentMethod();

        if (chosenPaymentMethod.toLowerCase() !== 'klarnaprivate') {
            removeWhitespaces('#tbSenderTelephone');
            removeWhitespaces('#tbRecipientTelephone');
        }
        
        var isFormValid = validateRecipientForm(onePageCheckout === true ? '#recipientForm' : "#senderForm");
        var isAdyenValid = Adyen.validate(chosenPaymentMethod);

        var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent));
        if(isFormValid && !isAdyenValid && isMobile){                  
                //Adyen errors don't show immediately
                setTimeout(function () {
                    try {
                        //scroll to Adyen error    
                        $('html, body').animate({
                            scrollTop: ($('.adyen-checkout__field--error').offset().top - 200)
                        }, 2000);
                    } catch (ex) {}
                });            
        }
        
        var funcWithCallback = onePageCheckout === true
        ? function (callback) {
                SaveWholeCheckout(true, callback);
            }
        : SaveBilling;
        
        if(!isFormValid || !isAdyenValid){
            funcWithCallback();
            return false;
        }

        if (onePageCheckout) {
            TriggerGTMBlockedLocationEventIfNeeded();
        }

        if(Adyen.pay(chosenPaymentMethod, funcWithCallback, event)) {
            //Adyen will handle further payment proccess
            return false;
        }
        
        SubmitOnCallback(button, funcWithCallback, event, true);
    } catch (exception) {
        LogFatalError("Error makePayment: " + exception)
    }
}

function TriggerGTMBlockedLocationEventIfNeeded() {
    if (!document.getElementById('tbRecipientPostCode')
        || !document.getElementById('tbRecipientCity')) {
        return;
    }

    var deliveryRestrictionsCallback = function (response) {
        if (response !== "" && response.isLocationBlocked) {
            GTM.ProductNotAvailableForPostcode($('#tbRecipientPostCode').val(), 'global_blocked');
        }
    }

    CallController("Delivery", "IsLocationBlocked", { orderKey: $(document.getElementById("tbOrderKey")).val() }, deliveryRestrictionsCallback, null);
}

function PayWithApplePay(options, elem, funcWithCallback) {
    if (!options || !options.TotalPrice) {
        LogWarning('[main.checkout].[PayWithApplePay] undefined TotalPrice! options: ' + JSON.stringify(options) + ' \nStackTrace: ' + JSON.stringify(new Error().stack));
    }

    var request = {
        countryCode: window.CountryCode,
        currencyCode: window.Currency,
        supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
        merchantCapabilities: ['supports3DS'],
        total: {
            label: window.Brand,
            amount: options.TotalPrice.toString()
        },
    };

    //Version 4 added support for new supported networks, if not available then fallback to 1 
    var version = window.ApplePaySession.supportsVersion(4) === true ? 4 : 1;

    if (version === 4) {
        request.supportedNetworks = request.supportedNetworks.concat(['maestro', 'electron', 'cartesBancaires']);
    }
    var session = new ApplePaySession(version, request);

    session.onvalidatemerchant = function(event) {
        $.post("/Payment/ApplePayRequestSession", { url: event.validationURL })
            .done(function (result) {
                if (result.Success) {
                    session.completeMerchantValidation(result.Data);
                } else {
                    session.abort();
                    Adyen.resolveResult(result);
                }
            })
            .fail(function (jqXHR, textStatus) {
                LogFatalError(
                    'Error on validating ApplePay merchant session. Status:' + textStatus);
                window.location.reload(false);
            });
    };

    session.onpaymentauthorized = function (event) {
        OverlayOn('body', true);
        var token = JSON.stringify(event.payment.token.paymentData);
        $('#applepaytoken').val(token);
        if (typeof options.OnAuthorized === 'undefined') {
            LogFatalError('ApplePay OnAuthorized callback has not been provided');
            return false;
        }
        options.OnAuthorized();
    };

    OverlayOn('body', false);
    
    funcWithCallback(function () {
        Ajax.POST('Checkout/CheckOrders', {
            success: function (data) {
                OverlayOff();
                if (data.Success) {
                    session.begin();
                } else  {
                    Adyen.resolveResult(data);
                }
            },
            error: function () {
                OverlayOff();
            }
        });
    });
}

function PayWithApple(options, elem, funcWithCallback) {
    if (!options || !options.TotalPrice) {
        LogWarning('[main.checkout].[PayWithApple] undefined TotalPrice! options: ' + JSON.stringify(options) + ' \nStackTrace: ' + JSON.stringify(new Error().stack));
    }

    var request = {
        countryCode: window.CountryCode,
        currencyCode: window.Currency,
        supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
        merchantCapabilities: ['supports3DS'],
        total: {
            label: window.Brand,
            amount: options.TotalPrice.toString()
        },
    };

    //Version 4 added support for new supported networks, if not available then fallback to 1
    var version = window.ApplePaySession.supportsVersion(4) === true ? 4 : 1;

    if (version === 4) {
        request.supportedNetworks = request.supportedNetworks.concat(['maestro', 'electron', 'cartesBancaires']);
    }
    var session = new ApplePaySession(version, request);

    session.onvalidatemerchant = function (event) {
        $.post("/Payment/CreateApplePaySession", { hostname: window.location.hostname })
            .done(function (result) {
                if (result.Success) {
                    try {
                        session.completeMerchantValidation(JSON.parse(result.Data));
                    } catch (exception) {
                        LogFatalError("[main.checkout].[PayWithApple] Exception data " + JSON.stringify(exception));
                    }
                } else {
                    session.abort();
                    Adyen.resolveResult(result);
                }
            })
            .fail(function (jqXHR, textStatus) {
                LogFatalError('[main.checkout].[PayWithApple].[onvalidatemerchant] Error on validating ApplePay merchant session. Status: ' + JSON.stringify(textStatus));
                window.location.reload(false);
            });
    };

    session.onpaymentauthorized = function (event) {
        OverlayOn('body', true);
        var token = JSON.stringify(event.payment.token.paymentData);
        $('#applepaytoken').val(token);
        if (typeof options.OnAuthorized === 'undefined') {
            LogFatalError('[main.checkout].[PayWithApple].[onvalidatemerchant] ApplePay OnAuthorized callback has not been provided');
            return false;
        }
        options.OnAuthorized();
    };

    OverlayOn('body', false);

    funcWithCallback(function () {
        Ajax.POST('Checkout/CheckOrders', {
            success: function (data) {
                OverlayOff();
                if (data.Success) {
                    session.begin();
                } else {
                    Adyen.resolveResult(data);
                }
            },
            error: function (data) {
                OverlayOff();
            }
        });
    });
}

function RateCompany(email) {
    $('#rateCompany').click(function () {
        var rateCompany = $('#rateInformation').fadeOut(1000);
        rateCompany.promise().done(function () {
            $.ajax({
                type: "POST",
                url: "/Confirmation/SaveContactApproval",
                data: { email: email }
            });  
            
            $('#rateConfirmation').fadeIn(2000);
        });
    });
}

var AddressValid = {
    translations: {},
    postcode: null,
    input: null,
    container: null,
    searchBtn: null,

    init: function (translations, selector) {
        AddressValid.postcode = $('#tbRecipientPostCode');
        AddressValid.input = typeof selector !== 'undefined' ? $(selector) : $('#tbRecipientSearchQuery');
        AddressValid.container = $('.address-search:not(.fill-panel)');
        AddressValid.searchBtn = $('.address-search-btn');
        AddressValid.input.focusout(function () {
            AddressValid.check(translations);
        });

        AddressValid.input.focus(function () {
            $(this).removeClass('error');
        });
    },

    check: function (translations) {
        AddressValid.translations = translations || {};
        var postcode = AddressValid.postcode.val(); 
        if (AddressValid.input.is(":visible") && (postcode === "" || typeof postcode === 'undefined')) {
            AddressValid.container.addClass('error');
            AddressValid.input.addClass('error');
            AddressValid.searchBtn.html(AddressValid.translations.error);

        } else {
            AddressValid.container.removeClass('error');
            AddressValid.searchBtn.html(AddressValid.translations.info);
        }
    }    
};

function validateRecipientForm(selector) {
    if ($('#tbRecipientAddress1').value == null) {
        ShowRecipientDetailsFields();
        OverlayOff();
    }

    var valid = $(selector).valid(),
        isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent));
    if (!valid && isMobile) {
        $('html, body').animate({
            scrollTop: ($('.has-error').offset().top - 200)
        }, 2000);
    }

    return valid;
};


var DisableDayParts = {
    getTime: function (offset) {
        var d = new Date(),
            utc = d.getTime() + (d.getTimezoneOffset() * 60000),
            localTime = new Date(utc + (3600000 * offset)),
            localTimeHour = localTime.getHours(),
            localTimeMin = localTime.getMinutes();

        return (localTimeHour*100) + localTimeMin;
    },
    morning: function (offset, endTime) {
        var localTime = DisableDayParts.getTime(offset),
            dayOfMonth = Number.parseInt(new Date().getDate()),
            orderDate = $('#tbDeliveryDate').val();

        if (typeof orderDate !== typeof undefined) {
            var orderDay = Number.parseInt(orderDate.split('-')[0]);

            if (localTime > endTime && dayOfMonth === orderDay) {
                $("#ddlDayPart option[value=M]").attr("disabled", "disabled");

                if (!$('body').hasClass('rebranding-layout')) {
                    $("#ddlDayPart").selectpicker('refresh');
                }
            }
        }
    }
};

function LoadAddressSearchFields(displayFieldsClass) {
    var allValid = true;
    var allEmpty= true;
    
    var fields = $('.address-search').find(".form-control");
    for (var i = 0; i < fields.length; i++) {
        var field = $(fields[i]);
        $("form").validate().element(field);
        if(!field.valid()) allValid = false;
        if(field.val().length > 0) allEmpty = false; 
    }
    
    if(allEmpty) {
        $('#fillPanel').removeClass(displayFieldsClass);
        $('.address-bar').addClass('hidden');
    } else if(allValid){
        $('#fillPanel').removeClass(displayFieldsClass);
        $('.address-bar').removeClass('hidden');
    } else {
        $('#fillPanel').addClass(displayFieldsClass);
        $('.address-bar').addClass('hidden');
    }
}

function ValidateSenderDetails() {
    if ($('#tbSenderEMail').length > 0 && $('#tbSenderEMail').val() != "")
        $("form").validate().element("#tbSenderEMail");
    if ($('#tbSenderFirstName').length > 0 && $('#tbSenderFirstName').val() != "")
        $("form").validate().element("#tbSenderFirstName");
    if ($('#tbSenderLastName').length > 0 && $('#tbSenderLastName').val() != "")
        $("form").validate().element("#tbSenderLastName");
    if ($('#tbSenderTelephone').length > 0 && $('#tbSenderTelephone').val() != "")
        $("form").validate().element("#tbSenderTelephone");
}

function getSelectedPaymentMethod() {
    return $('input[name=ChosenPaymentMethod]:checked').val();
}

var PaymentButton = (function () {
    var OPTIONS = document.getElementsByName('ChosenPaymentMethod'),
        TRANSLATION = '';

    var changeContent = function (value) {
        var PAYMENT_BUTTON = document.getElementById('btnGoToPayment');
        switch (value) {
            case 'PayPal':
                PAYMENT_BUTTON.innerHTML = '<span class="inline-block checkout-btn-payment-text">Continue with</span><span class="inline-block checkout-btn-payment-icon"><img class="img-responsive checkout-btn-payment-image" src="/Content/PaymentIcons/pay-pal.svg"></span>';
                PAYMENT_BUTTON.classList.add('checkout-btn-payment');
                break;
            case 'Adyen_applePay':
                PAYMENT_BUTTON.innerHTML = '<span class="inline-block checkout-btn-payment-text checkout-btn-payment-text-apple">Continue with</span><span class="inline-block checkout-btn-payment-icon checkout-btn-payment-icon-apple"><img class="img-responsive checkout-btn-payment-image checkout-btn-payment-image-apple" src="/Content/PaymentIcons/apple-pay.svg"></span>';
                PAYMENT_BUTTON.classList.add('checkout-btn-payment');
                break;
            default:
                PAYMENT_BUTTON.innerHTML = TRANSLATION;
                PAYMENT_BUTTON.classList.remove('checkout-btn-payment');
        }
    };

    var handleChange = function (e) {
        var target = e.target;
        changeContent(target.value);
    };

    var bindEvents = function (elem) {
        elem.addEventListener('change', handleChange);
    };

    var init = function (textBtn) {
        TRANSLATION = textBtn;
        Array.prototype.forEach.call(OPTIONS, function (element) {

            if (element.checked) {
                changeContent(element.value);
            }

            bindEvents(element);
        });
    };

    return {
        init: init
    };

})();

//============== EMPTY CART ANIMATION ==============
function EmptyCartHoverToggle() {
    if ($(".emptycart") !== 0) {
        $(".emptycart p a").mouseenter(function () {
            var img = $(".emptycart").find("img");
            var temp = $(img).attr("src");
            $(img).attr("src", $(img).attr("srcsecondary"));
            $(img).attr("srcsecondary", temp);
        });
        $(".emptycart p a").mouseleave(function () {
            var img = $(".emptycart").find("img");
            var temp = $(img).attr("srcsecondary");
            $(img).attr("srcsecondary", $(img).attr("src"));
            $(img).attr("src", temp);
        });
    }
}

function InitCharsLeftRebranding(direction) {
    var labels = $(".chars-left");
    labels.each(function () {
        var textarea = $(this).parents('.form-group').find("textarea, input[type='text']");
        var charlimit = parseInt(textarea.attr("data-val-length-max"));
        var activeLbl = textarea.parent().find(".chars-left");
        var inputLenght = textarea.val().length;
        charUpdate(activeLbl, charlimit, inputLenght, direction);
        $(textarea).bind('input propertychange', function (event) {
            inputLenght = textarea.val().length;
            charUpdate(activeLbl, charlimit, inputLenght, direction);
        });
    });
}

function InitCharsLeft(direction) {
    var labels = $(".chars-left");
    labels.each(function () {
        var textarea = $(this).parent().find("textarea, input[type='text']");
        var charlimit = parseInt(textarea.attr("data-val-length-max"));
        var activeLbl = textarea.parent().find(".chars-left");
        var inputLenght = textarea.val().length;
        charUpdate(activeLbl, charlimit, inputLenght, direction);
        $(textarea).bind('input propertychange', function (event) {
            inputLenght = textarea.val().length;
            charUpdate(activeLbl, charlimit, inputLenght, direction);
        });
    });
}

function charUpdate(_label, _charlimit, _lenght, direction) {
    if (direction === 0) {
        _label.text(_charlimit - _lenght);
    }
    else {
        _label.text(_lenght + "/" + _charlimit);
    }
    if (_lenght > _charlimit)
        _label.addDistinctClass("exceeded");
    else
        _label.removeClass("exceeded");
}

function BindRibbonWarning(message, hfId, timeout) {
    if (typeof $("#" + hfId) !== "undefined" && $("#" + hfId).val() === "False")
        ShowInfoTooltip(message, "danger", timeout);
}

function SearchInKlarnaByPersonalNumber(queryTextBox, callback) {
    CallController('Checkout', 'GetKlarnaPersonSearchResult', { personalNo: $(queryTextBox).val() }, callback, null);
}

function ChangeOrderPreview(dropdown, partsToReload) {
    var selected = $(dropdown).find("option:selected");
    var callback = function () {
        ChangeBasketPreview({
            orderKey: selected.data("orderkey"),
            pageUpdatePanel: selected.data("pageupdatepanel"),
            PartsToReload: partsToReload
        },
            '#' + selected.data("pageupdatepanel"),
            true);
    };
    SaveOrder(callback);
}

var OptionStorage = {
    getField: function () {
        var selector = localStorage.getItem('fieldToInit');
        if (!!selector) {
            $('#' + selector).focus();
            localStorage.removeItem('fieldToInit');
        }
    },
    setField: function (value) {
        localStorage.setItem('fieldToInit', value);
    }
};


(function ($) {
    $.AddressSearch = function (elem, options, translation) {
        var _IsIOS = (/iPhone|iPad|iPod/i.test(navigator.userAgent));
        var _Response = null;
        var _Open = function (event, ui) {
            if (_IsIOS) {
                $('.ui-autocomplete').off('menufocus hover mouseover');
            }
            if (options.matchInputWidth)
                $(options.resultListSelector).outerWidth($(elem).outerWidth());
            if (options.limitLength) {
                var _height = $($(options.resultListSelector).children()[0]).outerHeight() * 10 + 11;
                $(options.resultListSelector).css("max-height", _height + "px");
                $(options.resultListSelector).css("overflow-x", "auto");
                $(options.resultListSelector).addClass('address-search-list');
            }

            if ($('.address-search-list').eq(0).find('.show-recipient-fields').length === 0 && typeof translation !== 'undefined') {
                $('.address-search-list').eq(0).append(
                    '<li class="ui-menu-item show-recipient-fields" onclick="ShowRecipientDetailsFields()" aria-label="' + translation + '">' +
                    translation +
                    '</li>');
            }

        };
        var _Focus = function (event, ui) {
            if (options.preventDefaults)
                event.preventDefault();
        };

        var _Source = function (request, response) {
            if (typeof response !== "undefined")
                if (response !== null)
                    _Response = response;

            var callback = function (data) {
                var searchResults = _PrepareResultList(data);
                if (typeof _Response !== "undefined") {
                    if (_Response !== null)
                        _Response(searchResults);
                }
                else {
                    response(searchResults);
                }
            };

            CallController("Checkout", "GetAddressSearchSuggestions", { query: elem.val(), container: "" }, callback, null);
        };

        var _Hide = true;
        var _Select = function (event, ui) {
            if (typeof ui === 'undefined' || typeof ui.item === 'undefined') {
                if (options.preventDefaults)
                    event.preventDefault();
                return;
            }
            if (ui.item.canStepIn) {
                _Hide = false;
                var callback = function (data) {
                    data = _PrepareResultList(data);
                    $(elem).autocomplete("option", { source: data, minLength: 0 });
                    $(elem).autocomplete("search", "");
                    _Hide = true;
                    $(elem).autocomplete("option", { source: _Source, minLength: options.minLength });
                };
                CallController("Checkout", "GetAddressSearchSuggestions", { query: elem.val(), container: ui.item.value }, callback, null);
            }
            else {
                _Hide = true;
                $(elem).autocomplete("option", { source: _Source, minLength: options.minLength });
                var pageType = $("input[name = hfpageTypeForSearch]").val();
                if (pageType === "MyAccount") {
                    UpdateContactDetails({ addressReference: ui.item.value, pageType: pageType }, '#addressSearchResultUpdatePanel', true);
                }
                else {
                    UpdateRecipientDetails({
                        addressReference: ui.item.value,
                        pageType: pageType,
                        addressBar: options.addressBar
                    },
                        '#addressSearchResultUpdatePanel',
                        true);
                }
            }
            if (options.preventDefaults)
                event.preventDefault();
        };

        var _Result = function (label, value, canStepIn) {
            this.label = label;
            this.value = value;
            this.canStepIn = canStepIn;
        };

        var _PrepareResultList = function (data) {
            var _searchResults = [];
            var index = 0;
            $.each(data, function (i, item) {
                _searchResults[index++] = new _Result(item.PartialAddress, item.Reference, item.CanStepIn);
            });
            return _searchResults;
        };

        elem.autocomplete({
            minLength: options.minLength,
            select: _Select,
            source: _Source,
            focus: _Focus,
            open: _Open,
            close: function (event, ui) {
                if (!_Hide && !$(options.resultListSelector).is(":visible")) {
                    $(options.resultListSelector).show();
                }
            },
            create: function () {
                $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
                    var _class = item.canStepIn ? "group ui-menu-item" : "ui-menu-item";
                    return $('<li class="' + _class + '">')
                        .append(item.label)
                        .appendTo(ul);
                };
            }
        });

        elem.attr("autocomplete", "new-password");
    };

    $.fn.open = function () {
        this.autocomplete('search');
        this.focus();
    };

    // Default options
    $.AddressSearch.defaults = {
        'minLength': 2,
        'resultListSelector': '.ui-autocomplete',
        'preventDefaults': true,
        'matchInputWidth': false,
        'limitLength': true
    };

    $.fn.addressSearch = function (translation, options) {
        options = $.extend({}, $.AddressSearch.defaults, options);
        return this.each(function () {
            new $.AddressSearch($(this), options, translation);
        });
    };
})(jQuery);

function SaveWholeCheckout(showFields, callback) {
    if (showFields)
        ShowRecipientDetailsFields();

    var orderSaved = function () {
        SaveBilling(callback || function () { });
    };

    SaveOrder(orderSaved);
}


//============== SAVE BILLING TO TEMPDATA ==============

function SaveBilling(callback) {

    var callback = callback || function () {
        return true;
    };

    // Only when sender partial exist
    var choosenPhoneType = $('input[name="Sender.ChoosenPhoneType"]:checked');
    if (choosenPhoneType.length > 0)
        choosenPhoneType = $('input[name="Sender.ChoosenPhoneType"]:checked').val();
    else if ($("#Sender_ChoosenPhoneType") !== undefined)
        choosenPhoneType = $("#Sender_ChoosenPhoneType").val();
    else
        choosenPhoneType = null;

    if ($('#tbSenderFirstName').val() !== undefined) {
        var args = {
            Title: $('#hiddenTitleId').val(),
            TitleID: $('#ddlTitles').val(),
            FirstName: $('#tbSenderFirstName').val(),
            LastName: $('#tbSenderLastName').val(),
            PostCode: $('#tbSenderPostCode').val(),
            Address1: $('#tbSenderAddress1').val(),
            Address2: $('#tbSenderAddress2').val(),
            HouseNr: $('#tbSenderHouseNr').val(),
            City: $('#tbSenderCity').val(),
            County: $('#tbSenderCounty').val(),
            Country: $('#ddlCountries').val(),

            EMail: $('#tbSenderEMail').val(),
            SendNewsletter: $('#cbSendNewsletter').prop('checked'),
            SendSmsNews: $('#cbSendSmsNews').prop('checked'),
            DontSendNewsletter: $('#cbDontSendNewsletter').prop('checked'),
            RewardNumber: $('#tbRewardNumber').val(),
            PersonalNumber: $('#tbPersonalNumber').val(),
            BirthDate: $('#tbSenderBirthDate').val(),
            HouseNrSuffix: $('#tbHouseNrSuffix').val(),
            Gender: $('#ddlGenders').val(),

            ChoosenPhoneType: choosenPhoneType,
            Telephone: $('#tbSenderTelephone').val(),
            Telephone2: $('#tbSenderTelephone2').val(),

            //corp
            Company: $('#tbSenderCompany').val(),
            TaxIdentityNumber: $('#tbSenderTaxIdenfityNumber').val(),
            CostCenter: $('#tbSenderCostCenter').val(),
            InvoiceCreditCheckDone: $('#tbInvoiceCheckDone').val(),
            AllowInvoice: $('#tbAllowInvoice').val()
        };

        CallController("Checkout", "SaveSenderDataTR", args,
            callback, null);
    } else {
        callback();
    }
}

//============== SAVE ORDER TO SESSION ==============
function SaveOrderAndRedirect(redirectUrl) {
    var callback = function () {
        window.location.href = redirectUrl;
    };

    SaveOrder(callback);
}

var Option = function (tab) {
    var Fields = { 'tbRecipientFirstName': tab[0], 'tbDeliveryCardText': tab[1], 'tbDeliveryDate': $('#tbDeliveryDate').val(), 'tbRecipientLastName': ' ' };

    var OptionManager = {
        optionSelector: '',
        init: function () {
            var elem = $(this.optionSelector).find('.edit');
            this.setDate();

            elem.click(function () {
                var fieldToEdit = $(this).data('checkout-option');
                var elem = $('#' + fieldToEdit);
                Field.setTooltip(fieldToEdit);
                elem.focus();
                Field.edit(fieldToEdit);
            });
        },
        setProductSelector: function (orderKey) {
            this.optionSelector = '#checkoutOptions-' + orderKey;
        },
        setDate: function () {
            $(this.optionSelector).find('.edit[data-checkout-option="tbDeliveryDate"]')
                .prev().html($('#tbDeliveryDate').val());
        },
        update: function (value, option) {
            if (!!value && option) {
                $(this.optionSelector).find('.edit[data-checkout-option=' + option + ']')
                    .prev().html(value);
            }
        },
        changeState: function (fieldSelector, fieldValue, defaultValue) {
            if (fieldValue !== null) {
                if (fieldValue.length === 0) {
                    $(this.optionSelector).find('.edit[data-checkout-option=' + fieldSelector + ']').html(tab[3]);
                    this.update(defaultValue, fieldSelector);
                }
                else {
                    $(this.optionSelector).find('.edit[data-checkout-option=' + fieldSelector + ']').html(tab[2]);
                }
            }
        },
        getRecipientData: function (orderKey) {
            $.ajax({
                url: "/Checkout/GetSerializedRecipient",
                data: { orderKey: orderKey },
                type: 'POST'
            })
                .done(function (recipient) {
                    for (var recipientProp in recipient) {
                        switch (recipientProp) {
                            case 'FirstName':
                                OptionManager.update(recipient[recipientProp], 'tbRecipientFirstName');
                                OptionManager.changeState('tbRecipientFirstName', recipient[recipientProp], Fields['tbRecipientFirstName']);
                                break;
                            case 'CardText':
                                OptionManager.update(recipient[recipientProp], 'tbDeliveryCardText');
                                OptionManager.changeState('tbDeliveryCardText', recipient[recipientProp], Fields['tbDeliveryCardText']);
                                break;
                            case 'DeliveryDate':
                                OptionManager.update(recipient[recipientProp], 'tbDeliveryDate');
                                OptionManager.changeState('tbDeliveryDate', recipient[recipientProp], Fields['tbDeliveryDate']);
                                break;
                        }
                    }
                });
        },
        changeBasketPreview: function (orderKey) {
            $(this.optionSelector).find('.edit').click(function () {
                SaveOrder(function () {
                    ChangeBasketPreview({ orderKey: orderKey, pageUpdatePanel: 'cartPreviewUpdatePanel' }, '#cartPreviewUpdatePanel');
                });
            });
        }
    };

    var Field = {
        init: function () {
            $.each(Fields, function (elem, defaultValue) {
                var elemValue = $('#' + elem).val();
                OptionManager.update(elemValue, elem);
                OptionManager.changeState(elem, elemValue, Fields[defaultValue]);
                Field.edit(elem);
            });
        },
        edit: function (elementToEdit) {
            var elem = $('#' + elementToEdit);

            elem.focusout(function () {
                SaveOrder();
                OptionManager.update(elem.val(), elementToEdit);
                OptionManager.changeState(elementToEdit, elem.val(), Fields[elementToEdit]);
                $('#cardTextOption').readMore(30, '...', false, true);
            });
        },
        setTooltip: function (elementToEdit) {
            var elem = $('#' + elementToEdit);

            elem.tooltip({
                delay: 500,
                placement: "top",
                title: tab[4],
                trigger: "manual"
            });

            elem.tooltip('show');
            setTimeout(function () {
                elem.tooltip('hide');
            }, 2000);
        }
    };

    var Helper = {
        getEditedProductOrderKey: function () {
            return $('#OrderKey').val();
        },
        checkThatProductIsEdited: function (orderKey) {
            var currentProductOrderKey = this.getEditedProductOrderKey();
            if (currentProductOrderKey === orderKey) return true;

            return false;
        }
    };

    return {
        init: function (orderKey) {
            OptionManager.setProductSelector(orderKey);
            OptionManager.getRecipientData(orderKey);

            if (Helper.checkThatProductIsEdited(orderKey)) { //we check here that product is remaining
                OptionManager.init();
                Field.init();
            } else {
                OptionManager.changeBasketPreview(orderKey);
            }
        }
    };
};

function SaveOrder(callback) {
    var callback = callback || function () {
        return true;
    };

    // Only when details and recipient partial exist
    if ($('#tbOrderKey').val() !== undefined) {
        var _Recipient = {
            TitleID: $('#ddlTitle').val(),
            FirstName: $('#tbRecipientFirstName').val(),
            LastName: $('#tbRecipientLastName').val(),
            PostCode: $('#tbRecipientPostCode').val(),
            Address1: $('#tbRecipientAddress1').val(),
            Address2: $('#tbRecipientAddress2').val(),
            City: $('#tbRecipientCity').val(),
            County: $('#tbRecipientCounty').val(),
            HouseNr: $('#tbRecipientHouseNr').val(),
            HouseNrSuffix: $('#tbRecipientHouseNrSuffix').val(),
            CountryISO: $('#hfRecipientCountryISO').val(),
            ValidatePostCode: $('#hfRecipientValidatePostCode').val(),
            Telephone: $('#tbRecipientTelephone').val() ? $('#tbRecipientTelephone').val().replace(/\s/g, '') : null,
            FuneralDirector: $('#tbFuneralDirector').val(),
            ChurchName: $('#tbChurch').val(),
            IsBoxOrder: $('#tbIsBoxOrder').val(),
            ProductGroupCode: $('#hfProductGroupCode').val(),
            CountryId: $('#hfCountryId').val(),
            MobilePhone: $('#tbRecipientTelephone2').val(),
            Company: $('#tbRecipientCompanyName').val()
        };

        var _DeliveryDetails = {
            DeliveryDateUniversal: $("#hfDeliveryDate").val(),
            DeliveryTimeForm: $('#ddlChooseTime').val(),
            OccasionId: $('#ddlOccasion').val(),
            CardText: $('#tbDeliveryCardText').val(),
            InstructionsToFlorist: $('#tbDeliveryInstructionsToFlorist').val(),
            OptionNeighbour: $('#cbNeighbour').prop('checked'),
            OptionDoor: $('#cbDoor').prop('checked'),
            OptionCallRecipient: $('#cbCallRecipient').prop('checked'),
            TextOnRibbon: $('#tbDeliveryRibbonText').val(),
            PracticalInformation: $('#ddlDayPart').val()
        };
        if ("Checkout".indexOf("Ext") > -1) {
            _DeliveryDetails.DeliveryDate = new Date($("[id$='DeliveryDate']").val());
        }
        else {
            _DeliveryDetails.DeliveryDateUniversal = $("#hfDeliveryDate").val();
        }

        var args;
        if ($('#tbIsFuneral').val() === "True") {
            args = {
                FuneralRecipient: _Recipient,
                FuneralDeliveryDetails: _DeliveryDetails,
                CountryName: $('#tbCountryName').val(),
                OrderKey: $('#tbOrderKey').val(),
                IsFuneral: true
            };
        }
        else {
            args = {
                Recipient: _Recipient,
                DeliveryDetails: _DeliveryDetails,
                CountryName: $('#tbCountryName').val(),
                OrderKey: $('#tbOrderKey').val(),
                IsFuneral: false,
                CountryId: $('#hfCountryId').val()
            };
        }

        CallController("Checkout", "SaveOrderDataTR", args, callback, null);
    } else {
        callback();
    }
};
