/* Minification failed. Returning unminified contents.
(11414,108-109): run-time error JS1195: Expected expression: ?
(12486,1-6): run-time error JS1195: Expected expression: class
(12487,28-29): run-time error JS1004: Expected ';': {
(12515,32-33): run-time error JS1004: Expected ';': {
(12528,32-33): run-time error JS1004: Expected ';': {
(12532,40-41): run-time error JS1004: Expected ';': {
(12543,36-37): run-time error JS1004: Expected ';': {
(12556,22-23): run-time error JS1004: Expected ';': {
(12593,20-21): run-time error JS1004: Expected ';': {
(12596,1-2): run-time error JS1002: Syntax error: }
(12602,31-32): run-time error JS1004: Expected ';': {
(12637,2-3): run-time error JS1195: Expected expression: )
(12639,31-32): run-time error JS1004: Expected ';': {
(12934,2-3): run-time error JS1195: Expected expression: )
(12936,31-32): run-time error JS1004: Expected ';': {
(13099,2-3): run-time error JS1195: Expected expression: )
(13101,31-32): run-time error JS1004: Expected ';': {
(13117,2-3): run-time error JS1195: Expected expression: )
(13119,30-31): run-time error JS1004: Expected ';': {
(13135,2-3): run-time error JS1195: Expected expression: )
(13136,30-31): run-time error JS1004: Expected ';': {
(13153,2-3): run-time error JS1195: Expected expression: )
(13154,31-32): run-time error JS1004: Expected ';': {
(13401,2-3): run-time error JS1195: Expected expression: )
(13401,4-10): run-time error JS1197: Too many errors. The file might not be a JavaScript file: window
 */
/* Minification failed. Returning unminified contents.
(11387,108-109): run-time error JS1195: Expected expression: ?
(12459,1-6): run-time error JS1195: Expected expression: class
(12460,28-29): run-time error JS1004: Expected ';': {
(12488,32-33): run-time error JS1004: Expected ';': {
(12501,32-33): run-time error JS1004: Expected ';': {
(12505,40-41): run-time error JS1004: Expected ';': {
(12516,36-37): run-time error JS1004: Expected ';': {
(12529,22-23): run-time error JS1004: Expected ';': {
(12566,20-21): run-time error JS1004: Expected ';': {
(12569,1-2): run-time error JS1002: Syntax error: }
(12575,31-32): run-time error JS1004: Expected ';': {
(12610,2-3): run-time error JS1195: Expected expression: )
(12612,31-32): run-time error JS1004: Expected ';': {
(12907,2-3): run-time error JS1195: Expected expression: )
(12909,31-32): run-time error JS1004: Expected ';': {
(13072,2-3): run-time error JS1195: Expected expression: )
(13074,31-32): run-time error JS1004: Expected ';': {
(13090,2-3): run-time error JS1195: Expected expression: )
(13092,30-31): run-time error JS1004: Expected ';': {
(13108,2-3): run-time error JS1195: Expected expression: )
(13109,30-31): run-time error JS1004: Expected ';': {
(13126,2-3): run-time error JS1195: Expected expression: )
(13127,31-32): run-time error JS1004: Expected ';': {
(13374,2-3): run-time error JS1195: Expected expression: )
(13374,4-10): run-time error JS1197: Too many errors. The file might not be a JavaScript file: window
 */
/*! jQuery UI - v1.13.2 - 2022-07-14
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-patch.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

!function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(V){"use strict";V.ui=V.ui||{};V.ui.version="1.13.2";var n,i=0,a=Array.prototype.hasOwnProperty,r=Array.prototype.slice;V.cleanData=(n=V.cleanData,function(t){for(var e,i,s=0;null!=(i=t[s]);s++)(e=V._data(i,"events"))&&e.remove&&V(i).triggerHandler("remove");n(t)}),V.widget=function(t,i,e){var s,n,o,a={},r=t.split(".")[0],l=r+"-"+(t=t.split(".")[1]);return e||(e=i,i=V.Widget),Array.isArray(e)&&(e=V.extend.apply(null,[{}].concat(e))),V.expr.pseudos[l.toLowerCase()]=function(t){return!!V.data(t,l)},V[r]=V[r]||{},s=V[r][t],n=V[r][t]=function(t,e){if(!this||!this._createWidget)return new n(t,e);arguments.length&&this._createWidget(t,e)},V.extend(n,s,{version:e.version,_proto:V.extend({},e),_childConstructors:[]}),(o=new i).options=V.widget.extend({},o.options),V.each(e,function(e,s){function n(){return i.prototype[e].apply(this,arguments)}function o(t){return i.prototype[e].apply(this,t)}a[e]="function"==typeof s?function(){var t,e=this._super,i=this._superApply;return this._super=n,this._superApply=o,t=s.apply(this,arguments),this._super=e,this._superApply=i,t}:s}),n.prototype=V.widget.extend(o,{widgetEventPrefix:s&&o.widgetEventPrefix||t},a,{constructor:n,namespace:r,widgetName:t,widgetFullName:l}),s?(V.each(s._childConstructors,function(t,e){var i=e.prototype;V.widget(i.namespace+"."+i.widgetName,n,e._proto)}),delete s._childConstructors):i._childConstructors.push(n),V.widget.bridge(t,n),n},V.widget.extend=function(t){for(var e,i,s=r.call(arguments,1),n=0,o=s.length;n<o;n++)for(e in s[n])i=s[n][e],a.call(s[n],e)&&void 0!==i&&(V.isPlainObject(i)?t[e]=V.isPlainObject(t[e])?V.widget.extend({},t[e],i):V.widget.extend({},i):t[e]=i);return t},V.widget.bridge=function(o,e){var a=e.prototype.widgetFullName||o;V.fn[o]=function(i){var t="string"==typeof i,s=r.call(arguments,1),n=this;return t?this.length||"instance"!==i?this.each(function(){var t,e=V.data(this,a);return"instance"===i?(n=e,!1):e?"function"!=typeof e[i]||"_"===i.charAt(0)?V.error("no such method '"+i+"' for "+o+" widget instance"):(t=e[i].apply(e,s))!==e&&void 0!==t?(n=t&&t.jquery?n.pushStack(t.get()):t,!1):void 0:V.error("cannot call methods on "+o+" prior to initialization; attempted to call method '"+i+"'")}):n=void 0:(s.length&&(i=V.widget.extend.apply(null,[i].concat(s))),this.each(function(){var t=V.data(this,a);t?(t.option(i||{}),t._init&&t._init()):V.data(this,a,new e(i,this))})),n}},V.Widget=function(){},V.Widget._childConstructors=[],V.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=V(e||this.defaultElement||this)[0],this.element=V(e),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=V(),this.hoverable=V(),this.focusable=V(),this.classesElementLookup={},e!==this&&(V.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=V(e.style?e.ownerDocument:e.document||e),this.window=V(this.document[0].defaultView||this.document[0].parentWindow)),this.options=V.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:V.noop,_create:V.noop,_init:V.noop,destroy:function(){var i=this;this._destroy(),V.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:V.noop,widget:function(){return this.element},option:function(t,e){var i,s,n,o=t;if(0===arguments.length)return V.widget.extend({},this.options);if("string"==typeof t)if(o={},t=(i=t.split(".")).shift(),i.length){for(s=o[t]=V.widget.extend({},this.options[t]),n=0;n<i.length-1;n++)s[i[n]]=s[i[n]]||{},s=s[i[n]];if(t=i.pop(),1===arguments.length)return void 0===s[t]?null:s[t];s[t]=e}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=e}return this._setOptions(o),this},_setOptions:function(t){for(var e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(t){var e,i,s;for(e in t)s=this.classesElementLookup[e],t[e]!==this.options.classes[e]&&s&&s.length&&(i=V(s.get()),this._removeClass(s,e),i.addClass(this._classes({element:i,keys:e,classes:t,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(n){var o=[],a=this;function t(t,e){for(var i,s=0;s<t.length;s++)i=a.classesElementLookup[t[s]]||V(),i=n.add?(function(){var i=[];n.element.each(function(t,e){V.map(a.classesElementLookup,function(t){return t}).some(function(t){return t.is(e)})||i.push(e)}),a._on(V(i),{remove:"_untrackClassesElement"})}(),V(V.uniqueSort(i.get().concat(n.element.get())))):V(i.not(n.element).get()),a.classesElementLookup[t[s]]=i,o.push(t[s]),e&&n.classes[t[s]]&&o.push(n.classes[t[s]])}return(n=V.extend({element:this.element,classes:this.options.classes||{}},n)).keys&&t(n.keys.match(/\S+/g)||[],!0),n.extra&&t(n.extra.match(/\S+/g)||[]),o.join(" ")},_untrackClassesElement:function(i){var s=this;V.each(s.classesElementLookup,function(t,e){-1!==V.inArray(i.target,e)&&(s.classesElementLookup[t]=V(e.not(i.target).get()))}),this._off(V(i.target))},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){var n="string"==typeof t||null===t,i={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s="boolean"==typeof s?s:i};return i.element.toggleClass(this._classes(i),s),this},_on:function(n,o,t){var a,r=this;"boolean"!=typeof n&&(t=o,o=n,n=!1),t?(o=a=V(o),this.bindings=this.bindings.add(o)):(t=o,o=this.element,a=this.widget()),V.each(t,function(t,e){function i(){if(n||!0!==r.options.disabled&&!V(this).hasClass("ui-state-disabled"))return("string"==typeof e?r[e]:e).apply(r,arguments)}"string"!=typeof e&&(i.guid=e.guid=e.guid||i.guid||V.guid++);var s=t.match(/^([\w:-]*)\s*(.*)$/),t=s[1]+r.eventNamespace,s=s[2];s?a.on(t,s,i):o.on(t,i)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.off(e),this.bindings=V(this.bindings.not(t).get()),this.focusable=V(this.focusable.not(t).get()),this.hoverable=V(this.hoverable.not(t).get())},_delay:function(t,e){var i=this;return setTimeout(function(){return("string"==typeof t?i[t]:t).apply(i,arguments)},e||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){this._addClass(V(t.currentTarget),null,"ui-state-hover")},mouseleave:function(t){this._removeClass(V(t.currentTarget),null,"ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){this._addClass(V(t.currentTarget),null,"ui-state-focus")},focusout:function(t){this._removeClass(V(t.currentTarget),null,"ui-state-focus")}})},_trigger:function(t,e,i){var s,n,o=this.options[t];if(i=i||{},(e=V.Event(e)).type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),e.target=this.element[0],n=e.originalEvent)for(s in n)s in e||(e[s]=n[s]);return this.element.trigger(e,i),!("function"==typeof o&&!1===o.apply(this.element[0],[e].concat(i))||e.isDefaultPrevented())}},V.each({show:"fadeIn",hide:"fadeOut"},function(o,a){V.Widget.prototype["_"+o]=function(e,t,i){var s,n=(t="string"==typeof t?{effect:t}:t)?!0!==t&&"number"!=typeof t&&t.effect||a:o;"number"==typeof(t=t||{})?t={duration:t}:!0===t&&(t={}),s=!V.isEmptyObject(t),t.complete=i,t.delay&&e.delay(t.delay),s&&V.effects&&V.effects.effect[n]?e[o](t):n!==o&&e[n]?e[n](t.duration,t.easing,i):e.queue(function(t){V(this)[o](),i&&i.call(e[0]),t()})}});var s,x,k,o,l,h,c,u,C;V.widget;function D(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function I(t,e){return parseInt(V.css(t,e),10)||0}function T(t){return null!=t&&t===t.window}x=Math.max,k=Math.abs,o=/left|center|right/,l=/top|center|bottom/,h=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,C=V.fn.position,V.position={scrollbarWidth:function(){if(void 0!==s)return s;var t,e=V("<div style='display:block;position:absolute;width:200px;height:200px;overflow:hidden;'><div style='height:300px;width:auto;'></div></div>"),i=e.children()[0];return V("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),s=t-i},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.width<t.element[0].scrollWidth;return{width:"scroll"===i||"auto"===i&&t.height<t.element[0].scrollHeight?V.position.scrollbarWidth():0,height:e?V.position.scrollbarWidth():0}},getWithinInfo:function(t){var e=V(t||window),i=T(e[0]),s=!!e[0]&&9===e[0].nodeType;return{element:e,isWindow:i,isDocument:s,offset:!i&&!s?V(t).offset():{left:0,top:0},scrollLeft:e.scrollLeft(),scrollTop:e.scrollTop(),width:e.outerWidth(),height:e.outerHeight()}}},V.fn.position=function(u){if(!u||!u.of)return C.apply(this,arguments);var d,p,f,g,m,t,_="string"==typeof(u=V.extend({},u)).of?V(document).find(u.of):V(u.of),v=V.position.getWithinInfo(u.within),b=V.position.getScrollInfo(v),y=(u.collision||"flip").split(" "),w={},e=9===(t=(e=_)[0]).nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:T(t)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:t.preventDefault?{width:0,height:0,offset:{top:t.pageY,left:t.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()};return _[0].preventDefault&&(u.at="left top"),p=e.width,f=e.height,m=V.extend({},g=e.offset),V.each(["my","at"],function(){var t,e,i=(u[this]||"").split(" ");(i=1===i.length?o.test(i[0])?i.concat(["center"]):l.test(i[0])?["center"].concat(i):["center","center"]:i)[0]=o.test(i[0])?i[0]:"center",i[1]=l.test(i[1])?i[1]:"center",t=h.exec(i[0]),e=h.exec(i[1]),w[this]=[t?t[0]:0,e?e[0]:0],u[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===y.length&&(y[1]=y[0]),"right"===u.at[0]?m.left+=p:"center"===u.at[0]&&(m.left+=p/2),"bottom"===u.at[1]?m.top+=f:"center"===u.at[1]&&(m.top+=f/2),d=D(w.at,p,f),m.left+=d[0],m.top+=d[1],this.each(function(){var i,t,a=V(this),r=a.outerWidth(),l=a.outerHeight(),e=I(this,"marginLeft"),s=I(this,"marginTop"),n=r+e+I(this,"marginRight")+b.width,o=l+s+I(this,"marginBottom")+b.height,h=V.extend({},m),c=D(w.my,a.outerWidth(),a.outerHeight());"right"===u.my[0]?h.left-=r:"center"===u.my[0]&&(h.left-=r/2),"bottom"===u.my[1]?h.top-=l:"center"===u.my[1]&&(h.top-=l/2),h.left+=c[0],h.top+=c[1],i={marginLeft:e,marginTop:s},V.each(["left","top"],function(t,e){V.ui.position[y[t]]&&V.ui.position[y[t]][e](h,{targetWidth:p,targetHeight:f,elemWidth:r,elemHeight:l,collisionPosition:i,collisionWidth:n,collisionHeight:o,offset:[d[0]+c[0],d[1]+c[1]],my:u.my,at:u.at,within:v,elem:a})}),u.using&&(t=function(t){var e=g.left-h.left,i=e+p-r,s=g.top-h.top,n=s+f-l,o={target:{element:_,left:g.left,top:g.top,width:p,height:f},element:{element:a,left:h.left,top:h.top,width:r,height:l},horizontal:i<0?"left":0<e?"right":"center",vertical:n<0?"top":0<s?"bottom":"middle"};p<r&&k(e+i)<p&&(o.horizontal="center"),f<l&&k(s+n)<f&&(o.vertical="middle"),x(k(e),k(i))>x(k(s),k(n))?o.important="horizontal":o.important="vertical",u.using.call(this,t,o)}),a.offset(V.extend(h,{using:t}))})},V.ui.position={fit:{left:function(t,e){var i=e.within,s=i.isWindow?i.scrollLeft:i.offset.left,n=i.width,o=t.left-e.collisionPosition.marginLeft,a=s-o,r=o+e.collisionWidth-n-s;e.collisionWidth>n?0<a&&r<=0?(i=t.left+a+e.collisionWidth-n-s,t.left+=a-i):t.left=!(0<r&&a<=0)&&r<a?s+n-e.collisionWidth:s:0<a?t.left+=a:0<r?t.left-=r:t.left=x(t.left-o,t.left)},top:function(t,e){var i=e.within,s=i.isWindow?i.scrollTop:i.offset.top,n=e.within.height,o=t.top-e.collisionPosition.marginTop,a=s-o,r=o+e.collisionHeight-n-s;e.collisionHeight>n?0<a&&r<=0?(i=t.top+a+e.collisionHeight-n-s,t.top+=a-i):t.top=!(0<r&&a<=0)&&r<a?s+n-e.collisionHeight:s:0<a?t.top+=a:0<r?t.top-=r:t.top=x(t.top-o,t.top)}},flip:{left:function(t,e){var i=e.within,s=i.offset.left+i.scrollLeft,n=i.width,o=i.isWindow?i.scrollLeft:i.offset.left,a=t.left-e.collisionPosition.marginLeft,r=a-o,l=a+e.collisionWidth-n-o,h="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,i="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,a=-2*e.offset[0];r<0?((s=t.left+h+i+a+e.collisionWidth-n-s)<0||s<k(r))&&(t.left+=h+i+a):0<l&&(0<(o=t.left-e.collisionPosition.marginLeft+h+i+a-o)||k(o)<l)&&(t.left+=h+i+a)},top:function(t,e){var i=e.within,s=i.offset.top+i.scrollTop,n=i.height,o=i.isWindow?i.scrollTop:i.offset.top,a=t.top-e.collisionPosition.marginTop,r=a-o,l=a+e.collisionHeight-n-o,h="top"===e.my[1]?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,i="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,a=-2*e.offset[1];r<0?((s=t.top+h+i+a+e.collisionHeight-n-s)<0||s<k(r))&&(t.top+=h+i+a):0<l&&(0<(o=t.top-e.collisionPosition.marginTop+h+i+a-o)||k(o)<l)&&(t.top+=h+i+a)}},flipfit:{left:function(){V.ui.position.flip.left.apply(this,arguments),V.ui.position.fit.left.apply(this,arguments)},top:function(){V.ui.position.flip.top.apply(this,arguments),V.ui.position.fit.top.apply(this,arguments)}}};V.ui.position,V.extend(V.expr.pseudos,{data:V.expr.createPseudo?V.expr.createPseudo(function(e){return function(t){return!!V.data(t,e)}}):function(t,e,i){return!!V.data(t,i[3])}}),V.fn.extend({disableSelection:(t="onselectstart"in document.createElement("div")?"selectstart":"mousedown",function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}),enableSelection:function(){return this.off(".ui-disableSelection")}});var t,d=V,p={},e=p.toString,f=/^([\-+])=\s*(\d+\.?\d*)/,g=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16),t[4]?(parseInt(t[4],16)/255).toFixed(2):1]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),t[4]?(parseInt(t[4]+t[4],16)/255).toFixed(2):1]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],m=d.Color=function(t,e,i,s){return new d.Color.fn.parse(t,e,i,s)},_={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"}}}},v={byte:{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},b=m.support={},y=d("<p>")[0],w=d.each;function P(t){return null==t?t+"":"object"==typeof t?p[e.call(t)]||"object":typeof t}function M(t,e,i){var s=v[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:Math.min(s.max,Math.max(0,t)))}function S(s){var n=m(),o=n._rgba=[];return s=s.toLowerCase(),w(g,function(t,e){var i=e.re.exec(s),i=i&&e.parse(i),e=e.space||"rgba";if(i)return i=n[e](i),n[_[e].cache]=i[_[e].cache],o=n._rgba=i._rgba,!1}),o.length?("0,0,0,0"===o.join()&&d.extend(o,B.transparent),n):B[s]}function H(t,e,i){return 6*(i=(i+1)%1)<1?t+(e-t)*i*6:2*i<1?e:3*i<2?t+(e-t)*(2/3-i)*6:t}y.style.cssText="background-color:rgba(1,1,1,.5)",b.rgba=-1<y.style.backgroundColor.indexOf("rgba"),w(_,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),d.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(t,e){p["[object "+e+"]"]=e.toLowerCase()}),(m.fn=d.extend(m.prototype,{parse:function(n,t,e,i){if(void 0===n)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=d(n).css(t),t=void 0);var o=this,s=P(n),a=this._rgba=[];return void 0!==t&&(n=[n,t,e,i],s="array"),"string"===s?this.parse(S(n)||B._default):"array"===s?(w(_.rgba.props,function(t,e){a[e.idx]=M(n[e.idx],e)}),this):"object"===s?(w(_,n instanceof m?function(t,e){n[e.cache]&&(o[e.cache]=n[e.cache].slice())}:function(t,i){var s=i.cache;w(i.props,function(t,e){if(!o[s]&&i.to){if("alpha"===t||null==n[t])return;o[s]=i.to(o._rgba)}o[s][e.idx]=M(n[t],e,!0)}),o[s]&&d.inArray(null,o[s].slice(0,3))<0&&(null==o[s][3]&&(o[s][3]=1),i.from&&(o._rgba=i.from(o[s])))}),this):void 0},is:function(t){var n=m(t),o=!0,a=this;return w(_,function(t,e){var i,s=n[e.cache];return s&&(i=a[e.cache]||e.to&&e.to(a._rgba)||[],w(e.props,function(t,e){if(null!=s[e.idx])return o=s[e.idx]===i[e.idx]})),o}),o},_space:function(){var i=[],s=this;return w(_,function(t,e){s[e.cache]&&i.push(t)}),i.pop()},transition:function(t,a){var e=(h=m(t))._space(),i=_[e],t=0===this.alpha()?m("transparent"):this,r=t[i.cache]||i.to(t._rgba),l=r.slice(),h=h[i.cache];return w(i.props,function(t,e){var i=e.idx,s=r[i],n=h[i],o=v[e.type]||{};null!==n&&(null===s?l[i]=n:(o.mod&&(n-s>o.mod/2?s+=o.mod:s-n>o.mod/2&&(s-=o.mod)),l[i]=M((n-s)*a+s,e)))}),this[e](l)},blend:function(t){if(1===this._rgba[3])return this;var e=this._rgba.slice(),i=e.pop(),s=m(t)._rgba;return m(d.map(e,function(t,e){return(1-i)*s[e]+i*t}))},toRgbaString:function(){var t="rgba(",e=d.map(this._rgba,function(t,e){return null!=t?t:2<e?1:0});return 1===e[3]&&(e.pop(),t="rgb("),t+e.join()+")"},toHslaString:function(){var t="hsla(",e=d.map(this.hsla(),function(t,e){return null==t&&(t=2<e?1:0),t=e&&e<3?Math.round(100*t)+"%":t});return 1===e[3]&&(e.pop(),t="hsl("),t+e.join()+")"},toHexString:function(t){var e=this._rgba.slice(),i=e.pop();return t&&e.push(~~(255*i)),"#"+d.map(e,function(t){return 1===(t=(t||0).toString(16)).length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}})).parse.prototype=m.fn,_.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/255,i=t[1]/255,s=t[2]/255,n=t[3],o=Math.max(e,i,s),a=Math.min(e,i,s),r=o-a,l=o+a,t=.5*l,i=a===o?0:e===o?60*(i-s)/r+360:i===o?60*(s-e)/r+120:60*(e-i)/r+240,l=0==r?0:t<=.5?r/l:r/(2-l);return[Math.round(i)%360,l,t,null==n?1:n]},_.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],t=t[3],i=s<=.5?s*(1+i):s+i-s*i,s=2*s-i;return[Math.round(255*H(s,i,e+1/3)),Math.round(255*H(s,i,e)),Math.round(255*H(s,i,e-1/3)),t]},w(_,function(l,t){var e=t.props,o=t.cache,a=t.to,r=t.from;m.fn[l]=function(t){if(a&&!this[o]&&(this[o]=a(this._rgba)),void 0===t)return this[o].slice();var i=P(t),s="array"===i||"object"===i?t:arguments,n=this[o].slice();return w(e,function(t,e){t=s["object"===i?t:e.idx];null==t&&(t=n[e.idx]),n[e.idx]=M(t,e)}),r?((t=m(r(n)))[o]=n,t):m(n)},w(e,function(a,r){m.fn[a]||(m.fn[a]=function(t){var e,i=P(t),s="alpha"===a?this._hsla?"hsla":"rgba":l,n=this[s](),o=n[r.idx];return"undefined"===i?o:("function"===i&&(i=P(t=t.call(this,o))),null==t&&r.empty?this:("string"===i&&(e=f.exec(t))&&(t=o+parseFloat(e[2])*("+"===e[1]?1:-1)),n[r.idx]=t,this[s](n)))})})}),(m.hook=function(t){t=t.split(" ");w(t,function(t,o){d.cssHooks[o]={set:function(t,e){var i,s,n="";if("transparent"!==e&&("string"!==P(e)||(i=S(e)))){if(e=m(i||e),!b.rgba&&1!==e._rgba[3]){for(s="backgroundColor"===o?t.parentNode:t;(""===n||"transparent"===n)&&s&&s.style;)try{n=d.css(s,"backgroundColor"),s=s.parentNode}catch(t){}e=e.blend(n&&"transparent"!==n?n:"_default")}e=e.toRgbaString()}try{t.style[o]=e}catch(t){}}},d.fx.step[o]=function(t){t.colorInit||(t.start=m(t.elem,o),t.end=m(t.end),t.colorInit=!0),d.cssHooks[o].set(t.elem,t.start.transition(t.end,t.pos))}})})("backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor"),d.cssHooks.borderColor={expand:function(i){var s={};return w(["Top","Right","Bottom","Left"],function(t,e){s["border"+e+"Color"]=i}),s}};var z,A,O,N,E,W,F,L,R,Y,B=d.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"},j="ui-effects-",q="ui-effects-style",K="ui-effects-animated";function U(t){var e,i,s=t.ownerDocument.defaultView?t.ownerDocument.defaultView.getComputedStyle(t,null):t.currentStyle,n={};if(s&&s.length&&s[0]&&s[s[0]])for(i=s.length;i--;)"string"==typeof s[e=s[i]]&&(n[e.replace(/-([\da-z])/gi,function(t,e){return e.toUpperCase()})]=s[e]);else for(e in s)"string"==typeof s[e]&&(n[e]=s[e]);return n}function X(t,e,i,s){return t={effect:t=V.isPlainObject(t)?(e=t).effect:t},"function"==typeof(e=null==e?{}:e)&&(s=e,i=null,e={}),"number"!=typeof e&&!V.fx.speeds[e]||(s=i,i=e,e={}),"function"==typeof i&&(s=i,i=null),e&&V.extend(t,e),i=i||e.duration,t.duration=V.fx.off?0:"number"==typeof i?i:i in V.fx.speeds?V.fx.speeds[i]:V.fx.speeds._default,t.complete=s||e.complete,t}function $(t){return!t||"number"==typeof t||V.fx.speeds[t]||("string"==typeof t&&!V.effects.effect[t]||("function"==typeof t||"object"==typeof t&&!t.effect))}function G(t,e){var i=e.outerWidth(),e=e.outerHeight(),t=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/.exec(t)||["",0,i,e,0];return{top:parseFloat(t[1])||0,right:"auto"===t[2]?i:parseFloat(t[2]),bottom:"auto"===t[3]?e:parseFloat(t[3]),left:parseFloat(t[4])||0}}V.effects={effect:{}},N=["add","remove","toggle"],E={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1},V.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,e){V.fx.step[e]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(d.style(t.elem,e,t.end),t.setAttr=!0)}}),V.fn.addBack||(V.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),V.effects.animateClass=function(n,t,e,i){var o=V.speed(t,e,i);return this.queue(function(){var i=V(this),t=i.attr("class")||"",e=(e=o.children?i.find("*").addBack():i).map(function(){return{el:V(this),start:U(this)}}),s=function(){V.each(N,function(t,e){n[e]&&i[e+"Class"](n[e])})};s(),e=e.map(function(){return this.end=U(this.el[0]),this.diff=function(t,e){var i,s,n={};for(i in e)s=e[i],t[i]!==s&&(E[i]||!V.fx.step[i]&&isNaN(parseFloat(s))||(n[i]=s));return n}(this.start,this.end),this}),i.attr("class",t),e=e.map(function(){var t=this,e=V.Deferred(),i=V.extend({},o,{queue:!1,complete:function(){e.resolve(t)}});return this.el.animate(this.diff,i),e.promise()}),V.when.apply(V,e.get()).done(function(){s(),V.each(arguments,function(){var e=this.el;V.each(this.diff,function(t){e.css(t,"")})}),o.complete.call(i[0])})})},V.fn.extend({addClass:(O=V.fn.addClass,function(t,e,i,s){return e?V.effects.animateClass.call(this,{add:t},e,i,s):O.apply(this,arguments)}),removeClass:(A=V.fn.removeClass,function(t,e,i,s){return 1<arguments.length?V.effects.animateClass.call(this,{remove:t},e,i,s):A.apply(this,arguments)}),toggleClass:(z=V.fn.toggleClass,function(t,e,i,s,n){return"boolean"==typeof e||void 0===e?i?V.effects.animateClass.call(this,e?{add:t}:{remove:t},i,s,n):z.apply(this,arguments):V.effects.animateClass.call(this,{toggle:t},e,i,s)}),switchClass:function(t,e,i,s,n){return V.effects.animateClass.call(this,{add:e,remove:t},i,s,n)}}),V.expr&&V.expr.pseudos&&V.expr.pseudos.animated&&(V.expr.pseudos.animated=(W=V.expr.pseudos.animated,function(t){return!!V(t).data(K)||W(t)})),!1!==V.uiBackCompat&&V.extend(V.effects,{save:function(t,e){for(var i=0,s=e.length;i<s;i++)null!==e[i]&&t.data(j+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;s<n;s++)null!==e[s]&&(i=t.data(j+e[s]),t.css(e[s],i))},setMode:function(t,e){return e="toggle"===e?t.is(":hidden")?"show":"hide":e},createWrapper:function(i){if(i.parent().is(".ui-effects-wrapper"))return i.parent();var s={width:i.outerWidth(!0),height:i.outerHeight(!0),float:i.css("float")},t=V("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e={width:i.width(),height:i.height()},n=document.activeElement;try{n.id}catch(t){n=document.body}return i.wrap(t),i[0]!==n&&!V.contains(i[0],n)||V(n).trigger("focus"),t=i.parent(),"static"===i.css("position")?(t.css({position:"relative"}),i.css({position:"relative"})):(V.extend(s,{position:i.css("position"),zIndex:i.css("z-index")}),V.each(["top","left","bottom","right"],function(t,e){s[e]=i.css(e),isNaN(parseInt(s[e],10))&&(s[e]="auto")}),i.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),i.css(e),t.css(s).show()},removeWrapper:function(t){var e=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),t[0]!==e&&!V.contains(t[0],e)||V(e).trigger("focus")),t}}),V.extend(V.effects,{version:"1.13.2",define:function(t,e,i){return i||(i=e,e="effect"),V.effects.effect[t]=i,V.effects.effect[t].mode=e,i},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,e="vertical"!==i?(e||100)/100:1;return{height:t.height()*e,width:t.width()*s,outerHeight:t.outerHeight()*e,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();1<e&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(q,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(q)||"",t.removeData(q)},mode:function(t,e){t=t.is(":hidden");return"toggle"===e&&(e=t?"show":"hide"),e=(t?"hide"===e:"show"===e)?"none":e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createPlaceholder:function(t){var e,i=t.css("position"),s=t.position();return t.css({marginTop:t.css("marginTop"),marginBottom:t.css("marginBottom"),marginLeft:t.css("marginLeft"),marginRight:t.css("marginRight")}).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()),/^(static|relative)/.test(i)&&(i="absolute",e=V("<"+t[0].nodeName+">").insertAfter(t).css({display:/^(inline|ruby)/.test(t.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:t.css("marginTop"),marginBottom:t.css("marginBottom"),marginLeft:t.css("marginLeft"),marginRight:t.css("marginRight"),float:t.css("float")}).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).addClass("ui-effects-placeholder"),t.data(j+"placeholder",e)),t.css({position:i,left:s.left,top:s.top}),e},removePlaceholder:function(t){var e=j+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(t){V.effects.restoreStyle(t),V.effects.removePlaceholder(t)},setTransition:function(s,t,n,o){return o=o||{},V.each(t,function(t,e){var i=s.cssUnit(e);0<i[0]&&(o[e]=i[0]*n+i[1])}),o}}),V.fn.extend({effect:function(){function t(t){var e=V(this),i=V.effects.mode(e,r)||o;e.data(K,!0),l.push(i),o&&("show"===i||i===o&&"hide"===i)&&e.show(),o&&"none"===i||V.effects.saveStyle(e),"function"==typeof t&&t()}var s=X.apply(this,arguments),n=V.effects.effect[s.effect],o=n.mode,e=s.queue,i=e||"fx",a=s.complete,r=s.mode,l=[];return V.fx.off||!n?r?this[r](s.duration,a):this.each(function(){a&&a.call(this)}):!1===e?this.each(t).each(h):this.queue(i,t).queue(i,h);function h(t){var e=V(this);function i(){"function"==typeof a&&a.call(e[0]),"function"==typeof t&&t()}s.mode=l.shift(),!1===V.uiBackCompat||o?"none"===s.mode?(e[r](),i()):n.call(e[0],s,function(){e.removeData(K),V.effects.cleanUp(e),"hide"===s.mode&&e.hide(),i()}):(e.is(":hidden")?"hide"===r:"show"===r)?(e[r](),i()):n.call(e[0],s,i)}},show:(R=V.fn.show,function(t){if($(t))return R.apply(this,arguments);t=X.apply(this,arguments);return t.mode="show",this.effect.call(this,t)}),hide:(L=V.fn.hide,function(t){if($(t))return L.apply(this,arguments);t=X.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)}),toggle:(F=V.fn.toggle,function(t){if($(t)||"boolean"==typeof t)return F.apply(this,arguments);t=X.apply(this,arguments);return t.mode="toggle",this.effect.call(this,t)}),cssUnit:function(t){var i=this.css(t),s=[];return V.each(["em","px","%","pt"],function(t,e){0<i.indexOf(e)&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):G(this.css("clip"),this)},transfer:function(t,e){var i=V(this),s=V(t.to),n="fixed"===s.css("position"),o=V("body"),a=n?o.scrollTop():0,r=n?o.scrollLeft():0,o=s.offset(),o={top:o.top-a,left:o.left-r,height:s.innerHeight(),width:s.innerWidth()},s=i.offset(),l=V("<div class='ui-effects-transfer'></div>");l.appendTo("body").addClass(t.className).css({top:s.top-a,left:s.left-r,height:i.innerHeight(),width:i.innerWidth(),position:n?"fixed":"absolute"}).animate(o,t.duration,t.easing,function(){l.remove(),"function"==typeof e&&e()})}}),V.fx.step.clip=function(t){t.clipInit||(t.start=V(t.elem).cssClip(),"string"==typeof t.end&&(t.end=G(t.end,t.elem)),t.clipInit=!0),V(t.elem).cssClip({top:t.pos*(t.end.top-t.start.top)+t.start.top,right:t.pos*(t.end.right-t.start.right)+t.start.right,bottom:t.pos*(t.end.bottom-t.start.bottom)+t.start.bottom,left:t.pos*(t.end.left-t.start.left)+t.start.left})},Y={},V.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,t){Y[t]=function(t){return Math.pow(t,e+2)}}),V.extend(Y,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;t<((e=Math.pow(2,--i))-1)/11;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),V.each(Y,function(t,e){V.easing["easeIn"+t]=e,V.easing["easeOut"+t]=function(t){return 1-e(1-t)},V.easing["easeInOut"+t]=function(t){return t<.5?e(2*t)/2:1-e(-2*t+2)/2}});y=V.effects,V.effects.define("blind","hide",function(t,e){var i={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},s=V(this),n=t.direction||"up",o=s.cssClip(),a={clip:V.extend({},o)},r=V.effects.createPlaceholder(s);a.clip[i[n][0]]=a.clip[i[n][1]],"show"===t.mode&&(s.cssClip(a.clip),r&&r.css(V.effects.clipToBox(a)),a.clip=o),r&&r.animate(V.effects.clipToBox(a),t.duration,t.easing),s.animate(a,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("bounce",function(t,e){var i,s,n=V(this),o=t.mode,a="hide"===o,r="show"===o,l=t.direction||"up",h=t.distance,c=t.times||5,o=2*c+(r||a?1:0),u=t.duration/o,d=t.easing,p="up"===l||"down"===l?"top":"left",f="up"===l||"left"===l,g=0,t=n.queue().length;for(V.effects.createPlaceholder(n),l=n.css(p),h=h||n["top"==p?"outerHeight":"outerWidth"]()/3,r&&((s={opacity:1})[p]=l,n.css("opacity",0).css(p,f?2*-h:2*h).animate(s,u,d)),a&&(h/=Math.pow(2,c-1)),(s={})[p]=l;g<c;g++)(i={})[p]=(f?"-=":"+=")+h,n.animate(i,u,d).animate(s,u,d),h=a?2*h:h/2;a&&((i={opacity:0})[p]=(f?"-=":"+=")+h,n.animate(i,u,d)),n.queue(e),V.effects.unshift(n,t,1+o)}),V.effects.define("clip","hide",function(t,e){var i={},s=V(this),n=t.direction||"vertical",o="both"===n,a=o||"horizontal"===n,o=o||"vertical"===n,n=s.cssClip();i.clip={top:o?(n.bottom-n.top)/2:n.top,right:a?(n.right-n.left)/2:n.right,bottom:o?(n.bottom-n.top)/2:n.bottom,left:a?(n.right-n.left)/2:n.left},V.effects.createPlaceholder(s),"show"===t.mode&&(s.cssClip(i.clip),i.clip=n),s.animate(i,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("drop","hide",function(t,e){var i=V(this),s="show"===t.mode,n=t.direction||"left",o="up"===n||"down"===n?"top":"left",a="up"===n||"left"===n?"-=":"+=",r="+="==a?"-=":"+=",l={opacity:0};V.effects.createPlaceholder(i),n=t.distance||i["top"==o?"outerHeight":"outerWidth"](!0)/2,l[o]=a+n,s&&(i.css(l),l[o]=r+n,l.opacity=1),i.animate(l,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("explode","hide",function(t,e){var i,s,n,o,a,r,l=t.pieces?Math.round(Math.sqrt(t.pieces)):3,h=l,c=V(this),u="show"===t.mode,d=c.show().css("visibility","hidden").offset(),p=Math.ceil(c.outerWidth()/h),f=Math.ceil(c.outerHeight()/l),g=[];function m(){g.push(this),g.length===l*h&&(c.css({visibility:"visible"}),V(g).remove(),e())}for(i=0;i<l;i++)for(o=d.top+i*f,r=i-(l-1)/2,s=0;s<h;s++)n=d.left+s*p,a=s-(h-1)/2,c.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-s*p,top:-i*f}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:p,height:f,left:n+(u?a*p:0),top:o+(u?r*f:0),opacity:u?0:1}).animate({left:n+(u?0:a*p),top:o+(u?0:r*f),opacity:u?1:0},t.duration||500,t.easing,m)}),V.effects.define("fade","toggle",function(t,e){var i="show"===t.mode;V(this).css("opacity",i?0:1).animate({opacity:i?1:0},{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("fold","hide",function(e,t){var i=V(this),s=e.mode,n="show"===s,o="hide"===s,a=e.size||15,r=/([0-9]+)%/.exec(a),l=!!e.horizFirst?["right","bottom"]:["bottom","right"],h=e.duration/2,c=V.effects.createPlaceholder(i),u=i.cssClip(),d={clip:V.extend({},u)},p={clip:V.extend({},u)},f=[u[l[0]],u[l[1]]],s=i.queue().length;r&&(a=parseInt(r[1],10)/100*f[o?0:1]),d.clip[l[0]]=a,p.clip[l[0]]=a,p.clip[l[1]]=0,n&&(i.cssClip(p.clip),c&&c.css(V.effects.clipToBox(p)),p.clip=u),i.queue(function(t){c&&c.animate(V.effects.clipToBox(d),h,e.easing).animate(V.effects.clipToBox(p),h,e.easing),t()}).animate(d,h,e.easing).animate(p,h,e.easing).queue(t),V.effects.unshift(i,s,4)}),V.effects.define("highlight","show",function(t,e){var i=V(this),s={backgroundColor:i.css("backgroundColor")};"hide"===t.mode&&(s.opacity=0),V.effects.saveStyle(i),i.css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(s,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("size",function(s,e){var n,i=V(this),t=["fontSize"],o=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],a=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],r=s.mode,l="effect"!==r,h=s.scale||"both",c=s.origin||["middle","center"],u=i.css("position"),d=i.position(),p=V.effects.scaledDimensions(i),f=s.from||p,g=s.to||V.effects.scaledDimensions(i,0);V.effects.createPlaceholder(i),"show"===r&&(r=f,f=g,g=r),n={from:{y:f.height/p.height,x:f.width/p.width},to:{y:g.height/p.height,x:g.width/p.width}},"box"!==h&&"both"!==h||(n.from.y!==n.to.y&&(f=V.effects.setTransition(i,o,n.from.y,f),g=V.effects.setTransition(i,o,n.to.y,g)),n.from.x!==n.to.x&&(f=V.effects.setTransition(i,a,n.from.x,f),g=V.effects.setTransition(i,a,n.to.x,g))),"content"!==h&&"both"!==h||n.from.y!==n.to.y&&(f=V.effects.setTransition(i,t,n.from.y,f),g=V.effects.setTransition(i,t,n.to.y,g)),c&&(c=V.effects.getBaseline(c,p),f.top=(p.outerHeight-f.outerHeight)*c.y+d.top,f.left=(p.outerWidth-f.outerWidth)*c.x+d.left,g.top=(p.outerHeight-g.outerHeight)*c.y+d.top,g.left=(p.outerWidth-g.outerWidth)*c.x+d.left),delete f.outerHeight,delete f.outerWidth,i.css(f),"content"!==h&&"both"!==h||(o=o.concat(["marginTop","marginBottom"]).concat(t),a=a.concat(["marginLeft","marginRight"]),i.find("*[width]").each(function(){var t=V(this),e=V.effects.scaledDimensions(t),i={height:e.height*n.from.y,width:e.width*n.from.x,outerHeight:e.outerHeight*n.from.y,outerWidth:e.outerWidth*n.from.x},e={height:e.height*n.to.y,width:e.width*n.to.x,outerHeight:e.height*n.to.y,outerWidth:e.width*n.to.x};n.from.y!==n.to.y&&(i=V.effects.setTransition(t,o,n.from.y,i),e=V.effects.setTransition(t,o,n.to.y,e)),n.from.x!==n.to.x&&(i=V.effects.setTransition(t,a,n.from.x,i),e=V.effects.setTransition(t,a,n.to.x,e)),l&&V.effects.saveStyle(t),t.css(i),t.animate(e,s.duration,s.easing,function(){l&&V.effects.restoreStyle(t)})})),i.animate(g,{queue:!1,duration:s.duration,easing:s.easing,complete:function(){var t=i.offset();0===g.opacity&&i.css("opacity",f.opacity),l||(i.css("position","static"===u?"relative":u).offset(t),V.effects.saveStyle(i)),e()}})}),V.effects.define("scale",function(t,e){var i=V(this),s=t.mode,s=parseInt(t.percent,10)||(0===parseInt(t.percent,10)||"effect"!==s?0:100),s=V.extend(!0,{from:V.effects.scaledDimensions(i),to:V.effects.scaledDimensions(i,s,t.direction||"both"),origin:t.origin||["middle","center"]},t);t.fade&&(s.from.opacity=1,s.to.opacity=0),V.effects.effect.size.call(this,s,e)}),V.effects.define("puff","hide",function(t,e){t=V.extend(!0,{},t,{fade:!0,percent:parseInt(t.percent,10)||150});V.effects.effect.scale.call(this,t,e)}),V.effects.define("pulsate","show",function(t,e){var i=V(this),s=t.mode,n="show"===s,o=2*(t.times||5)+(n||"hide"===s?1:0),a=t.duration/o,r=0,l=1,s=i.queue().length;for(!n&&i.is(":visible")||(i.css("opacity",0).show(),r=1);l<o;l++)i.animate({opacity:r},a,t.easing),r=1-r;i.animate({opacity:r},a,t.easing),i.queue(e),V.effects.unshift(i,s,1+o)}),V.effects.define("shake",function(t,e){var i=1,s=V(this),n=t.direction||"left",o=t.distance||20,a=t.times||3,r=2*a+1,l=Math.round(t.duration/r),h="up"===n||"down"===n?"top":"left",c="up"===n||"left"===n,u={},d={},p={},n=s.queue().length;for(V.effects.createPlaceholder(s),u[h]=(c?"-=":"+=")+o,d[h]=(c?"+=":"-=")+2*o,p[h]=(c?"-=":"+=")+2*o,s.animate(u,l,t.easing);i<a;i++)s.animate(d,l,t.easing).animate(p,l,t.easing);s.animate(d,l,t.easing).animate(u,l/2,t.easing).queue(e),V.effects.unshift(s,n,1+r)}),V.effects.define("slide","show",function(t,e){var i,s,n=V(this),o={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},a=t.mode,r=t.direction||"left",l="up"===r||"down"===r?"top":"left",h="up"===r||"left"===r,c=t.distance||n["top"==l?"outerHeight":"outerWidth"](!0),u={};V.effects.createPlaceholder(n),i=n.cssClip(),s=n.position()[l],u[l]=(h?-1:1)*c+s,u.clip=n.cssClip(),u.clip[o[r][1]]=u.clip[o[r][0]],"show"===a&&(n.cssClip(u.clip),n.css(l,u[l]),u.clip=i,u[l]=s),n.animate(u,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),y=!1!==V.uiBackCompat?V.effects.define("transfer",function(t,e){V(this).transfer(t,e)}):y;V.ui.focusable=function(t,e){var i,s,n,o,a=t.nodeName.toLowerCase();return"area"===a?(s=(i=t.parentNode).name,!(!t.href||!s||"map"!==i.nodeName.toLowerCase())&&(0<(s=V("img[usemap='#"+s+"']")).length&&s.is(":visible"))):(/^(input|select|textarea|button|object)$/.test(a)?(n=!t.disabled)&&(o=V(t).closest("fieldset")[0])&&(n=!o.disabled):n="a"===a&&t.href||e,n&&V(t).is(":visible")&&function(t){var e=t.css("visibility");for(;"inherit"===e;)t=t.parent(),e=t.css("visibility");return"visible"===e}(V(t)))},V.extend(V.expr.pseudos,{focusable:function(t){return V.ui.focusable(t,null!=V.attr(t,"tabindex"))}});var Q,J;V.ui.focusable,V.fn._form=function(){return"string"==typeof this[0].form?this.closest("form"):V(this[0].form)},V.ui.formResetMixin={_formResetHandler:function(){var e=V(this);setTimeout(function(){var t=e.data("ui-form-reset-instances");V.each(t,function(){this.refresh()})})},_bindFormResetHandler:function(){var t;this.form=this.element._form(),this.form.length&&((t=this.form.data("ui-form-reset-instances")||[]).length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t))},_unbindFormResetHandler:function(){var t;this.form.length&&((t=this.form.data("ui-form-reset-instances")).splice(V.inArray(this,t),1),t.length?this.form.data("ui-form-reset-instances",t):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset"))}};V.expr.pseudos||(V.expr.pseudos=V.expr[":"]),V.uniqueSort||(V.uniqueSort=V.unique),V.escapeSelector||(Q=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,J=function(t,e){return e?"\0"===t?"�":t.slice(0,-1)+"\\"+t.charCodeAt(t.length-1).toString(16)+" ":"\\"+t},V.escapeSelector=function(t){return(t+"").replace(Q,J)}),V.fn.even&&V.fn.odd||V.fn.extend({even:function(){return this.filter(function(t){return t%2==0})},odd:function(){return this.filter(function(t){return t%2==1})}});var Z;V.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},V.fn.labels=function(){var t,e,i;return this.length?this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(e=this.eq(0).parents("label"),(t=this.attr("id"))&&(i=(i=this.eq(0).parents().last()).add((i.length?i:this).siblings()),t="label[for='"+V.escapeSelector(t)+"']",e=e.add(i.find(t).addBack(t))),this.pushStack(e)):this.pushStack([])},V.fn.scrollParent=function(t){var e=this.css("position"),i="absolute"===e,s=t?/(auto|scroll|hidden)/:/(auto|scroll)/,t=this.parents().filter(function(){var t=V(this);return(!i||"static"!==t.css("position"))&&s.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==e&&t.length?t:V(this[0].ownerDocument||document)},V.extend(V.expr.pseudos,{tabbable:function(t){var e=V.attr(t,"tabindex"),i=null!=e;return(!i||0<=e)&&V.ui.focusable(t,i)}}),V.fn.extend({uniqueId:(Z=0,function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++Z)})}),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&V(this).removeAttr("id")})}}),V.widget("ui.accordion",{version:"1.13.2",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:function(t){return t.find("> li > :first-child").add(t.find("> :not(li)").even())},heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var t=this.options;this.prevShow=this.prevHide=V(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),t.collapsible||!1!==t.active&&null!=t.active||(t.active=0),this._processPanels(),t.active<0&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():V()}},_createIcons:function(){var t,e=this.options.icons;e&&(t=V("<span>"),this._addClass(t,"ui-accordion-header-icon","ui-icon "+e.header),t.prependTo(this.headers),t=this.active.children(".ui-accordion-header-icon"),this._removeClass(t,e.header)._addClass(t,null,e.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){"active"!==t?("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||!1!==this.options.active||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons())):this._activate(e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(t){if(!t.altKey&&!t.ctrlKey){var e=V.ui.keyCode,i=this.headers.length,s=this.headers.index(t.target),n=!1;switch(t.keyCode){case e.RIGHT:case e.DOWN:n=this.headers[(s+1)%i];break;case e.LEFT:case e.UP:n=this.headers[(s-1+i)%i];break;case e.SPACE:case e.ENTER:this._eventHandler(t);break;case e.HOME:n=this.headers[0];break;case e.END:n=this.headers[i-1]}n&&(V(t.target).attr("tabIndex",-1),V(n).attr("tabIndex",0),V(n).trigger("focus"),t.preventDefault())}},_panelKeyDown:function(t){t.keyCode===V.ui.keyCode.UP&&t.ctrlKey&&V(t.currentTarget).prev().trigger("focus")},refresh:function(){var t=this.options;this._processPanels(),!1===t.active&&!0===t.collapsible||!this.headers.length?(t.active=!1,this.active=V()):!1===t.active?this._activate(0):this.active.length&&!V.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=V()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;"function"==typeof this.options.header?this.headers=this.options.header(this.element):this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var i,t=this.options,e=t.heightStyle,s=this.element.parent();this.active=this._findActive(t.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var t=V(this),e=t.uniqueId().attr("id"),i=t.next(),s=i.uniqueId().attr("id");t.attr("aria-controls",s),i.attr("aria-labelledby",e)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(t.event),"fill"===e?(i=s.height(),this.element.siblings(":visible").each(function(){var t=V(this),e=t.css("position");"absolute"!==e&&"fixed"!==e&&(i-=t.outerHeight(!0))}),this.headers.each(function(){i-=V(this).outerHeight(!0)}),this.headers.next().each(function(){V(this).height(Math.max(0,i-V(this).innerHeight()+V(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.headers.next().each(function(){var t=V(this).is(":visible");t||V(this).show(),i=Math.max(i,V(this).css("height","").height()),t||V(this).hide()}).height(i))},_activate:function(t){t=this._findActive(t)[0];t!==this.active[0]&&(t=t||this.active[0],this._eventHandler({target:t,currentTarget:t,preventDefault:V.noop}))},_findActive:function(t){return"number"==typeof t?this.headers.eq(t):V()},_setupEvents:function(t){var i={keydown:"_keydown"};t&&V.each(t.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var e=this.options,i=this.active,s=V(t.currentTarget),n=s[0]===i[0],o=n&&e.collapsible,a=o?V():s.next(),r=i.next(),a={oldHeader:i,oldPanel:r,newHeader:o?V():s,newPanel:a};t.preventDefault(),n&&!e.collapsible||!1===this._trigger("beforeActivate",t,a)||(e.active=!o&&this.headers.index(s),this.active=n?V():s,this._toggle(a),this._removeClass(i,"ui-accordion-header-active","ui-state-active"),e.icons&&(i=i.children(".ui-accordion-header-icon"),this._removeClass(i,null,e.icons.activeHeader)._addClass(i,null,e.icons.header)),n||(this._removeClass(s,"ui-accordion-header-collapsed")._addClass(s,"ui-accordion-header-active","ui-state-active"),e.icons&&(n=s.children(".ui-accordion-header-icon"),this._removeClass(n,null,e.icons.header)._addClass(n,null,e.icons.activeHeader)),this._addClass(s.next(),"ui-accordion-content-active")))},_toggle:function(t){var e=t.newPanel,i=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=e,this.prevHide=i,this.options.animate?this._animate(e,i,t):(i.hide(),e.show(),this._toggleComplete(t)),i.attr({"aria-hidden":"true"}),i.prev().attr({"aria-selected":"false","aria-expanded":"false"}),e.length&&i.length?i.prev().attr({tabIndex:-1,"aria-expanded":"false"}):e.length&&this.headers.filter(function(){return 0===parseInt(V(this).attr("tabIndex"),10)}).attr("tabIndex",-1),e.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,i,e){var s,n,o,a=this,r=0,l=t.css("box-sizing"),h=t.length&&(!i.length||t.index()<i.index()),c=this.options.animate||{},u=h&&c.down||c,h=function(){a._toggleComplete(e)};return n=(n="string"==typeof u?u:n)||u.easing||c.easing,o=(o="number"==typeof u?u:o)||u.duration||c.duration,i.length?t.length?(s=t.show().outerHeight(),i.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),void t.hide().animate(this.showProps,{duration:o,easing:n,complete:h,step:function(t,e){e.now=Math.round(t),"height"!==e.prop?"content-box"===l&&(r+=e.now):"content"!==a.options.heightStyle&&(e.now=Math.round(s-i.outerHeight()-r),r=0)}})):i.animate(this.hideProps,o,n,h):t.animate(this.showProps,o,n,h)},_toggleComplete:function(t){var e=t.oldPanel,i=e.prev();this._removeClass(e,"ui-accordion-content-active"),this._removeClass(i,"ui-accordion-header-active")._addClass(i,"ui-accordion-header-collapsed"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}}),V.ui.safeActiveElement=function(e){var i;try{i=e.activeElement}catch(t){i=e.body}return i=!(i=i||e.body).nodeName?e.body:i},V.widget("ui.menu",{version:"1.13.2",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.lastMousePosition={x:null,y:null},this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content","ui-corner-all"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault(),this._activateItem(t)},"click .ui-menu-item":function(t){var e=V(t.target),i=V(V.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&e.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),e.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&i.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this._menuItems().first();e||this.focus(t,i)},blur:function(t){this._delay(function(){V.contains(this.element[0],V.ui.safeActiveElement(this.document[0]))||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t,!0),this.mouseHandled=!1}})},_activateItem:function(t){var e,i;this.previousFilter||t.clientX===this.lastMousePosition.x&&t.clientY===this.lastMousePosition.y||(this.lastMousePosition={x:t.clientX,y:t.clientY},e=V(t.target).closest(".ui-menu-item"),i=V(t.currentTarget),e[0]===i[0]&&(i.is(".ui-state-active")||(this._removeClass(i.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(t,i))))},_destroy:function(){var t=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),t.children().each(function(){var t=V(this);t.data("ui-menu-submenu-caret")&&t.remove()})},_keydown:function(t){var e,i,s,n=!0;switch(t.keyCode){case V.ui.keyCode.PAGE_UP:this.previousPage(t);break;case V.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case V.ui.keyCode.HOME:this._move("first","first",t);break;case V.ui.keyCode.END:this._move("last","last",t);break;case V.ui.keyCode.UP:this.previous(t);break;case V.ui.keyCode.DOWN:this.next(t);break;case V.ui.keyCode.LEFT:this.collapse(t);break;case V.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case V.ui.keyCode.ENTER:case V.ui.keyCode.SPACE:this._activate(t);break;case V.ui.keyCode.ESCAPE:this.collapse(t);break;default:e=this.previousFilter||"",s=n=!1,i=96<=t.keyCode&&t.keyCode<=105?(t.keyCode-96).toString():String.fromCharCode(t.keyCode),clearTimeout(this.filterTimer),i===e?s=!0:i=e+i,e=this._filterMenuItems(i),(e=s&&-1!==e.index(this.active.next())?this.active.nextAll(".ui-menu-item"):e).length||(i=String.fromCharCode(t.keyCode),e=this._filterMenuItems(i)),e.length?(this.focus(t,e),this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}n&&t.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var t,e,s=this,n=this.options.icons.submenu,i=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),e=i.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=V(this),e=t.prev(),i=V("<span>").data("ui-menu-submenu-caret",!0);s._addClass(i,"ui-menu-icon","ui-icon "+n),e.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",e.attr("id"))}),this._addClass(e,"ui-menu","ui-widget ui-widget-content ui-front"),(t=i.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var t=V(this);s._isDivider(t)&&s._addClass(t,"ui-menu-divider","ui-widget-content")}),i=(e=t.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(e,"ui-menu-item")._addClass(i,"ui-menu-item-wrapper"),t.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!V.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){var i;"icons"===t&&(i=this.element.find(".ui-menu-icon"),this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",String(t)),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),i=this.active.children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",i.attr("id")),i=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=e.children(".ui-menu")).length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(t){var e,i,s;this._hasScroll()&&(i=parseFloat(V.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(V.css(this.activeMenu[0],"paddingTop"))||0,e=t.offset().top-this.activeMenu.offset().top-i-s,i=this.activeMenu.scrollTop(),s=this.activeMenu.height(),t=t.outerHeight(),e<0?this.activeMenu.scrollTop(i+e):s<e+t&&this.activeMenu.scrollTop(i+e-s+t))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(t){var e=V.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(e)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var t=i?this.element:V(e&&e.target).closest(this.element.find(".ui-menu"));t.length||(t=this.element),this._close(t),this.blur(e),this._removeClass(t.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=t},i?0:this.delay)},_close:function(t){this.isNewMenu = true,(t=t||(this.active?this.active.parent():this.element)).find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(t){return!V(t.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this._menuItems(this.active.children(".ui-menu")).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_menuItems:function(t){return(t||this.element).find(this.options.items).filter(".ui-menu-item")},_move:function(t,e,i){var s;(s=this.active?"first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").last():this.active[t+"All"](".ui-menu-item").first():s)&&s.length&&this.active||(s=this._menuItems(this.activeMenu)[e]()),this.focus(i,s)},nextPage:function(t){var e,i,s;this.active?this.isLastItem()||(this._hasScroll()?(i=this.active.offset().top,s=this.element.innerHeight(),0===V.fn.jquery.indexOf("3.2.")&&(s+=this.element[0].offsetHeight-this.element.outerHeight()),this.active.nextAll(".ui-menu-item").each(function(){return(e=V(this)).offset().top-i-s<0}),this.focus(t,e)):this.focus(t,this._menuItems(this.activeMenu)[this.active?"last":"first"]())):this.next(t)},previousPage:function(t){var e,i,s;this.active?this.isFirstItem()||(this._hasScroll()?(i=this.active.offset().top,s=this.element.innerHeight(),0===V.fn.jquery.indexOf("3.2.")&&(s+=this.element[0].offsetHeight-this.element.outerHeight()),this.active.prevAll(".ui-menu-item").each(function(){return 0<(e=V(this)).offset().top-i+s}),this.focus(t,e)):this.focus(t,this._menuItems(this.activeMenu).first())):this.next(t)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||V(t.target).closest(".ui-menu-item");var e={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,e)},_filterMenuItems:function(t){var t=t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),e=new RegExp("^"+t,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return e.test(String.prototype.trim.call(V(this).children(".ui-menu-item-wrapper").text()))})}});V.widget("ui.autocomplete",{version:"1.13.2",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,liveRegionTimer:null,_create:function(){var i,s,n,t=this.element[0].nodeName.toLowerCase(),e="textarea"===t,t="input"===t;this.isMultiLine=e||!t&&this._isContentEditable(this.element),this.valueMethod=this.element[e||t?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(t){if(this.element.prop("readOnly"))s=n=i=!0;else{s=n=i=!1;var e=V.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:i=!0,this._move("previousPage",t);break;case e.PAGE_DOWN:i=!0,this._move("nextPage",t);break;case e.UP:i=!0,this._keyEvent("previous",t);break;case e.DOWN:i=!0,this._keyEvent("next",t);break;case e.ENTER:this.menu.active&&(i=!0,t.preventDefault(),this.menu.select(t));break;case e.TAB:this.menu.active&&this.menu.select(t);break;case e.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(t),t.preventDefault());break;default:s=!0,this._searchTimeout(t)}}},keypress:function(t){if(i)return i=!1,void(this.isMultiLine&&!this.menu.element.is(":visible")||t.preventDefault());if(!s){var e=V.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:this._move("previousPage",t);break;case e.PAGE_DOWN:this._move("nextPage",t);break;case e.UP:this._keyEvent("previous",t);break;case e.DOWN:this._keyEvent("next",t)}}},input:function(t){if(n)return n=!1,void t.preventDefault();this._searchTimeout(t)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){clearTimeout(this.searching),this.close(t),this._change(t)}}),this._initSource(),this.menu=V("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().attr({unselectable:"on"}).menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault()},menufocus:function(t,e){var i,s;if(this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type)))return this.menu.blur(),void this.document.one("mousemove",function(){V(t.target).trigger(t.originalEvent)});s=e.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:s})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(s.value),(i=e.item.attr("aria-label")||s.value)&&String.prototype.trim.call(i).length&&(clearTimeout(this.liveRegionTimer),this.liveRegionTimer=this._delay(function(){this.liveRegion.html(V("<div>").text(i))},100))},menuselect:function(t,e){var i=e.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==V.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",t,{item:i})&&this._value(i.value),this.term=this._value(),this.close(t),this.selectedItem=i}}),this.liveRegion=V("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(t){var e=this.menu.element[0];return t.target===this.element[0]||t.target===e||V.contains(e,t.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var t=this.options.appendTo;return t=!(t=!(t=t&&(t.jquery||t.nodeType?V(t):this.document.find(t).eq(0)))||!t[0]?this.element.closest(".ui-front, dialog"):t).length?this.document[0].body:t},_initSource:function(){var i,s,n=this;Array.isArray(this.options.source)?(i=this.options.source,this.source=function(t,e){e(V.ui.autocomplete.filter(i,t.term))}):"string"==typeof this.options.source?(s=this.options.source,this.source=function(t,e){n.xhr&&n.xhr.abort(),n.xhr=V.ajax({url:s,data:t,dataType:"json",success:function(t){e(t)},error:function(){e([])}})}):this.source=this.options.source},_searchTimeout:function(s){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),e=this.menu.element.is(":visible"),i=s.altKey||s.ctrlKey||s.metaKey||s.shiftKey;t&&(e||i)||(this.selectedItem=null,this.search(null,s))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):!1!==this._trigger("search",e)?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")}.bind(this)},__response:function(t){t=t&&this._normalize(t),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this.isNewMenu = true,this._off(this.document,"mousedown"),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:V.map(t,function(t){return"string"==typeof t?{label:t,value:t}:V.extend({},t,{label:t.label||t.value,value:t.value||t.label})})},_suggest:function(t){var e=this.menu.element.empty();this._renderMenu(e,t),this.isNewMenu=!0,this.menu.refresh(),e.show(),this._resizeMenu(),e.position(V.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(),this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(i,t){var s=this;V.each(t,function(t,e){s._renderItemData(i,e)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(t,e){return V("<li>").append(V("<a>").text(e.label)).appendTo(t)},_move:function(t,e){if(this.menu.element.is(":visible"))return this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),void this.menu.blur()):void this.menu[t](e);this.search(null,e)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){this.isMultiLine&&!this.menu.element.is(":visible")||(this._move(t,e),e.preventDefault())},_isContentEditable:function(t){if(!t.length)return!1;var e=t.prop("contentEditable");return"inherit"===e?this._isContentEditable(t.parent()):"true"===e}}),V.extend(V.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,e){var i=new RegExp(V.ui.autocomplete.escapeRegex(e),"i");return V.grep(t,function(t){return i.test(t.label||t.value||t)})}}),V.widget("ui.autocomplete",V.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(1<t?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var e;this._superApply(arguments),this.options.disabled||this.cancelSearch||(e=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,clearTimeout(this.liveRegionTimer),this.liveRegionTimer=this._delay(function(){this.liveRegion.html(V("<div>").text(e))},100))}});V.ui.autocomplete;var tt=/ui-corner-([a-z]){2,6}/g;V.widget("ui.controlgroup",{version:"1.13.2",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:!0,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar"),this.refresh()},_destroy:function(){this._callChildMethod("destroy"),this.childWidgets.removeData("ui-controlgroup-data"),this.element.removeAttr("role"),this.options.items.controlgroupLabel&&this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()},_initWidgets:function(){var o=this,a=[];V.each(this.options.items,function(s,t){var e,n={};if(t)return"controlgroupLabel"===s?((e=o.element.find(t)).each(function(){var t=V(this);t.children(".ui-controlgroup-label-contents").length||t.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),o._addClass(e,null,"ui-widget ui-widget-content ui-state-default"),void(a=a.concat(e.get()))):void(V.fn[s]&&(n=o["_"+s+"Options"]?o["_"+s+"Options"]("middle"):{classes:{}},o.element.find(t).each(function(){var t=V(this),e=t[s]("instance"),i=V.widget.extend({},n);"button"===s&&t.parent(".ui-spinner").length||((e=e||t[s]()[s]("instance"))&&(i.classes=o._resolveClassesValues(i.classes,e)),t[s](i),i=t[s]("widget"),V.data(i[0],"ui-controlgroup-data",e||t[s]("instance")),a.push(i[0]))})))}),this.childWidgets=V(V.uniqueSort(a)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var t=V(this).data("ui-controlgroup-data");t&&t[e]&&t[e]()})},_updateCornerClass:function(t,e){e=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,"ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all"),this._addClass(t,null,e)},_buildSimpleOptions:function(t,e){var i="vertical"===this.options.direction,s={classes:{}};return s.classes[e]={middle:"",first:"ui-corner-"+(i?"top":"left"),last:"ui-corner-"+(i?"bottom":"right"),only:"ui-corner-all"}[t],s},_spinnerOptions:function(t){t=this._buildSimpleOptions(t,"ui-spinner");return t.classes["ui-spinner-up"]="",t.classes["ui-spinner-down"]="",t},_buttonOptions:function(t){return this._buildSimpleOptions(t,"ui-button")},_checkboxradioOptions:function(t){return this._buildSimpleOptions(t,"ui-checkboxradio-label")},_selectmenuOptions:function(t){var e="vertical"===this.options.direction;return{width:e&&"auto",classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(e?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(e?"top":"left")},last:{"ui-selectmenu-button-open":e?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(e?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[t]}},_resolveClassesValues:function(i,s){var n={};return V.each(i,function(t){var e=s.options.classes[t]||"",e=String.prototype.trim.call(e.replace(tt,""));n[t]=(e+" "+i[t]).replace(/\s+/g," ")}),n},_setOption:function(t,e){"direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"!==t?this.refresh():this._callChildMethod(e?"disable":"enable")},refresh:function(){var n,o=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),n=this.childWidgets,(n=this.options.onlyVisible?n.filter(":visible"):n).length&&(V.each(["first","last"],function(t,e){var i,s=n[e]().data("ui-controlgroup-data");s&&o["_"+s.widgetName+"Options"]?((i=o["_"+s.widgetName+"Options"](1===n.length?"only":e)).classes=o._resolveClassesValues(i.classes,s),s.element[s.widgetName](i)):o._updateCornerClass(n[e](),e)}),this._callChildMethod("refresh"))}});V.widget("ui.checkboxradio",[V.ui.formResetMixin,{version:"1.13.2",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var t,e=this._super()||{};return this._readType(),t=this.element.labels(),this.label=V(t[t.length-1]),this.label.length||V.error("No label found for checkboxradio widget"),this.originalLabel="",(t=this.label.contents().not(this.element[0])).length&&(this.originalLabel+=t.clone().wrapAll("<div></div>").parent().html()),this.originalLabel&&(e.label=this.originalLabel),null!=(t=this.element[0].disabled)&&(e.disabled=t),e},_create:function(){var t=this.element[0].checked;this._bindFormResetHandler(),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled),this._setOption("disabled",this.options.disabled),this._addClass("ui-checkboxradio","ui-helper-hidden-accessible"),this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget"),"radio"===this.type&&this._addClass(this.label,"ui-checkboxradio-radio-label"),this.options.label&&this.options.label!==this.originalLabel?this._updateLabel():this.originalLabel&&(this.options.label=this.originalLabel),this._enhance(),t&&this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active"),this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var t=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===t&&/radio|checkbox/.test(this.type)||V.error("Can't create checkboxradio on element.nodeName="+t+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var t=this.element[0].name,e="input[name='"+V.escapeSelector(t)+"']";return t?(this.form.length?V(this.form[0].elements).filter(e):V(e).filter(function(){return 0===V(this)._form().length})).not(this.element):V([])},_toggleClasses:function(){var t=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",t)._toggleClass(this.icon,null,"ui-icon-blank",!t),"radio"===this.type&&this._getRadioGroup().each(function(){var t=V(this).checkboxradio("instance");t&&t._removeClass(t.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){if("label"!==t||e){if(this._super(t,e),"disabled"===t)return this._toggleClass(this.label,null,"ui-state-disabled",e),void(this.element[0].disabled=e);this.refresh()}},_updateIcon:function(t){var e="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=V("<span>"),this.iconSpace=V("<span> </span>"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(e+=t?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,t?"ui-icon-blank":"ui-icon-check")):e+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",e),t||this._removeClass(this.icon,null,"ui-icon-check ui-state-checked"),this.icon.prependTo(this.label).after(this.iconSpace)):void 0!==this.icon&&(this.icon.remove(),this.iconSpace.remove(),delete this.icon)},_updateLabel:function(){var t=this.label.contents().not(this.element[0]);this.icon&&(t=t.not(this.icon[0])),(t=this.iconSpace?t.not(this.iconSpace[0]):t).remove(),this.label.append(this.options.label)},refresh:function(){var t=this.element[0].checked,e=this.element[0].disabled;this._updateIcon(t),this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),null!==this.options.label&&this._updateLabel(),e!==this.options.disabled&&this._setOptions({disabled:e})}}]);var et;V.ui.checkboxradio;V.widget("ui.button",{version:"1.13.2",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:!0},_getCreateOptions:function(){var t,e=this._super()||{};return this.isInput=this.element.is("input"),null!=(t=this.element[0].disabled)&&(e.disabled=t),this.originalLabel=this.isInput?this.element.val():this.element.html(),this.originalLabel&&(e.label=this.originalLabel),e},_create:function(){!this.option.showLabel&!this.options.icon&&(this.options.showLabel=!0),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled||!1),this.hasTitle=!!this.element.attr("title"),this.options.label&&this.options.label!==this.originalLabel&&(this.isInput?this.element.val(this.options.label):this.element.html(this.options.label)),this._addClass("ui-button","ui-widget"),this._setOption("disabled",this.options.disabled),this._enhance(),this.element.is("a")&&this._on({keyup:function(t){t.keyCode===V.ui.keyCode.SPACE&&(t.preventDefault(),this.element[0].click?this.element[0].click():this.element.trigger("click"))}})},_enhance:function(){this.element.is("button")||this.element.attr("role","button"),this.options.icon&&(this._updateIcon("icon",this.options.icon),this._updateTooltip())},_updateTooltip:function(){this.title=this.element.attr("title"),this.options.showLabel||this.title||this.element.attr("title",this.options.label)},_updateIcon:function(t,e){var i="iconPosition"!==t,s=i?this.options.iconPosition:e,t="top"===s||"bottom"===s;this.icon?i&&this._removeClass(this.icon,null,this.options.icon):(this.icon=V("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),i&&this._addClass(this.icon,null,e),this._attachIcon(s),t?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconSpace||(this.iconSpace=V("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(s))},_destroy:function(){this.element.removeAttr("role"),this.icon&&this.icon.remove(),this.iconSpace&&this.iconSpace.remove(),this.hasTitle||this.element.removeAttr("title")},_attachIconSpace:function(t){this.icon[/^(?:end|bottom)/.test(t)?"before":"after"](this.iconSpace)},_attachIcon:function(t){this.element[/^(?:end|bottom)/.test(t)?"append":"prepend"](this.icon)},_setOptions:function(t){var e=(void 0===t.showLabel?this.options:t).showLabel,i=(void 0===t.icon?this.options:t).icon;e||i||(t.showLabel=!0),this._super(t)},_setOption:function(t,e){"icon"===t&&(e?this._updateIcon(t,e):this.icon&&(this.icon.remove(),this.iconSpace&&this.iconSpace.remove())),"iconPosition"===t&&this._updateIcon(t,e),"showLabel"===t&&(this._toggleClass("ui-button-icon-only",null,!e),this._updateTooltip()),"label"===t&&(this.isInput?this.element.val(e):(this.element.html(e),this.icon&&(this._attachIcon(this.options.iconPosition),this._attachIconSpace(this.options.iconPosition)))),this._super(t,e),"disabled"===t&&(this._toggleClass(null,"ui-state-disabled",e),(this.element[0].disabled=e)&&this.element.trigger("blur"))},refresh:function(){var t=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOptions({disabled:t}),this._updateTooltip()}}),!1!==V.uiBackCompat&&(V.widget("ui.button",V.ui.button,{options:{text:!0,icons:{primary:null,secondary:null}},_create:function(){this.options.showLabel&&!this.options.text&&(this.options.showLabel=this.options.text),!this.options.showLabel&&this.options.text&&(this.options.text=this.options.showLabel),this.options.icon||!this.options.icons.primary&&!this.options.icons.secondary?this.options.icon&&(this.options.icons.primary=this.options.icon):this.options.icons.primary?this.options.icon=this.options.icons.primary:(this.options.icon=this.options.icons.secondary,this.options.iconPosition="end"),this._super()},_setOption:function(t,e){"text"!==t?("showLabel"===t&&(this.options.text=e),"icon"===t&&(this.options.icons.primary=e),"icons"===t&&(e.primary?(this._super("icon",e.primary),this._super("iconPosition","beginning")):e.secondary&&(this._super("icon",e.secondary),this._super("iconPosition","end"))),this._superApply(arguments)):this._super("showLabel",e)}}),V.fn.button=(et=V.fn.button,function(i){var t="string"==typeof i,s=Array.prototype.slice.call(arguments,1),n=this;return t?this.length||"instance"!==i?this.each(function(){var t=V(this).attr("type"),e=V.data(this,"ui-"+("checkbox"!==t&&"radio"!==t?"button":"checkboxradio"));return"instance"===i?(n=e,!1):e?"function"!=typeof e[i]||"_"===i.charAt(0)?V.error("no such method '"+i+"' for button widget instance"):(t=e[i].apply(e,s))!==e&&void 0!==t?(n=t&&t.jquery?n.pushStack(t.get()):t,!1):void 0:V.error("cannot call methods on button prior to initialization; attempted to call method '"+i+"'")}):n=void 0:(s.length&&(i=V.widget.extend.apply(null,[i].concat(s))),this.each(function(){var t=V(this).attr("type"),e="checkbox"!==t&&"radio"!==t?"button":"checkboxradio",t=V.data(this,"ui-"+e);t?(t.option(i||{}),t._init&&t._init()):"button"!=e?V(this).checkboxradio(V.extend({icon:!1},i)):et.call(V(this),i)})),n}),V.fn.buttonset=function(){return V.ui.controlgroup||V.error("Controlgroup widget missing"),"option"===arguments[0]&&"items"===arguments[1]&&arguments[2]?this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]):"option"===arguments[0]&&"items"===arguments[1]?this.controlgroup.apply(this,[arguments[0],"items.button"]):("object"==typeof arguments[0]&&arguments[0].items&&(arguments[0].items={button:arguments[0].items}),this.controlgroup.apply(this,arguments))});var it;V.ui.button;function st(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:"",selectMonthLabel:"Select month",selectYearLabel:"Select year"},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,onUpdateDatepicker:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},V.extend(this._defaults,this.regional[""]),this.regional.en=V.extend(!0,{},this.regional[""]),this.regional["en-US"]=V.extend(!0,{},this.regional.en),this.dpDiv=nt(V("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function nt(t){var e="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.on("mouseout",e,function(){V(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&V(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&V(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",e,ot)}function ot(){V.datepicker._isDisabledDatepicker((it.inline?it.dpDiv.parent():it.input)[0])||(V(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),V(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&V(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&V(this).addClass("ui-datepicker-next-hover"))}function at(t,e){for(var i in V.extend(t,e),e)null==e[i]&&(t[i]=e[i]);return t}V.extend(V.ui,{datepicker:{version:"1.13.2"}}),V.extend(st.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return at(this._defaults,t||{}),this},_attachDatepicker:function(t,e){var i,s=t.nodeName.toLowerCase(),n="div"===s||"span"===s;t.id||(this.uuid+=1,t.id="dp"+this.uuid),(i=this._newInst(V(t),n)).settings=V.extend({},e||{}),"input"===s?this._connectDatepicker(t,i):n&&this._inlineDatepicker(t,i)},_newInst:function(t,e){return{id:t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1"),input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:e,dpDiv:e?nt(V("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,e){var i=V(t);e.append=V([]),e.trigger=V([]),i.hasClass(this.markerClassName)||(this._attachments(i,e),i.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(e),V.data(t,"datepicker",e),e.settings.disabled&&this._disableDatepicker(t))},_attachments:function(t,e){var i,s=this._get(e,"appendText"),n=this._get(e,"isRTL");e.append&&e.append.remove(),s&&(e.append=V("<span>").addClass(this._appendClass).text(s),t[n?"before":"after"](e.append)),t.off("focus",this._showDatepicker),e.trigger&&e.trigger.remove(),"focus"!==(i=this._get(e,"showOn"))&&"both"!==i||t.on("focus",this._showDatepicker),"button"!==i&&"both"!==i||(s=this._get(e,"buttonText"),i=this._get(e,"buttonImage"),this._get(e,"buttonImageOnly")?e.trigger=V("<img>").addClass(this._triggerClass).attr({src:i,alt:s,title:s}):(e.trigger=V("<button type='button'>").addClass(this._triggerClass),i?e.trigger.html(V("<img>").attr({src:i,alt:s,title:s})):e.trigger.text(s)),t[n?"before":"after"](e.trigger),e.trigger.on("click",function(){return V.datepicker._datepickerShowing&&V.datepicker._lastInput===t[0]?V.datepicker._hideDatepicker():(V.datepicker._datepickerShowing&&V.datepicker._lastInput!==t[0]&&V.datepicker._hideDatepicker(),V.datepicker._showDatepicker(t[0])),!1}))},_autoSize:function(t){var e,i,s,n,o,a;this._get(t,"autoSize")&&!t.inline&&(o=new Date(2009,11,20),(a=this._get(t,"dateFormat")).match(/[DM]/)&&(e=function(t){for(n=s=i=0;n<t.length;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length))},_inlineDatepicker:function(t,e){var i=V(t);i.hasClass(this.markerClassName)||(i.addClass(this.markerClassName).append(e.dpDiv),V.data(t,"datepicker",e),this._setDate(e,this._getDefaultDate(e),!0),this._updateDatepicker(e),this._updateAlternate(e),e.settings.disabled&&this._disableDatepicker(t),e.dpDiv.css("display","block"))},_dialogDatepicker:function(t,e,i,s,n){var o,a=this._dialogInst;return a||(this.uuid+=1,o="dp"+this.uuid,this._dialogInput=V("<input type='text' id='"+o+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.on("keydown",this._doKeyDown),V("body").append(this._dialogInput),(a=this._dialogInst=this._newInst(this._dialogInput,!1)).settings={},V.data(this._dialogInput[0],"datepicker",a)),at(a.settings,s||{}),e=e&&e.constructor===Date?this._formatDate(a,e):e,this._dialogInput.val(e),this._pos=n?n.length?n:[n.pageX,n.pageY]:null,this._pos||(o=document.documentElement.clientWidth,s=document.documentElement.clientHeight,e=document.documentElement.scrollLeft||document.body.scrollLeft,n=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[o/2-100+e,s/2-150+n]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),a.settings.onSelect=i,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),V.blockUI&&V.blockUI(this.dpDiv),V.data(this._dialogInput[0],"datepicker",a),this},_destroyDatepicker:function(t){var e,i=V(t),s=V.data(t,"datepicker");i.hasClass(this.markerClassName)&&(e=t.nodeName.toLowerCase(),V.removeData(t,"datepicker"),"input"===e?(s.append.remove(),s.trigger.remove(),i.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):"div"!==e&&"span"!==e||i.removeClass(this.markerClassName).empty(),it===s&&(it=null,this._curInst=null))},_enableDatepicker:function(e){var t,i=V(e),s=V.data(e,"datepicker");i.hasClass(this.markerClassName)&&("input"===(t=e.nodeName.toLowerCase())?(e.disabled=!1,s.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):"div"!==t&&"span"!==t||((i=i.children("."+this._inlineClass)).children().removeClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=V.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var t,i=V(e),s=V.data(e,"datepicker");i.hasClass(this.markerClassName)&&("input"===(t=e.nodeName.toLowerCase())?(e.disabled=!0,s.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):"div"!==t&&"span"!==t||((i=i.children("."+this._inlineClass)).children().addClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=V.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;e<this._disabledInputs.length;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(t){try{return V.data(t,"datepicker")}catch(t){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(t,e,i){var s,n,o=this._getInst(t);if(2===arguments.length&&"string"==typeof e)return"defaults"===e?V.extend({},V.datepicker._defaults):o?"all"===e?V.extend({},o.settings):this._get(o,e):null;s=e||{},"string"==typeof e&&((s={})[e]=i),o&&(this._curInst===o&&this._hideDatepicker(),n=this._getDateDatepicker(t,!0),e=this._getMinMaxDate(o,"min"),i=this._getMinMaxDate(o,"max"),at(o.settings,s),null!==e&&void 0!==s.dateFormat&&void 0===s.minDate&&(o.settings.minDate=this._formatDate(o,e)),null!==i&&void 0!==s.dateFormat&&void 0===s.maxDate&&(o.settings.maxDate=this._formatDate(o,i)),"disabled"in s&&(s.disabled?this._disableDatepicker(t):this._enableDatepicker(t)),this._attachments(V(t),o),this._autoSize(o),this._setDate(o,n),this._updateAlternate(o),this._updateDatepicker(o))},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){t=this._getInst(t);t&&this._updateDatepicker(t)},_setDateDatepicker:function(t,e){t=this._getInst(t);t&&(this._setDate(t,e),this._updateDatepicker(t),this._updateAlternate(t))},_getDateDatepicker:function(t,e){t=this._getInst(t);return t&&!t.inline&&this._setDateFromField(t,e),t?this._getDate(t):null},_doKeyDown:function(t){var e,i,s=V.datepicker._getInst(t.target),n=!0,o=s.dpDiv.is(".ui-datepicker-rtl");if(s._keyEvent=!0,V.datepicker._datepickerShowing)switch(t.keyCode){case 9:V.datepicker._hideDatepicker(),n=!1;break;case 13:return(i=V("td."+V.datepicker._dayOverClass+":not(."+V.datepicker._currentClass+")",s.dpDiv))[0]&&V.datepicker._selectDay(t.target,s.selectedMonth,s.selectedYear,i[0]),(e=V.datepicker._get(s,"onSelect"))?(i=V.datepicker._formatDate(s),e.apply(s.input?s.input[0]:null,[i,s])):V.datepicker._hideDatepicker(),!1;case 27:V.datepicker._hideDatepicker();break;case 33:V.datepicker._adjustDate(t.target,t.ctrlKey?-V.datepicker._get(s,"stepBigMonths"):-V.datepicker._get(s,"stepMonths"),"M");break;case 34:V.datepicker._adjustDate(t.target,t.ctrlKey?+V.datepicker._get(s,"stepBigMonths"):+V.datepicker._get(s,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&V.datepicker._clearDate(t.target),n=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&V.datepicker._gotoToday(t.target),n=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,o?1:-1,"D"),n=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&V.datepicker._adjustDate(t.target,t.ctrlKey?-V.datepicker._get(s,"stepBigMonths"):-V.datepicker._get(s,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,-7,"D"),n=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,o?-1:1,"D"),n=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&V.datepicker._adjustDate(t.target,t.ctrlKey?+V.datepicker._get(s,"stepBigMonths"):+V.datepicker._get(s,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,7,"D"),n=t.ctrlKey||t.metaKey;break;default:n=!1}else 36===t.keyCode&&t.ctrlKey?V.datepicker._showDatepicker(this):n=!1;n&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(t){var e,i=V.datepicker._getInst(t.target);if(V.datepicker._get(i,"constrainInput"))return e=V.datepicker._possibleChars(V.datepicker._get(i,"dateFormat")),i=String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),t.ctrlKey||t.metaKey||i<" "||!e||-1<e.indexOf(i)},_doKeyUp:function(t){t=V.datepicker._getInst(t.target);if(t.input.val()!==t.lastVal)try{V.datepicker.parseDate(V.datepicker._get(t,"dateFormat"),t.input?t.input.val():null,V.datepicker._getFormatConfig(t))&&(V.datepicker._setDateFromField(t),V.datepicker._updateAlternate(t),V.datepicker._updateDatepicker(t))}catch(t){}return!0},_showDatepicker:function(t){var e,i,s,n;"input"!==(t=t.target||t).nodeName.toLowerCase()&&(t=V("input",t.parentNode)[0]),V.datepicker._isDisabledDatepicker(t)||V.datepicker._lastInput===t||(n=V.datepicker._getInst(t),V.datepicker._curInst&&V.datepicker._curInst!==n&&(V.datepicker._curInst.dpDiv.stop(!0,!0),n&&V.datepicker._datepickerShowing&&V.datepicker._hideDatepicker(V.datepicker._curInst.input[0])),!1!==(i=(s=V.datepicker._get(n,"beforeShow"))?s.apply(t,[t,n]):{})&&(at(n.settings,i),n.lastVal=null,V.datepicker._lastInput=t,V.datepicker._setDateFromField(n),V.datepicker._inDialog&&(t.value=""),V.datepicker._pos||(V.datepicker._pos=V.datepicker._findPos(t),V.datepicker._pos[1]+=t.offsetHeight),e=!1,V(t).parents().each(function(){return!(e|="fixed"===V(this).css("position"))}),s={left:V.datepicker._pos[0],top:V.datepicker._pos[1]},V.datepicker._pos=null,n.dpDiv.empty(),n.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),V.datepicker._updateDatepicker(n),s=V.datepicker._checkOffset(n,s,e),n.dpDiv.css({position:V.datepicker._inDialog&&V.blockUI?"static":e?"fixed":"absolute",display:"none",left:s.left+"px",top:s.top+"px"}),n.inline||(i=V.datepicker._get(n,"showAnim"),s=V.datepicker._get(n,"duration"),n.dpDiv.css("z-index",function(t){for(var e,i;t.length&&t[0]!==document;){if(("absolute"===(e=t.css("position"))||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}(V(t))+1),V.datepicker._datepickerShowing=!0,V.effects&&V.effects.effect[i]?n.dpDiv.show(i,V.datepicker._get(n,"showOptions"),s):n.dpDiv[i||"show"](i?s:null),V.datepicker._shouldFocusInput(n)&&n.input.trigger("focus"),V.datepicker._curInst=n)))},_updateDatepicker:function(t){this.maxRows=4,(it=t).dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t);var e,i=this._getNumberOfMonths(t),s=i[1],n=t.dpDiv.find("."+this._dayOverClass+" a"),o=V.datepicker._get(t,"onUpdateDatepicker");0<n.length&&ot.apply(n.get(0)),t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),1<s&&t.dpDiv.addClass("ui-datepicker-multi-"+s).css("width",17*s+"em"),t.dpDiv[(1!==i[0]||1!==i[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===V.datepicker._curInst&&V.datepicker._datepickerShowing&&V.datepicker._shouldFocusInput(t)&&t.input.trigger("focus"),t.yearshtml&&(e=t.yearshtml,setTimeout(function(){e===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year").first().replaceWith(t.yearshtml),e=t.yearshtml=null},0)),o&&o.apply(t.input?t.input[0]:null,[t])},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(t,e,i){var s=t.dpDiv.outerWidth(),n=t.dpDiv.outerHeight(),o=t.input?t.input.outerWidth():0,a=t.input?t.input.outerHeight():0,r=document.documentElement.clientWidth+(i?0:V(document).scrollLeft()),l=document.documentElement.clientHeight+(i?0:V(document).scrollTop());return e.left-=this._get(t,"isRTL")?s-o:0,e.left-=i&&e.left===t.input.offset().left?V(document).scrollLeft():0,e.top-=i&&e.top===t.input.offset().top+a?V(document).scrollTop():0,e.left-=Math.min(e.left,e.left+s>r&&s<r?Math.abs(e.left+s-r):0),e.top-=Math.min(e.top,e.top+n>l&&n<l?Math.abs(n+a):0),e},_findPos:function(t){for(var e=this._getInst(t),i=this._get(e,"isRTL");t&&("hidden"===t.type||1!==t.nodeType||V.expr.pseudos.hidden(t));)t=t[i?"previousSibling":"nextSibling"];return[(e=V(t).offset()).left,e.top]},_hideDatepicker:function(t){var e,i,s=this._curInst;!s||t&&s!==V.data(t,"datepicker")||this._datepickerShowing&&(e=this._get(s,"showAnim"),i=this._get(s,"duration"),t=function(){V.datepicker._tidyDialog(s)},V.effects&&(V.effects.effect[e]||V.effects[e])?s.dpDiv.hide(e,V.datepicker._get(s,"showOptions"),i,t):s.dpDiv["slideDown"===e?"slideUp":"fadeIn"===e?"fadeOut":"hide"](e?i:null,t),e||t(),this._datepickerShowing=!1,(t=this._get(s,"onClose"))&&t.apply(s.input?s.input[0]:null,[s.input?s.input.val():"",s]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),V.blockUI&&(V.unblockUI(),V("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(t){var e;V.datepicker._curInst&&(e=V(t.target),t=V.datepicker._getInst(e[0]),(e[0].id===V.datepicker._mainDivId||0!==e.parents("#"+V.datepicker._mainDivId).length||e.hasClass(V.datepicker.markerClassName)||e.closest("."+V.datepicker._triggerClass).length||!V.datepicker._datepickerShowing||V.datepicker._inDialog&&V.blockUI)&&(!e.hasClass(V.datepicker.markerClassName)||V.datepicker._curInst===t)||V.datepicker._hideDatepicker())},_adjustDate:function(t,e,i){var s=V(t),t=this._getInst(s[0]);this._isDisabledDatepicker(s[0])||(this._adjustInstDate(t,e,i),this._updateDatepicker(t))},_gotoToday:function(t){var e=V(t),i=this._getInst(e[0]);this._get(i,"gotoCurrent")&&i.currentDay?(i.selectedDay=i.currentDay,i.drawMonth=i.selectedMonth=i.currentMonth,i.drawYear=i.selectedYear=i.currentYear):(t=new Date,i.selectedDay=t.getDate(),i.drawMonth=i.selectedMonth=t.getMonth(),i.drawYear=i.selectedYear=t.getFullYear()),this._notifyChange(i),this._adjustDate(e)},_selectMonthYear:function(t,e,i){var s=V(t),t=this._getInst(s[0]);t["selected"+("M"===i?"Month":"Year")]=t["draw"+("M"===i?"Month":"Year")]=parseInt(e.options[e.selectedIndex].value,10),this._notifyChange(t),this._adjustDate(s)},_selectDay:function(t,e,i,s){var n=V(t);V(s).hasClass(this._unselectableClass)||this._isDisabledDatepicker(n[0])||((n=this._getInst(n[0])).selectedDay=n.currentDay=parseInt(V("a",s).attr("data-date")),n.selectedMonth=n.currentMonth=e,n.selectedYear=n.currentYear=i,this._selectDate(t,this._formatDate(n,n.currentDay,n.currentMonth,n.currentYear)))},_clearDate:function(t){t=V(t);this._selectDate(t,"")},_selectDate:function(t,e){var i=V(t),t=this._getInst(i[0]);e=null!=e?e:this._formatDate(t),t.input&&t.input.val(e),this._updateAlternate(t),(i=this._get(t,"onSelect"))?i.apply(t.input?t.input[0]:null,[e,t]):t.input&&t.input.trigger("change"),t.inline?this._updateDatepicker(t):(this._hideDatepicker(),this._lastInput=t.input[0],"object"!=typeof t.input[0]&&t.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(t){var e,i,s=this._get(t,"altField");s&&(e=this._get(t,"altFormat")||this._get(t,"dateFormat"),i=this._getDate(t),t=this.formatDate(e,i,this._getFormatConfig(t)),V(document).find(s).val(t))},noWeekends:function(t){t=t.getDay();return[0<t&&t<6,""]},iso8601Week:function(t){var e=new Date(t.getTime());return e.setDate(e.getDate()+4-(e.getDay()||7)),t=e.getTime(),e.setMonth(0),e.setDate(1),Math.floor(Math.round((t-e)/864e5)/7)+1},parseDate:function(e,n,t){if(null==e||null==n)throw"Invalid arguments";if(""===(n="object"==typeof n?n.toString():n+""))return null;for(var i,s,o,a=0,r=(t?t.shortYearCutoff:null)||this._defaults.shortYearCutoff,r="string"!=typeof r?r:(new Date).getFullYear()%100+parseInt(r,10),l=(t?t.dayNamesShort:null)||this._defaults.dayNamesShort,h=(t?t.dayNames:null)||this._defaults.dayNames,c=(t?t.monthNamesShort:null)||this._defaults.monthNamesShort,u=(t?t.monthNames:null)||this._defaults.monthNames,d=-1,p=-1,f=-1,g=-1,m=!1,_=function(t){t=w+1<e.length&&e.charAt(w+1)===t;return t&&w++,t},v=function(t){var e=_(t),e="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,e=new RegExp("^\\d{"+("y"===t?e:1)+","+e+"}"),e=n.substring(a).match(e);if(!e)throw"Missing number at position "+a;return a+=e[0].length,parseInt(e[0],10)},b=function(t,e,i){var s=-1,e=V.map(_(t)?i:e,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(V.each(e,function(t,e){var i=e[1];if(n.substr(a,i.length).toLowerCase()===i.toLowerCase())return s=e[0],a+=i.length,!1}),-1!==s)return s+1;throw"Unknown name at position "+a},y=function(){if(n.charAt(a)!==e.charAt(w))throw"Unexpected literal at position "+a;a++},w=0;w<e.length;w++)if(m)"'"!==e.charAt(w)||_("'")?y():m=!1;else switch(e.charAt(w)){case"d":f=v("d");break;case"D":b("D",l,h);break;case"o":g=v("o");break;case"m":p=v("m");break;case"M":p=b("M",c,u);break;case"y":d=v("y");break;case"@":d=(o=new Date(v("@"))).getFullYear(),p=o.getMonth()+1,f=o.getDate();break;case"!":d=(o=new Date((v("!")-this._ticksTo1970)/1e4)).getFullYear(),p=o.getMonth()+1,f=o.getDate();break;case"'":_("'")?y():m=!0;break;default:y()}if(a<n.length&&(s=n.substr(a),!/^\s+/.test(s)))throw"Extra/unparsed characters found in date: "+s;if(-1===d?d=(new Date).getFullYear():d<100&&(d+=(new Date).getFullYear()-(new Date).getFullYear()%100+(d<=r?0:-100)),-1<g)for(p=1,f=g;;){if(f<=(i=this._getDaysInMonth(d,p-1)))break;p++,f-=i}if((o=this._daylightSavingAdjust(new Date(d,p-1,f))).getFullYear()!==d||o.getMonth()+1!==p||o.getDate()!==f)throw"Invalid date";return o},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*60*60*1e7,formatDate:function(e,t,i){if(!t)return"";function s(t,e,i){var s=""+e;if(c(t))for(;s.length<i;)s="0"+s;return s}function n(t,e,i,s){return(c(t)?s:i)[e]}var o,a=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,r=(i?i.dayNames:null)||this._defaults.dayNames,l=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,h=(i?i.monthNames:null)||this._defaults.monthNames,c=function(t){t=o+1<e.length&&e.charAt(o+1)===t;return t&&o++,t},u="",d=!1;if(t)for(o=0;o<e.length;o++)if(d)"'"!==e.charAt(o)||c("'")?u+=e.charAt(o):d=!1;else switch(e.charAt(o)){case"d":u+=s("d",t.getDate(),2);break;case"D":u+=n("D",t.getDay(),a,r);break;case"o":u+=s("o",Math.round((new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()-new Date(t.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=s("m",t.getMonth()+1,2);break;case"M":u+=n("M",t.getMonth(),l,h);break;case"y":u+=c("y")?t.getFullYear():(t.getFullYear()%100<10?"0":"")+t.getFullYear()%100;break;case"@":u+=t.getTime();break;case"!":u+=1e4*t.getTime()+this._ticksTo1970;break;case"'":c("'")?u+="'":d=!0;break;default:u+=e.charAt(o)}return u},_possibleChars:function(e){for(var t="",i=!1,s=function(t){t=n+1<e.length&&e.charAt(n+1)===t;return t&&n++,t},n=0;n<e.length;n++)if(i)"'"!==e.charAt(n)||s("'")?t+=e.charAt(n):i=!1;else switch(e.charAt(n)){case"d":case"m":case"y":case"@":t+="0123456789";break;case"D":case"M":return null;case"'":s("'")?t+="'":i=!0;break;default:t+=e.charAt(n)}return t},_get:function(t,e){return(void 0!==t.settings[e]?t.settings:this._defaults)[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(t){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(r,t,e){var i,s,t=null==t||""===t?e:"string"==typeof t?function(t){try{return V.datepicker.parseDate(V.datepicker._get(r,"dateFormat"),t,V.datepicker._getFormatConfig(r))}catch(t){}for(var e=(t.toLowerCase().match(/^c/)?V.datepicker._getDate(r):null)||new Date,i=e.getFullYear(),s=e.getMonth(),n=e.getDate(),o=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,a=o.exec(t);a;){switch(a[2]||"d"){case"d":case"D":n+=parseInt(a[1],10);break;case"w":case"W":n+=7*parseInt(a[1],10);break;case"m":case"M":s+=parseInt(a[1],10),n=Math.min(n,V.datepicker._getDaysInMonth(i,s));break;case"y":case"Y":i+=parseInt(a[1],10),n=Math.min(n,V.datepicker._getDaysInMonth(i,s))}a=o.exec(t)}return new Date(i,s,n)}(t):"number"==typeof t?isNaN(t)?e:(i=t,(s=new Date).setDate(s.getDate()+i),s):new Date(t.getTime());return(t=t&&"Invalid Date"===t.toString()?e:t)&&(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0)),this._daylightSavingAdjust(t)},_daylightSavingAdjust:function(t){return t?(t.setHours(12<t.getHours()?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,e=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=e.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=e.getMonth(),t.drawYear=t.selectedYear=t.currentYear=e.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){return!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay))},_attachHandlers:function(t){var e=this._get(t,"stepMonths"),i="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){V.datepicker._adjustDate(i,-e,"M")},next:function(){V.datepicker._adjustDate(i,+e,"M")},hide:function(){V.datepicker._hideDatepicker()},today:function(){V.datepicker._gotoToday(i)},selectDay:function(){return V.datepicker._selectDay(i,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return V.datepicker._selectMonthYear(i,this,"M"),!1},selectYear:function(){return V.datepicker._selectMonthYear(i,this,"Y"),!1}};V(this).on(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,l,h,c,u,d,p,f,g,m,_,v,b,y,w,x,k,C,D,I,T,P,M,S,H,z,A=new Date,O=this._daylightSavingAdjust(new Date(A.getFullYear(),A.getMonth(),A.getDate())),N=this._get(t,"isRTL"),E=this._get(t,"showButtonPanel"),W=this._get(t,"hideIfNoPrevNext"),F=this._get(t,"navigationAsDateFormat"),L=this._getNumberOfMonths(t),R=this._get(t,"showCurrentAtPos"),A=this._get(t,"stepMonths"),Y=1!==L[0]||1!==L[1],B=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),j=this._getMinMaxDate(t,"min"),q=this._getMinMaxDate(t,"max"),K=t.drawMonth-R,U=t.drawYear;if(K<0&&(K+=12,U--),q)for(e=this._daylightSavingAdjust(new Date(q.getFullYear(),q.getMonth()-L[0]*L[1]+1,q.getDate())),e=j&&e<j?j:e;this._daylightSavingAdjust(new Date(U,K,1))>e;)--K<0&&(K=11,U--);for(t.drawMonth=K,t.drawYear=U,R=this._get(t,"prevText"),R=F?this.formatDate(R,this._daylightSavingAdjust(new Date(U,K-A,1)),this._getFormatConfig(t)):R,i=this._canAdjustMonth(t,-1,U,K)?V("<a>").attr({class:"ui-datepicker-prev ui-corner-all","data-handler":"prev","data-event":"click",title:R}).append(V("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(N?"e":"w")).text(R))[0].outerHTML:W?"":V("<a>").attr({class:"ui-datepicker-prev ui-corner-all ui-state-disabled",title:R}).append(V("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(N?"e":"w")).text(R))[0].outerHTML,R=this._get(t,"nextText"),R=F?this.formatDate(R,this._daylightSavingAdjust(new Date(U,K+A,1)),this._getFormatConfig(t)):R,s=this._canAdjustMonth(t,1,U,K)?V("<a>").attr({class:"ui-datepicker-next ui-corner-all","data-handler":"next","data-event":"click",title:R}).append(V("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(N?"w":"e")).text(R))[0].outerHTML:W?"":V("<a>").attr({class:"ui-datepicker-next ui-corner-all ui-state-disabled",title:R}).append(V("<span>").attr("class","ui-icon ui-icon-circle-triangle-"+(N?"w":"e")).text(R))[0].outerHTML,A=this._get(t,"currentText"),W=this._get(t,"gotoCurrent")&&t.currentDay?B:O,A=F?this.formatDate(A,W,this._getFormatConfig(t)):A,R="",t.inline||(R=V("<button>").attr({type:"button",class:"ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all","data-handler":"hide","data-event":"click"}).text(this._get(t,"closeText"))[0].outerHTML),F="",E&&(F=V("<div class='ui-datepicker-buttonpane ui-widget-content'>").append(N?R:"").append(this._isInRange(t,W)?V("<button>").attr({type:"button",class:"ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all","data-handler":"today","data-event":"click"}).text(A):"").append(N?"":R)[0].outerHTML),n=parseInt(this._get(t,"firstDay"),10),n=isNaN(n)?0:n,o=this._get(t,"showWeek"),a=this._get(t,"dayNames"),r=this._get(t,"dayNamesMin"),l=this._get(t,"monthNames"),h=this._get(t,"monthNamesShort"),c=this._get(t,"beforeShowDay"),u=this._get(t,"showOtherMonths"),d=this._get(t,"selectOtherMonths"),p=this._getDefaultDate(t),f="",m=0;m<L[0];m++){for(_="",this.maxRows=4,v=0;v<L[1];v++){if(b=this._daylightSavingAdjust(new Date(U,K,t.selectedDay)),y=" ui-corner-all",w="",Y){if(w+="<div class='ui-datepicker-group",1<L[1])switch(v){case 0:w+=" ui-datepicker-group-first",y=" ui-corner-"+(N?"right":"left");break;case L[1]-1:w+=" ui-datepicker-group-last",y=" ui-corner-"+(N?"left":"right");break;default:w+=" ui-datepicker-group-middle",y=""}w+="'>"}for(w+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+y+"'>"+(/all|left/.test(y)&&0===m?N?s:i:"")+(/all|right/.test(y)&&0===m?N?i:s:"")+this._generateMonthYearHeader(t,K,U,j,q,0<m||0<v,l,h)+"</div><table class='ui-datepicker-calendar'><thead><tr>",x=o?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",g=0;g<7;g++)x+="<th scope='col'"+(5<=(g+n+6)%7?" class='ui-datepicker-week-end'":"")+"><span title='"+a[k=(g+n)%7]+"'>"+r[k]+"</span></th>";for(w+=x+"</tr></thead><tbody>",D=this._getDaysInMonth(U,K),U===t.selectedYear&&K===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,D)),C=(this._getFirstDayOfMonth(U,K)-n+7)%7,D=Math.ceil((C+D)/7),I=Y&&this.maxRows>D?this.maxRows:D,this.maxRows=I,T=this._daylightSavingAdjust(new Date(U,K,1-C)),P=0;P<I;P++){for(w+="<tr>",M=o?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(T)+"</td>":"",g=0;g<7;g++)S=c?c.apply(t.input?t.input[0]:null,[T]):[!0,""],z=(H=T.getMonth()!==K)&&!d||!S[0]||j&&T<j||q&&q<T,M+="<td class='"+(5<=(g+n+6)%7?" ui-datepicker-week-end":"")+(H?" ui-datepicker-other-month":"")+(T.getTime()===b.getTime()&&K===t.selectedMonth&&t._keyEvent||p.getTime()===T.getTime()&&p.getTime()===b.getTime()?" "+this._dayOverClass:"")+(z?" "+this._unselectableClass+" ui-state-disabled":"")+(H&&!u?"":" "+S[1]+(T.getTime()===B.getTime()?" "+this._currentClass:"")+(T.getTime()===O.getTime()?" ui-datepicker-today":""))+"'"+(H&&!u||!S[2]?"":" title='"+S[2].replace(/'/g,"&#39;")+"'")+(z?"":" data-handler='selectDay' data-event='click' data-month='"+T.getMonth()+"' data-year='"+T.getFullYear()+"'")+">"+(H&&!u?"&#xa0;":z?"<span class='ui-state-default'>"+T.getDate()+"</span>":"<a class='ui-state-default"+(T.getTime()===O.getTime()?" ui-state-highlight":"")+(T.getTime()===B.getTime()?" ui-state-active":"")+(H?" ui-priority-secondary":"")+"' href='#' aria-current='"+(T.getTime()===B.getTime()?"true":"false")+"' data-date='"+T.getDate()+"'>"+T.getDate()+"</a>")+"</td>",T.setDate(T.getDate()+1),T=this._daylightSavingAdjust(T);w+=M+"</tr>"}11<++K&&(K=0,U++),_+=w+="</tbody></table>"+(Y?"</div>"+(0<L[0]&&v===L[1]-1?"<div class='ui-datepicker-row-break'></div>":""):"")}f+=_}return f+=F,t._keyEvent=!1,f},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var l,h,c,u,d,p,f=this._get(t,"changeMonth"),g=this._get(t,"changeYear"),m=this._get(t,"showMonthAfterYear"),_=this._get(t,"selectMonthLabel"),v=this._get(t,"selectYearLabel"),b="<div class='ui-datepicker-title'>",y="";if(o||!f)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(l=s&&s.getFullYear()===i,h=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' aria-label='"+_+"' data-handler='selectMonth' data-event='change'>",c=0;c<12;c++)(!l||c>=s.getMonth())&&(!h||c<=n.getMonth())&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(m||(b+=y+(!o&&f&&g?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!g)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(a=this._get(t,"yearRange").split(":"),u=(new Date).getFullYear(),d=(_=function(t){t=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?u+parseInt(t,10):parseInt(t,10);return isNaN(t)?u:t})(a[0]),p=Math.max(d,_(a[1]||"")),d=s?Math.max(d,s.getFullYear()):d,p=n?Math.min(p,n.getFullYear()):p,t.yearshtml+="<select class='ui-datepicker-year' aria-label='"+v+"' data-handler='selectYear' data-event='change'>";d<=p;d++)t.yearshtml+="<option value='"+d+"'"+(d===i?" selected='selected'":"")+">"+d+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),m&&(b+=(!o&&f&&g?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),e=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),e=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,e)));t.selectedDay=e.getDate(),t.drawMonth=t.selectedMonth=e.getMonth(),t.drawYear=t.selectedYear=e.getFullYear(),"M"!==i&&"Y"!==i||this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),t=this._getMinMaxDate(t,"max"),e=i&&e<i?i:e;return t&&t<e?t:e},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){t=this._get(t,"numberOfMonths");return null==t?[1,1]:"number"==typeof t?[1,t]:t},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),n=this._daylightSavingAdjust(new Date(i,s+(e<0?e:n[0]*n[1]),1));return e<0&&n.setDate(this._getDaysInMonth(n.getFullYear(),n.getMonth())),this._isInRange(t,n)},_isInRange:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=null,o=null,a=this._get(t,"yearRange");return a&&(t=a.split(":"),a=(new Date).getFullYear(),n=parseInt(t[0],10),o=parseInt(t[1],10),t[0].match(/[+\-].*/)&&(n+=a),t[1].match(/[+\-].*/)&&(o+=a)),(!i||e.getTime()>=i.getTime())&&(!s||e.getTime()<=s.getTime())&&(!n||e.getFullYear()>=n)&&(!o||e.getFullYear()<=o)},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return{shortYearCutoff:e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);e=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),e,this._getFormatConfig(t))}}),V.fn.datepicker=function(t){if(!this.length)return this;V.datepicker.initialized||(V(document).on("mousedown",V.datepicker._checkExternalClick),V.datepicker.initialized=!0),0===V("#"+V.datepicker._mainDivId).length&&V("body").append(V.datepicker.dpDiv);var e=Array.prototype.slice.call(arguments,1);return"string"==typeof t&&("isDisabled"===t||"getDate"===t||"widget"===t)||"option"===t&&2===arguments.length&&"string"==typeof arguments[1]?V.datepicker["_"+t+"Datepicker"].apply(V.datepicker,[this[0]].concat(e)):this.each(function(){"string"==typeof t?V.datepicker["_"+t+"Datepicker"].apply(V.datepicker,[this].concat(e)):V.datepicker._attachDatepicker(this,t)})},V.datepicker=new st,V.datepicker.initialized=!1,V.datepicker.uuid=(new Date).getTime(),V.datepicker.version="1.13.2";V.datepicker,V.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var rt=!1;V(document).on("mouseup",function(){rt=!1});V.widget("ui.mouse",{version:"1.13.2",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(t){if(!0===V.data(t.target,e.widgetName+".preventClickEvent"))return V.removeData(t.target,e.widgetName+".preventClickEvent"),t.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!rt){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var e=this,i=1===t.which,s=!("string"!=typeof this.options.cancel||!t.target.nodeName)&&V(t.target).closest(this.options.cancel).length;return i&&!s&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=!1!==this._mouseStart(t),!this._mouseStarted)?(t.preventDefault(),!0):(!0===V.data(t.target,this.widgetName+".preventClickEvent")&&V.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return e._mouseMove(t)},this._mouseUpDelegate=function(t){return e._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),rt=!0)):!0}},_mouseMove:function(t){if(this._mouseMoved){if(V.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button)return this._mouseUp(t);if(!t.which)if(t.originalEvent.altKey||t.originalEvent.ctrlKey||t.originalEvent.metaKey||t.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(t)}return(t.which||t.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=!1!==this._mouseStart(this._mouseDownEvent,t),this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&V.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,rt=!1,t.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),V.ui.plugin={add:function(t,e,i){var s,n=V.ui[t].prototype;for(s in i)n.plugins[s]=n.plugins[s]||[],n.plugins[s].push([e,i[s]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;n<o.length;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},V.ui.safeBlur=function(t){t&&"body"!==t.nodeName.toLowerCase()&&V(t).trigger("blur")};V.widget("ui.draggable",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){(this.helper||this.element).is(".ui-draggable-dragging")?this.destroyOnClear=!0:(this._removeHandleClassName(),this._mouseDestroy())},_mouseCapture:function(t){var e=this.options;return!(this.helper||e.disabled||0<V(t.target).closest(".ui-resizable-handle").length)&&(this.handle=this._getHandle(t),!!this.handle&&(this._blurActiveElement(t),this._blockFrames(!0===e.iframeFix?"iframe":e.iframeFix),!0))},_blockFrames:function(t){this.iframeBlocks=this.document.find(t).map(function(){var t=V(this);return V("<div>").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var e=V.ui.safeActiveElement(this.document[0]);V(t.target).closest(e).length||V.ui.safeBlur(e)},_mouseStart:function(t){var e=this.options;return this.helper=this._createHelper(t),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),V.ui.ddmanager&&(V.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=0<this.helper.parents().filter(function(){return"fixed"===V(this).css("position")}).length,this.positionAbs=this.element.offset(),this._refreshOffsets(t),this.originalPosition=this.position=this._generatePosition(t,!1),this.originalPageX=t.pageX,this.originalPageY=t.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this._setContainment(),!1===this._trigger("start",t)?(this._clear(),!1):(this._cacheHelperProportions(),V.ui.ddmanager&&!e.dropBehaviour&&V.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),V.ui.ddmanager&&V.ui.ddmanager.dragStart(this,t),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(t,e){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t,!0),this.positionAbs=this._convertPositionTo("absolute"),!e){e=this._uiHash();if(!1===this._trigger("drag",t,e))return this._mouseUp(new V.Event("mouseup",t)),!1;this.position=e.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",V.ui.ddmanager&&V.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var e=this,i=!1;return V.ui.ddmanager&&!this.options.dropBehaviour&&(i=V.ui.ddmanager.drop(this,t)),this.dropped&&(i=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!i||"valid"===this.options.revert&&i||!0===this.options.revert||"function"==typeof this.options.revert&&this.options.revert.call(this.element,i)?V(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){!1!==e._trigger("stop",t)&&e._clear()}):!1!==this._trigger("stop",t)&&this._clear(),!1},_mouseUp:function(t){return this._unblockFrames(),V.ui.ddmanager&&V.ui.ddmanager.dragStop(this,t),this.handleElement.is(t.target)&&this.element.trigger("focus"),V.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new V.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(t){return!this.options.handle||!!V(t.target).closest(this.element.find(this.options.handle)).length},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(t){var e=this.options,i="function"==typeof e.helper,t=i?V(e.helper.apply(this.element[0],[t])):"clone"===e.helper?this.element.clone().removeAttr("id"):this.element;return t.parents("body").length||t.appendTo("parent"===e.appendTo?this.element[0].parentNode:e.appendTo),i&&t[0]===this.element[0]&&this._setPositionRelative(),t[0]===this.element[0]||/(fixed|absolute)/.test(t.css("position"))||t.css("position","absolute"),t},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),"left"in(t=Array.isArray(t)?{left:+t[0],top:+t[1]||0}:t)&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var t=this.offsetParent.offset(),e=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==e&&V.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),{top:(t=this._isRootNode(this.offsetParent[0])?{top:0,left:0}:t).top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,e,i,s=this.options,n=this.document[0];this.relativeContainer=null,s.containment?"window"!==s.containment?"document"!==s.containment?s.containment.constructor!==Array?("parent"===s.containment&&(s.containment=this.helper[0].parentNode),(i=(e=V(s.containment))[0])&&(t=/(scroll|auto)/.test(e.css("overflow")),this.containment=[(parseInt(e.css("borderLeftWidth"),10)||0)+(parseInt(e.css("paddingLeft"),10)||0),(parseInt(e.css("borderTopWidth"),10)||0)+(parseInt(e.css("paddingTop"),10)||0),(t?Math.max(i.scrollWidth,i.offsetWidth):i.offsetWidth)-(parseInt(e.css("borderRightWidth"),10)||0)-(parseInt(e.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(i.scrollHeight,i.offsetHeight):i.offsetHeight)-(parseInt(e.css("borderBottomWidth"),10)||0)-(parseInt(e.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=e)):this.containment=s.containment:this.containment=[0,0,V(n).width()-this.helperProportions.width-this.margins.left,(V(n).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]:this.containment=[V(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,V(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,V(window).scrollLeft()+V(window).width()-this.helperProportions.width-this.margins.left,V(window).scrollTop()+(V(window).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]:this.containment=null},_convertPositionTo:function(t,e){e=e||this.position;var i="absolute"===t?1:-1,t=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:t?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:t?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s=this.options,n=this._isRootNode(this.scrollParent[0]),o=t.pageX,a=t.pageY;return n&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(i=this.relativeContainer?(i=this.relativeContainer.offset(),[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]):this.containment,t.pageX-this.offset.click.left<i[0]&&(o=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(a=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(o=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(a=i[3]+this.offset.click.top)),s.grid&&(t=s.grid[1]?this.originalPageY+Math.round((a-this.originalPageY)/s.grid[1])*s.grid[1]:this.originalPageY,a=!i||t-this.offset.click.top>=i[1]||t-this.offset.click.top>i[3]?t:t-this.offset.click.top>=i[1]?t-s.grid[1]:t+s.grid[1],t=s.grid[0]?this.originalPageX+Math.round((o-this.originalPageX)/s.grid[0])*s.grid[0]:this.originalPageX,o=!i||t-this.offset.click.left>=i[0]||t-this.offset.click.left>i[2]?t:t-this.offset.click.left>=i[0]?t-s.grid[0]:t+s.grid[0]),"y"===s.axis&&(o=this.originalPageX),"x"===s.axis&&(a=this.originalPageY)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:n?0:this.offset.scroll.top),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:n?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(t,e,i){return i=i||this._uiHash(),V.ui.plugin.call(this,t,[e,i,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),i.offset=this.positionAbs),V.Widget.prototype._trigger.call(this,t,e,i)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),V.ui.plugin.add("draggable","connectToSortable",{start:function(e,t,i){var s=V.extend({},t,{item:i.element});i.sortables=[],V(i.options.connectToSortable).each(function(){var t=V(this).sortable("instance");t&&!t.options.disabled&&(i.sortables.push(t),t.refreshPositions(),t._trigger("activate",e,s))})},stop:function(e,t,i){var s=V.extend({},t,{item:i.element});i.cancelHelperRemoval=!1,V.each(i.sortables,function(){var t=this;t.isOver?(t.isOver=0,i.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,s))})},drag:function(i,s,n){V.each(n.sortables,function(){var t=!1,e=this;e.positionAbs=n.positionAbs,e.helperProportions=n.helperProportions,e.offset.click=n.offset.click,e._intersectsWith(e.containerCache)&&(t=!0,V.each(n.sortables,function(){return this.positionAbs=n.positionAbs,this.helperProportions=n.helperProportions,this.offset.click=n.offset.click,t=this!==e&&this._intersectsWith(this.containerCache)&&V.contains(e.element[0],this.element[0])?!1:t})),t?(e.isOver||(e.isOver=1,n._parent=s.helper.parent(),e.currentItem=s.helper.appendTo(e.element).data("ui-sortable-item",!0),e.options._helper=e.options.helper,e.options.helper=function(){return s.helper[0]},i.target=e.currentItem[0],e._mouseCapture(i,!0),e._mouseStart(i,!0,!0),e.offset.click.top=n.offset.click.top,e.offset.click.left=n.offset.click.left,e.offset.parent.left-=n.offset.parent.left-e.offset.parent.left,e.offset.parent.top-=n.offset.parent.top-e.offset.parent.top,n._trigger("toSortable",i),n.dropped=e.element,V.each(n.sortables,function(){this.refreshPositions()}),n.currentItem=n.element,e.fromOutside=n),e.currentItem&&(e._mouseDrag(i),s.position=e.position)):e.isOver&&(e.isOver=0,e.cancelHelperRemoval=!0,e.options._revert=e.options.revert,e.options.revert=!1,e._trigger("out",i,e._uiHash(e)),e._mouseStop(i,!0),e.options.revert=e.options._revert,e.options.helper=e.options._helper,e.placeholder&&e.placeholder.remove(),s.helper.appendTo(n._parent),n._refreshOffsets(i),s.position=n._generatePosition(i,!0),n._trigger("fromSortable",i),n.dropped=!1,V.each(n.sortables,function(){this.refreshPositions()}))})}}),V.ui.plugin.add("draggable","cursor",{start:function(t,e,i){var s=V("body"),i=i.options;s.css("cursor")&&(i._cursor=s.css("cursor")),s.css("cursor",i.cursor)},stop:function(t,e,i){i=i.options;i._cursor&&V("body").css("cursor",i._cursor)}}),V.ui.plugin.add("draggable","opacity",{start:function(t,e,i){e=V(e.helper),i=i.options;e.css("opacity")&&(i._opacity=e.css("opacity")),e.css("opacity",i.opacity)},stop:function(t,e,i){i=i.options;i._opacity&&V(e.helper).css("opacity",i._opacity)}}),V.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(t,e,i){var s=i.options,n=!1,o=i.scrollParentNotHidden[0],a=i.document[0];o!==a&&"HTML"!==o.tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+o.offsetHeight-t.pageY<s.scrollSensitivity?o.scrollTop=n=o.scrollTop+s.scrollSpeed:t.pageY-i.overflowOffset.top<s.scrollSensitivity&&(o.scrollTop=n=o.scrollTop-s.scrollSpeed)),s.axis&&"y"===s.axis||(i.overflowOffset.left+o.offsetWidth-t.pageX<s.scrollSensitivity?o.scrollLeft=n=o.scrollLeft+s.scrollSpeed:t.pageX-i.overflowOffset.left<s.scrollSensitivity&&(o.scrollLeft=n=o.scrollLeft-s.scrollSpeed))):(s.axis&&"x"===s.axis||(t.pageY-V(a).scrollTop()<s.scrollSensitivity?n=V(a).scrollTop(V(a).scrollTop()-s.scrollSpeed):V(window).height()-(t.pageY-V(a).scrollTop())<s.scrollSensitivity&&(n=V(a).scrollTop(V(a).scrollTop()+s.scrollSpeed))),s.axis&&"y"===s.axis||(t.pageX-V(a).scrollLeft()<s.scrollSensitivity?n=V(a).scrollLeft(V(a).scrollLeft()-s.scrollSpeed):V(window).width()-(t.pageX-V(a).scrollLeft())<s.scrollSensitivity&&(n=V(a).scrollLeft(V(a).scrollLeft()+s.scrollSpeed)))),!1!==n&&V.ui.ddmanager&&!s.dropBehaviour&&V.ui.ddmanager.prepareOffsets(i,t)}}),V.ui.plugin.add("draggable","snap",{start:function(t,e,i){var s=i.options;i.snapElements=[],V(s.snap.constructor!==String?s.snap.items||":data(ui-draggable)":s.snap).each(function(){var t=V(this),e=t.offset();this!==i.element[0]&&i.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:e.top,left:e.left})})},drag:function(t,e,i){for(var s,n,o,a,r,l,h,c,u,d=i.options,p=d.snapTolerance,f=e.offset.left,g=f+i.helperProportions.width,m=e.offset.top,_=m+i.helperProportions.height,v=i.snapElements.length-1;0<=v;v--)l=(r=i.snapElements[v].left-i.margins.left)+i.snapElements[v].width,c=(h=i.snapElements[v].top-i.margins.top)+i.snapElements[v].height,g<r-p||l+p<f||_<h-p||c+p<m||!V.contains(i.snapElements[v].item.ownerDocument,i.snapElements[v].item)?(i.snapElements[v].snapping&&i.options.snap.release&&i.options.snap.release.call(i.element,t,V.extend(i._uiHash(),{snapItem:i.snapElements[v].item})),i.snapElements[v].snapping=!1):("inner"!==d.snapMode&&(s=Math.abs(h-_)<=p,n=Math.abs(c-m)<=p,o=Math.abs(r-g)<=p,a=Math.abs(l-f)<=p,s&&(e.position.top=i._convertPositionTo("relative",{top:h-i.helperProportions.height,left:0}).top),n&&(e.position.top=i._convertPositionTo("relative",{top:c,left:0}).top),o&&(e.position.left=i._convertPositionTo("relative",{top:0,left:r-i.helperProportions.width}).left),a&&(e.position.left=i._convertPositionTo("relative",{top:0,left:l}).left)),u=s||n||o||a,"outer"!==d.snapMode&&(s=Math.abs(h-m)<=p,n=Math.abs(c-_)<=p,o=Math.abs(r-f)<=p,a=Math.abs(l-g)<=p,s&&(e.position.top=i._convertPositionTo("relative",{top:h,left:0}).top),n&&(e.position.top=i._convertPositionTo("relative",{top:c-i.helperProportions.height,left:0}).top),o&&(e.position.left=i._convertPositionTo("relative",{top:0,left:r}).left),a&&(e.position.left=i._convertPositionTo("relative",{top:0,left:l-i.helperProportions.width}).left)),!i.snapElements[v].snapping&&(s||n||o||a||u)&&i.options.snap.snap&&i.options.snap.snap.call(i.element,t,V.extend(i._uiHash(),{snapItem:i.snapElements[v].item})),i.snapElements[v].snapping=s||n||o||a||u)}}),V.ui.plugin.add("draggable","stack",{start:function(t,e,i){var s,i=i.options,i=V.makeArray(V(i.stack)).sort(function(t,e){return(parseInt(V(t).css("zIndex"),10)||0)-(parseInt(V(e).css("zIndex"),10)||0)});i.length&&(s=parseInt(V(i[0]).css("zIndex"),10)||0,V(i).each(function(t){V(this).css("zIndex",s+t)}),this.css("zIndex",s+i.length))}}),V.ui.plugin.add("draggable","zIndex",{start:function(t,e,i){e=V(e.helper),i=i.options;e.css("zIndex")&&(i._zIndex=e.css("zIndex")),e.css("zIndex",i.zIndex)},stop:function(t,e,i){i=i.options;i._zIndex&&V(e.helper).css("zIndex",i._zIndex)}});V.ui.draggable;V.widget("ui.resizable",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(t,e){if("hidden"===V(t).css("overflow"))return!1;var i=e&&"left"===e?"scrollLeft":"scrollTop",e=!1;if(0<t[i])return!0;try{t[i]=1,e=0<t[i],t[i]=0}catch(t){}return e},_create:function(){var t,e=this.options,i=this;this._addClass("ui-resizable"),V.extend(this,{_aspectRatio:!!e.aspectRatio,aspectRatio:e.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:e.helper||e.ghost||e.animate?e.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(V("<div class='ui-wrapper'></div>").css({overflow:"hidden",position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,t={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(t),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(t),this._proportionallyResize()),this._setupHandles(),e.autoHide&&V(this.element).on("mouseenter",function(){e.disabled||(i._removeClass("ui-resizable-autohide"),i._handles.show())}).on("mouseleave",function(){e.disabled||i.resizing||(i._addClass("ui-resizable-autohide"),i._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy(),this._addedHandles.remove();function t(t){V(t).removeData("resizable").removeData("ui-resizable").off(".resizable")}var e;return this.elementIsWrapper&&(t(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;case"aspectRatio":this._aspectRatio=!!e}},_setupHandles:function(){var t,e,i,s,n,o=this.options,a=this;if(this.handles=o.handles||(V(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=V(),this._addedHandles=V(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),i=this.handles.split(","),this.handles={},e=0;e<i.length;e++)s="ui-resizable-"+(t=String.prototype.trim.call(i[e])),n=V("<div>"),this._addClass(n,"ui-resizable-handle "+s),n.css({zIndex:o.zIndex}),this.handles[t]=".ui-resizable-"+t,this.element.children(this.handles[t]).length||(this.element.append(n),this._addedHandles=this._addedHandles.add(n));this._renderAxis=function(t){var e,i,s;for(e in t=t||this.element,this.handles)this.handles[e].constructor===String?this.handles[e]=this.element.children(this.handles[e]).first().show():(this.handles[e].jquery||this.handles[e].nodeType)&&(this.handles[e]=V(this.handles[e]),this._on(this.handles[e],{mousedown:a._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(i=V(this.handles[e],this.element),s=/sw|ne|nw|se|n|s/.test(e)?i.outerHeight():i.outerWidth(),i=["padding",/ne|nw|n/.test(e)?"Top":/se|sw|s/.test(e)?"Bottom":/^e$/.test(e)?"Right":"Left"].join(""),t.css(i,s),this._proportionallyResize()),this._handles=this._handles.add(this.handles[e])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){a.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),a.axis=n&&n[1]?n[1]:"se")}),o.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._addedHandles.remove()},_mouseCapture:function(t){var e,i,s=!1;for(e in this.handles)(i=V(this.handles[e])[0])!==t.target&&!V.contains(i,t.target)||(s=!0);return!this.options.disabled&&s},_mouseStart:function(t){var e,i,s=this.options,n=this.element;return this.resizing=!0,this._renderProxy(),e=this._num(this.helper.css("left")),i=this._num(this.helper.css("top")),s.containment&&(e+=V(s.containment).scrollLeft()||0,i+=V(s.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:e,top:i},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:n.width(),height:n.height()},this.originalSize=this._helper?{width:n.outerWidth(),height:n.outerHeight()}:{width:n.width(),height:n.height()},this.sizeDiff={width:n.outerWidth()-n.width(),height:n.outerHeight()-n.height()},this.originalPosition={left:e,top:i},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof s.aspectRatio?s.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=V(".ui-resizable-"+this.axis).css("cursor"),V("body").css("cursor","auto"===s?this.axis+"-resize":s),this._addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var e=this.originalMousePosition,i=this.axis,s=t.pageX-e.left||0,e=t.pageY-e.top||0,i=this._change[i];return this._updatePrevProperties(),i&&(e=i.apply(this,[t,s,e]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(e=this._updateRatio(e,t)),e=this._respectSize(e,t),this._updateCache(e),this._propagate("resize",t),e=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),V.isEmptyObject(e)||(this._updatePrevProperties(),this._trigger("resize",t,this.ui()),this._applyChanges())),!1},_mouseStop:function(t){this.resizing=!1;var e,i,s,n=this.options,o=this;return this._helper&&(s=(e=(i=this._proportionallyResizeElements).length&&/textarea/i.test(i[0].nodeName))&&this._hasScroll(i[0],"left")?0:o.sizeDiff.height,i=e?0:o.sizeDiff.width,e={width:o.helper.width()-i,height:o.helper.height()-s},i=parseFloat(o.element.css("left"))+(o.position.left-o.originalPosition.left)||null,s=parseFloat(o.element.css("top"))+(o.position.top-o.originalPosition.top)||null,n.animate||this.element.css(V.extend(e,{top:s,left:i})),o.helper.height(o.size.height),o.helper.width(o.size.width),this._helper&&!n.animate&&this._proportionallyResize()),V("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s=this.options,n={minWidth:this._isNumber(s.minWidth)?s.minWidth:0,maxWidth:this._isNumber(s.maxWidth)?s.maxWidth:1/0,minHeight:this._isNumber(s.minHeight)?s.minHeight:0,maxHeight:this._isNumber(s.maxHeight)?s.maxHeight:1/0};(this._aspectRatio||t)&&(e=n.minHeight*this.aspectRatio,i=n.minWidth/this.aspectRatio,s=n.maxHeight*this.aspectRatio,t=n.maxWidth/this.aspectRatio,e>n.minWidth&&(n.minWidth=e),i>n.minHeight&&(n.minHeight=i),s<n.maxWidth&&(n.maxWidth=s),t<n.maxHeight&&(n.maxHeight=t)),this._vBoundaries=n},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,l=this.originalPosition.top+this.originalSize.height,h=/sw|nw|w/.test(i),i=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&h&&(t.left=r-e.minWidth),s&&h&&(t.left=r-e.maxWidth),a&&i&&(t.top=l-e.minHeight),n&&i&&(t.top=l-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];e<4;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;e<this._proportionallyResizeElements.length;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var t=this.element,e=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||V("<div></div>").css({overflow:"hidden"}),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++e.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize;return{left:this.originalPosition.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize;return{top:this.originalPosition.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(t,e,i){return V.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},sw:function(t,e,i){return V.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,e,i]))},ne:function(t,e,i){return V.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},nw:function(t,e,i){return V.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,e,i]))}},_propagate:function(t,e){V.ui.plugin.call(this,t,[e,this.ui()]),"resize"!==t&&this._trigger(t,e,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),V.ui.plugin.add("resizable","animate",{stop:function(e){var i=V(this).resizable("instance"),t=i.options,s=i._proportionallyResizeElements,n=s.length&&/textarea/i.test(s[0].nodeName),o=n&&i._hasScroll(s[0],"left")?0:i.sizeDiff.height,a=n?0:i.sizeDiff.width,n={width:i.size.width-a,height:i.size.height-o},a=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,o=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(V.extend(n,o&&a?{top:o,left:a}:{}),{duration:t.animateDuration,easing:t.animateEasing,step:function(){var t={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};s&&s.length&&V(s[0]).css({width:t.width,height:t.height}),i._updateCache(t),i._propagate("resize",e)}})}}),V.ui.plugin.add("resizable","containment",{start:function(){var i,s,n=V(this).resizable("instance"),t=n.options,e=n.element,o=t.containment,a=o instanceof V?o.get(0):/parent/.test(o)?e.parent().get(0):o;a&&(n.containerElement=V(a),/document/.test(o)||o===document?(n.containerOffset={left:0,top:0},n.containerPosition={left:0,top:0},n.parentData={element:V(document),left:0,top:0,width:V(document).width(),height:V(document).height()||document.body.parentNode.scrollHeight}):(i=V(a),s=[],V(["Top","Right","Left","Bottom"]).each(function(t,e){s[t]=n._num(i.css("padding"+e))}),n.containerOffset=i.offset(),n.containerPosition=i.position(),n.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},t=n.containerOffset,e=n.containerSize.height,o=n.containerSize.width,o=n._hasScroll(a,"left")?a.scrollWidth:o,e=n._hasScroll(a)?a.scrollHeight:e,n.parentData={element:a,left:t.left,top:t.top,width:o,height:e}))},resize:function(t){var e=V(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.position,o=e._aspectRatio||t.shiftKey,a={top:0,left:0},r=e.containerElement,t=!0;r[0]!==document&&/static/.test(r.css("position"))&&(a=s),n.left<(e._helper?s.left:0)&&(e.size.width=e.size.width+(e._helper?e.position.left-s.left:e.position.left-a.left),o&&(e.size.height=e.size.width/e.aspectRatio,t=!1),e.position.left=i.helper?s.left:0),n.top<(e._helper?s.top:0)&&(e.size.height=e.size.height+(e._helper?e.position.top-s.top:e.position.top),o&&(e.size.width=e.size.height*e.aspectRatio,t=!1),e.position.top=e._helper?s.top:0),i=e.containerElement.get(0)===e.element.parent().get(0),n=/relative|absolute/.test(e.containerElement.css("position")),i&&n?(e.offset.left=e.parentData.left+e.position.left,e.offset.top=e.parentData.top+e.position.top):(e.offset.left=e.element.offset().left,e.offset.top=e.element.offset().top),n=Math.abs(e.sizeDiff.width+(e._helper?e.offset.left-a.left:e.offset.left-s.left)),s=Math.abs(e.sizeDiff.height+(e._helper?e.offset.top-a.top:e.offset.top-s.top)),n+e.size.width>=e.parentData.width&&(e.size.width=e.parentData.width-n,o&&(e.size.height=e.size.width/e.aspectRatio,t=!1)),s+e.size.height>=e.parentData.height&&(e.size.height=e.parentData.height-s,o&&(e.size.width=e.size.height*e.aspectRatio,t=!1)),t||(e.position.left=e.prevPosition.left,e.position.top=e.prevPosition.top,e.size.width=e.prevSize.width,e.size.height=e.prevSize.height)},stop:function(){var t=V(this).resizable("instance"),e=t.options,i=t.containerOffset,s=t.containerPosition,n=t.containerElement,o=V(t.helper),a=o.offset(),r=o.outerWidth()-t.sizeDiff.width,o=o.outerHeight()-t.sizeDiff.height;t._helper&&!e.animate&&/relative/.test(n.css("position"))&&V(this).css({left:a.left-s.left-i.left,width:r,height:o}),t._helper&&!e.animate&&/static/.test(n.css("position"))&&V(this).css({left:a.left-s.left-i.left,width:r,height:o})}}),V.ui.plugin.add("resizable","alsoResize",{start:function(){var t=V(this).resizable("instance").options;V(t.alsoResize).each(function(){var t=V(this);t.data("ui-resizable-alsoresize",{width:parseFloat(t.width()),height:parseFloat(t.height()),left:parseFloat(t.css("left")),top:parseFloat(t.css("top"))})})},resize:function(t,i){var e=V(this).resizable("instance"),s=e.options,n=e.originalSize,o=e.originalPosition,a={height:e.size.height-n.height||0,width:e.size.width-n.width||0,top:e.position.top-o.top||0,left:e.position.left-o.left||0};V(s.alsoResize).each(function(){var t=V(this),s=V(this).data("ui-resizable-alsoresize"),n={},e=t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];V.each(e,function(t,e){var i=(s[e]||0)+(a[e]||0);i&&0<=i&&(n[e]=i||null)}),t.css(n)})},stop:function(){V(this).removeData("ui-resizable-alsoresize")}}),V.ui.plugin.add("resizable","ghost",{start:function(){var t=V(this).resizable("instance"),e=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:e.height,width:e.width,margin:0,left:0,top:0}),t._addClass(t.ghost,"ui-resizable-ghost"),!1!==V.uiBackCompat&&"string"==typeof t.options.ghost&&t.ghost.addClass(this.options.ghost),t.ghost.appendTo(t.helper)},resize:function(){var t=V(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=V(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),V.ui.plugin.add("resizable","grid",{resize:function(){var t,e=V(this).resizable("instance"),i=e.options,s=e.size,n=e.originalSize,o=e.originalPosition,a=e.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,l=r[0]||1,h=r[1]||1,c=Math.round((s.width-n.width)/l)*l,u=Math.round((s.height-n.height)/h)*h,d=n.width+c,p=n.height+u,f=i.maxWidth&&i.maxWidth<d,g=i.maxHeight&&i.maxHeight<p,m=i.minWidth&&i.minWidth>d,s=i.minHeight&&i.minHeight>p;i.grid=r,m&&(d+=l),s&&(p+=h),f&&(d-=l),g&&(p-=h),/^(se|s|e)$/.test(a)?(e.size.width=d,e.size.height=p):/^(ne)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.top=o.top-u):/^(sw)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.left=o.left-c):((p-h<=0||d-l<=0)&&(t=e._getPaddingPlusBorderDimensions(this)),0<p-h?(e.size.height=p,e.position.top=o.top-u):(p=h-t.height,e.size.height=p,e.position.top=o.top+n.height-p),0<d-l?(e.size.width=d,e.position.left=o.left-c):(d=l-t.width,e.size.width=d,e.position.left=o.left+n.width-d))}});V.ui.resizable;V.widget("ui.dialog",{version:"1.13.2",options:{appendTo:"body",autoOpen:!0,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:!0,closeText:"Close",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var e=V(this).css(t).offset().top;e<0&&V(this).css("top",t.top-e)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),null==this.options.title&&null!=this.originalTitle&&(this.options.title=this.originalTitle),this.options.disabled&&(this.options.disabled=!1),this._createWrapper(),this.element.show().removeAttr("title").appendTo(this.uiDialog),this._addClass("ui-dialog-content","ui-widget-content"),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&V.fn.draggable&&this._makeDraggable(),this.options.resizable&&V.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?V(t):this.document.find(t||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().css(this.originalCss).detach(),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),(t=e.parent.children().eq(e.index)).length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog},disable:V.noop,enable:V.noop,close:function(t){var e=this;this._isOpen&&!1!==this._trigger("beforeClose",t)&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||V.ui.safeBlur(V.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){e._trigger("close",t)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(t,e){var i=!1,s=this.uiDialog.siblings(".ui-front:visible").map(function(){return+V(this).css("z-index")}).get(),s=Math.max.apply(null,s);return s>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",s+1),i=!0),i&&!e&&this._trigger("focus",t),i},open:function(){var t=this;this._isOpen?this._moveToTop()&&this._focusTabbable():(this._isOpen=!0,this.opener=V(V.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){t._focusTabbable(),t._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"))},_focusTabbable:function(){var t=this._focusedElement;(t=!(t=!(t=!(t=!(t=t||this.element.find("[autofocus]")).length?this.element.find(":tabbable"):t).length?this.uiDialogButtonPane.find(":tabbable"):t).length?this.uiDialogTitlebarClose.filter(":tabbable"):t).length?this.uiDialog:t).eq(0).trigger("focus")},_restoreTabbableFocus:function(){var t=V.ui.safeActiveElement(this.document[0]);this.uiDialog[0]===t||V.contains(this.uiDialog[0],t)||this._focusTabbable()},_keepFocus:function(t){t.preventDefault(),this._restoreTabbableFocus(),this._delay(this._restoreTabbableFocus)},_createWrapper:function(){this.uiDialog=V("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===V.ui.keyCode.ESCAPE)return t.preventDefault(),void this.close(t);var e,i,s;t.keyCode!==V.ui.keyCode.TAB||t.isDefaultPrevented()||(e=this.uiDialog.find(":tabbable"),i=e.first(),s=e.last(),t.target!==s[0]&&t.target!==this.uiDialog[0]||t.shiftKey?t.target!==i[0]&&t.target!==this.uiDialog[0]||!t.shiftKey||(this._delay(function(){s.trigger("focus")}),t.preventDefault()):(this._delay(function(){i.trigger("focus")}),t.preventDefault()))},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=V("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(t){V(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=V("<button type='button'></button>").button({label:V("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),t=V("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(t,"ui-dialog-title"),this._title(t),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=V("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=V("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var s=this,t=this.options.buttons;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),V.isEmptyObject(t)||Array.isArray(t)&&!t.length?this._removeClass(this.uiDialog,"ui-dialog-buttons"):(V.each(t,function(t,e){var i;e=V.extend({type:"button"},e="function"==typeof e?{click:e,text:t}:e),i=e.click,t={icon:e.icon,iconPosition:e.iconPosition,showLabel:e.showLabel,icons:e.icons,text:e.text},delete e.click,delete e.icon,delete e.iconPosition,delete e.showLabel,delete e.icons,"boolean"==typeof e.text&&delete e.text,V("<button></button>",e).button(t).appendTo(s.uiButtonSet).on("click",function(){i.apply(s.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog))},_makeDraggable:function(){var n=this,o=this.options;function a(t){return{position:t.position,offset:t.offset}}this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(t,e){n._addClass(V(this),"ui-dialog-dragging"),n._blockFrames(),n._trigger("dragStart",t,a(e))},drag:function(t,e){n._trigger("drag",t,a(e))},stop:function(t,e){var i=e.offset.left-n.document.scrollLeft(),s=e.offset.top-n.document.scrollTop();o.position={my:"left top",at:"left"+(0<=i?"+":"")+i+" top"+(0<=s?"+":"")+s,of:n.window},n._removeClass(V(this),"ui-dialog-dragging"),n._unblockFrames(),n._trigger("dragStop",t,a(e))}})},_makeResizable:function(){var n=this,o=this.options,t=o.resizable,e=this.uiDialog.css("position"),t="string"==typeof t?t:"n,e,s,w,se,sw,ne,nw";function a(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:o.maxWidth,maxHeight:o.maxHeight,minWidth:o.minWidth,minHeight:this._minHeight(),handles:t,start:function(t,e){n._addClass(V(this),"ui-dialog-resizing"),n._blockFrames(),n._trigger("resizeStart",t,a(e))},resize:function(t,e){n._trigger("resize",t,a(e))},stop:function(t,e){var i=n.uiDialog.offset(),s=i.left-n.document.scrollLeft(),i=i.top-n.document.scrollTop();o.height=n.uiDialog.height(),o.width=n.uiDialog.width(),o.position={my:"left top",at:"left"+(0<=s?"+":"")+s+" top"+(0<=i?"+":"")+i,of:n.window},n._removeClass(V(this),"ui-dialog-resizing"),n._unblockFrames(),n._trigger("resizeStop",t,a(e))}}).css("position",e)},_trackFocus:function(){this._on(this.widget(),{focusin:function(t){this._makeFocusTarget(),this._focusedElement=V(t.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var t=this._trackingInstances(),e=V.inArray(this,t);-1!==e&&t.splice(e,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||this.document.data("ui-dialog-instances",t=[]),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(t){var i=this,s=!1,n={};V.each(t,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(t,e){var i,s=this.uiDialog;"disabled"!==t&&(this._super(t,e),"appendTo"===t&&this.uiDialog.appendTo(this._appendTo()),"buttons"===t&&this._createButtons(),"closeText"===t&&this.uiDialogTitlebarClose.button({label:V("<a>").text(""+this.options.closeText).html()}),"draggable"===t&&((i=s.is(":data(ui-draggable)"))&&!e&&s.draggable("destroy"),!i&&e&&this._makeDraggable()),"position"===t&&this._position(),"resizable"===t&&((i=s.is(":data(ui-resizable)"))&&!e&&s.resizable("destroy"),i&&"string"==typeof e&&s.resizable("option","handles",e),i||!1===e||this._makeResizable()),"title"===t&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var t=V(this);return V("<div>").css({position:"absolute",width:t.outerWidth(),height:t.outerHeight()}).appendTo(t.parent()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(t){return!!V(t.target).closest(".ui-dialog").length||!!V(t.target).closest(".ui-datepicker").length},_createOverlay:function(){var i,s;this.options.modal&&(i=V.fn.jquery.substring(0,4),s=!0,this._delay(function(){s=!1}),this.document.data("ui-dialog-overlays")||this.document.on("focusin.ui-dialog",function(t){var e;s||((e=this._trackingInstances()[0])._allowInteraction(t)||(t.preventDefault(),e._focusTabbable(),"3.4."!==i&&"3.5."!==i||e._delay(e._restoreTabbableFocus)))}.bind(this)),this.overlay=V("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1))},_destroyOverlay:function(){var t;this.options.modal&&this.overlay&&((t=this.document.data("ui-dialog-overlays")-1)?this.document.data("ui-dialog-overlays",t):(this.document.off("focusin.ui-dialog"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null)}}),!1!==V.uiBackCompat&&V.widget("ui.dialog",V.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super(),this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(t,e){"dialogClass"===t&&this.uiDialog.removeClass(this.options.dialogClass).addClass(e),this._superApply(arguments)}});V.ui.dialog;function lt(t,e,i){return e<=t&&t<e+i}V.widget("ui.droppable",{version:"1.13.2",widgetEventPrefix:"drop",options:{accept:"*",addClasses:!0,greedy:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t,e=this.options,i=e.accept;this.isover=!1,this.isout=!0,this.accept="function"==typeof i?i:function(t){return t.is(i)},this.proportions=function(){if(!arguments.length)return t=t||{width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};t=arguments[0]},this._addToManager(e.scope),e.addClasses&&this._addClass("ui-droppable")},_addToManager:function(t){V.ui.ddmanager.droppables[t]=V.ui.ddmanager.droppables[t]||[],V.ui.ddmanager.droppables[t].push(this)},_splice:function(t){for(var e=0;e<t.length;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var t=V.ui.ddmanager.droppables[this.options.scope];this._splice(t)},_setOption:function(t,e){var i;"accept"===t?this.accept="function"==typeof e?e:function(t){return t.is(e)}:"scope"===t&&(i=V.ui.ddmanager.droppables[this.options.scope],this._splice(i),this._addToManager(e)),this._super(t,e)},_activate:function(t){var e=V.ui.ddmanager.current;this._addActiveClass(),e&&this._trigger("activate",t,this.ui(e))},_deactivate:function(t){var e=V.ui.ddmanager.current;this._removeActiveClass(),e&&this._trigger("deactivate",t,this.ui(e))},_over:function(t){var e=V.ui.ddmanager.current;e&&(e.currentItem||e.element)[0]!==this.element[0]&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this._addHoverClass(),this._trigger("over",t,this.ui(e)))},_out:function(t){var e=V.ui.ddmanager.current;e&&(e.currentItem||e.element)[0]!==this.element[0]&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this._removeHoverClass(),this._trigger("out",t,this.ui(e)))},_drop:function(e,t){var i=t||V.ui.ddmanager.current,s=!1;return!(!i||(i.currentItem||i.element)[0]===this.element[0])&&(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=V(this).droppable("instance");if(t.options.greedy&&!t.options.disabled&&t.options.scope===i.options.scope&&t.accept.call(t.element[0],i.currentItem||i.element)&&V.ui.intersect(i,V.extend(t,{offset:t.element.offset()}),t.options.tolerance,e))return!(s=!0)}),!s&&(!!this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(i)),this.element)))},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}}),V.ui.intersect=function(t,e,i,s){if(!e.offset)return!1;var n=(t.positionAbs||t.position.absolute).left+t.margins.left,o=(t.positionAbs||t.position.absolute).top+t.margins.top,a=n+t.helperProportions.width,r=o+t.helperProportions.height,l=e.offset.left,h=e.offset.top,c=l+e.proportions().width,u=h+e.proportions().height;switch(i){case"fit":return l<=n&&a<=c&&h<=o&&r<=u;case"intersect":return l<n+t.helperProportions.width/2&&a-t.helperProportions.width/2<c&&h<o+t.helperProportions.height/2&&r-t.helperProportions.height/2<u;case"pointer":return lt(s.pageY,h,e.proportions().height)&&lt(s.pageX,l,e.proportions().width);case"touch":return(h<=o&&o<=u||h<=r&&r<=u||o<h&&u<r)&&(l<=n&&n<=c||l<=a&&a<=c||n<l&&c<a);default:return!1}},!(V.ui.ddmanager={current:null,droppables:{default:[]},prepareOffsets:function(t,e){var i,s,n=V.ui.ddmanager.droppables[t.options.scope]||[],o=e?e.type:null,a=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();t:for(i=0;i<n.length;i++)if(!(n[i].options.disabled||t&&!n[i].accept.call(n[i].element[0],t.currentItem||t.element))){for(s=0;s<a.length;s++)if(a[s]===n[i].element[0]){n[i].proportions().height=0;continue t}n[i].visible="none"!==n[i].element.css("display"),n[i].visible&&("mousedown"===o&&n[i]._activate.call(n[i],e),n[i].offset=n[i].element.offset(),n[i].proportions({width:n[i].element[0].offsetWidth,height:n[i].element[0].offsetHeight}))}},drop:function(t,e){var i=!1;return V.each((V.ui.ddmanager.droppables[t.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&V.ui.intersect(t,this,this.options.tolerance,e)&&(i=this._drop.call(this,e)||i),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,e)))}),i},dragStart:function(t,e){t.element.parentsUntil("body").on("scroll.droppable",function(){t.options.refreshPositions||V.ui.ddmanager.prepareOffsets(t,e)})},drag:function(n,o){n.options.refreshPositions&&V.ui.ddmanager.prepareOffsets(n,o),V.each(V.ui.ddmanager.droppables[n.options.scope]||[],function(){var t,e,i,s;this.options.disabled||this.greedyChild||!this.visible||(s=!(i=V.ui.intersect(n,this,this.options.tolerance,o))&&this.isover?"isout":i&&!this.isover?"isover":null)&&(this.options.greedy&&(e=this.options.scope,(i=this.element.parents(":data(ui-droppable)").filter(function(){return V(this).droppable("instance").options.scope===e})).length&&((t=V(i[0]).droppable("instance")).greedyChild="isover"===s)),t&&"isover"===s&&(t.isover=!1,t.isout=!0,t._out.call(t,o)),this[s]=!0,this["isout"===s?"isover":"isout"]=!1,this["isover"===s?"_over":"_out"].call(this,o),t&&"isout"===s&&(t.isout=!1,t.isover=!0,t._over.call(t,o)))})},dragStop:function(t,e){t.element.parentsUntil("body").off("scroll.droppable"),t.options.refreshPositions||V.ui.ddmanager.prepareOffsets(t,e)}})!==V.uiBackCompat&&V.widget("ui.droppable",V.ui.droppable,{options:{hoverClass:!1,activeClass:!1},_addActiveClass:function(){this._super(),this.options.activeClass&&this.element.addClass(this.options.activeClass)},_removeActiveClass:function(){this._super(),this.options.activeClass&&this.element.removeClass(this.options.activeClass)},_addHoverClass:function(){this._super(),this.options.hoverClass&&this.element.addClass(this.options.hoverClass)},_removeHoverClass:function(){this._super(),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass)}});V.ui.droppable,V.widget("ui.progressbar",{version:"1.13.2",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.attr({role:"progressbar","aria-valuemin":this.min}),this._addClass("ui-progressbar","ui-widget ui-widget-content"),this.valueDiv=V("<div>").appendTo(this.element),this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header"),this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow"),this.valueDiv.remove()},value:function(t){if(void 0===t)return this.options.value;this.options.value=this._constrainedValue(t),this._refreshValue()},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=!1===t,"number"!=typeof t&&(t=0),!this.indeterminate&&Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var t=this.options.value,e=this._percentage();this.valueDiv.toggle(this.indeterminate||t>this.min).width(e.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,t===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=V("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":t}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==t&&(this.oldValue=t,this._trigger("change")),t===this.options.max&&this._trigger("complete")}}),V.widget("ui.selectable",V.ui.mouse,{version:"1.13.2",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var i=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){i.elementPos=V(i.element[0]).offset(),i.selectees=V(i.options.filter,i.element[0]),i._addClass(i.selectees,"ui-selectee"),i.selectees.each(function(){var t=V(this),e=t.offset(),e={left:e.left-i.elementPos.left,top:e.top-i.elementPos.top};V.data(this,"selectable-item",{element:this,$element:t,left:e.left,top:e.top,right:e.left+t.outerWidth(),bottom:e.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=V("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(i){var s=this,t=this.options;this.opos=[i.pageX,i.pageY],this.elementPos=V(this.element[0]).offset(),this.options.disabled||(this.selectees=V(t.filter,this.element[0]),this._trigger("start",i),V(t.appendTo).append(this.helper),this.helper.css({left:i.pageX,top:i.pageY,width:0,height:0}),t.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var t=V.data(this,"selectable-item");t.startselected=!0,i.metaKey||i.ctrlKey||(s._removeClass(t.$element,"ui-selected"),t.selected=!1,s._addClass(t.$element,"ui-unselecting"),t.unselecting=!0,s._trigger("unselecting",i,{unselecting:t.element}))}),V(i.target).parents().addBack().each(function(){var t,e=V.data(this,"selectable-item");if(e)return t=!i.metaKey&&!i.ctrlKey||!e.$element.hasClass("ui-selected"),s._removeClass(e.$element,t?"ui-unselecting":"ui-selected")._addClass(e.$element,t?"ui-selecting":"ui-unselecting"),e.unselecting=!t,e.selecting=t,(e.selected=t)?s._trigger("selecting",i,{selecting:e.element}):s._trigger("unselecting",i,{unselecting:e.element}),!1}))},_mouseDrag:function(s){if(this.dragged=!0,!this.options.disabled){var t,n=this,o=this.options,a=this.opos[0],r=this.opos[1],l=s.pageX,h=s.pageY;return l<a&&(t=l,l=a,a=t),h<r&&(t=h,h=r,r=t),this.helper.css({left:a,top:r,width:l-a,height:h-r}),this.selectees.each(function(){var t=V.data(this,"selectable-item"),e=!1,i={};t&&t.element!==n.element[0]&&(i.left=t.left+n.elementPos.left,i.right=t.right+n.elementPos.left,i.top=t.top+n.elementPos.top,i.bottom=t.bottom+n.elementPos.top,"touch"===o.tolerance?e=!(i.left>l||i.right<a||i.top>h||i.bottom<r):"fit"===o.tolerance&&(e=i.left>a&&i.right<l&&i.top>r&&i.bottom<h),e?(t.selected&&(n._removeClass(t.$element,"ui-selected"),t.selected=!1),t.unselecting&&(n._removeClass(t.$element,"ui-unselecting"),t.unselecting=!1),t.selecting||(n._addClass(t.$element,"ui-selecting"),t.selecting=!0,n._trigger("selecting",s,{selecting:t.element}))):(t.selecting&&((s.metaKey||s.ctrlKey)&&t.startselected?(n._removeClass(t.$element,"ui-selecting"),t.selecting=!1,n._addClass(t.$element,"ui-selected"),t.selected=!0):(n._removeClass(t.$element,"ui-selecting"),t.selecting=!1,t.startselected&&(n._addClass(t.$element,"ui-unselecting"),t.unselecting=!0),n._trigger("unselecting",s,{unselecting:t.element}))),t.selected&&(s.metaKey||s.ctrlKey||t.startselected||(n._removeClass(t.$element,"ui-selected"),t.selected=!1,n._addClass(t.$element,"ui-unselecting"),t.unselecting=!0,n._trigger("unselecting",s,{unselecting:t.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,V(".ui-unselecting",this.element[0]).each(function(){var t=V.data(this,"selectable-item");i._removeClass(t.$element,"ui-unselecting"),t.unselecting=!1,t.startselected=!1,i._trigger("unselected",e,{unselected:t.element})}),V(".ui-selecting",this.element[0]).each(function(){var t=V.data(this,"selectable-item");i._removeClass(t.$element,"ui-selecting")._addClass(t.$element,"ui-selected"),t.selecting=!1,t.selected=!0,t.startselected=!0,i._trigger("selected",e,{selected:t.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),V.widget("ui.selectmenu",[V.ui.formResetMixin,{version:"1.13.2",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:!1,change:null,close:null,focus:null,open:null,select:null},_create:function(){var t=this.element.uniqueId().attr("id");this.ids={element:t,button:t+"-button",menu:t+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=V()},_drawButton:function(){var t,e=this,i=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button),this._on(this.labels,{click:function(t){this.button.trigger("focus"),t.preventDefault()}}),this.element.hide(),this.button=V("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element),this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget"),t=V("<span>").appendTo(this.button),this._addClass(t,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(i).appendTo(this.button),!1!==this.options.width&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){e._rendered||e._refreshMenu()})},_drawMenu:function(){var i=this;this.menu=V("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=V("<div>").append(this.menu),this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front"),this.menuWrap.appendTo(this._appendTo()),this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(t,e){t.preventDefault(),i._setSelection(),i._select(e.item.data("ui-selectmenu-item"),t)},focus:function(t,e){e=e.item.data("ui-selectmenu-item");null!=i.focusIndex&&e.index!==i.focusIndex&&(i._trigger("focus",t,{item:e}),i.isOpen||i._select(e,t)),i.focusIndex=e.index,i.button.attr("aria-activedescendant",i.menuItems.eq(e.index).attr("id"))}}).menu("instance"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{})),null===this.options.width&&this._resizeButton()},_refreshMenu:function(){var t=this.element.find("option");this.menu.empty(),this._parseOptions(t),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper"),this._rendered=!0,t.length&&(t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){this.options.disabled||(this._rendered?(this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.menuItems.length&&(this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t)))},_position:function(){this.menuWrap.position(V.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(t){var e=V("<span>");return this._setText(e,t.label),this._addClass(e,"ui-selectmenu-text"),e},_renderMenu:function(s,t){var n=this,o="";V.each(t,function(t,e){var i;e.optgroup!==o&&(i=V("<li>",{text:e.optgroup}),n._addClass(i,"ui-selectmenu-optgroup","ui-menu-divider"+(e.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),i.appendTo(s),o=e.optgroup),n._renderItemData(s,e)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(t,e){var i=V("<li>"),s=V("<div>",{title:e.element.attr("title")});return e.disabled&&this._addClass(i,null,"ui-state-disabled"),this._setText(s,e.label),i.append(s).appendTo(t)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),s+=":not(.ui-state-disabled)"),(s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](s).eq(-1):i[t+"All"](s).eq(0)).length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&(window.getSelection?((t=window.getSelection()).removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.trigger("focus"))},_documentClick:{mousedown:function(t){this.isOpen&&(V(t.target).closest(".ui-selectmenu-menu, #"+V.escapeSelector(this.ids.button)).length||this.close(t))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection()).rangeCount&&(this.range=t.getRangeAt(0)):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(t){var e=!0;switch(t.keyCode){case V.ui.keyCode.TAB:case V.ui.keyCode.ESCAPE:this.close(t),e=!1;break;case V.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(t);break;case V.ui.keyCode.UP:t.altKey?this._toggle(t):this._move("prev",t);break;case V.ui.keyCode.DOWN:t.altKey?this._toggle(t):this._move("next",t);break;case V.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(t):this._toggle(t);break;case V.ui.keyCode.LEFT:this._move("prev",t);break;case V.ui.keyCode.RIGHT:this._move("next",t);break;case V.ui.keyCode.HOME:case V.ui.keyCode.PAGE_UP:this._move("first",t);break;case V.ui.keyCode.END:case V.ui.keyCode.PAGE_DOWN:this._move("last",t);break;default:this.menu.trigger(t),e=!1}e&&t.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex).parent("li");e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(t)),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){t=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":t,"aria-activedescendant":t}),this.menu.attr("aria-activedescendant",t)},_setOption:function(t,e){var i;"icons"===t&&(i=this.button.find("span.ui-icon"),this._removeClass(i,null,this.options.icons.button)._addClass(i,null,e.button)),this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"width"===t&&this._resizeButton()},_setOptionDisabled:function(t){this._super(t),this.menuInstance.option("disabled",t),this.button.attr("aria-disabled",t),this._toggleClass(this.button,null,"ui-state-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)},_appendTo:function(){var t=this.options.appendTo;return t=!(t=!(t=t&&(t.jquery||t.nodeType?V(t):this.document.find(t).eq(0)))||!t[0]?this.element.closest(".ui-front, dialog"):t).length?this.document[0].body:t},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen),this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;!1!==t?(null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t)):this.button.css("width","")},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){var t=this._super();return t.disabled=this.element.prop("disabled"),t},_parseOptions:function(t){var i=this,s=[];t.each(function(t,e){e.hidden||s.push(i._parseOption(V(e),t))}),this.items=s},_parseOption:function(t,e){var i=t.parent("optgroup");return{element:t,index:e,value:t.val(),label:t.text(),optgroup:i.attr("label")||"",disabled:i.prop("disabled")||t.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler(),this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.labels.attr("for",this.ids.element)}}]),V.widget("ui.slider",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var t,e=this.options,i=this.element.find(".ui-slider-handle"),s=[],n=e.values&&e.values.length||1;for(i.length>n&&(i.slice(n).remove(),i=i.slice(0,n)),t=i.length;t<n;t++)s.push("<span tabindex='0'></span>");this.handles=i.add(V(s.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(t){V(this).data("ui-slider-handle-index",t).attr("tabIndex",0)})},_createRange:function(){var t=this.options;t.range?(!0===t.range&&(t.values?t.values.length&&2!==t.values.length?t.values=[t.values[0],t.values[0]]:Array.isArray(t.values)&&(t.values=t.values.slice(0)):t.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=V("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),"min"!==t.range&&"max"!==t.range||this._addClass(this.range,"ui-slider-range-"+t.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(t){var i,s,n,o,e,a,r=this,l=this.options;return!l.disabled&&(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),a={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(a),s=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var e=Math.abs(i-r.values(t));(e<s||s===e&&(t===r._lastChangedValue||r.values(t)===l.min))&&(s=e,n=V(this),o=t)}),!1!==this._start(t,o)&&(this._mouseSliding=!0,this._handleIndex=o,this._addClass(n,null,"ui-state-active"),n.trigger("focus"),e=n.offset(),a=!V(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=a?{left:0,top:0}:{left:t.pageX-e.left-n.width()/2,top:t.pageY-e.top-n.height()/2-(parseInt(n.css("borderTopWidth"),10)||0)-(parseInt(n.css("borderBottomWidth"),10)||0)+(parseInt(n.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,i),this._animateOff=!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},e=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,e),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,t="horizontal"===this.orientation?(e=this.elementSize.width,t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),t=t/e;return(t=1<t?1:t)<0&&(t=0),"vertical"===this.orientation&&(t=1-t),e=this._valueMax()-this._valueMin(),e=this._valueMin()+t*e,this._trimAlignValue(e)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n=this.value(),o=this.values();this._hasMultipleValues()&&(s=this.values(e?0:1),n=this.values(e),2===this.options.values.length&&!0===this.options.range&&(i=0===e?Math.min(s,i):Math.max(s,i)),o[e]=i),i!==n&&!1!==this._trigger("slide",t,this._uiHash(e,i,o))&&(this._hasMultipleValues()?this.values(e,i):this.value(i))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),void this._change(null,0)):this._value()},values:function(t,e){var i,s,n;if(1<arguments.length)return this.options.values[t]=this._trimAlignValue(e),this._refreshValue(),void this._change(null,t);if(!arguments.length)return this._values();if(!Array.isArray(t))return this._hasMultipleValues()?this._values(t):this.value();for(i=this.options.values,s=t,n=0;n<i.length;n+=1)i[n]=this._trimAlignValue(s[n]),this._change(null,n);this._refreshValue()},_setOption:function(t,e){var i,s=0;switch("range"===t&&!0===this.options.range&&("min"===e?(this.options.value=this._values(0),this.options.values=null):"max"===e&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),Array.isArray(this.options.values)&&(s=this.options.values.length),this._super(t,e),t){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(e),this.handles.css("horizontal"===e?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),i=s-1;0<=i;i--)this._change(null,i);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(t){this._super(t),this._toggleClass(null,"ui-state-disabled",!!t)},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i;if(arguments.length)return t=this.options.values[t],t=this._trimAlignValue(t);if(this._hasMultipleValues()){for(e=this.options.values.slice(),i=0;i<e.length;i+=1)e[i]=this._trimAlignValue(e[i]);return e}return[]},_trimAlignValue:function(t){if(t<=this._valueMin())return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=0<this.options.step?this.options.step:1,i=(t-this._valueMin())%e,t=t-i;return 2*Math.abs(i)>=e&&(t+=0<i?e:-e),parseFloat(t.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step;(t=Math.round((t-e)/i)*i+e)>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return t=null!==this.options.min?Math.max(t,this._precisionOf(this.options.min)):t},_precisionOf:function(t){var e=t.toString(),t=e.indexOf(".");return-1===t?0:e.length-t-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(t){"vertical"===t&&this.range.css({width:"",left:""}),"horizontal"===t&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var e,i,t,s,n,o=this.options.range,a=this.options,r=this,l=!this._animateOff&&a.animate,h={};this._hasMultipleValues()?this.handles.each(function(t){i=(r.values(t)-r._valueMin())/(r._valueMax()-r._valueMin())*100,h["horizontal"===r.orientation?"left":"bottom"]=i+"%",V(this).stop(1,1)[l?"animate":"css"](h,a.animate),!0===r.options.range&&("horizontal"===r.orientation?(0===t&&r.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},a.animate),1===t&&r.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:a.animate})):(0===t&&r.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},a.animate),1===t&&r.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:a.animate}))),e=i}):(t=this.value(),s=this._valueMin(),n=this._valueMax(),i=n!==s?(t-s)/(n-s)*100:0,h["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](h,a.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},a.animate),"max"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:100-i+"%"},a.animate),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},a.animate),"max"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:100-i+"%"},a.animate))},_handleEvents:{keydown:function(t){var e,i,s,n=V(t.target).data("ui-slider-handle-index");switch(t.keyCode){case V.ui.keyCode.HOME:case V.ui.keyCode.END:case V.ui.keyCode.PAGE_UP:case V.ui.keyCode.PAGE_DOWN:case V.ui.keyCode.UP:case V.ui.keyCode.RIGHT:case V.ui.keyCode.DOWN:case V.ui.keyCode.LEFT:if(t.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(V(t.target),null,"ui-state-active"),!1===this._start(t,n)))return}switch(s=this.options.step,e=i=this._hasMultipleValues()?this.values(n):this.value(),t.keyCode){case V.ui.keyCode.HOME:i=this._valueMin();break;case V.ui.keyCode.END:i=this._valueMax();break;case V.ui.keyCode.PAGE_UP:i=this._trimAlignValue(e+(this._valueMax()-this._valueMin())/this.numPages);break;case V.ui.keyCode.PAGE_DOWN:i=this._trimAlignValue(e-(this._valueMax()-this._valueMin())/this.numPages);break;case V.ui.keyCode.UP:case V.ui.keyCode.RIGHT:if(e===this._valueMax())return;i=this._trimAlignValue(e+s);break;case V.ui.keyCode.DOWN:case V.ui.keyCode.LEFT:if(e===this._valueMin())return;i=this._trimAlignValue(e-s)}this._slide(t,n,i)},keyup:function(t){var e=V(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,e),this._change(t,e),this._removeClass(V(t.target),null,"ui-state-active"))}}}),V.widget("ui.sortable",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return e<=t&&t<e+i},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var t=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),V.each(this.items,function(){t._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;0<=t;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(t,e){var i=null,s=!1,n=this;return!this.reverting&&(!this.options.disabled&&"static"!==this.options.type&&(this._refreshItems(t),V(t.target).parents().each(function(){if(V.data(this,n.widgetName+"-item")===n)return i=V(this),!1}),!!(i=V.data(t.target,n.widgetName+"-item")===n?V(t.target):i)&&(!(this.options.handle&&!e&&(V(this.options.handle,i).find("*").addBack().each(function(){this===t.target&&(s=!0)}),!s))&&(this.currentItem=i,this._removeCurrentsFromItems(),!0))))},_mouseStart:function(t,e,i){var s,n,o=this.options;if((this.currentContainer=this).refreshPositions(),this.appendTo=V("parent"!==o.appendTo?o.appendTo:this.currentItem.parent()),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},V.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),this.scrollParent=this.placeholder.scrollParent(),V.extend(this.offset,{parent:this._getParentOffset()}),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(n=this.document.find("body"),this.storedCursor=n.css("cursor"),n.css("cursor",o.cursor),this.storedStylesheet=V("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(n)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!i)for(s=this.containers.length-1;0<=s;s--)this.containers[s]._trigger("activate",t,this._uiHash(this));return V.ui.ddmanager&&(V.ui.ddmanager.current=this),V.ui.ddmanager&&!o.dropBehaviour&&V.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this.helper.parent().is(this.appendTo)||(this.helper.detach().appendTo(this.appendTo),this.offset.parent=this._getParentOffset()),this.position=this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,this.lastPositionAbs=this.positionAbs=this._convertPositionTo("absolute"),this._mouseDrag(t),!0},_scroll:function(t){var e=this.options,i=!1;return this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<e.scrollSensitivity?this.scrollParent[0].scrollTop=i=this.scrollParent[0].scrollTop+e.scrollSpeed:t.pageY-this.overflowOffset.top<e.scrollSensitivity&&(this.scrollParent[0].scrollTop=i=this.scrollParent[0].scrollTop-e.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<e.scrollSensitivity?this.scrollParent[0].scrollLeft=i=this.scrollParent[0].scrollLeft+e.scrollSpeed:t.pageX-this.overflowOffset.left<e.scrollSensitivity&&(this.scrollParent[0].scrollLeft=i=this.scrollParent[0].scrollLeft-e.scrollSpeed)):(t.pageY-this.document.scrollTop()<e.scrollSensitivity?i=this.document.scrollTop(this.document.scrollTop()-e.scrollSpeed):this.window.height()-(t.pageY-this.document.scrollTop())<e.scrollSensitivity&&(i=this.document.scrollTop(this.document.scrollTop()+e.scrollSpeed)),t.pageX-this.document.scrollLeft()<e.scrollSensitivity?i=this.document.scrollLeft(this.document.scrollLeft()-e.scrollSpeed):this.window.width()-(t.pageX-this.document.scrollLeft())<e.scrollSensitivity&&(i=this.document.scrollLeft(this.document.scrollLeft()+e.scrollSpeed))),i},_mouseDrag:function(t){var e,i,s,n,o=this.options;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),o.scroll&&!1!==this._scroll(t)&&(this._refreshItemPositions(!0),V.ui.ddmanager&&!o.dropBehaviour&&V.ui.ddmanager.prepareOffsets(this,t)),this.dragDirection={vertical:this._getDragVerticalDirection(),horizontal:this._getDragHorizontalDirection()},e=this.items.length-1;0<=e;e--)if(s=(i=this.items[e]).item[0],(n=this._intersectsWithPointer(i))&&i.instance===this.currentContainer&&!(s===this.currentItem[0]||this.placeholder[1===n?"next":"prev"]()[0]===s||V.contains(this.placeholder[0],s)||"semi-dynamic"===this.options.type&&V.contains(this.element[0],s))){if(this.direction=1===n?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(i))break;this._rearrange(t,i),this._trigger("change",t,this._uiHash());break}return this._contactContainers(t),V.ui.ddmanager&&V.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,e){var i,s,n,o;if(t)return V.ui.ddmanager&&!this.options.dropBehaviour&&V.ui.ddmanager.drop(this,t),this.options.revert?(s=(i=this).placeholder.offset(),o={},(n=this.options.axis)&&"x"!==n||(o.left=s.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),n&&"y"!==n||(o.top=s.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,V(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){i._clear(t)})):this._clear(t,e),!1},cancel:function(){if(this.dragging){this._mouseUp(new V.Event("mouseup",{target:null})),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var t=this.containers.length-1;0<=t;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),V.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?V(this.domPosition.prev).after(this.currentItem):V(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var t=this._getItemsAsjQuery(e&&e.connected),i=[];return e=e||{},V(t).each(function(){var t=(V(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);t&&i.push((e.key||t[1]+"[]")+"="+(e.key&&e.expression?t[1]:t[2]))}),!i.length&&e.key&&i.push(e.key+"="),i.join("&")},toArray:function(t){var e=this._getItemsAsjQuery(t&&t.connected),i=[];return t=t||{},e.each(function(){i.push(V(t.item||this).attr(t.attribute||"id")||"")}),i},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,l=r+t.height,h=this.offset.click.top,c=this.offset.click.left,h="x"===this.options.axis||r<s+h&&s+h<l,c="y"===this.options.axis||o<e+c&&e+c<a;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?h&&c:o<e+this.helperProportions.width/2&&i-this.helperProportions.width/2<a&&r<s+this.helperProportions.height/2&&n-this.helperProportions.height/2<l},_intersectsWithPointer:function(t){var e="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),t="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width);return!(!e||!t)&&(e=this.dragDirection.vertical,t=this.dragDirection.horizontal,this.floating?"right"===t||"down"===e?2:1:e&&("down"===e?2:1))},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this.dragDirection.vertical,t=this.dragDirection.horizontal;return this.floating&&t?"right"===t&&i||"left"===t&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!=t&&(0<t?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!=t&&(0<t?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(t){var e,i,s,n,o=[],a=[],r=this._connectWith();if(r&&t)for(e=r.length-1;0<=e;e--)for(i=(s=V(r[e],this.document[0])).length-1;0<=i;i--)(n=V.data(s[i],this.widgetFullName))&&n!==this&&!n.options.disabled&&a.push(["function"==typeof n.options.items?n.options.items.call(n.element):V(n.options.items,n.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),n]);function l(){o.push(this)}for(a.push(["function"==typeof this.options.items?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):V(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),e=a.length-1;0<=e;e--)a[e][0].each(l);return V(o)},_removeCurrentsFromItems:function(){var i=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=V.grep(this.items,function(t){for(var e=0;e<i.length;e++)if(i[e]===t.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var e,i,s,n,o,a,r,l,h=this.items,c=[["function"==typeof this.options.items?this.options.items.call(this.element[0],t,{item:this.currentItem}):V(this.options.items,this.element),this]],u=this._connectWith();if(u&&this.ready)for(e=u.length-1;0<=e;e--)for(i=(s=V(u[e],this.document[0])).length-1;0<=i;i--)(n=V.data(s[i],this.widgetFullName))&&n!==this&&!n.options.disabled&&(c.push(["function"==typeof n.options.items?n.options.items.call(n.element[0],t,{item:this.currentItem}):V(n.options.items,n.element),n]),this.containers.push(n));for(e=c.length-1;0<=e;e--)for(o=c[e][1],l=(a=c[e][i=0]).length;i<l;i++)(r=V(a[i])).data(this.widgetName+"-item",o),h.push({item:r,instance:o,width:0,height:0,left:0,top:0})},_refreshItemPositions:function(t){for(var e,i,s=this.items.length-1;0<=s;s--)e=this.items[s],this.currentContainer&&e.instance!==this.currentContainer&&e.item[0]!==this.currentItem[0]||(i=this.options.toleranceElement?V(this.options.toleranceElement,e.item):e.item,t||(e.width=i.outerWidth(),e.height=i.outerHeight()),i=i.offset(),e.left=i.left,e.top=i.top)},refreshPositions:function(t){var e,i;if(this.floating=!!this.items.length&&("x"===this.options.axis||this._isFloating(this.items[0].item)),this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset()),this._refreshItemPositions(t),this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(e=this.containers.length-1;0<=e;e--)i=this.containers[e].element.offset(),this.containers[e].containerCache.left=i.left,this.containers[e].containerCache.top=i.top,this.containers[e].containerCache.width=this.containers[e].element.outerWidth(),this.containers[e].containerCache.height=this.containers[e].element.outerHeight();return this},_createPlaceholder:function(i){var s,n,o=(i=i||this).options;o.placeholder&&o.placeholder.constructor!==String||(s=o.placeholder,n=i.currentItem[0].nodeName.toLowerCase(),o.placeholder={element:function(){var t=V("<"+n+">",i.document[0]);return i._addClass(t,"ui-sortable-placeholder",s||i.currentItem[0].className)._removeClass(t,"ui-sortable-helper"),"tbody"===n?i._createTrPlaceholder(i.currentItem.find("tr").eq(0),V("<tr>",i.document[0]).appendTo(t)):"tr"===n?i._createTrPlaceholder(i.currentItem,t):"img"===n&&t.attr("src",i.currentItem.attr("src")),s||t.css("visibility","hidden"),t},update:function(t,e){s&&!o.forcePlaceholderSize||(e.height()&&(!o.forcePlaceholderSize||"tbody"!==n&&"tr"!==n)||e.height(i.currentItem.innerHeight()-parseInt(i.currentItem.css("paddingTop")||0,10)-parseInt(i.currentItem.css("paddingBottom")||0,10)),e.width()||e.width(i.currentItem.innerWidth()-parseInt(i.currentItem.css("paddingLeft")||0,10)-parseInt(i.currentItem.css("paddingRight")||0,10)))}}),i.placeholder=V(o.placeholder.element.call(i.element,i.currentItem)),i.currentItem.after(i.placeholder),o.placeholder.update(i,i.placeholder)},_createTrPlaceholder:function(t,e){var i=this;t.children().each(function(){V("<td>&#160;</td>",i.document[0]).attr("colspan",V(this).attr("colspan")||1).appendTo(e)})},_contactContainers:function(t){for(var e,i,s,n,o,a,r,l,h,c=null,u=null,d=this.containers.length-1;0<=d;d--)V.contains(this.currentItem[0],this.containers[d].element[0])||(this._intersectsWith(this.containers[d].containerCache)?c&&V.contains(this.containers[d].element[0],c.element[0])||(c=this.containers[d],u=d):this.containers[d].containerCache.over&&(this.containers[d]._trigger("out",t,this._uiHash(this)),this.containers[d].containerCache.over=0));if(c)if(1===this.containers.length)this.containers[u].containerCache.over||(this.containers[u]._trigger("over",t,this._uiHash(this)),this.containers[u].containerCache.over=1);else{for(i=1e4,s=null,n=(l=c.floating||this._isFloating(this.currentItem))?"left":"top",o=l?"width":"height",h=l?"pageX":"pageY",e=this.items.length-1;0<=e;e--)V.contains(this.containers[u].element[0],this.items[e].item[0])&&this.items[e].item[0]!==this.currentItem[0]&&(a=this.items[e].item.offset()[n],r=!1,t[h]-a>this.items[e][o]/2&&(r=!0),Math.abs(t[h]-a)<i&&(i=Math.abs(t[h]-a),s=this.items[e],this.direction=r?"up":"down"));(s||this.options.dropOnEmpty)&&(this.currentContainer!==this.containers[u]?(s?this._rearrange(t,s,null,!0):this._rearrange(t,null,this.containers[u].element,!0),this._trigger("change",t,this._uiHash()),this.containers[u]._trigger("change",t,this._uiHash(this)),this.currentContainer=this.containers[u],this.options.placeholder.update(this.currentContainer,this.placeholder),this.scrollParent=this.placeholder.scrollParent(),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this.containers[u]._trigger("over",t,this._uiHash(this)),this.containers[u].containerCache.over=1):this.currentContainer.containerCache.over||(this.containers[u]._trigger("over",t,this._uiHash()),this.currentContainer.containerCache.over=1))}},_createHelper:function(t){var e=this.options,t="function"==typeof e.helper?V(e.helper.apply(this.element[0],[t,this.currentItem])):"clone"===e.helper?this.currentItem.clone():this.currentItem;return t.parents("body").length||this.appendTo[0].appendChild(t[0]),t[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),t[0].style.width&&!e.forceHelperSize||t.width(this.currentItem.width()),t[0].style.height&&!e.forceHelperSize||t.height(this.currentItem.height()),t},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),"left"in(t=Array.isArray(t)?{left:+t[0],top:+t[1]||0}:t)&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&V.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),{top:(t=this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&V.ui.ie?{top:0,left:0}:t).top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,e,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode),"document"!==i.containment&&"window"!==i.containment||(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===i.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===i.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(i.containment)||(t=V(i.containment)[0],e=V(i.containment).offset(),i="hidden"!==V(t).css("overflow"),this.containment=[e.left+(parseInt(V(t).css("borderLeftWidth"),10)||0)+(parseInt(V(t).css("paddingLeft"),10)||0)-this.margins.left,e.top+(parseInt(V(t).css("borderTopWidth"),10)||0)+(parseInt(V(t).css("paddingTop"),10)||0)-this.margins.top,e.left+(i?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(V(t).css("borderLeftWidth"),10)||0)-(parseInt(V(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,e.top+(i?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(V(t).css("borderTopWidth"),10)||0)-(parseInt(V(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,e){e=e||this.position;var i="absolute"===t?1:-1,s="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&V.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,t=/(html|body)/i.test(s[0].tagName);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():t?0:s.scrollTop())*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():t?0:s.scrollLeft())*i}},_generatePosition:function(t){var e=this.options,i=t.pageX,s=t.pageY,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&V.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(i=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(s=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(i=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(s=this.containment[3]+this.offset.click.top)),e.grid&&(t=this.originalPageY+Math.round((s-this.originalPageY)/e.grid[1])*e.grid[1],s=!this.containment||t-this.offset.click.top>=this.containment[1]&&t-this.offset.click.top<=this.containment[3]?t:t-this.offset.click.top>=this.containment[1]?t-e.grid[1]:t+e.grid[1],t=this.originalPageX+Math.round((i-this.originalPageX)/e.grid[0])*e.grid[0],i=!this.containment||t-this.offset.click.left>=this.containment[0]&&t-this.offset.click.left<=this.containment[2]?t:t-this.offset.click.left>=this.containment[0]?t-e.grid[0]:t+e.grid[0])),{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop()),left:i-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){this.reverting=!1;var i,s=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)"auto"!==this._storedCSS[i]&&"static"!==this._storedCSS[i]||(this._storedCSS[i]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();function n(e,i,s){return function(t){s._trigger(e,t,i._uiHash(i))}}for(this.fromOutside&&!e&&s.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||s.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(s.push(function(t){this._trigger("remove",t,this._uiHash())}),s.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),s.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),i=this.containers.length-1;0<=i;i--)e||s.push(n("deactivate",this,this.containers[i])),this.containers[i].containerCache.over&&(s.push(n("out",this,this.containers[i])),this.containers[i].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(i=0;i<s.length;i++)s[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){!1===V.Widget.prototype._trigger.apply(this,arguments)&&this.cancel()},_uiHash:function(t){var e=t||this;return{helper:e.helper,placeholder:e.placeholder||V([]),position:e.position,originalPosition:e.originalPosition,offset:e.positionAbs,item:e.currentItem,sender:t?t.element:null}}});function ht(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger("change")}}V.widget("ui.spinner",{version:"1.13.2",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var s=this._super(),n=this.element;return V.each(["min","max","step"],function(t,e){var i=n.attr(e);null!=i&&i.length&&(s[e]=i)}),s},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){this.cancelBlur?delete this.cancelBlur:(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t))},mousewheel:function(t,e){var i=V.ui.safeActiveElement(this.document[0]);if(this.element[0]===i&&e){if(!this.spinning&&!this._start(t))return!1;this._spin((0<e?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(t){var e;function i(){this.element[0]===V.ui.safeActiveElement(this.document[0])||(this.element.trigger("focus"),this.previous=e,this._delay(function(){this.previous=e}))}e=this.element[0]===V.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),t.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),!1!==this._start(t)&&this._repeat(null,V(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){if(V(t.currentTarget).hasClass("ui-state-active"))return!1!==this._start(t)&&void this._repeat(null,V(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",!0).button({classes:{"ui-button":""}}),this._removeClass(this.buttons,"ui-corner-all"),this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up"),this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down"),this.buttons.first().button({icon:this.options.icons.up,showLabel:!1}),this.buttons.last().button({icon:this.options.icons.down,showLabel:!1}),this.buttons.height()>Math.ceil(.5*this.uiSpinner.height())&&0<this.uiSpinner.height()&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(t){var e=this.options,i=V.ui.keyCode;switch(t.keyCode){case i.UP:return this._repeat(null,1,t),!0;case i.DOWN:return this._repeat(null,-1,t),!0;case i.PAGE_UP:return this._repeat(null,e.page,t),!0;case i.PAGE_DOWN:return this._repeat(null,-e.page,t),!0}return!1},_start:function(t){return!(!this.spinning&&!1===this._trigger("start",t))&&(this.counter||(this.counter=1),this.spinning=!0)},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&!1===this._trigger("spin",e,{value:i})||(this._value(i),this.counter++)},_increment:function(t){var e=this.options.incremental;return e?"function"==typeof e?e(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return t=null!==this.options.min?Math.max(t,this._precisionOf(this.options.min)):t},_precisionOf:function(t){var e=t.toString(),t=e.indexOf(".");return-1===t?0:e.length-t-1},_adjustValue:function(t){var e=this.options,i=null!==e.min?e.min:0,s=t-i;return t=i+Math.round(s/e.step)*e.step,t=parseFloat(t.toFixed(this._precision())),null!==e.max&&t>e.max?e.max:null!==e.min&&t<e.min?e.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){var i;if("culture"===t||"numberFormat"===t)return i=this._parse(this.element.val()),this.options[t]=e,void this.element.val(this._format(i));"max"!==t&&"min"!==t&&"step"!==t||"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(i=this.buttons.first().find(".ui-icon"),this._removeClass(i,null,this.options.icons.up),this._addClass(i,null,e.up),i=this.buttons.last().find(".ui-icon"),this._removeClass(i,null,this.options.icons.down),this._addClass(i,null,e.down)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable")},_setOptions:ht(function(t){this._super(t)}),_parse:function(t){return""===(t="string"==typeof t&&""!==t?window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t:t)||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null!==t&&t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&null!==(i=this._parse(t))&&(e||(i=this._adjustValue(i)),t=this._format(i)),this.element.val(t),this._refresh()},_destroy:function(){this.element.prop("disabled",!1).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:ht(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:ht(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:ht(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:ht(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){if(!arguments.length)return this._parse(this.element.val());ht(this._value).call(this,t)},widget:function(){return this.uiSpinner}}),!1!==V.uiBackCompat&&V.widget("ui.spinner",V.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}});var ct;V.ui.spinner;V.widget("ui.tabs",{version:"1.13.2",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:(ct=/#.*$/,function(t){var e=t.href.replace(ct,""),i=location.href.replace(ct,"");try{e=decodeURIComponent(e)}catch(t){}try{i=decodeURIComponent(i)}catch(t){}return 1<t.hash.length&&e===i}),_create:function(){var e=this,t=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,t.collapsible),this._processTabs(),t.active=this._initialActive(),Array.isArray(t.disabled)&&(t.disabled=V.uniqueSort(t.disabled.concat(V.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),!1!==this.options.active&&this.anchors.length?this.active=this._findActive(t.active):this.active=V(),this._refresh(),this.active.length&&this.load(t.active)},_initialActive:function(){var i=this.options.active,t=this.options.collapsible,s=location.hash.substring(1);return null===i&&(s&&this.tabs.each(function(t,e){if(V(e).attr("aria-controls")===s)return i=t,!1}),null!==(i=null===i?this.tabs.index(this.tabs.filter(".ui-tabs-active")):i)&&-1!==i||(i=!!this.tabs.length&&0)),!1!==i&&-1===(i=this.tabs.index(this.tabs.eq(i)))&&(i=!t&&0),i=!t&&!1===i&&this.anchors.length?0:i},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):V()}},_tabKeydown:function(t){var e=V(V.ui.safeActiveElement(this.document[0])).closest("li"),i=this.tabs.index(e),s=!0;if(!this._handlePageNav(t)){switch(t.keyCode){case V.ui.keyCode.RIGHT:case V.ui.keyCode.DOWN:i++;break;case V.ui.keyCode.UP:case V.ui.keyCode.LEFT:s=!1,i--;break;case V.ui.keyCode.END:i=this.anchors.length-1;break;case V.ui.keyCode.HOME:i=0;break;case V.ui.keyCode.SPACE:return t.preventDefault(),clearTimeout(this.activating),void this._activate(i);case V.ui.keyCode.ENTER:return t.preventDefault(),clearTimeout(this.activating),void this._activate(i!==this.options.active&&i);default:return}t.preventDefault(),clearTimeout(this.activating),i=this._focusNextTab(i,s),t.ctrlKey||t.metaKey||(e.attr("aria-selected","false"),this.tabs.eq(i).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",i)},this.delay))}},_panelKeydown:function(t){this._handlePageNav(t)||t.ctrlKey&&t.keyCode===V.ui.keyCode.UP&&(t.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(t){return t.altKey&&t.keyCode===V.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):t.altKey&&t.keyCode===V.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(t,e){var i=this.tabs.length-1;for(;-1!==V.inArray(t=(t=i<t?0:t)<0?i:t,this.options.disabled);)t=e?t+1:t-1;return t},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){"active"!==t?(this._super(t,e),"collapsible"===t&&(this._toggleClass("ui-tabs-collapsible",null,e),e||!1!==this.options.active||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e)):this._activate(e)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,e=this.tablist.children(":has(a[href])");t.disabled=V.map(e.filter(".ui-state-disabled"),function(t){return e.index(t)}),this._processTabs(),!1!==t.active&&this.anchors.length?this.active.length&&!V.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=V()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active):(t.active=!1,this.active=V()),this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._addClass(this.active,"ui-tabs-active","ui-state-active"),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var l=this,t=this.tabs,e=this.anchors,i=this.panels;this.tablist=this._getList().attr("role","tablist"),this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header"),this.tablist.on("mousedown"+this.eventNamespace,"> li",function(t){V(this).is(".ui-state-disabled")&&t.preventDefault()}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){V(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1}),this._addClass(this.tabs,"ui-tabs-tab","ui-state-default"),this.anchors=this.tabs.map(function(){return V("a",this)[0]}).attr({tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=V(),this.anchors.each(function(t,e){var i,s,n,o=V(e).uniqueId().attr("id"),a=V(e).closest("li"),r=a.attr("aria-controls");l._isLocal(e)?(n=(i=e.hash).substring(1),s=l.element.find(l._sanitizeSelector(i))):(n=a.attr("aria-controls")||V({}).uniqueId()[0].id,(s=l.element.find(i="#"+n)).length||(s=l._createPanel(n)).insertAfter(l.panels[t-1]||l.tablist),s.attr("aria-live","polite")),s.length&&(l.panels=l.panels.add(s)),r&&a.data("ui-tabs-aria-controls",r),a.attr({"aria-controls":n,"aria-labelledby":o}),s.attr("aria-labelledby",o)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),t&&(this._off(t.not(this.tabs)),this._off(e.not(this.anchors)),this._off(i.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(t){return V("<div>").attr("id",t).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(t){var e,i;for(Array.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1),i=0;e=this.tabs[i];i++)e=V(e),!0===t||-1!==V.inArray(i,t)?(e.attr("aria-disabled","true"),this._addClass(e,null,"ui-state-disabled")):(e.removeAttr("aria-disabled"),this._removeClass(e,null,"ui-state-disabled"));this.options.disabled=t,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!0===t)},_setupEvents:function(t){var i={};t&&V.each(t.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var i,e=this.element.parent();"fill"===t?(i=e.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var t=V(this),e=t.css("position");"absolute"!==e&&"fixed"!==e&&(i-=t.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=V(this).outerHeight(!0)}),this.panels.each(function(){V(this).height(Math.max(0,i-V(this).innerHeight()+V(this).height()))}).css("overflow","auto")):"auto"===t&&(i=0,this.panels.each(function(){i=Math.max(i,V(this).height("").height())}).height(i))},_eventHandler:function(t){var e=this.options,i=this.active,s=V(t.currentTarget).closest("li"),n=s[0]===i[0],o=n&&e.collapsible,a=o?V():this._getPanelForTab(s),r=i.length?this._getPanelForTab(i):V(),i={oldTab:i,oldPanel:r,newTab:o?V():s,newPanel:a};t.preventDefault(),s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||n&&!e.collapsible||!1===this._trigger("beforeActivate",t,i)||(e.active=!o&&this.tabs.index(s),this.active=n?V():s,this.xhr&&this.xhr.abort(),r.length||a.length||V.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&&this.load(this.tabs.index(s),t),this._toggle(t,i))},_toggle:function(t,e){var i=this,s=e.newPanel,n=e.oldPanel;function o(){i.running=!1,i._trigger("activate",t,e)}function a(){i._addClass(e.newTab.closest("li"),"ui-tabs-active","ui-state-active"),s.length&&i.options.show?i._show(s,i.options.show,o):(s.show(),o())}this.running=!0,n.length&&this.options.hide?this._hide(n,this.options.hide,function(){i._removeClass(e.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),a()}):(this._removeClass(e.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),n.hide(),a()),n.attr("aria-hidden","true"),e.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),s.length&&n.length?e.oldTab.attr("tabIndex",-1):s.length&&this.tabs.filter(function(){return 0===V(this).attr("tabIndex")}).attr("tabIndex",-1),s.attr("aria-hidden","false"),e.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(t){var t=this._findActive(t);t[0]!==this.active[0]&&(t=(t=!t.length?this.active:t).find(".ui-tabs-anchor")[0],this._eventHandler({target:t,currentTarget:t,preventDefault:V.noop}))},_findActive:function(t){return!1===t?V():this.tabs.eq(t)},_getIndex:function(t){return t="string"==typeof t?this.anchors.index(this.anchors.filter("[href$='"+V.escapeSelector(t)+"']")):t},_destroy:function(){this.xhr&&this.xhr.abort(),this.tablist.removeAttr("role").off(this.eventNamespace),this.anchors.removeAttr("role tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){V.data(this,"ui-tabs-destroy")?V(this).remove():V(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var t=V(this),e=t.data("ui-tabs-aria-controls");e?t.attr("aria-controls",e).removeData("ui-tabs-aria-controls"):t.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(i){var t=this.options.disabled;!1!==t&&(t=void 0!==i&&(i=this._getIndex(i),Array.isArray(t)?V.map(t,function(t){return t!==i?t:null}):V.map(this.tabs,function(t,e){return e!==i?e:null})),this._setOptionDisabled(t))},disable:function(t){var e=this.options.disabled;if(!0!==e){if(void 0===t)e=!0;else{if(t=this._getIndex(t),-1!==V.inArray(t,e))return;e=Array.isArray(e)?V.merge([t],e).sort():[t]}this._setOptionDisabled(e)}},load:function(t,s){t=this._getIndex(t);function n(t,e){"abort"===e&&o.panels.stop(!1,!0),o._removeClass(i,"ui-tabs-loading"),a.removeAttr("aria-busy"),t===o.xhr&&delete o.xhr}var o=this,i=this.tabs.eq(t),t=i.find(".ui-tabs-anchor"),a=this._getPanelForTab(i),r={tab:i,panel:a};this._isLocal(t[0])||(this.xhr=V.ajax(this._ajaxSettings(t,s,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(this._addClass(i,"ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,i){setTimeout(function(){a.html(t),o._trigger("load",s,r),n(i,e)},1)}).fail(function(t,e){setTimeout(function(){n(t,e)},1)})))},_ajaxSettings:function(t,i,s){var n=this;return{url:t.attr("href").replace(/#.*$/,""),beforeSend:function(t,e){return n._trigger("beforeLoad",i,V.extend({jqXHR:t,ajaxSettings:e},s))}}},_getPanelForTab:function(t){t=V(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+t))}}),!1!==V.uiBackCompat&&V.widget("ui.tabs",V.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}});V.ui.tabs;V.widget("ui.tooltip",{version:"1.13.2",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var t=V(this).attr("title");return V("<a>").text(t).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,track:!1,close:null,open:null},_addDescribedBy:function(t,e){var i=(t.attr("aria-describedby")||"").split(/\s+/);i.push(e),t.data("ui-tooltip-id",e).attr("aria-describedby",String.prototype.trim.call(i.join(" ")))},_removeDescribedBy:function(t){var e=t.data("ui-tooltip-id"),i=(t.attr("aria-describedby")||"").split(/\s+/),e=V.inArray(e,i);-1!==e&&i.splice(e,1),t.removeData("ui-tooltip-id"),(i=String.prototype.trim.call(i.join(" ")))?t.attr("aria-describedby",i):t.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=V("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this.disabledTitles=V([])},_setOption:function(t,e){var i=this;this._super(t,e),"content"===t&&V.each(this.tooltips,function(t,e){i._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var s=this;V.each(this.tooltips,function(t,e){var i=V.Event("blur");i.target=i.currentTarget=e.element[0],s.close(i,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var t=V(this);if(t.is("[title]"))return t.data("ui-tooltip-title",t.attr("title")).removeAttr("title")}))},_enable:function(){this.disabledTitles.each(function(){var t=V(this);t.data("ui-tooltip-title")&&t.attr("title",t.data("ui-tooltip-title"))}),this.disabledTitles=V([])},open:function(t){var i=this,e=V(t?t.target:this.element).closest(this.options.items);e.length&&!e.data("ui-tooltip-id")&&(e.attr("title")&&e.data("ui-tooltip-title",e.attr("title")),e.data("ui-tooltip-open",!0),t&&"mouseover"===t.type&&e.parents().each(function(){var t,e=V(this);e.data("ui-tooltip-open")&&((t=V.Event("blur")).target=t.currentTarget=this,i.close(t,!0)),e.attr("title")&&(e.uniqueId(),i.parents[this.id]={element:this,title:e.attr("title")},e.attr("title",""))}),this._registerCloseHandlers(t,e),this._updateContent(e,t))},_updateContent:function(e,i){var t=this.options.content,s=this,n=i?i.type:null;if("string"==typeof t||t.nodeType||t.jquery)return this._open(i,e,t);(t=t.call(e[0],function(t){s._delay(function(){e.data("ui-tooltip-open")&&(i&&(i.type=n),this._open(i,e,t))})}))&&this._open(i,e,t)},_open:function(t,e,i){var s,n,o,a=V.extend({},this.options.position);function r(t){a.of=t,n.is(":hidden")||n.position(a)}i&&((s=this._find(e))?s.tooltip.find(".ui-tooltip-content").html(i):(e.is("[title]")&&(t&&"mouseover"===t.type?e.attr("title",""):e.removeAttr("title")),s=this._tooltip(e),n=s.tooltip,this._addDescribedBy(e,n.attr("id")),n.find(".ui-tooltip-content").html(i),this.liveRegion.children().hide(),(i=V("<div>").html(n.find(".ui-tooltip-content").html())).removeAttr("name").find("[name]").removeAttr("name"),i.removeAttr("id").find("[id]").removeAttr("id"),i.appendTo(this.liveRegion),this.options.track&&t&&/^mouse/.test(t.type)?(this._on(this.document,{mousemove:r}),r(t)):n.position(V.extend({of:e},this.options.position)),n.hide(),this._show(n,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(o=this.delayedShow=setInterval(function(){n.is(":visible")&&(r(a.of),clearInterval(o))},13)),this._trigger("open",t,{tooltip:n})))},_registerCloseHandlers:function(t,e){var i={keyup:function(t){t.keyCode===V.ui.keyCode.ESCAPE&&((t=V.Event(t)).currentTarget=e[0],this.close(t,!0))}};e[0]!==this.element[0]&&(i.remove=function(){var t=this._find(e);t&&this._removeTooltip(t.tooltip)}),t&&"mouseover"!==t.type||(i.mouseleave="close"),t&&"focusin"!==t.type||(i.focusout="close"),this._on(!0,e,i)},close:function(t){var e,i=this,s=V(t?t.currentTarget:this.element),n=this._find(s);n?(e=n.tooltip,n.closing||(clearInterval(this.delayedShow),s.data("ui-tooltip-title")&&!s.attr("title")&&s.attr("title",s.data("ui-tooltip-title")),this._removeDescribedBy(s),n.hiding=!0,e.stop(!0),this._hide(e,this.options.hide,function(){i._removeTooltip(V(this))}),s.removeData("ui-tooltip-open"),this._off(s,"mouseleave focusout keyup"),s[0]!==this.element[0]&&this._off(s,"remove"),this._off(this.document,"mousemove"),t&&"mouseleave"===t.type&&V.each(this.parents,function(t,e){V(e.element).attr("title",e.title),delete i.parents[t]}),n.closing=!0,this._trigger("close",t,{tooltip:e}),n.hiding||(n.closing=!1))):s.removeData("ui-tooltip-open")},_tooltip:function(t){var e=V("<div>").attr("role","tooltip"),i=V("<div>").appendTo(e),s=e.uniqueId().attr("id");return this._addClass(i,"ui-tooltip-content"),this._addClass(e,"ui-tooltip","ui-widget ui-widget-content"),e.appendTo(this._appendTo(t)),this.tooltips[s]={element:t,tooltip:e}},_find:function(t){t=t.data("ui-tooltip-id");return t?this.tooltips[t]:null},_removeTooltip:function(t){clearInterval(this.delayedShow),t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){t=t.closest(".ui-front, dialog");return t=!t.length?this.document[0].body:t},_destroy:function(){var s=this;V.each(this.tooltips,function(t,e){var i=V.Event("blur"),e=e.element;i.target=i.currentTarget=e[0],s.close(i,!0),V("#"+t).remove(),e.data("ui-tooltip-title")&&(e.attr("title")||e.attr("title",e.data("ui-tooltip-title")),e.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),!1!==V.uiBackCompat&&V.widget("ui.tooltip",V.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}});V.ui.tooltip});;
/**
 * This work is licensed under the MIT License
 *
 * Configurable idle (no activity) timer and logout redirect for jQuery.
 * Works across multiple windows and tabs from the same domain.
 *
 * Dependencies: JQuery v1.7+, JQuery UI, store.js from https://github.com/marcuswestin/store.js - v1.3.4+
 * version 1.0.8
 **/

/*global jQuery: false, document: false, store: false, clearInterval: false, setInterval: false, setTimeout: false, window: false, alert: false*/
/*jslint indent: 2, sloppy: true*/

(function ($) {

    $.fn.idleTimeout = function (options) {
        // Chrome poorly supports 508c standards, especially aria-live attribute.
        // So we need to know if it's Chrome to implement some features in another way.
        var isChrome = !!window.chrome;


        //##############################
        //## Configuration Variables
        //##############################
        var defaults = {
            idleTimeLimit: 1200,       // 'No activity' time limit in seconds. 1200 = 20 Minutes
            redirectUrl: '/logout',    // redirect to this url on timeout logout. Set to "redirectUrl: false" to disable redirect

            // optional custom callback to perform before logout
            customCallback: false,     // set to false for no customCallback
            // customCallback:    function () {    // define optional custom js function
            // perform custom action before logout
            // },

            // configure which activity events to detect
            // http://www.quirksmode.org/dom/events/
            // https://developer.mozilla.org/en-US/docs/Web/Reference/Events
            activityEvents: 'click keypress scroll wheel mousewheel mousemove', // separate each event with a space

            // warning dialog box configuration
            enableDialog: true,        // set to false for logout without warning dialog
            dialogDisplayLimit: 180,   // time to display the warning dialog before logout (and optional callback) in seconds. 180 = 3 Minutes
            dialogTitle: 'Session Expiration Warning',
            dialogText: 'Because you have been inactive, your session is about to expire.',
            dialogTimeRemaining: 'Time remaining',
            dialogStayLoggedInButton: 'Stay Logged In',
            dialogLogOutNowButton: 'Log Out Now',

            pronounceWarningInterval: 15, // in seconds

            // error message
            errorAlertMessage: 'Please disable "Private Mode", or upgrade to a modern browser. Or perhaps a dependent file missing. Please see: https://github.com/marcuswestin/store.js',

            // server-side session keep-alive timer
            sessionKeepAliveTimer: 600, // Ping the server at this interval in seconds. 600 = 10 Minutes
            // sessionKeepAliveTimer: false, // Set to false to disable pings
            sessionKeepAliveUrl: window.location.href, // set URL to ping - does not apply if sessionKeepAliveTimer: false
            stopTrackingEvent: ''
        },

        //##############################
        //## Private Variables
        //##############################
          opts = $.extend(defaults, options),
          checkHeartbeat = 2, // frequency to check for timeouts in seconds
          origTitle = document.title, // save original browser title
          startKeepSessionAlive, stopKeepSessionAlive, keepSession, keepAlivePing, activityDetector,
          idleTimer, remainingTimer, checkIdleTimeout, idleTimerLastActivity, startIdleTimer, stopIdleTimer,
          $warningContainer, $warningContainerParent, $warningResumeLink, initializeWarningDialog, openWarningDialog,
          dialogTimer, checkDialogTimeout, startDialogTimer, stopDialogTimer, isDialogOpen, closeWarningDialog,
          countdownDisplay, triggerResume, logoutUser;

        //##############################
        //## Private Functions
        //##############################
        startKeepSessionAlive = function () {

            keepSession = function () {
                if (idleTimerLastActivity === store.get('idleTimerLastActivity')) {
                    $.get(opts.sessionKeepAliveUrl);
                }
            };

            keepAlivePing = setInterval(keepSession, (opts.sessionKeepAliveTimer * 1000));
        };

        stopKeepSessionAlive = function () {
            clearInterval(keepAlivePing);
        };

        activityDetector = function () {

            $('body').on(opts.activityEvents, function () {

                if (!opts.enableDialog || (opts.enableDialog && isDialogOpen() !== true)) {
                    startIdleTimer();
                }
            });
        };

        checkIdleTimeout = function () {
            var timeNow = $.now(), timeIdleTimeout = (store.get('idleTimerLastActivity') + (opts.idleTimeLimit * 1000));

            if (timeNow > timeIdleTimeout) {

                if (!opts.enableDialog) {
                    logoutUser();
                } else if (opts.enableDialog && isDialogOpen() !== true) {
                    openWarningDialog();
                    startDialogTimer();
                    triggerResume();
                }
            } else if (store.get('idleTimerLoggedOut') === true) { //a 'manual' user logout?
                logoutUser();
            } else {
                if (isDialogOpen() === true) {
                    closeWarningDialog();
                    stopDialogTimer();
                }
            }
        };

        startIdleTimer = function () {
            stopIdleTimer();
            idleTimerLastActivity = $.now();
            store.set('idleTimerLastActivity', idleTimerLastActivity);
            idleTimer = setInterval(checkIdleTimeout, (checkHeartbeat * 1000));
        };

        stopIdleTimer = function () {
            clearInterval(idleTimer);
        };

        initializeWarningDialog = function() {
            $warningContainer = $('#idletimeout-container');
            var $countdownPlaceholder = $('.countdown-place-holder', $warningContainer);
            $countdownPlaceholder.before(opts.dialogText);

            $warningResumeLink = $('#idletimeout-resume-link', $warningContainer);
            $warningResumeLink.text(opts.dialogStayLoggedInButton);

            if (isChrome) {
                // Chrome doesn't like changing of aria-live attribute, so
                // it should be permanently here.
                $warningContainer.attr('aria-live', 'assertive');
            }

            $($warningResumeLink).on('click', function() {
                closeWarningDialog();
                stopDialogTimer();
                startIdleTimer();
            });
        };

        openWarningDialog = function () {
            $warningContainerParent = $warningContainer.parent();
            $warningContainer.prependTo('body');
            $warningContainer.slideDown();

            countdownDisplay();

            document.title = opts.dialogTitle;

            if (opts.sessionKeepAliveTimer) {
                stopKeepSessionAlive();
            }
        };

        checkDialogTimeout = function () {
            var timeNow = $.now(), timeDialogTimeout = (store.get('idleTimerLastActivity') + (opts.idleTimeLimit * 1000) + (opts.dialogDisplayLimit * 1000));

            if ((timeNow > timeDialogTimeout) || (store.get('idleTimerLoggedOut') === true)) {
                logoutUser();
            }
        };

        startDialogTimer = function () {
            dialogTimer = setInterval(checkDialogTimeout, (checkHeartbeat * 1000));
        };

        stopDialogTimer = function () {
            clearInterval(dialogTimer);
            clearInterval(remainingTimer);
        };

        isDialogOpen = function () {
            var dialogOpen = $($warningContainer).is(":visible");

            if (dialogOpen === true) {
                return true;
            }
            return false;
        };

        closeWarningDialog = function () {
            if (!isChrome) {
                $warningContainer.removeAttr('aria-live');
            }

            $warningContainer.slideUp({
                complete: function () {
                    $warningContainer.appendTo($warningContainerParent);
                }
            });

            document.title = origTitle;

            if (opts.sessionKeepAliveTimer) {
                startKeepSessionAlive();
            }
        };

        // display remaining time on warning dialog
        countdownDisplay = function () {
            var dialogDisplaySeconds = opts.dialogDisplayLimit, mins, secs;
            var timeUntilPronounce = 1; // Skip first value because of NVDA issue.
            var $countdownPlaceholder = $('span', $warningContainer);

            function updateTimer() {
                if (!isChrome) {
                    if (timeUntilPronounce === 0) {
                        $warningContainer.attr('aria-live', 'assertive');
                        timeUntilPronounce = opts.pronounceWarningInterval;
                    } else if (timeUntilPronounce === opts.pronounceWarningInterval - 1) {
                        // Time was pronounced last time, we need to remove aria-live
                        $warningContainer.removeAttr('aria-live');
                    }
                }

                mins = Math.floor(dialogDisplaySeconds / 60); // minutes
                if (mins < 10) { mins = '0' + mins; }
                secs = dialogDisplaySeconds - (mins * 60); // seconds
                if (secs < 10) { secs = '0' + secs; }
                $countdownPlaceholder.html(mins + ':' + secs);
                dialogDisplaySeconds -= 1;
                timeUntilPronounce -= 1;
            }

            updateTimer();
            remainingTimer = setInterval(updateTimer, 1000);
        };

        triggerResume = function() {
            var isFired = false;

            $('body').one(opts.activityEvents, function (event) {
                if (isFired) { return; }

                isFired = true;

                var $target = $(event.target);

                if (!$target.is($warningResumeLink)) {
                    $warningResumeLink.trigger('click');
                }
            });
        };

        logoutUser = function () {
            store.set('idleTimerLoggedOut', true);

            if (opts.sessionKeepAliveTimer) {
                stopKeepSessionAlive();
            }

            if (opts.customCallback) {
                if (opts.customCallback()) {
                    stopDialogTimer();
                    stopIdleTimer();
                }
            }

            if (opts.redirectUrl) {
                window.location.href = opts.redirectUrl;
            }
        };

        //###############################
        // Build & Return the instance of the item as a plugin
        // This is your construct.
        //###############################
        return this.each(function () {

            if (store.enabled) {
                idleTimerLastActivity = $.now();
                store.set('idleTimerLastActivity', idleTimerLastActivity);
                store.set('idleTimerLoggedOut', false);
            } else {
                alert(opts.errorAlertMessage);
            }

            initializeWarningDialog();

            activityDetector();

            if (opts.sessionKeepAliveTimer) {
                startKeepSessionAlive();
            }

            startIdleTimer();

            if (opts.stopTrackingEvent) {
                $(document).one(opts.stopTrackingEvent, function() {
                    $('body').off(opts.activityEvents);
                    closeWarningDialog();
                    stopKeepSessionAlive();
                    stopDialogTimer();
                    stopIdleTimer();
                });
            }
        });
    };
}(jQuery));;
(function(){var h,k=this,l=function(a){return void 0!==a},ba=function(){},n=function(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&
!a.propertyIsEnumerable("call"))return"function"}else return"null";else if("function"==b&&"undefined"==typeof a.call)return"object";return b},p=function(a){return"array"==n(a)},ca=function(a){var b=n(a);return"array"==b||"object"==b&&"number"==typeof a.length},q=function(a){return"string"==typeof a},r=function(a){return"function"==n(a)},da=function(a){var b=typeof a;return"object"==b&&null!=a||"function"==b},ea=function(a,b,c){return a.call.apply(a.bind,arguments)},fa=function(a,b,c){if(!a)throw Error();
if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(c,d);return a.apply(b,c)}}return function(){return a.apply(b,arguments)}},t=function(a,b,c){t=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?ea:fa;return t.apply(null,arguments)},ga=function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var b=c.slice();b.push.apply(b,arguments);
return a.apply(this,b)}},ha=Date.now||function(){return+new Date},ia=null,u=function(a,b){var c=a.split("."),d=k;c[0]in d||!d.execScript||d.execScript("var "+c[0]);for(var e;c.length&&(e=c.shift());)!c.length&&l(b)?d[e]=b:d=d[e]?d[e]:d[e]={}},v=function(a,b){function c(){}c.prototype=b.prototype;a.superClass_=b.prototype;a.prototype=new c;a.base=function(a,c,g){for(var f=Array(arguments.length-2),m=2;m<arguments.length;m++)f[m-2]=arguments[m];return b.prototype[c].apply(a,f)}};
Function.prototype.bind=Function.prototype.bind||function(a,b){if(1<arguments.length){var c=Array.prototype.slice.call(arguments,1);c.unshift(this,a);return t.apply(null,c)}return t(this,a)};var w={};u("RecaptchaTemplates",w);w.VertHtml='<table id="recaptcha_table" class="recaptchatable" > <tr> <td colspan="6" class=\'recaptcha_r1_c1\'></td> </tr> <tr> <td class=\'recaptcha_r2_c1\'></td> <td colspan="4" class=\'recaptcha_image_cell\'><center><div id="recaptcha_image"></div></center></td> <td class=\'recaptcha_r2_c2\'></td> </tr> <tr> <td rowspan="6" class=\'recaptcha_r3_c1\'></td> <td colspan="4" class=\'recaptcha_r3_c2\'></td> <td rowspan="6" class=\'recaptcha_r3_c3\'></td> </tr> <tr> <td rowspan="3" class=\'recaptcha_r4_c1\' height="49"> <div class="recaptcha_input_area"> <input name="recaptcha_response_field" id="recaptcha_response_field" type="text" autocorrect="off" autocapitalize="off" placeholder="" /> <span id="recaptcha_privacy" class="recaptcha_only_if_privacy"></span> </div> </td> <td rowspan="4" class=\'recaptcha_r4_c2\'></td> <td><a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="17" /></a></td> <td rowspan="4" class=\'recaptcha_r4_c4\'></td> </tr> <tr> <td><a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="16" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="16" alt=""/></a></td> </tr> <tr> <td><a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a></td> </tr> <tr> <td class=\'recaptcha_r7_c1\'></td> <td class=\'recaptcha_r8_c1\'></td> </tr> </table> ';w.CleanCss=".recaptchatable td img{display:block}.recaptchatable .recaptcha_image_cell center img{height:57px}.recaptchatable .recaptcha_image_cell center{height:57px}.recaptchatable .recaptcha_image_cell{background-color:white;height:57px;padding:7px!important}.recaptchatable,#recaptcha_area tr,#recaptcha_area td,#recaptcha_area th{margin:0!important;border:0!important;border-collapse:collapse!important;vertical-align:middle!important}.recaptchatable *{margin:0;padding:0;border:0;color:black;position:static;top:auto;left:auto;right:auto;bottom:auto}.recaptchatable #recaptcha_image{position:relative;margin:auto;border:1px solid #dfdfdf!important}.recaptchatable #recaptcha_image #recaptcha_challenge_image{display:block}.recaptchatable #recaptcha_image #recaptcha_ad_image{display:block;position:absolute;top:0}.recaptchatable a img{border:0}.recaptchatable a,.recaptchatable a:hover{cursor:pointer;outline:none;border:0!important;padding:0!important;text-decoration:none;color:blue;background:none!important;font-weight:normal}.recaptcha_input_area{position:relative!important;background:none!important}.recaptchatable label.recaptcha_input_area_text{border:1px solid #dfdfdf!important;margin:0!important;padding:0!important;position:static!important;top:auto!important;left:auto!important;right:auto!important;bottom:auto!important}.recaptcha_theme_red label.recaptcha_input_area_text,.recaptcha_theme_white label.recaptcha_input_area_text{color:black!important}.recaptcha_theme_blackglass label.recaptcha_input_area_text{color:white!important}.recaptchatable #recaptcha_response_field{font-size:11pt}.recaptcha_theme_blackglass #recaptcha_response_field,.recaptcha_theme_white #recaptcha_response_field{border:1px solid gray}.recaptcha_theme_red #recaptcha_response_field{border:1px solid #cca940}.recaptcha_audio_cant_hear_link{font-size:7pt;color:black}.recaptchatable{line-height:1em;border:1px solid #dfdfdf!important}.recaptcha_error_text{color:red}.recaptcha_only_if_privacy{float:right;text-align:right;margin-right:7px}#recaptcha-ad-choices{position:absolute;height:15px;top:0;right:0}#recaptcha-ad-choices img{height:15px}.recaptcha-ad-choices-collapsed{width:30px;height:15px;display:block}.recaptcha-ad-choices-expanded{width:75px;height:15px;display:none}#recaptcha-ad-choices:hover .recaptcha-ad-choices-collapsed{display:none}#recaptcha-ad-choices:hover .recaptcha-ad-choices-expanded{display:block}";w.CleanHtml='<table id="recaptcha_table" class="recaptchatable"> <tr height="73"> <td class=\'recaptcha_image_cell\' width="302"><center><div id="recaptcha_image"></div></center></td> <td style="padding: 10px 7px 7px 7px;"> <a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="18" alt="" /></a> <a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="15" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="15" alt=""/></a> <a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a> </td> <td style="padding: 18px 7px 18px 7px;"> <img id=\'recaptcha_logo\' alt="" width="71" height="36" /> </td> </tr> <tr> <td style="padding-left: 7px;"> <div class="recaptcha_input_area" style="padding-top: 2px; padding-bottom: 7px;"> <input style="border: 1px solid #3c3c3c; width: 302px;" name="recaptcha_response_field" id="recaptcha_response_field" type="text" /> </div> </td> <td colspan=2><span id="recaptcha_privacy" class="recaptcha_only_if_privacy"></span></td> </tr> </table> ';w.VertCss=".recaptchatable td img{display:block}.recaptchatable .recaptcha_r1_c1{background:url('IMGROOT/sprite.png') 0 -63px no-repeat;width:318px;height:9px}.recaptchatable .recaptcha_r2_c1{background:url('IMGROOT/sprite.png') -18px 0 no-repeat;width:9px;height:57px}.recaptchatable .recaptcha_r2_c2{background:url('IMGROOT/sprite.png') -27px 0 no-repeat;width:9px;height:57px}.recaptchatable .recaptcha_r3_c1{background:url('IMGROOT/sprite.png') 0 0 no-repeat;width:9px;height:63px}.recaptchatable .recaptcha_r3_c2{background:url('IMGROOT/sprite.png') -18px -57px no-repeat;width:300px;height:6px}.recaptchatable .recaptcha_r3_c3{background:url('IMGROOT/sprite.png') -9px 0 no-repeat;width:9px;height:63px}.recaptchatable .recaptcha_r4_c1{background:url('IMGROOT/sprite.png') -43px 0 no-repeat;width:171px;height:49px}.recaptchatable .recaptcha_r4_c2{background:url('IMGROOT/sprite.png') -36px 0 no-repeat;width:7px;height:57px}.recaptchatable .recaptcha_r4_c4{background:url('IMGROOT/sprite.png') -214px 0 no-repeat;width:97px;height:57px}.recaptchatable .recaptcha_r7_c1{background:url('IMGROOT/sprite.png') -43px -49px no-repeat;width:171px;height:8px}.recaptchatable .recaptcha_r8_c1{background:url('IMGROOT/sprite.png') -43px -49px no-repeat;width:25px;height:8px}.recaptchatable .recaptcha_image_cell center img{height:57px}.recaptchatable .recaptcha_image_cell center{height:57px}.recaptchatable .recaptcha_image_cell{background-color:white;height:57px}#recaptcha_area,#recaptcha_table{width:318px!important}.recaptchatable,#recaptcha_area tr,#recaptcha_area td,#recaptcha_area th{margin:0!important;border:0!important;padding:0!important;border-collapse:collapse!important;vertical-align:middle!important}.recaptchatable *{margin:0;padding:0;border:0;font-family:helvetica,sans-serif;font-size:8pt;color:black;position:static;top:auto;left:auto;right:auto;bottom:auto}.recaptchatable #recaptcha_image{position:relative;margin:auto}.recaptchatable #recaptcha_image #recaptcha_challenge_image{display:block}.recaptchatable #recaptcha_image #recaptcha_ad_image{display:block;position:absolute;top:0}.recaptchatable img{border:0!important;margin:0!important;padding:0!important}.recaptchatable a,.recaptchatable a:hover{cursor:pointer;outline:none;border:0!important;padding:0!important;text-decoration:none;color:blue;background:none!important;font-weight:normal}.recaptcha_input_area{position:relative!important;width:153px!important;height:45px!important;margin-left:7px!important;margin-right:7px!important;background:none!important}.recaptchatable label.recaptcha_input_area_text{margin:0!important;padding:0!important;position:static!important;top:auto!important;left:auto!important;right:auto!important;bottom:auto!important;background:none!important;height:auto!important;width:auto!important}.recaptcha_theme_red label.recaptcha_input_area_text,.recaptcha_theme_white label.recaptcha_input_area_text{color:black!important}.recaptcha_theme_blackglass label.recaptcha_input_area_text{color:white!important}.recaptchatable #recaptcha_response_field{width:153px!important;position:relative!important;bottom:7px!important;padding:0!important;margin:15px 0 0 0!important;font-size:10pt}.recaptcha_theme_blackglass #recaptcha_response_field,.recaptcha_theme_white #recaptcha_response_field{border:1px solid gray}.recaptcha_theme_red #recaptcha_response_field{border:1px solid #cca940}.recaptcha_audio_cant_hear_link{font-size:7pt;color:black}.recaptchatable{line-height:1!important}#recaptcha_instructions_error{color:red!important}.recaptcha_only_if_privacy{float:right;text-align:right}#recaptcha-ad-choices{position:absolute;height:15px;top:0;right:0}#recaptcha-ad-choices img{height:15px}.recaptcha-ad-choices-collapsed{width:30px;height:15px;display:block}.recaptcha-ad-choices-expanded{width:75px;height:15px;display:none}#recaptcha-ad-choices:hover .recaptcha-ad-choices-collapsed{display:none}#recaptcha-ad-choices:hover .recaptcha-ad-choices-expanded{display:block}";var x={visual_challenge:"Get a visual challenge",audio_challenge:"Get an audio challenge",refresh_btn:"Get a new challenge",instructions_visual:"Type the text:",instructions_audio:"Type what you hear:",help_btn:"Help",play_again:"Play sound again",cant_hear_this:"Download sound as MP3",incorrect_try_again:"Incorrect. Try again.",image_alt_text:"reCAPTCHA challenge image",privacy_and_terms:"Privacy & Terms"},ja={visual_challenge:"\u0627\u0644\u062d\u0635\u0648\u0644 \u0639\u0644\u0649 \u062a\u062d\u062f\u064d \u0645\u0631\u0626\u064a",
audio_challenge:"\u0627\u0644\u062d\u0635\u0648\u0644 \u0639\u0644\u0649 \u062a\u062d\u062f\u064d \u0635\u0648\u062a\u064a",refresh_btn:"\u0627\u0644\u062d\u0635\u0648\u0644 \u0639\u0644\u0649 \u062a\u062d\u062f\u064d \u062c\u062f\u064a\u062f",instructions_visual:"\u064a\u0631\u062c\u0649 \u0643\u062a\u0627\u0628\u0629 \u0627\u0644\u0646\u0635:",instructions_audio:"\u0627\u0643\u062a\u0628 \u0645\u0627 \u062a\u0633\u0645\u0639\u0647:",help_btn:"\u0645\u0633\u0627\u0639\u062f\u0629",play_again:"\u062a\u0634\u063a\u064a\u0644 \u0627\u0644\u0635\u0648\u062a \u0645\u0631\u0629 \u0623\u062e\u0631\u0649",
cant_hear_this:"\u062a\u0646\u0632\u064a\u0644 \u0627\u0644\u0635\u0648\u062a \u0628\u062a\u0646\u0633\u064a\u0642 MP3",incorrect_try_again:"\u063a\u064a\u0631 \u0635\u062d\u064a\u062d. \u0623\u0639\u062f \u0627\u0644\u0645\u062d\u0627\u0648\u0644\u0629.",image_alt_text:"\u0635\u0648\u0631\u0629 \u0627\u0644\u062a\u062d\u062f\u064a \u0645\u0646 reCAPTCHA",privacy_and_terms:"\u0627\u0644\u062e\u0635\u0648\u0635\u064a\u0629 \u0648\u0627\u0644\u0628\u0646\u0648\u062f"},ka={visual_challenge:"Obtener una pista visual",
audio_challenge:"Obtener una pista sonora",refresh_btn:"Obtener una pista nueva",instructions_visual:"Introduzca el texto:",instructions_audio:"Escribe lo que oigas:",help_btn:"Ayuda",play_again:"Volver a reproducir el sonido",cant_hear_this:"Descargar el sonido en MP3",incorrect_try_again:"Incorrecto. Vu\u00e9lvelo a intentar.",image_alt_text:"Pista de imagen reCAPTCHA",privacy_and_terms:"Privacidad y condiciones"},la={visual_challenge:"Kumuha ng pagsubok na visual",audio_challenge:"Kumuha ng pagsubok na audio",
refresh_btn:"Kumuha ng bagong pagsubok",instructions_visual:"I-type ang teksto:",instructions_audio:"I-type ang iyong narinig",help_btn:"Tulong",play_again:"I-play muli ang tunog",cant_hear_this:"I-download ang tunog bilang MP3",incorrect_try_again:"Hindi wasto. Muling subukan.",image_alt_text:"larawang panghamon ng reCAPTCHA",privacy_and_terms:"Privacy at Mga Tuntunin"},ma={visual_challenge:"Test visuel",audio_challenge:"Test audio",refresh_btn:"Nouveau test",instructions_visual:"Saisissez le texte\u00a0:",
instructions_audio:"Qu'entendez-vous ?",help_btn:"Aide",play_again:"R\u00e9\u00e9couter",cant_hear_this:"T\u00e9l\u00e9charger l'audio au format MP3",incorrect_try_again:"Incorrect. Veuillez r\u00e9essayer.",image_alt_text:"Image reCAPTCHA",privacy_and_terms:"Confidentialit\u00e9 et conditions d'utilisation"},na={visual_challenge:"Dapatkan kata pengujian berbentuk visual",audio_challenge:"Dapatkan kata pengujian berbentuk audio",refresh_btn:"Dapatkan kata pengujian baru",instructions_visual:"Ketik teks:",
instructions_audio:"Ketik yang Anda dengar:",help_btn:"Bantuan",play_again:"Putar suara sekali lagi",cant_hear_this:"Unduh suara sebagai MP3",incorrect_try_again:"Salah. Coba lagi.",image_alt_text:"Gambar tantangan reCAPTCHA",privacy_and_terms:"Privasi & Persyaratan"},oa={visual_challenge:"\u05e7\u05d1\u05dc \u05d0\u05ea\u05d2\u05e8 \u05d7\u05d6\u05d5\u05ea\u05d9",audio_challenge:"\u05e7\u05d1\u05dc \u05d0\u05ea\u05d2\u05e8 \u05e9\u05de\u05e2",refresh_btn:"\u05e7\u05d1\u05dc \u05d0\u05ea\u05d2\u05e8 \u05d7\u05d3\u05e9",
instructions_visual:"\u05d4\u05e7\u05dc\u05d3 \u05d0\u05ea \u05d4\u05d8\u05e7\u05e1\u05d8:",instructions_audio:"\u05d4\u05e7\u05dc\u05d3 \u05d0\u05ea \u05de\u05d4 \u05e9\u05d0\u05ea\u05d4 \u05e9\u05d5\u05de\u05e2:",help_btn:"\u05e2\u05d6\u05e8\u05d4",play_again:"\u05d4\u05e4\u05e2\u05dc \u05e9\u05d5\u05d1 \u05d0\u05ea \u05d4\u05e9\u05de\u05e2",cant_hear_this:"\u05d4\u05d5\u05e8\u05d3 \u05e9\u05de\u05e2 \u05db-3MP",incorrect_try_again:"\u05e9\u05d2\u05d5\u05d9. \u05e0\u05e1\u05d4 \u05e9\u05d5\u05d1.",
image_alt_text:"\u05ea\u05de\u05d5\u05e0\u05ea \u05d0\u05ea\u05d2\u05e8 \u05e9\u05dc reCAPTCHA",privacy_and_terms:"\u05e4\u05e8\u05d8\u05d9\u05d5\u05ea \u05d5\u05ea\u05e0\u05d0\u05d9\u05dd"},pa={visual_challenge:"Obter um desafio visual",audio_challenge:"Obter um desafio de \u00e1udio",refresh_btn:"Obter um novo desafio",instructions_visual:"Digite o texto:",instructions_audio:"Digite o que voc\u00ea ouve:",help_btn:"Ajuda",play_again:"Reproduzir som novamente",cant_hear_this:"Fazer download do som no formato MP3",
incorrect_try_again:"Incorreto. Tente novamente.",image_alt_text:"Imagem de desafio reCAPTCHA",privacy_and_terms:"Privacidade e Termos"},qa={visual_challenge:"Ob\u0163ine\u0163i un cod captcha vizual",audio_challenge:"Ob\u0163ine\u0163i un cod captcha audio",refresh_btn:"Ob\u0163ine\u0163i un nou cod captcha",instructions_visual:"Introduce\u021bi textul:",instructions_audio:"Introduce\u0163i ceea ce auzi\u0163i:",help_btn:"Ajutor",play_again:"Reda\u0163i sunetul din nou",cant_hear_this:"Desc\u0103rca\u0163i fi\u015fierul audio ca MP3",
incorrect_try_again:"Incorect. \u00cencerca\u0163i din nou.",image_alt_text:"Imagine de verificare reCAPTCHA",privacy_and_terms:"Confiden\u0163ialitate \u015fi termeni"},ra={visual_challenge:"\u6536\u5230\u4e00\u4e2a\u89c6\u9891\u9080\u8bf7",audio_challenge:"\u6362\u4e00\u7ec4\u97f3\u9891\u9a8c\u8bc1\u7801",refresh_btn:"\u6362\u4e00\u7ec4\u9a8c\u8bc1\u7801",instructions_visual:"\u8f93\u5165\u6587\u5b57\uff1a",instructions_audio:"\u8bf7\u952e\u5165\u60a8\u542c\u5230\u7684\u5185\u5bb9\uff1a",help_btn:"\u5e2e\u52a9",
play_again:"\u91cd\u65b0\u64ad\u653e",cant_hear_this:"\u4ee5 MP3 \u683c\u5f0f\u4e0b\u8f7d\u58f0\u97f3",incorrect_try_again:"\u4e0d\u6b63\u786e\uff0c\u8bf7\u91cd\u8bd5\u3002",image_alt_text:"reCAPTCHA \u9a8c\u8bc1\u56fe\u7247",privacy_and_terms:"\u9690\u79c1\u6743\u548c\u4f7f\u7528\u6761\u6b3e"},sa={en:x,af:{visual_challenge:"Kry 'n visuele verifi\u00ebring",audio_challenge:"Kry 'n klankverifi\u00ebring",refresh_btn:"Kry 'n nuwe verifi\u00ebring",instructions_visual:"",instructions_audio:"Tik wat jy hoor:",
help_btn:"Hulp",play_again:"Speel geluid weer",cant_hear_this:"Laai die klank af as MP3",incorrect_try_again:"Verkeerd. Probeer weer.",image_alt_text:"reCAPTCHA-uitdagingprent",privacy_and_terms:"Privaatheid en bepalings"},am:{visual_challenge:"\u12e8\u12a5\u12ed\u1273 \u1270\u130b\u1323\u121a \u12a0\u130d\u129d",audio_challenge:"\u120c\u120b \u12a0\u12f2\u1235 \u12e8\u12f5\u121d\u133d \u1325\u12eb\u1244 \u12ed\u1245\u1228\u1265",refresh_btn:"\u120c\u120b \u12a0\u12f2\u1235 \u1325\u12eb\u1244 \u12ed\u1245\u1228\u1265",
instructions_visual:"",instructions_audio:"\u12e8\u121d\u1275\u1230\u121b\u12cd\u1295 \u1270\u12ed\u1265\u1361-",help_btn:"\u12a5\u1308\u12db",play_again:"\u12f5\u121d\u1339\u1295 \u12a5\u1295\u12f0\u1308\u1293 \u12a0\u132b\u12cd\u1275",cant_hear_this:"\u12f5\u121d\u1339\u1295 \u1260MP3 \u1245\u122d\u133d \u12a0\u12cd\u122d\u12f5",incorrect_try_again:"\u1275\u12ad\u12ad\u120d \u12a0\u12ed\u12f0\u1208\u121d\u1362 \u12a5\u1295\u12f0\u1308\u1293 \u121e\u12ad\u122d\u1362",image_alt_text:"reCAPTCHA \u121d\u1235\u120d \u130d\u1320\u121d",
privacy_and_terms:"\u130d\u120b\u12ca\u1290\u1275 \u12a5\u1293 \u12cd\u120d"},ar:ja,"ar-EG":ja,bg:{visual_challenge:"\u041f\u043e\u043b\u0443\u0447\u0430\u0432\u0430\u043d\u0435 \u043d\u0430 \u0432\u0438\u0437\u0443\u0430\u043b\u043d\u0430 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430",audio_challenge:"\u0417\u0430\u0440\u0435\u0436\u0434\u0430\u043d\u0435 \u043d\u0430 \u0430\u0443\u0434\u0438\u043e\u0442\u0435\u0441\u0442",refresh_btn:"\u0417\u0430\u0440\u0435\u0436\u0434\u0430\u043d\u0435 \u043d\u0430 \u043d\u043e\u0432 \u0442\u0435\u0441\u0442",
instructions_visual:"\u0412\u044a\u0432\u0435\u0434\u0435\u0442\u0435 \u0442\u0435\u043a\u0441\u0442\u0430:",instructions_audio:"\u0412\u044a\u0432\u0435\u0434\u0435\u0442\u0435 \u0447\u0443\u0442\u043e\u0442\u043e:",help_btn:"\u041f\u043e\u043c\u043e\u0449",play_again:"\u041f\u043e\u0432\u0442\u043e\u0440\u043d\u043e \u043f\u0443\u0441\u043a\u0430\u043d\u0435 \u043d\u0430 \u0437\u0432\u0443\u043a\u0430",cant_hear_this:"\u0418\u0437\u0442\u0435\u0433\u043b\u044f\u043d\u0435 \u043d\u0430 \u0437\u0432\u0443\u043a\u0430 \u0432\u044a\u0432 \u0444\u043e\u0440\u043c\u0430\u0442 MP3",
incorrect_try_again:"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u043d\u043e. \u041e\u043f\u0438\u0442\u0430\u0439\u0442\u0435 \u043e\u0442\u043d\u043e\u0432\u043e.",image_alt_text:"\u0418\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u043d\u0430 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\u0442\u0430 \u0441 reCAPTCHA",privacy_and_terms:"\u041f\u043e\u0432\u0435\u0440\u0438\u0442\u0435\u043b\u043d\u043e\u0441\u0442 \u0438 \u041e\u0431\u0449\u0438 \u0443\u0441\u043b\u043e\u0432\u0438\u044f"},
bn:{visual_challenge:"\u098f\u0995\u099f\u09bf \u09a6\u09c3\u09b6\u09cd\u09af\u09ae\u09be\u09a8 \u09aa\u09cd\u09b0\u09a4\u09bf\u09a6\u09cd\u09ac\u09a8\u09cd\u09a6\u09cd\u09ac\u09bf\u09a4\u09be \u09aa\u09be\u09a8",audio_challenge:"\u098f\u0995\u099f\u09bf \u0985\u09a1\u09bf\u0993 \u09aa\u09cd\u09b0\u09a4\u09bf\u09a6\u09cd\u09ac\u09a8\u09cd\u09a6\u09cd\u09ac\u09bf\u09a4\u09be  \u09aa\u09be\u09a8",refresh_btn:"\u098f\u0995\u099f\u09bf \u09a8\u09a4\u09c1\u09a8 \u09aa\u09cd\u09b0\u09a4\u09bf\u09a6\u09cd\u09ac\u09a8\u09cd\u09a6\u09cd\u09ac\u09bf\u09a4\u09be  \u09aa\u09be\u09a8",
instructions_visual:"",instructions_audio:"\u0986\u09aa\u09a8\u09bf \u09af\u09be \u09b6\u09c1\u09a8\u099b\u09c7\u09a8 \u09a4\u09be \u09b2\u09bf\u0996\u09c1\u09a8:",help_btn:"\u09b8\u09b9\u09be\u09df\u09a4\u09be",play_again:"\u0986\u09ac\u09be\u09b0 \u09b8\u09be\u0989\u09a8\u09cd\u09a1 \u09aa\u09cd\u09b2\u09c7 \u0995\u09b0\u09c1\u09a8",cant_hear_this:"MP3 \u09b0\u09c2\u09aa\u09c7 \u09b6\u09ac\u09cd\u09a6 \u09a1\u09be\u0989\u09a8\u09b2\u09cb\u09a1 \u0995\u09b0\u09c1\u09a8",incorrect_try_again:"\u09ac\u09c7\u09a0\u09bf\u0995\u09f7 \u0986\u09ac\u09be\u09b0 \u099a\u09c7\u09b7\u09cd\u099f\u09be \u0995\u09b0\u09c1\u09a8\u09f7",
image_alt_text:"reCAPTCHA \u099a\u09cd\u09af\u09be\u09b2\u09c7\u099e\u09cd\u099c \u099a\u09bf\u09a4\u09cd\u09b0",privacy_and_terms:"\u0997\u09cb\u09aa\u09a8\u09c0\u09af\u09bc\u09a4\u09be \u0993 \u09b6\u09b0\u09cd\u09a4\u09be\u09ac\u09b2\u09c0"},ca:{visual_challenge:"Obt\u00e9n un repte visual",audio_challenge:"Obteniu una pista sonora",refresh_btn:"Obteniu una pista nova",instructions_visual:"Escriviu el text:",instructions_audio:"Escriviu el que escolteu:",help_btn:"Ajuda",play_again:"Torna a reproduir el so",
cant_hear_this:"Baixa el so com a MP3",incorrect_try_again:"No \u00e9s correcte. Torna-ho a provar.",image_alt_text:"Imatge del repte de reCAPTCHA",privacy_and_terms:"Privadesa i condicions"},cs:{visual_challenge:"Zobrazit vizu\u00e1ln\u00ed podobu v\u00fdrazu",audio_challenge:"P\u0159ehr\u00e1t zvukovou podobu v\u00fdrazu",refresh_btn:"Zobrazit nov\u00fd v\u00fdraz",instructions_visual:"Zadejte text:",instructions_audio:"Napi\u0161te, co jste sly\u0161eli:",help_btn:"N\u00e1pov\u011bda",play_again:"Znovu p\u0159ehr\u00e1t zvuk",
cant_hear_this:"St\u00e1hnout zvuk ve form\u00e1tu MP3",incorrect_try_again:"\u0160patn\u011b. Zkuste to znovu.",image_alt_text:"Obr\u00e1zek reCAPTCHA",privacy_and_terms:"Ochrana soukrom\u00ed a smluvn\u00ed podm\u00ednky"},da:{visual_challenge:"Hent en visuel udfordring",audio_challenge:"Hent en lydudfordring",refresh_btn:"Hent en ny udfordring",instructions_visual:"Indtast teksten:",instructions_audio:"Indtast det, du h\u00f8rer:",help_btn:"Hj\u00e6lp",play_again:"Afspil lyden igen",cant_hear_this:"Download lyd som MP3",
incorrect_try_again:"Forkert. Pr\u00f8v igen.",image_alt_text:"reCAPTCHA-udfordringsbillede",privacy_and_terms:"Privatliv og vilk\u00e5r"},de:{visual_challenge:"Captcha abrufen",audio_challenge:"Audio-Captcha abrufen",refresh_btn:"Neues Captcha abrufen",instructions_visual:"Geben Sie den angezeigten Text ein:",instructions_audio:"Geben Sie das Geh\u00f6rte ein:",help_btn:"Hilfe",play_again:"Wort erneut abspielen",cant_hear_this:"Wort als MP3 herunterladen",incorrect_try_again:"Falsch. Bitte versuchen Sie es erneut.",
image_alt_text:"reCAPTCHA-Bild",privacy_and_terms:"Datenschutzerkl\u00e4rung & Nutzungsbedingungen"},el:{visual_challenge:"\u039f\u03c0\u03c4\u03b9\u03ba\u03ae \u03c0\u03c1\u03cc\u03ba\u03bb\u03b7\u03c3\u03b7",audio_challenge:"\u0397\u03c7\u03b7\u03c4\u03b9\u03ba\u03ae \u03c0\u03c1\u03cc\u03ba\u03bb\u03b7\u03c3\u03b7",refresh_btn:"\u039d\u03ad\u03b1 \u03c0\u03c1\u03cc\u03ba\u03bb\u03b7\u03c3\u03b7",instructions_visual:"\u03a0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf \u03ba\u03b5\u03af\u03bc\u03b5\u03bd\u03bf:",
instructions_audio:"\u03a0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03ae\u03c3\u03c4\u03b5 \u03cc\u03c4\u03b9 \u03b1\u03ba\u03bf\u03cd\u03c4\u03b5:",help_btn:"\u0392\u03bf\u03ae\u03b8\u03b5\u03b9\u03b1",play_again:"\u0391\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03b3\u03c9\u03b3\u03ae \u03ae\u03c7\u03bf\u03c5 \u03be\u03b1\u03bd\u03ac",cant_hear_this:"\u039b\u03ae\u03c8\u03b7 \u03ae\u03c7\u03bf\u03c5 \u03c9\u03c2 \u039c\u03a13",incorrect_try_again:"\u039b\u03ac\u03b8\u03bf\u03c2. \u0394\u03bf\u03ba\u03b9\u03bc\u03ac\u03c3\u03c4\u03b5 \u03be\u03b1\u03bd\u03ac.",
image_alt_text:"\u0395\u03b9\u03ba\u03cc\u03bd\u03b1 \u03c0\u03c1\u03cc\u03ba\u03bb\u03b7\u03c3\u03b7\u03c2 reCAPTCHA",privacy_and_terms:"\u0391\u03c0\u03cc\u03c1\u03c1\u03b7\u03c4\u03bf \u03ba\u03b1\u03b9 \u03cc\u03c1\u03bf\u03b9"},"en-GB":x,"en-US":x,es:ka,"es-419":{visual_challenge:"Enfrentar un desaf\u00edo visual",audio_challenge:"Enfrentar un desaf\u00edo de audio",refresh_btn:"Enfrentar un nuevo desaf\u00edo",instructions_visual:"Escriba el texto:",instructions_audio:"Escribe lo que escuchas:",
help_btn:"Ayuda",play_again:"Reproducir sonido de nuevo",cant_hear_this:"Descargar sonido en formato MP3",incorrect_try_again:"Incorrecto. Vuelve a intentarlo.",image_alt_text:"Imagen del desaf\u00edo de la reCAPTCHA",privacy_and_terms:"Privacidad y condiciones"},"es-ES":ka,et:{visual_challenge:"Kuva kuvap\u00f5hine robotil\u00f5ks",audio_challenge:"Kuva helip\u00f5hine robotil\u00f5ks",refresh_btn:"Kuva uus robotil\u00f5ks",instructions_visual:"Tippige tekst:",instructions_audio:"Tippige, mida kuulete.",
help_btn:"Abi",play_again:"Esita heli uuesti",cant_hear_this:"Laadi heli alla MP3-vormingus",incorrect_try_again:"Vale. Proovige uuesti.",image_alt_text:"reCAPTCHA robotil\u00f5ksu kujutis",privacy_and_terms:"Privaatsus ja tingimused"},eu:{visual_challenge:"Eskuratu ikusizko erronka",audio_challenge:"Eskuratu audio-erronka",refresh_btn:"Eskuratu erronka berria",instructions_visual:"",instructions_audio:"Idatzi entzuten duzuna:",help_btn:"Laguntza",play_again:"Erreproduzitu soinua berriro",cant_hear_this:"Deskargatu soinua MP3 gisa",
incorrect_try_again:"Ez da zuzena. Saiatu berriro.",image_alt_text:"reCAPTCHA erronkaren irudia",privacy_and_terms:"Pribatutasuna eta baldintzak"},fa:{visual_challenge:"\u062f\u0631\u06cc\u0627\u0641\u062a \u06cc\u06a9 \u0645\u0639\u0645\u0627\u06cc \u062f\u06cc\u062f\u0627\u0631\u06cc",audio_challenge:"\u062f\u0631\u06cc\u0627\u0641\u062a \u06cc\u06a9 \u0645\u0639\u0645\u0627\u06cc \u0635\u0648\u062a\u06cc",refresh_btn:"\u062f\u0631\u06cc\u0627\u0641\u062a \u06cc\u06a9 \u0645\u0639\u0645\u0627\u06cc \u062c\u062f\u06cc\u062f",
instructions_visual:"",instructions_audio:"\u0622\u0646\u0686\u0647 \u0631\u0627 \u06a9\u0647 \u0645\u06cc\u200c\u0634\u0646\u0648\u06cc\u062f \u062a\u0627\u06cc\u067e \u06a9\u0646\u06cc\u062f:",help_btn:"\u0631\u0627\u0647\u0646\u0645\u0627\u06cc\u06cc",play_again:"\u067e\u062e\u0634 \u0645\u062c\u062f\u062f \u0635\u062f\u0627",cant_hear_this:"\u062f\u0627\u0646\u0644\u0648\u062f \u0635\u062f\u0627 \u0628\u0647 \u0635\u0648\u0631\u062a MP3",incorrect_try_again:"\u0646\u0627\u062f\u0631\u0633\u062a. \u062f\u0648\u0628\u0627\u0631\u0647 \u0627\u0645\u062a\u062d\u0627\u0646 \u06a9\u0646\u06cc\u062f.",
image_alt_text:"\u062a\u0635\u0648\u06cc\u0631 \u0686\u0627\u0644\u0634\u06cc reCAPTCHA",privacy_and_terms:"\u062d\u0631\u06cc\u0645 \u062e\u0635\u0648\u0635\u06cc \u0648 \u0634\u0631\u0627\u06cc\u0637"},fi:{visual_challenge:"Kuvavahvistus",audio_challenge:"\u00c4\u00e4nivahvistus",refresh_btn:"Uusi kuva",instructions_visual:"Kirjoita teksti:",instructions_audio:"Kirjoita kuulemasi:",help_btn:"Ohje",play_again:"Toista \u00e4\u00e4ni uudelleen",cant_hear_this:"Lataa \u00e4\u00e4ni MP3-tiedostona",
incorrect_try_again:"V\u00e4\u00e4rin. Yrit\u00e4 uudelleen.",image_alt_text:"reCAPTCHA-kuva",privacy_and_terms:"Tietosuoja ja k\u00e4ytt\u00f6ehdot"},fil:la,fr:ma,"fr-CA":{visual_challenge:"Obtenir un test visuel",audio_challenge:"Obtenir un test audio",refresh_btn:"Obtenir un nouveau test",instructions_visual:"Saisissez le texte\u00a0:",instructions_audio:"Tapez ce que vous entendez\u00a0:",help_btn:"Aide",play_again:"Jouer le son de nouveau",cant_hear_this:"T\u00e9l\u00e9charger le son en format MP3",
incorrect_try_again:"Erreur, essayez \u00e0 nouveau",image_alt_text:"Image reCAPTCHA",privacy_and_terms:"Confidentialit\u00e9 et conditions d'utilisation"},"fr-FR":ma,gl:{visual_challenge:"Obter unha proba visual",audio_challenge:"Obter unha proba de audio",refresh_btn:"Obter unha proba nova",instructions_visual:"",instructions_audio:"Escribe o que escoitas:",help_btn:"Axuda",play_again:"Reproducir o son de novo",cant_hear_this:"Descargar son como MP3",incorrect_try_again:"Incorrecto. T\u00e9ntao de novo.",
image_alt_text:"Imaxe de proba de reCAPTCHA",privacy_and_terms:"Privacidade e condici\u00f3ns"},gu:{visual_challenge:"\u0a8f\u0a95 \u0aa6\u0ac3\u0ab6\u0acd\u0aaf\u0abe\u0aa4\u0acd\u0aae\u0a95 \u0aaa\u0aa1\u0a95\u0abe\u0ab0 \u0aae\u0ac7\u0ab3\u0ab5\u0acb",audio_challenge:"\u0a8f\u0a95 \u0a91\u0aa1\u0abf\u0a93 \u0aaa\u0aa1\u0a95\u0abe\u0ab0 \u0aae\u0ac7\u0ab3\u0ab5\u0acb",refresh_btn:"\u0a8f\u0a95 \u0aa8\u0ab5\u0acb \u0aaa\u0aa1\u0a95\u0abe\u0ab0 \u0aae\u0ac7\u0ab3\u0ab5\u0acb",instructions_visual:"",
instructions_audio:"\u0aa4\u0aae\u0ac7 \u0a9c\u0ac7 \u0ab8\u0abe\u0a82\u0aad\u0ab3\u0acb \u0a9b\u0acb \u0aa4\u0ac7 \u0ab2\u0a96\u0acb:",help_btn:"\u0ab8\u0ab9\u0abe\u0aaf",play_again:"\u0aa7\u0acd\u0ab5\u0aa8\u0abf \u0aab\u0ab0\u0ac0\u0aa5\u0ac0 \u0a9a\u0ab2\u0abe\u0ab5\u0acb",cant_hear_this:"MP3 \u0aa4\u0ab0\u0ac0\u0a95\u0ac7 \u0aa7\u0acd\u0ab5\u0aa8\u0abf\u0aa8\u0ac7 \u0aa1\u0abe\u0a89\u0aa8\u0ab2\u0acb\u0aa1 \u0a95\u0ab0\u0acb",incorrect_try_again:"\u0a96\u0acb\u0a9f\u0ac1\u0a82. \u0aab\u0ab0\u0ac0 \u0aaa\u0acd\u0ab0\u0aaf\u0abe\u0ab8 \u0a95\u0ab0\u0acb.",
image_alt_text:"reCAPTCHA \u0aaa\u0aa1\u0a95\u0abe\u0ab0 \u0a9b\u0aac\u0ac0",privacy_and_terms:"\u0a97\u0acb\u0aaa\u0aa8\u0ac0\u0aaf\u0aa4\u0abe \u0a85\u0aa8\u0ac7 \u0ab6\u0ab0\u0aa4\u0acb"},hi:{visual_challenge:"\u0915\u094b\u0908 \u0935\u093f\u091c\u0941\u0905\u0932 \u091a\u0941\u0928\u094c\u0924\u0940 \u0932\u0947\u0902",audio_challenge:"\u0915\u094b\u0908 \u0911\u0921\u093f\u092f\u094b \u091a\u0941\u0928\u094c\u0924\u0940 \u0932\u0947\u0902",refresh_btn:"\u0915\u094b\u0908 \u0928\u0908 \u091a\u0941\u0928\u094c\u0924\u0940 \u0932\u0947\u0902",
instructions_visual:"\u091f\u0947\u0915\u094d\u0938\u094d\u091f \u091f\u093e\u0907\u092a \u0915\u0930\u0947\u0902:",instructions_audio:"\u091c\u094b \u0906\u092a \u0938\u0941\u0928 \u0930\u0939\u0947 \u0939\u0948\u0902 \u0909\u0938\u0947 \u0932\u093f\u0916\u0947\u0902:",help_btn:"\u0938\u0939\u093e\u092f\u0924\u093e",play_again:"\u0927\u094d\u200d\u0935\u0928\u093f \u092a\u0941\u0928: \u091a\u0932\u093e\u090f\u0902",cant_hear_this:"\u0927\u094d\u200d\u0935\u0928\u093f \u0915\u094b MP3 \u0915\u0947 \u0930\u0942\u092a \u092e\u0947\u0902 \u0921\u093e\u0909\u0928\u0932\u094b\u0921 \u0915\u0930\u0947\u0902",
incorrect_try_again:"\u0917\u0932\u0924. \u092a\u0941\u0928: \u092a\u094d\u0930\u092f\u093e\u0938 \u0915\u0930\u0947\u0902.",image_alt_text:"reCAPTCHA \u091a\u0941\u0928\u094c\u0924\u0940 \u091a\u093f\u0924\u094d\u0930",privacy_and_terms:"\u0917\u094b\u092a\u0928\u0940\u092f\u0924\u093e \u0914\u0930 \u0936\u0930\u094d\u0924\u0947\u0902"},hr:{visual_challenge:"Dohvati vizualni upit",audio_challenge:"Dohvati zvu\u010dni upit",refresh_btn:"Dohvati novi upit",instructions_visual:"Unesite tekst:",instructions_audio:"Upi\u0161ite \u0161to \u010dujete:",
help_btn:"Pomo\u0107",play_again:"Ponovi zvuk",cant_hear_this:"Preuzmi zvuk u MP3 formatu",incorrect_try_again:"Nije to\u010dno. Poku\u0161ajte ponovno.",image_alt_text:"Slikovni izazov reCAPTCHA",privacy_and_terms:"Privatnost i odredbe"},hu:{visual_challenge:"Vizu\u00e1lis kih\u00edv\u00e1s k\u00e9r\u00e9se",audio_challenge:"Hangkih\u00edv\u00e1s k\u00e9r\u00e9se",refresh_btn:"\u00daj kih\u00edv\u00e1s k\u00e9r\u00e9se",instructions_visual:"\u00cdrja be a sz\u00f6veget:",instructions_audio:"\u00cdrja le, amit hall:",
help_btn:"S\u00fag\u00f3",play_again:"Hang ism\u00e9telt lej\u00e1tsz\u00e1sa",cant_hear_this:"Hang let\u00f6lt\u00e9se MP3 form\u00e1tumban",incorrect_try_again:"Hib\u00e1s. Pr\u00f3b\u00e1lkozzon \u00fajra.",image_alt_text:"reCAPTCHA ellen\u0151rz\u0151 k\u00e9p",privacy_and_terms:"Adatv\u00e9delem \u00e9s Szerz\u0151d\u00e9si Felt\u00e9telek"},hy:{visual_challenge:"\u054d\u057f\u0561\u0576\u0561\u056c \u057f\u0565\u057d\u0578\u0572\u0561\u056f\u0561\u0576 \u056d\u0576\u0564\u056b\u0580",audio_challenge:"\u054d\u057f\u0561\u0576\u0561\u056c \u0571\u0561\u0575\u0576\u0561\u0575\u056b\u0576 \u056d\u0576\u0564\u056b\u0580",
refresh_btn:"\u054d\u057f\u0561\u0576\u0561\u056c \u0576\u0578\u0580 \u056d\u0576\u0564\u056b\u0580",instructions_visual:"\u0544\u0578\u0582\u057f\u0584\u0561\u0563\u0580\u0565\u0584 \u057f\u0565\u0584\u057d\u057f\u0568\u055d",instructions_audio:"\u0544\u0578\u0582\u057f\u0584\u0561\u0563\u0580\u0565\u0584 \u0561\u0575\u0576, \u056b\u0576\u0579 \u056c\u057d\u0578\u0582\u0574 \u0565\u0584\u055d",help_btn:"\u0555\u0563\u0576\u0578\u0582\u0569\u0575\u0578\u0582\u0576",play_again:"\u0546\u057e\u0561\u0563\u0561\u0580\u056f\u0565\u056c \u0571\u0561\u0575\u0576\u0568 \u056f\u0580\u056f\u056b\u0576",
cant_hear_this:"\u0532\u0565\u057c\u0576\u0565\u056c \u0571\u0561\u0575\u0576\u0568 \u0578\u0580\u057a\u0565\u057d MP3",incorrect_try_again:"\u054d\u056d\u0561\u056c \u0567: \u0553\u0578\u0580\u0571\u0565\u0584 \u056f\u0580\u056f\u056b\u0576:",image_alt_text:"reCAPTCHA \u057a\u0561\u057f\u056f\u0565\u0580\u0578\u057e \u056d\u0576\u0564\u056b\u0580",privacy_and_terms:"\u0533\u0561\u0572\u057f\u0576\u056b\u0578\u0582\u0569\u0575\u0561\u0576 & \u057a\u0561\u0575\u0574\u0561\u0576\u0576\u0565\u0580"},
id:na,is:{visual_challenge:"F\u00e1 a\u00f0gangspr\u00f3f sem mynd",audio_challenge:"F\u00e1 a\u00f0gangspr\u00f3f sem hlj\u00f3\u00f0skr\u00e1",refresh_btn:"F\u00e1 n\u00fdtt a\u00f0gangspr\u00f3f",instructions_visual:"",instructions_audio:"Sl\u00e1\u00f0u inn \u00fea\u00f0 sem \u00fe\u00fa heyrir:",help_btn:"Hj\u00e1lp",play_again:"Spila hlj\u00f3\u00f0 aftur",cant_hear_this:"S\u00e6kja hlj\u00f3\u00f0 sem MP3",incorrect_try_again:"Rangt. Reyndu aftur.",image_alt_text:"mynd reCAPTCHA a\u00f0gangspr\u00f3fs",
privacy_and_terms:"Pers\u00f3nuvernd og skilm\u00e1lar"},it:{visual_challenge:"Verifica visiva",audio_challenge:"Verifica audio",refresh_btn:"Nuova verifica",instructions_visual:"Digita il testo:",instructions_audio:"Digita ci\u00f2 che senti:",help_btn:"Guida",play_again:"Riproduci di nuovo audio",cant_hear_this:"Scarica audio in MP3",incorrect_try_again:"Sbagliato. Riprova.",image_alt_text:"Immagine di verifica reCAPTCHA",privacy_and_terms:"Privacy e Termini"},iw:oa,ja:{visual_challenge:"\u753b\u50cf\u3067\u78ba\u8a8d\u3057\u307e\u3059",
audio_challenge:"\u97f3\u58f0\u3067\u78ba\u8a8d\u3057\u307e\u3059",refresh_btn:"\u5225\u306e\u5358\u8a9e\u3067\u3084\u308a\u76f4\u3057\u307e\u3059",instructions_visual:"\u30c6\u30ad\u30b9\u30c8\u3092\u5165\u529b:",instructions_audio:"\u805e\u3053\u3048\u305f\u5358\u8a9e\u3092\u5165\u529b\u3057\u307e\u3059:",help_btn:"\u30d8\u30eb\u30d7",play_again:"\u3082\u3046\u4e00\u5ea6\u805e\u304f",cant_hear_this:"MP3 \u3067\u97f3\u58f0\u3092\u30c0\u30a6\u30f3\u30ed\u30fc\u30c9",incorrect_try_again:"\u6b63\u3057\u304f\u3042\u308a\u307e\u305b\u3093\u3002\u3082\u3046\u4e00\u5ea6\u3084\u308a\u76f4\u3057\u3066\u304f\u3060\u3055\u3044\u3002",
image_alt_text:"reCAPTCHA \u78ba\u8a8d\u7528\u753b\u50cf",privacy_and_terms:"\u30d7\u30e9\u30a4\u30d0\u30b7\u30fc\u3068\u5229\u7528\u898f\u7d04"},kn:{visual_challenge:"\u0ca6\u0cc3\u0cb6\u0ccd\u0caf \u0cb8\u0cb5\u0cbe\u0cb2\u0cca\u0c82\u0ca6\u0ca8\u0ccd\u0ca8\u0cc1 \u0cb8\u0ccd\u0cb5\u0cc0\u0c95\u0cb0\u0cbf\u0cb8\u0cbf",audio_challenge:"\u0c86\u0ca1\u0cbf\u0caf\u0ccb \u0cb8\u0cb5\u0cbe\u0cb2\u0cca\u0c82\u0ca6\u0ca8\u0ccd\u0ca8\u0cc1 \u0cb8\u0ccd\u0cb5\u0cc0\u0c95\u0cb0\u0cbf\u0cb8\u0cbf",refresh_btn:"\u0cb9\u0cca\u0cb8 \u0cb8\u0cb5\u0cbe\u0cb2\u0cca\u0c82\u0ca6\u0ca8\u0ccd\u0ca8\u0cc1 \u0caa\u0ca1\u0cc6\u0caf\u0cbf\u0cb0\u0cbf",
instructions_visual:"",instructions_audio:"\u0ca8\u0cbf\u0cae\u0c97\u0cc6 \u0c95\u0cc7\u0cb3\u0cbf\u0cb8\u0cc1\u0cb5\u0cc1\u0ca6\u0ca8\u0ccd\u0ca8\u0cc1 \u0c9f\u0cc8\u0caa\u0ccd\u200c \u0cae\u0cbe\u0ca1\u0cbf:",help_btn:"\u0cb8\u0cb9\u0cbe\u0caf",play_again:"\u0ca7\u0ccd\u0cb5\u0ca8\u0cbf\u0caf\u0ca8\u0ccd\u0ca8\u0cc1 \u0cae\u0ca4\u0ccd\u0ca4\u0cc6 \u0caa\u0ccd\u0cb2\u0cc7 \u0cae\u0cbe\u0ca1\u0cbf",cant_hear_this:"\u0ca7\u0ccd\u0cb5\u0ca8\u0cbf\u0caf\u0ca8\u0ccd\u0ca8\u0cc1 MP3 \u0cb0\u0cc2\u0caa\u0ca6\u0cb2\u0ccd\u0cb2\u0cbf \u0ca1\u0ccc\u0ca8\u0ccd\u200c\u0cb2\u0ccb\u0ca1\u0ccd \u0cae\u0cbe\u0ca1\u0cbf",
incorrect_try_again:"\u0ca4\u0caa\u0ccd\u0caa\u0cbe\u0c97\u0cbf\u0ca6\u0cc6. \u0cae\u0ca4\u0ccd\u0ca4\u0cca\u0cae\u0ccd\u0cae\u0cc6 \u0caa\u0ccd\u0cb0\u0caf\u0ca4\u0ccd\u0ca8\u0cbf\u0cb8\u0cbf.",image_alt_text:"reCAPTCHA \u0cb8\u0cb5\u0cbe\u0cb2\u0cc1 \u0c9a\u0cbf\u0ca4\u0ccd\u0cb0",privacy_and_terms:"\u0c97\u0ccc\u0caa\u0ccd\u0caf\u0ca4\u0cc6 \u0cae\u0ca4\u0ccd\u0ca4\u0cc1 \u0ca8\u0cbf\u0caf\u0cae\u0c97\u0cb3\u0cc1"},ko:{visual_challenge:"\uadf8\ub9bc\uc73c\ub85c \ubcf4\uc548\ubb38\uc790 \ubc1b\uae30",
audio_challenge:"\uc74c\uc131\uc73c\ub85c \ubcf4\uc548\ubb38\uc790 \ubc1b\uae30",refresh_btn:"\ubcf4\uc548\ubb38\uc790 \uc0c8\ub85c \ubc1b\uae30",instructions_visual:"\ud14d\uc2a4\ud2b8 \uc785\ub825:",instructions_audio:"\uc74c\uc131 \ubcf4\uc548\ubb38\uc790 \uc785\ub825:",help_btn:"\ub3c4\uc6c0\ub9d0",play_again:"\uc74c\uc131 \ub2e4\uc2dc \ub4e3\uae30",cant_hear_this:"\uc74c\uc131\uc744 MP3\ub85c \ub2e4\uc6b4\ub85c\ub4dc",incorrect_try_again:"\ud2c0\ub838\uc2b5\ub2c8\ub2e4. \ub2e4\uc2dc \uc2dc\ub3c4\ud574 \uc8fc\uc138\uc694.",
image_alt_text:"reCAPTCHA \ubcf4\uc548\ubb38\uc790 \uc774\ubbf8\uc9c0",privacy_and_terms:"\uac1c\uc778\uc815\ubcf4 \ubcf4\ud638 \ubc0f \uc57d\uad00"},ln:ma,lt:{visual_challenge:"Gauti vaizdin\u012f atpa\u017einimo test\u0105",audio_challenge:"Gauti garso atpa\u017einimo test\u0105",refresh_btn:"Gauti nauj\u0105 atpa\u017einimo test\u0105",instructions_visual:"\u012eveskite tekst\u0105:",instructions_audio:"\u012eveskite tai, k\u0105 girdite:",help_btn:"Pagalba",play_again:"Dar kart\u0105 paleisti gars\u0105",
cant_hear_this:"Atsisi\u0173sti gars\u0105 kaip MP3",incorrect_try_again:"Neteisingai. Bandykite dar kart\u0105.",image_alt_text:"Testo \u201ereCAPTCHA\u201c vaizdas",privacy_and_terms:"Privatumas ir s\u0105lygos"},lv:{visual_challenge:"Sa\u0146emt vizu\u0101lu izaicin\u0101jumu",audio_challenge:"Sa\u0146emt audio izaicin\u0101jumu",refresh_btn:"Sa\u0146emt jaunu izaicin\u0101jumu",instructions_visual:"Ievadiet tekstu:",instructions_audio:"Ierakstiet dzirdamo:",help_btn:"Pal\u012bdz\u012bba",play_again:"V\u0113lreiz atska\u0146ot ska\u0146u",
cant_hear_this:"Lejupiel\u0101d\u0113t ska\u0146u MP3\u00a0form\u0101t\u0101",incorrect_try_again:"Nepareizi. M\u0113\u0123iniet v\u0113lreiz.",image_alt_text:"reCAPTCHA izaicin\u0101juma att\u0113ls",privacy_and_terms:"Konfidencialit\u0101te un noteikumi"},ml:{visual_challenge:"\u0d12\u0d30\u0d41 \u0d26\u0d43\u0d36\u0d4d\u0d2f \u0d1a\u0d32\u0d1e\u0d4d\u0d1a\u0d4d \u0d28\u0d47\u0d1f\u0d41\u0d15",audio_challenge:"\u0d12\u0d30\u0d41 \u0d13\u0d21\u0d3f\u0d2f\u0d4b \u0d1a\u0d32\u0d1e\u0d4d\u0d1a\u0d4d \u0d28\u0d47\u0d1f\u0d41\u0d15",
refresh_btn:"\u0d12\u0d30\u0d41 \u0d2a\u0d41\u0d24\u0d3f\u0d2f \u0d1a\u0d32\u0d1e\u0d4d\u0d1a\u0d4d \u0d28\u0d47\u0d1f\u0d41\u0d15",instructions_visual:"",instructions_audio:"\u0d15\u0d47\u0d7e\u0d15\u0d4d\u0d15\u0d41\u0d28\u0d4d\u0d28\u0d24\u0d4d \u0d1f\u0d48\u0d2a\u0d4d\u0d2a\u0d4d \u0d1a\u0d46\u0d2f\u0d4d\u0d2f\u0d42:",help_btn:"\u0d38\u0d39\u0d3e\u0d2f\u0d02",play_again:"\u0d36\u0d2c\u0d4d\u200c\u0d26\u0d02 \u0d35\u0d40\u0d23\u0d4d\u0d1f\u0d41\u0d02 \u0d2a\u0d4d\u0d32\u0d47 \u0d1a\u0d46\u0d2f\u0d4d\u0d2f\u0d41\u0d15",
cant_hear_this:"\u0d36\u0d2c\u0d4d\u200c\u0d26\u0d02 MP3 \u0d06\u0d2f\u0d3f \u0d21\u0d57\u0d7a\u0d32\u0d4b\u0d21\u0d4d \u0d1a\u0d46\u0d2f\u0d4d\u0d2f\u0d41\u0d15",incorrect_try_again:"\u0d24\u0d46\u0d31\u0d4d\u0d31\u0d3e\u0d23\u0d4d. \u0d35\u0d40\u0d23\u0d4d\u0d1f\u0d41\u0d02 \u0d36\u0d4d\u0d30\u0d2e\u0d3f\u0d15\u0d4d\u0d15\u0d41\u0d15.",image_alt_text:"reCAPTCHA \u0d1a\u0d32\u0d1e\u0d4d\u0d1a\u0d4d \u0d07\u0d2e\u0d47\u0d1c\u0d4d",privacy_and_terms:"\u0d38\u0d4d\u0d35\u0d15\u0d3e\u0d30\u0d4d\u0d2f\u0d24\u0d2f\u0d41\u0d02 \u0d28\u0d3f\u0d2c\u0d28\u0d4d\u0d27\u0d28\u0d15\u0d33\u0d41\u0d02"},
mr:{visual_challenge:"\u0926\u0943\u0936\u094d\u200d\u092f\u092e\u093e\u0928 \u0906\u0935\u094d\u0939\u093e\u0928 \u092a\u094d\u0930\u093e\u092a\u094d\u0924 \u0915\u0930\u093e",audio_challenge:"\u0911\u0921\u0940\u0913 \u0906\u0935\u094d\u0939\u093e\u0928 \u092a\u094d\u0930\u093e\u092a\u094d\u0924 \u0915\u0930\u093e",refresh_btn:"\u090f\u0915 \u0928\u0935\u0940\u0928 \u0906\u0935\u094d\u0939\u093e\u0928 \u092a\u094d\u0930\u093e\u092a\u094d\u0924 \u0915\u0930\u093e",instructions_visual:"",instructions_audio:"\u0906\u092a\u0932\u094d\u092f\u093e\u0932\u093e \u091c\u0947 \u0910\u0915\u0942 \u092f\u0947\u0908\u0932 \u0924\u0947 \u091f\u093e\u0907\u092a \u0915\u0930\u093e:",
help_btn:"\u092e\u0926\u0924",play_again:"\u0927\u094d\u200d\u0935\u0928\u0940 \u092a\u0941\u0928\u094d\u0939\u093e \u092a\u094d\u200d\u0932\u0947 \u0915\u0930\u093e",cant_hear_this:"MP3 \u0930\u0941\u092a\u093e\u0924 \u0927\u094d\u200d\u0935\u0928\u0940 \u0921\u093e\u0909\u0928\u0932\u094b\u0921 \u0915\u0930\u093e",incorrect_try_again:"\u0905\u092f\u094b\u0917\u094d\u200d\u092f. \u092a\u0941\u0928\u094d\u200d\u0939\u093e \u092a\u094d\u0930\u092f\u0924\u094d\u200d\u0928 \u0915\u0930\u093e.",image_alt_text:"reCAPTCHA \u0906\u0935\u094d\u200d\u0939\u093e\u0928 \u092a\u094d\u0930\u0924\u093f\u092e\u093e",
privacy_and_terms:"\u0917\u094b\u092a\u0928\u0940\u092f\u0924\u093e \u0906\u0923\u093f \u0905\u091f\u0940"},ms:{visual_challenge:"Dapatkan cabaran visual",audio_challenge:"Dapatkan cabaran audio",refresh_btn:"Dapatkan cabaran baru",instructions_visual:"Taipkan teksnya:",instructions_audio:"Taip apa yang didengari:",help_btn:"Bantuan",play_again:"Mainkan bunyi sekali lagi",cant_hear_this:"Muat turun bunyi sebagai MP3",incorrect_try_again:"Tidak betul. Cuba lagi.",image_alt_text:"Imej cabaran reCAPTCHA",
privacy_and_terms:"Privasi & Syarat"},nl:{visual_challenge:"Een visuele uitdaging proberen",audio_challenge:"Een audio-uitdaging proberen",refresh_btn:"Een nieuwe uitdaging proberen",instructions_visual:"Typ de tekst:",instructions_audio:"Typ wat u hoort:",help_btn:"Help",play_again:"Geluid opnieuw afspelen",cant_hear_this:"Geluid downloaden als MP3",incorrect_try_again:"Onjuist. Probeer het opnieuw.",image_alt_text:"reCAPTCHA-uitdagingsafbeelding",privacy_and_terms:"Privacy en voorwaarden"},no:{visual_challenge:"F\u00e5 en bildeutfordring",
audio_challenge:"F\u00e5 en lydutfordring",refresh_btn:"F\u00e5 en ny utfordring",instructions_visual:"Skriv inn teksten:",instructions_audio:"Skriv inn det du h\u00f8rer:",help_btn:"Hjelp",play_again:"Spill av lyd p\u00e5 nytt",cant_hear_this:"Last ned lyd som MP3",incorrect_try_again:"Feil. Pr\u00f8v p\u00e5 nytt.",image_alt_text:"reCAPTCHA-utfordringsbilde",privacy_and_terms:"Personvern og vilk\u00e5r"},pl:{visual_challenge:"Poka\u017c podpowied\u017a wizualn\u0105",audio_challenge:"Odtw\u00f3rz podpowied\u017a d\u017awi\u0119kow\u0105",
refresh_btn:"Nowa podpowied\u017a",instructions_visual:"Przepisz tekst:",instructions_audio:"Wpisz us\u0142yszane s\u0142owa:",help_btn:"Pomoc",play_again:"Odtw\u00f3rz d\u017awi\u0119k ponownie",cant_hear_this:"Pobierz d\u017awi\u0119k jako plik MP3",incorrect_try_again:"Nieprawid\u0142owo. Spr\u00f3buj ponownie.",image_alt_text:"Zadanie obrazkowe reCAPTCHA",privacy_and_terms:"Prywatno\u015b\u0107 i warunki"},pt:pa,"pt-BR":pa,"pt-PT":{visual_challenge:"Obter um desafio visual",audio_challenge:"Obter um desafio de \u00e1udio",
refresh_btn:"Obter um novo desafio",instructions_visual:"Introduza o texto:",instructions_audio:"Escreva o que ouvir:",help_btn:"Ajuda",play_again:"Reproduzir som novamente",cant_hear_this:"Transferir som como MP3",incorrect_try_again:"Incorreto. Tente novamente.",image_alt_text:"Imagem de teste reCAPTCHA",privacy_and_terms:"Privacidade e Termos de Utiliza\u00e7\u00e3o"},ro:qa,ru:{visual_challenge:"\u0412\u0438\u0437\u0443\u0430\u043b\u044c\u043d\u0430\u044f \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430",
audio_challenge:"\u0417\u0432\u0443\u043a\u043e\u0432\u0430\u044f \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430",refresh_btn:"\u041e\u0431\u043d\u043e\u0432\u0438\u0442\u044c",instructions_visual:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0442\u0435\u043a\u0441\u0442:",instructions_audio:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0442\u043e, \u0447\u0442\u043e \u0441\u043b\u044b\u0448\u0438\u0442\u0435:",help_btn:"\u0421\u043f\u0440\u0430\u0432\u043a\u0430",play_again:"\u041f\u0440\u043e\u0441\u043b\u0443\u0448\u0430\u0442\u044c \u0435\u0449\u0435 \u0440\u0430\u0437",
cant_hear_this:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c MP3-\u0444\u0430\u0439\u043b",incorrect_try_again:"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e. \u041f\u043e\u0432\u0442\u043e\u0440\u0438\u0442\u0435 \u043f\u043e\u043f\u044b\u0442\u043a\u0443.",image_alt_text:"\u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043f\u043e \u0441\u043b\u043e\u0432\u0443 reCAPTCHA",privacy_and_terms:"\u041f\u0440\u0430\u0432\u0438\u043b\u0430 \u0438 \u043f\u0440\u0438\u043d\u0446\u0438\u043f\u044b"},
sk:{visual_challenge:"Zobrazi\u0165 vizu\u00e1lnu podobu",audio_challenge:"Prehra\u0165 zvukov\u00fa podobu",refresh_btn:"Zobrazi\u0165 nov\u00fd v\u00fdraz",instructions_visual:"Zadajte text:",instructions_audio:"Zadajte, \u010do po\u010dujete:",help_btn:"Pomocn\u00edk",play_again:"Znova prehra\u0165 zvuk",cant_hear_this:"Prevzia\u0165 zvuk v podobe s\u00faboru MP3",incorrect_try_again:"Nespr\u00e1vne. Sk\u00faste to znova.",image_alt_text:"Obr\u00e1zok zadania reCAPTCHA",privacy_and_terms:"Ochrana osobn\u00fdch \u00fadajov a Zmluvn\u00e9 podmienky"},
sl:{visual_challenge:"Vizualni preskus",audio_challenge:"Zvo\u010dni preskus",refresh_btn:"Nov preskus",instructions_visual:"Vnesite besedilo:",instructions_audio:"Natipkajte, kaj sli\u0161ite:",help_btn:"Pomo\u010d",play_again:"Znova predvajaj zvok",cant_hear_this:"Prenesi zvok kot MP3",incorrect_try_again:"Napa\u010dno. Poskusite znova.",image_alt_text:"Slika izziva reCAPTCHA",privacy_and_terms:"Zasebnost in pogoji"},sr:{visual_challenge:"\u041f\u0440\u0438\u043c\u0438\u0442\u0435 \u0432\u0438\u0437\u0443\u0435\u043b\u043d\u0438 \u0443\u043f\u0438\u0442",
audio_challenge:"\u041f\u0440\u0438\u043c\u0438\u0442\u0435 \u0430\u0443\u0434\u0438\u043e \u0443\u043f\u0438\u0442",refresh_btn:"\u041f\u0440\u0438\u043c\u0438\u0442\u0435 \u043d\u043e\u0432\u0438 \u0443\u043f\u0438\u0442",instructions_visual:"\u0423\u043d\u0435\u0441\u0438\u0442\u0435 \u0442\u0435\u043a\u0441\u0442:",instructions_audio:"\u041e\u0442\u043a\u0443\u0446\u0430\u0458\u0442\u0435 \u043e\u043d\u043e \u0448\u0442\u043e \u0447\u0443\u0458\u0435\u0442\u0435:",help_btn:"\u041f\u043e\u043c\u043e\u045b",
play_again:"\u041f\u043e\u043d\u043e\u0432\u043e \u043f\u0443\u0441\u0442\u0438 \u0437\u0432\u0443\u043a",cant_hear_this:"\u041f\u0440\u0435\u0443\u0437\u043c\u0438 \u0437\u0432\u0443\u043a \u043a\u0430\u043e MP3 \u0441\u043d\u0438\u043c\u0430\u043a",incorrect_try_again:"\u041d\u0435\u0442\u0430\u0447\u043d\u043e. \u041f\u043e\u043a\u0443\u0448\u0430\u0458\u0442\u0435 \u043f\u043e\u043d\u043e\u0432\u043e.",image_alt_text:"\u0421\u043b\u0438\u043a\u0430 reCAPTCHA \u043f\u0440\u043e\u0432\u0435\u0440\u0435",
privacy_and_terms:"\u041f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0441\u0442 \u0438 \u0443\u0441\u043b\u043e\u0432\u0438"},sv:{visual_challenge:"H\u00e4mta captcha i bildformat",audio_challenge:"H\u00e4mta captcha i ljudformat",refresh_btn:"H\u00e4mta ny captcha",instructions_visual:"Skriv texten:",instructions_audio:"Skriv det du h\u00f6r:",help_btn:"Hj\u00e4lp",play_again:"Spela upp ljudet igen",cant_hear_this:"H\u00e4mta ljud som MP3",incorrect_try_again:"Fel. F\u00f6rs\u00f6k igen.",image_alt_text:"reCAPTCHA-bild",
privacy_and_terms:"Sekretess och villkor"},sw:{visual_challenge:"Pata herufi za kusoma",audio_challenge:"Pata herufi za kusikiliza",refresh_btn:"Pata herufi mpya",instructions_visual:"",instructions_audio:"Charaza unachosikia:",help_btn:"Usaidizi",play_again:"Cheza sauti tena",cant_hear_this:"Pakua sauti kama MP3",incorrect_try_again:"Sio sahihi. Jaribu tena.",image_alt_text:"picha ya changamoto ya reCAPTCHA",privacy_and_terms:"Faragha & Masharti"},ta:{visual_challenge:"\u0baa\u0bbe\u0bb0\u0bcd\u0bb5\u0bc8 \u0b9a\u0bc7\u0bb2\u0b9e\u0bcd\u0b9a\u0bc8\u0baa\u0bcd \u0baa\u0bc6\u0bb1\u0bc1\u0b95",
audio_challenge:"\u0b86\u0b9f\u0bbf\u0baf\u0bcb \u0b9a\u0bc7\u0bb2\u0b9e\u0bcd\u0b9a\u0bc8\u0baa\u0bcd \u0baa\u0bc6\u0bb1\u0bc1\u0b95",refresh_btn:"\u0baa\u0bc1\u0ba4\u0bbf\u0baf \u0b9a\u0bc7\u0bb2\u0b9e\u0bcd\u0b9a\u0bc8\u0baa\u0bcd \u0baa\u0bc6\u0bb1\u0bc1\u0b95",instructions_visual:"",instructions_audio:"\u0b95\u0bc7\u0b9f\u0bcd\u0baa\u0ba4\u0bc8 \u0b9f\u0bc8\u0baa\u0bcd \u0b9a\u0bc6\u0baf\u0bcd\u0b95:",help_btn:"\u0b89\u0ba4\u0bb5\u0bbf",play_again:"\u0b92\u0bb2\u0bbf\u0baf\u0bc8 \u0bae\u0bc0\u0ba3\u0bcd\u0b9f\u0bc1\u0bae\u0bcd \u0b87\u0baf\u0b95\u0bcd\u0b95\u0bc1",
cant_hear_this:"\u0b92\u0bb2\u0bbf\u0baf\u0bc8 MP3 \u0b86\u0b95 \u0baa\u0ba4\u0bbf\u0bb5\u0bbf\u0bb1\u0b95\u0bcd\u0b95\u0bc1\u0b95",incorrect_try_again:"\u0ba4\u0bb5\u0bb1\u0bbe\u0ba9\u0ba4\u0bc1. \u0bae\u0bc0\u0ba3\u0bcd\u0b9f\u0bc1\u0bae\u0bcd \u0bae\u0bc1\u0baf\u0bb2\u0bb5\u0bc1\u0bae\u0bcd.",image_alt_text:"reCAPTCHA \u0b9a\u0bc7\u0bb2\u0b9e\u0bcd\u0b9a\u0bcd \u0baa\u0b9f\u0bae\u0bcd",privacy_and_terms:"\u0ba4\u0ba9\u0bbf\u0baf\u0bc1\u0bb0\u0bbf\u0bae\u0bc8 & \u0bb5\u0bbf\u0ba4\u0bbf\u0bae\u0bc1\u0bb1\u0bc8\u0b95\u0bb3\u0bcd"},
te:{visual_challenge:"\u0c12\u0c15 \u0c26\u0c43\u0c36\u0c4d\u0c2f\u0c2e\u0c3e\u0c28 \u0c38\u0c35\u0c3e\u0c32\u0c41\u0c28\u0c41 \u0c38\u0c4d\u0c35\u0c40\u0c15\u0c30\u0c3f\u0c02\u0c1a\u0c02\u0c21\u0c3f",audio_challenge:"\u0c12\u0c15 \u0c06\u0c21\u0c3f\u0c2f\u0c4b \u0c38\u0c35\u0c3e\u0c32\u0c41\u0c28\u0c41 \u0c38\u0c4d\u0c35\u0c40\u0c15\u0c30\u0c3f\u0c02\u0c1a\u0c02\u0c21\u0c3f",refresh_btn:"\u0c15\u0c4d\u0c30\u0c4a\u0c24\u0c4d\u0c24 \u0c38\u0c35\u0c3e\u0c32\u0c41\u0c28\u0c41 \u0c38\u0c4d\u0c35\u0c40\u0c15\u0c30\u0c3f\u0c02\u0c1a\u0c02\u0c21\u0c3f",
instructions_visual:"",instructions_audio:"\u0c2e\u0c40\u0c30\u0c41 \u0c35\u0c3f\u0c28\u0c4d\u0c28\u0c26\u0c3f \u0c1f\u0c48\u0c2a\u0c4d \u0c1a\u0c47\u0c2f\u0c02\u0c21\u0c3f:",help_btn:"\u0c38\u0c39\u0c3e\u0c2f\u0c02",play_again:"\u0c27\u0c4d\u0c35\u0c28\u0c3f\u0c28\u0c3f \u0c2e\u0c33\u0c4d\u0c32\u0c40 \u0c2a\u0c4d\u0c32\u0c47 \u0c1a\u0c47\u0c2f\u0c3f",cant_hear_this:"\u0c27\u0c4d\u0c35\u0c28\u0c3f\u0c28\u0c3f MP3 \u0c35\u0c32\u0c46 \u0c21\u0c4c\u0c28\u0c4d\u200c\u0c32\u0c4b\u0c21\u0c4d \u0c1a\u0c47\u0c2f\u0c3f",
incorrect_try_again:"\u0c24\u0c2a\u0c4d\u0c2a\u0c41. \u0c2e\u0c33\u0c4d\u0c32\u0c40 \u0c2a\u0c4d\u0c30\u0c2f\u0c24\u0c4d\u0c28\u0c3f\u0c02\u0c1a\u0c02\u0c21\u0c3f.",image_alt_text:"reCAPTCHA \u0c38\u0c35\u0c3e\u0c32\u0c41 \u0c1a\u0c3f\u0c24\u0c4d\u0c30\u0c02",privacy_and_terms:"\u0c17\u0c4b\u0c2a\u0c4d\u0c2f\u0c24 & \u0c28\u0c3f\u0c2c\u0c02\u0c27\u0c28\u0c32\u0c41"},th:{visual_challenge:"\u0e23\u0e31\u0e1a\u0e04\u0e27\u0e32\u0e21\u0e17\u0e49\u0e32\u0e17\u0e32\u0e22\u0e14\u0e49\u0e32\u0e19\u0e20\u0e32\u0e1e",
audio_challenge:"\u0e23\u0e31\u0e1a\u0e04\u0e27\u0e32\u0e21\u0e17\u0e49\u0e32\u0e17\u0e32\u0e22\u0e14\u0e49\u0e32\u0e19\u0e40\u0e2a\u0e35\u0e22\u0e07",refresh_btn:"\u0e23\u0e31\u0e1a\u0e04\u0e27\u0e32\u0e21\u0e17\u0e49\u0e32\u0e17\u0e32\u0e22\u0e43\u0e2b\u0e21\u0e48",instructions_visual:"\u0e1e\u0e34\u0e21\u0e1e\u0e4c\u0e02\u0e49\u0e2d\u0e04\u0e27\u0e32\u0e21\u0e19\u0e35\u0e49:",instructions_audio:"\u0e1e\u0e34\u0e21\u0e1e\u0e4c\u0e2a\u0e34\u0e48\u0e07\u0e17\u0e35\u0e48\u0e04\u0e38\u0e13\u0e44\u0e14\u0e49\u0e22\u0e34\u0e19:",
help_btn:"\u0e04\u0e27\u0e32\u0e21\u0e0a\u0e48\u0e27\u0e22\u0e40\u0e2b\u0e25\u0e37\u0e2d",play_again:"\u0e40\u0e25\u0e48\u0e19\u0e40\u0e2a\u0e35\u0e22\u0e07\u0e2d\u0e35\u0e01\u0e04\u0e23\u0e31\u0e49\u0e07",cant_hear_this:"\u0e14\u0e32\u0e27\u0e42\u0e2b\u0e25\u0e14\u0e40\u0e2a\u0e35\u0e22\u0e07\u0e40\u0e1b\u0e47\u0e19 MP3",incorrect_try_again:"\u0e44\u0e21\u0e48\u0e16\u0e39\u0e01\u0e15\u0e49\u0e2d\u0e07 \u0e25\u0e2d\u0e07\u0e2d\u0e35\u0e01\u0e04\u0e23\u0e31\u0e49\u0e07",image_alt_text:"\u0e23\u0e2b\u0e31\u0e2a\u0e20\u0e32\u0e1e reCAPTCHA",
privacy_and_terms:"\u0e19\u0e42\u0e22\u0e1a\u0e32\u0e22\u0e2a\u0e48\u0e27\u0e19\u0e1a\u0e38\u0e04\u0e04\u0e25\u0e41\u0e25\u0e30\u0e02\u0e49\u0e2d\u0e01\u0e33\u0e2b\u0e19\u0e14"},tr:{visual_challenge:"G\u00f6rsel sorgu al",audio_challenge:"Sesli sorgu al",refresh_btn:"Yeniden y\u00fckle",instructions_visual:"Metni yaz\u0131n:",instructions_audio:"Duydu\u011funuzu yaz\u0131n:",help_btn:"Yard\u0131m",play_again:"Sesi tekrar \u00e7al",cant_hear_this:"Sesi MP3 olarak indir",incorrect_try_again:"Yanl\u0131\u015f. Tekrar deneyin.",
image_alt_text:"reCAPTCHA sorusu resmi",privacy_and_terms:"Gizlilik ve \u015eartlar"},uk:{visual_challenge:"\u041e\u0442\u0440\u0438\u043c\u0430\u0442\u0438 \u0432\u0456\u0437\u0443\u0430\u043b\u044c\u043d\u0438\u0439 \u0442\u0435\u043a\u0441\u0442",audio_challenge:"\u041e\u0442\u0440\u0438\u043c\u0430\u0442\u0438 \u0430\u0443\u0434\u0456\u043e\u0437\u0430\u043f\u0438\u0441",refresh_btn:"\u041e\u043d\u043e\u0432\u0438\u0442\u0438 \u0442\u0435\u043a\u0441\u0442",instructions_visual:"\u0412\u0432\u0435\u0434\u0456\u0442\u044c \u0442\u0435\u043a\u0441\u0442:",
instructions_audio:"\u0412\u0432\u0435\u0434\u0456\u0442\u044c \u043f\u043e\u0447\u0443\u0442\u0435:",help_btn:"\u0414\u043e\u0432\u0456\u0434\u043a\u0430",play_again:"\u0412\u0456\u0434\u0442\u0432\u043e\u0440\u0438\u0442\u0438 \u0437\u0430\u043f\u0438\u0441 \u0449\u0435 \u0440\u0430\u0437",cant_hear_this:"\u0417\u0430\u0432\u0430\u043d\u0442\u0430\u0436\u0438\u0442\u0438 \u0437\u0430\u043f\u0438\u0441 \u044f\u043a MP3",incorrect_try_again:"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e. \u0421\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435 \u0449\u0435 \u0440\u0430\u0437.",
image_alt_text:"\u0417\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u043d\u044f \u0437\u0430\u0432\u0434\u0430\u043d\u043d\u044f reCAPTCHA",privacy_and_terms:"\u041a\u043e\u043d\u0444\u0456\u0434\u0435\u043d\u0446\u0456\u0439\u043d\u0456\u0441\u0442\u044c \u0456 \u0443\u043c\u043e\u0432\u0438"},ur:{visual_challenge:"\u0627\u06cc\u06a9 \u0645\u0631\u0626\u06cc \u0686\u06cc\u0644\u0646\u062c \u062d\u0627\u0635\u0644 \u06a9\u0631\u06cc\u06ba",audio_challenge:"\u0627\u06cc\u06a9 \u0622\u0688\u06cc\u0648 \u0686\u06cc\u0644\u0646\u062c \u062d\u0627\u0635\u0644 \u06a9\u0631\u06cc\u06ba",
refresh_btn:"\u0627\u06cc\u06a9 \u0646\u06cc\u0627 \u0686\u06cc\u0644\u0646\u062c \u062d\u0627\u0635\u0644 \u06a9\u0631\u06cc\u06ba",instructions_visual:"",instructions_audio:"\u062c\u0648 \u0633\u0646\u0627\u0626\u06cc \u062f\u06cc\u062a\u0627 \u06c1\u06d2 \u0648\u06c1 \u0679\u0627\u0626\u067e \u06a9\u0631\u06cc\u06ba:",help_btn:"\u0645\u062f\u062f",play_again:"\u0622\u0648\u0627\u0632 \u062f\u0648\u0628\u0627\u0631\u06c1 \u0686\u0644\u0627\u0626\u06cc\u06ba",cant_hear_this:"\u0622\u0648\u0627\u0632 \u06a9\u0648 MP3 \u06a9\u06d2 \u0628\u0637\u0648\u0631 \u0688\u0627\u0624\u0646 \u0644\u0648\u0688 \u06a9\u0631\u06cc\u06ba",
incorrect_try_again:"\u063a\u0644\u0637\u06d4 \u062f\u0648\u0628\u0627\u0631\u06c1 \u06a9\u0648\u0634\u0634 \u06a9\u0631\u06cc\u06ba\u06d4",image_alt_text:"reCAPTCHA \u0686\u06cc\u0644\u0646\u062c \u0648\u0627\u0644\u06cc \u0634\u0628\u06cc\u06c1",privacy_and_terms:"\u0631\u0627\u0632\u062f\u0627\u0631\u06cc \u0648 \u0634\u0631\u0627\u0626\u0637"},vi:{visual_challenge:"Nh\u1eadn th\u1eed th\u00e1ch h\u00ecnh \u1ea3nh",audio_challenge:"Nh\u1eadn th\u1eed th\u00e1ch \u00e2m thanh",refresh_btn:"Nh\u1eadn th\u1eed th\u00e1ch m\u1edbi",
instructions_visual:"Nh\u1eadp v\u0103n b\u1ea3n:",instructions_audio:"Nh\u1eadp n\u1ed9i dung b\u1ea1n nghe th\u1ea5y:",help_btn:"Tr\u1ee3 gi\u00fap",play_again:"Ph\u00e1t l\u1ea1i \u00e2m thanh",cant_hear_this:"T\u1ea3i \u00e2m thanh xu\u1ed1ng d\u01b0\u1edbi d\u1ea1ng MP3",incorrect_try_again:"Kh\u00f4ng ch\u00ednh x\u00e1c. H\u00e3y th\u1eed l\u1ea1i.",image_alt_text:"H\u00ecnh x\u00e1c th\u1ef1c reCAPTCHA",privacy_and_terms:"B\u1ea3o m\u1eadt v\u00e0 \u0111i\u1ec1u kho\u1ea3n"},"zh-CN":ra,"zh-HK":{visual_challenge:"\u56de\u7b54\u5716\u50cf\u9a57\u8b49\u554f\u984c",
audio_challenge:"\u53d6\u5f97\u8a9e\u97f3\u9a57\u8b49\u554f\u984c",refresh_btn:"\u63db\u4e00\u500b\u9a57\u8b49\u554f\u984c",instructions_visual:"\u8f38\u5165\u6587\u5b57\uff1a",instructions_audio:"\u9375\u5165\u60a8\u6240\u807d\u5230\u7684\uff1a",help_btn:"\u8aaa\u660e",play_again:"\u518d\u6b21\u64ad\u653e\u8072\u97f3",cant_hear_this:"\u5c07\u8072\u97f3\u4e0b\u8f09\u70ba MP3",incorrect_try_again:"\u4e0d\u6b63\u78ba\uff0c\u518d\u8a66\u4e00\u6b21\u3002",image_alt_text:"reCAPTCHA \u9a57\u8b49\u6587\u5b57\u5716\u7247",
privacy_and_terms:"\u79c1\u96b1\u6b0a\u8207\u689d\u6b3e"},"zh-TW":{visual_challenge:"\u53d6\u5f97\u5716\u7247\u9a57\u8b49\u554f\u984c",audio_challenge:"\u53d6\u5f97\u8a9e\u97f3\u9a57\u8b49\u554f\u984c",refresh_btn:"\u53d6\u5f97\u65b0\u7684\u9a57\u8b49\u554f\u984c",instructions_visual:"\u8acb\u8f38\u5165\u5716\u7247\u4e2d\u7684\u6587\u5b57\uff1a",instructions_audio:"\u8acb\u8f38\u5165\u8a9e\u97f3\u5167\u5bb9\uff1a",help_btn:"\u8aaa\u660e",play_again:"\u518d\u6b21\u64ad\u653e",cant_hear_this:"\u4ee5 MP3 \u683c\u5f0f\u4e0b\u8f09\u8072\u97f3",
incorrect_try_again:"\u9a57\u8b49\u78bc\u6709\u8aa4\uff0c\u8acb\u518d\u8a66\u4e00\u6b21\u3002",image_alt_text:"reCAPTCHA \u9a57\u8b49\u6587\u5b57\u5716\u7247",privacy_and_terms:"\u96b1\u79c1\u6b0a\u8207\u689d\u6b3e"},zu:{visual_challenge:"Thola inselelo ebonakalayo",audio_challenge:"Thola inselelo yokulalelwayo",refresh_btn:"Thola inselelo entsha",instructions_visual:"",instructions_audio:"Bhala okuzwayo:",help_btn:"Usizo",play_again:"Phinda udlale okulalelwayo futhi",cant_hear_this:"Layisha umsindo njenge-MP3",
incorrect_try_again:"Akulungile. Zama futhi.",image_alt_text:"umfanekiso oyinselelo we-reCAPTCHA",privacy_and_terms:"Okwangasese kanye nemigomo"},tl:la,he:oa,"in":na,mo:qa,zh:ra};var y=function(a){if(Error.captureStackTrace)Error.captureStackTrace(this,y);else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))};v(y,Error);y.prototype.name="CustomError";var ta;var ua=function(a,b){for(var c=a.split("%s"),d="",e=Array.prototype.slice.call(arguments,1);e.length&&1<c.length;)d+=c.shift()+e.shift();return d+c.join("%s")},va=String.prototype.trim?function(a){return a.trim()}:function(a){return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},Da=function(a){if(!wa.test(a))return a;-1!=a.indexOf("&")&&(a=a.replace(xa,"&amp;"));-1!=a.indexOf("<")&&(a=a.replace(ya,"&lt;"));-1!=a.indexOf(">")&&(a=a.replace(za,"&gt;"));-1!=a.indexOf('"')&&(a=a.replace(Aa,"&quot;"));-1!=a.indexOf("'")&&
(a=a.replace(Ba,"&#39;"));-1!=a.indexOf("\x00")&&(a=a.replace(Ca,"&#0;"));return a},xa=/&/g,ya=/</g,za=/>/g,Aa=/"/g,Ba=/'/g,Ca=/\x00/g,wa=/[\x00&<>"']/,Ea=function(a,b){return a<b?-1:a>b?1:0},Fa=function(a){return String(a).replace(/\-([a-z])/g,function(a,c){return c.toUpperCase()})},Ga=function(a){var b=q(void 0)?"undefined".replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08"):"\\s";return a.replace(new RegExp("(^"+(b?"|["+b+"]+":"")+")([a-z])","g"),function(a,b,e){return b+e.toUpperCase()})};var Ha=function(a,b){b.unshift(a);y.call(this,ua.apply(null,b));b.shift()};v(Ha,y);Ha.prototype.name="AssertionError";
var Ia=function(a,b,c,d){var e="Assertion failed";if(c)var e=e+(": "+c),g=d;else a&&(e+=": "+a,g=b);throw new Ha(""+e,g||[]);},z=function(a,b,c){a||Ia("",null,b,Array.prototype.slice.call(arguments,2))},Ja=function(a,b){throw new Ha("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));},Ka=function(a,b,c){q(a)||Ia("Expected string but got %s: %s.",[n(a),a],b,Array.prototype.slice.call(arguments,2));return a},La=function(a,b,c){r(a)||Ia("Expected function but got %s: %s.",[n(a),a],b,Array.prototype.slice.call(arguments,
2))};var A=Array.prototype,Ma=A.indexOf?function(a,b,c){z(null!=a.length);return A.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(q(a))return q(b)&&1==b.length?a.indexOf(b,c):-1;for(;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1},Na=A.forEach?function(a,b,c){z(null!=a.length);A.forEach.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=q(a)?a.split(""):a,g=0;g<d;g++)g in e&&b.call(c,e[g],g,a)},Oa=A.map?function(a,b,c){z(null!=a.length);return A.map.call(a,b,c)}:
function(a,b,c){for(var d=a.length,e=Array(d),g=q(a)?a.split(""):a,f=0;f<d;f++)f in g&&(e[f]=b.call(c,g[f],f,a));return e},Pa=A.some?function(a,b,c){z(null!=a.length);return A.some.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=q(a)?a.split(""):a,g=0;g<d;g++)if(g in e&&b.call(c,e[g],g,a))return!0;return!1},Qa=function(a,b){var c=Ma(a,b),d;if(d=0<=c)z(null!=a.length),A.splice.call(a,c,1);return d},Ra=function(a){var b=a.length;if(0<b){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}return[]},
Sa=function(a,b,c){z(null!=a.length);return 2>=arguments.length?A.slice.call(a,b):A.slice.call(a,b,c)};var Ta=function(a,b){for(var c in a)b.call(void 0,a[c],c,a)},Ua=function(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b},Va=function(a){for(var b in a)return!1;return!0},Xa=function(){var a=Wa()?k.google_ad:null,b={},c;for(c in a)b[c]=a[c];return b},Ya="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),Za=function(a,b){for(var c,d,e=1;e<arguments.length;e++){d=arguments[e];for(c in d)a[c]=d[c];for(var g=0;g<Ya.length;g++)c=Ya[g],Object.prototype.hasOwnProperty.call(d,
c)&&(a[c]=d[c])}},$a=function(a){var b=arguments.length;if(1==b&&p(arguments[0]))return $a.apply(null,arguments[0]);for(var c={},d=0;d<b;d++)c[arguments[d]]=!0;return c};var B;t:{var ab=k.navigator;if(ab){var bb=ab.userAgent;if(bb){B=bb;break t}}B=""};var cb=-1!=B.indexOf("Opera")||-1!=B.indexOf("OPR"),C=-1!=B.indexOf("Trident")||-1!=B.indexOf("MSIE"),E=-1!=B.indexOf("Gecko")&&-1==B.toLowerCase().indexOf("webkit")&&!(-1!=B.indexOf("Trident")||-1!=B.indexOf("MSIE")),F=-1!=B.toLowerCase().indexOf("webkit"),db=function(){var a=k.document;return a?a.documentMode:void 0},eb=function(){var a="",b;if(cb&&k.opera)return a=k.opera.version,r(a)?a():a;E?b=/rv\:([^\);]+)(\)|;)/:C?b=/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/:F&&(b=/WebKit\/(\S+)/);b&&(a=(a=b.exec(B))?
a[1]:"");return C&&(b=db(),b>parseFloat(a))?String(b):a}(),fb={},G=function(a){var b;if(!(b=fb[a])){b=0;for(var c=va(String(eb)).split("."),d=va(String(a)).split("."),e=Math.max(c.length,d.length),g=0;0==b&&g<e;g++){var f=c[g]||"",m=d[g]||"",D=RegExp("(\\d*)(\\D*)","g"),M=RegExp("(\\d*)(\\D*)","g");do{var I=D.exec(f)||["","",""],aa=M.exec(m)||["","",""];if(0==I[0].length&&0==aa[0].length)break;b=Ea(0==I[1].length?0:parseInt(I[1],10),0==aa[1].length?0:parseInt(aa[1],10))||Ea(0==I[2].length,0==aa[2].length)||
Ea(I[2],aa[2])}while(0==b)}b=fb[a]=0<=b}return b},gb=k.document,hb=gb&&C?db()||("CSS1Compat"==gb.compatMode?parseInt(eb,10):5):void 0;var ib=function(a){if(8192>a.length)return String.fromCharCode.apply(null,a);for(var b="",c=0;c<a.length;c+=8192)var d=Sa(a,c,c+8192),b=b+String.fromCharCode.apply(null,d);return b},jb=function(a){return Oa(a,function(a){a=a.toString(16);return 1<a.length?a:"0"+a}).join("")};var kb=null,lb=null,mb=function(a){if(!kb){kb={};lb={};for(var b=0;65>b;b++)kb[b]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(b),lb[kb[b]]=b,62<=b&&(lb["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(b)]=b)}for(var b=lb,c=[],d=0;d<a.length;){var e=b[a.charAt(d++)],g=d<a.length?b[a.charAt(d)]:0;++d;var f=d<a.length?b[a.charAt(d)]:64;++d;var m=d<a.length?b[a.charAt(d)]:64;++d;if(null==e||null==g||null==f||null==m)throw Error();c.push(e<<2|g>>
4);64!=f&&(c.push(g<<4&240|f>>2),64!=m&&c.push(f<<6&192|m))}return c};var H=function(){this.disposed_=this.disposed_;this.onDisposeCallbacks_=this.onDisposeCallbacks_};H.prototype.disposed_=!1;H.prototype.dispose=function(){this.disposed_||(this.disposed_=!0,this.disposeInternal())};var nb=function(a,b){a.disposed_?b.call(void 0):(a.onDisposeCallbacks_||(a.onDisposeCallbacks_=[]),a.onDisposeCallbacks_.push(l(void 0)?t(b,void 0):b))};H.prototype.disposeInternal=function(){if(this.onDisposeCallbacks_)for(;this.onDisposeCallbacks_.length;)this.onDisposeCallbacks_.shift()()};
var ob=function(a){a&&"function"==typeof a.dispose&&a.dispose()};$a("area base br col command embed hr img input keygen link meta param source track wbr".split(" "));$a("action","cite","data","formaction","href","manifest","poster","src");$a("embed","iframe","link","object","script","style","template");var pb=!C||C&&9<=hb;!E&&!C||C&&C&&9<=hb||E&&G("1.9.1");C&&G("9");var sb=function(a){return a?new qb(rb(a)):ta||(ta=new qb)},tb=function(a,b){return q(b)?a.getElementById(b):b},vb=function(a,b){Ta(b,function(b,d){"style"==d?a.style.cssText=b:"class"==d?a.className=b:"for"==d?a.htmlFor=b:d in ub?a.setAttribute(ub[d],b):0==d.lastIndexOf("aria-",0)||0==d.lastIndexOf("data-",0)?a.setAttribute(d,b):a[d]=b})},ub={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",role:"role",rowspan:"rowSpan",
type:"type",usemap:"useMap",valign:"vAlign",width:"width"},xb=function(a,b,c){return wb(document,arguments)},wb=function(a,b){var c=b[0],d=b[1];if(!pb&&d&&(d.name||d.type)){c=["<",c];d.name&&c.push(' name="',Da(d.name),'"');if(d.type){c.push(' type="',Da(d.type),'"');var e={};Za(e,d);delete e.type;d=e}c.push(">");c=c.join("")}c=a.createElement(c);d&&(q(d)?c.className=d:p(d)?c.className=d.join(" "):vb(c,d));2<b.length&&yb(a,c,b);return c},yb=function(a,b,c){function d(c){c&&b.appendChild(q(c)?a.createTextNode(c):
c)}for(var e=2;e<c.length;e++){var g=c[e];!ca(g)||da(g)&&0<g.nodeType?d(g):Na(zb(g)?Ra(g):g,d)}},Ab=function(a){for(var b;b=a.firstChild;)a.removeChild(b)},Bb=function(a){a&&a.parentNode&&a.parentNode.removeChild(a)},rb=function(a){z(a,"Node cannot be null or undefined.");return 9==a.nodeType?a:a.ownerDocument||a.document},zb=function(a){if(a&&"number"==typeof a.length){if(da(a))return"function"==typeof a.item||"string"==typeof a.item;if(r(a))return"function"==typeof a.item}return!1},qb=function(a){this.document_=
a||k.document||document};h=qb.prototype;h.getDomHelper=sb;h.getElement=function(a){return tb(this.document_,a)};h.$=qb.prototype.getElement;h.createDom=function(a,b,c){return wb(this.document_,arguments)};h.createElement=function(a){return this.document_.createElement(a)};h.createTextNode=function(a){return this.document_.createTextNode(String(a))};h.appendChild=function(a,b){a.appendChild(b)};var Cb=function(a){k.setTimeout(function(){throw a;},0)},Db,Eb=function(){var a=k.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&(a=function(){var a=document.createElement("iframe");a.style.display="none";a.src="";document.documentElement.appendChild(a);var b=a.contentWindow,a=b.document;a.open();a.write("");a.close();var c="callImmediate"+Math.random(),d="file:"==b.location.protocol?"*":b.location.protocol+"//"+b.location.host,a=t(function(a){if(("*"==
d||a.origin==d)&&a.data==c)this.port1.onmessage()},this);b.addEventListener("message",a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(c,d)}}});if("undefined"!==typeof a&&-1==B.indexOf("Trident")&&-1==B.indexOf("MSIE")){var b=new a,c={},d=c;b.port1.onmessage=function(){if(l(c.next)){c=c.next;var a=c.cb;c.cb=null;a()}};return function(a){d.next={cb:a};d=d.next;b.port2.postMessage(0)}}return"undefined"!==typeof document&&"onreadystatechange"in document.createElement("script")?function(a){var b=
document.createElement("script");b.onreadystatechange=function(){b.onreadystatechange=null;b.parentNode.removeChild(b);b=null;a();a=null};document.documentElement.appendChild(b)}:function(a){k.setTimeout(a,0)}};var Kb=function(a,b){Fb||Gb();Hb||(Fb(),Hb=!0);Ib.push(new Jb(a,b))},Fb,Gb=function(){if(k.Promise&&k.Promise.resolve){var a=k.Promise.resolve();Fb=function(){a.then(Lb)}}else Fb=function(){var a=Lb;!r(k.setImmediate)||k.Window&&k.Window.prototype.setImmediate==k.setImmediate?(Db||(Db=Eb()),Db(a)):k.setImmediate(a)}},Hb=!1,Ib=[],Lb=function(){for(;Ib.length;){var a=Ib;Ib=[];for(var b=0;b<a.length;b++){var c=a[b];try{c.fn.call(c.scope)}catch(d){Cb(d)}}}Hb=!1},Jb=function(a,b){this.fn=a;this.scope=
b};var Mb=function(a){a.prototype.then=a.prototype.then;a.prototype.$goog_Thenable=!0},Nb=function(a){if(!a)return!1;try{return!!a.$goog_Thenable}catch(b){return!1}};var L=function(a,b){this.state_=0;this.result_=void 0;this.callbackEntries_=this.parent_=null;this.hadUnhandledRejection_=this.executing_=!1;try{var c=this;a.call(b,function(a){J(c,2,a)},function(a){if(!(a instanceof K))try{if(a instanceof Error)throw a;throw Error("Promise rejected.");}catch(b){}J(c,3,a)})}catch(d){J(this,3,d)}};
L.prototype.then=function(a,b,c){null!=a&&La(a,"opt_onFulfilled should be a function.");null!=b&&La(b,"opt_onRejected should be a function. Did you pass opt_context as the second argument instead of the third?");return Ob(this,r(a)?a:null,r(b)?b:null,c)};Mb(L);L.prototype.cancel=function(a){0==this.state_&&Kb(function(){var b=new K(a);Pb(this,b)},this)};
var Pb=function(a,b){if(0==a.state_)if(a.parent_){var c=a.parent_;if(c.callbackEntries_){for(var d=0,e=-1,g=0,f;f=c.callbackEntries_[g];g++)if(f=f.child)if(d++,f==a&&(e=g),0<=e&&1<d)break;0<=e&&(0==c.state_&&1==d?Pb(c,b):(d=c.callbackEntries_.splice(e,1)[0],Qb(c,d,3,b)))}}else J(a,3,b)},Sb=function(a,b){a.callbackEntries_&&a.callbackEntries_.length||2!=a.state_&&3!=a.state_||Rb(a);a.callbackEntries_||(a.callbackEntries_=[]);a.callbackEntries_.push(b)},Ob=function(a,b,c,d){var e={child:null,onFulfilled:null,
onRejected:null};e.child=new L(function(a,f){e.onFulfilled=b?function(c){try{var e=b.call(d,c);a(e)}catch(M){f(M)}}:a;e.onRejected=c?function(b){try{var e=c.call(d,b);!l(e)&&b instanceof K?f(b):a(e)}catch(M){f(M)}}:f});e.child.parent_=a;Sb(a,e);return e.child};L.prototype.unblockAndFulfill_=function(a){z(1==this.state_);this.state_=0;J(this,2,a)};L.prototype.unblockAndReject_=function(a){z(1==this.state_);this.state_=0;J(this,3,a)};
var J=function(a,b,c){if(0==a.state_){if(a==c)b=3,c=new TypeError("Promise cannot resolve to itself");else{if(Nb(c)){a.state_=1;c.then(a.unblockAndFulfill_,a.unblockAndReject_,a);return}if(da(c))try{var d=c.then;if(r(d)){Tb(a,c,d);return}}catch(e){b=3,c=e}}a.result_=c;a.state_=b;Rb(a);3!=b||c instanceof K||Ub(a,c)}},Tb=function(a,b,c){a.state_=1;var d=!1,e=function(b){d||(d=!0,a.unblockAndFulfill_(b))},g=function(b){d||(d=!0,a.unblockAndReject_(b))};try{c.call(b,e,g)}catch(f){g(f)}},Rb=function(a){a.executing_||
(a.executing_=!0,Kb(a.executeCallbacks_,a))};L.prototype.executeCallbacks_=function(){for(;this.callbackEntries_&&this.callbackEntries_.length;){var a=this.callbackEntries_;this.callbackEntries_=[];for(var b=0;b<a.length;b++)Qb(this,a[b],this.state_,this.result_)}this.executing_=!1};
var Qb=function(a,b,c,d){if(2==c)b.onFulfilled(d);else{if(b.child)for(;a&&a.hadUnhandledRejection_;a=a.parent_)a.hadUnhandledRejection_=!1;b.onRejected(d)}},Ub=function(a,b){a.hadUnhandledRejection_=!0;Kb(function(){a.hadUnhandledRejection_&&Vb.call(null,b)})},Vb=Cb,K=function(a){y.call(this,a)};v(K,y);K.prototype.name="cancel";/*
 Portions of this code are from MochiKit, received by
 The Closure Authors under the MIT license. All other code is Copyright
 2005-2009 The Closure Authors. All Rights Reserved.
*/
var N=function(a,b){this.sequence_=[];this.onCancelFunction_=a;this.defaultScope_=b||null;this.hadError_=this.fired_=!1;this.result_=void 0;this.silentlyCanceled_=this.blocking_=this.blocked_=!1;this.unhandledErrorId_=0;this.parent_=null;this.branches_=0};
N.prototype.cancel=function(a){if(this.fired_)this.result_ instanceof N&&this.result_.cancel();else{if(this.parent_){var b=this.parent_;delete this.parent_;a?b.cancel(a):(b.branches_--,0>=b.branches_&&b.cancel())}this.onCancelFunction_?this.onCancelFunction_.call(this.defaultScope_,this):this.silentlyCanceled_=!0;this.fired_||Wb(this,new Xb)}};N.prototype.continue_=function(a,b){this.blocked_=!1;Yb(this,a,b)};
var Yb=function(a,b,c){a.fired_=!0;a.result_=c;a.hadError_=!b;Zb(a)},ac=function(a){if(a.fired_){if(!a.silentlyCanceled_)throw new $b;a.silentlyCanceled_=!1}};N.prototype.callback=function(a){ac(this);bc(a);Yb(this,!0,a)};var Wb=function(a,b){ac(a);bc(b);Yb(a,!1,b)},bc=function(a){z(!(a instanceof N),"An execution sequence may not be initiated with a blocking Deferred.")},cc=function(a,b,c,d){z(!a.blocking_,"Blocking Deferreds can not be re-used");a.sequence_.push([b,c,d]);a.fired_&&Zb(a)};
N.prototype.then=function(a,b,c){var d,e,g=new L(function(a,b){d=a;e=b});cc(this,d,function(a){a instanceof Xb?g.cancel():e(a)});return g.then(a,b,c)};Mb(N);
var dc=function(a){return Pa(a.sequence_,function(a){return r(a[1])})},Zb=function(a){if(a.unhandledErrorId_&&a.fired_&&dc(a)){var b=a.unhandledErrorId_,c=ec[b];c&&(k.clearTimeout(c.id_),delete ec[b]);a.unhandledErrorId_=0}a.parent_&&(a.parent_.branches_--,delete a.parent_);for(var b=a.result_,d=c=!1;a.sequence_.length&&!a.blocked_;){var e=a.sequence_.shift(),g=e[0],f=e[1],e=e[2];if(g=a.hadError_?f:g)try{var m=g.call(e||a.defaultScope_,b);l(m)&&(a.hadError_=a.hadError_&&(m==b||m instanceof Error),
a.result_=b=m);Nb(b)&&(d=!0,a.blocked_=!0)}catch(D){b=D,a.hadError_=!0,dc(a)||(c=!0)}}a.result_=b;d&&(m=t(a.continue_,a,!0),d=t(a.continue_,a,!1),b instanceof N?(cc(b,m,d),b.blocking_=!0):b.then(m,d));c&&(b=new fc(b),ec[b.id_]=b,a.unhandledErrorId_=b.id_)},$b=function(){y.call(this)};v($b,y);$b.prototype.message="Deferred has already fired";$b.prototype.name="AlreadyCalledError";var Xb=function(){y.call(this)};v(Xb,y);Xb.prototype.message="Deferred was canceled";Xb.prototype.name="CanceledError";
var fc=function(a){this.id_=k.setTimeout(t(this.throwError,this),0);this.error_=a};fc.prototype.throwError=function(){z(ec[this.id_],"Cannot throw an error that is not scheduled.");delete ec[this.id_];throw this.error_;};var ec={};var kc=function(a){var b={},c=b.document||document,d=document.createElement("SCRIPT"),e={script_:d,timeout_:void 0},g=new N(gc,e),f=null,m=null!=b.timeout?b.timeout:5E3;0<m&&(f=window.setTimeout(function(){hc(d,!0);Wb(g,new ic(1,"Timeout reached for loading script "+a))},m),e.timeout_=f);d.onload=d.onreadystatechange=function(){d.readyState&&"loaded"!=d.readyState&&"complete"!=d.readyState||(hc(d,b.cleanupWhenDone||!1,f),g.callback(null))};d.onerror=function(){hc(d,!0,f);Wb(g,new ic(0,"Error while loading script "+
a))};vb(d,{type:"text/javascript",charset:"UTF-8",src:a});jc(c).appendChild(d);return g},jc=function(a){var b=a.getElementsByTagName("HEAD");return b&&0!=b.length?b[0]:a.documentElement},gc=function(){if(this&&this.script_){var a=this.script_;a&&"SCRIPT"==a.tagName&&hc(a,!0,this.timeout_)}},hc=function(a,b,c){null!=c&&k.clearTimeout(c);a.onload=ba;a.onerror=ba;a.onreadystatechange=ba;b&&window.setTimeout(function(){Bb(a)},0)},ic=function(a,b){var c="Jsloader error (code #"+a+")";b&&(c+=": "+b);y.call(this,
c);this.code=a};v(ic,y);var lc=function(a){lc[" "](a);return a};lc[" "]=ba;var mc=!C||C&&9<=hb,nc=C&&!G("9");!F||G("528");E&&G("1.9b")||C&&G("8")||cb&&G("9.5")||F&&G("528");E&&!G("8")||C&&G("9");var O=function(a,b){this.type=a;this.currentTarget=this.target=b;this.defaultPrevented=this.propagationStopped_=!1;this.returnValue_=!0};O.prototype.disposeInternal=function(){};O.prototype.dispose=function(){};O.prototype.preventDefault=function(){this.defaultPrevented=!0;this.returnValue_=!1};var oc=function(a,b){O.call(this,a?a.type:"");this.relatedTarget=this.currentTarget=this.target=null;this.charCode=this.keyCode=this.button=this.screenY=this.screenX=this.clientY=this.clientX=this.offsetY=this.offsetX=0;this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.event_=this.state=null;if(a){this.event_=a;var c=this.type=a.type;this.target=a.target||a.srcElement;this.currentTarget=b;var d=a.relatedTarget;if(d){if(E){var e;t:{try{lc(d.nodeName);e=!0;break t}catch(g){}e=!1}e||(d=null)}}else"mouseover"==
c?d=a.fromElement:"mouseout"==c&&(d=a.toElement);this.relatedTarget=d;Object.defineProperties?Object.defineProperties(this,{offsetX:{configurable:!0,enumerable:!0,get:this.getOffsetX_,set:this.setOffsetX_},offsetY:{configurable:!0,enumerable:!0,get:this.getOffsetY_,set:this.setOffsetY_}}):(this.offsetX=this.getOffsetX_(),this.offsetY=this.getOffsetY_());this.clientX=void 0!==a.clientX?a.clientX:a.pageX;this.clientY=void 0!==a.clientY?a.clientY:a.pageY;this.screenX=a.screenX||0;this.screenY=a.screenY||
0;this.button=a.button;this.keyCode=a.keyCode||0;this.charCode=a.charCode||("keypress"==c?a.keyCode:0);this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.state=a.state;a.defaultPrevented&&this.preventDefault()}};v(oc,O);h=oc.prototype;h.preventDefault=function(){oc.superClass_.preventDefault.call(this);var a=this.event_;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,nc)try{if(a.ctrlKey||112<=a.keyCode&&123>=a.keyCode)a.keyCode=-1}catch(b){}};
h.disposeInternal=function(){};h.getOffsetX_=function(){return F||void 0!==this.event_.offsetX?this.event_.offsetX:this.event_.layerX};h.setOffsetX_=function(a){Object.defineProperties(this,{offsetX:{writable:!0,enumerable:!0,configurable:!0,value:a}})};h.getOffsetY_=function(){return F||void 0!==this.event_.offsetY?this.event_.offsetY:this.event_.layerY};h.setOffsetY_=function(a){Object.defineProperties(this,{offsetY:{writable:!0,enumerable:!0,configurable:!0,value:a}})};var pc="closure_listenable_"+(1E6*Math.random()|0),qc=0;var rc=function(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.handler=e;this.key=++qc;this.removed=this.callOnce=!1},sc=function(a){a.removed=!0;a.listener=null;a.proxy=null;a.src=null;a.handler=null};var P=function(a){this.src=a;this.listeners={};this.typeCount_=0};P.prototype.add=function(a,b,c,d,e){var g=a.toString();a=this.listeners[g];a||(a=this.listeners[g]=[],this.typeCount_++);var f=tc(a,b,d,e);-1<f?(b=a[f],c||(b.callOnce=!1)):(b=new rc(b,this.src,g,!!d,e),b.callOnce=c,a.push(b));return b};
P.prototype.remove=function(a,b,c,d){a=a.toString();if(!(a in this.listeners))return!1;var e=this.listeners[a];b=tc(e,b,c,d);return-1<b?(sc(e[b]),z(null!=e.length),A.splice.call(e,b,1),0==e.length&&(delete this.listeners[a],this.typeCount_--),!0):!1};var uc=function(a,b){var c=b.type;if(!(c in a.listeners))return!1;var d=Qa(a.listeners[c],b);d&&(sc(b),0==a.listeners[c].length&&(delete a.listeners[c],a.typeCount_--));return d};
P.prototype.removeAll=function(a){a=a&&a.toString();var b=0,c;for(c in this.listeners)if(!a||c==a){for(var d=this.listeners[c],e=0;e<d.length;e++)++b,sc(d[e]);delete this.listeners[c];this.typeCount_--}return b};P.prototype.getListener=function(a,b,c,d){a=this.listeners[a.toString()];var e=-1;a&&(e=tc(a,b,c,d));return-1<e?a[e]:null};var tc=function(a,b,c,d){for(var e=0;e<a.length;++e){var g=a[e];if(!g.removed&&g.listener==b&&g.capture==!!c&&g.handler==d)return e}return-1};var vc="closure_lm_"+(1E6*Math.random()|0),wc={},xc=0,yc=function(a,b,c,d,e){if(p(b)){for(var g=0;g<b.length;g++)yc(a,b[g],c,d,e);return null}c=zc(c);if(a&&a[pc])a=a.listen(b,c,d,e);else{if(!b)throw Error("Invalid event type");var g=!!d,f=Ac(a);f||(a[vc]=f=new P(a));c=f.add(b,c,!1,d,e);c.proxy||(d=Bc(),c.proxy=d,d.src=a,d.listener=c,a.addEventListener?a.addEventListener(b.toString(),d,g):a.attachEvent(Cc(b.toString()),d),xc++);a=c}return a},Bc=function(){var a=Dc,b=mc?function(c){return a.call(b.src,
b.listener,c)}:function(c){c=a.call(b.src,b.listener,c);if(!c)return c};return b},Ec=function(a,b,c,d,e){if(p(b))for(var g=0;g<b.length;g++)Ec(a,b[g],c,d,e);else c=zc(c),a&&a[pc]?a.unlisten(b,c,d,e):a&&(a=Ac(a))&&(b=a.getListener(b,c,!!d,e))&&Fc(b)},Fc=function(a){if("number"==typeof a||!a||a.removed)return!1;var b=a.src;if(b&&b[pc])return uc(b.eventTargetListeners_,a);var c=a.type,d=a.proxy;b.removeEventListener?b.removeEventListener(c,d,a.capture):b.detachEvent&&b.detachEvent(Cc(c),d);xc--;(c=Ac(b))?
(uc(c,a),0==c.typeCount_&&(c.src=null,b[vc]=null)):sc(a);return!0},Cc=function(a){return a in wc?wc[a]:wc[a]="on"+a},Hc=function(a,b,c,d){var e=!0;if(a=Ac(a))if(b=a.listeners[b.toString()])for(b=b.concat(),a=0;a<b.length;a++){var g=b[a];g&&g.capture==c&&!g.removed&&(g=Gc(g,d),e=e&&!1!==g)}return e},Gc=function(a,b){var c=a.listener,d=a.handler||a.src;a.callOnce&&Fc(a);return c.call(d,b)},Dc=function(a,b){if(a.removed)return!0;if(!mc){var c;if(!(c=b))t:{c=["window","event"];for(var d=k,e;e=c.shift();)if(null!=
d[e])d=d[e];else{c=null;break t}c=d}e=c;c=new oc(e,this);d=!0;if(!(0>e.keyCode||void 0!=e.returnValue)){t:{var g=!1;if(0==e.keyCode)try{e.keyCode=-1;break t}catch(f){g=!0}if(g||void 0==e.returnValue)e.returnValue=!0}e=[];for(g=c.currentTarget;g;g=g.parentNode)e.push(g);for(var g=a.type,m=e.length-1;!c.propagationStopped_&&0<=m;m--){c.currentTarget=e[m];var D=Hc(e[m],g,!0,c),d=d&&D}for(m=0;!c.propagationStopped_&&m<e.length;m++)c.currentTarget=e[m],D=Hc(e[m],g,!1,c),d=d&&D}return d}return Gc(a,new oc(b,
this))},Ac=function(a){a=a[vc];return a instanceof P?a:null},Ic="__closure_events_fn_"+(1E9*Math.random()>>>0),zc=function(a){z(a,"Listener can not be null.");if(r(a))return a;z(a.handleEvent,"An object listener must have handleEvent method.");a[Ic]||(a[Ic]=function(b){return a.handleEvent(b)});return a[Ic]};var Q=function(a){H.call(this);this.handler_=a;this.keys_={}};v(Q,H);var Jc=[];h=Q.prototype;h.listen=function(a,b,c,d){p(b)||(b&&(Jc[0]=b.toString()),b=Jc);for(var e=0;e<b.length;e++){var g=yc(a,b[e],c||this.handleEvent,d||!1,this.handler_||this);if(!g)break;this.keys_[g.key]=g}return this};
h.unlisten=function(a,b,c,d,e){if(p(b))for(var g=0;g<b.length;g++)this.unlisten(a,b[g],c,d,e);else c=c||this.handleEvent,e=e||this.handler_||this,c=zc(c),d=!!d,b=a&&a[pc]?a.getListener(b,c,d,e):a?(a=Ac(a))?a.getListener(b,c,d,e):null:null,b&&(Fc(b),delete this.keys_[b.key]);return this};h.removeAll=function(){Ta(this.keys_,Fc);this.keys_={}};h.disposeInternal=function(){Q.superClass_.disposeInternal.call(this);this.removeAll()};
h.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented");};var R=function(){H.call(this);this.eventTargetListeners_=new P(this);this.actualEventTarget_=this;this.parentEventTarget_=null};v(R,H);R.prototype[pc]=!0;h=R.prototype;h.setParentEventTarget=function(a){this.parentEventTarget_=a};h.addEventListener=function(a,b,c,d){yc(this,a,b,c,d)};h.removeEventListener=function(a,b,c,d){Ec(this,a,b,c,d)};
h.dispatchEvent=function(a){Kc(this);var b,c=this.parentEventTarget_;if(c){b=[];for(var d=1;c;c=c.parentEventTarget_)b.push(c),z(1E3>++d,"infinite loop")}c=this.actualEventTarget_;d=a.type||a;if(q(a))a=new O(a,c);else if(a instanceof O)a.target=a.target||c;else{var e=a;a=new O(d,c);Za(a,e)}var e=!0,g;if(b)for(var f=b.length-1;!a.propagationStopped_&&0<=f;f--)g=a.currentTarget=b[f],e=Lc(g,d,!0,a)&&e;a.propagationStopped_||(g=a.currentTarget=c,e=Lc(g,d,!0,a)&&e,a.propagationStopped_||(e=Lc(g,d,!1,a)&&
e));if(b)for(f=0;!a.propagationStopped_&&f<b.length;f++)g=a.currentTarget=b[f],e=Lc(g,d,!1,a)&&e;return e};h.disposeInternal=function(){R.superClass_.disposeInternal.call(this);this.eventTargetListeners_&&this.eventTargetListeners_.removeAll(void 0);this.parentEventTarget_=null};h.listen=function(a,b,c,d){Kc(this);return this.eventTargetListeners_.add(String(a),b,!1,c,d)};h.unlisten=function(a,b,c,d){return this.eventTargetListeners_.remove(String(a),b,c,d)};
var Lc=function(a,b,c,d){b=a.eventTargetListeners_.listeners[String(b)];if(!b)return!0;b=b.concat();for(var e=!0,g=0;g<b.length;++g){var f=b[g];if(f&&!f.removed&&f.capture==c){var m=f.listener,D=f.handler||f.src;f.callOnce&&uc(a.eventTargetListeners_,f);e=!1!==m.call(D,d)&&e}}return e&&0!=d.returnValue_};R.prototype.getListener=function(a,b,c,d){return this.eventTargetListeners_.getListener(String(a),b,c,d)};var Kc=function(a){z(a.eventTargetListeners_,"Event target is not initialized. Did you call the superclass (goog.events.EventTarget) constructor?")};var S=function(a){R.call(this);this.imageIdToRequestMap_={};this.imageIdToImageMap_={};this.handler_=new Q(this);this.parent_=a};v(S,R);var Mc=[C&&!G("11")?"readystatechange":"load","abort","error"],Nc=function(a,b,c){(c=q(c)?c:c.src)&&(a.imageIdToRequestMap_[b]={src:c,corsRequestType:l(void 0)?void 0:null})};
S.prototype.start=function(){var a=this.imageIdToRequestMap_;Na(Ua(a),function(b){var c=a[b];if(c&&(delete a[b],!this.disposed_)){var d;d=this.parent_?sb(this.parent_).createDom("img"):new Image;c.corsRequestType&&(d.crossOrigin=c.corsRequestType);this.handler_.listen(d,Mc,this.onNetworkEvent_);this.imageIdToImageMap_[b]=d;d.id=b;d.src=c.src}},this)};
S.prototype.onNetworkEvent_=function(a){var b=a.currentTarget;if(b){if("readystatechange"==a.type)if("complete"==b.readyState)a.type="load";else return;"undefined"==typeof b.naturalWidth&&("load"==a.type?(b.naturalWidth=b.width,b.naturalHeight=b.height):(b.naturalWidth=0,b.naturalHeight=0));this.dispatchEvent({type:a.type,target:b});!this.disposed_&&(a=b.id,delete this.imageIdToRequestMap_[a],b=this.imageIdToImageMap_[a])&&(delete this.imageIdToImageMap_[a],this.handler_.unlisten(b,Mc,this.onNetworkEvent_),
Va(this.imageIdToImageMap_)&&Va(this.imageIdToRequestMap_)&&this.dispatchEvent("complete"))}};S.prototype.disposeInternal=function(){delete this.imageIdToRequestMap_;delete this.imageIdToImageMap_;ob(this.handler_);S.superClass_.disposeInternal.call(this)};var Oc={};var T=function(){};T.getInstance=function(){return T.instance_?T.instance_:T.instance_=new T};T.prototype.nextId_=0;var U=function(a){R.call(this);this.dom_=a||sb();this.id_=null;this.inDocument_=!1;this.element_=null;this.googUiComponentHandler_=void 0;this.childIndex_=this.children_=this.parent_=null;this.wasDecorated_=!1};v(U,R);h=U.prototype;h.idGenerator_=T.getInstance();h.getElement=function(){return this.element_};h.setParentEventTarget=function(a){if(this.parent_&&this.parent_!=a)throw Error("Method not supported");U.superClass_.setParentEventTarget.call(this,a)};h.getDomHelper=function(){return this.dom_};
h.createDom=function(){this.element_=this.dom_.createElement("div")};
var Qc=function(a,b){if(a.inDocument_)throw Error("Component already rendered");a.element_||a.createDom();b?b.insertBefore(a.element_,null):a.dom_.document_.body.appendChild(a.element_);a.parent_&&!a.parent_.inDocument_||Pc(a)},Pc=function(a){a.inDocument_=!0;Rc(a,function(a){!a.inDocument_&&a.getElement()&&Pc(a)})},Sc=function(a){Rc(a,function(a){a.inDocument_&&Sc(a)});a.googUiComponentHandler_&&a.googUiComponentHandler_.removeAll();a.inDocument_=!1};
U.prototype.disposeInternal=function(){this.inDocument_&&Sc(this);this.googUiComponentHandler_&&(this.googUiComponentHandler_.dispose(),delete this.googUiComponentHandler_);Rc(this,function(a){a.dispose()});!this.wasDecorated_&&this.element_&&Bb(this.element_);this.parent_=this.element_=this.childIndex_=this.children_=null;U.superClass_.disposeInternal.call(this)};var Rc=function(a,b){a.children_&&Na(a.children_,b,void 0)};
U.prototype.removeChild=function(a,b){if(a){var c=q(a)?a:a.id_||(a.id_=":"+(a.idGenerator_.nextId_++).toString(36)),d;this.childIndex_&&c?(d=this.childIndex_,d=(c in d?d[c]:void 0)||null):d=null;a=d;if(c&&a){d=this.childIndex_;c in d&&delete d[c];Qa(this.children_,a);b&&(Sc(a),a.element_&&Bb(a.element_));c=a;if(null==c)throw Error("Unable to set parent component");c.parent_=null;U.superClass_.setParentEventTarget.call(c,null)}}if(!a)throw Error("Child is not in parent component");return a};var V=function(a,b,c){U.call(this,c);this.captchaImage_=a;this.adImage_=b&&300==b.naturalWidth&&57==b.naturalHeight?b:null};v(V,U);V.prototype.createDom=function(){V.superClass_.createDom.call(this);var a=this.getElement();this.captchaImage_.alt=W.image_alt_text;this.getDomHelper().appendChild(a,this.captchaImage_);this.adImage_&&(this.adImage_.alt=W.image_alt_text,this.getDomHelper().appendChild(a,this.adImage_),this.adImage_&&Tc(this.adImage_)&&(a.innerHTML+='<div id="recaptcha-ad-choices"><div class="recaptcha-ad-choices-collapsed"><img height="15" width="30" alt="AdChoices" border="0" src="//www.gstatic.com/recaptcha/api/img/adicon.png"/></div><div class="recaptcha-ad-choices-expanded"><a href="https://support.google.com/adsense/troubleshooter/1631343" target="_blank"><img height="15" width="75" alt="AdChoices" border="0" src="//www.gstatic.com/recaptcha/api/img/adchoices.png"/></a></div></div>'))};
var Tc=function(a){var b=Uc(a,"visibility");a=Uc(a,"display");return"hidden"!=b&&"none"!=a},Uc=function(a,b){var c;t:{c=rb(a);if(c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defaultView.getComputedStyle(a,null))){c=c[b]||c.getPropertyValue(b)||"";break t}c=""}if(!(c=c||(a.currentStyle?a.currentStyle[b]:null))&&(c=a.style[Fa(b)],"undefined"===typeof c)){c=a.style;var d=Oc[b];if(!d){var e=Fa(b),d=e;void 0===a.style[e]&&(e=(F?"Webkit":E?"Moz":C?"ms":cb?"O":null)+Ga(e),void 0!==a.style[e]&&(d=
e));Oc[b]=d}c=c[d]||""}return c};V.prototype.disposeInternal=function(){delete this.captchaImage_;delete this.adImage_;V.superClass_.disposeInternal.call(this)};var Vc=function(a,b,c){H.call(this);this.listener_=a;this.interval_=b||0;this.handler_=c;this.callback_=t(this.doAction_,this)};v(Vc,H);h=Vc.prototype;h.id_=0;h.disposeInternal=function(){Vc.superClass_.disposeInternal.call(this);this.stop();delete this.listener_;delete this.handler_};
h.start=function(a){this.stop();var b=this.callback_;a=l(a)?a:this.interval_;if(!r(b))if(b&&"function"==typeof b.handleEvent)b=t(b.handleEvent,b);else throw Error("Invalid listener argument");this.id_=2147483647<a?-1:k.setTimeout(b,a||0)};h.stop=function(){this.isActive()&&k.clearTimeout(this.id_);this.id_=0};h.isActive=function(){return 0!=this.id_};h.doAction_=function(){this.id_=0;this.listener_&&this.listener_.call(this.handler_)};var Wc=function(a,b){H.call(this);this.listener_=a;this.handler_=b;this.delay_=new Vc(t(this.onTick_,this),0,this)};v(Wc,H);h=Wc.prototype;h.interval_=0;h.runUntil_=0;h.disposeInternal=function(){this.delay_.dispose();delete this.listener_;delete this.handler_;Wc.superClass_.disposeInternal.call(this)};h.start=function(a,b){this.stop();var c=b||0;this.interval_=Math.max(a||0,0);this.runUntil_=0>c?-1:ha()+c;this.delay_.start(0>c?this.interval_:Math.min(this.interval_,c))};h.stop=function(){this.delay_.stop()};
h.isActive=function(){return this.delay_.isActive()};h.onSuccess=function(){};h.onFailure=function(){};h.onTick_=function(){if(this.listener_.call(this.handler_))this.onSuccess();else if(0>this.runUntil_)this.delay_.start(this.interval_);else{var a=this.runUntil_-ha();if(0>=a)this.onFailure();else this.delay_.start(Math.min(this.interval_,a))}};var Xc={sanitizedContentKindHtml:!0},Yc={sanitizedContentKindText:!0},Zc=function(){throw Error("Do not instantiate directly");};Zc.prototype.contentDir=null;Zc.prototype.toString=function(){return this.content};var dd=function(a){var b=$c;z(b,"Soy template may not be null.");var c=sb().createElement("DIV");a=ad(b(a||bd,void 0,void 0));b=a.match(cd);z(!b,"This template starts with a %s, which cannot be a child of a <div>, as required by soy internals. Consider using goog.soy.renderElement instead.\nTemplate output: %s",b&&b[0],a);c.innerHTML=a;return 1==c.childNodes.length&&(a=c.firstChild,1==a.nodeType)?a:c},ad=function(a){if(!da(a))return String(a);if(a instanceof Zc){if(a.contentKind===Xc)return Ka(a.content);
if(a.contentKind===Yc)return Da(a.content)}Ja("Soy template output is unsafe for use as HTML: "+a);return"zSoyz"},cd=/^<(body|caption|col|colgroup|head|html|tr|td|tbody|thead|tfoot)>/i,bd={};C&&G(8);var ed=function(){Zc.call(this)};v(ed,Zc);ed.prototype.contentKind=Xc;var fd=function(a){function b(a){this.content=a}b.prototype=a.prototype;return function(a,d){var e=new b(String(a));void 0!==d&&(e.contentDir=d);return e}}(ed);(function(a){function b(a){this.content=a}b.prototype=a.prototype;return function(a,d){var e=String(a);if(!e)return"";e=new b(e);void 0!==d&&(e.contentDir=d);return e}})(ed);
var gd={"\x00":"\\x00","\b":"\\x08","\t":"\\t","\n":"\\n","\x0B":"\\x0b","\f":"\\f","\r":"\\r",'"':"\\x22",$:"\\x24","&":"\\x26","'":"\\x27","(":"\\x28",")":"\\x29","*":"\\x2a","+":"\\x2b",",":"\\x2c","-":"\\x2d",".":"\\x2e","/":"\\/",":":"\\x3a","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\x3f","[":"\\x5b","\\":"\\\\","]":"\\x5d","^":"\\x5e","{":"\\x7b","|":"\\x7c","}":"\\x7d","\u0085":"\\x85","\u2028":"\\u2028","\u2029":"\\u2029"},hd=function(a){return gd[a]},id=/[\x00\x08-\x0d\x22\x26\x27\/\x3c-\x3e\\\x85\u2028\u2029]/g;var $c=function(a){return fd('<script type="text/javascript">var challenge = \''+String(a.challenge).replace(id,hd)+"'; var publisherId = '"+String(a.publisherId).replace(id,hd)+"';"+("ca-mongoogle"==a.publisherId?'google_page_url = "3pcerttesting.com/dab/recaptcha.html";':"")+"\n    google_ad_client = publisherId;\n    google_ad_type = 'html';\n    google_ad_output = 'js';\n    google_image_size = '300x57';\n    google_captcha_token = challenge;\n    google_ad_request_done = function(ad) {\n      window.parent.recaptcha.ads.adutils.googleAdRequestDone(ad);\n    };\n    \x3c/script><script type=\"text/javascript\" src=\"//pagead2.googlesyndication.com/pagead/show_ads.js\">\x3c/script>")};
$c.soyTemplateName="recaptcha.soy.ads.iframeAdsLoader.main";var Wa=function(){var a=k.google_ad;return!!(a&&a.token&&a.imageAdUrl&&a.hashedAnswer&&a.salt&&a.delayedImpressionUrl&&a.engagementUrl)},jd=function(){k.google_ad&&(k.google_ad=null)},kd=function(a){a=a||document.body;var b=k.google_ad;b&&b.searchUpliftUrl&&(b=xb("iframe",{src:'data:text/html;charset=utf-8,<body><img src="https://'+b.searchUpliftUrl+'"></img></body>',style:"display:none"}),a.appendChild(b))},ld=0,md=function(a){var b=new S;Nc(b,"recaptcha-url-"+ld++,a);b.start()},nd=function(a,b){var c=
RecaptchaState.publisher_id;jd();var d=xb("iframe",{id:"recaptcha-loader-"+ld++,style:"display: none"});document.body.appendChild(d);var e=d.contentWindow?d.contentWindow.document:d.contentDocument;e.open("text/html","replace");e.write(dd({challenge:a,publisherId:c}).innerHTML);e.close();c=new Wc(function(){return!!k.google_ad});c.onSuccess=function(){Bb(d);b()};c.onFailure=function(){Bb(d);b()};c.start(50,2E3)};u("recaptcha.ads.adutils.googleAdRequestDone",function(a){k.google_ad=a});var od=function(){this.blockSize=-1};var pd=function(){this.blockSize=-1;this.blockSize=64;this.chain_=Array(4);this.block_=Array(this.blockSize);this.totalLength_=this.blockLength_=0;this.reset()};v(pd,od);pd.prototype.reset=function(){this.chain_[0]=1732584193;this.chain_[1]=4023233417;this.chain_[2]=2562383102;this.chain_[3]=271733878;this.totalLength_=this.blockLength_=0};
var qd=function(a,b,c){c||(c=0);var d=Array(16);if(q(b))for(var e=0;16>e;++e)d[e]=b.charCodeAt(c++)|b.charCodeAt(c++)<<8|b.charCodeAt(c++)<<16|b.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=b[c++]|b[c++]<<8|b[c++]<<16|b[c++]<<24;b=a.chain_[0];c=a.chain_[1];var e=a.chain_[2],g=a.chain_[3],f=0,f=b+(g^c&(e^g))+d[0]+3614090360&4294967295;b=c+(f<<7&4294967295|f>>>25);f=g+(e^b&(c^e))+d[1]+3905402710&4294967295;g=b+(f<<12&4294967295|f>>>20);f=e+(c^g&(b^c))+d[2]+606105819&4294967295;e=g+(f<<17&4294967295|
f>>>15);f=c+(b^e&(g^b))+d[3]+3250441966&4294967295;c=e+(f<<22&4294967295|f>>>10);f=b+(g^c&(e^g))+d[4]+4118548399&4294967295;b=c+(f<<7&4294967295|f>>>25);f=g+(e^b&(c^e))+d[5]+1200080426&4294967295;g=b+(f<<12&4294967295|f>>>20);f=e+(c^g&(b^c))+d[6]+2821735955&4294967295;e=g+(f<<17&4294967295|f>>>15);f=c+(b^e&(g^b))+d[7]+4249261313&4294967295;c=e+(f<<22&4294967295|f>>>10);f=b+(g^c&(e^g))+d[8]+1770035416&4294967295;b=c+(f<<7&4294967295|f>>>25);f=g+(e^b&(c^e))+d[9]+2336552879&4294967295;g=b+(f<<12&4294967295|
f>>>20);f=e+(c^g&(b^c))+d[10]+4294925233&4294967295;e=g+(f<<17&4294967295|f>>>15);f=c+(b^e&(g^b))+d[11]+2304563134&4294967295;c=e+(f<<22&4294967295|f>>>10);f=b+(g^c&(e^g))+d[12]+1804603682&4294967295;b=c+(f<<7&4294967295|f>>>25);f=g+(e^b&(c^e))+d[13]+4254626195&4294967295;g=b+(f<<12&4294967295|f>>>20);f=e+(c^g&(b^c))+d[14]+2792965006&4294967295;e=g+(f<<17&4294967295|f>>>15);f=c+(b^e&(g^b))+d[15]+1236535329&4294967295;c=e+(f<<22&4294967295|f>>>10);f=b+(e^g&(c^e))+d[1]+4129170786&4294967295;b=c+(f<<
5&4294967295|f>>>27);f=g+(c^e&(b^c))+d[6]+3225465664&4294967295;g=b+(f<<9&4294967295|f>>>23);f=e+(b^c&(g^b))+d[11]+643717713&4294967295;e=g+(f<<14&4294967295|f>>>18);f=c+(g^b&(e^g))+d[0]+3921069994&4294967295;c=e+(f<<20&4294967295|f>>>12);f=b+(e^g&(c^e))+d[5]+3593408605&4294967295;b=c+(f<<5&4294967295|f>>>27);f=g+(c^e&(b^c))+d[10]+38016083&4294967295;g=b+(f<<9&4294967295|f>>>23);f=e+(b^c&(g^b))+d[15]+3634488961&4294967295;e=g+(f<<14&4294967295|f>>>18);f=c+(g^b&(e^g))+d[4]+3889429448&4294967295;c=
e+(f<<20&4294967295|f>>>12);f=b+(e^g&(c^e))+d[9]+568446438&4294967295;b=c+(f<<5&4294967295|f>>>27);f=g+(c^e&(b^c))+d[14]+3275163606&4294967295;g=b+(f<<9&4294967295|f>>>23);f=e+(b^c&(g^b))+d[3]+4107603335&4294967295;e=g+(f<<14&4294967295|f>>>18);f=c+(g^b&(e^g))+d[8]+1163531501&4294967295;c=e+(f<<20&4294967295|f>>>12);f=b+(e^g&(c^e))+d[13]+2850285829&4294967295;b=c+(f<<5&4294967295|f>>>27);f=g+(c^e&(b^c))+d[2]+4243563512&4294967295;g=b+(f<<9&4294967295|f>>>23);f=e+(b^c&(g^b))+d[7]+1735328473&4294967295;
e=g+(f<<14&4294967295|f>>>18);f=c+(g^b&(e^g))+d[12]+2368359562&4294967295;c=e+(f<<20&4294967295|f>>>12);f=b+(c^e^g)+d[5]+4294588738&4294967295;b=c+(f<<4&4294967295|f>>>28);f=g+(b^c^e)+d[8]+2272392833&4294967295;g=b+(f<<11&4294967295|f>>>21);f=e+(g^b^c)+d[11]+1839030562&4294967295;e=g+(f<<16&4294967295|f>>>16);f=c+(e^g^b)+d[14]+4259657740&4294967295;c=e+(f<<23&4294967295|f>>>9);f=b+(c^e^g)+d[1]+2763975236&4294967295;b=c+(f<<4&4294967295|f>>>28);f=g+(b^c^e)+d[4]+1272893353&4294967295;g=b+(f<<11&4294967295|
f>>>21);f=e+(g^b^c)+d[7]+4139469664&4294967295;e=g+(f<<16&4294967295|f>>>16);f=c+(e^g^b)+d[10]+3200236656&4294967295;c=e+(f<<23&4294967295|f>>>9);f=b+(c^e^g)+d[13]+681279174&4294967295;b=c+(f<<4&4294967295|f>>>28);f=g+(b^c^e)+d[0]+3936430074&4294967295;g=b+(f<<11&4294967295|f>>>21);f=e+(g^b^c)+d[3]+3572445317&4294967295;e=g+(f<<16&4294967295|f>>>16);f=c+(e^g^b)+d[6]+76029189&4294967295;c=e+(f<<23&4294967295|f>>>9);f=b+(c^e^g)+d[9]+3654602809&4294967295;b=c+(f<<4&4294967295|f>>>28);f=g+(b^c^e)+d[12]+
3873151461&4294967295;g=b+(f<<11&4294967295|f>>>21);f=e+(g^b^c)+d[15]+530742520&4294967295;e=g+(f<<16&4294967295|f>>>16);f=c+(e^g^b)+d[2]+3299628645&4294967295;c=e+(f<<23&4294967295|f>>>9);f=b+(e^(c|~g))+d[0]+4096336452&4294967295;b=c+(f<<6&4294967295|f>>>26);f=g+(c^(b|~e))+d[7]+1126891415&4294967295;g=b+(f<<10&4294967295|f>>>22);f=e+(b^(g|~c))+d[14]+2878612391&4294967295;e=g+(f<<15&4294967295|f>>>17);f=c+(g^(e|~b))+d[5]+4237533241&4294967295;c=e+(f<<21&4294967295|f>>>11);f=b+(e^(c|~g))+d[12]+1700485571&
4294967295;b=c+(f<<6&4294967295|f>>>26);f=g+(c^(b|~e))+d[3]+2399980690&4294967295;g=b+(f<<10&4294967295|f>>>22);f=e+(b^(g|~c))+d[10]+4293915773&4294967295;e=g+(f<<15&4294967295|f>>>17);f=c+(g^(e|~b))+d[1]+2240044497&4294967295;c=e+(f<<21&4294967295|f>>>11);f=b+(e^(c|~g))+d[8]+1873313359&4294967295;b=c+(f<<6&4294967295|f>>>26);f=g+(c^(b|~e))+d[15]+4264355552&4294967295;g=b+(f<<10&4294967295|f>>>22);f=e+(b^(g|~c))+d[6]+2734768916&4294967295;e=g+(f<<15&4294967295|f>>>17);f=c+(g^(e|~b))+d[13]+1309151649&
4294967295;c=e+(f<<21&4294967295|f>>>11);f=b+(e^(c|~g))+d[4]+4149444226&4294967295;b=c+(f<<6&4294967295|f>>>26);f=g+(c^(b|~e))+d[11]+3174756917&4294967295;g=b+(f<<10&4294967295|f>>>22);f=e+(b^(g|~c))+d[2]+718787259&4294967295;e=g+(f<<15&4294967295|f>>>17);f=c+(g^(e|~b))+d[9]+3951481745&4294967295;a.chain_[0]=a.chain_[0]+b&4294967295;a.chain_[1]=a.chain_[1]+(e+(f<<21&4294967295|f>>>11))&4294967295;a.chain_[2]=a.chain_[2]+e&4294967295;a.chain_[3]=a.chain_[3]+g&4294967295};
pd.prototype.update=function(a,b){l(b)||(b=a.length);for(var c=b-this.blockSize,d=this.block_,e=this.blockLength_,g=0;g<b;){if(0==e)for(;g<=c;)qd(this,a,g),g+=this.blockSize;if(q(a))for(;g<b;){if(d[e++]=a.charCodeAt(g++),e==this.blockSize){qd(this,d);e=0;break}}else for(;g<b;)if(d[e++]=a[g++],e==this.blockSize){qd(this,d);e=0;break}}this.blockLength_=e;this.totalLength_+=b};var X=function(){Q.call(this);this.callback_=this.element_=null;this.md5_=new pd};v(X,Q);var rd=function(a,b,c,d,e){a.unwatch();a.element_=b;a.callback_=e;a.listen(b,"keyup",t(a.onChanged_,a,c,d))};X.prototype.unwatch=function(){this.element_&&this.callback_&&(this.removeAll(),this.callback_=this.element_=null)};
X.prototype.onChanged_=function(a,b){var c;c=(c=this.element_.value)?c.replace(/[\s\xa0]+/g,"").toLowerCase():"";this.md5_.reset();this.md5_.update(c+"."+b);c=this.md5_;var d=Array((56>c.blockLength_?c.blockSize:2*c.blockSize)-c.blockLength_);d[0]=128;for(var e=1;e<d.length-8;++e)d[e]=0;for(var g=8*c.totalLength_,e=d.length-8;e<d.length;++e)d[e]=g&255,g/=256;c.update(d);d=Array(16);for(e=g=0;4>e;++e)for(var f=0;32>f;f+=8)d[g++]=c.chain_[e]>>>f&255;jb(d).toLowerCase()==a.toLowerCase()&&this.callback_()};
X.prototype.disposeInternal=function(){this.element_=null;X.superClass_.disposeInternal.call(this)};var td=function(a,b,c){this.adObject_=a;this.captchaImageUrl_=b;this.opt_successCallback_=c||null;sd(this)};v(td,H);var sd=function(a){var b=new S;nb(a,ga(ob,b));Nc(b,"recaptcha_challenge_image",a.captchaImageUrl_);Nc(b,"recaptcha_ad_image",a.adObject_.imageAdUrl);var c={};yc(b,"load",t(function(a,b){a[b.target.id]=b.target},a,c));yc(b,"complete",t(a.handleImagesLoaded_,a,c));b.start()};
td.prototype.handleImagesLoaded_=function(a){a=new V(a.recaptcha_challenge_image,a.recaptcha_ad_image);nb(this,ga(ob,a));var b=tb(document,"recaptcha_image");Ab(b);Qc(a,b);a.adImage_&&Tc(a.adImage_)&&(md(this.adObject_.delayedImpressionUrl),a=new X,nb(this,ga(ob,a)),rd(a,tb(document,"recaptcha_response_field"),this.adObject_.hashedAnswer,this.adObject_.salt,t(function(a,b){a.unwatch();md(b)},this,a,this.adObject_.engagementUrl)),this.opt_successCallback_&&this.opt_successCallback_("04"+this.adObject_.token))};var W=x;u("RecaptchaStr",W);var Y=k.RecaptchaOptions;u("RecaptchaOptions",Y);var ud={tabindex:0,theme:"red",callback:null,lang:null,custom_theme_widget:null,custom_translations:null};u("RecaptchaDefaultOptions",ud);
var Z={widget:null,timer_id:-1,style_set:!1,theme:null,type:"image",ajax_verify_cb:null,th1:null,th2:null,th3:null,element:"",ad_captcha_plugin:null,reload_timeout:-1,force_reload:!1,$:function(a){return"string"==typeof a?document.getElementById(a):a},attachEvent:function(a,b,c){a&&a.addEventListener?a.addEventListener(b,c,!1):a&&a.attachEvent&&a.attachEvent("on"+b,c)},create:function(a,b,c){Z.destroy();b&&(Z.widget=Z.$(b),Z.element=b);Z._init_options(c);Z._call_challenge(a)},destroy:function(){var a=
Z.$("recaptcha_challenge_field");a&&a.parentNode.removeChild(a);-1!=Z.timer_id&&clearInterval(Z.timer_id);Z.timer_id=-1;if(a=Z.$("recaptcha_image"))a.innerHTML="";Z.update_widget();Z.widget&&("custom"!=Z.theme?Z.widget.innerHTML="":Z.widget.style.display="none",Z.widget=null)},focus_response_field:function(){var a=Z.$("recaptcha_response_field");a&&a.focus()},get_challenge:function(){return"undefined"==typeof RecaptchaState?null:RecaptchaState.challenge},get_response:function(){var a=Z.$("recaptcha_response_field");
return a?a.value:null},ajax_verify:function(a){Z.ajax_verify_cb=a;a=Z.get_challenge()||"";var b=Z.get_response()||"";a=Z._get_api_server()+"/ajaxverify?c="+encodeURIComponent(a)+"&response="+encodeURIComponent(b);Z._add_script(a)},_ajax_verify_callback:function(a){Z.ajax_verify_cb(a)},_get_overridable_url:function(a){var b=window.location.protocol;if("undefined"!=typeof _RecaptchaOverrideApiServer)a=_RecaptchaOverrideApiServer;else if("undefined"!=typeof RecaptchaState&&"string"==typeof RecaptchaState.server&&
0<RecaptchaState.server.length)return RecaptchaState.server.replace(/\/+$/,"");return b+"//"+a},_get_api_server:function(){return Z._get_overridable_url("www.google.com/recaptcha/api")},_get_static_url_root:function(){return Z._get_overridable_url("www.gstatic.com/recaptcha/api")},_call_challenge:function(a){a=Z._get_api_server()+"/challenge?k="+a+"&ajax=1&cachestop="+Math.random();Z.getLang_()&&(a+="&lang="+Z.getLang_());"undefined"!=typeof Y.extra_challenge_params&&(a+="&"+Y.extra_challenge_params);
Z._add_script(a)},_add_script:function(a){var b=document.createElement("script");b.type="text/javascript";b.src=a;Z._get_script_area().appendChild(b)},_get_script_area:function(){var a=document.getElementsByTagName("head");return a=!a||1>a.length?document.body:a[0]},_hash_merge:function(a){for(var b={},c=0;c<a.length;c++)for(var d in a[c])b[d]=a[c][d];return b},_init_options:function(a){Y=Z._hash_merge([ud,a||{}])},challenge_callback_internal:function(){Z.update_widget();Z._reset_timer();W=Z._hash_merge([x,
sa[Z.getLang_()]||{},Y.custom_translations||{}]);window.addEventListener&&window.addEventListener("unload",function(){Z.destroy()},!1);Z._is_ie()&&window.attachEvent&&window.attachEvent("onbeforeunload",function(){});if(0<navigator.userAgent.indexOf("KHTML")){var a=document.createElement("iframe");a.src="about:blank";a.style.height="0px";a.style.width="0px";a.style.visibility="hidden";a.style.border="none";a.style.display="none";a.appendChild(document.createTextNode("This frame prevents back/forward cache problems in Safari."));
document.body.appendChild(a)}Z._finish_widget()},_add_css:function(a){if(-1!=navigator.appVersion.indexOf("MSIE 5"))document.write('<style type="text/css">'+a+"</style>");else{var b=document.createElement("style");b.type="text/css";b.styleSheet?b.styleSheet.cssText=a:b.appendChild(document.createTextNode(a));Z._get_script_area().appendChild(b)}},_set_style:function(a){Z.style_set||(Z.style_set=!0,Z._add_css(a+"\n\n.recaptcha_is_showing_audio .recaptcha_only_if_image,.recaptcha_isnot_showing_audio .recaptcha_only_if_audio,.recaptcha_had_incorrect_sol .recaptcha_only_if_no_incorrect_sol,.recaptcha_nothad_incorrect_sol .recaptcha_only_if_incorrect_sol{display:none !important}"))},
_init_builtin_theme:function(){var a=Z.$,b=Z._get_static_url_root(),c=w.VertCss,d=w.VertHtml,e=b+"/img/"+Z.theme,g="gif",b=Z.theme;"clean"==b&&(c=w.CleanCss,d=w.CleanHtml,g="png");c=c.replace(/IMGROOT/g,e);Z._set_style(c);Z.update_widget();Z.widget.innerHTML='<div id="recaptcha_area">'+d+"</div>";c=Z.getLang_();a("recaptcha_privacy")&&null!=c&&"en"==c.substring(0,2).toLowerCase()&&null!=W.privacy_and_terms&&0<W.privacy_and_terms.length&&(c=document.createElement("a"),c.href="http://www.google.com/intl/en/policies/",
c.target="_blank",c.innerHTML=W.privacy_and_terms,a("recaptcha_privacy").appendChild(c));c=function(b,c,d,M){var I=a(b);I.src=e+"/"+c+"."+g;c=W[d];I.alt=c;b=a(b+"_btn");b.title=c;Z.attachEvent(b,"click",M)};c("recaptcha_reload","refresh","refresh_btn",function(){Z.reload_internal("r")});c("recaptcha_switch_audio","audio","audio_challenge",function(){Z.switch_type("audio")});c("recaptcha_switch_img","text","visual_challenge",function(){Z.switch_type("image")});c("recaptcha_whatsthis","help","help_btn",
Z.showhelp);"clean"==b&&(a("recaptcha_logo").src=e+"/logo."+g);a("recaptcha_table").className="recaptchatable recaptcha_theme_"+Z.theme;b=function(b,c){var d=a(b);d&&(RecaptchaState.rtl&&"span"==d.tagName.toLowerCase()&&(d.dir="rtl"),d.appendChild(document.createTextNode(W[c])))};b("recaptcha_instructions_image","instructions_visual");b("recaptcha_instructions_audio","instructions_audio");b("recaptcha_instructions_error","incorrect_try_again");a("recaptcha_instructions_image")||a("recaptcha_instructions_audio")||
(b="audio"==Z.type?W.instructions_audio:W.instructions_visual,b=b.replace(/:$/,""),a("recaptcha_response_field").setAttribute("placeholder",b))},_finish_widget:function(){var a=Z.$,b=Y,c=b.theme;c in{blackglass:1,clean:1,custom:1,red:1,white:1}||(c="red");Z.theme||(Z.theme=c);"custom"!=Z.theme?Z._init_builtin_theme():Z._set_style("");c=document.createElement("span");c.id="recaptcha_challenge_field_holder";c.style.display="none";a("recaptcha_response_field").parentNode.insertBefore(c,a("recaptcha_response_field"));
a("recaptcha_response_field").setAttribute("autocomplete","off");a("recaptcha_image").style.width="300px";a("recaptcha_image").style.height="57px";a("recaptcha_challenge_field_holder").innerHTML='<input type="hidden" name="recaptcha_challenge_field" id="recaptcha_challenge_field" value=""/>';Z.th_init();Z.should_focus=!1;Z.th3||Z.force_reload?(Z._set_challenge(RecaptchaState.challenge,"image",!0),setTimeout(function(){Z.reload_internal("i")},100)):Z._set_challenge(RecaptchaState.challenge,"image",
!1);Z.updateTabIndexes_();Z.update_widget();Z.widget&&(Z.widget.style.display="");b.callback&&b.callback()},updateTabIndexes_:function(){var a=Z.$,b=Y;b.tabindex&&(b=b.tabindex,a("recaptcha_response_field").tabIndex=b++,"audio"==Z.type&&a("recaptcha_audio_play_again")&&(a("recaptcha_audio_play_again").tabIndex=b++,a("recaptcha_audio_download"),a("recaptcha_audio_download").tabIndex=b++),"custom"!=Z.theme&&(a("recaptcha_reload_btn").tabIndex=b++,a("recaptcha_switch_audio_btn").tabIndex=b++,a("recaptcha_switch_img_btn").tabIndex=
b++,a("recaptcha_whatsthis_btn").tabIndex=b,a("recaptcha_privacy").tabIndex=b++))},switch_type:function(a){if(!((new Date).getTime()<Z.reload_timeout)&&(Z.type=a,Z.reload_internal("audio"==Z.type?"a":"v"),"custom"!=Z.theme)){a=Z.$;var b="audio"==Z.type?W.instructions_audio:W.instructions_visual,b=b.replace(/:$/,"");a("recaptcha_response_field").setAttribute("placeholder",b)}},reload:function(){Z.reload_internal("r")},reload_internal:function(a){var b=Y,c=RecaptchaState,d=(new Date).getTime();d<Z.reload_timeout||
(Z.reload_timeout=d+1E3,"undefined"==typeof a&&(a="r"),d=Z._get_api_server()+"/reload?c="+c.challenge+"&k="+c.site+"&reason="+a+"&type="+Z.type,Z.getLang_()&&(d+="&lang="+Z.getLang_()),"undefined"!=typeof b.extra_challenge_params&&(d+="&"+b.extra_challenge_params),Z.th_callback_invoke(),Z.th1&&(d+="&th="+Z.th1,Z.th1=""),"audio"==Z.type&&(d=b.audio_beta_12_08?d+"&audio_beta_12_08=1":d+"&new_audio_default=1"),Z.should_focus="t"!=a&&"i"!=a,Z._add_script(d),ob(Z.ad_captcha_plugin),c.publisher_id=null)},
th_callback_invoke:function(){if(Z.th3)try{var a=Z.th3.exec();a&&1600>a.length&&(Z.th1=a)}catch(b){Z.th1=""}},finish_reload:function(a,b,c,d){RecaptchaState.payload_url=c;RecaptchaState.is_incorrect=!1;RecaptchaState.publisher_id=d;Z._set_challenge(a,b,!1);Z.updateTabIndexes_()},_set_challenge:function(a,b,c){"image"==b&&RecaptchaState.publisher_id?nd(a,function(){Z._set_challenge_internal(a,b,c)}):Z._set_challenge_internal(a,b,c)},_set_challenge_internal:function(a,b,c){var d=Z.$,e=RecaptchaState;
e.challenge=a;Z.type=b;d("recaptcha_challenge_field").value=e.challenge;c||("audio"==b?(d("recaptcha_image").innerHTML=Z.getAudioCaptchaHtml(),Z._loop_playback()):"image"==b&&(a=e.payload_url,a||(a=Z._get_api_server()+"/image?c="+e.challenge,Z.th_callback_invoke(),Z.th1&&(a+="&th="+Z.th1,Z.th1="")),kd(d("recaptcha_widget_div")),Wa()?Z.ad_captcha_plugin=new td(Xa(),a,function(a){RecaptchaState.challenge=a;d("recaptcha_challenge_field").value=a}):d("recaptcha_image").innerHTML='<img id="recaptcha_challenge_image" alt="'+
W.image_alt_text+'" height="57" width="300" src="'+a+'" />',jd()));Z._css_toggle("recaptcha_had_incorrect_sol","recaptcha_nothad_incorrect_sol",e.is_incorrect);Z._css_toggle("recaptcha_is_showing_audio","recaptcha_isnot_showing_audio","audio"==b);Z._clear_input();Z.should_focus&&Z.focus_response_field();Z._reset_timer()},_reset_timer:function(){clearInterval(Z.timer_id);var a=Math.max(1E3*(RecaptchaState.timeout-60),6E4);Z.timer_id=setInterval(function(){Z.reload_internal("t")},a);return a},showhelp:function(){window.open(Z._get_help_link(),
"recaptcha_popup","width=460,height=580,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes")},_clear_input:function(){Z.$("recaptcha_response_field").value=""},_displayerror:function(a){var b=Z.$;b("recaptcha_image").innerHTML="";b("recaptcha_image").appendChild(document.createTextNode(a))},reloaderror:function(a){Z._displayerror(a)},_is_ie:function(){return 0<navigator.userAgent.indexOf("MSIE")&&!window.opera},_css_toggle:function(a,b,c){Z.update_widget();var d=Z.widget;d||
(d=document.body);var e=d.className,e=e.replace(new RegExp("(^|\\s+)"+a+"(\\s+|$)")," "),e=e.replace(new RegExp("(^|\\s+)"+b+"(\\s+|$)")," ");d.className=e+(" "+(c?a:b))},_get_help_link:function(){var a="https://support.google.com/recaptcha/";Z.getLang_()&&(a+="?hl="+Z.getLang_());return a},playAgain:function(){Z.$("recaptcha_image").innerHTML=Z.getAudioCaptchaHtml();Z._loop_playback()},_loop_playback:function(){var a=Z.$("recaptcha_audio_play_again");a&&Z.attachEvent(a,"click",function(){Z.playAgain();
return!1})},getAudioCaptchaHtml:function(){var a=RecaptchaState.payload_url;a||(a=Z._get_api_server()+"/audio.mp3?c="+RecaptchaState.challenge,Z.th_callback_invoke(),Z.th1&&(a+="&th="+Z.th1,Z.th1=""));var b=Z._get_api_server()+"/swf/audiocaptcha.swf?v2",b=Z._is_ie()?'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="audiocaptcha" width="0" height="0" codebase="https://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="movie" value="'+b+'" /><param name="quality" value="high" /><param name="bgcolor" value="#869ca7" /><param name="allowScriptAccess" value="always" /></object><br/>':
'<embed src="'+b+'" quality="high" bgcolor="#869ca7" width="0" height="0" name="audiocaptcha" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" /></embed>',c="";Z.checkFlashVer()&&(c="<br/>"+Z.getSpan_('<a id="recaptcha_audio_play_again" class="recaptcha_audio_cant_hear_link">'+W.play_again+"</a>"));c+="<br/>"+Z.getSpan_('<a id="recaptcha_audio_download" class="recaptcha_audio_cant_hear_link" target="_blank" href="'+
a+'">'+W.cant_hear_this+"</a>");return b+c},getSpan_:function(a){return"<span"+(RecaptchaState&&RecaptchaState.rtl?' dir="rtl"':"")+">"+a+"</span>"},gethttpwavurl:function(){if("audio"!=Z.type)return"";var a=RecaptchaState.payload_url;a||(a=Z._get_api_server()+"/image?c="+RecaptchaState.challenge,Z.th_callback_invoke(),Z.th1&&(a+="&th="+Z.th1,Z.th1=""));return a},checkFlashVer:function(){var a=-1!=navigator.appVersion.indexOf("MSIE"),b=-1!=navigator.appVersion.toLowerCase().indexOf("win"),c=-1!=navigator.userAgent.indexOf("Opera"),
d=-1;if(null!=navigator.plugins&&0<navigator.plugins.length){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"])d=navigator.plugins["Shockwave Flash"+(navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"")].description.split(" ")[2].split(".")[0]}else if(a&&b&&!c)try{d=(new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")).GetVariable("$version").split(" ")[1].split(",")[0]}catch(e){}return 9<=d},getLang_:function(){return Y.lang?Y.lang:"undefined"!=typeof RecaptchaState&&
RecaptchaState.lang?RecaptchaState.lang:null},challenge_callback:function(){Z.force_reload=!!RecaptchaState.force_reload;if(RecaptchaState.t3){var a=RecaptchaState.t1?ib(mb(RecaptchaState.t1)):"",b=RecaptchaState.t2?ib(mb(RecaptchaState.t2)):"",c=RecaptchaState.t3?ib(mb(RecaptchaState.t3)):"";Z.th2=c;if(a)b=kc(a),cc(b,Z.challenge_callback_internal,null,void 0),cc(b,null,Z.challenge_callback_internal,void 0);else{if(k.execScript)k.execScript(b,"JavaScript");else if(k.eval)null==ia&&(k.eval("var _et_ = 1;"),
"undefined"!=typeof k._et_?(delete k._et_,ia=!0):ia=!1),ia?k.eval(b):(a=k.document,c=a.createElement("script"),c.type="text/javascript",c.defer=!1,c.appendChild(a.createTextNode(b)),a.body.appendChild(c),a.body.removeChild(c));else throw Error("goog.globalEval not available");Z.challenge_callback_internal()}}else Z.challenge_callback_internal()},th_init:function(){try{k.thintinel&&k.thintinel.th&&(Z.th3=new k.thintinel.th(Z.th2),Z.th2="")}catch(a){}},update_widget:function(){Z.element&&(Z.widget=
Z.$(Z.element))}};u("Recaptcha",Z);})()
;
/*
 * jQuery.bind-first library v0.2.3
 * Copyright (c) 2013 Vladimir Zhuravlev
 *
 * Released under MIT License
 * @license
 *
 * Date: Thu Feb  6 10:13:59 ICT 2014
 **/
(function(t){function e(e){return u?e.data("events"):t._data(e[0]).events}function n(t,n,r){var i=e(t),a=i[n];if(!u){var s=r?a.splice(a.delegateCount-1,1)[0]:a.pop();return a.splice(r?0:a.delegateCount||0,0,s),void 0}r?i.live.unshift(i.live.pop()):a.unshift(a.pop())}function r(e,r,i){var a=r.split(/\s+/);e.each(function(){for(var e=0;a.length>e;++e){var r=t.trim(a[e]).match(/[^\.]+/i)[0];n(t(this),r,i)}})}function i(e){t.fn[e+"First"]=function(){var n=t.makeArray(arguments),i=n.shift();return i&&(t.fn[e].apply(this,arguments),r(this,i)),this}}var a=t.fn.jquery.split("."),s=parseInt(a[0]),f=parseInt(a[1]),u=1>s||1==s&&7>f;i("bind"),i("one"),t.fn.delegateFirst=function(){var e=t.makeArray(arguments),n=e[1];return n&&(e.splice(0,2),t.fn.delegate.apply(this,arguments),r(this,n,!0)),this},t.fn.liveFirst=function(){var e=t.makeArray(arguments);return e.unshift(this.selector),t.fn.delegateFirst.apply(t(document),e),this},u||(t.fn.onFirst=function(e,n){var i=t(this),a="string"==typeof n;if(t.fn.on.apply(i,arguments),"object"==typeof e)for(type in e)e.hasOwnProperty(type)&&r(i,type,a);else"string"==typeof e&&r(i,e,a);return i})})(jQuery);;
/*
 * jQuery File Upload Plugin 5.26
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, File, Blob, FormData, location */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'jquery.ui.widget'
        ], factory);
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // The FileReader API is not actually used, but works as feature detection,
    // as e.g. Safari supports XHR file uploads via the FormData API,
    // but not non-multipart XHR file uploads:
    $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
    $.support.xhrFormDataFileUpload = !!window.FormData;

    // The fileupload widget listens for change events on file input fields defined
    // via fileInput setting and paste or drop events of the given dropZone.
    // In addition to the default jQuery Widget methods, the fileupload widget
    // exposes the "add" and "send" methods, to add or directly send files using
    // the fileupload API.
    // By default, files added via file input selection, paste, drag & drop or
    // "add" method are uploaded immediately, but it is possible to override
    // the "add" callback option to queue file uploads.
    $.widget('blueimp.fileupload', {

        options: {
            // The drop target element(s), by the default the complete document.
            // Set to null to disable drag & drop support:
            dropZone: $(document),
            // The paste target element(s), by the default the complete document.
            // Set to null to disable paste support:
            pasteZone: $(document),
            // The file input field(s), that are listened to for change events.
            // If undefined, it is set to the file input fields inside
            // of the widget element on plugin initialization.
            // Set to null to disable the change listener.
            fileInput: undefined,
            // By default, the file input field is replaced with a clone after
            // each input field change event. This is required for iframe transport
            // queues and allows change events to be fired for the same file
            // selection, but can be disabled by setting the following option to false:
            replaceFileInput: true,
            // The parameter name for the file form data (the request argument name).
            // If undefined or empty, the name property of the file input field is
            // used, or "files[]" if the file input name property is also empty,
            // can be a string or an array of strings:
            paramName: undefined,
            // By default, each file of a selection is uploaded using an individual
            // request for XHR type uploads. Set to false to upload file
            // selections in one request each:
            singleFileUploads: true,
            // To limit the number of files uploaded with one XHR request,
            // set the following option to an integer greater than 0:
            limitMultiFileUploads: undefined,
            // Set the following option to true to issue all file upload requests
            // in a sequential order:
            sequentialUploads: false,
            // To limit the number of concurrent uploads,
            // set the following option to an integer greater than 0:
            limitConcurrentUploads: undefined,
            // Set the following option to true to force iframe transport uploads:
            forceIframeTransport: false,
            // Set the following option to the location of a redirect url on the
            // origin server, for cross-domain iframe transport uploads:
            redirect: undefined,
            // The parameter name for the redirect url, sent as part of the form
            // data and set to 'redirect' if this option is empty:
            redirectParamName: undefined,
            // Set the following option to the location of a postMessage window,
            // to enable postMessage transport uploads:
            postMessage: undefined,
            // By default, XHR file uploads are sent as multipart/form-data.
            // The iframe transport is always using multipart/form-data.
            // Set to false to enable non-multipart XHR uploads:
            multipart: true,
            // To upload large files in smaller chunks, set the following option
            // to a preferred maximum chunk size. If set to 0, null or undefined,
            // or the browser does not support the required Blob API, files will
            // be uploaded as a whole.
            maxChunkSize: undefined,
            // When a non-multipart upload or a chunked multipart upload has been
            // aborted, this option can be used to resume the upload by setting
            // it to the size of the already uploaded bytes. This option is most
            // useful when modifying the options object inside of the "add" or
            // "send" callbacks, as the options are cloned for each file upload.
            uploadedBytes: undefined,
            // By default, failed (abort or error) file uploads are removed from the
            // global progress calculation. Set the following option to false to
            // prevent recalculating the global progress data:
            recalculateProgress: true,
            // Interval in milliseconds to calculate and trigger progress events:
            progressInterval: 100,
            // Interval in milliseconds to calculate progress bitrate:
            bitrateInterval: 500,
            // By default, uploads are started automatically when adding files:
            autoUpload: true,

            // Additional form data to be sent along with the file uploads can be set
            // using this option, which accepts an array of objects with name and
            // value properties, a function returning such an array, a FormData
            // object (for XHR file uploads), or a simple object.
            // The form of the first fileInput is given as parameter to the function:
            formData: function (form) {
                return form.serializeArray();
            },

            // The add callback is invoked as soon as files are added to the fileupload
            // widget (via file input selection, drag & drop, paste or add API call).
            // If the singleFileUploads option is enabled, this callback will be
            // called once for each file in the selection for XHR file uplaods, else
            // once for each file selection.
            // The upload starts when the submit method is invoked on the data parameter.
            // The data object contains a files property holding the added files
            // and allows to override plugin options as well as define ajax settings.
            // Listeners for this callback can also be bound the following way:
            // .bind('fileuploadadd', func);
            // data.submit() returns a Promise object and allows to attach additional
            // handlers using jQuery's Deferred callbacks:
            // data.submit().done(func).fail(func).always(func);
            add: function (e, data) {
                if (data.autoUpload || (data.autoUpload !== false &&
                        ($(this).data('blueimp-fileupload') ||
                        $(this).data('fileupload')).options.autoUpload)) {
                    data.submit();
                }
            },

            // Other callbacks:

            // Callback for the submit event of each file upload:
            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);

            // Callback for the start of each file upload request:
            // send: function (e, data) {}, // .bind('fileuploadsend', func);

            // Callback for successful uploads:
            // done: function (e, data) {}, // .bind('fileuploaddone', func);

            // Callback for failed (abort or error) uploads:
            // fail: function (e, data) {}, // .bind('fileuploadfail', func);

            // Callback for completed (success, abort or error) requests:
            // always: function (e, data) {}, // .bind('fileuploadalways', func);

            // Callback for upload progress events:
            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);

            // Callback for global upload progress events:
            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);

            // Callback for uploads start, equivalent to the global ajaxStart event:
            // start: function (e) {}, // .bind('fileuploadstart', func);

            // Callback for uploads stop, equivalent to the global ajaxStop event:
            // stop: function (e) {}, // .bind('fileuploadstop', func);

            // Callback for change events of the fileInput(s):
            // change: function (e, data) {}, // .bind('fileuploadchange', func);

            // Callback for paste events to the pasteZone(s):
            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);

            // Callback for drop events of the dropZone(s):
            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);

            // Callback for dragover events of the dropZone(s):
            // dragover: function (e) {}, // .bind('fileuploaddragover', func);

            // Callback for the start of each chunk upload request:
            // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);

            // Callback for successful chunk uploads:
            // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);

            // Callback for failed (abort or error) chunk uploads:
            // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);

            // Callback for completed (success, abort or error) chunk upload requests:
            // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);

            // The plugin options are used as settings object for the ajax calls.
            // The following are jQuery ajax settings required for the file uploads:
            processData: false,
            contentType: false,
            cache: false
        },

        // A list of options that require a refresh after assigning a new value:
        _refreshOptionsList: [
            'fileInput',
            'dropZone',
            'pasteZone',
            'multipart',
            'forceIframeTransport'
        ],

        _BitrateTimer: function () {
            this.timestamp = +(new Date());
            this.loaded = 0;
            this.bitrate = 0;
            this.getBitrate = function (now, loaded, interval) {
                var timeDiff = now - this.timestamp;
                if (!this.bitrate || !interval || timeDiff > interval) {
                    this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
                    this.loaded = loaded;
                    this.timestamp = now;
                }
                return this.bitrate;
            };
        },

        _isXHRUpload: function (options) {
            return !options.forceIframeTransport &&
                ((!options.multipart && $.support.xhrFileUpload) ||
                $.support.xhrFormDataFileUpload);
        },

        _getFormData: function (options) {
            var formData;
            if (typeof options.formData === 'function') {
                return options.formData(options.form);
            }
            if ($.isArray(options.formData)) {
                return options.formData;
            }
            if (options.formData) {
                formData = [];
                $.each(options.formData, function (name, value) {
                    formData.push({name: name, value: value});
                });
                return formData;
            }
            return [];
        },

        _getTotal: function (files) {
            var total = 0;
            $.each(files, function (index, file) {
                total += file.size || 1;
            });
            return total;
        },

        _initProgressObject: function (obj) {
            obj._progress = {
                loaded: 0,
                total: 0,
                bitrate: 0
            };
        },

        _onProgress: function (e, data) {
            if (e.lengthComputable) {
                var now = +(new Date()),
                    loaded;
                if (data._time && data.progressInterval &&
                        (now - data._time < data.progressInterval) &&
                        e.loaded !== e.total) {
                    return;
                }
                data._time = now;
                loaded = Math.floor(
                    e.loaded / e.total * (data.chunkSize || data._progress.total)
                ) + (data.uploadedBytes || 0);
                // Add the difference from the previously loaded state
                // to the global loaded counter:
                this._progress.loaded += (loaded - data._progress.loaded);
                this._progress.bitrate = this._bitrateTimer.getBitrate(
                    now,
                    this._progress.loaded,
                    data.bitrateInterval
                );
                data._progress.loaded = data.loaded = loaded;
                data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
                    now,
                    loaded,
                    data.bitrateInterval
                );
                // Trigger a custom progress event with a total data property set
                // to the file size(s) of the current upload and a loaded data
                // property calculated accordingly:
                this._trigger('progress', e, data);
                // Trigger a global progress event for all current file uploads,
                // including ajax calls queued for sequential file uploads:
                this._trigger('progressall', e, this._progress);
            }
        },

        _initProgressListener: function (options) {
            var that = this,
                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
            // Accesss to the native XHR object is required to add event listeners
            // for the upload progress event:
            if (xhr.upload) {
                $(xhr.upload).bind('progress', function (e) {
                    var oe = e.originalEvent;
                    // Make sure the progress event properties get copied over:
                    e.lengthComputable = oe.lengthComputable;
                    e.loaded = oe.loaded;
                    e.total = oe.total;
                    that._onProgress(e, options);
                });
                options.xhr = function () {
                    return xhr;
                };
            }
        },

        _initXHRData: function (options) {
            var formData,
                file = options.files[0],
                // Ignore non-multipart setting if not supported:
                multipart = options.multipart || !$.support.xhrFileUpload,
                paramName = options.paramName[0];
            options.headers = options.headers || {};
            if (options.contentRange) {
                options.headers['Content-Range'] = options.contentRange;
            }
            if (!multipart) {
                options.headers['Content-Disposition'] = 'attachment; filename="' +
                    encodeURI(file.name) + '"';
                options.contentType = file.type;
                options.data = options.blob || file;
            } else if ($.support.xhrFormDataFileUpload) {
                if (options.postMessage) {
                    // window.postMessage does not allow sending FormData
                    // objects, so we just add the File/Blob objects to
                    // the formData array and let the postMessage window
                    // create the FormData object out of this array:
                    formData = this._getFormData(options);
                    if (options.blob) {
                        formData.push({
                            name: paramName,
                            value: options.blob
                        });
                    } else {
                        $.each(options.files, function (index, file) {
                            formData.push({
                                name: options.paramName[index] || paramName,
                                value: file
                            });
                        });
                    }
                } else {
                    if (options.formData instanceof FormData) {
                        formData = options.formData;
                    } else {
                        formData = new FormData();
                        $.each(this._getFormData(options), function (index, field) {
                            formData.append(field.name, field.value);
                        });
                    }
                    if (options.blob) {
                        options.headers['Content-Disposition'] = 'attachment; filename="' +
                            encodeURI(file.name) + '"';
                        formData.append(paramName, options.blob, file.name);
                    } else {
                        $.each(options.files, function (index, file) {
                            // Files are also Blob instances, but some browsers
                            // (Firefox 3.6) support the File API but not Blobs.
                            // This check allows the tests to run with
                            // dummy objects:
                            if ((window.Blob && file instanceof Blob) ||
                                    (window.File && file instanceof File)) {
                                formData.append(
                                    options.paramName[index] || paramName,
                                    file,
                                    file.name
                                );
                            }
                        });
                    }
                }
                options.data = formData;
            }
            // Blob reference is not needed anymore, free memory:
            options.blob = null;
        },

        _initIframeSettings: function (options) {
            // Setting the dataType to iframe enables the iframe transport:
            options.dataType = 'iframe ' + (options.dataType || '');
            // The iframe transport accepts a serialized array as form data:
            options.formData = this._getFormData(options);
            // Add redirect url to form data on cross-domain uploads:
            if (options.redirect && $('<a></a>').prop('href', options.url)
                    .prop('host') !== location.host) {
                options.formData.push({
                    name: options.redirectParamName || 'redirect',
                    value: options.redirect
                });
            }
        },

        _initDataSettings: function (options) {
            if (this._isXHRUpload(options)) {
                if (!this._chunkedUpload(options, true)) {
                    if (!options.data) {
                        this._initXHRData(options);
                    }
                    this._initProgressListener(options);
                }
                if (options.postMessage) {
                    // Setting the dataType to postmessage enables the
                    // postMessage transport:
                    options.dataType = 'postmessage ' + (options.dataType || '');
                }
            } else {
                this._initIframeSettings(options, 'iframe');
            }
        },

        _getParamName: function (options) {
            var fileInput = $(options.fileInput),
                paramName = options.paramName;
            if (!paramName) {
                paramName = [];
                fileInput.each(function () {
                    var input = $(this),
                        name = input.prop('name') || 'files[]',
                        i = (input.prop('files') || [1]).length;
                    while (i) {
                        paramName.push(name);
                        i -= 1;
                    }
                });
                if (!paramName.length) {
                    paramName = [fileInput.prop('name') || 'files[]'];
                }
            } else if (!$.isArray(paramName)) {
                paramName = [paramName];
            }
            return paramName;
        },

        _initFormSettings: function (options) {
            // Retrieve missing options from the input field and the
            // associated form, if available:
            if (!options.form || !options.form.length) {
                options.form = $(options.fileInput.prop('form'));
                // If the given file input doesn't have an associated form,
                // use the default widget file input's form:
                if (!options.form.length) {
                    options.form = $(this.options.fileInput.prop('form'));
                }
            }
            options.paramName = this._getParamName(options);
            if (!options.url) {
                options.url = options.form.prop('action') || location.href;
            }
            // The HTTP request method must be "POST" or "PUT":
            options.type = (options.type || options.form.prop('method') || '')
                .toUpperCase();
            if (options.type !== 'POST' && options.type !== 'PUT' &&
                    options.type !== 'PATCH') {
                options.type = 'POST';
            }
            if (!options.formAcceptCharset) {
                options.formAcceptCharset = options.form.attr('accept-charset');
            }
        },

        _getAJAXSettings: function (data) {
            var options = $.extend({}, this.options, data);
            this._initFormSettings(options);
            this._initDataSettings(options);
            return options;
        },

        // jQuery 1.6 doesn't provide .state(),
        // while jQuery 1.8+ removed .isRejected() and .isResolved():
        _getDeferredState: function (deferred) {
            if (deferred.state) {
                return deferred.state();
            }
            if (deferred.isResolved()) {
                return 'resolved';
            }
            if (deferred.isRejected()) {
                return 'rejected';
            }
            return 'pending';
        },

        // Maps jqXHR callbacks to the equivalent
        // methods of the given Promise object:
        _enhancePromise: function (promise) {
            promise.success = promise.done;
            promise.error = promise.fail;
            promise.complete = promise.always;
            return promise;
        },

        // Creates and returns a Promise object enhanced with
        // the jqXHR methods abort, success, error and complete:
        _getXHRPromise: function (resolveOrReject, context, args) {
            var dfd = $.Deferred(),
                promise = dfd.promise();
            context = context || this.options.context || promise;
            if (resolveOrReject === true) {
                dfd.resolveWith(context, args);
            } else if (resolveOrReject === false) {
                dfd.rejectWith(context, args);
            }
            promise.abort = dfd.promise;
            return this._enhancePromise(promise);
        },

        // Adds convenience methods to the callback arguments:
        _addConvenienceMethods: function (e, data) {
            var that = this;
            data.submit = function () {
                if (this.state() !== 'pending') {
                    data.jqXHR = this.jqXHR =
                        (that._trigger('submit', e, this) !== false) &&
                        that._onSend(e, this);
                }
                return this.jqXHR || that._getXHRPromise();
            };
            data.abort = function () {
                if (this.jqXHR) {
                    return this.jqXHR.abort();
                }
                return this._getXHRPromise();
            };
            data.state = function () {
                if (this.jqXHR) {
                    return that._getDeferredState(this.jqXHR);
                }
            };
            data.progress = function () {
                return this._progress;
            };
        },

        // Parses the Range header from the server response
        // and returns the uploaded bytes:
        _getUploadedBytes: function (jqXHR) {
            var range = jqXHR.getResponseHeader('Range'),
                parts = range && range.split('-'),
                upperBytesPos = parts && parts.length > 1 &&
                    parseInt(parts[1], 10);
            return upperBytesPos && upperBytesPos + 1;
        },

        // Uploads a file in multiple, sequential requests
        // by splitting the file up in multiple blob chunks.
        // If the second parameter is true, only tests if the file
        // should be uploaded in chunks, but does not invoke any
        // upload requests:
        _chunkedUpload: function (options, testOnly) {
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes = options.uploadedBytes || 0,
                mcs = options.maxChunkSize || fs,
                slice = file.slice || file.webkitSlice || file.mozSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
                    options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = 'Uploaded bytes exceed file size';
                return this._getXHRPromise(
                    false,
                    options.context,
                    [null, 'error', file.error]
                );
            }
            // The chunk upload method:
            upload = function () {
                // Clone the options object for each chunk upload:
                var o = $.extend({}, options),
                    currentLoaded = o._progress.loaded;
                o.blob = slice.call(
                    file,
                    ub,
                    ub + mcs,
                    file.type
                );
                // Store the current chunk size, as the blob itself
                // will be dereferenced after data processing:
                o.chunkSize = o.blob.size;
                // Expose the chunk bytes position range:
                o.contentRange = 'bytes ' + ub + '-' +
                    (ub + o.chunkSize - 1) + '/' + fs;
                // Process the upload data (the blob and potential form data):
                that._initXHRData(o);
                // Add progress listeners for this chunk upload:
                that._initProgressListener(o);
                jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
                        that._getXHRPromise(false, o.context))
                    .done(function (result, textStatus, jqXHR) {
                        ub = that._getUploadedBytes(jqXHR) ||
                            (ub + o.chunkSize);
                        // Create a progress event if no final progress event
                        // with loaded equaling total has been triggered
                        // for this chunk:
                        if (o._progress.loaded === currentLoaded) {
                            that._onProgress($.Event('progress', {
                                lengthComputable: true,
                                loaded: ub - o.uploadedBytes,
                                total: ub - o.uploadedBytes
                            }), o);
                        }
                        options.uploadedBytes = o.uploadedBytes = ub;
                        o.result = result;
                        o.textStatus = textStatus;
                        o.jqXHR = jqXHR;
                        that._trigger('chunkdone', null, o);
                        that._trigger('chunkalways', null, o);
                        if (ub < fs) {
                            // File upload not yet complete,
                            // continue with the next chunk:
                            upload();
                        } else {
                            dfd.resolveWith(
                                o.context,
                                [result, textStatus, jqXHR]
                            );
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        o.jqXHR = jqXHR;
                        o.textStatus = textStatus;
                        o.errorThrown = errorThrown;
                        that._trigger('chunkfail', null, o);
                        that._trigger('chunkalways', null, o);
                        dfd.rejectWith(
                            o.context,
                            [jqXHR, textStatus, errorThrown]
                        );
                    });
            };
            this._enhancePromise(promise);
            promise.abort = function () {
                return jqXHR.abort();
            };
            upload();
            return promise;
        },

        _beforeSend: function (e, data) {
            if (this._active === 0) {
                // the start callback is triggered when an upload starts
                // and no other uploads are currently running,
                // equivalent to the global ajaxStart event:
                this._trigger('start');
                // Set timer for global bitrate progress calculation:
                this._bitrateTimer = new this._BitrateTimer();
                // Reset the global progress values:
                this._progress.loaded = this._progress.total = 0;
                this._progress.bitrate = 0;
            }
            if (!data._progress) {
                data._progress = {};
            }
            data._progress.loaded = data.loaded = data.uploadedBytes || 0;
            data._progress.total = data.total = this._getTotal(data.files) || 1;
            data._progress.bitrate = data.bitrate = 0;
            this._active += 1;
            // Initialize the global progress values:
            this._progress.loaded += data.loaded;
            this._progress.total += data.total;
        },

        _onDone: function (result, textStatus, jqXHR, options) {
            var total = options._progress.total;
            if (options._progress.loaded < total) {
                // Create a progress event if no final progress event
                // with loaded equaling total has been triggered:
                this._onProgress($.Event('progress', {
                    lengthComputable: true,
                    loaded: total,
                    total: total
                }), options);
            }
            options.result = result;
            options.textStatus = textStatus;
            options.jqXHR = jqXHR;
            this._trigger('done', null, options);
        },

        _onFail: function (jqXHR, textStatus, errorThrown, options) {
            options.jqXHR = jqXHR;
            options.textStatus = textStatus;
            options.errorThrown = errorThrown;
            this._trigger('fail', null, options);
            if (options.recalculateProgress) {
                // Remove the failed (error or abort) file upload from
                // the global progress calculation:
                this._progress.loaded -= options._progress.loaded;
                this._progress.total -= options._progress.total;
            }
        },

        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
            // jqXHRorResult, textStatus and jqXHRorError are added to the
            // options object via done and fail callbacks
            this._active -= 1;
            this._trigger('always', null, options);
            if (this._active === 0) {
                // The stop callback is triggered when all uploads have
                // been completed, equivalent to the global ajaxStop event:
                this._trigger('stop');
            }
        },

        _onSend: function (e, data) {
            if (!data.submit) {
                this._addConvenienceMethods(e, data);
            }
            var that = this,
                jqXHR,
                aborted,
                slot,
                pipe,
                options = that._getAJAXSettings(data),
                send = function () {
                    that._sending += 1;
                    // Set timer for bitrate progress calculation:
                    options._bitrateTimer = new that._BitrateTimer();
                    jqXHR = jqXHR || (
                        ((aborted || that._trigger('send', e, options) === false) &&
                        that._getXHRPromise(false, options.context, aborted)) ||
                        that._chunkedUpload(options) || $.ajax(options)
                    ).done(function (result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, options);
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, options);
                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
                        that._sending -= 1;
                        that._onAlways(
                            jqXHRorResult,
                            textStatus,
                            jqXHRorError,
                            options
                        );
                        if (options.limitConcurrentUploads &&
                                options.limitConcurrentUploads > that._sending) {
                            // Start the next queued upload,
                            // that has not been aborted:
                            var nextSlot = that._slots.shift();
                            while (nextSlot) {
                                if (that._getDeferredState(nextSlot) === 'pending') {
                                    nextSlot.resolve();
                                    break;
                                }
                                nextSlot = that._slots.shift();
                            }
                        }
                    });
                    return jqXHR;
                };
            this._beforeSend(e, options);
            if (this.options.sequentialUploads ||
                    (this.options.limitConcurrentUploads &&
                    this.options.limitConcurrentUploads <= this._sending)) {
                if (this.options.limitConcurrentUploads > 1) {
                    slot = $.Deferred();
                    this._slots.push(slot);
                    pipe = slot.pipe(send);
                } else {
                    pipe = (this._sequence = this._sequence.pipe(send, send));
                }
                // Return the piped Promise object, enhanced with an abort method,
                // which is delegated to the jqXHR object of the current upload,
                // and jqXHR callbacks mapped to the equivalent Promise methods:
                pipe.abort = function () {
                    aborted = [undefined, 'abort', 'abort'];
                    if (!jqXHR) {
                        if (slot) {
                            slot.rejectWith(options.context, aborted);
                        }
                        return send();
                    }
                    return jqXHR.abort();
                };
                return this._enhancePromise(pipe);
            }
            return send();
        },

        _onAdd: function (e, data) {
            var that = this,
                result = true,
                options = $.extend({}, this.options, data),
                limit = options.limitMultiFileUploads,
                paramName = this._getParamName(options),
                paramNameSet,
                paramNameSlice,
                fileSet,
                i;
            if (!(options.singleFileUploads || limit) ||
                    !this._isXHRUpload(options)) {
                fileSet = [data.files];
                paramNameSet = [paramName];
            } else if (!options.singleFileUploads && limit) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < data.files.length; i += limit) {
                    fileSet.push(data.files.slice(i, i + limit));
                    paramNameSlice = paramName.slice(i, i + limit);
                    if (!paramNameSlice.length) {
                        paramNameSlice = paramName;
                    }
                    paramNameSet.push(paramNameSlice);
                }
            } else {
                paramNameSet = paramName;
            }
            data.originalFiles = data.files;
            $.each(fileSet || data.files, function (index, element) {
                var newData = $.extend({}, data);
                newData.files = fileSet ? element : [element];
                newData.paramName = paramNameSet[index];
                that._initProgressObject(newData);
                that._addConvenienceMethods(e, newData);
                result = that._trigger('add', e, newData);
                return result;
            });
            return result;
        },

        _replaceFileInput: function (input) {
            var inputClone = input.clone(true);
            $('<form></form>').append(inputClone)[0].reset();
            // Detaching allows to insert the fileInput on another form
            // without loosing the file input value:
            input.after(inputClone).detach();
            // Avoid memory leaks with the detached file input:
            $.cleanData(input.unbind('remove'));
            // Replace the original file input element in the fileInput
            // elements set with the clone, which has been copied including
            // event handlers:
            this.options.fileInput = this.options.fileInput.map(function (i, el) {
                if (el === input[0]) {
                    return inputClone[0];
                }
                return el;
            });
            // If the widget has been initialized on the file input itself,
            // override this.element with the file input clone:
            if (input[0] === this.element[0]) {
                this.element = inputClone;
            }
        },

        _handleFileTreeEntry: function (entry, path) {
            var that = this,
                dfd = $.Deferred(),
                errorHandler = function (e) {
                    if (e && !e.entry) {
                        e.entry = entry;
                    }
                    // Since $.when returns immediately if one
                    // Deferred is rejected, we use resolve instead.
                    // This allows valid files and invalid items
                    // to be returned together in one set:
                    dfd.resolve([e]);
                },
                dirReader;
            path = path || '';
            if (entry.isFile) {
                if (entry._file) {
                    // Workaround for Chrome bug #149735
                    entry._file.relativePath = path;
                    dfd.resolve(entry._file);
                } else {
                    entry.file(function (file) {
                        file.relativePath = path;
                        dfd.resolve(file);
                    }, errorHandler);
                }
            } else if (entry.isDirectory) {
                dirReader = entry.createReader();
                dirReader.readEntries(function (entries) {
                    that._handleFileTreeEntries(
                        entries,
                        path + entry.name + '/'
                    ).done(function (files) {
                        dfd.resolve(files);
                    }).fail(errorHandler);
                }, errorHandler);
            } else {
                // Return an empy list for file system items
                // other than files or directories:
                dfd.resolve([]);
            }
            return dfd.promise();
        },

        _handleFileTreeEntries: function (entries, path) {
            var that = this;
            return $.when.apply(
                $,
                $.map(entries, function (entry) {
                    return that._handleFileTreeEntry(entry, path);
                })
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _getDroppedFiles: function (dataTransfer) {
            dataTransfer = dataTransfer || {};
            var items = dataTransfer.items;
            if (items && items.length && (items[0].webkitGetAsEntry ||
                    items[0].getAsEntry)) {
                return this._handleFileTreeEntries(
                    $.map(items, function (item) {
                        var entry;
                        if (item.webkitGetAsEntry) {
                            entry = item.webkitGetAsEntry();
                            if (entry) {
                                // Workaround for Chrome bug #149735:
                                entry._file = item.getAsFile();
                            }
                            return entry;
                        }
                        return item.getAsEntry();
                    })
                );
            }
            return $.Deferred().resolve(
                $.makeArray(dataTransfer.files)
            ).promise();
        },

        _getSingleFileInputFiles: function (fileInput) {
            fileInput = $(fileInput);
            var entries = fileInput.prop('webkitEntries') ||
                    fileInput.prop('entries'),
                files,
                value;
            if (entries && entries.length) {
                return this._handleFileTreeEntries(entries);
            }
            files = $.makeArray(fileInput.prop('files'));
            if (!files.length) {
                value = fileInput.prop('value');
                if (!value) {
                    return $.Deferred().resolve([]).promise();
                }
                // If the files property is not available, the browser does not
                // support the File API and we add a pseudo File object with
                // the input value as name with path information removed:
                files = [{name: value.replace(/^.*\\/, '')}];
            } else if (files[0].name === undefined && files[0].fileName) {
                // File normalization for Safari 4 and Firefox 3:
                $.each(files, function (index, file) {
                    file.name = file.fileName;
                    file.size = file.fileSize;
                });
            }
            return $.Deferred().resolve(files).promise();
        },

        _getFileInputFiles: function (fileInput) {
            if (!(fileInput instanceof $) || fileInput.length === 1) {
                return this._getSingleFileInputFiles(fileInput);
            }
            return $.when.apply(
                $,
                $.map(fileInput, this._getSingleFileInputFiles)
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _onChange: function (e) {
            var that = this,
                data = {
                    fileInput: $(e.target),
                    form: $(e.target.form)
                };
            this._getFileInputFiles(data.fileInput).always(function (files) {
                data.files = files;
                if (that.options.replaceFileInput) {
                    that._replaceFileInput(data.fileInput);
                }
                if (that._trigger('change', e, data) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onPaste: function (e) {
            var cbd = e.originalEvent.clipboardData,
                items = (cbd && cbd.items) || [],
                data = {files: []};
            $.each(items, function (index, item) {
                var file = item.getAsFile && item.getAsFile();
                if (file) {
                    data.files.push(file);
                }
            });
            if (this._trigger('paste', e, data) === false ||
                    this._onAdd(e, data) === false) {
                return false;
            }
        },

        _onDrop: function (e) {
            var that = this,
                dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
                data = {};
            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
                e.preventDefault();
            }
            this._getDroppedFiles(dataTransfer).always(function (files) {
                data.files = files;
                if (that._trigger('drop', e, data) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onDragOver: function (e) {
            var dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
            if (this._trigger('dragover', e) === false) {
                return false;
            }
            if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1) {
                dataTransfer.dropEffect = 'copy';
                e.preventDefault();
            }
        },

        _initEventHandlers: function () {
            if (this._isXHRUpload(this.options)) {
                this._on(this.options.dropZone, {
                    dragover: this._onDragOver,
                    drop: this._onDrop
                });
                this._on(this.options.pasteZone, {
                    paste: this._onPaste
                });
            }
            this._on(this.options.fileInput, {
                change: this._onChange
            });
        },

        _destroyEventHandlers: function () {
            this._off(this.options.dropZone, 'dragover drop');
            this._off(this.options.pasteZone, 'paste');
            this._off(this.options.fileInput, 'change');
        },

        _setOption: function (key, value) {
            var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
            if (refresh) {
                this._destroyEventHandlers();
            }
            this._super(key, value);
            if (refresh) {
                this._initSpecialOptions();
                this._initEventHandlers();
            }
        },

        _initSpecialOptions: function () {
            var options = this.options;
            if (options.fileInput === undefined) {
                options.fileInput = this.element.is('input[type="file"]') ?
                        this.element : this.element.find('input[type="file"]');
            } else if (!(options.fileInput instanceof $)) {
                options.fileInput = $(options.fileInput);
            }
            if (!(options.dropZone instanceof $)) {
                options.dropZone = $(options.dropZone);
            }
            if (!(options.pasteZone instanceof $)) {
                options.pasteZone = $(options.pasteZone);
            }
        },

        _create: function () {
            var options = this.options;
            // Initialize options set via HTML5 data-attributes:
            $.extend(options, $(this.element[0].cloneNode(false)).data());
            this._initSpecialOptions();
            this._slots = [];
            this._sequence = this._getXHRPromise(true);
            this._sending = this._active = 0;
            this._initProgressObject(this);
            this._initEventHandlers();
        },

        // This method is exposed to the widget API and allows to query
        // the widget upload progress.
        // It returns an object with loaded, total and bitrate properties
        // for the running uploads:
        progress: function () {
            return this._progress;
        },

        // This method is exposed to the widget API and allows adding files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files property and can contain additional options:
        // .fileupload('add', {files: filesList});
        add: function (data) {
            var that = this;
            if (!data || this.options.disabled) {
                return;
            }
            if (data.fileInput && !data.files) {
                this._getFileInputFiles(data.fileInput).always(function (files) {
                    data.files = files;
                    that._onAdd(null, data);
                });
            } else {
                data.files = $.makeArray(data.files);
                this._onAdd(null, data);
            }
        },

        // This method is exposed to the widget API and allows sending files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files or fileInput property and can contain additional options:
        // .fileupload('send', {files: filesList});
        // The method returns a Promise object for the file upload call.
        send: function (data) {
            if (data && !this.options.disabled) {
                if (data.fileInput && !data.files) {
                    var that = this,
                        dfd = $.Deferred(),
                        promise = dfd.promise(),
                        jqXHR,
                        aborted;
                    promise.abort = function () {
                        aborted = true;
                        if (jqXHR) {
                            return jqXHR.abort();
                        }
                        dfd.reject(null, 'abort', 'abort');
                        return promise;
                    };
                    this._getFileInputFiles(data.fileInput).always(
                        function (files) {
                            if (aborted) {
                                return;
                            }
                            data.files = files;
                            jqXHR = that._onSend(null, data).then(
                                function (result, textStatus, jqXHR) {
                                    dfd.resolve(result, textStatus, jqXHR);
                                },
                                function (jqXHR, textStatus, errorThrown) {
                                    dfd.reject(jqXHR, textStatus, errorThrown);
                                }
                            );
                        }
                    );
                    return this._enhancePromise(promise);
                }
                data.files = $.makeArray(data.files);
                if (data.files.length) {
                    return this._onSend(null, data);
                }
            }
            return this._getXHRPromise(false, data && data.context);
        }

    });

}));
;
/*
 * jQuery Iframe Transport Plugin 1.6.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint unparam: true, nomen: true */
/*global define, window, document */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define(['jquery'], factory);
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Helper variable to create unique names for the transport iframes:
    var counter = 0;

    // The iframe transport accepts three additional options:
    // options.fileInput: a jQuery collection of file input fields
    // options.paramName: the parameter name for the file form data,
    //  overrides the name property of the file input field(s),
    //  can be a string or an array of strings.
    // options.formData: an array of objects with name and value properties,
    //  equivalent to the return data of .serializeArray(), e.g.:
    //  [{name: 'a', value: 1}, {name: 'b', value: 2}]
    $.ajaxTransport('iframe', function (options) {
        if (options.async) {
            var form,
                iframe,
                addParamChar;
            return {
                send: function (_, completeCallback) {
                    form = $('<form style="display:none;"></form>');
                    form.attr('accept-charset', options.formAcceptCharset);
                    addParamChar = /\?/.test(options.url) ? '&' : '?';
                    // XDomainRequest only supports GET and POST:
                    if (options.type === 'DELETE') {
                        options.url = options.url + addParamChar + '_method=DELETE';
                        options.type = 'POST';
                    } else if (options.type === 'PUT') {
                        options.url = options.url + addParamChar + '_method=PUT';
                        options.type = 'POST';
                    } else if (options.type === 'PATCH') {
                        options.url = options.url + addParamChar + '_method=PATCH';
                        options.type = 'POST';
                    }
                    // javascript:false as initial iframe src
                    // prevents warning popups on HTTPS in IE6.
                    // IE versions below IE8 cannot set the name property of
                    // elements that have already been added to the DOM,
                    // so we set the name along with the iframe HTML markup:
                    iframe = $(
                        '<iframe src="javascript:false;" name="iframe-transport-' +
                            (counter += 1) + '"></iframe>'
                    ).bind('load', function () {
                        var fileInputClones,
                            paramNames = $.isArray(options.paramName) ?
                                    options.paramName : [options.paramName];
                        iframe
                            .unbind('load')
                            .bind('load', function () {
                                var response;
                                // Wrap in a try/catch block to catch exceptions thrown
                                // when trying to access cross-domain iframe contents:
                                try {
                                    response = iframe.contents();
                                    // Google Chrome and Firefox do not throw an
                                    // exception when calling iframe.contents() on
                                    // cross-domain requests, so we unify the response:
                                    if (!response.length || !response[0].firstChild) {
                                        throw new Error();
                                    }
                                } catch (e) {
                                    response = undefined;
                                }
                                // The complete callback returns the
                                // iframe content document as response object:
                                completeCallback(
                                    200,
                                    'success',
                                    {'iframe': response}
                                );
                                // Fix for IE endless progress bar activity bug
                                // (happens on form submits to iframe targets):
                                $('<iframe src="javascript:false;"></iframe>')
                                    .appendTo(form);
                                form.remove();
                            });
                        form
                            .prop('target', iframe.prop('name'))
                            .prop('action', options.url)
                            .prop('method', options.type);
                        if (options.formData) {
                            $.each(options.formData, function (index, field) {
                                $('<input type="hidden"/>')
                                    .prop('name', field.name)
                                    .val(field.value)
                                    .appendTo(form);
                            });
                        }
                        if (options.fileInput && options.fileInput.length &&
                                options.type === 'POST') {
                            fileInputClones = options.fileInput.clone();
                            // Insert a clone for each file input field:
                            options.fileInput.after(function (index) {
                                return fileInputClones[index];
                            });
                            if (options.paramName) {
                                options.fileInput.each(function (index) {
                                    $(this).prop(
                                        'name',
                                        paramNames[index] || options.paramName
                                    );
                                });
                            }
                            // Appending the file input fields to the hidden form
                            // removes them from their original location:
                            form
                                .append(options.fileInput)
                                .prop('enctype', 'multipart/form-data')
                                // enctype must be set as encoding for IE:
                                .prop('encoding', 'multipart/form-data');
                        }
                        form.submit();
                        // Insert the file input fields at their original location
                        // by replacing the clones with the originals:
                        if (fileInputClones && fileInputClones.length) {
                            options.fileInput.each(function (index, input) {
                                var clone = $(fileInputClones[index]);
                                $(input).prop('name', clone.prop('name'));
                                clone.replaceWith(input);
                            });
                        }
                    });
                    form.append(iframe).appendTo(document.body);
                },
                abort: function () {
                    if (iframe) {
                        // javascript:false as iframe src aborts the request
                        // and prevents warning popups on HTTPS in IE6.
                        // concat is used to avoid the "Script URL" JSLint error:
                        iframe
                            .unbind('load')
                            .prop('src', 'javascript'.concat(':false;'));
                    }
                    if (form) {
                        form.remove();
                    }
                }
            };
        }
    });

    // The iframe transport returns the iframe content document as response.
    // The following adds converters from iframe to text, json, html, and script:
    $.ajaxSetup({
        converters: {
            'iframe text': function (iframe) {
                return iframe && $(iframe[0].body).text();
            },
            'iframe json': function (iframe) {
                return iframe && $.parseJSON($(iframe[0].body).text());
            },
            'iframe html': function (iframe) {
                return iframe && $(iframe[0].body).html();
            },
            'iframe script': function (iframe) {
                return iframe && $.globalEval($(iframe[0].body).text());
            }
        }
    });

}));
;
/*mousewheel*/
(function(a){function d(b){var c=b||window.event,d=[].slice.call(arguments,1),e=0,f=!0,g=0,h=0;return b=a.event.fix(c),b.type="mousewheel",c.wheelDelta&&(e=c.wheelDelta/120),c.detail&&(e=-c.detail/3),h=e,c.axis!==undefined&&c.axis===c.HORIZONTAL_AXIS&&(h=0,g=-1*e),c.wheelDeltaY!==undefined&&(h=c.wheelDeltaY/120),c.wheelDeltaX!==undefined&&(g=-1*c.wheelDeltaX/120),d.unshift(b,e,g,h),(a.event.dispatch||a.event.handle).apply(this,d)}var b=["DOMMouseScroll","mousewheel"];if(a.event.fixHooks)for(var c=b.length;c;)a.event.fixHooks[b[--c]]=a.event.mouseHooks;a.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=b.length;a;)this.addEventListener(b[--a],d,!1);else this.onmousewheel=d},teardown:function(){if(this.removeEventListener)for(var a=b.length;a;)this.removeEventListener(b[--a],d,!1);else this.onmousewheel=null}},a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
/*custom scrollbar*/
(function(c){var b={init:function(e){var f={set_width:false,set_height:false,horizontalScroll:false,scrollInertia:950,mouseWheel:true,mouseWheelPixels:"auto",autoDraggerLength:true,autoHideScrollbar:false,snapAmount:null,snapOffset:0,scrollButtons:{enable:false,scrollType:"continuous",scrollSpeed:"auto",scrollAmount:40},advanced:{updateOnBrowserResize:true,updateOnContentResize:false,autoExpandHorizontalScroll:false,autoScrollOnFocus:true,normalizeMouseWheelDelta:false},contentTouchScroll:true,callbacks:{onScrollStart:function(){},onScroll:function(){},onTotalScroll:function(){},onTotalScrollBack:function(){},onTotalScrollOffset:0,onTotalScrollBackOffset:0,whileScrolling:function(){}},theme:"light"},e=c.extend(true,f,e);return this.each(function(){var m=c(this);if(e.set_width){m.css("width",e.set_width)}if(e.set_height){m.css("height",e.set_height)}if(!c(document).data("mCustomScrollbar-index")){c(document).data("mCustomScrollbar-index","1")}else{var t=parseInt(c(document).data("mCustomScrollbar-index"));c(document).data("mCustomScrollbar-index",t+1)}m.wrapInner("<div class='mCustomScrollBox mCS-"+e.theme+"' id='mCSB_"+c(document).data("mCustomScrollbar-index")+"' style='position:relative; height:100%; overflow:hidden; max-width:100%;' />").addClass("mCustomScrollbar _mCS_"+c(document).data("mCustomScrollbar-index"));var g=m.children(".mCustomScrollBox");if(e.horizontalScroll){g.addClass("mCSB_horizontal").wrapInner("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />");var k=g.children(".mCSB_h_wrapper");k.wrapInner("<div class='mCSB_container' style='position:absolute; left:0;' />").children(".mCSB_container").css({width:k.children().outerWidth(),position:"relative"}).unwrap()}else{g.wrapInner("<div class='mCSB_container' style='position:relative; top:0;' />")}var o=g.children(".mCSB_container");if(c.support.touch){o.addClass("mCS_touch")}o.after("<div class='mCSB_scrollTools' style='position:absolute;'><div class='mCSB_draggerContainer'><div class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' style='position:relative;'></div></div><div class='mCSB_draggerRail'></div></div></div>");var l=g.children(".mCSB_scrollTools"),h=l.children(".mCSB_draggerContainer"),q=h.children(".mCSB_dragger");if(e.horizontalScroll){q.data("minDraggerWidth",q.width())}else{q.data("minDraggerHeight",q.height())}if(e.scrollButtons.enable){if(e.horizontalScroll){l.prepend("<a class='mCSB_buttonLeft' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonRight' oncontextmenu='return false;'></a>")}else{l.prepend("<a class='mCSB_buttonUp' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonDown' oncontextmenu='return false;'></a>")}}g.bind("scroll",function(){if(!m.is(".mCS_disabled")){g.scrollTop(0).scrollLeft(0)}});m.data({mCS_Init:true,mCustomScrollbarIndex:c(document).data("mCustomScrollbar-index"),horizontalScroll:e.horizontalScroll,scrollInertia:e.scrollInertia,scrollEasing:"mcsEaseOut",mouseWheel:e.mouseWheel,mouseWheelPixels:e.mouseWheelPixels,autoDraggerLength:e.autoDraggerLength,autoHideScrollbar:e.autoHideScrollbar,snapAmount:e.snapAmount,snapOffset:e.snapOffset,scrollButtons_enable:e.scrollButtons.enable,scrollButtons_scrollType:e.scrollButtons.scrollType,scrollButtons_scrollSpeed:e.scrollButtons.scrollSpeed,scrollButtons_scrollAmount:e.scrollButtons.scrollAmount,autoExpandHorizontalScroll:e.advanced.autoExpandHorizontalScroll,autoScrollOnFocus:e.advanced.autoScrollOnFocus,normalizeMouseWheelDelta:e.advanced.normalizeMouseWheelDelta,contentTouchScroll:e.contentTouchScroll,onScrollStart_Callback:e.callbacks.onScrollStart,onScroll_Callback:e.callbacks.onScroll,onTotalScroll_Callback:e.callbacks.onTotalScroll,onTotalScrollBack_Callback:e.callbacks.onTotalScrollBack,onTotalScroll_Offset:e.callbacks.onTotalScrollOffset,onTotalScrollBack_Offset:e.callbacks.onTotalScrollBackOffset,whileScrolling_Callback:e.callbacks.whileScrolling,bindEvent_scrollbar_drag:false,bindEvent_content_touch:false,bindEvent_scrollbar_click:false,bindEvent_mousewheel:false,bindEvent_buttonsContinuous_y:false,bindEvent_buttonsContinuous_x:false,bindEvent_buttonsPixels_y:false,bindEvent_buttonsPixels_x:false,bindEvent_focusin:false,bindEvent_autoHideScrollbar:false,mCSB_buttonScrollRight:false,mCSB_buttonScrollLeft:false,mCSB_buttonScrollDown:false,mCSB_buttonScrollUp:false});if(e.horizontalScroll){if(m.css("max-width")!=="none"){if(!e.advanced.updateOnContentResize){e.advanced.updateOnContentResize=true}}}else{if(m.css("max-height")!=="none"){var s=false,r=parseInt(m.css("max-height"));if(m.css("max-height").indexOf("%")>=0){s=r,r=m.parent().height()*s/100}m.css("overflow","hidden");g.css("max-height",r)}}m.mCustomScrollbar("update");if(e.advanced.updateOnBrowserResize){var i,j=c(window).width(),u=c(window).height();c(window).bind("resize."+m.data("mCustomScrollbarIndex"),function(){if(i){clearTimeout(i)}i=setTimeout(function(){if(!m.is(".mCS_disabled")&&!m.is(".mCS_destroyed")){var w=c(window).width(),v=c(window).height();if(j!==w||u!==v){if(m.css("max-height")!=="none"&&s){g.css("max-height",m.parent().height()*s/100)}m.mCustomScrollbar("update");j=w;u=v}}},150)})}if(e.advanced.updateOnContentResize){var p;if(e.horizontalScroll){var n=o.outerWidth()}else{var n=o.outerHeight()}p=setInterval(function(){if(e.horizontalScroll){if(e.advanced.autoExpandHorizontalScroll){o.css({position:"absolute",width:"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:o.outerWidth(),position:"relative"}).unwrap()}var v=o.outerWidth()}else{var v=o.outerHeight()}if(v!=n){m.mCustomScrollbar("update");n=v}},300)}})},update:function(){var n=c(this),k=n.children(".mCustomScrollBox"),q=k.children(".mCSB_container");q.removeClass("mCS_no_scrollbar");n.removeClass("mCS_disabled mCS_destroyed");k.scrollTop(0).scrollLeft(0);var y=k.children(".mCSB_scrollTools"),o=y.children(".mCSB_draggerContainer"),m=o.children(".mCSB_dragger");if(n.data("horizontalScroll")){var A=y.children(".mCSB_buttonLeft"),t=y.children(".mCSB_buttonRight"),f=k.width();if(n.data("autoExpandHorizontalScroll")){q.css({position:"absolute",width:"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:q.outerWidth(),position:"relative"}).unwrap()}var z=q.outerWidth()}else{var w=y.children(".mCSB_buttonUp"),g=y.children(".mCSB_buttonDown"),r=k.height(),i=q.outerHeight()}if(i>r&&!n.data("horizontalScroll")){y.css("display","block");var s=o.height();if(n.data("autoDraggerLength")){var u=Math.round(r/i*s),l=m.data("minDraggerHeight");if(u<=l){m.css({height:l})}else{if(u>=s-10){var p=s-10;m.css({height:p})}else{m.css({height:u})}}m.children(".mCSB_dragger_bar").css({"line-height":m.height()+"px"})}var B=m.height(),x=(i-r)/(s-B);n.data("scrollAmount",x).mCustomScrollbar("scrolling",k,q,o,m,w,g,A,t);var D=Math.abs(q.position().top);n.mCustomScrollbar("scrollTo",D,{scrollInertia:0,trigger:"internal"})}else{if(z>f&&n.data("horizontalScroll")){y.css("display","block");var h=o.width();if(n.data("autoDraggerLength")){var j=Math.round(f/z*h),C=m.data("minDraggerWidth");if(j<=C){m.css({width:C})}else{if(j>=h-10){var e=h-10;m.css({width:e})}else{m.css({width:j})}}}var v=m.width(),x=(z-f)/(h-v);n.data("scrollAmount",x).mCustomScrollbar("scrolling",k,q,o,m,w,g,A,t);var D=Math.abs(q.position().left);n.mCustomScrollbar("scrollTo",D,{scrollInertia:0,trigger:"internal"})}else{k.unbind("mousewheel focusin");if(n.data("horizontalScroll")){m.add(q).css("left",0)}else{m.add(q).css("top",0)}y.css("display","none");q.addClass("mCS_no_scrollbar");n.data({bindEvent_mousewheel:false,bindEvent_focusin:false})}}},scrolling:function(h,p,m,j,w,e,A,v){var k=c(this);if(!k.data("bindEvent_scrollbar_drag")){var n,o;if(c.support.msPointer){j.bind("MSPointerDown",function(H){H.preventDefault();k.data({on_drag:true});j.addClass("mCSB_dragger_onDrag");var G=c(this),J=G.offset(),F=H.originalEvent.pageX-J.left,I=H.originalEvent.pageY-J.top;if(F<G.width()&&F>0&&I<G.height()&&I>0){n=I;o=F}});c(document).bind("MSPointerMove."+k.data("mCustomScrollbarIndex"),function(H){H.preventDefault();if(k.data("on_drag")){var G=j,J=G.offset(),F=H.originalEvent.pageX-J.left,I=H.originalEvent.pageY-J.top;D(n,o,I,F)}}).bind("MSPointerUp."+k.data("mCustomScrollbarIndex"),function(x){k.data({on_drag:false});j.removeClass("mCSB_dragger_onDrag")})}else{j.bind("mousedown touchstart",function(H){H.preventDefault();H.stopImmediatePropagation();var G=c(this),K=G.offset(),F,J;if(H.type==="touchstart"){var I=H.originalEvent.touches[0]||H.originalEvent.changedTouches[0];F=I.pageX-K.left;J=I.pageY-K.top}else{k.data({on_drag:true});j.addClass("mCSB_dragger_onDrag");F=H.pageX-K.left;J=H.pageY-K.top}if(F<G.width()&&F>0&&J<G.height()&&J>0){n=J;o=F}}).bind("touchmove",function(H){H.preventDefault();H.stopImmediatePropagation();var K=H.originalEvent.touches[0]||H.originalEvent.changedTouches[0],G=c(this),J=G.offset(),F=K.pageX-J.left,I=K.pageY-J.top;D(n,o,I,F)});c(document).bind("mousemove."+k.data("mCustomScrollbarIndex"),function(H){if(k.data("on_drag")){var G=j,J=G.offset(),F=H.pageX-J.left,I=H.pageY-J.top;D(n,o,I,F)}}).bind("mouseup."+k.data("mCustomScrollbarIndex"),function(x){k.data({on_drag:false});j.removeClass("mCSB_dragger_onDrag")})}k.data({bindEvent_scrollbar_drag:true})}function D(G,H,I,F){if(k.data("horizontalScroll")){k.mCustomScrollbar("scrollTo",(j.position().left-(H))+F,{moveDragger:true,trigger:"internal"})}else{k.mCustomScrollbar("scrollTo",(j.position().top-(G))+I,{moveDragger:true,trigger:"internal"})}}if(c.support.touch&&k.data("contentTouchScroll")){if(!k.data("bindEvent_content_touch")){var l,B,r,s,u,C,E;p.bind("touchstart",function(x){x.stopImmediatePropagation();l=x.originalEvent.touches[0]||x.originalEvent.changedTouches[0];B=c(this);r=B.offset();u=l.pageX-r.left;s=l.pageY-r.top;C=s;E=u});p.bind("touchmove",function(x){x.preventDefault();x.stopImmediatePropagation();l=x.originalEvent.touches[0]||x.originalEvent.changedTouches[0];B=c(this).parent();r=B.offset();u=l.pageX-r.left;s=l.pageY-r.top;if(k.data("horizontalScroll")){k.mCustomScrollbar("scrollTo",E-u,{trigger:"internal"})}else{k.mCustomScrollbar("scrollTo",C-s,{trigger:"internal"})}})}}if(!k.data("bindEvent_scrollbar_click")){m.bind("click",function(F){var x=(F.pageY-m.offset().top)*k.data("scrollAmount"),y=c(F.target);if(k.data("horizontalScroll")){x=(F.pageX-m.offset().left)*k.data("scrollAmount")}if(y.hasClass("mCSB_draggerContainer")||y.hasClass("mCSB_draggerRail")){k.mCustomScrollbar("scrollTo",x,{trigger:"internal",scrollEasing:"draggerRailEase"})}});k.data({bindEvent_scrollbar_click:true})}if(k.data("mouseWheel")){if(!k.data("bindEvent_mousewheel")){h.bind("mousewheel",function(H,J){var G,F=k.data("mouseWheelPixels"),x=Math.abs(p.position().top),I=j.position().top,y=m.height()-j.height();if(k.data("normalizeMouseWheelDelta")){if(J<0){J=-1}else{J=1}}if(F==="auto"){F=100+Math.round(k.data("scrollAmount")/2)}if(k.data("horizontalScroll")){I=j.position().left;y=m.width()-j.width();x=Math.abs(p.position().left)}if((J>0&&I!==0)||(J<0&&I!==y)){H.preventDefault();H.stopImmediatePropagation()}G=x-(J*F);k.mCustomScrollbar("scrollTo",G,{trigger:"internal"})});k.data({bindEvent_mousewheel:true})}}if(k.data("scrollButtons_enable")){if(k.data("scrollButtons_scrollType")==="pixels"){if(k.data("horizontalScroll")){v.add(A).unbind("mousedown touchstart MSPointerDown mouseup MSPointerUp mouseout MSPointerOut touchend",i,g);k.data({bindEvent_buttonsContinuous_x:false});if(!k.data("bindEvent_buttonsPixels_x")){v.bind("click",function(x){x.preventDefault();q(Math.abs(p.position().left)+k.data("scrollButtons_scrollAmount"))});A.bind("click",function(x){x.preventDefault();q(Math.abs(p.position().left)-k.data("scrollButtons_scrollAmount"))});k.data({bindEvent_buttonsPixels_x:true})}}else{e.add(w).unbind("mousedown touchstart MSPointerDown mouseup MSPointerUp mouseout MSPointerOut touchend",i,g);k.data({bindEvent_buttonsContinuous_y:false});if(!k.data("bindEvent_buttonsPixels_y")){e.bind("click",function(x){x.preventDefault();q(Math.abs(p.position().top)+k.data("scrollButtons_scrollAmount"))});w.bind("click",function(x){x.preventDefault();q(Math.abs(p.position().top)-k.data("scrollButtons_scrollAmount"))});k.data({bindEvent_buttonsPixels_y:true})}}function q(x){if(!j.data("preventAction")){j.data("preventAction",true);k.mCustomScrollbar("scrollTo",x,{trigger:"internal"})}}}else{if(k.data("horizontalScroll")){v.add(A).unbind("click");k.data({bindEvent_buttonsPixels_x:false});if(!k.data("bindEvent_buttonsContinuous_x")){v.bind("mousedown touchstart MSPointerDown",function(y){y.preventDefault();var x=z();k.data({mCSB_buttonScrollRight:setInterval(function(){k.mCustomScrollbar("scrollTo",Math.abs(p.position().left)+x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var i=function(x){x.preventDefault();clearInterval(k.data("mCSB_buttonScrollRight"))};v.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",i);A.bind("mousedown touchstart MSPointerDown",function(y){y.preventDefault();var x=z();k.data({mCSB_buttonScrollLeft:setInterval(function(){k.mCustomScrollbar("scrollTo",Math.abs(p.position().left)-x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var g=function(x){x.preventDefault();clearInterval(k.data("mCSB_buttonScrollLeft"))};A.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",g);k.data({bindEvent_buttonsContinuous_x:true})}}else{e.add(w).unbind("click");k.data({bindEvent_buttonsPixels_y:false});if(!k.data("bindEvent_buttonsContinuous_y")){e.bind("mousedown touchstart MSPointerDown",function(y){y.preventDefault();var x=z();k.data({mCSB_buttonScrollDown:setInterval(function(){k.mCustomScrollbar("scrollTo",Math.abs(p.position().top)+x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var t=function(x){x.preventDefault();clearInterval(k.data("mCSB_buttonScrollDown"))};e.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",t);w.bind("mousedown touchstart MSPointerDown",function(y){y.preventDefault();var x=z();k.data({mCSB_buttonScrollUp:setInterval(function(){k.mCustomScrollbar("scrollTo",Math.abs(p.position().top)-x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var f=function(x){x.preventDefault();clearInterval(k.data("mCSB_buttonScrollUp"))};w.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",f);k.data({bindEvent_buttonsContinuous_y:true})}}function z(){var x=k.data("scrollButtons_scrollSpeed");if(k.data("scrollButtons_scrollSpeed")==="auto"){x=Math.round((k.data("scrollInertia")+100)/40)}return x}}}if(k.data("autoScrollOnFocus")){if(!k.data("bindEvent_focusin")){h.bind("focusin",function(){h.scrollTop(0).scrollLeft(0);var x=c(document.activeElement);if(x.is("input,textarea,select,button,a[tabindex],area,object")){var G=p.position().top,y=x.position().top,F=h.height()-x.outerHeight();if(k.data("horizontalScroll")){G=p.position().left;y=x.position().left;F=h.width()-x.outerWidth()}if(G+y<0||G+y>F){k.mCustomScrollbar("scrollTo",y,{trigger:"internal"})}}});k.data({bindEvent_focusin:true})}}if(k.data("autoHideScrollbar")){if(!k.data("bindEvent_autoHideScrollbar")){h.bind("mouseenter",function(x){h.addClass("mCS-mouse-over");d.showScrollbar.call(h.children(".mCSB_scrollTools"))}).bind("mouseleave touchend",function(x){h.removeClass("mCS-mouse-over");if(x.type==="mouseleave"){d.hideScrollbar.call(h.children(".mCSB_scrollTools"))}});k.data({bindEvent_autoHideScrollbar:true})}}},scrollTo:function(e,f){var i=c(this),o={moveDragger:false,trigger:"external",callbacks:true,scrollInertia:i.data("scrollInertia"),scrollEasing:i.data("scrollEasing")},f=c.extend(o,f),p,g=i.children(".mCustomScrollBox"),k=g.children(".mCSB_container"),r=g.children(".mCSB_scrollTools"),j=r.children(".mCSB_draggerContainer"),h=j.children(".mCSB_dragger"),t=draggerSpeed=f.scrollInertia,q,s,m,l;if(!k.hasClass("mCS_no_scrollbar")){i.data({mCS_trigger:f.trigger});if(i.data("mCS_Init")){f.callbacks=false}if(e||e===0){if(typeof(e)==="number"){if(f.moveDragger){p=e;if(i.data("horizontalScroll")){e=h.position().left*i.data("scrollAmount")}else{e=h.position().top*i.data("scrollAmount")}draggerSpeed=0}else{p=e/i.data("scrollAmount")}}else{if(typeof(e)==="string"){var v;if(e==="top"){v=0}else{if(e==="bottom"&&!i.data("horizontalScroll")){v=k.outerHeight()-g.height()}else{if(e==="left"){v=0}else{if(e==="right"&&i.data("horizontalScroll")){v=k.outerWidth()-g.width()}else{if(e==="first"){v=i.find(".mCSB_container").find(":first")}else{if(e==="last"){v=i.find(".mCSB_container").find(":last")}else{v=i.find(e)}}}}}}if(v.length===1){if(i.data("horizontalScroll")){e=v.position().left}else{e=v.position().top}p=e/i.data("scrollAmount")}else{p=e=v}}}if(i.data("horizontalScroll")){if(i.data("onTotalScrollBack_Offset")){s=-i.data("onTotalScrollBack_Offset")}if(i.data("onTotalScroll_Offset")){l=g.width()-k.outerWidth()+i.data("onTotalScroll_Offset")}if(p<0){p=e=0;clearInterval(i.data("mCSB_buttonScrollLeft"));if(!s){q=true}}else{if(p>=j.width()-h.width()){p=j.width()-h.width();e=g.width()-k.outerWidth();clearInterval(i.data("mCSB_buttonScrollRight"));if(!l){m=true}}else{e=-e}}var n=i.data("snapAmount");if(n){e=Math.round(e/n)*n-i.data("snapOffset")}d.mTweenAxis.call(this,h[0],"left",Math.round(p),draggerSpeed,f.scrollEasing);d.mTweenAxis.call(this,k[0],"left",Math.round(e),t,f.scrollEasing,{onStart:function(){if(f.callbacks&&!i.data("mCS_tweenRunning")){u("onScrollStart")}if(i.data("autoHideScrollbar")){d.showScrollbar.call(r)}},onUpdate:function(){if(f.callbacks){u("whileScrolling")}},onComplete:function(){if(f.callbacks){u("onScroll");if(q||(s&&k.position().left>=s)){u("onTotalScrollBack")}if(m||(l&&k.position().left<=l)){u("onTotalScroll")}}h.data("preventAction",false);i.data("mCS_tweenRunning",false);if(i.data("autoHideScrollbar")){if(!g.hasClass("mCS-mouse-over")){d.hideScrollbar.call(r)}}}})}else{if(i.data("onTotalScrollBack_Offset")){s=-i.data("onTotalScrollBack_Offset")}if(i.data("onTotalScroll_Offset")){l=g.height()-k.outerHeight()+i.data("onTotalScroll_Offset")}if(p<0){p=e=0;clearInterval(i.data("mCSB_buttonScrollUp"));if(!s){q=true}}else{if(p>=j.height()-h.height()){p=j.height()-h.height();e=g.height()-k.outerHeight();clearInterval(i.data("mCSB_buttonScrollDown"));if(!l){m=true}}else{e=-e}}var n=i.data("snapAmount");if(n){e=Math.round(e/n)*n-i.data("snapOffset")}d.mTweenAxis.call(this,h[0],"top",Math.round(p),draggerSpeed,f.scrollEasing);d.mTweenAxis.call(this,k[0],"top",Math.round(e),t,f.scrollEasing,{onStart:function(){if(f.callbacks&&!i.data("mCS_tweenRunning")){u("onScrollStart")}if(i.data("autoHideScrollbar")){d.showScrollbar.call(r)}},onUpdate:function(){if(f.callbacks){u("whileScrolling")}},onComplete:function(){if(f.callbacks){u("onScroll");if(q||(s&&k.position().top>=s)){u("onTotalScrollBack")}if(m||(l&&k.position().top<=l)){u("onTotalScroll")}}h.data("preventAction",false);i.data("mCS_tweenRunning",false);if(i.data("autoHideScrollbar")){if(!g.hasClass("mCS-mouse-over")){d.hideScrollbar.call(r)}}}})}if(i.data("mCS_Init")){i.data({mCS_Init:false})}}}function u(w){this.mcs={top:k.position().top,left:k.position().left,draggerTop:h.position().top,draggerLeft:h.position().left,topPct:Math.round((100*Math.abs(k.position().top))/Math.abs(k.outerHeight()-g.height())),leftPct:Math.round((100*Math.abs(k.position().left))/Math.abs(k.outerWidth()-g.width()))};switch(w){case"onScrollStart":i.data("mCS_tweenRunning",true).data("onScrollStart_Callback").call(i,this.mcs);break;case"whileScrolling":i.data("whileScrolling_Callback").call(i,this.mcs);break;case"onScroll":i.data("onScroll_Callback").call(i,this.mcs);break;case"onTotalScrollBack":i.data("onTotalScrollBack_Callback").call(i,this.mcs);break;case"onTotalScroll":i.data("onTotalScroll_Callback").call(i,this.mcs);break}}},stop:function(){var g=c(this),e=g.children().children(".mCSB_container"),f=g.children().children().children().children(".mCSB_dragger");d.mTweenAxisStop.call(this,e[0]);d.mTweenAxisStop.call(this,f[0])},disable:function(e){var j=c(this),f=j.children(".mCustomScrollBox"),h=f.children(".mCSB_container"),g=f.children(".mCSB_scrollTools"),i=g.children().children(".mCSB_dragger");f.unbind("mousewheel focusin mouseenter mouseleave touchend");h.unbind("touchstart touchmove");if(e){if(j.data("horizontalScroll")){i.add(h).css("left",0)}else{i.add(h).css("top",0)}}g.css("display","none");h.addClass("mCS_no_scrollbar");j.data({bindEvent_mousewheel:false,bindEvent_focusin:false,bindEvent_content_touch:false,bindEvent_autoHideScrollbar:false}).addClass("mCS_disabled")},destroy:function(){var e=c(this);e.removeClass("mCustomScrollbar _mCS_"+e.data("mCustomScrollbarIndex")).addClass("mCS_destroyed").children().children(".mCSB_container").unwrap().children().unwrap().siblings(".mCSB_scrollTools").remove();c(document).unbind("mousemove."+e.data("mCustomScrollbarIndex")+" mouseup."+e.data("mCustomScrollbarIndex")+" MSPointerMove."+e.data("mCustomScrollbarIndex")+" MSPointerUp."+e.data("mCustomScrollbarIndex"));c(window).unbind("resize."+e.data("mCustomScrollbarIndex"))}},d={showScrollbar:function(){this.stop().animate({opacity:1},"fast")},hideScrollbar:function(){this.stop().animate({opacity:0},"fast")},mTweenAxis:function(g,i,h,f,o,y){var y=y||{},v=y.onStart||function(){},p=y.onUpdate||function(){},w=y.onComplete||function(){};var n=t(),l,j=0,r=g.offsetTop,s=g.style;if(i==="left"){r=g.offsetLeft}var m=h-r;q();e();function t(){if(window.performance&&window.performance.now){return window.performance.now()}else{if(window.performance&&window.performance.webkitNow){return window.performance.webkitNow()}else{if(Date.now){return Date.now()}else{return new Date().getTime()}}}}function x(){if(!j){v.call()}j=t()-n;u();if(j>=g._time){g._time=(j>g._time)?j+l-(j-g._time):j+l-1;if(g._time<j+1){g._time=j+1}}if(g._time<f){g._id=_request(x)}else{w.call()}}function u(){if(f>0){g.currVal=k(g._time,r,m,f,o);s[i]=Math.round(g.currVal)+"px"}else{s[i]=h+"px"}p.call()}function e(){l=1000/60;g._time=j+l;_request=(!window.requestAnimationFrame)?function(z){u();return setTimeout(z,0.01)}:window.requestAnimationFrame;g._id=_request(x)}function q(){if(g._id==null){return}if(!window.requestAnimationFrame){clearTimeout(g._id)}else{window.cancelAnimationFrame(g._id)}g._id=null}function k(B,A,F,E,C){switch(C){case"linear":return F*B/E+A;break;case"easeOutQuad":B/=E;return -F*B*(B-2)+A;break;case"easeInOutQuad":B/=E/2;if(B<1){return F/2*B*B+A}B--;return -F/2*(B*(B-2)-1)+A;break;case"easeOutCubic":B/=E;B--;return F*(B*B*B+1)+A;break;case"easeOutQuart":B/=E;B--;return -F*(B*B*B*B-1)+A;break;case"easeOutQuint":B/=E;B--;return F*(B*B*B*B*B+1)+A;break;case"easeOutCirc":B/=E;B--;return F*Math.sqrt(1-B*B)+A;break;case"easeOutSine":return F*Math.sin(B/E*(Math.PI/2))+A;break;case"easeOutExpo":return F*(-Math.pow(2,-10*B/E)+1)+A;break;case"mcsEaseOut":var D=(B/=E)*B,z=D*B;return A+F*(0.499999999999997*z*D+-2.5*D*D+5.5*z+-6.5*D+4*B);break;case"draggerRailEase":B/=E/2;if(B<1){return F/2*B*B*B+A}B-=2;return F/2*(B*B*B+2)+A;break}}},mTweenAxisStop:function(e){if(e._id==null){return}if(!window.requestAnimationFrame){clearTimeout(e._id)}else{window.cancelAnimationFrame(e._id)}e._id=null},rafPolyfill:function(){var f=["ms","moz","webkit","o"],e=f.length;while(--e>-1&&!window.requestAnimationFrame){window.requestAnimationFrame=window[f[e]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[f[e]+"CancelAnimationFrame"]||window[f[e]+"CancelRequestAnimationFrame"]}}};d.rafPolyfill.call();c.support.touch=!!("ontouchstart" in window);c.support.msPointer=window.navigator.msPointerEnabled;var a=("https:"==document.location.protocol)?"https:":"http:";c.event.special.mousewheel||document.write('<script src="'+a+'//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.0.6/jquery.mousewheel.min.js"><\/script>');c.fn.mCustomScrollbar=function(e){if(b[e]){return b[e].apply(this,Array.prototype.slice.call(arguments,1))}else{if(typeof e==="object"||!e){return b.init.apply(this,arguments)}else{c.error("Method "+e+" does not exist")}}}})(jQuery);;
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var H;function f(){return H.apply(null,arguments)}function a(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function F(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function L(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;for(var t in e)if(c(e,t))return;return 1}function o(e){return void 0===e}function u(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function V(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function G(e,t){for(var n=[],s=e.length,i=0;i<s;++i)n.push(t(e[i],i));return n}function E(e,t){for(var n in t)c(t,n)&&(e[n]=t[n]);return c(t,"toString")&&(e.toString=t.toString),c(t,"valueOf")&&(e.valueOf=t.valueOf),e}function l(e,t,n,s){return Pt(e,t,n,s,!0).utc()}function m(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function A(e){if(null==e._isValid){var t=m(e),n=j.call(t.parsedDateParts,function(e){return null!=e}),n=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(n=n&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return n;e._isValid=n}return e._isValid}function I(e){var t=l(NaN);return null!=e?E(m(t),e):m(t).userInvalidated=!0,t}var j=Array.prototype.some||function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1},Z=f.momentProperties=[],z=!1;function $(e,t){var n,s,i,r=Z.length;if(o(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),o(t._i)||(e._i=t._i),o(t._f)||(e._f=t._f),o(t._l)||(e._l=t._l),o(t._strict)||(e._strict=t._strict),o(t._tzm)||(e._tzm=t._tzm),o(t._isUTC)||(e._isUTC=t._isUTC),o(t._offset)||(e._offset=t._offset),o(t._pf)||(e._pf=m(t)),o(t._locale)||(e._locale=t._locale),0<r)for(n=0;n<r;n++)o(i=t[s=Z[n]])||(e[s]=i);return e}function q(e){$(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===z&&(z=!0,f.updateOffset(this),z=!1)}function h(e){return e instanceof q||null!=e&&null!=e._isAMomentObject}function B(e){!1===f.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function e(r,a){var o=!0;return E(function(){if(null!=f.deprecationHandler&&f.deprecationHandler(null,r),o){for(var e,t,n=[],s=arguments.length,i=0;i<s;i++){if(e="","object"==typeof arguments[i]){for(t in e+="\n["+i+"] ",arguments[0])c(arguments[0],t)&&(e+=t+": "+arguments[0][t]+", ");e=e.slice(0,-2)}else e=arguments[i];n.push(e)}B(r+"\nArguments: "+Array.prototype.slice.call(n).join("")+"\n"+(new Error).stack),o=!1}return a.apply(this,arguments)},a)}var J={};function Q(e,t){null!=f.deprecationHandler&&f.deprecationHandler(e,t),J[e]||(B(t),J[e]=!0)}function d(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function X(e,t){var n,s=E({},e);for(n in t)c(t,n)&&(F(e[n])&&F(t[n])?(s[n]={},E(s[n],e[n]),E(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)c(e,n)&&!c(t,n)&&F(e[n])&&(s[n]=E({},s[n]));return s}function K(e){null!=e&&this.set(e)}f.suppressDeprecationWarnings=!1,f.deprecationHandler=null;var ee=Object.keys||function(e){var t,n=[];for(t in e)c(e,t)&&n.push(t);return n};function r(e,t,n){var s=""+Math.abs(e);return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,t-s.length)).toString().substr(1)+s}var te=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,ne=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,se={},ie={};function s(e,t,n,s){var i="string"==typeof s?function(){return this[s]()}:s;e&&(ie[e]=i),t&&(ie[t[0]]=function(){return r(i.apply(this,arguments),t[1],t[2])}),n&&(ie[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function re(e,t){return e.isValid()?(t=ae(t,e.localeData()),se[t]=se[t]||function(s){for(var e,i=s.match(te),t=0,r=i.length;t<r;t++)ie[i[t]]?i[t]=ie[i[t]]:i[t]=(e=i[t]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var t="",n=0;n<r;n++)t+=d(i[n])?i[n].call(e,s):i[n];return t}}(t),se[t](e)):e.localeData().invalidDate()}function ae(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(ne.lastIndex=0;0<=n&&ne.test(e);)e=e.replace(ne,s),ne.lastIndex=0,--n;return e}var oe={};function t(e,t){var n=e.toLowerCase();oe[n]=oe[n+"s"]=oe[t]=e}function _(e){return"string"==typeof e?oe[e]||oe[e.toLowerCase()]:void 0}function ue(e){var t,n,s={};for(n in e)c(e,n)&&(t=_(n))&&(s[t]=e[n]);return s}var le={};function n(e,t){le[e]=t}function he(e){return e%4==0&&e%100!=0||e%400==0}function y(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function g(e){var e=+e,t=0;return t=0!=e&&isFinite(e)?y(e):t}function de(t,n){return function(e){return null!=e?(fe(this,t,e),f.updateOffset(this,n),this):ce(this,t)}}function ce(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function fe(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&he(e.year())&&1===e.month()&&29===e.date()?(n=g(n),e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),We(n,e.month()))):e._d["set"+(e._isUTC?"UTC":"")+t](n))}var i=/\d/,w=/\d\d/,me=/\d{3}/,_e=/\d{4}/,ye=/[+-]?\d{6}/,p=/\d\d?/,ge=/\d\d\d\d?/,we=/\d\d\d\d\d\d?/,pe=/\d{1,3}/,ke=/\d{1,4}/,ve=/[+-]?\d{1,6}/,Me=/\d+/,De=/[+-]?\d+/,Se=/Z|[+-]\d\d:?\d\d/gi,Ye=/Z|[+-]\d\d(?::?\d\d)?/gi,k=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;function v(e,n,s){be[e]=d(n)?n:function(e,t){return e&&s?s:n}}function Oe(e,t){return c(be,e)?be[e](t._strict,t._locale):new RegExp(M(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function M(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var be={},xe={};function D(e,n){var t,s,i=n;for("string"==typeof e&&(e=[e]),u(n)&&(i=function(e,t){t[n]=g(e)}),s=e.length,t=0;t<s;t++)xe[e[t]]=i}function Te(e,i){D(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}var S,Y=0,O=1,b=2,x=3,T=4,N=5,Ne=6,Pe=7,Re=8;function We(e,t){if(isNaN(e)||isNaN(t))return NaN;var n=(t%(n=12)+n)%n;return e+=(t-n)/12,1==n?he(e)?29:28:31-n%7%2}S=Array.prototype.indexOf||function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1},s("M",["MM",2],"Mo",function(){return this.month()+1}),s("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),s("MMMM",0,0,function(e){return this.localeData().months(this,e)}),t("month","M"),n("month",8),v("M",p),v("MM",p,w),v("MMM",function(e,t){return t.monthsShortRegex(e)}),v("MMMM",function(e,t){return t.monthsRegex(e)}),D(["M","MM"],function(e,t){t[O]=g(e)-1}),D(["MMM","MMMM"],function(e,t,n,s){s=n._locale.monthsParse(e,s,n._strict);null!=s?t[O]=s:m(n).invalidMonth=e});var Ce="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Ue="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),He=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Fe=k,Le=k;function Ve(e,t){var n;if(e.isValid()){if("string"==typeof t)if(/^\d+$/.test(t))t=g(t);else if(!u(t=e.localeData().monthsParse(t)))return;n=Math.min(e.date(),We(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n)}}function Ge(e){return null!=e?(Ve(this,e),f.updateOffset(this,!0),this):ce(this,"Month")}function Ee(){function e(e,t){return t.length-e.length}for(var t,n=[],s=[],i=[],r=0;r<12;r++)t=l([2e3,r]),n.push(this.monthsShort(t,"")),s.push(this.months(t,"")),i.push(this.months(t,"")),i.push(this.monthsShort(t,""));for(n.sort(e),s.sort(e),i.sort(e),r=0;r<12;r++)n[r]=M(n[r]),s[r]=M(s[r]);for(r=0;r<24;r++)i[r]=M(i[r]);this._monthsRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+n.join("|")+")","i")}function Ae(e){return he(e)?366:365}s("Y",0,0,function(){var e=this.year();return e<=9999?r(e,4):"+"+e}),s(0,["YY",2],0,function(){return this.year()%100}),s(0,["YYYY",4],0,"year"),s(0,["YYYYY",5],0,"year"),s(0,["YYYYYY",6,!0],0,"year"),t("year","y"),n("year",1),v("Y",De),v("YY",p,w),v("YYYY",ke,_e),v("YYYYY",ve,ye),v("YYYYYY",ve,ye),D(["YYYYY","YYYYYY"],Y),D("YYYY",function(e,t){t[Y]=2===e.length?f.parseTwoDigitYear(e):g(e)}),D("YY",function(e,t){t[Y]=f.parseTwoDigitYear(e)}),D("Y",function(e,t){t[Y]=parseInt(e,10)}),f.parseTwoDigitYear=function(e){return g(e)+(68<g(e)?1900:2e3)};var Ie=de("FullYear",!0);function je(e,t,n,s,i,r,a){var o;return e<100&&0<=e?(o=new Date(e+400,t,n,s,i,r,a),isFinite(o.getFullYear())&&o.setFullYear(e)):o=new Date(e,t,n,s,i,r,a),o}function Ze(e){var t;return e<100&&0<=e?((t=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,t)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function ze(e,t,n){n=7+t-n;return n-(7+Ze(e,0,n).getUTCDay()-t)%7-1}function $e(e,t,n,s,i){var r,t=1+7*(t-1)+(7+n-s)%7+ze(e,s,i),n=t<=0?Ae(r=e-1)+t:t>Ae(e)?(r=e+1,t-Ae(e)):(r=e,t);return{year:r,dayOfYear:n}}function qe(e,t,n){var s,i,r=ze(e.year(),t,n),r=Math.floor((e.dayOfYear()-r-1)/7)+1;return r<1?s=r+P(i=e.year()-1,t,n):r>P(e.year(),t,n)?(s=r-P(e.year(),t,n),i=e.year()+1):(i=e.year(),s=r),{week:s,year:i}}function P(e,t,n){var s=ze(e,t,n),t=ze(e+1,t,n);return(Ae(e)-s+t)/7}s("w",["ww",2],"wo","week"),s("W",["WW",2],"Wo","isoWeek"),t("week","w"),t("isoWeek","W"),n("week",5),n("isoWeek",5),v("w",p),v("ww",p,w),v("W",p),v("WW",p,w),Te(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=g(e)});function Be(e,t){return e.slice(t,7).concat(e.slice(0,t))}s("d",0,"do","day"),s("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),s("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),s("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),s("e",0,0,"weekday"),s("E",0,0,"isoWeekday"),t("day","d"),t("weekday","e"),t("isoWeekday","E"),n("day",11),n("weekday",11),n("isoWeekday",11),v("d",p),v("e",p),v("E",p),v("dd",function(e,t){return t.weekdaysMinRegex(e)}),v("ddd",function(e,t){return t.weekdaysShortRegex(e)}),v("dddd",function(e,t){return t.weekdaysRegex(e)}),Te(["dd","ddd","dddd"],function(e,t,n,s){s=n._locale.weekdaysParse(e,s,n._strict);null!=s?t.d=s:m(n).invalidWeekday=e}),Te(["d","e","E"],function(e,t,n,s){t[s]=g(e)});var Je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Qe="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Xe="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Ke=k,et=k,tt=k;function nt(){function e(e,t){return t.length-e.length}for(var t,n,s,i=[],r=[],a=[],o=[],u=0;u<7;u++)s=l([2e3,1]).day(u),t=M(this.weekdaysMin(s,"")),n=M(this.weekdaysShort(s,"")),s=M(this.weekdays(s,"")),i.push(t),r.push(n),a.push(s),o.push(t),o.push(n),o.push(s);i.sort(e),r.sort(e),a.sort(e),o.sort(e),this._weekdaysRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+i.join("|")+")","i")}function st(){return this.hours()%12||12}function it(e,t){s(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function rt(e,t){return t._meridiemParse}s("H",["HH",2],0,"hour"),s("h",["hh",2],0,st),s("k",["kk",2],0,function(){return this.hours()||24}),s("hmm",0,0,function(){return""+st.apply(this)+r(this.minutes(),2)}),s("hmmss",0,0,function(){return""+st.apply(this)+r(this.minutes(),2)+r(this.seconds(),2)}),s("Hmm",0,0,function(){return""+this.hours()+r(this.minutes(),2)}),s("Hmmss",0,0,function(){return""+this.hours()+r(this.minutes(),2)+r(this.seconds(),2)}),it("a",!0),it("A",!1),t("hour","h"),n("hour",13),v("a",rt),v("A",rt),v("H",p),v("h",p),v("k",p),v("HH",p,w),v("hh",p,w),v("kk",p,w),v("hmm",ge),v("hmmss",we),v("Hmm",ge),v("Hmmss",we),D(["H","HH"],x),D(["k","kk"],function(e,t,n){e=g(e);t[x]=24===e?0:e}),D(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),D(["h","hh"],function(e,t,n){t[x]=g(e),m(n).bigHour=!0}),D("hmm",function(e,t,n){var s=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s)),m(n).bigHour=!0}),D("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s,2)),t[N]=g(e.substr(i)),m(n).bigHour=!0}),D("Hmm",function(e,t,n){var s=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s))}),D("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s,2)),t[N]=g(e.substr(i))});k=de("Hours",!0);var at,ot={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Ce,monthsShort:Ue,week:{dow:0,doy:6},weekdays:Je,weekdaysMin:Xe,weekdaysShort:Qe,meridiemParse:/[ap]\.?m?\.?/i},R={},ut={};function lt(e){return e&&e.toLowerCase().replace("_","-")}function ht(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=lt(e[r]).split("-")).length,n=(n=lt(e[r+1]))?n.split("-"):null;0<t;){if(s=dt(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&function(e,t){for(var n=Math.min(e.length,t.length),s=0;s<n;s+=1)if(e[s]!==t[s])return s;return n}(i,n)>=t-1)break;t--}r++}return at}function dt(t){var e;if(void 0===R[t]&&"undefined"!=typeof module&&module&&module.exports&&null!=t.match("^[^/\\\\]*$"))try{e=at._abbr,require("./locale/"+t),ct(e)}catch(e){R[t]=null}return R[t]}function ct(e,t){return e&&((t=o(t)?mt(e):ft(e,t))?at=t:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),at._abbr}function ft(e,t){if(null===t)return delete R[e],null;var n,s=ot;if(t.abbr=e,null!=R[e])Q("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),s=R[e]._config;else if(null!=t.parentLocale)if(null!=R[t.parentLocale])s=R[t.parentLocale]._config;else{if(null==(n=dt(t.parentLocale)))return ut[t.parentLocale]||(ut[t.parentLocale]=[]),ut[t.parentLocale].push({name:e,config:t}),null;s=n._config}return R[e]=new K(X(s,t)),ut[e]&&ut[e].forEach(function(e){ft(e.name,e.config)}),ct(e),R[e]}function mt(e){var t;if(!(e=e&&e._locale&&e._locale._abbr?e._locale._abbr:e))return at;if(!a(e)){if(t=dt(e))return t;e=[e]}return ht(e)}function _t(e){var t=e._a;return t&&-2===m(e).overflow&&(t=t[O]<0||11<t[O]?O:t[b]<1||t[b]>We(t[Y],t[O])?b:t[x]<0||24<t[x]||24===t[x]&&(0!==t[T]||0!==t[N]||0!==t[Ne])?x:t[T]<0||59<t[T]?T:t[N]<0||59<t[N]?N:t[Ne]<0||999<t[Ne]?Ne:-1,m(e)._overflowDayOfYear&&(t<Y||b<t)&&(t=b),m(e)._overflowWeeks&&-1===t&&(t=Pe),m(e)._overflowWeekday&&-1===t&&(t=Re),m(e).overflow=t),e}var yt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,gt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,wt=/Z|[+-]\d\d(?::?\d\d)?/,pt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],kt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],vt=/^\/?Date\((-?\d+)/i,Mt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Dt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function St(e){var t,n,s,i,r,a,o=e._i,u=yt.exec(o)||gt.exec(o),o=pt.length,l=kt.length;if(u){for(m(e).iso=!0,t=0,n=o;t<n;t++)if(pt[t][1].exec(u[1])){i=pt[t][0],s=!1!==pt[t][2];break}if(null==i)e._isValid=!1;else{if(u[3]){for(t=0,n=l;t<n;t++)if(kt[t][1].exec(u[3])){r=(u[2]||" ")+kt[t][0];break}if(null==r)return void(e._isValid=!1)}if(s||null==r){if(u[4]){if(!wt.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),Tt(e)}else e._isValid=!1}}else e._isValid=!1}function Yt(e,t,n,s,i,r){e=[function(e){e=parseInt(e,10);{if(e<=49)return 2e3+e;if(e<=999)return 1900+e}return e}(e),Ue.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&e.push(parseInt(r,10)),e}function Ot(e){var t,n,s,i,r=Mt.exec(e._i.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));r?(t=Yt(r[4],r[3],r[2],r[5],r[6],r[7]),n=r[1],s=t,i=e,n&&Qe.indexOf(n)!==new Date(s[0],s[1],s[2]).getDay()?(m(i).weekdayMismatch=!0,i._isValid=!1):(e._a=t,e._tzm=(n=r[8],s=r[9],i=r[10],n?Dt[n]:s?0:60*(((n=parseInt(i,10))-(s=n%100))/100)+s),e._d=Ze.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),m(e).rfc2822=!0)):e._isValid=!1}function bt(e,t,n){return null!=e?e:null!=t?t:n}function xt(e){var t,n,s,i,r,a,o,u,l,h,d,c=[];if(!e._d){for(s=e,i=new Date(f.now()),n=s._useUTC?[i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()]:[i.getFullYear(),i.getMonth(),i.getDate()],e._w&&null==e._a[b]&&null==e._a[O]&&(null!=(i=(s=e)._w).GG||null!=i.W||null!=i.E?(u=1,l=4,r=bt(i.GG,s._a[Y],qe(W(),1,4).year),a=bt(i.W,1),((o=bt(i.E,1))<1||7<o)&&(h=!0)):(u=s._locale._week.dow,l=s._locale._week.doy,d=qe(W(),u,l),r=bt(i.gg,s._a[Y],d.year),a=bt(i.w,d.week),null!=i.d?((o=i.d)<0||6<o)&&(h=!0):null!=i.e?(o=i.e+u,(i.e<0||6<i.e)&&(h=!0)):o=u),a<1||a>P(r,u,l)?m(s)._overflowWeeks=!0:null!=h?m(s)._overflowWeekday=!0:(d=$e(r,a,o,u,l),s._a[Y]=d.year,s._dayOfYear=d.dayOfYear)),null!=e._dayOfYear&&(i=bt(e._a[Y],n[Y]),(e._dayOfYear>Ae(i)||0===e._dayOfYear)&&(m(e)._overflowDayOfYear=!0),h=Ze(i,0,e._dayOfYear),e._a[O]=h.getUTCMonth(),e._a[b]=h.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=c[t]=n[t];for(;t<7;t++)e._a[t]=c[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[x]&&0===e._a[T]&&0===e._a[N]&&0===e._a[Ne]&&(e._nextDay=!0,e._a[x]=0),e._d=(e._useUTC?Ze:je).apply(null,c),r=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[x]=24),e._w&&void 0!==e._w.d&&e._w.d!==r&&(m(e).weekdayMismatch=!0)}}function Tt(e){if(e._f===f.ISO_8601)St(e);else if(e._f===f.RFC_2822)Ot(e);else{e._a=[],m(e).empty=!0;for(var t,n,s,i,r,a=""+e._i,o=a.length,u=0,l=ae(e._f,e._locale).match(te)||[],h=l.length,d=0;d<h;d++)n=l[d],(t=(a.match(Oe(n,e))||[])[0])&&(0<(s=a.substr(0,a.indexOf(t))).length&&m(e).unusedInput.push(s),a=a.slice(a.indexOf(t)+t.length),u+=t.length),ie[n]?(t?m(e).empty=!1:m(e).unusedTokens.push(n),s=n,r=e,null!=(i=t)&&c(xe,s)&&xe[s](i,r._a,r,s)):e._strict&&!t&&m(e).unusedTokens.push(n);m(e).charsLeftOver=o-u,0<a.length&&m(e).unusedInput.push(a),e._a[x]<=12&&!0===m(e).bigHour&&0<e._a[x]&&(m(e).bigHour=void 0),m(e).parsedDateParts=e._a.slice(0),m(e).meridiem=e._meridiem,e._a[x]=function(e,t,n){if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((e=e.isPM(n))&&t<12&&(t+=12),t=e||12!==t?t:0):t}(e._locale,e._a[x],e._meridiem),null!==(o=m(e).era)&&(e._a[Y]=e._locale.erasConvertYear(o,e._a[Y])),xt(e),_t(e)}}function Nt(e){var t,n,s,i=e._i,r=e._f;if(e._locale=e._locale||mt(e._l),null===i||void 0===r&&""===i)return I({nullInput:!0});if("string"==typeof i&&(e._i=i=e._locale.preparse(i)),h(i))return new q(_t(i));if(V(i))e._d=i;else if(a(r))!function(e){var t,n,s,i,r,a,o=!1,u=e._f.length;if(0===u)return m(e).invalidFormat=!0,e._d=new Date(NaN);for(i=0;i<u;i++)r=0,a=!1,t=$({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Tt(t),A(t)&&(a=!0),r=(r+=m(t).charsLeftOver)+10*m(t).unusedTokens.length,m(t).score=r,o?r<s&&(s=r,n=t):(null==s||r<s||a)&&(s=r,n=t,a&&(o=!0));E(e,n||t)}(e);else if(r)Tt(e);else if(o(r=(i=e)._i))i._d=new Date(f.now());else V(r)?i._d=new Date(r.valueOf()):"string"==typeof r?(n=i,null!==(t=vt.exec(n._i))?n._d=new Date(+t[1]):(St(n),!1===n._isValid&&(delete n._isValid,Ot(n),!1===n._isValid&&(delete n._isValid,n._strict?n._isValid=!1:f.createFromInputFallback(n))))):a(r)?(i._a=G(r.slice(0),function(e){return parseInt(e,10)}),xt(i)):F(r)?(t=i)._d||(s=void 0===(n=ue(t._i)).day?n.date:n.day,t._a=G([n.year,n.month,s,n.hour,n.minute,n.second,n.millisecond],function(e){return e&&parseInt(e,10)}),xt(t)):u(r)?i._d=new Date(r):f.createFromInputFallback(i);return A(e)||(e._d=null),e}function Pt(e,t,n,s,i){var r={};return!0!==t&&!1!==t||(s=t,t=void 0),!0!==n&&!1!==n||(s=n,n=void 0),(F(e)&&L(e)||a(e)&&0===e.length)&&(e=void 0),r._isAMomentObject=!0,r._useUTC=r._isUTC=i,r._l=n,r._i=e,r._f=t,r._strict=s,(i=new q(_t(Nt(i=r))))._nextDay&&(i.add(1,"d"),i._nextDay=void 0),i}function W(e,t,n,s){return Pt(e,t,n,s,!1)}f.createFromInputFallback=e("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),f.ISO_8601=function(){},f.RFC_2822=function(){};ge=e("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=W.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:I()}),we=e("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=W.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:I()});function Rt(e,t){var n,s;if(!(t=1===t.length&&a(t[0])?t[0]:t).length)return W();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Wt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ct(e){var e=ue(e),t=e.year||0,n=e.quarter||0,s=e.month||0,i=e.week||e.isoWeek||0,r=e.day||0,a=e.hour||0,o=e.minute||0,u=e.second||0,l=e.millisecond||0;this._isValid=function(e){var t,n,s=!1,i=Wt.length;for(t in e)if(c(e,t)&&(-1===S.call(Wt,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[Wt[n]]){if(s)return!1;parseFloat(e[Wt[n]])!==g(e[Wt[n]])&&(s=!0)}return!0}(e),this._milliseconds=+l+1e3*u+6e4*o+1e3*a*60*60,this._days=+r+7*i,this._months=+s+3*n+12*t,this._data={},this._locale=mt(),this._bubble()}function Ut(e){return e instanceof Ct}function Ht(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,n){s(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+r(~~(e/60),2)+n+r(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),v("Z",Ye),v("ZZ",Ye),D(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Vt(Ye,e)});var Lt=/([\+\-]|\d\d)/gi;function Vt(e,t){var t=(t||"").match(e);return null===t?null:0===(t=60*(e=((t[t.length-1]||[])+"").match(Lt)||["-",0,0])[1]+g(e[2]))?0:"+"===e[0]?t:-t}function Gt(e,t){var n;return t._isUTC?(t=t.clone(),n=(h(e)||V(e)?e:W(e)).valueOf()-t.valueOf(),t._d.setTime(t._d.valueOf()+n),f.updateOffset(t,!1),t):W(e).local()}function Et(e){return-Math.round(e._d.getTimezoneOffset())}function At(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}f.updateOffset=function(){};var It=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,jt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function C(e,t){var n,s=e,i=null;return Ut(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:u(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(i=It.exec(e))?(n="-"===i[1]?-1:1,s={y:0,d:g(i[b])*n,h:g(i[x])*n,m:g(i[T])*n,s:g(i[N])*n,ms:g(Ht(1e3*i[Ne]))*n}):(i=jt.exec(e))?(n="-"===i[1]?-1:1,s={y:Zt(i[2],n),M:Zt(i[3],n),w:Zt(i[4],n),d:Zt(i[5],n),h:Zt(i[6],n),m:Zt(i[7],n),s:Zt(i[8],n)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(t=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Gt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(W(s.from),W(s.to)),(s={}).ms=t.milliseconds,s.M=t.months),i=new Ct(s),Ut(e)&&c(e,"_locale")&&(i._locale=e._locale),Ut(e)&&c(e,"_isValid")&&(i._isValid=e._isValid),i}function Zt(e,t){e=e&&parseFloat(e.replace(",","."));return(isNaN(e)?0:e)*t}function zt(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function $t(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(Q(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),qt(this,C(e,t),s),this}}function qt(e,t,n,s){var i=t._milliseconds,r=Ht(t._days),t=Ht(t._months);e.isValid()&&(s=null==s||s,t&&Ve(e,ce(e,"Month")+t*n),r&&fe(e,"Date",ce(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s&&f.updateOffset(e,r||t))}C.fn=Ct.prototype,C.invalid=function(){return C(NaN)};Ce=$t(1,"add"),Je=$t(-1,"subtract");function Bt(e){return"string"==typeof e||e instanceof String}function Jt(e){return h(e)||V(e)||Bt(e)||u(e)||function(t){var e=a(t),n=!1;e&&(n=0===t.filter(function(e){return!u(e)&&Bt(t)}).length);return e&&n}(e)||function(e){var t,n,s=F(e)&&!L(e),i=!1,r=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],a=r.length;for(t=0;t<a;t+=1)n=r[t],i=i||c(e,n);return s&&i}(e)||null==e}function Qt(e,t){if(e.date()<t.date())return-Qt(t,e);var n=12*(t.year()-e.year())+(t.month()-e.month()),s=e.clone().add(n,"months"),t=t-s<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(1+n,"months")-s);return-(n+t)||0}function Xt(e){return void 0===e?this._locale._abbr:(null!=(e=mt(e))&&(this._locale=e),this)}f.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",f.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";Xe=e("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}var en=126227808e5;function tn(e,t){return(e%t+t)%t}function nn(e,t,n){return e<100&&0<=e?new Date(e+400,t,n)-en:new Date(e,t,n).valueOf()}function sn(e,t,n){return e<100&&0<=e?Date.UTC(e+400,t,n)-en:Date.UTC(e,t,n)}function rn(e,t){return t.erasAbbrRegex(e)}function an(){for(var e=[],t=[],n=[],s=[],i=this.eras(),r=0,a=i.length;r<a;++r)t.push(M(i[r].name)),e.push(M(i[r].abbr)),n.push(M(i[r].narrow)),s.push(M(i[r].name)),s.push(M(i[r].abbr)),s.push(M(i[r].narrow));this._erasRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+t.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+e.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+n.join("|")+")","i")}function on(e,t){s(0,[e,e.length],0,t)}function un(e,t,n,s,i){var r;return null==e?qe(this,s,i).year:(r=P(e,s,i),function(e,t,n,s,i){e=$e(e,t,n,s,i),t=Ze(e.year,0,e.dayOfYear);return this.year(t.getUTCFullYear()),this.month(t.getUTCMonth()),this.date(t.getUTCDate()),this}.call(this,e,t=r<t?r:t,n,s,i))}s("N",0,0,"eraAbbr"),s("NN",0,0,"eraAbbr"),s("NNN",0,0,"eraAbbr"),s("NNNN",0,0,"eraName"),s("NNNNN",0,0,"eraNarrow"),s("y",["y",1],"yo","eraYear"),s("y",["yy",2],0,"eraYear"),s("y",["yyy",3],0,"eraYear"),s("y",["yyyy",4],0,"eraYear"),v("N",rn),v("NN",rn),v("NNN",rn),v("NNNN",function(e,t){return t.erasNameRegex(e)}),v("NNNNN",function(e,t){return t.erasNarrowRegex(e)}),D(["N","NN","NNN","NNNN","NNNNN"],function(e,t,n,s){s=n._locale.erasParse(e,s,n._strict);s?m(n).era=s:m(n).invalidEra=e}),v("y",Me),v("yy",Me),v("yyy",Me),v("yyyy",Me),v("yo",function(e,t){return t._eraYearOrdinalRegex||Me}),D(["y","yy","yyy","yyyy"],Y),D(["yo"],function(e,t,n,s){var i;n._locale._eraYearOrdinalRegex&&(i=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[Y]=n._locale.eraYearOrdinalParse(e,i):t[Y]=parseInt(e,10)}),s(0,["gg",2],0,function(){return this.weekYear()%100}),s(0,["GG",2],0,function(){return this.isoWeekYear()%100}),on("gggg","weekYear"),on("ggggg","weekYear"),on("GGGG","isoWeekYear"),on("GGGGG","isoWeekYear"),t("weekYear","gg"),t("isoWeekYear","GG"),n("weekYear",1),n("isoWeekYear",1),v("G",De),v("g",De),v("GG",p,w),v("gg",p,w),v("GGGG",ke,_e),v("gggg",ke,_e),v("GGGGG",ve,ye),v("ggggg",ve,ye),Te(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=g(e)}),Te(["gg","GG"],function(e,t,n,s){t[s]=f.parseTwoDigitYear(e)}),s("Q",0,"Qo","quarter"),t("quarter","Q"),n("quarter",7),v("Q",i),D("Q",function(e,t){t[O]=3*(g(e)-1)}),s("D",["DD",2],"Do","date"),t("date","D"),n("date",9),v("D",p),v("DD",p,w),v("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),D(["D","DD"],b),D("Do",function(e,t){t[b]=g(e.match(p)[0])});ke=de("Date",!0);s("DDD",["DDDD",3],"DDDo","dayOfYear"),t("dayOfYear","DDD"),n("dayOfYear",4),v("DDD",pe),v("DDDD",me),D(["DDD","DDDD"],function(e,t,n){n._dayOfYear=g(e)}),s("m",["mm",2],0,"minute"),t("minute","m"),n("minute",14),v("m",p),v("mm",p,w),D(["m","mm"],T);var ln,_e=de("Minutes",!1),ve=(s("s",["ss",2],0,"second"),t("second","s"),n("second",15),v("s",p),v("ss",p,w),D(["s","ss"],N),de("Seconds",!1));for(s("S",0,0,function(){return~~(this.millisecond()/100)}),s(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),s(0,["SSS",3],0,"millisecond"),s(0,["SSSS",4],0,function(){return 10*this.millisecond()}),s(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),s(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),s(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),s(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),s(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),t("millisecond","ms"),n("millisecond",16),v("S",pe,i),v("SS",pe,w),v("SSS",pe,me),ln="SSSS";ln.length<=9;ln+="S")v(ln,Me);function hn(e,t){t[Ne]=g(1e3*("0."+e))}for(ln="S";ln.length<=9;ln+="S")D(ln,hn);ye=de("Milliseconds",!1),s("z",0,0,"zoneAbbr"),s("zz",0,0,"zoneName");i=q.prototype;function dn(e){return e}i.add=Ce,i.calendar=function(e,t){1===arguments.length&&(arguments[0]?Jt(arguments[0])?(e=arguments[0],t=void 0):function(e){for(var t=F(e)&&!L(e),n=!1,s=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],i=0;i<s.length;i+=1)n=n||c(e,s[i]);return t&&n}(arguments[0])&&(t=arguments[0],e=void 0):t=e=void 0);var e=e||W(),n=Gt(e,this).startOf("day"),n=f.calendarFormat(this,n)||"sameElse",t=t&&(d(t[n])?t[n].call(this,e):t[n]);return this.format(t||this.localeData().calendar(n,this,W(e)))},i.clone=function(){return new q(this)},i.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Gt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=_(t)){case"year":r=Qt(this,s)/12;break;case"month":r=Qt(this,s);break;case"quarter":r=Qt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:y(r)},i.endOf=function(e){var t,n;if(void 0===(e=_(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=36e5-tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":t=this._d.valueOf(),t+=6e4-tn(t,6e4)-1;break;case"second":t=this._d.valueOf(),t+=1e3-tn(t,1e3)-1;break}return this._d.setTime(t),f.updateOffset(this,!0),this},i.format=function(e){return e=e||(this.isUtc()?f.defaultFormatUtc:f.defaultFormat),e=re(this,e),this.localeData().postformat(e)},i.from=function(e,t){return this.isValid()&&(h(e)&&e.isValid()||W(e).isValid())?C({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},i.fromNow=function(e){return this.from(W(),e)},i.to=function(e,t){return this.isValid()&&(h(e)&&e.isValid()||W(e).isValid())?C({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},i.toNow=function(e){return this.to(W(),e)},i.get=function(e){return d(this[e=_(e)])?this[e]():this},i.invalidAt=function(){return m(this).overflow},i.isAfter=function(e,t){return e=h(e)?e:W(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=_(t)||"millisecond")?this.valueOf()>e.valueOf():e.valueOf()<this.clone().startOf(t).valueOf())},i.isBefore=function(e,t){return e=h(e)?e:W(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=_(t)||"millisecond")?this.valueOf()<e.valueOf():this.clone().endOf(t).valueOf()<e.valueOf())},i.isBetween=function(e,t,n,s){return e=h(e)?e:W(e),t=h(t)?t:W(t),!!(this.isValid()&&e.isValid()&&t.isValid())&&(("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n)))},i.isSame=function(e,t){var e=h(e)?e:W(e);return!(!this.isValid()||!e.isValid())&&("millisecond"===(t=_(t)||"millisecond")?this.valueOf()===e.valueOf():(e=e.valueOf(),this.clone().startOf(t).valueOf()<=e&&e<=this.clone().endOf(t).valueOf()))},i.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},i.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},i.isValid=function(){return A(this)},i.lang=Xe,i.locale=Xt,i.localeData=Kt,i.max=we,i.min=ge,i.parsingFlags=function(){return E({},m(this))},i.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t,n=[];for(t in e)c(e,t)&&n.push({unit:t,priority:le[t]});return n.sort(function(e,t){return e.priority-t.priority}),n}(e=ue(e)),s=n.length,i=0;i<s;i++)this[n[i].unit](e[n[i].unit]);else if(d(this[e=_(e)]))return this[e](t);return this},i.startOf=function(e){var t,n;if(void 0===(e=_(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":t=this._d.valueOf(),t-=tn(t,6e4);break;case"second":t=this._d.valueOf(),t-=tn(t,1e3);break}return this._d.setTime(t),f.updateOffset(this,!0),this},i.subtract=Je,i.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},i.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},i.toDate=function(){return new Date(this.valueOf())},i.toISOString=function(e){if(!this.isValid())return null;var t=(e=!0!==e)?this.clone().utc():this;return t.year()<0||9999<t.year()?re(t,e?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):d(Date.prototype.toISOString)?e?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",re(t,"Z")):re(t,e?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},i.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e,t="moment",n="";return this.isLocal()||(t=0===this.utcOffset()?"moment.utc":"moment.parseZone",n="Z"),t="["+t+'("]',e=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",this.format(t+e+"-MM-DD[T]HH:mm:ss.SSS"+(n+'[")]'))},"undefined"!=typeof Symbol&&null!=Symbol.for&&(i[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),i.toJSON=function(){return this.isValid()?this.toISOString():null},i.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},i.unix=function(){return Math.floor(this.valueOf()/1e3)},i.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},i.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},i.eraName=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].name;if(t[n].until<=e&&e<=t[n].since)return t[n].name}return""},i.eraNarrow=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].narrow;if(t[n].until<=e&&e<=t[n].since)return t[n].narrow}return""},i.eraAbbr=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].abbr;if(t[n].until<=e&&e<=t[n].since)return t[n].abbr}return""},i.eraYear=function(){for(var e,t,n=this.localeData().eras(),s=0,i=n.length;s<i;++s)if(e=n[s].since<=n[s].until?1:-1,t=this.clone().startOf("day").valueOf(),n[s].since<=t&&t<=n[s].until||n[s].until<=t&&t<=n[s].since)return(this.year()-f(n[s].since).year())*e+n[s].offset;return this.year()},i.year=Ie,i.isLeapYear=function(){return he(this.year())},i.weekYear=function(e){return un.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},i.isoWeekYear=function(e){return un.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},i.quarter=i.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},i.month=Ge,i.daysInMonth=function(){return We(this.year(),this.month())},i.week=i.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},i.isoWeek=i.isoWeeks=function(e){var t=qe(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},i.weeksInYear=function(){var e=this.localeData()._week;return P(this.year(),e.dow,e.doy)},i.weeksInWeekYear=function(){var e=this.localeData()._week;return P(this.weekYear(),e.dow,e.doy)},i.isoWeeksInYear=function(){return P(this.year(),1,4)},i.isoWeeksInISOWeekYear=function(){return P(this.isoWeekYear(),1,4)},i.date=ke,i.day=i.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,s=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-s,"d")):s},i.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},i.isoWeekday=function(e){return this.isValid()?null!=e?(t=e,n=this.localeData(),n="string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t,this.day(this.day()%7?n:n-7)):this.day()||7:null!=e?this:NaN;var t,n},i.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},i.hour=i.hours=k,i.minute=i.minutes=_e,i.second=i.seconds=ve,i.millisecond=i.milliseconds=ye,i.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Et(this);if("string"==typeof e){if(null===(e=Vt(Ye,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Et(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?qt(this,C(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,f.updateOffset(this,!0),this._changeInProgress=null)),this},i.utc=function(e){return this.utcOffset(0,e)},i.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Et(this),"m")),this},i.parseZone=function(){var e;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(e=Vt(Se,this._i))?this.utcOffset(e):this.utcOffset(0,!0)),this},i.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?W(e).utcOffset():0,(this.utcOffset()-e)%60==0)},i.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},i.isLocal=function(){return!!this.isValid()&&!this._isUTC},i.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},i.isUtc=At,i.isUTC=At,i.zoneAbbr=function(){return this._isUTC?"UTC":""},i.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},i.dates=e("dates accessor is deprecated. Use date instead.",ke),i.months=e("months accessor is deprecated. Use month instead",Ge),i.years=e("years accessor is deprecated. Use year instead",Ie),i.zone=e("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?(this.utcOffset(e="string"!=typeof e?-e:e,t),this):-this.utcOffset()}),i.isDSTShifted=e("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!o(this._isDSTShifted))return this._isDSTShifted;var e,t={};return $(t,this),(t=Nt(t))._a?(e=(t._isUTC?l:W)(t._a),this._isDSTShifted=this.isValid()&&0<function(e,t,n){for(var s=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),r=0,a=0;a<s;a++)(n&&e[a]!==t[a]||!n&&g(e[a])!==g(t[a]))&&r++;return r+i}(t._a,e.toArray())):this._isDSTShifted=!1,this._isDSTShifted});w=K.prototype;function cn(e,t,n,s){var i=mt(),s=l().set(s,t);return i[n](s,e)}function fn(e,t,n){if(u(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");for(var s=[],i=0;i<12;i++)s[i]=cn(e,i,n,"month");return s}function mn(e,t,n,s){t=("boolean"==typeof e?u(t)&&(n=t,t=void 0):(t=e,e=!1,u(n=t)&&(n=t,t=void 0)),t||"");var i,r=mt(),a=e?r._week.dow:0,o=[];if(null!=n)return cn(t,(n+a)%7,s,"day");for(i=0;i<7;i++)o[i]=cn(t,(i+a)%7,s,"day");return o}w.calendar=function(e,t,n){return d(e=this._calendar[e]||this._calendar.sameElse)?e.call(t,n):e},w.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(te).map(function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e}).join(""),this._longDateFormat[e])},w.invalidDate=function(){return this._invalidDate},w.ordinal=function(e){return this._ordinal.replace("%d",e)},w.preparse=dn,w.postformat=dn,w.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return d(i)?i(e,t,n,s):i.replace(/%d/i,e)},w.pastFuture=function(e,t){return d(e=this._relativeTime[0<e?"future":"past"])?e(t):e.replace(/%s/i,t)},w.set=function(e){var t,n;for(n in e)c(e,n)&&(d(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},w.eras=function(e,t){for(var n,s=this._eras||mt("en")._eras,i=0,r=s.length;i<r;++i){switch(typeof s[i].since){case"string":n=f(s[i].since).startOf("day"),s[i].since=n.valueOf();break}switch(typeof s[i].until){case"undefined":s[i].until=1/0;break;case"string":n=f(s[i].until).startOf("day").valueOf(),s[i].until=n.valueOf();break}}return s},w.erasParse=function(e,t,n){var s,i,r,a,o,u=this.eras();for(e=e.toUpperCase(),s=0,i=u.length;s<i;++s)if(r=u[s].name.toUpperCase(),a=u[s].abbr.toUpperCase(),o=u[s].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(a===e)return u[s];break;case"NNNN":if(r===e)return u[s];break;case"NNNNN":if(o===e)return u[s];break}else if(0<=[r,a,o].indexOf(e))return u[s]},w.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?f(e.since).year():f(e.since).year()+(t-e.offset)*n},w.erasAbbrRegex=function(e){return c(this,"_erasAbbrRegex")||an.call(this),e?this._erasAbbrRegex:this._erasRegex},w.erasNameRegex=function(e){return c(this,"_erasNameRegex")||an.call(this),e?this._erasNameRegex:this._erasRegex},w.erasNarrowRegex=function(e){return c(this,"_erasNarrowRegex")||an.call(this),e?this._erasNarrowRegex:this._erasRegex},w.months=function(e,t){return e?(a(this._months)?this._months:this._months[(this._months.isFormat||He).test(t)?"format":"standalone"])[e.month()]:a(this._months)?this._months:this._months.standalone},w.monthsShort=function(e,t){return e?(a(this._monthsShort)?this._monthsShort:this._monthsShort[He.test(t)?"format":"standalone"])[e.month()]:a(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},w.monthsParse=function(e,t,n){var s,i;if(this._monthsParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=l([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=S.call(this._shortMonthsParse,e))?i:null:-1!==(i=S.call(this._longMonthsParse,e))?i:null:"MMM"===t?-1!==(i=S.call(this._shortMonthsParse,e))||-1!==(i=S.call(this._longMonthsParse,e))?i:null:-1!==(i=S.call(this._longMonthsParse,e))||-1!==(i=S.call(this._shortMonthsParse,e))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=l([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(i="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(i.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},w.monthsRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||Ee.call(this),e?this._monthsStrictRegex:this._monthsRegex):(c(this,"_monthsRegex")||(this._monthsRegex=Le),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},w.monthsShortRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||Ee.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(c(this,"_monthsShortRegex")||(this._monthsShortRegex=Fe),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},w.week=function(e){return qe(e,this._week.dow,this._week.doy).week},w.firstDayOfYear=function(){return this._week.doy},w.firstDayOfWeek=function(){return this._week.dow},w.weekdays=function(e,t){return t=a(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"],!0===e?Be(t,this._week.dow):e?t[e.day()]:t},w.weekdaysMin=function(e){return!0===e?Be(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},w.weekdaysShort=function(e){return!0===e?Be(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},w.weekdaysParse=function(e,t,n){var s,i;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=l([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=S.call(this._weekdaysParse,e))?i:null:"ddd"===t?-1!==(i=S.call(this._shortWeekdaysParse,e))?i:null:-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:"dddd"===t?-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._shortWeekdaysParse,e))||-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:"ddd"===t?-1!==(i=S.call(this._shortWeekdaysParse,e))||-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:-1!==(i=S.call(this._minWeekdaysParse,e))||-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._shortWeekdaysParse,e))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=l([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[s]||(i="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(i.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},w.weekdaysRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(c(this,"_weekdaysRegex")||(this._weekdaysRegex=Ke),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},w.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(c(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=et),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},w.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(c(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=tt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},w.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},w.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ct("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===g(e%100/10)?"th":1==t?"st":2==t?"nd":3==t?"rd":"th")}}),f.lang=e("moment.lang is deprecated. Use moment.locale instead.",ct),f.langData=e("moment.langData is deprecated. Use moment.localeData instead.",mt);var _n=Math.abs;function yn(e,t,n,s){t=C(t,n);return e._milliseconds+=s*t._milliseconds,e._days+=s*t._days,e._months+=s*t._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function wn(e){return 4800*e/146097}function pn(e){return 146097*e/4800}function kn(e){return function(){return this.as(e)}}pe=kn("ms"),me=kn("s"),Ce=kn("m"),we=kn("h"),ge=kn("d"),Je=kn("w"),k=kn("M"),_e=kn("Q"),ve=kn("y");function vn(e){return function(){return this.isValid()?this._data[e]:NaN}}var ye=vn("milliseconds"),ke=vn("seconds"),Ie=vn("minutes"),w=vn("hours"),Mn=vn("days"),Dn=vn("months"),Sn=vn("years");var Yn=Math.round,On={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function bn(e,t,n,s){var i=C(e).abs(),r=Yn(i.as("s")),a=Yn(i.as("m")),o=Yn(i.as("h")),u=Yn(i.as("d")),l=Yn(i.as("M")),h=Yn(i.as("w")),i=Yn(i.as("y")),r=(r<=n.ss?["s",r]:r<n.s&&["ss",r])||a<=1&&["m"]||a<n.m&&["mm",a]||o<=1&&["h"]||o<n.h&&["hh",o]||u<=1&&["d"]||u<n.d&&["dd",u];return(r=(r=null!=n.w?r||h<=1&&["w"]||h<n.w&&["ww",h]:r)||l<=1&&["M"]||l<n.M&&["MM",l]||i<=1&&["y"]||["yy",i])[2]=t,r[3]=0<+e,r[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,r)}var xn=Math.abs;function Tn(e){return(0<e)-(e<0)||+e}function Nn(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n,s,i,r,a,o=xn(this._milliseconds)/1e3,u=xn(this._days),l=xn(this._months),h=this.asSeconds();return h?(e=y(o/60),t=y(e/60),o%=60,e%=60,n=y(l/12),l%=12,s=o?o.toFixed(3).replace(/\.?0+$/,""):"",i=Tn(this._months)!==Tn(h)?"-":"",r=Tn(this._days)!==Tn(h)?"-":"",a=Tn(this._milliseconds)!==Tn(h)?"-":"",(h<0?"-":"")+"P"+(n?i+n+"Y":"")+(l?i+l+"M":"")+(u?r+u+"D":"")+(t||e||o?"T":"")+(t?a+t+"H":"")+(e?a+e+"M":"")+(o?a+s+"S":"")):"P0D"}var U=Ct.prototype;return U.isValid=function(){return this._isValid},U.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},U.add=function(e,t){return yn(this,e,t,1)},U.subtract=function(e,t){return yn(this,e,t,-1)},U.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=_(e))||"quarter"===e||"year"===e)switch(t=this._days+s/864e5,n=this._months+wn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(pn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},U.asMilliseconds=pe,U.asSeconds=me,U.asMinutes=Ce,U.asHours=we,U.asDays=ge,U.asWeeks=Je,U.asMonths=k,U.asQuarters=_e,U.asYears=ve,U.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*g(this._months/12):NaN},U._bubble=function(){var e=this._milliseconds,t=this._days,n=this._months,s=this._data;return 0<=e&&0<=t&&0<=n||e<=0&&t<=0&&n<=0||(e+=864e5*gn(pn(n)+t),n=t=0),s.milliseconds=e%1e3,e=y(e/1e3),s.seconds=e%60,e=y(e/60),s.minutes=e%60,e=y(e/60),s.hours=e%24,t+=y(e/24),n+=e=y(wn(t)),t-=gn(pn(e)),e=y(n/12),n%=12,s.days=t,s.months=n,s.years=e,this},U.clone=function(){return C(this)},U.get=function(e){return e=_(e),this.isValid()?this[e+"s"]():NaN},U.milliseconds=ye,U.seconds=ke,U.minutes=Ie,U.hours=w,U.days=Mn,U.weeks=function(){return y(this.days()/7)},U.months=Dn,U.years=Sn,U.humanize=function(e,t){if(!this.isValid())return this.localeData().invalidDate();var n=!1,s=On;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(n=e),"object"==typeof t&&(s=Object.assign({},On,t),null!=t.s&&null==t.ss&&(s.ss=t.s-1)),e=this.localeData(),t=bn(this,!n,s,e),n&&(t=e.pastFuture(+this,t)),e.postformat(t)},U.toISOString=Nn,U.toString=Nn,U.toJSON=Nn,U.locale=Xt,U.localeData=Kt,U.toIsoString=e("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Nn),U.lang=Xe,s("X",0,0,"unix"),s("x",0,0,"valueOf"),v("x",De),v("X",/[+-]?\d+(\.\d{1,3})?/),D("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e))}),D("x",function(e,t,n){n._d=new Date(g(e))}),f.version="2.29.4",H=W,f.fn=i,f.min=function(){return Rt("isBefore",[].slice.call(arguments,0))},f.max=function(){return Rt("isAfter",[].slice.call(arguments,0))},f.now=function(){return Date.now?Date.now():+new Date},f.utc=l,f.unix=function(e){return W(1e3*e)},f.months=function(e,t){return fn(e,t,"months")},f.isDate=V,f.locale=ct,f.invalid=I,f.duration=C,f.isMoment=h,f.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},f.parseZone=function(){return W.apply(null,arguments).parseZone()},f.localeData=mt,f.isDuration=Ut,f.monthsShort=function(e,t){return fn(e,t,"monthsShort")},f.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},f.defineLocale=ft,f.updateLocale=function(e,t){var n,s;return null!=t?(s=ot,null!=R[e]&&null!=R[e].parentLocale?R[e].set(X(R[e]._config,t)):(t=X(s=null!=(n=dt(e))?n._config:s,t),null==n&&(t.abbr=e),(s=new K(t)).parentLocale=R[e],R[e]=s),ct(e)):null!=R[e]&&(null!=R[e].parentLocale?(R[e]=R[e].parentLocale,e===ct()&&ct(e)):null!=R[e]&&delete R[e]),R[e]},f.locales=function(){return ee(R)},f.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},f.normalizeUnits=_,f.relativeTimeRounding=function(e){return void 0===e?Yn:"function"==typeof e&&(Yn=e,!0)},f.relativeTimeThreshold=function(e,t){return void 0!==On[e]&&(void 0===t?On[e]:(On[e]=t,"s"===e&&(On.ss=t-1),!0))},f.calendarFormat=function(e,t){return(e=e.diff(t,"days",!0))<-6?"sameElse":e<-1?"lastWeek":e<0?"lastDay":e<1?"sameDay":e<2?"nextDay":e<7?"nextWeek":"sameElse"},f.prototype=i,f.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},f});
//# sourceMappingURL=moment.min.js.map;
/* ========================================================================
 * Bootstrap: affix.js v3.2.0
 * http://getbootstrap.com/javascript/#affix
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // AFFIX CLASS DEFINITION
  // ======================

  var Affix = function (element, options) {
    this.options = $.extend({}, Affix.DEFAULTS, options)

    this.$target = $(this.options.target)
      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))

    this.$element     = $(element)
    this.affixed      =
    this.unpin        =
    this.pinnedOffset = null

    this.checkPosition()
  }

  Affix.VERSION  = '3.2.0'

  Affix.RESET    = 'affix affix-top affix-bottom'

  Affix.DEFAULTS = {
    offset: 0,
    target: window
  }

  Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
    var scrollTop    = this.$target.scrollTop()
    var position     = this.$element.offset()
    var targetHeight = this.$target.height()

    if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false

    if (this.affixed == 'bottom') {
      if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
      return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
    }

    var initializing   = this.affixed == null
    var colliderTop    = initializing ? scrollTop : position.top
    var colliderHeight = initializing ? targetHeight : height

    if (offsetTop != null && colliderTop <= offsetTop) return 'top'
    if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'

    return false
  }

  Affix.prototype.getPinnedOffset = function () {
    if (this.pinnedOffset) return this.pinnedOffset
    this.$element.removeClass(Affix.RESET).addClass('affix')
    var scrollTop = this.$target.scrollTop()
    var position  = this.$element.offset()
    return (this.pinnedOffset = position.top - scrollTop)
  }

  Affix.prototype.checkPositionWithEventLoop = function () {
    setTimeout($.proxy(this.checkPosition, this), 1)
  }

  Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var height       = this.$element.height()
    var offset       = this.options.offset
    var offsetTop    = offset.top
    var offsetBottom = offset.bottom
    var scrollHeight = $('body').height()

    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)

    var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)

    if (this.affixed != affix) {
      if (this.unpin != null) this.$element.css('top', '')

      var affixType = 'affix' + (affix ? '-' + affix : '')
      var e         = $.Event(affixType + '.bs.affix')

      this.$element.trigger(e)

      if (e.isDefaultPrevented()) return

      this.affixed = affix
      this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null

      this.$element
        .removeClass(Affix.RESET)
        .addClass(affixType)
        .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
    }

    if (affix == 'bottom') {
      this.$element.offset({
        top: scrollHeight - height - offsetBottom
      })
    }
  }


  // AFFIX PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.affix')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.affix

  $.fn.affix             = Plugin
  $.fn.affix.Constructor = Affix


  // AFFIX NO CONFLICT
  // =================

  $.fn.affix.noConflict = function () {
    $.fn.affix = old
    return this
  }


  // AFFIX DATA-API
  // ==============

  $(window).on('load', function () {
    $('[data-spy="affix"]').each(function () {
      var $spy = $(this)
      var data = $spy.data()

      data.offset = data.offset || {}

      if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
      if (data.offsetTop    != null) data.offset.top    = data.offsetTop

      Plugin.call($spy, data)
    })
  })

}(jQuery);
;
/* ========================================================================
 * Bootstrap: alert.js v3.2.0
 * http://getbootstrap.com/javascript/#alerts
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // ALERT CLASS DEFINITION
  // ======================

  var dismiss = '[data-dismiss="alert"]'
  var Alert   = function (el) {
    $(el).on('click', dismiss, this.close)
  }

  Alert.VERSION = '3.2.0'

  Alert.TRANSITION_DURATION = 150

  Alert.prototype.close = function (e) {
    var $this    = $(this)
    var selector = $this.attr('data-target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    var $parent = $(selector)

    if (e) e.preventDefault()

    if (!$parent.length) {
      $parent = $this.closest('.alert')
    }

    $parent.trigger(e = $.Event('close.bs.alert'))

    if (e.isDefaultPrevented()) return

    $parent.removeClass('in')

    function removeElement() {
      // detach from parent, fire event then clean up data
      $parent.detach().trigger('closed.bs.alert').remove()
    }

    $.support.transition && $parent.hasClass('fade') ?
      $parent
        .one('bsTransitionEnd', removeElement)
        .emulateTransitionEnd(Alert.TRANSITION_DURATION) :
      removeElement()
  }


  // ALERT PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.alert')

      if (!data) $this.data('bs.alert', (data = new Alert(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  var old = $.fn.alert

  $.fn.alert             = Plugin
  $.fn.alert.Constructor = Alert


  // ALERT NO CONFLICT
  // =================

  $.fn.alert.noConflict = function () {
    $.fn.alert = old
    return this
  }


  // ALERT DATA-API
  // ==============

  $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)

}(jQuery);
;
/* ========================================================================
 * Bootstrap: button.js v3.2.0
 * http://getbootstrap.com/javascript/#buttons
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // BUTTON PUBLIC CLASS DEFINITION
  // ==============================

  var Button = function (element, options) {
    this.$element  = $(element)
    this.options   = $.extend({}, Button.DEFAULTS, options)
    this.isLoading = false
  }

  Button.VERSION  = '3.2.0'

  Button.DEFAULTS = {
    loadingText: 'loading...'
  }

  Button.prototype.setState = function (state) {
    var d    = 'disabled'
    var $el  = this.$element
    var val  = $el.is('input') ? 'val' : 'html'
    var data = $el.data()

    state = state + 'Text'

    if (data.resetText == null) $el.data('resetText', $el[val]())

    $el[val](data[state] == null ? this.options[state] : data[state])

    // push to event loop to allow forms to submit
    setTimeout($.proxy(function () {
      if (state == 'loadingText') {
        this.isLoading = true
        $el.addClass(d).attr(d, d)
      } else if (this.isLoading) {
        this.isLoading = false
        $el.removeClass(d).removeAttr(d)
      }
    }, this), 0)
  }

  Button.prototype.toggle = function () {
    var changed = true
    var $parent = this.$element.closest('[data-toggle="buttons"]')

    if ($parent.length) {
      var $input = this.$element.find('input')
      if ($input.prop('type') == 'radio') {
        if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
        else $parent.find('.active').removeClass('active')
      }
      if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
    }

    if (changed) this.$element.toggleClass('active')
  }


  // BUTTON PLUGIN DEFINITION
  // ========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.button')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.button', (data = new Button(this, options)))

      if (option == 'toggle') data.toggle()
      else if (option) data.setState(option)
    })
  }

  var old = $.fn.button

  $.fn.button             = Plugin
  $.fn.button.Constructor = Button


  // BUTTON NO CONFLICT
  // ==================

  $.fn.button.noConflict = function () {
    $.fn.button = old
    return this
  }


  // BUTTON DATA-API
  // ===============

  $(document)
    .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
      var $btn = $(e.target)
      if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
      Plugin.call($btn, 'toggle')
      e.preventDefault()
    })
    .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
      $(e.target).closest('.btn').toggleClass('focus', e.type == 'focus')
    })

}(jQuery);
;
/* ========================================================================
 * Bootstrap: carousel.js v3.2.0
 * http://getbootstrap.com/javascript/#carousel
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // CAROUSEL CLASS DEFINITION
  // =========================

  var Carousel = function (element, options) {
    this.$element    = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this))
    this.$indicators = this.$element.find('.carousel-indicators')
    this.options     = options
    this.paused      =
    this.sliding     =
    this.interval    =
    this.$active     =
    this.$items      = null

    this.options.pause == 'hover' && this.$element
      .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
      .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
  }

  Carousel.VERSION  = '3.2.0'

  Carousel.TRANSITION_DURATION = 600

  Carousel.DEFAULTS = {
    interval: 5000,
    pause: 'hover',
    wrap: true
  }

  Carousel.prototype.keydown = function (e) {
    switch (e.which) {
      case 37: this.prev(); break
      case 39: this.next(); break
      default: return
    }

    e.preventDefault()
  }

  Carousel.prototype.cycle = function (e) {
    e || (this.paused = false)

    this.interval && clearInterval(this.interval)

    this.options.interval
      && !this.paused
      && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))

    return this
  }

  Carousel.prototype.getItemIndex = function (item) {
    this.$items = item.parent().children('.item')
    return this.$items.index(item || this.$active)
  }

  Carousel.prototype.getItemForDirection = function (direction, active) {
    var delta = direction == 'prev' ? -1 : 1
    var activeIndex = this.getItemIndex(active)
    var itemIndex = (activeIndex + delta) % this.$items.length
    return this.$items.eq(itemIndex)
  }

  Carousel.prototype.to = function (pos) {
    var that        = this
    var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))

    if (pos > (this.$items.length - 1) || pos < 0) return

    if (this.sliding)       return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
    if (activeIndex == pos) return this.pause().cycle()

    return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
  }

  Carousel.prototype.pause = function (e) {
    e || (this.paused = true)

    if (this.$element.find('.next, .prev').length && $.support.transition) {
      this.$element.trigger($.support.transition.end)
      this.cycle(true)
    }

    this.interval = clearInterval(this.interval)

    return this
  }

  Carousel.prototype.next = function () {
    if (this.sliding) return
    return this.slide('next')
  }

  Carousel.prototype.prev = function () {
    if (this.sliding) return
    return this.slide('prev')
  }

  Carousel.prototype.slide = function (type, next) {
    var $active   = this.$element.find('.item.active')
    var $next     = next || this.getItemForDirection(type, $active)
    var isCycling = this.interval
    var direction = type == 'next' ? 'left' : 'right'
    var fallback  = type == 'next' ? 'first' : 'last'
    var that      = this

    if (!$next.length) {
      if (!this.options.wrap) return
      $next = this.$element.find('.item')[fallback]()
    }

    if ($next.hasClass('active')) return (this.sliding = false)

    var relatedTarget = $next[0]
    var slideEvent = $.Event('slide.bs.carousel', {
      relatedTarget: relatedTarget,
      direction: direction
    })
    this.$element.trigger(slideEvent)
    if (slideEvent.isDefaultPrevented()) return

    this.sliding = true

    isCycling && this.pause()

    if (this.$indicators.length) {
      this.$indicators.find('.active').removeClass('active')
      var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
      $nextIndicator && $nextIndicator.addClass('active')
    }

    var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
    if ($.support.transition && this.$element.hasClass('slide')) {
      $next.addClass(type)
      $next[0].offsetWidth // force reflow
      $active.addClass(direction)
      $next.addClass(direction)
      $active
        .one('bsTransitionEnd', function () {
          $next.removeClass([type, direction].join(' ')).addClass('active')
          $active.removeClass(['active', direction].join(' '))
          that.sliding = false
          setTimeout(function () {
            that.$element.trigger(slidEvent)
          }, 0)
        })
        .emulateTransitionEnd(Carousel.TRANSITION_DURATION)
    } else {
      $active.removeClass('active')
      $next.addClass('active')
      this.sliding = false
      this.$element.trigger(slidEvent)
    }

    isCycling && this.cycle()

    return this
  }


  // CAROUSEL PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.carousel')
      var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
      var action  = typeof option == 'string' ? option : options.slide

      if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
      if (typeof option == 'number') data.to(option)
      else if (action) data[action]()
      else if (options.interval) data.pause().cycle()
    })
  }

  var old = $.fn.carousel

  $.fn.carousel             = Plugin
  $.fn.carousel.Constructor = Carousel


  // CAROUSEL NO CONFLICT
  // ====================

  $.fn.carousel.noConflict = function () {
    $.fn.carousel = old
    return this
  }


  // CAROUSEL DATA-API
  // =================

  $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
    var href
    var $this   = $(this)
    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
    if (!$target.hasClass('carousel')) return
    var options = $.extend({}, $target.data(), $this.data())
    var slideIndex = $this.attr('data-slide-to')
    if (slideIndex) options.interval = false

    Plugin.call($target, options)

    if (slideIndex) {
      $target.data('bs.carousel').to(slideIndex)
    }

    e.preventDefault()
  })

  $(window).on('load', function () {
    $('[data-ride="carousel"]').each(function () {
      var $carousel = $(this)
      Plugin.call($carousel, $carousel.data())
    })
  })

}(jQuery);
;
/* ========================================================================
 * Bootstrap: collapse.js v3.2.0
 * http://getbootstrap.com/javascript/#collapse
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // COLLAPSE PUBLIC CLASS DEFINITION
  // ================================

  var Collapse = function (element, options) {
    this.$element      = $(element)
    this.options       = $.extend({}, Collapse.DEFAULTS, options)
    this.transitioning = null

    if (this.options.parent) this.$parent = $(this.options.parent)
    if (this.options.toggle) this.toggle()
  }

  Collapse.VERSION  = '3.2.0'

  Collapse.TRANSITION_DURATION = 350

  Collapse.DEFAULTS = {
    toggle: true
  }

  Collapse.prototype.dimension = function () {
    var hasWidth = this.$element.hasClass('width')
    return hasWidth ? 'width' : 'height'
  }

  Collapse.prototype.show = function () {
    if (this.transitioning || this.$element.hasClass('in')) return

    var startEvent = $.Event('show.bs.collapse')
    this.$element.trigger(startEvent)
    if (startEvent.isDefaultPrevented()) return

    var actives = this.$parent && this.$parent.find('> .panel > .in')

    if (actives && actives.length) {
      var hasData = actives.data('bs.collapse')
      if (hasData && hasData.transitioning) return
      Plugin.call(actives, 'hide')
      hasData || actives.data('bs.collapse', null)
    }

    var dimension = this.dimension()

    this.$element
      .removeClass('collapse')
      .addClass('collapsing')[dimension](0)
      .attr('aria-expanded', true)

    this.transitioning = 1

    var complete = function () {
      this.$element
        .removeClass('collapsing')
        .addClass('collapse in')[dimension]('')
      this.transitioning = 0
      this.$element
        .trigger('shown.bs.collapse')
    }

    if (!$.support.transition) return complete.call(this)

    var scrollSize = $.camelCase(['scroll', dimension].join('-'))

    this.$element
      .one('bsTransitionEnd', $.proxy(complete, this))
      .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
  }

  Collapse.prototype.hide = function () {
    if (this.transitioning || !this.$element.hasClass('in')) return

    var startEvent = $.Event('hide.bs.collapse')
    this.$element.trigger(startEvent)
    if (startEvent.isDefaultPrevented()) return

    var dimension = this.dimension()

    this.$element[dimension](this.$element[dimension]())[0].offsetHeight

    this.$element
      .addClass('collapsing')
      .removeClass('collapse in')
      .attr('aria-expanded', false)

    this.transitioning = 1

    var complete = function () {
      this.transitioning = 0
      this.$element
        .removeClass('collapsing')
        .addClass('collapse')
        .trigger('hidden.bs.collapse')
    }

    if (!$.support.transition) return complete.call(this)

    this.$element
      [dimension](0)
      .one('bsTransitionEnd', $.proxy(complete, this))
      .emulateTransitionEnd(Collapse.TRANSITION_DURATION)
  }

  Collapse.prototype.toggle = function () {
    this[this.$element.hasClass('in') ? 'hide' : 'show']()
  }


  // COLLAPSE PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.collapse')
      var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)

      if (!data && options.toggle && option == 'show') options.toggle = false
      if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.collapse

  $.fn.collapse             = Plugin
  $.fn.collapse.Constructor = Collapse


  // COLLAPSE NO CONFLICT
  // ====================

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }


  // COLLAPSE DATA-API
  // =================

  $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
    var href
    var $this   = $(this)
    var target  = $this.attr('data-target')
        || e.preventDefault()
        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
    var $target = $(target)
    var data    = $target.data('bs.collapse')
    var option  = data ? 'toggle' : $this.data()
    var parent  = $this.attr('data-parent')
    var $parent = parent && $(parent)

    if (!data || !data.transitioning) {
      if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed').attr('aria-expanded', false)
      var isCollapsed = $target.hasClass('in')
      $this.toggleClass('collapsed', isCollapsed).attr('aria-expanded', !isCollapsed)
    }

    Plugin.call($target, option)
  })

}(jQuery);
;
/* ========================================================================
 * Bootstrap: dropdown.js v3.2.0
 * http://getbootstrap.com/javascript/#dropdowns
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // DROPDOWN CLASS DEFINITION
  // =========================

  var backdrop = '.dropdown-backdrop'
  var toggle   = '[data-toggle="dropdown"]'
  var Dropdown = function (element) {
    $(element).on('click.bs.dropdown', this.toggle)
  }

  Dropdown.VERSION = '3.2.0'

  Dropdown.prototype.toggle = function (e) {
    var $this = $(this)

    if ($this.is('.disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('open')

    clearMenus()

    if (!isActive) {
      if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
        // if mobile we use a backdrop because click events don't delegate
        $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
      }

      var relatedTarget = { relatedTarget: this }
      $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))

      if (e.isDefaultPrevented()) return

      $this
        .trigger('focus')
        .attr('aria-expanded', 'true')

      $parent
        .toggleClass('open')
        .trigger('shown.bs.dropdown', relatedTarget)
    }

    return false
  }

  Dropdown.prototype.keydown = function (e) {
    if (!/(38|40|27)/.test(e.keyCode)) return

    var $this = $(this)

    e.preventDefault()
    e.stopPropagation()

    if ($this.is('.disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('open')

    if (!isActive || (isActive && e.keyCode == 27)) {
      if (e.which == 27) $parent.find(toggle).trigger('focus')
      return $this.trigger('click')
    }

    var desc = ' li:not(.divider):visible a'
    var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)

    if (!$items.length) return

    var index = $items.index($items.filter(':focus'))

    if (e.keyCode == 38 && index > 0)                 index--                        // up
    if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
    if (!~index)                                      index = 0

    $items.eq(index).trigger('focus')
  }

  function clearMenus(e) {
    if (e && e.which === 3) return
    $(backdrop).remove()
    $(toggle).each(function () {
      var $this         = $(this)
      var $parent       = getParent($this)
      var relatedTarget = { relatedTarget: this }

      if (!$parent.hasClass('open')) return

      $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))

      if (e.isDefaultPrevented()) return

      $this.attr('aria-expanded', 'false')
      $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
    })
  }

  function getParent($this) {
    var selector = $this.attr('data-target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    var $parent = selector && $(selector)

    return $parent && $parent.length ? $parent : $this.parent()
  }


  // DROPDOWN PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.dropdown')

      if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  var old = $.fn.dropdown

  $.fn.dropdown             = Plugin
  $.fn.dropdown.Constructor = Dropdown


  // DROPDOWN NO CONFLICT
  // ====================

  $.fn.dropdown.noConflict = function () {
    $.fn.dropdown = old
    return this
  }


  // APPLY TO STANDARD DROPDOWN ELEMENTS
  // ===================================

  $(document)
    .on('click.bs.dropdown.data-api', clearMenus)
    .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
    .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
    .on('keydown.bs.dropdown.data-api', toggle + ', [role="menu"], [role="listbox"]', Dropdown.prototype.keydown)

}(jQuery);
;
/* ========================================================================
 * Bootstrap: modal.js v3.2.0
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // MODAL CLASS DEFINITION
  // ======================

  var Modal = function (element, options) {
    this.options        = options
    this.$body          = $(document.body)
    this.$element       = $(element)
    this.$backdrop      =
    this.isShown        = null
    this.scrollbarWidth = 0

    if (this.options.remote) {
      this.$element
        .find('.modal-content')
        .load(this.options.remote, $.proxy(function () {
          this.$element.trigger('loaded.bs.modal')
        }, this))
    }
  }

  Modal.VERSION  = '3.2.0'

  Modal.TRANSITION_DURATION = 300
  Modal.BACKDROP_TRANSITION_DURATION = 150

  Modal.DEFAULTS = {
    backdrop: true,
    keyboard: true,
    show: true
  }

  Modal.prototype.toggle = function (_relatedTarget) {
    return this.isShown ? this.hide() : this.show(_relatedTarget)
  }

  Modal.prototype.show = function (_relatedTarget) {
    var that = this
    var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })

    this.$element.trigger(e)

    if (this.isShown || e.isDefaultPrevented()) return

    this.isShown = true

    this.checkScrollbar()
    this.$body.addClass('modal-open')

    this.setScrollbar()
    this.escape()

    this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))

    this.backdrop(function () {
      var transition = $.support.transition && that.$element.hasClass('fade')

      if (!that.$element.parent().length) {
        that.$element.appendTo(that.$body) // don't move modals dom position
      }

      that.$element
        .show()
        .scrollTop(0)

      if (transition) {
        that.$element[0].offsetWidth // force reflow
      }

      that.$element
        .addClass('in')
        .attr('aria-hidden', false)

      that.enforceFocus()

      var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })

      transition ?
        that.$element.find('.modal-dialog') // wait for modal to slide in
          .one('bsTransitionEnd', function () {
            that.$element.trigger('focus').trigger(e)
          })
          .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
        that.$element.trigger('focus').trigger(e)
    })
  }

  Modal.prototype.hide = function (e) {
    if (e) e.preventDefault()

    e = $.Event('hide.bs.modal')

    this.$element.trigger(e)

    if (!this.isShown || e.isDefaultPrevented()) return

    this.isShown = false

    this.$body.removeClass('modal-open')

    this.resetScrollbar()
    this.escape()

    $(document).off('focusin.bs.modal')

    this.$element
      .removeClass('in')
      .attr('aria-hidden', true)
      .off('click.dismiss.bs.modal')

    $.support.transition && this.$element.hasClass('fade') ?
      this.$element
        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
        .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
      this.hideModal()
  }

  Modal.prototype.enforceFocus = function () {
    $(document)
      .off('focusin.bs.modal') // guard against infinite focus loop
      .on('focusin.bs.modal', $.proxy(function (e) {
        if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
          this.$element.trigger('focus')
        }
      }, this))
  }

  Modal.prototype.escape = function () {
    if (this.isShown && this.options.keyboard) {
      this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
        e.which == 27 && this.hide()
      }, this))
    } else if (!this.isShown) {
      this.$element.off('keydown.dismiss.bs.modal')
    }
  }

  Modal.prototype.hideModal = function () {
    var that = this
    this.$element.hide()
    this.backdrop(function () {
      that.$element.trigger('hidden.bs.modal')
    })
  }

  Modal.prototype.removeBackdrop = function () {
    this.$backdrop && this.$backdrop.remove()
    this.$backdrop = null
  }

  Modal.prototype.backdrop = function (callback) {
    var that = this
    var animate = this.$element.hasClass('fade') ? 'fade' : ''

    if (this.isShown && this.options.backdrop) {
      var doAnimate = $.support.transition && animate

      this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
        .appendTo(this.$body)

      this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
        if (e.target !== e.currentTarget) return
        this.options.backdrop == 'static'
          ? this.$element[0].focus.call(this.$element[0])
          : this.hide.call(this)
      }, this))

      if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

      this.$backdrop.addClass('in')

      if (!callback) return

      doAnimate ?
        this.$backdrop
          .one('bsTransitionEnd', callback)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callback()

    } else if (!this.isShown && this.$backdrop) {
      this.$backdrop.removeClass('in')

      var callbackRemove = function () {
        that.removeBackdrop()
        callback && callback()
      }
      $.support.transition && this.$element.hasClass('fade') ?
        this.$backdrop
          .one('bsTransitionEnd', callbackRemove)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callbackRemove()

    } else if (callback) {
      callback()
    }
  }

  Modal.prototype.checkScrollbar = function () {
    this.scrollbarWidth = this.measureScrollbar()
  }

  Modal.prototype.setScrollbar = function () {
    var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
    if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
  }

  Modal.prototype.resetScrollbar = function () {
    this.$body.css('padding-right', '')
  }

  Modal.prototype.measureScrollbar = function () { // thx walsh
    if (document.body.clientWidth >= window.innerWidth) return 0
    var scrollDiv = document.createElement('div')
    scrollDiv.className = 'modal-scrollbar-measure'
    this.$body.append(scrollDiv)
    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
    this.$body[0].removeChild(scrollDiv)
    return scrollbarWidth
  }


  // MODAL PLUGIN DEFINITION
  // =======================

  function Plugin(option, _relatedTarget) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.modal')
      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

      if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
      if (typeof option == 'string') data[option](_relatedTarget)
      else if (options.show) data.show(_relatedTarget)
    })
  }

  var old = $.fn.modal

  $.fn.modal             = Plugin
  $.fn.modal.Constructor = Modal


  // MODAL NO CONFLICT
  // =================

  $.fn.modal.noConflict = function () {
    $.fn.modal = old
    return this
  }


  // MODAL DATA-API
  // ==============

  $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
    var $this   = $(this)
    var href    = $this.attr('href')
    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
    var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())

    if ($this.is('a')) e.preventDefault()

    $target.one('show.bs.modal', function (showEvent) {
      if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
      $target.one('hidden.bs.modal', function () {
        $this.is(':visible') && $this.trigger('focus')
      })
    })
    Plugin.call($target, option, this)
  })

}(jQuery);
;
/* ========================================================================
 * Bootstrap: tooltip.js v3.4.1
 * https://getbootstrap.com/docs/3.4/javascript/#tooltip
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ========================================================================
 * Copyright 2011-2019 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

+function ($) {
    'use strict';

    var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn']

    var uriAttrs = [
        'background',
        'cite',
        'href',
        'itemtype',
        'longdesc',
        'poster',
        'src',
        'xlink:href'
    ]

    var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i

    var DefaultWhitelist = {
        // Global attributes allowed on any supplied element below.
        '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],
        a: ['target', 'href', 'title', 'rel'],
        area: [],
        b: [],
        br: [],
        col: [],
        code: [],
        div: [],
        em: [],
        hr: [],
        h1: [],
        h2: [],
        h3: [],
        h4: [],
        h5: [],
        h6: [],
        i: [],
        img: ['src', 'alt', 'title', 'width', 'height'],
        li: [],
        ol: [],
        p: [],
        pre: [],
        s: [],
        small: [],
        span: [],
        sub: [],
        sup: [],
        strong: [],
        u: [],
        ul: []
    }

    /**
     * A pattern that recognizes a commonly useful subset of URLs that are safe.
     *
     * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
     */
    var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi

    /**
     * A pattern that matches safe data URLs. Only matches image, video and audio types.
     *
     * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
     */
    var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i

    function allowedAttribute(attr, allowedAttributeList) {
        var attrName = attr.nodeName.toLowerCase()

        if ($.inArray(attrName, allowedAttributeList) !== -1) {
            if ($.inArray(attrName, uriAttrs) !== -1) {
                return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
            }

            return true
        }

        var regExp = $(allowedAttributeList).filter(function (index, value) {
            return value instanceof RegExp
        })

        // Check if a regular expression validates the attribute.
        for (var i = 0, l = regExp.length; i < l; i++) {
            if (attrName.match(regExp[i])) {
                return true
            }
        }

        return false
    }

    function sanitizeHtml(unsafeHtml, whiteList, sanitizeFn) {
        if (unsafeHtml.length === 0) {
            return unsafeHtml
        }

        if (sanitizeFn && typeof sanitizeFn === 'function') {
            return sanitizeFn(unsafeHtml)
        }

        // IE 8 and below don't support createHTMLDocument
        if (!document.implementation || !document.implementation.createHTMLDocument) {
            return unsafeHtml
        }

        var createdDocument = document.implementation.createHTMLDocument('sanitization')
        createdDocument.body.innerHTML = unsafeHtml

        var whitelistKeys = $.map(whiteList, function (el, i) { return i })
        var elements = $(createdDocument.body).find('*')

        for (var i = 0, len = elements.length; i < len; i++) {
            var el = elements[i]
            var elName = el.nodeName.toLowerCase()

            if ($.inArray(elName, whitelistKeys) === -1) {
                el.parentNode.removeChild(el)

                continue
            }

            var attributeList = $.map(el.attributes, function (el) { return el })
            var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || [])

            for (var j = 0, len2 = attributeList.length; j < len2; j++) {
                if (!allowedAttribute(attributeList[j], whitelistedAttributes)) {
                    el.removeAttribute(attributeList[j].nodeName)
                }
            }
        }

        return createdDocument.body.innerHTML
    }

    // TOOLTIP PUBLIC CLASS DEFINITION
    // ===============================

    var Tooltip = function (element, options) {
        this.type = null
        this.options = null
        this.enabled = null
        this.timeout = null
        this.hoverState = null
        this.$element = null
        this.inState = null

        this.init('tooltip', element, options)
    }

    Tooltip.VERSION = '3.4.1'

    Tooltip.TRANSITION_DURATION = 150

    Tooltip.DEFAULTS = {
        animation: true,
        placement: 'top',
        selector: false,
        template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
        trigger: 'hover focus',
        title: '',
        delay: 0,
        html: false,
        container: false,
        viewport: {
            selector: 'body',
            padding: 0
        },
        sanitize: true,
        sanitizeFn: null,
        whiteList: DefaultWhitelist
    }

    Tooltip.prototype.init = function (type, element, options) {
        this.enabled = true
        this.type = type
        this.$element = $(element)
        this.options = this.getOptions(options)
        this.$viewport = this.options.viewport && $(document).find($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
        this.inState = { click: false, hover: false, focus: false }

        if (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!')
        }

        var triggers = this.options.trigger.split(' ')

        for (var i = triggers.length; i--;) {
            var trigger = triggers[i]

            if (trigger == 'click') {
                this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
            } else if (trigger != 'manual') {
                var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
                var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'

                this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
                this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
            }
        }

        this.options.selector ?
            (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
            this.fixTitle()
    }

    Tooltip.prototype.getDefaults = function () {
        return Tooltip.DEFAULTS
    }

    Tooltip.prototype.getOptions = function (options) {
        var dataAttributes = this.$element.data()

        for (var dataAttr in dataAttributes) {
            if (dataAttributes.hasOwnProperty(dataAttr) && $.inArray(dataAttr, DISALLOWED_ATTRIBUTES) !== -1) {
                delete dataAttributes[dataAttr]
            }
        }

        options = $.extend({}, this.getDefaults(), dataAttributes, options)

        if (options.delay && typeof options.delay == 'number') {
            options.delay = {
                show: options.delay,
                hide: options.delay
            }
        }

        if (options.sanitize) {
            options.template = sanitizeHtml(options.template, options.whiteList, options.sanitizeFn)
        }

        return options
    }

    Tooltip.prototype.getDelegateOptions = function () {
        var options = {}
        var defaults = this.getDefaults()

        this._options && $.each(this._options, function (key, value) {
            if (defaults[key] != value) options[key] = value
        })

        return options
    }

    Tooltip.prototype.enter = function (obj) {
        var self = obj instanceof this.constructor ?
            obj : $(obj.currentTarget).data('bs.' + this.type)

        if (!self) {
            self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
            $(obj.currentTarget).data('bs.' + this.type, self)
        }

        if (obj instanceof $.Event) {
            self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
        }

        if (self.tip().hasClass('in') || self.hoverState == 'in') {
            self.hoverState = 'in'
            return
        }

        clearTimeout(self.timeout)

        self.hoverState = 'in'

        if (!self.options.delay || !self.options.delay.show) return self.show()

        self.timeout = setTimeout(function () {
            if (self.hoverState == 'in') self.show()
        }, self.options.delay.show)
    }

    Tooltip.prototype.isInStateTrue = function () {
        for (var key in this.inState) {
            if (this.inState[key]) return true
        }

        return false
    }

    Tooltip.prototype.leave = function (obj) {
        var self = obj instanceof this.constructor ?
            obj : $(obj.currentTarget).data('bs.' + this.type)

        if (!self) {
            self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
            $(obj.currentTarget).data('bs.' + this.type, self)
        }

        if (obj instanceof $.Event) {
            self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
        }

        if (self.isInStateTrue()) return

        clearTimeout(self.timeout)

        self.hoverState = 'out'
        // Get the tooltip element
        var $tip = self.tip()

        // Verify tooltip exists and has an ID
        if ($tip.length && $tip[0] && $tip[0].id) {
            // First remove any existing handlers to prevent duplicates
            $tip.off('mouseenter.tooltip.interactive mouseleave.tooltip.interactive')

            // Store the hover state on the tooltip object itself for persistence
            self._isOverTooltip = false

            // Add new event handlers using jQuery for consistency
            $tip.on('mouseenter.tooltip.interactive', function () {
                self._isOverTooltip = true
                self.hoverState = 'in'
                clearTimeout(self.timeout)
            })

            $tip.on('mouseleave.tooltip.interactive', function () {
                self._isOverTooltip = false
                self.hoverState = 'out'

                if (!self.options.delay || !self.options.delay.hide) {
                    self.hide()
                } else {
                    self.timeout = setTimeout(function () {
                        if (self.hoverState == 'out') self.hide()
                    }, self.options.delay.hide)
                }
            })

            // Wait briefly to see if mouse moved to tooltip
            self.timeout = setTimeout(function () {
                if (!self._isOverTooltip && self.hoverState == 'out') {
                    if (!self.options.delay || !self.options.delay.hide) {
                        self.hide()
                    } else {
                        self.timeout = setTimeout(function () {
                            if (self.hoverState == 'out') self.hide()
                        }, self.options.delay.hide)
                    }
                }
            }, 100) // Shorter delay for better responsiveness

            return // Exit early for interactive tooltips
        }

        // Standard non-interactive behavior as fallback
        if (!self.options.delay || !self.options.delay.hide) return self.hide();

        self.timeout = setTimeout(function () {
            if (self.hoverState == 'out') self.hide()
        }, self.options.delay.hide)
    }

    Tooltip.prototype.show = function () {
        var e = $.Event('show.bs.' + this.type)

        if (this.hasContent() && this.enabled) {
            this.$element.trigger(e)

            var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
            if (e.isDefaultPrevented() || !inDom) return
            var that = this

            var $tip = this.tip()

            var tipId = this.getUID(this.type)

            this.setContent()
            $tip.attr('id', tipId)
            this.$element.not('.hide-aria-label').attr('aria-describedby', tipId)

            if (this.options.animation) $tip.addClass('fade')

            var placement = typeof this.options.placement == 'function' ?
                this.options.placement.call(this, $tip[0], this.$element[0]) :
                this.options.placement

            var autoToken = /\s?auto?\s?/i
            var autoPlace = autoToken.test(placement)
            if (autoPlace) placement = placement.replace(autoToken, '') || 'top'

            $tip
                .detach()
                .css({ top: 0, left: 0, display: 'block' })
                .addClass(placement)
                .data('bs.' + this.type, this)

            this.options.container ? $tip.appendTo($(document).find(this.options.container)) : $tip.insertAfter(this.$element)
            this.$element.trigger('inserted.bs.' + this.type)

            var pos = this.getPosition()
            var actualWidth = $tip[0].offsetWidth
            var actualHeight = $tip[0].offsetHeight

            if (autoPlace) {
                var orgPlacement = placement
                var viewportDim = this.getPosition(this.$viewport)

                placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
                    placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
                        placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
                            placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
                                placement

                $tip
                    .removeClass(orgPlacement)
                    .addClass(placement)
            }

            var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

            this.applyPlacement(calculatedOffset, placement)

            var complete = function () {
                var prevHoverState = that.hoverState
                that.$element.trigger('shown.bs.' + that.type)
                that.hoverState = null

                if (prevHoverState == 'out') that.leave(that)
            }

            $.support.transition && this.$tip.hasClass('fade') ?
                $tip
                    .one('bsTransitionEnd', complete)
                    .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
                complete()
        }
    }

    $.fn.emulateTransitionEnd = function (duration) {
        var called = false, $el = this
        $(this).one($.support.transition.end, function () { called = true })
        var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
        setTimeout(callback, duration)
        return this
    };

    Tooltip.prototype.applyPlacement = function (offset, placement) {
        var $tip = this.tip()
        var width = $tip[0].offsetWidth
        var height = $tip[0].offsetHeight

        // manually read margins because getBoundingClientRect includes difference
        var marginTop = parseInt($tip.css('margin-top'), 10)
        var marginLeft = parseInt($tip.css('margin-left'), 10)

        // we must check for NaN for ie 8/9
        if (isNaN(marginTop)) marginTop = 0
        if (isNaN(marginLeft)) marginLeft = 0

        offset.top += marginTop
        offset.left += marginLeft

        // $.fn.offset doesn't round pixel values
        // so we use setOffset directly with our own function B-0
        $.offset.setOffset($tip[0], $.extend({
            using: function (props) {
                $tip.css({
                    top: Math.round(props.top),
                    left: Math.round(props.left)
                })
            }
        }, offset), 0)

        $tip.addClass('in')

        // check to see if placing tip in new offset caused the tip to resize itself
        var actualWidth = $tip[0].offsetWidth
        var actualHeight = $tip[0].offsetHeight

        if (placement == 'top' && actualHeight != height) {
            offset.top = offset.top + height - actualHeight
        }

        var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)

        if (delta.left) offset.left += delta.left
        else offset.top += delta.top

        var isVertical = /top|bottom/.test(placement)
        var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
        var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'

        $tip.offset(offset)
        this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
    }

    Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
        this.arrow()
            .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
            .css(isVertical ? 'top' : 'left', '')
    }

    Tooltip.prototype.setContent = function () {
        var $tip = this.tip()
        var title = this.getTitle()

        if (this.options.html) {
            if (this.options.sanitize) {
                title = sanitizeHtml(title, this.options.whiteList, this.options.sanitizeFn)
            }

            $tip.find('.tooltip-inner').html(title)
        } else {
            $tip.find('.tooltip-inner').text(title)
        }

        $tip.removeClass('fade in top bottom left right')
    }

    Tooltip.prototype.hide = function (callback) {
        var that = this
        var $tip = $(this.$tip)
        var e = $.Event('hide.bs.' + this.type)

        function complete() {
            if (that.hoverState != 'in') $tip.detach()
            if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
                that.$element
                    .removeAttr('aria-describedby')
                    .trigger('hidden.bs.' + that.type)
            }
            callback && callback()
        }

        this.$element.trigger(e)

        if (e.isDefaultPrevented()) return

        $tip.removeClass('in')

        $.support.transition && $tip.hasClass('fade') ?
            $tip
                .one('bsTransitionEnd', complete)
                .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
            complete()

        this.hoverState = null

        return this
    }

    Tooltip.prototype.fixTitle = function () {
        var $e = this.$element
        if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
            $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
        }
    }

    Tooltip.prototype.hasContent = function () {
        return this.getTitle()
    }

    Tooltip.prototype.getPosition = function ($element) {
        $element = $element || this.$element

        var el = $element[0]
        var isBody = el.tagName == 'BODY'

        var elRect = el.getBoundingClientRect()
        if (elRect.width == null) {
            // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
            elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
        }
        var isSvg = window.SVGElement && el instanceof window.SVGElement
        // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
        // See https://github.com/twbs/bootstrap/issues/20280
        var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
        var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
        var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null

        return $.extend({}, elRect, scroll, outerDims, elOffset)
    }

    Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
        return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
            placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
                placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }

    }

    Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
        var delta = { top: 0, left: 0 }
        if (!this.$viewport) return delta

        var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
        var viewportDimensions = this.getPosition(this.$viewport)

        if (/right|left/.test(placement)) {
            var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
            var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
            if (topEdgeOffset < viewportDimensions.top) { // top overflow
                delta.top = viewportDimensions.top - topEdgeOffset
            } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
                delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
            }
        } else {
            var leftEdgeOffset = pos.left - viewportPadding
            var rightEdgeOffset = pos.left + viewportPadding + actualWidth
            if (leftEdgeOffset < viewportDimensions.left) { // left overflow
                delta.left = viewportDimensions.left - leftEdgeOffset
            } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
                delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
            }
        }

        return delta
    }

    Tooltip.prototype.getTitle = function () {
        var title
        var $e = this.$element
        var o = this.options

        title = $e.attr('data-original-title')
            || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)

        return title
    }

    Tooltip.prototype.getUID = function (prefix) {
        do prefix += ~~(Math.random() * 1000000)
        while (document.getElementById(prefix))
        return prefix
    }

    Tooltip.prototype.tip = function () {
        if (!this.$tip) {
            this.$tip = $(this.options.template)
            if (this.$tip.length != 1) {
                throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
            }
        }
        return this.$tip
    }

    Tooltip.prototype.arrow = function () {
        return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
    }

    Tooltip.prototype.enable = function () {
        this.enabled = true
    }

    Tooltip.prototype.disable = function () {
        this.enabled = false
    }

    Tooltip.prototype.toggleEnabled = function () {
        this.enabled = !this.enabled
    }

    Tooltip.prototype.toggle = function (e) {
        var self = this
        if (e) {
            self = $(e.currentTarget).data('bs.' + this.type)
            if (!self) {
                self = new this.constructor(e.currentTarget, this.getDelegateOptions())
                $(e.currentTarget).data('bs.' + this.type, self)
            }
        }

        if (e) {
            self.inState.click = !self.inState.click
            if (self.isInStateTrue()) self.enter(self)
            else self.leave(self)
        } else {
            self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
        }
    }

    Tooltip.prototype.destroy = function () {
        var that = this
        clearTimeout(this.timeout)

        this.hide(function () {
            that.$element.off('.' + that.type).removeData('bs.' + that.type)
            if (that.$tip) {
                that.$tip.detach()
            }
            that.$tip = null
            that.$arrow = null
            that.$viewport = null
            that.$element = null
        })
    }

    Tooltip.prototype.sanitizeHtml = function (unsafeHtml) {
        return sanitizeHtml(unsafeHtml, this.options.whiteList, this.options.sanitizeFn)
    }

    // TOOLTIP PLUGIN DEFINITION
    // =========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.tooltip')
            var options = typeof option == 'object' && option

            if (!data && /destroy|hide/.test(option)) return
            if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.tooltip

    $.fn.tooltip = Plugin
    $.fn.tooltip.Constructor = Tooltip


    // TOOLTIP NO CONFLICT
    // ===================

    $.fn.tooltip.noConflict = function () {
        $.fn.tooltip = old
        return this
    }

}(jQuery);
;
(function () {

    $(document).on('focus mouseenter', '[data-toggle="popover"]', function () {
        this._title = this.title;
        this.title = '';
        var isPopoverVisible = $('.popover-content').length > 0;
        if ($(this)[0].id != "redirectLink" && isPopoverVisible) {
            $('#redirectLink').popover('hide');
            $('.click-popover').removeClass('visible-desktop');
            $('.click-popover').hide();
        }
    });
    

    $(document).on('mouseleave','[data-toggle="popover"]', function() {
        this.title = this._title;        
    });

    $.fn.tooltip.Constructor.prototype.fixTitle = function () {
        var $e = this.$element
        if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
            $e.attr('data-original-title', $e.attr('title') || '');
        }
    }
})();;
/* ========================================================================
 * Bootstrap: popover.js v3.2.0
 * http://getbootstrap.com/javascript/#popovers
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // POPOVER PUBLIC CLASS DEFINITION
  // ===============================

  var Popover = function (element, options) {
    this.init('popover', element, options)
  }

  if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')

  Popover.VERSION  = '3.2.0'

  Popover.DEFAULTS = $.extend({}, $.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>'
  })


  // NOTE: POPOVER EXTENDS tooltip.js
  // ================================

  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)

  Popover.prototype.constructor = Popover

  Popover.prototype.getDefaults = function () {
    return Popover.DEFAULTS
  }

  Popover.prototype.setContent = function () {
    var $tip    = this.tip()
    var title   = this.getTitle()
    var content = this.getContent()

    $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
    $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
      this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
    ](content)

    $tip.removeClass('fade top bottom left right in')

    // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
    // this manually by checking the contents.
    if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
  }

  Popover.prototype.hasContent = function () {
    return this.getTitle() || this.getContent()
  }

  Popover.prototype.getContent = function () {
    var $e = this.$element
    var o  = this.options

    return $e.attr('data-content')
      || (typeof o.content == 'function' ?
            o.content.call($e[0]) :
            o.content)
  }

  Popover.prototype.arrow = function () {
    return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
  }

  Popover.prototype.tip = function () {
    if (!this.$tip) this.$tip = $(this.options.template)
    return this.$tip
  }


  // POPOVER PLUGIN DEFINITION
  // =========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.popover')
      var options = typeof option == 'object' && option

      if (!data && option == 'destroy') return
      if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.popover

  $.fn.popover             = Plugin
  $.fn.popover.Constructor = Popover


  // POPOVER NO CONFLICT
  // ===================

  $.fn.popover.noConflict = function () {
    $.fn.popover = old
    return this
  }

}(jQuery);
;
/* ========================================================================
 * Bootstrap: scrollspy.js v3.2.0
 * http://getbootstrap.com/javascript/#scrollspy
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // SCROLLSPY CLASS DEFINITION
  // ==========================

  function ScrollSpy(element, options) {
    var process  = $.proxy(this.process, this)

    this.$body          = $('body')
    this.$scrollElement = $(element).is('body') ? $(window) : $(element)
    this.options        = $.extend({}, ScrollSpy.DEFAULTS, options)
    this.selector       = (this.options.target || '') + ' .nav li > a'
    this.offsets        = []
    this.targets        = []
    this.activeTarget   = null
    this.scrollHeight   = 0

    this.$scrollElement.on('scroll.bs.scrollspy', process)
    this.refresh()
    this.process()
  }

  ScrollSpy.VERSION  = '3.2.0'

  ScrollSpy.DEFAULTS = {
    offset: 10
  }

  ScrollSpy.prototype.getScrollHeight = function () {
    return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
  }

  ScrollSpy.prototype.refresh = function () {
    var offsetMethod = 'offset'
    var offsetBase   = 0

    if (!$.isWindow(this.$scrollElement[0])) {
      offsetMethod = 'position'
      offsetBase   = this.$scrollElement.scrollTop()
    }

    this.offsets = []
    this.targets = []
    this.scrollHeight = this.getScrollHeight()

    var self     = this

    this.$body
      .find(this.selector)
      .map(function () {
        var $el   = $(this)
        var href  = $el.data('target') || $el.attr('href')
        var $href = /^#./.test(href) && $(href)

        return ($href
          && $href.length
          && $href.is(':visible')
          && [[$href[offsetMethod]().top + offsetBase, href]]) || null
      })
      .sort(function (a, b) { return a[0] - b[0] })
      .each(function () {
        self.offsets.push(this[0])
        self.targets.push(this[1])
      })
  }

  ScrollSpy.prototype.process = function () {
    var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
    var scrollHeight = this.getScrollHeight()
    var maxScroll    = this.options.offset + scrollHeight - this.$scrollElement.height()
    var offsets      = this.offsets
    var targets      = this.targets
    var activeTarget = this.activeTarget
    var i

    if (this.scrollHeight != scrollHeight) {
      this.refresh()
    }

    if (scrollTop >= maxScroll) {
      return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
    }

    if (activeTarget && scrollTop <= offsets[0]) {
      return activeTarget != (i = targets[0]) && this.activate(i)
    }

    for (i = offsets.length; i--;) {
      activeTarget != targets[i]
        && scrollTop >= offsets[i]
        && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
        && this.activate(targets[i])
    }
  }

  ScrollSpy.prototype.activate = function (target) {
    this.activeTarget = target

    $(this.selector)
      .parentsUntil(this.options.target, '.active')
      .removeClass('active')

    var selector = this.selector +
        '[data-target="' + target + '"],' +
        this.selector + '[href="' + target + '"]'

    var active = $(selector)
      .parents('li')
      .addClass('active')

    if (active.parent('.dropdown-menu').length) {
      active = active
        .closest('li.dropdown')
        .addClass('active')
    }

    active.trigger('activate.bs.scrollspy')
  }


  // SCROLLSPY PLUGIN DEFINITION
  // ===========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.scrollspy')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.scrollspy

  $.fn.scrollspy             = Plugin
  $.fn.scrollspy.Constructor = ScrollSpy


  // SCROLLSPY NO CONFLICT
  // =====================

  $.fn.scrollspy.noConflict = function () {
    $.fn.scrollspy = old
    return this
  }


  // SCROLLSPY DATA-API
  // ==================

  $(window).on('load.bs.scrollspy.data-api', function () {
    $('[data-spy="scroll"]').each(function () {
      var $spy = $(this)
      Plugin.call($spy, $spy.data())
    })
  })

}(jQuery);
;
/* ========================================================================
 * Bootstrap: transition.js v3.2.0
 * http://getbootstrap.com/javascript/#transitions
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
  // ============================================================

  function transitionEnd() {
    var el = document.createElement('bootstrap')

    var transEndEventNames = {
      WebkitTransition : 'webkitTransitionEnd',
      MozTransition    : 'transitionend',
      OTransition      : 'oTransitionEnd otransitionend',
      transition       : 'transitionend'
    }

    for (var name in transEndEventNames) {
      if (el.style[name] !== undefined) {
        return { end: transEndEventNames[name] }
      }
    }

    return false // explicit for ie8 (  ._.)
  }

  // http://blog.alexmaccaw.com/css-transitions
  $.fn.emulateTransitionEnd = function (duration) {
    var called = false
    var $el = this
    $(this).one('bsTransitionEnd', function () { called = true })
    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
    setTimeout(callback, duration)
    return this
  }

  $(function () {
    $.support.transition = transitionEnd()

    if (!$.support.transition) return

    $.event.special.bsTransitionEnd = {
      bindType: $.support.transition.end,
      delegateType: $.support.transition.end,
      handle: function (e) {
        if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
      }
    }
  })

}(jQuery);
;
/* ========================================================================
 * Bootstrap: tab.js v3.4.1
 * https://getbootstrap.com/docs/3.4/javascript/#tabs
 * ========================================================================
 * Copyright 2011-2019 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


!function ($) {
  'use strict';

  // TAB CLASS DEFINITION
  // ====================

  var Tab = function (element) {
    // jscs:disable requireDollarBeforejQueryAssignment
    this.element = $(element)
    // jscs:enable requireDollarBeforejQueryAssignment
  }

  Tab.VERSION = '3.4.1'

  Tab.TRANSITION_DURATION = 150

  Tab.prototype.show = function () {
    var $this    = this.element
    var $ul      = $this.closest('ul:not(.dropdown-menu)')
    var selector = $this.data('target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    if ($this.parent('li').hasClass('active')) return

    var $previous = $ul.find('.active:last a')
    var hideEvent = $.Event('hide.bs.tab', {
      relatedTarget: $this[0]
    })
    var showEvent = $.Event('show', {
      relatedTarget: $previous[0]
    })

    $previous.trigger(hideEvent)
    $this.trigger(showEvent)

    if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return

    var $target = $(document).find(selector)

    this.activate($this.closest('li'), $ul)
    this.activate($target, $target.parent(), function () {
      $previous.trigger({
        type: 'hidden.bs.tab',
        relatedTarget: $this[0]
      })
      $this.trigger({
        type: 'shown',
        relatedTarget: $previous[0]
      })
    })
  }

  Tab.prototype.activate = function (element, container, callback) {
    var $active    = container.find('> .active')
    var transition = callback
      && $.support.transition
      && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)

    function next() {
      $active
        .removeClass('active')
        .find('> .dropdown-menu > .active')
        .removeClass('active')
        .end()
        //.find('[data-toggle="tab"]') //Commented for ONLINE-13390 finding
        //.attr('aria-expanded', false)

      element
        .addClass('active')
        //.find('[data-toggle="tab"]')//Commented for ONLINE-13390 finding
        //.attr('aria-expanded', true)

      if (transition) {
        element[0].offsetWidth // reflow for transition
        element.addClass('in')
      } else {
        element.removeClass('fade')
      }

      if (element.parent('.dropdown-menu').length) {
        element
          .closest('li.dropdown')
          .addClass('active')
          .end()
          .find('[data-toggle="tab"]')
          .attr('aria-expanded', true)
      }

      callback && callback()
    }

    $active.length && transition ?
      $active
        .one('bsTransitionEnd', next)
        .emulateTransitionEnd(Tab.TRANSITION_DURATION) :
      next()

    $active.removeClass('in')
  }


  // TAB PLUGIN DEFINITION
  // =====================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.tab')

      if (!data) $this.data('bs.tab', (data = new Tab(this)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.tab

  $.fn.tab             = Plugin
  $.fn.tab.Constructor = Tab


  // TAB NO CONFLICT
  // ===============

  $.fn.tab.noConflict = function () {
    $.fn.tab = old
    return this
  }


  // TAB DATA-API
  // ============

  var clickHandler = function (e) {
    e.preventDefault()
    Plugin.call($(this), 'show')
  }

  $(document)
    .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
    .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)

}(jQuery);
;
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.SignaturePad=e()}(this,function(){"use strict";function t(t,e,i){this.x=t,this.y=e,this.time=i||(new Date).getTime()}function e(t,e,i,o){this.startPoint=t,this.control1=e,this.control2=i,this.endPoint=o}function i(t,e,i){var o,n,s,r=null,h=0;i||(i={});var a=function(){h=!1===i.leading?0:Date.now(),r=null,s=t.apply(o,n),r||(o=n=null)};return function(){var c=Date.now();h||!1!==i.leading||(h=c);var d=e-(c-h);return o=this,n=arguments,d<=0||d>e?(r&&(clearTimeout(r),r=null),h=c,s=t.apply(o,n),r||(o=n=null)):r||!1===i.trailing||(r=setTimeout(a,d)),s}}function o(t,e){var n=this,s=e||{};this.velocityFilterWeight=s.velocityFilterWeight||.7,this.minWidth=s.minWidth||.5,this.maxWidth=s.maxWidth||2.5,this.throttle="throttle"in s?s.throttle:16,this.minDistance="minDistance"in s?s.minDistance:5,this.throttle?this._strokeMoveUpdate=i(o.prototype._strokeUpdate,this.throttle):this._strokeMoveUpdate=o.prototype._strokeUpdate,this.dotSize=s.dotSize||function(){return(this.minWidth+this.maxWidth)/2},this.penColor=s.penColor||"black",this.backgroundColor=s.backgroundColor||"rgba(0,0,0,0)",this.onBegin=s.onBegin,this.onEnd=s.onEnd,this._canvas=t,this._ctx=t.getContext("2d"),this.clear(),this._handleMouseDown=function(t){1===t.which&&(n._mouseButtonDown=!0,n._strokeBegin(t))},this._handleMouseMove=function(t){n._mouseButtonDown&&n._strokeMoveUpdate(t)},this._handleMouseUp=function(t){1===t.which&&n._mouseButtonDown&&(n._mouseButtonDown=!1,n._strokeEnd(t))},this._handleTouchStart=function(t){if(1===t.targetTouches.length){var e=t.changedTouches[0];n._strokeBegin(e)}},this._handleTouchMove=function(t){t.preventDefault();var e=t.targetTouches[0];n._strokeMoveUpdate(e)},this._handleTouchEnd=function(t){t.target===n._canvas&&(t.preventDefault(),n._strokeEnd(t))},this.on()}return t.prototype.velocityFrom=function(t){return this.time!==t.time?this.distanceTo(t)/(this.time-t.time):1},t.prototype.distanceTo=function(t){return Math.sqrt(Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2))},t.prototype.equals=function(t){return this.x===t.x&&this.y===t.y&&this.time===t.time},e.prototype.length=function(){for(var t=0,e=void 0,i=void 0,o=0;o<=10;o+=1){var n=o/10,s=this._point(n,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),r=this._point(n,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(o>0){var h=s-e,a=r-i;t+=Math.sqrt(h*h+a*a)}e=s,i=r}return t},e.prototype._point=function(t,e,i,o,n){return e*(1-t)*(1-t)*(1-t)+3*i*(1-t)*(1-t)*t+3*o*(1-t)*t*t+n*t*t*t},o.prototype.clear=function(){var t=this._ctx,e=this._canvas;t.fillStyle=this.backgroundColor,t.clearRect(0,0,e.width,e.height),t.fillRect(0,0,e.width,e.height),this._data=[],this._reset(),this._isEmpty=!0},o.prototype.fromDataURL=function(t){var e=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=new Image,n=i.ratio||window.devicePixelRatio||1,s=i.width||this._canvas.width/n,r=i.height||this._canvas.height/n;this._reset(),o.src=t,o.onload=function(){e._ctx.drawImage(o,0,0,s,r)},this._isEmpty=!1},o.prototype.toDataURL=function(t){var e;switch(t){case"image/svg+xml":return this._toSVG();default:for(var i=arguments.length,o=Array(i>1?i-1:0),n=1;n<i;n++)o[n-1]=arguments[n];return(e=this._canvas).toDataURL.apply(e,[t].concat(o))}},o.prototype.on=function(){this._handleMouseEvents(),this._handleTouchEvents()},o.prototype.off=function(){this._canvas.removeEventListener("mousedown",this._handleMouseDown),this._canvas.removeEventListener("mousemove",this._handleMouseMove),document.removeEventListener("mouseup",this._handleMouseUp),this._canvas.removeEventListener("touchstart",this._handleTouchStart),this._canvas.removeEventListener("touchmove",this._handleTouchMove),this._canvas.removeEventListener("touchend",this._handleTouchEnd)},o.prototype.isEmpty=function(){return this._isEmpty},o.prototype._strokeBegin=function(t){this._data.push([]),this._reset(),this._strokeUpdate(t),"function"==typeof this.onBegin&&this.onBegin(t)},o.prototype._strokeUpdate=function(t){var e=t.clientX,i=t.clientY,o=this._createPoint(e,i),n=this._data[this._data.length-1],s=n&&n[n.length-1],r=s&&o.distanceTo(s)<this.minDistance;if(!s||!r){var h=this._addPoint(o),a=h.curve,c=h.widths;a&&c&&this._drawCurve(a,c.start,c.end),this._data[this._data.length-1].push({x:o.x,y:o.y,time:o.time,color:this.penColor})}},o.prototype._strokeEnd=function(t){var e=this.points.length>2,i=this.points[0];if(!e&&i&&this._drawDot(i),i){var o=this._data[this._data.length-1],n=o[o.length-1];i.equals(n)||o.push({x:i.x,y:i.y,time:i.time,color:this.penColor})}"function"==typeof this.onEnd&&this.onEnd(t)},o.prototype._handleMouseEvents=function(){this._mouseButtonDown=!1,this._canvas.addEventListener("mousedown",this._handleMouseDown),this._canvas.addEventListener("mousemove",this._handleMouseMove),document.addEventListener("mouseup",this._handleMouseUp)},o.prototype._handleTouchEvents=function(){this._canvas.style.msTouchAction="none",this._canvas.style.touchAction="none",this._canvas.addEventListener("touchstart",this._handleTouchStart),this._canvas.addEventListener("touchmove",this._handleTouchMove),this._canvas.addEventListener("touchend",this._handleTouchEnd)},o.prototype._reset=function(){this.points=[],this._lastVelocity=0,this._lastWidth=(this.minWidth+this.maxWidth)/2,this._ctx.fillStyle=this.penColor},o.prototype._createPoint=function(e,i,o){var n=this._canvas.getBoundingClientRect();return new t(e-n.left,i-n.top,o||(new Date).getTime())},o.prototype._addPoint=function(t){var i=this.points,o=void 0;if(i.push(t),i.length>2){3===i.length&&i.unshift(i[0]),o=this._calculateCurveControlPoints(i[0],i[1],i[2]);var n=o.c2;o=this._calculateCurveControlPoints(i[1],i[2],i[3]);var s=o.c1,r=new e(i[1],n,s,i[2]),h=this._calculateCurveWidths(r);return i.shift(),{curve:r,widths:h}}return{}},o.prototype._calculateCurveControlPoints=function(e,i,o){var n=e.x-i.x,s=e.y-i.y,r=i.x-o.x,h=i.y-o.y,a={x:(e.x+i.x)/2,y:(e.y+i.y)/2},c={x:(i.x+o.x)/2,y:(i.y+o.y)/2},d=Math.sqrt(n*n+s*s),l=Math.sqrt(r*r+h*h),u=a.x-c.x,v=a.y-c.y,p=l/(d+l),_={x:c.x+u*p,y:c.y+v*p},y=i.x-_.x,f=i.y-_.y;return{c1:new t(a.x+y,a.y+f),c2:new t(c.x+y,c.y+f)}},o.prototype._calculateCurveWidths=function(t){var e=t.startPoint,i=t.endPoint,o={start:null,end:null},n=this.velocityFilterWeight*i.velocityFrom(e)+(1-this.velocityFilterWeight)*this._lastVelocity,s=this._strokeWidth(n);return o.start=this._lastWidth,o.end=s,this._lastVelocity=n,this._lastWidth=s,o},o.prototype._strokeWidth=function(t){return Math.max(this.maxWidth/(t+1),this.minWidth)},o.prototype._drawPoint=function(t,e,i){var o=this._ctx;o.moveTo(t,e),o.arc(t,e,i,0,2*Math.PI,!1),this._isEmpty=!1},o.prototype._drawCurve=function(t,e,i){var o=this._ctx,n=i-e,s=Math.floor(t.length());o.beginPath();for(var r=0;r<s;r+=1){var h=r/s,a=h*h,c=a*h,d=1-h,l=d*d,u=l*d,v=u*t.startPoint.x;v+=3*l*h*t.control1.x,v+=3*d*a*t.control2.x,v+=c*t.endPoint.x;var p=u*t.startPoint.y;p+=3*l*h*t.control1.y,p+=3*d*a*t.control2.y,p+=c*t.endPoint.y;var _=e+c*n;this._drawPoint(v,p,_)}o.closePath(),o.fill()},o.prototype._drawDot=function(t){var e=this._ctx,i="function"==typeof this.dotSize?this.dotSize():this.dotSize;e.beginPath(),this._drawPoint(t.x,t.y,i),e.closePath(),e.fill()},o.prototype._fromData=function(e,i,o){for(var n=0;n<e.length;n+=1){var s=e[n];if(s.length>1)for(var r=0;r<s.length;r+=1){var h=s[r],a=new t(h.x,h.y,h.time),c=h.color;if(0===r)this.penColor=c,this._reset(),this._addPoint(a);else if(r!==s.length-1){var d=this._addPoint(a),l=d.curve,u=d.widths;l&&u&&i(l,u,c)}}else{this._reset();o(s[0])}}},o.prototype._toSVG=function(){var t=this,e=this._data,i=this._canvas,o=Math.max(window.devicePixelRatio||1,1),n=i.width/o,s=i.height/o,r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttributeNS(null,"width",i.width),r.setAttributeNS(null,"height",i.height),this._fromData(e,function(t,e,i){var o=document.createElement("path");if(!(isNaN(t.control1.x)||isNaN(t.control1.y)||isNaN(t.control2.x)||isNaN(t.control2.y))){var n="M "+t.startPoint.x.toFixed(3)+","+t.startPoint.y.toFixed(3)+" C "+t.control1.x.toFixed(3)+","+t.control1.y.toFixed(3)+" "+t.control2.x.toFixed(3)+","+t.control2.y.toFixed(3)+" "+t.endPoint.x.toFixed(3)+","+t.endPoint.y.toFixed(3);o.setAttribute("d",n),o.setAttribute("stroke-width",(2.25*e.end).toFixed(3)),o.setAttribute("stroke",i),o.setAttribute("fill","none"),o.setAttribute("stroke-linecap","round"),r.appendChild(o)}},function(e){var i=document.createElement("circle"),o="function"==typeof t.dotSize?t.dotSize():t.dotSize;i.setAttribute("r",o),i.setAttribute("cx",e.x),i.setAttribute("cy",e.y),i.setAttribute("fill",e.color),r.appendChild(i)});var h='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 '+n+" "+s+'" width="'+n+'" height="'+s+'">',a=r.innerHTML;if(void 0===a){var c=document.createElement("dummy"),d=r.childNodes;c.innerHTML="";for(var l=0;l<d.length;l+=1)c.appendChild(d[l].cloneNode(!0));a=c.innerHTML}var u=h+a+"</svg>";return"data:image/svg+xml;base64,"+btoa(u)},o.prototype.fromData=function(t){var e=this;this.clear(),this._fromData(t,function(t,i){return e._drawCurve(t,i.start,i.end)},function(t){return e._drawDot(t)}),this._data=t},o.prototype.toData=function(){return this._data},o});;
/*
    json2.js
    2013-05-26

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, regexp: true */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (typeof JSON !== 'object') {
    JSON = {};
}

(function () {
    'use strict';

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function () {

            return isFinite(this.valueOf())
                ? this.getUTCFullYear()     + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate())      + 'T' +
                    f(this.getUTCHours())     + ':' +
                    f(this.getUTCMinutes())   + ':' +
                    f(this.getUTCSeconds())   + 'Z'
                : null;
        };

        String.prototype.toJSON      =
            Number.prototype.toJSON  =
            Boolean.prototype.toJSON = function () {
                return this.valueOf();
            };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string'
                ? c
                : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0
                    ? '[]'
                    : gap
                    ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                    : '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0
                ? '{}'
                : gap
                ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
                : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function'
                    ? walk({'': j}, '')
                    : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());
;
/*!jQuery Knob*/
/**
 * Downward compatible, touchable dial
 *
 * Version: 1.2.0 (15/07/2012)
 * Requires: jQuery v1.7+
 *
 * Copyright (c) 2012 Anthony Terrien
 * Under MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to vor, eskimoblood, spiffistan, FabrizioC
 */
(function($) {

    /**
     * Kontrol library
     */
    "use strict";

    /**
     * Definition of globals and core
     */
    var k = {}, // kontrol
        max = Math.max,
        min = Math.min;

    k.c = {};
    k.c.d = $(document);
    k.c.t = function (e) {
        return e.originalEvent.touches.length - 1;
    };

    /**
     * Kontrol Object
     *
     * Definition of an abstract UI control
     *
     * Each concrete component must call this one.
     * <code>
     * k.o.call(this);
     * </code>
     */
    k.o = function () {
        var s = this;

        this.o = null; // array of options
        this.$ = null; // jQuery wrapped element
        this.i = null; // mixed HTMLInputElement or array of HTMLInputElement
        this.g = null; // 2D graphics context for 'pre-rendering'
        this.v = null; // value ; mixed array or integer
        this.cv = null; // change value ; not commited value
        this.x = 0; // canvas x position
        this.y = 0; // canvas y position
        this.$c = null; // jQuery canvas element
        this.c = null; // rendered canvas context
        this.t = 0; // touches index
        this.isInit = false;
        this.fgColor = null; // main color
        this.pColor = null; // previous color
        this.dH = null; // draw hook
        this.cH = null; // change hook
        this.eH = null; // cancel hook
        this.rH = null; // release hook

        this.run = function () {
            var cf = function (e, conf) {
                var k;
                for (k in conf) {
                    s.o[k] = conf[k];
                }
                s.init();
                s._configure()
                 ._draw();
            };

            if(this.$.data('kontroled')) return;
            this.$.data('kontroled', true);

            this.extend();
            this.o = $.extend(
                {
                    // Config
                    min : this.$.data('min') || 0,
                    max : this.$.data('max') || 100,
                    stopper : true,
                    readOnly : this.$.data('readonly'),

                    // UI
                    cursor : (this.$.data('cursor') === true && 30)
                                || this.$.data('cursor')
                                || 0,
                    thickness : this.$.data('thickness') || 0.35,
                    lineCap : this.$.data('linecap') || 'butt',
                    width : this.$.data('width') || 200,
                    height : this.$.data('height') || 200,
                    displayInput : this.$.data('displayinput') == null || this.$.data('displayinput'),
                    displayPrevious : this.$.data('displayprevious'),
                    fgColor : this.$.data('fgcolor') || '#87CEEB',
                    inputColor: this.$.data('inputcolor') || this.$.data('fgcolor') || '#87CEEB',
                    inline : false,
                    step : this.$.data('step') || 1,

                    // Hooks
                    draw : null, // function () {}
                    change : null, // function (value) {}
                    cancel : null, // function () {}
                    release : null // function (value) {}
                }, this.o
            );

            // routing value
            if(this.$.is('fieldset')) {

                // fieldset = array of integer
                this.v = {};
                this.i = this.$.find('input')
                this.i.each(function(k) {
                    var $this = $(this);
                    s.i[k] = $this;
                    s.v[k] = $this.val();

                    $this.bind(
                        'change'
                        , function () {
                            var val = {};
                            val[k] = $this.val();
                            s.val(val);
                        }
                    );
                });
                this.$.find('legend').remove();

            } else {
                // input = integer
                this.i = this.$;
                this.v = this.$.val();
                (this.v == '') && (this.v = this.o.min);

                this.$.bind(
                    'change'
                    , function () {
                        s.val(s._validate(s.$.val()));
                    }
                );
            }

            (!this.o.displayInput) && this.$.hide();

            this.$c = $('<canvas width="' +
                            this.o.width + 'px" height="' +
                            this.o.height + 'px"></canvas>');
            this.c = this.$c[0].getContext("2d");

            this.$
                .wrap($('<div style="' + (this.o.inline ? 'display:inline;' : '') +
                        'width:' + this.o.width + 'px;height:' +
                        this.o.height + 'px;"></div>'))
                .before(this.$c);

            if (this.v instanceof Object) {
                this.cv = {};
                this.copy(this.v, this.cv);
            } else {
                this.cv = this.v;
            }

            this.$
                .bind("configure", cf)
                .parent()
                .bind("configure", cf);

            this._listen()
                ._configure()
                ._xy()
                .init();

            this.isInit = true;

            this._draw();

            return this;
        };

        this._draw = function () {

            // canvas pre-rendering
            var d = true,
                c = document.createElement('canvas');

            c.width = s.o.width;
            c.height = s.o.height;
            s.g = c.getContext('2d');

            s.clear();

            s.dH
            && (d = s.dH());

            (d !== false) && s.draw();

            s.c.drawImage(c, 0, 0);
            c = null;
        };

        this._touch = function (e) {

            var touchMove = function (e) {

                var v = s.xy2val(
                            e.originalEvent.touches[s.t].pageX,
                            e.originalEvent.touches[s.t].pageY
                            );

                if (v == s.cv) return;

                if (
                    s.cH
                    && (s.cH(v) === false)
                ) return;


                s.change(s._validate(v));
                s._draw();
            };

            // get touches index
            this.t = k.c.t(e);

            // First touch
            touchMove(e);

            // Touch events listeners
            k.c.d
                .bind("touchmove.k", touchMove)
                .bind(
                    "touchend.k"
                    , function () {
                        k.c.d.unbind('touchmove.k touchend.k');

                        if (
                            s.rH
                            && (s.rH(s.cv) === false)
                        ) return;

                        s.val(s.cv);
                    }
                );

            return this;
        };

        this._mouse = function (e) {

            var mouseMove = function (e) {
                var v = s.xy2val(e.pageX, e.pageY);
                if (v == s.cv) return;

                if (
                    s.cH
                    && (s.cH(v) === false)
                ) return;

                s.change(s._validate(v));
                s._draw();
            };

            // First click
            mouseMove(e);

            // Mouse events listeners
            k.c.d
                .bind("mousemove.k", mouseMove)
                .bind(
                    // Escape key cancel current change
                    "keyup.k"
                    , function (e) {
                        if (e.keyCode === 27) {
                            k.c.d.unbind("mouseup.k mousemove.k keyup.k");

                            if (
                                s.eH
                                && (s.eH() === false)
                            ) return;

                            s.cancel();
                        }
                    }
                )
                .bind(
                    "mouseup.k"
                    , function (e) {
                        k.c.d.unbind('mousemove.k mouseup.k keyup.k');

                        if (
                            s.rH
                            && (s.rH(s.cv) === false)
                        ) return;

                        s.val(s.cv);
                    }
                );

            return this;
        };

        this._xy = function () {
            var o = this.$c.offset();
            this.x = o.left;
            this.y = o.top;
            return this;
        };

        this._listen = function () {

            if (!this.o.readOnly) {
                this.$c
                    .bind(
                        "mousedown"
                        , function (e) {
                            e.preventDefault();
                            s._xy()._mouse(e);
                         }
                    )
                    .bind(
                        "touchstart"
                        , function (e) {
                            e.preventDefault();
                            s._xy()._touch(e);
                         }
                    );
                this.listen();
            } else {
                this.$.attr('readonly', 'readonly');
            }

            return this;
        };

        this._configure = function () {

            // Hooks
            if (this.o.draw) this.dH = this.o.draw;
            if (this.o.change) this.cH = this.o.change;
            if (this.o.cancel) this.eH = this.o.cancel;
            if (this.o.release) this.rH = this.o.release;

            if (this.o.displayPrevious) {
                this.pColor = this.h2rgba(this.o.fgColor, "0.4");
                this.fgColor = this.h2rgba(this.o.fgColor, "0.6");
            } else {
                this.fgColor = this.o.fgColor;
            }

            return this;
        };

        this._clear = function () {
            this.$c[0].width = this.$c[0].width;
        };

        this._validate = function(v) {
            return (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step;
        };

        // Abstract methods
        this.listen = function () {}; // on start, one time
        this.extend = function () {}; // each time configure triggered
        this.init = function () {}; // each time configure triggered
        this.change = function (v) {}; // on change
        this.val = function (v) {}; // on release
        this.xy2val = function (x, y) {}; //
        this.draw = function () {}; // on change / on release
        this.clear = function () { this._clear(); };

        // Utils
        this.h2rgba = function (h, a) {
            var rgb;
            h = h.substring(1,7)
            rgb = [parseInt(h.substring(0,2),16)
                   ,parseInt(h.substring(2,4),16)
                   ,parseInt(h.substring(4,6),16)];
            return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")";
        };

        this.copy = function (f, t) {
            for (var i in f) { t[i] = f[i]; }
        };
    };


    /**
     * k.Dial
     */
    k.Dial = function () {
        k.o.call(this);

        this.startAngle = null;
        this.xy = null;
        this.radius = null;
        this.lineWidth = null;
        this.cursorExt = null;
        this.w2 = null;
        this.PI2 = 2*Math.PI;

        this.extend = function () {
            this.o = $.extend(
                {
                    bgColor : this.$.data('bgcolor') || '#EEEEEE',
                    angleOffset : this.$.data('angleoffset') || 0,
                    angleArc : this.$.data('anglearc') || 360,
                    inline : true
                }, this.o
            );
        };

        this.val = function (v) {
            if (null != v) {
                this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v;
                this.v = this.cv;
                this.$.val(this.v);
                this._draw();
            } else {
                return this.v;
            }
        };

        this.xy2val = function (x, y) {
            var a, ret;

            a = Math.atan2(
                        x - (this.x + this.w2)
                        , - (y - this.y - this.w2)
                    ) - this.angleOffset;

            if(this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) {
                // if isset angleArc option, set to min if .5 under min
                a = 0;
            } else if (a < 0) {
                a += this.PI2;
            }

            ret = ~~ (0.5 + (a * (this.o.max - this.o.min) / this.angleArc))
                    + this.o.min;

            this.o.stopper
            && (ret = max(min(ret, this.o.max), this.o.min));

            return ret;
        };

        this.listen = function () {
            // bind MouseWheel
            var s = this,
                mw = function (e) {
                            e.preventDefault();
                            var ori = e.originalEvent
                                ,deltaX = ori.detail || ori.wheelDeltaX
                                ,deltaY = ori.detail || ori.wheelDeltaY
                                ,v = parseInt(s.$.val()) + (deltaX>0 || deltaY>0 ? s.o.step : deltaX<0 || deltaY<0 ? -s.o.step : 0);

                            if (
                                s.cH
                                && (s.cH(v) === false)
                            ) return;

                            s.val(v);
                        }
                , kval, to, m = 1, kv = {37:-s.o.step, 38:s.o.step, 39:s.o.step, 40:-s.o.step};

            this.$
                .bind(
                    "keydown"
                    ,function (e) {
                        var kc = e.keyCode;

                        // numpad support
                        if(kc >= 96 && kc <= 105) {
                            kc = e.keyCode = kc - 48;
                        }

                        kval = parseInt(String.fromCharCode(kc));

                        if (isNaN(kval)) {

                            (kc !== 13)         // enter
                            && (kc !== 8)       // bs
                            && (kc !== 9)       // tab
                            && (kc !== 189)     // -
                            && e.preventDefault();

                            // arrows
                            if ($.inArray(kc,[37,38,39,40]) > -1) {
                                e.preventDefault();

                                var v = parseInt(s.$.val()) + kv[kc] * m;

                                s.o.stopper
                                && (v = max(min(v, s.o.max), s.o.min));

                                s.change(v);
                                s._draw();

                                // long time keydown speed-up
                                to = window.setTimeout(
                                    function () { m*=2; }
                                    ,30
                                );
                            }
                        }
                    }
                )
                .bind(
                    "keyup"
                    ,function (e) {
                        if (isNaN(kval)) {
                            if (to) {
                                window.clearTimeout(to);
                                to = null;
                                m = 1;
                                s.val(s.$.val());
                            }
                        } else {
                            // kval postcond
                            (s.$.val() > s.o.max && s.$.val(s.o.max))
                            || (s.$.val() < s.o.min && s.$.val(s.o.min));
                        }

                    }
                );

            this.$c.bind("mousewheel DOMMouseScroll", mw);
            this.$.bind("mousewheel DOMMouseScroll", mw)
        };

        this.init = function () {

            if (
                this.v < this.o.min
                || this.v > this.o.max
            ) this.v = this.o.min;

            this.$.val(this.v);
            this.w2 = this.o.width / 2;
            this.cursorExt = this.o.cursor / 100;
            this.xy = this.w2;
            this.lineWidth = this.xy * this.o.thickness;
            this.lineCap = this.o.lineCap;
            this.radius = this.xy - this.lineWidth / 2;

            this.o.angleOffset
            && (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset);

            this.o.angleArc
            && (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc);

            // deg to rad
            this.angleOffset = this.o.angleOffset * Math.PI / 180;
            this.angleArc = this.o.angleArc * Math.PI / 180;

            // compute start and end angles
            this.startAngle = 1.5 * Math.PI + this.angleOffset;
            this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc;

            var s = max(
                            String(Math.abs(this.o.max)).length
                            , String(Math.abs(this.o.min)).length
                            , 2
                            ) + 2;

            this.o.displayInput
                && this.i.css({
                        'width' : ((this.o.width / 2 + 4) >> 0) + 'px'
                        ,'height' : ((this.o.width / 3) >> 0) + 'px'
                        ,'position' : 'absolute'
                        ,'vertical-align' : 'middle'
                        ,'margin-top' : ((this.o.width / 3) >> 0) + 'px'
                        ,'margin-left' : '-' + ((this.o.width * 3 / 4 + 2) >> 0) + 'px'
                        ,'border' : 0
                        ,'background' : 'none'
                        ,'font' : 'bold ' + ((this.o.width / s) >> 0) + 'px Arial'
                        ,'text-align' : 'center'
                        ,'color' : this.o.inputColor || this.o.fgColor
                        ,'padding' : '0px'
                        ,'-webkit-appearance': 'none'
                        })
                || this.i.css({
                        'width' : '0px'
                        ,'visibility' : 'hidden'
                        });
        };

        this.change = function (v) {
            this.cv = v;
            this.$.val(v);
        };

        this.angle = function (v) {
            return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min);
        };

        this.draw = function () {

            var c = this.g,                 // context
                a = this.angle(this.cv)    // Angle
                , sat = this.startAngle     // Start angle
                , eat = sat + a             // End angle
                , sa, ea                    // Previous angles
                , r = 1;

            c.lineWidth = this.lineWidth;

            c.lineCap = this.lineCap;

            this.o.cursor
                && (sat = eat - this.cursorExt)
                && (eat = eat + this.cursorExt);

            c.beginPath();
                c.strokeStyle = this.o.bgColor;
                c.arc(this.xy, this.xy, this.radius, this.endAngle, this.startAngle, true);
            c.stroke();

            if (this.o.displayPrevious) {
                ea = this.startAngle + this.angle(this.v);
                sa = this.startAngle;
                this.o.cursor
                    && (sa = ea - this.cursorExt)
                    && (ea = ea + this.cursorExt);

                c.beginPath();
                    c.strokeStyle = this.pColor;
                    c.arc(this.xy, this.xy, this.radius, sa, ea, false);
                c.stroke();
                r = (this.cv == this.v);
            }

            c.beginPath();
                c.strokeStyle = r ? this.o.fgColor : this.fgColor ;
                c.arc(this.xy, this.xy, this.radius, sat, eat, false);
            c.stroke();
        };

        this.cancel = function () {
            this.val(this.v);
        };
    };

    $.fn.dial = $.fn.knob = function (o) {
        return this.each(
            function () {
                var d = new k.Dial();
                d.o = o;
                d.$ = $(this);
                d.run();
            }
        ).parent();
    };

})(jQuery);;
(function($) {
    "use strict";

    $.fn.htmlClean = function() {
        this.contents().filter(function() {
            if (this.nodeType != 3) {
                $(this).htmlClean();
                return false;
            } else {
                //var $that = $(this);
                //var textContent = $that.text();
                //textContent = $.trim(textContent);
                //$that.text(textContent);

                return !/\S/.test(this.nodeValue);
            }
        }).remove();
        return this;
    };

})(jQuery);;
/* MediaMatch v.2.0.2 - Testing css media queries in Javascript. Authors & copyright (c) 2013: WebLinc, David Knight. */

window.matchMedia || (window.matchMedia = function (win) {
    'use strict';

    // Internal globals
    var _doc        = win.document,
        _viewport   = _doc.documentElement,
        _queries    = [],
        _queryID    = 0,
        _type       = '',
        _features   = {},
                    // only screen
                    // only screen and
                    // not screen
                    // not screen and
                    // screen
                    // screen and
        _typeExpr   = /\s*(only|not)?\s*(screen|print|[a-z\-]+)\s*(and)?\s*/i,
                    // (-vendor-min-width: 300px)
                    // (min-width: 300px)
                    // (width: 300px)
                    // (width)
                    // (orientation: portrait|landscape)
        _mediaExpr  = /^\s*\(\s*(-[a-z]+-)?(min-|max-)?([a-z\-]+)\s*(:?\s*([0-9]+(\.[0-9]+)?|portrait|landscape)(px|em|dppx|dpcm|rem|%|in|cm|mm|ex|pt|pc|\/([0-9]+(\.[0-9]+)?))?)?\s*\)\s*$/,
        _timer      = 0,

        // Helper methods

        /*
            _matches
         */
        _matches = function (media) {
            // screen and (min-width: 400px), screen and (max-width: 500px)
            var mql         = (media.indexOf(',') !== -1 && media.split(',')) || [media],
                mqIndex     = mql.length - 1,
                mqLength    = mqIndex,
                mq          = null,

                // not screen, screen
                negateType      = null,
                negateTypeFound = '',
                negateTypeIndex = 0,
                negate          = false,
                type            = '',

                // (min-width: 400px), (min-width)
                exprListStr = '',
                exprList    = null,
                exprIndex   = 0,
                exprLength  = 0,
                expr        = null,

                prefix      = '',
                length      = '',
                unit        = '',
                value       = '',
                feature     = '',

                match       = false;

            if (media === '') {
                return true;
            }

            do {
                mq          = mql[mqLength - mqIndex];
                negate      = false;
                negateType  = mq.match(_typeExpr);

                if (negateType) {
                    negateTypeFound = negateType[0];
                    negateTypeIndex = negateType.index;
                }

                if (!negateType || ((mq.substring(0, negateTypeIndex).indexOf('(') === -1) && (negateTypeIndex || (!negateType[3] && negateTypeFound !== negateType.input)))) {
                    match = false;
                    continue;
                }

                exprListStr = mq;

                negate = negateType[1] === 'not';

                if (!negateTypeIndex) {
                    type        =  negateType[2];
                    exprListStr = mq.substring(negateTypeFound.length);
                }

                // Test media type
                // Test type against this device or if 'all' or empty ''
                match       = type === _type || type === 'all' || type === '';

                exprList    = (exprListStr.indexOf(' and ') !== -1 && exprListStr.split(' and ')) || [exprListStr];
                exprIndex   = exprList.length - 1;
                exprLength  = exprIndex;

                if (match && exprIndex >= 0 && exprListStr !== '') {
                    do {
                        expr = exprList[exprIndex].match(_mediaExpr);

                        if (!expr || !_features[expr[3]]) {
                            match = false;
                            break;
                        }

                        prefix  = expr[2];
                        length  = expr[5];
                        value   = length;
                        unit    = expr[7];
                        feature = _features[expr[3]];

                        // Convert unit types
                        if (unit) {
                            if (unit === 'px') {
                                // If unit is px
                                value = Number(length);
                            } else if (unit === 'em' || unit === 'rem') {
                                // Convert relative length unit to pixels
                                // Assumed base font size is 16px
                                value = 16 * length;
                            } else if (expr[8]) {
                                // Convert aspect ratio to decimal
                                value = (length / expr[8]).toFixed(2);
                            } else if (unit === 'dppx') {
                                // Convert resolution dppx unit to pixels
                                value = length * 96;
                            } else if (unit === 'dpcm') {
                                // Convert resolution dpcm unit to pixels
                                value = length * 0.3937;
                            } else {
                                // default
                                value = Number(length);
                            }
                        }

                        // Test for prefix min or max
                        // Test value against feature
                        if (prefix === 'min-' && value) {
                            match = feature >= value;
                        } else if (prefix === 'max-' && value) {
                            match = feature <= value;
                        } else if (value) {
                            match = feature === value;
                        } else {
                            match = !!feature;
                        }

                        // If 'match' is false, break loop
                        // Continue main loop through query list
                        if (!match) {
                            break;
                        }
                    } while (exprIndex--);
                }

                // If match is true, break loop
                // Once matched, no need to check other queries
                if (match) {
                    break;
                }
            } while (mqIndex--);

            return negate ? !match : match;
        },

        /*
            _setFeature
         */
        _setFeature = function () {
            // Sets properties of '_features' that change on resize and/or orientation.
            var w   = win.innerWidth || _viewport.clientWidth,
                h   = win.innerHeight || _viewport.clientHeight,
                dw  = win.screen.width,
                dh  = win.screen.height,
                c   = win.screen.colorDepth,
                x   = win.devicePixelRatio;

            _features.width                     = w;
            _features.height                    = h;
            _features['aspect-ratio']           = (w / h).toFixed(2);
            _features['device-width']           = dw;
            _features['device-height']          = dh;
            _features['device-aspect-ratio']    = (dw / dh).toFixed(2);
            _features.color                     = c;
            _features['color-index']            = Math.pow(2, c);
            _features.orientation               = (h >= w ? 'portrait' : 'landscape');
            _features.resolution                = (x && x * 96) || win.screen.deviceXDPI || 96;
            _features['device-pixel-ratio']     = x || 1;
        },

        /*
            _watch
         */
        _watch = function () {
            clearTimeout(_timer);

            _timer = setTimeout(function () {
                var query   = null,
                    qIndex  = _queryID - 1,
                    qLength = qIndex,
                    match   = false;

                if (qIndex >= 0) {
                    _setFeature();

                    do {
                        query = _queries[qLength - qIndex];

                        if (query) {
                            match = _matches(query.mql.media);

                            if ((match && !query.mql.matches) || (!match && query.mql.matches)) {
                                query.mql.matches = match;

                                if (query.listeners) {
                                    for (var i = 0, il = query.listeners.length; i < il; i++) {
                                        if (query.listeners[i]) {
                                            query.listeners[i].call(win, query.mql);
                                        }
                                    }
                                }
                            }
                        }
                    } while(qIndex--);
                }

                
            }, 10);
        },

        /*
            _init
         */
        _init = function () {
            var head        = _doc.getElementsByTagName('head')[0],
                style       = _doc.createElement('style'),
                info        = null,
                typeList    = ['screen', 'print', 'speech', 'projection', 'handheld', 'tv', 'braille', 'embossed', 'tty'],
                typeIndex   = 0,
                typeLength  = typeList.length,
                cssText     = '#mediamatchjs { position: relative; z-index: 0; }',
                eventPrefix = '',
                addEvent    = win.addEventListener || (eventPrefix = 'on') && win.attachEvent;

            style.type  = 'text/css';
            style.id    = 'mediamatchjs';

            head.appendChild(style);

            // Must be placed after style is inserted into the DOM for IE
            info = (win.getComputedStyle && win.getComputedStyle(style)) || style.currentStyle;

            // Create media blocks to test for media type
            for ( ; typeIndex < typeLength; typeIndex++) {
                cssText += '@media ' + typeList[typeIndex] + ' { #mediamatchjs { position: relative; z-index: ' + typeIndex + ' } }';
            }

            // Add rules to style element
            if (style.styleSheet) {
                style.styleSheet.cssText = cssText;
            } else {
                style.textContent = cssText;
            }

            // Get media type
            _type = typeList[(info.zIndex * 1) || 0];

            head.removeChild(style);

            _setFeature();

            // Set up listeners
            addEvent(eventPrefix + 'resize', _watch);
            addEvent(eventPrefix + 'orientationchange', _watch);
        };

    _init();

    /*
        A list of parsed media queries, ex. screen and (max-width: 400px), screen and (max-width: 800px)
    */
    return function (media) {
        var id  = _queryID,
            mql = {
                matches         : false,
                media           : media,
                addListener     : function addListener(listener) {
                    _queries[id].listeners || (_queries[id].listeners = []);
                    listener && _queries[id].listeners.push(listener);
                },
                removeListener  : function removeListener(listener) {
                    var query   = _queries[id],
                        i       = 0,
                        il      = 0;

                    if (!query) {
                        return;
                    }

                    il = query.listeners.length;

                    for ( ; i < il; i++) {
                        if (query.listeners[i] === listener) {
                            query.listeners.splice(i, 1);
                        }
                    }
                }
            };

        if (media === '') {
            mql.matches = true;
            return mql;
        }

        mql.matches = _matches(media);

        _queryID = _queries.push({
            mql         : mql,
            listeners   : null
        });

        return mql;
    };
}(window));;
// enquire.js v2.0.2 - Awesome Media Queries in JavaScript
// Copyright (c) 2013 Nick Williams - http://wicky.nillia.ms/enquire.js
// License: MIT (http://www.opensource.org/licenses/mit-license.php)

;(function(global) {

'use strict';

var matchMedia = global.matchMedia;

    /*jshint -W098 */
    /**
     * Helper function for iterating over a collection
     *
     * @param collection
     * @param fn
     */
    function each(collection, fn) {
        var i      = 0,
            length = collection.length,
            cont;

        for(i; i < length; i++) {
            cont = fn(collection[i], i);
            if(cont === false) {
                break; //allow early exit
            }
        }
    }

    /**
     * Helper function for determining whether target object is an array
     *
     * @param target the object under test
     * @return {Boolean} true if array, false otherwise
     */
    function isArray(target) {
        return Object.prototype.toString.apply(target) === '[object Array]';
    }

    /**
     * Helper function for determining whether target object is a function
     *
     * @param target the object under test
     * @return {Boolean} true if function, false otherwise
     */
    function isFunction(target) {
        return typeof target === 'function';
    }

/**
 * Delegate to handle a media query being matched and unmatched.
 *
 * @param {object} options
 * @param {function} options.match callback for when the media query is matched
 * @param {function} [options.unmatch] callback for when the media query is unmatched
 * @param {function} [options.setup] one-time callback triggered the first time a query is matched
 * @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched?
 * @constructor
 */
function QueryHandler(options) {
    this.options = options;
    !options.deferSetup && this.setup();
}
QueryHandler.prototype = {

    /**
     * coordinates setup of the handler
     *
     * @function
     */
    setup : function() {
        if(this.options.setup) {
            this.options.setup();
        }
        this.initialised = true;
    },

    /**
     * coordinates setup and triggering of the handler
     *
     * @function
     */
    on : function() {
        !this.initialised && this.setup();
        this.options.match && this.options.match();
    },

    /**
     * coordinates the unmatch event for the handler
     *
     * @function
     */
    off : function() {
        this.options.unmatch && this.options.unmatch();
    },

    /**
     * called when a handler is to be destroyed.
     * delegates to the destroy or unmatch callbacks, depending on availability.
     *
     * @function
     */
    destroy : function() {
        this.options.destroy ? this.options.destroy() : this.off();
    },

    /**
     * determines equality by reference.
     * if object is supplied compare options, if function, compare match callback
     *
     * @function
     * @param {object || function} [target] the target for comparison
     */
    equals : function(target) {
        return this.options === target || this.options.match === target;
    }

};
/**
 * Represents a single media query, manages it's state and registered handlers for this query
 *
 * @constructor
 * @param {string} query the media query string
 * @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design
 */
function MediaQuery(query, isUnconditional) {
    this.query = query;
    this.isUnconditional = isUnconditional;
    this.handlers = [];
    this.mql = matchMedia(query);

    var self = this;
    this.listener = function(mql) {
        self.mql = mql;
        self.assess();
    };
    this.mql.addListener(this.listener);
}
MediaQuery.prototype = {

    /**
     * add a handler for this query, triggering if already active
     *
     * @param {object} handler
     * @param {function} handler.match callback for when query is activated
     * @param {function} [handler.unmatch] callback for when query is deactivated
     * @param {function} [handler.setup] callback for immediate execution when a query handler is registered
     * @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched?
     */
    addHandler : function(handler) {
        var qh = new QueryHandler(handler);
        this.handlers.push(qh);

        this.matches() && qh.on();
    },

    /**
     * removes the given handler from the collection, and calls it's destroy methods
     * 
     * @param {object || function} handler the handler to remove
     */
    removeHandler : function(handler) {
        var handlers = this.handlers;
        each(handlers, function(h, i) {
            if(h.equals(handler)) {
                h.destroy();
                return !handlers.splice(i,1); //remove from array and exit each early
            }
        });
    },

    /**
     * Determine whether the media query should be considered a match
     * 
     * @return {Boolean} true if media query can be considered a match, false otherwise
     */
    matches : function() {
        return this.mql.matches || this.isUnconditional;
    },

    /**
     * Clears all handlers and unbinds events
     */
    clear : function() {
        each(this.handlers, function(handler) {
            handler.destroy();
        });
        this.mql.removeListener(this.listener);
        this.handlers.length = 0; //clear array
    },

    /*
     * Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match
     */
    assess : function() {
        var action = this.matches() ? 'on' : 'off';

        each(this.handlers, function(handler) {
            handler[action]();
        });
    }
};
/**
 * Allows for registration of query handlers.
 * Manages the query handler's state and is responsible for wiring up browser events
 *
 * @constructor
 */
function MediaQueryDispatch () {
    if(!matchMedia) {
        throw new Error('matchMedia not present, legacy browsers require a polyfill');
    }

    this.queries = {};
    this.browserIsIncapable = !matchMedia('only all').matches;
}

MediaQueryDispatch.prototype = {

    /**
     * Registers a handler for the given media query
     *
     * @param {string} q the media query
     * @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers
     * @param {function} options.match fired when query matched
     * @param {function} [options.unmatch] fired when a query is no longer matched
     * @param {function} [options.setup] fired when handler first triggered
     * @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched
     * @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers
     */
    register : function(q, options, shouldDegrade) {
        var queries         = this.queries,
            isUnconditional = shouldDegrade && this.browserIsIncapable;

        if(!queries[q]) {
            queries[q] = new MediaQuery(q, isUnconditional);
        }

        //normalise to object in an array
        if(isFunction(options)) {
            options = { match : options };
        }
        if(!isArray(options)) {
            options = [options];
        }
        each(options, function(handler) {
            queries[q].addHandler(handler);
        });

        return this;
    },

    /**
     * unregisters a query and all it's handlers, or a specific handler for a query
     *
     * @param {string} q the media query to target
     * @param {object || function} [handler] specific handler to unregister
     */
    unregister : function(q, handler) {
        var query = this.queries[q];

        if(query) {
            if(handler) {
                query.removeHandler(handler);
            }
            else {
                query.clear();
                delete this.queries[q];
            }
        }

        return this;
    }
};

global.enquire = global.enquire || new MediaQueryDispatch();

}(this));;
/*! LAB.js (LABjs :: Loading And Blocking JavaScript)
    v2.0.3 (c) Kyle Simpson
    MIT License
*/

(function(global){
	var _$LAB = global.$LAB,
	
		// constants for the valid keys of the options object
		_UseLocalXHR = "UseLocalXHR",
		_AlwaysPreserveOrder = "AlwaysPreserveOrder",
		_AllowDuplicates = "AllowDuplicates",
		_CacheBust = "CacheBust",
		/*!START_DEBUG*/_Debug = "Debug",/*!END_DEBUG*/
		_BasePath = "BasePath",
		
		// stateless variables used across all $LAB instances
		root_page = /^[^?#]*\//.exec(location.href)[0],
		root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
		append_to = document.head || document.getElementsByTagName("head"),
		
		// inferences... ick, but still necessary
		opera_or_gecko = (global.opera && Object.prototype.toString.call(global.opera) == "[object Opera]") || ("MozAppearance" in document.documentElement.style),

/*!START_DEBUG*/
		// console.log() and console.error() wrappers
		log_msg = function(){}, 
		log_error = log_msg,
/*!END_DEBUG*/
		
		// feature sniffs (yay!)
		test_script_elem = document.createElement("script"),
		explicit_preloading = typeof test_script_elem.preload == "boolean", // http://wiki.whatwg.org/wiki/Script_Execution_Control#Proposal_1_.28Nicholas_Zakas.29
		real_preloading = explicit_preloading || (test_script_elem.readyState && test_script_elem.readyState == "uninitialized"), // will a script preload with `src` set before DOM append?
		script_ordered_async = !real_preloading && test_script_elem.async === true, // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
		
		// XHR preloading (same-domain) and cache-preloading (remote-domain) are the fallbacks (for some browsers)
		xhr_or_cache_preloading = !real_preloading && !script_ordered_async && !opera_or_gecko
	;

/*!START_DEBUG*/
	// define console wrapper functions if applicable
	if (global.console && global.console.log) {
		if (!global.console.error) global.console.error = global.console.log;
		log_msg = function(msg) { global.console.log(msg); };
		log_error = function(msg,err) { global.console.error(msg,err); };
	}
/*!END_DEBUG*/

	// test for function
	function is_func(func) { return Object.prototype.toString.call(func) == "[object Function]"; }

	// test for array
	function is_array(arr) { return Object.prototype.toString.call(arr) == "[object Array]"; }

	// make script URL absolute/canonical
	function canonical_uri(src,base_path) {
		var absolute_regex = /^\w+\:\/\//;
		
		// is `src` is protocol-relative (begins with // or ///), prepend protocol
		if (/^\/\/\/?/.test(src)) {
			src = location.protocol + src;
		}
		// is `src` page-relative? (not an absolute URL, and not a domain-relative path, beginning with /)
		else if (!absolute_regex.test(src) && src.charAt(0) != "/") {
			// prepend `base_path`, if any
			src = (base_path || "") + src;
		}
		// make sure to return `src` as absolute
		return absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src);
	}

	// merge `source` into `target`
	function merge_objs(source,target) {
		for (var k in source) { if (source.hasOwnProperty(k)) {
			target[k] = source[k]; // TODO: does this need to be recursive for our purposes?
		}}
		return target;
	}

	// does the chain group have any ready-to-execute scripts?
	function check_chain_group_scripts_ready(chain_group) {
		var any_scripts_ready = false;
		for (var i=0; i<chain_group.scripts.length; i++) {
			if (chain_group.scripts[i].ready && chain_group.scripts[i].exec_trigger) {
				any_scripts_ready = true;
				chain_group.scripts[i].exec_trigger();
				chain_group.scripts[i].exec_trigger = null;
			}
		}
		return any_scripts_ready;
	}

	// creates a script load listener
	function create_script_load_listener(elem,registry_item,flag,onload) {
		elem.onload = elem.onreadystatechange = function() {
			if ((elem.readyState && elem.readyState != "complete" && elem.readyState != "loaded") || registry_item[flag]) return;
			elem.onload = elem.onreadystatechange = null;
			onload();
		};
	}

	// script executed handler
	function script_executed(registry_item) {
		registry_item.ready = registry_item.finished = true;
		for (var i=0; i<registry_item.finished_listeners.length; i++) {
			registry_item.finished_listeners[i]();
		}
		registry_item.ready_listeners = [];
		registry_item.finished_listeners = [];
	}

	// make the request for a scriptha
	function request_script(chain_opts,script_obj,registry_item,onload,preload_this_script) {
		// setTimeout() "yielding" prevents some weird race/crash conditions in older browsers
		setTimeout(function(){
			var script, src = script_obj.real_src, xhr;
			
			// don't proceed until `append_to` is ready to append to
			if ("item" in append_to) { // check if `append_to` ref is still a live node list
				if (!append_to[0]) { // `append_to` node not yet ready
					// try again in a little bit -- note: will re-call the anonymous function in the outer setTimeout, not the parent `request_script()`
					setTimeout(arguments.callee,25);
					return;
				}
				// reassign from live node list ref to pure node ref -- avoids nasty IE bug where changes to DOM invalidate live node lists
				append_to = append_to[0];
			}
			script = document.createElement("script");
			if (script_obj.type) script.type = script_obj.type;
			if (script_obj.charset) script.charset = script_obj.charset;
			
			// should preloading be used for this script?
			if (preload_this_script) {
				// real script preloading?
				if (real_preloading) {
					/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("start script preload: "+src);/*!END_DEBUG*/
					registry_item.elem = script;
					if (explicit_preloading) { // explicit preloading (aka, Zakas' proposal)
						script.preload = true;
						script.onpreload = onload;
					}
					else {
						script.onreadystatechange = function(){
							if (script.readyState == "loaded") onload();
						};
					}
					script.src = src;
					// NOTE: no append to DOM yet, appending will happen when ready to execute
				}
				// same-domain and XHR allowed? use XHR preloading
				else if (preload_this_script && src.indexOf(root_domain) == 0 && chain_opts[_UseLocalXHR]) {
					xhr = new XMLHttpRequest(); // note: IE never uses XHR (it supports true preloading), so no more need for ActiveXObject fallback for IE <= 7
					/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("start script preload (xhr): "+src);/*!END_DEBUG*/
					xhr.onreadystatechange = function() {
						if (xhr.readyState == 4) {
							xhr.onreadystatechange = function(){}; // fix a memory leak in IE
							registry_item.text = xhr.responseText + "\n//@ sourceURL=" + src; // http://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
							onload();
						}
					};
					xhr.open("GET",src);
					xhr.send();
				}
				// as a last resort, use cache-preloading
				else {
					/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("start script preload (cache): "+src);/*!END_DEBUG*/
					script.type = "text/cache-script";
					create_script_load_listener(script,registry_item,"ready",function() {
						append_to.removeChild(script);
						onload();
					});
					script.src = src;
					append_to.insertBefore(script,append_to.firstChild);
				}
			}
			// use async=false for ordered async? parallel-load-serial-execute http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
			else if (script_ordered_async) {
				/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("start script load (ordered async): "+src);/*!END_DEBUG*/
				script.async = false;
				create_script_load_listener(script,registry_item,"finished",onload);
				script.src = src;
				append_to.insertBefore(script,append_to.firstChild);
			}
			// otherwise, just a normal script element
			else {
				/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("start script load: "+src);/*!END_DEBUG*/
				create_script_load_listener(script,registry_item,"finished",onload);
				script.src = src;
				append_to.insertBefore(script,append_to.firstChild);
			}
		},0);
	}
		
	// create a clean instance of $LAB
	function create_sandbox() {
		var global_defaults = {},
			can_use_preloading = real_preloading || xhr_or_cache_preloading,
			queue = [],
			registry = {},
			instanceAPI
		;
		
		// global defaults
		global_defaults[_UseLocalXHR] = true;
		global_defaults[_AlwaysPreserveOrder] = false;
		global_defaults[_AllowDuplicates] = false;
		global_defaults[_CacheBust] = false;
		/*!START_DEBUG*/global_defaults[_Debug] = false;/*!END_DEBUG*/
		global_defaults[_BasePath] = "";

		// execute a script that has been preloaded already
		function execute_preloaded_script(chain_opts,script_obj,registry_item) {
			var script;
			
			function preload_execute_finished() {
				if (script != null) { // make sure this only ever fires once
					script = null;
					script_executed(registry_item);
				}
			}
			
			if (registry[script_obj.src].finished) return;
			if (!chain_opts[_AllowDuplicates]) registry[script_obj.src].finished = true;
			
			script = registry_item.elem || document.createElement("script");
			if (script_obj.type) script.type = script_obj.type;
			if (script_obj.charset) script.charset = script_obj.charset;
			create_script_load_listener(script,registry_item,"finished",preload_execute_finished);
			
			// script elem was real-preloaded
			if (registry_item.elem) {
				registry_item.elem = null;
			}
			// script was XHR preloaded
			else if (registry_item.text) {
				script.onload = script.onreadystatechange = null;	// script injection doesn't fire these events
				script.text = registry_item.text;
			}
			// script was cache-preloaded
			else {
				script.src = script_obj.real_src;
			}
			append_to.insertBefore(script,append_to.firstChild);

			// manually fire execution callback for injected scripts, since events don't fire
			if (registry_item.text) {
				preload_execute_finished();
			}
		}
	
		// process the script request setup
		function do_script(chain_opts,script_obj,chain_group,preload_this_script) {
			var registry_item,
				registry_items,
				ready_cb = function(){ script_obj.ready_cb(script_obj,function(){ execute_preloaded_script(chain_opts,script_obj,registry_item); }); },
				finished_cb = function(){ script_obj.finished_cb(script_obj,chain_group); }
			;
			
			script_obj.src = canonical_uri(script_obj.src,chain_opts[_BasePath]);
			script_obj.real_src = script_obj.src + 
				// append cache-bust param to URL?
				(chain_opts[_CacheBust] ? ((/\?.*$/.test(script_obj.src) ? "&_" : "?_") + ~~(Math.random()*1E9) + "=") : "")
			;
			
			if (!registry[script_obj.src]) registry[script_obj.src] = {items:[],finished:false};
			registry_items = registry[script_obj.src].items;

			// allowing duplicates, or is this the first recorded load of this script?
			if (chain_opts[_AllowDuplicates] || registry_items.length == 0) {
				registry_item = registry_items[registry_items.length] = {
					ready:false,
					finished:false,
					ready_listeners:[ready_cb],
					finished_listeners:[finished_cb]
				};

				request_script(chain_opts,script_obj,registry_item,
					// which callback type to pass?
					(
					 	(preload_this_script) ? // depends on script-preloading
						function(){
							registry_item.ready = true;
							for (var i=0; i<registry_item.ready_listeners.length; i++) {
								registry_item.ready_listeners[i]();
							}
							registry_item.ready_listeners = [];
						} :
						function(){ script_executed(registry_item); }
					),
					// signal if script-preloading should be used or not
					preload_this_script
				);
			}
			else {
				registry_item = registry_items[0];
				if (registry_item.finished) {
					finished_cb();
				}
				else {
					registry_item.finished_listeners.push(finished_cb);
				}
			}
		}

		// creates a closure for each separate chain spawned from this $LAB instance, to keep state cleanly separated between chains
		function create_chain() {
			var chainedAPI,
				chain_opts = merge_objs(global_defaults,{}),
				chain = [],
				exec_cursor = 0,
				scripts_currently_loading = false,
				group
			;
			
			// called when a script has finished preloading
			function chain_script_ready(script_obj,exec_trigger) {
				/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("script preload finished: "+script_obj.real_src);/*!END_DEBUG*/
				script_obj.ready = true;
				script_obj.exec_trigger = exec_trigger;
				advance_exec_cursor(); // will only check for 'ready' scripts to be executed
			}

			// called when a script has finished executing
			function chain_script_executed(script_obj,chain_group) {
				/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("script execution finished: "+script_obj.real_src);/*!END_DEBUG*/
				script_obj.ready = script_obj.finished = true;
				script_obj.exec_trigger = null;
				// check if chain group is all finished
				for (var i=0; i<chain_group.scripts.length; i++) {
					if (!chain_group.scripts[i].finished) return;
				}
				// chain_group is all finished if we get this far
				chain_group.finished = true;
				advance_exec_cursor();
			}

			// main driver for executing each part of the chain
			function advance_exec_cursor() {
				while (exec_cursor < chain.length) {
					if (is_func(chain[exec_cursor])) {
						/*!START_DEBUG*/if (chain_opts[_Debug]) log_msg("$LAB.wait() executing: "+chain[exec_cursor]);/*!END_DEBUG*/
						try { chain[exec_cursor++](); } catch (err) {
							/*!START_DEBUG*/if (chain_opts[_Debug]) log_error("$LAB.wait() error caught: ",err);/*!END_DEBUG*/
						}
						continue;
					}
					else if (!chain[exec_cursor].finished) {
						if (check_chain_group_scripts_ready(chain[exec_cursor])) continue;
						break;
					}
					exec_cursor++;
				}
				// we've reached the end of the chain (so far)
				if (exec_cursor == chain.length) {
					scripts_currently_loading = false;
					group = false;
				}
			}
			
			// setup next chain script group
			function init_script_chain_group() {
				if (!group || !group.scripts) {
					chain.push(group = {scripts:[],finished:true});
				}
			}

			// API for $LAB chains
			chainedAPI = {
				// start loading one or more scripts
				script:function(){
					for (var i=0; i<arguments.length; i++) {
						(function(script_obj,script_list){
							var splice_args;
							
							if (!is_array(script_obj)) {
								script_list = [script_obj];
							}
							for (var j=0; j<script_list.length; j++) {
								init_script_chain_group();
								script_obj = script_list[j];
								
								if (is_func(script_obj)) script_obj = script_obj();
								if (!script_obj) continue;
								if (is_array(script_obj)) {
									// set up an array of arguments to pass to splice()
									splice_args = [].slice.call(script_obj); // first include the actual array elements we want to splice in
									splice_args.unshift(j,1); // next, put the `index` and `howMany` parameters onto the beginning of the splice-arguments array
									[].splice.apply(script_list,splice_args); // use the splice-arguments array as arguments for splice()
									j--; // adjust `j` to account for the loop's subsequent `j++`, so that the next loop iteration uses the same `j` index value
									continue;
								}
								if (typeof script_obj == "string") script_obj = {src:script_obj};
								script_obj = merge_objs(script_obj,{
									ready:false,
									ready_cb:chain_script_ready,
									finished:false,
									finished_cb:chain_script_executed
								});
								group.finished = false;
								group.scripts.push(script_obj);
								
								do_script(chain_opts,script_obj,group,(can_use_preloading && scripts_currently_loading));
								scripts_currently_loading = true;
								
								if (chain_opts[_AlwaysPreserveOrder]) chainedAPI.wait();
							}
						})(arguments[i],arguments[i]);
					}
					return chainedAPI;
				},
				// force LABjs to pause in execution at this point in the chain, until the execution thus far finishes, before proceeding
				wait:function(){
					if (arguments.length > 0) {
						for (var i=0; i<arguments.length; i++) {
							chain.push(arguments[i]);
						}
						group = chain[chain.length-1];
					}
					else group = false;
					
					advance_exec_cursor();
					
					return chainedAPI;
				}
			};

			// the first chain link API (includes `setOptions` only this first time)
			return {
				script:chainedAPI.script, 
				wait:chainedAPI.wait, 
				setOptions:function(opts){
					merge_objs(opts,chain_opts);
					return chainedAPI;
				}
			};
		}

		// API for each initial $LAB instance (before chaining starts)
		instanceAPI = {
			// main API functions
			setGlobalDefaults:function(opts){
				merge_objs(opts,global_defaults);
				return instanceAPI;
			},
			setOptions:function(){
				return create_chain().setOptions.apply(null,arguments);
			},
			script:function(){
				return create_chain().script.apply(null,arguments);
			},
			wait:function(){
				return create_chain().wait.apply(null,arguments);
			},

			// built-in queuing for $LAB `script()` and `wait()` calls
			// useful for building up a chain programmatically across various script locations, and simulating
			// execution of the chain
			queueScript:function(){
				queue[queue.length] = {type:"script", args:[].slice.call(arguments)};
				return instanceAPI;
			},
			queueWait:function(){
				queue[queue.length] = {type:"wait", args:[].slice.call(arguments)};
				return instanceAPI;
			},
			runQueue:function(){
				var $L = instanceAPI, len=queue.length, i=len, val;
				for (;--i>=0;) {
					val = queue.shift();
					$L = $L[val.type].apply(null,val.args);
				}
				return $L;
			},

			// rollback `[global].$LAB` to what it was before this file was loaded, the return this current instance of $LAB
			noConflict:function(){
				global.$LAB = _$LAB;
				return instanceAPI;
			},

			// create another clean instance of $LAB
			sandbox:function(){
				return create_sandbox();
			}
		};

		return instanceAPI;
	}

	// create the main instance of $LAB
	global.$LAB = create_sandbox();


	/* The following "hack" was suggested by Andrea Giammarchi and adapted from: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
	   NOTE: this hack only operates in FF and then only in versions where document.readyState is not present (FF < 3.6?).
	   
	   The hack essentially "patches" the **page** that LABjs is loaded onto so that it has a proper conforming document.readyState, so that if a script which does 
	   proper and safe dom-ready detection is loaded onto a page, after dom-ready has passed, it will still be able to detect this state, by inspecting the now hacked 
	   document.readyState property. The loaded script in question can then immediately trigger any queued code executions that were waiting for the DOM to be ready. 
	   For instance, jQuery 1.4+ has been patched to take advantage of document.readyState, which is enabled by this hack. But 1.3.2 and before are **not** safe or 
	   fixed by this hack, and should therefore **not** be lazy-loaded by script loader tools such as LABjs.
	*/ 
	(function(addEvent,domLoaded,handler){
		if (document.readyState == null && document[addEvent]){
			document.readyState = "loading";
			document[addEvent](domLoaded,handler = function(){
				document.removeEventListener(domLoaded,handler,false);
				document.readyState = "complete";
			},false);
		}
	})("addEventListener","DOMContentLoaded");

})(this);;
/*
 * Toastr
 * Copyright 2012-2015
 * Authors: John Papa, Hans Fjällemark, and Tim Ferrell.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * ARIA Support: Greta Krafsig
 *
 * Project: https://github.com/CodeSeven/toastr
 */
/* global define */
(function (define) {
    define(['jquery'], function ($) {
        return (function () {
            var $container;
            var listener;
            var toastId = 0;
            var toastType = {
                error: 'error',
                info: 'info',
                success: 'success',
                warning: 'warning'
            };

            var toastr = {
                clear: clear,
                remove: remove,
                error: error,
                getContainer: getContainer,
                info: info,
                options: {},
                subscribe: subscribe,
                success: success,
                version: '2.1.4',
                warning: warning
            };

            var previousToast;

            return toastr;

            ////////////////

            function error(message, title, optionsOverride) {
                return notify({
                    type: toastType.error,
                    iconClass: getOptions().iconClasses.error,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function getContainer(options, create) {
                if (!options) { options = getOptions(); }
                $container = $('#' + options.containerId);
                if ($container.length) {
                    return $container;
                }
                if (create) {
                    $container = createContainer(options);
                }
                return $container;
            }

            function info(message, title, optionsOverride) {
                return notify({
                    type: toastType.info,
                    iconClass: getOptions().iconClasses.info,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function subscribe(callback) {
                listener = callback;
            }

            function success(message, title, optionsOverride) {
                return notify({
                    type: toastType.success,
                    iconClass: getOptions().iconClasses.success,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function warning(message, title, optionsOverride) {
                return notify({
                    type: toastType.warning,
                    iconClass: getOptions().iconClasses.warning,
                    message: message,
                    optionsOverride: optionsOverride,
                    title: title
                });
            }

            function clear($toastElement, clearOptions) {
                var options = getOptions();
                if (!$container) { getContainer(options); }
                if (!clearToast($toastElement, options, clearOptions)) {
                    clearContainer(options);
                }
            }

            function remove($toastElement) {
                var options = getOptions();
                if (!$container) { getContainer(options); }
                if ($toastElement && $(':focus', $toastElement).length === 0) {
                    removeToast($toastElement);
                    return;
                }
                if ($container.children().length) {
                    $container.remove();
                }
            }

            // internal functions

            function clearContainer (options) {
                var toastsToClear = $container.children();
                for (var i = toastsToClear.length - 1; i >= 0; i--) {
                    clearToast($(toastsToClear[i]), options);
                }
            }

            function clearToast ($toastElement, options, clearOptions) {
                var force = clearOptions && clearOptions.force ? clearOptions.force : false;
                if ($toastElement && (force || $(':focus', $toastElement).length === 0)) {
                    $toastElement[options.hideMethod]({
                        duration: options.hideDuration,
                        easing: options.hideEasing,
                        complete: function () { removeToast($toastElement); }
                    });
                    return true;
                }
                return false;
            }

            function createContainer(options) {
                $container = $('<div/>')
                    .attr('id', options.containerId)
                    .addClass(options.positionClass);

                $container.appendTo($(options.target));
                return $container;
            }

            function getDefaults() {
                return {
                    tapToDismiss: true,
                    toastClass: 'toast',
                    containerId: 'toast-container',
                    debug: false,

                    showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery
                    showDuration: 300,
                    showEasing: 'swing', //swing and linear are built into jQuery
                    onShown: undefined,
                    hideMethod: 'fadeOut',
                    hideDuration: 1000,
                    hideEasing: 'swing',
                    onHidden: undefined,
                    closeMethod: false,
                    closeDuration: false,
                    closeEasing: false,
                    closeOnHover: true,

                    extendedTimeOut: 1000,
                    iconClasses: {
                        error: 'toast-error',
                        info: 'toast-info',
                        success: 'toast-success',
                        warning: 'toast-warning'
                    },
                    iconClass: 'toast-info',
                    positionClass: 'toast-top-right',
                    timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky
                    titleClass: 'toast-title',
                    messageClass: 'toast-message',
                    escapeHtml: false,
                    target: 'body',
                    closeHtml: '<button type="button">&times;</button>',
                    closeClass: 'toast-close-button',
                    newestOnTop: true,
                    preventDuplicates: false,
                    progressBar: false,
                    progressClass: 'toast-progress',
                    rtl: false
                };
            }

            function publish(args) {
                if (!listener) { return; }
                listener(args);
            }

            function notify(map) {
                var options = getOptions();
                var iconClass = map.iconClass || options.iconClass;

                if (typeof (map.optionsOverride) !== 'undefined') {
                    options = $.extend(options, map.optionsOverride);
                    iconClass = map.optionsOverride.iconClass || iconClass;
                }

                if (shouldExit(options, map)) { return; }

                toastId++;

                $container = getContainer(options, true);

                var intervalId = null;
                var $toastElement = $('<div/>');
                var $titleElement = $('<div/>');
                var $messageElement = $('<div/>');
                var $progressElement = $('<div/>');
                var $closeElement = $(options.closeHtml);
                var progressBar = {
                    intervalId: null,
                    hideEta: null,
                    maxHideTime: null
                };
                var response = {
                    toastId: toastId,
                    state: 'visible',
                    startTime: new Date(),
                    options: options,
                    map: map
                };

                personalizeToast();

                displayToast();

                handleEvents();

                publish(response);

                if (options.debug && console) {
                    console.log(response);
                }

                return $toastElement;

                function escapeHtml(source) {
                    if (source == null) {
                        source = '';
                    }

                    return source
                        .replace(/&/g, '&amp;')
                        .replace(/"/g, '&quot;')
                        .replace(/'/g, '&#39;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;');
                }

                function personalizeToast() {
                    setIcon();
                    setTitle();
                    setMessage();
                    setCloseButton();
                    setProgressBar();
                    setRTL();
                    setSequence();
                    setAria();
                }

                function setAria() {
                    var ariaValue = '';
                    switch (map.iconClass) {
                        case 'toast-success':
                        case 'toast-info':
                            ariaValue =  'polite';
                            break;
                        default:
                            ariaValue = 'assertive';
                    }
                    $toastElement.attr('aria-live', ariaValue);
                }

                function handleEvents() {
                    if (options.closeOnHover) {
                        $toastElement.hover(stickAround, delayedHideToast);
                    }

                    if (!options.onclick && options.tapToDismiss) {
                        $toastElement.click(hideToast);
                    }

                    if (options.closeButton && $closeElement) {
                        $closeElement.click(function (event) {
                            if (event.stopPropagation) {
                                event.stopPropagation();
                            } else if (event.cancelBubble !== undefined && event.cancelBubble !== true) {
                                event.cancelBubble = true;
                            }

                            if (options.onCloseClick) {
                                options.onCloseClick(event);
                            }

                            hideToast(true);
                        });
                    }

                    if (options.onclick) {
                        $toastElement.click(function (event) {
                            options.onclick(event);
                            hideToast();
                        });
                    }
                }

                function displayToast() {
                    $toastElement.hide();

                    $toastElement[options.showMethod](
                        {duration: options.showDuration, easing: options.showEasing, complete: options.onShown}
                    );

                    if (options.timeOut > 0) {
                        intervalId = setTimeout(hideToast, options.timeOut);
                        progressBar.maxHideTime = parseFloat(options.timeOut);
                        progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
                        if (options.progressBar) {
                            progressBar.intervalId = setInterval(updateProgress, 10);
                        }
                    }
                }

                function setIcon() {
                    if (map.iconClass) {
                        $toastElement.addClass(options.toastClass).addClass(iconClass);
                    }
                }

                function setSequence() {
                    if (options.newestOnTop) {
                        $container.prepend($toastElement);
                    } else {
                        $container.append($toastElement);
                    }
                }

                function setTitle() {
                    if (map.title) {
                        var suffix = map.title;
                        if (options.escapeHtml) {
                            suffix = escapeHtml(map.title);
                        }
                        $titleElement.append(suffix).addClass(options.titleClass);
                        $toastElement.append($titleElement);
                    }
                }

                function setMessage() {
                    if (map.message) {
                        var suffix = map.message;
                        if (options.escapeHtml) {
                            suffix = escapeHtml(map.message);
                        }
                        $messageElement.append(suffix).addClass(options.messageClass);
                        $toastElement.append($messageElement);
                    }
                }

                function setCloseButton() {
                    if (options.closeButton) {
                        $closeElement.addClass(options.closeClass).attr('role', 'button');
                        $toastElement.prepend($closeElement);
                    }
                }

                function setProgressBar() {
                    if (options.progressBar) {
                        $progressElement.addClass(options.progressClass);
                        $toastElement.prepend($progressElement);
                    }
                }

                function setRTL() {
                    if (options.rtl) {
                        $toastElement.addClass('rtl');
                    }
                }

                function shouldExit(options, map) {
                    if (options.preventDuplicates) {
                        if (map.message === previousToast) {
                            return true;
                        } else {
                            previousToast = map.message;
                        }
                    }
                    return false;
                }

                function hideToast(override) {
                    var method = override && options.closeMethod !== false ? options.closeMethod : options.hideMethod;
                    var duration = override && options.closeDuration !== false ?
                        options.closeDuration : options.hideDuration;
                    var easing = override && options.closeEasing !== false ? options.closeEasing : options.hideEasing;
                    if ($(':focus', $toastElement).length && !override) {
                        return;
                    }
                    clearTimeout(progressBar.intervalId);
                    return $toastElement[method]({
                        duration: duration,
                        easing: easing,
                        complete: function () {
                            removeToast($toastElement);
                            clearTimeout(intervalId);
                            if (options.onHidden && response.state !== 'hidden') {
                                options.onHidden();
                            }
                            response.state = 'hidden';
                            response.endTime = new Date();
                            publish(response);
                        }
                    });
                }

                function delayedHideToast() {
                    if (options.timeOut > 0 || options.extendedTimeOut > 0) {
                        intervalId = setTimeout(hideToast, options.extendedTimeOut);
                        progressBar.maxHideTime = parseFloat(options.extendedTimeOut);
                        progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
                    }
                }

                function stickAround() {
                    clearTimeout(intervalId);
                    progressBar.hideEta = 0;
                    $toastElement.stop(true, true)[options.showMethod](
                        {duration: options.showDuration, easing: options.showEasing}
                    );
                }

                function updateProgress() {
                    var percentage = ((progressBar.hideEta - (new Date().getTime())) / progressBar.maxHideTime) * 100;
                    $progressElement.width(percentage + '%');
                }
            }

            function getOptions() {
                return $.extend({}, getDefaults(), toastr.options);
            }

            function removeToast($toastElement) {
                if (!$container) { $container = getContainer(); }
                if ($toastElement.is(':visible')) {
                    return;
                }
                $toastElement.remove();
                $toastElement = null;
                if ($container.children().length === 0) {
                    $container.remove();
                    previousToast = undefined;
                }
            }

        })();
    });
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
    if (typeof module !== 'undefined' && module.exports) { //Node
        module.exports = factory(require('jquery'));
    } else {
        window.toastr = factory(window.jQuery);
    }
}));
;
"use strict"
// Module export pattern from
// https://github.com/umdjs/umd/blob/master/returnExports.js
;(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } 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();
    } else {
        // Browser globals (root is window)
        root.store = factory();
  }
}(this, function () {
	
	// Store.js
	var store = {},
		win = window,
		doc = win.document,
		localStorageName = 'localStorage',
		scriptTag = 'script',
		storage

	store.disabled = false
	store.version = '1.3.17'
	store.set = function(key, value) {}
	store.get = function(key, defaultVal) {}
	store.has = function(key) { return store.get(key) !== undefined }
	store.remove = function(key) {}
	store.clear = function() {}
	store.transact = function(key, defaultVal, transactionFn) {
		if (transactionFn == null) {
			transactionFn = defaultVal
			defaultVal = null
		}
		if (defaultVal == null) {
			defaultVal = {}
		}
		var val = store.get(key, defaultVal)
		transactionFn(val)
		store.set(key, val)
	}
	store.getAll = function() {}
	store.forEach = function() {}

	store.serialize = function(value) {
		return JSON.stringify(value)
	}
	store.deserialize = function(value) {
		if (typeof value != 'string') { return undefined }
		try { return JSON.parse(value) }
		catch(e) { return value || undefined }
	}

	// Functions to encapsulate questionable FireFox 3.6.13 behavior
	// when about.config::dom.storage.enabled === false
	// See https://github.com/marcuswestin/store.js/issues#issue/13
	function isLocalStorageNameSupported() {
		try { return (localStorageName in win && win[localStorageName]) }
		catch(err) { return false }
	}

	if (isLocalStorageNameSupported()) {
		storage = win[localStorageName]
		store.set = function(key, val) {
			if (val === undefined) { return store.remove(key) }
			storage.setItem(key, store.serialize(val))
			return val
		}
		store.get = function(key, defaultVal) {
			var val = store.deserialize(storage.getItem(key))
			return (val === undefined ? defaultVal : val)
		}
		store.remove = function(key) { storage.removeItem(key) }
		store.clear = function() { storage.clear() }
		store.getAll = function() {
			var ret = {}
			store.forEach(function(key, val) {
				ret[key] = val
			})
			return ret
		}
		store.forEach = function(callback) {
			for (var i=0; i<storage.length; i++) {
				var key = storage.key(i)
				callback(key, store.get(key))
			}
		}
	} else if (doc.documentElement.addBehavior) {
		var storageOwner,
			storageContainer
		// Since #userData storage applies only to specific paths, we need to
		// somehow link our data to a specific path.  We choose /favicon.ico
		// as a pretty safe option, since all browsers already make a request to
		// this URL anyway and being a 404 will not hurt us here.  We wrap an
		// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
		// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
		// since the iframe access rules appear to allow direct access and
		// manipulation of the document element, even for a 404 page.  This
		// document can be used instead of the current document (which would
		// have been limited to the current path) to perform #userData storage.
		try {
			storageContainer = new ActiveXObject('htmlfile')
			storageContainer.open()
			storageContainer.write('<'+scriptTag+'>document.w=window</'+scriptTag+'><iframe src="/favicon.ico"></iframe>')
			storageContainer.close()
			storageOwner = storageContainer.w.frames[0].document
			storage = storageOwner.createElement('div')
		} catch(e) {
			// somehow ActiveXObject instantiation failed (perhaps some special
			// security settings or otherwse), fall back to per-path storage
			storage = doc.createElement('div')
			storageOwner = doc.body
		}
		var withIEStorage = function(storeFunction) {
			return function() {
				var args = Array.prototype.slice.call(arguments, 0)
				args.unshift(storage)
				// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
				// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
				storageOwner.appendChild(storage)
				storage.addBehavior('#default#userData')
				storage.load(localStorageName)
				var result = storeFunction.apply(store, args)
				storageOwner.removeChild(storage)
				return result
			}
		}

		// In IE7, keys cannot start with a digit or contain certain chars.
		// See https://github.com/marcuswestin/store.js/issues/40
		// See https://github.com/marcuswestin/store.js/issues/83
		var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
		var ieKeyFix = function(key) {
			return key.replace(/^d/, '___$&').replace(forbiddenCharsRegex, '___')
		}
		store.set = withIEStorage(function(storage, key, val) {
			key = ieKeyFix(key)
			if (val === undefined) { return store.remove(key) }
			storage.setAttribute(key, store.serialize(val))
			storage.save(localStorageName)
			return val
		})
		store.get = withIEStorage(function(storage, key, defaultVal) {
			key = ieKeyFix(key)
			var val = store.deserialize(storage.getAttribute(key))
			return (val === undefined ? defaultVal : val)
		})
		store.remove = withIEStorage(function(storage, key) {
			key = ieKeyFix(key)
			storage.removeAttribute(key)
			storage.save(localStorageName)
		})
		store.clear = withIEStorage(function(storage) {
			var attributes = storage.XMLDocument.documentElement.attributes
			storage.load(localStorageName)
			while (attributes.length) {
				storage.removeAttribute(attributes[0].name)
			}
			storage.save(localStorageName)
		})
		store.getAll = function(storage) {
			var ret = {}
			store.forEach(function(key, val) {
				ret[key] = val
			})
			return ret
		}
		store.forEach = withIEStorage(function(storage, callback) {
			var attributes = storage.XMLDocument.documentElement.attributes
			for (var i=0, attr; attr=attributes[i]; ++i) {
				callback(attr.name, store.deserialize(storage.getAttribute(attr.name)))
			}
		})
	}

	try {
		var testKey = '__storejs__'
		store.set(testKey, testKey)
		if (store.get(testKey) != testKey) { store.disabled = true }
		store.remove(testKey)
	} catch(e) {
		store.disabled = true
	}
	store.enabled = !store.disabled
	
	return store
}));
;
// Chosen, a Select Box Enhancer for jQuery and Prototype
// by Patrick Filler for Harvest, http://getharvest.com
//
// Version 0.9.15
// Full source at https://github.com/harvesthq/chosen
// Copyright (c) 2011 Harvest http://getharvest.com

// MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md
// This file is generated by `cake build`, do not edit it by hand.
(function() {
  var SelectParser;

  SelectParser = (function() {
    function SelectParser() {
      this.options_index = 0;
      this.parsed = [];
    }

    SelectParser.prototype.add_node = function(child) {
      if (child.nodeName.toUpperCase() === "OPTGROUP") {
        return this.add_group(child);
      } else {
        return this.add_option(child);
      }
    };

    SelectParser.prototype.add_group = function(group) {
      var group_position, option, _i, _len, _ref, _results;
      group_position = this.parsed.length;
      this.parsed.push({
        array_index: group_position,
        group: true,
        label: group.label,
        children: 0,
        disabled: group.disabled
      });
      _ref = group.childNodes;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        _results.push(this.add_option(option, group_position, group.disabled));
      }
      return _results;
    };

    SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
      if (option.nodeName.toUpperCase() === "OPTION") {
        if (option.text !== "") {
          if (group_position != null) {
            this.parsed[group_position].children += 1;
          }
          this.parsed.push({
            array_index: this.parsed.length,
            options_index: this.options_index,
            value: option.value,
            text: option.text,
            html: option.innerHTML,
            selected: option.selected,
            disabled: group_disabled === true ? group_disabled : option.disabled,
            group_array_index: group_position,
            classes: option.className,
            style: option.style.cssText
          });
        } else {
          this.parsed.push({
            array_index: this.parsed.length,
            options_index: this.options_index,
            empty: true
          });
        }
        return this.options_index += 1;
      }
    };

    return SelectParser;

  })();

  SelectParser.select_to_array = function(select) {
    var child, parser, _i, _len, _ref;
    parser = new SelectParser();
    _ref = select.childNodes;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      child = _ref[_i];
      parser.add_node(child);
    }
    return parser.parsed;
  };

  this.SelectParser = SelectParser;

}).call(this);
/*
Chosen source: generate output using 'cake build'
Copyright (c) 2011 by Harvest
*/


(function() {
  var AbstractChosen, root;

  root = this;

  AbstractChosen = (function() {
    function AbstractChosen(form_field, options) {
      this.form_field = form_field;
      this.options = options != null ? options : {};
      if (!AbstractChosen.browser_is_supported()) {
        return;
      }
      this.is_multiple = this.form_field.multiple;
      this.set_default_text();
      this.set_default_values();
      this.setup();
      this.set_up_html();
      this.register_observers();
      this.finish_setup();
    }

    AbstractChosen.prototype.set_default_values = function() {
      var _this = this;
      this.click_test_action = function(evt) {
        return _this.test_active_click(evt);
      };
      this.activate_action = function(evt) {
        return _this.activate_field(evt);
      };
      this.active_field = false;
      this.mouse_on_container = false;
      this.results_showing = false;
      this.result_highlighted = null;
      this.result_single_selected = null;
      this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
      this.disable_search_threshold = this.options.disable_search_threshold || 0;
      this.disable_search = this.options.disable_search || false;
      this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
      this.search_contains = this.options.search_contains || false;
      this.single_backstroke_delete = this.options.single_backstroke_delete || false;
      this.max_selected_options = this.options.max_selected_options || Infinity;
      return this.inherit_select_classes = this.options.inherit_select_classes || false;
    };

    AbstractChosen.prototype.set_default_text = function() {
      if (this.form_field.getAttribute("data-placeholder")) {
        this.default_text = this.form_field.getAttribute("data-placeholder");
      } else if (this.is_multiple) {
        this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
      } else {
        this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
      }
      return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
    };

    AbstractChosen.prototype.mouse_enter = function() {
      return this.mouse_on_container = true;
    };

    AbstractChosen.prototype.mouse_leave = function() {
      return this.mouse_on_container = false;
    };

    AbstractChosen.prototype.input_focus = function(evt) {
      var _this = this;
      if (this.is_multiple) {
        if (!this.active_field) {
          return setTimeout((function() {
            return _this.container_mousedown();
          }), 50);
        }
      } else {
        if (!this.active_field) {
          return this.activate_field();
        }
      }
    };

    AbstractChosen.prototype.input_blur = function(evt) {
      var _this = this;
      if (!this.mouse_on_container) {
        this.active_field = false;
        return setTimeout((function() {
          return _this.blur_test();
        }), 100);
      }
    };

    AbstractChosen.prototype.result_add_option = function(option) {
      var classes, style;
      if (!option.disabled) {
        option.dom_id = this.container_id + "_o_" + option.array_index;
        classes = option.selected && this.is_multiple ? [] : ["active-result"];
        if (option.selected) {
          classes.push("result-selected");
        }
        if (option.group_array_index != null) {
          classes.push("group-option");
        }
        if (option.classes !== "") {
          classes.push(option.classes);
        }
        style = option.style.cssText !== "" ? " style=\"" + option.style + "\"" : "";
        return '<li id="' + option.dom_id + '" class="' + classes.join(' ') + '"' + style + '>' + option.html + '</li>';
      } else {
        return "";
      }
    };

    AbstractChosen.prototype.results_update_field = function() {
      this.set_default_text();
      if (!this.is_multiple) {
        this.results_reset_cleanup();
      }
      this.result_clear_highlight();
      this.result_single_selected = null;
      return this.results_build();
    };

    AbstractChosen.prototype.results_toggle = function() {
      if (this.results_showing) {
        return this.results_hide();
      } else {
        return this.results_show();
      }
    };

    AbstractChosen.prototype.results_search = function(evt) {
      if (this.results_showing) {
        return this.winnow_results();
      } else {
        return this.results_show();
      }
    };

    AbstractChosen.prototype.choices_count = function() {
      var option, _i, _len, _ref;
      if (this.selected_option_count != null) {
        return this.selected_option_count;
      }
      this.selected_option_count = 0;
      _ref = this.form_field.options;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        if (option.selected) {
          this.selected_option_count += 1;
        }
      }
      return this.selected_option_count;
    };

    AbstractChosen.prototype.choices_click = function(evt) {
      evt.preventDefault();
      if (!this.results_showing) {
        return this.results_show();
      }
    };

    AbstractChosen.prototype.keyup_checker = function(evt) {
      var stroke, _ref;
      stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
      this.search_field_scale();
      switch (stroke) {
        case 8:
          if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
            return this.keydown_backstroke();
          } else if (!this.pending_backstroke) {
            this.result_clear_highlight();
            return this.results_search();
          }
          break;
        case 13:
          evt.preventDefault();
          if (this.results_showing) {
            return this.result_select(evt);
          }
          break;
        case 27:
          if (this.results_showing) {
            this.results_hide();
          }
          return true;
        case 9:
        case 38:
        case 40:
        case 16:
        case 91:
        case 17:
          break;
        default:
          return this.results_search();
      }
    };

    AbstractChosen.prototype.generate_field_id = function() {
      var new_id;
      new_id = this.generate_random_id();
      this.form_field.id = new_id;
      return new_id;
    };

    AbstractChosen.prototype.generate_random_char = function() {
      var chars, newchar, rand;
      chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      rand = Math.floor(Math.random() * chars.length);
      return newchar = chars.substring(rand, rand + 1);
    };

    AbstractChosen.prototype.container_width = function() {
      if (this.options.width != null) {
        return this.options.width;
      } else {
        return "" + this.form_field.offsetWidth + "px";
      }
    };

    AbstractChosen.browser_is_supported = function() {
      var _ref;
      if (window.navigator.appName === "Microsoft Internet Explorer") {
        return (null !== (_ref = document.documentMode) && _ref >= 8);
      }
      return true;
    };

    AbstractChosen.default_multiple_text = "Select Some Options";

    AbstractChosen.default_single_text = "Select an Option";

    AbstractChosen.default_no_result_text = "No results match";

    return AbstractChosen;

  })();

  root.AbstractChosen = AbstractChosen;

}).call(this);
/*
Chosen source: generate output using 'cake build'
Copyright (c) 2011 by Harvest
*/


/*
Please note - this is a customized version of May 2013 build.
Modifications need to be merged into current version.
All changes are marked with "Customization" comment
*/


(function() {
  var $, Chosen, root, _ref,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  root = this;

  $ = jQuery;

  $.fn.extend({
    chosen: function(options) {
      if (!AbstractChosen.browser_is_supported()) {
        return this;
      }
      return this.each(function(input_field) {
        var $this;
        $this = $(this);
        if (!$this.hasClass("chzn-done")) {
          return $this.data('chosen', new Chosen(this, options));
        }
      });
    }
  });

  Chosen = (function(_super) {
    __extends(Chosen, _super);

    function Chosen() {
      _ref = Chosen.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    Chosen.prototype.setup = function() {
      this.form_field_jq = $(this.form_field);
      this.current_selectedIndex = this.form_field.selectedIndex;
      return this.is_rtl = this.form_field_jq.hasClass("chzn-rtl");
    };

    Chosen.prototype.finish_setup = function() {
      return this.form_field_jq.addClass("chzn-done");
    };

    Chosen.prototype.set_up_html = function() {
      var container_classes, container_props;
      this.container_id = this.form_field.id.length ? this.form_field.id.replace(/[^\w]/g, '_') : this.generate_field_id();
      this.container_id += "_chzn";
      container_classes = ["chzn-container"];
      container_classes.push("chzn-container-" + (this.is_multiple ? "multi" : "single"));
      if (this.inherit_select_classes && this.form_field.className) {
        container_classes.push(this.form_field.className);
      }
      if (this.is_rtl) {
        container_classes.push("chzn-rtl");
      }
      container_props = {
        'id': this.container_id,
        'class': container_classes.join(' '),
        'style': "width: " + (this.container_width()) + ";",
        'title': this.form_field.title
      };
      this.container = $("<div />", container_props);
      if (this.is_multiple) {
        this.container.html('<ul class="chzn-choices"><li class="search-field"><input type="text" value="' + this.default_text + '" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chzn-drop"><ul class="chzn-results"></ul></div>');
      } else {
        this.container.html('<a href="javascript:void(0)" class="chzn-single chzn-default" aria-label="' + this.default_text + '"><span>' + this.default_text + '</span><div class="chzn-search"><input type="text" autocomplete="off" /></div><div><b></b></div></a><div class="chzn-drop"><ul class="chzn-results"></ul></div>');
      }
      this.form_field_jq.hide().after(this.container);
      this.dropdown = this.container.find('div.chzn-drop').first();
      this.search_field = this.container.find('input').first();
      this.search_results = this.container.find('ul.chzn-results').first();
      this.search_field_scale();
      this.search_no_results = this.container.find('li.no-results').first();
      if (this.is_multiple) {
        this.search_choices = this.container.find('ul.chzn-choices').first();
        this.search_container = this.container.find('li.search-field').first();
      } else {
        this.search_container = this.container.find('div.chzn-search').first();
        this.selected_item = this.container.find('.chzn-single').first();
      }
      this.results_build();
      this.set_tab_index_initial();
      this.set_label_behavior();
      return this.form_field_jq.trigger("liszt:ready", {
        chosen: this
      });
    };

    Chosen.prototype.register_observers = function() {
      var _this = this;
      this.container.mousedown(function(evt) {
        _this.container_mousedown(evt);
      });
      this.container.mouseup(function(evt) {
        _this.container_mouseup(evt);
      });
      this.container.mouseenter(function(evt) {
        _this.mouse_enter(evt);
      });
      this.container.mouseleave(function(evt) {
        _this.mouse_leave(evt);
      });
      this.search_results.mouseup(function(evt) {
        _this.search_results_mouseup(evt);
      });
      this.search_results.mouseover(function(evt) {
        _this.search_results_mouseover(evt);
      });
      this.search_results.mouseout(function(evt) {
        _this.search_results_mouseout(evt);
      });
      this.search_results.bind('mousewheel DOMMouseScroll', function(evt) {
        _this.search_results_mousewheel(evt);
      });
      this.form_field_jq.bind("liszt:updated", function(evt) {
        _this.results_update_field(evt);
      });
      this.form_field_jq.bind("liszt:activate", function(evt) {
        _this.activate_field(evt);
      });
      this.form_field_jq.bind("liszt:open", function(evt) {
        _this.container_mousedown(evt);
      });
      this.search_field.blur(function(evt) {
        _this.input_blur(evt);
      });
      this.search_field.keyup(function(evt) {
        _this.keyup_checker(evt);
      });
      this.search_field.keydown(function(evt) {
        _this.keydown_checker(evt);
      });
      this.search_field.focus(function(evt) {
        _this.input_focus(evt);
      });
      if (!this.is_multiple) {
        this.selected_item.focus(function(evt) {
          _this.selected_item_focus(evt);
        });
      }
      if (this.is_multiple) {
        return this.search_choices.click(function(evt) {
          _this.choices_click(evt);
        });
      } else {
        return this.container.click(function(evt) {
          evt.preventDefault();
        });
      }
    };

    Chosen.prototype.search_field_disabled = function() {
      this.is_disabled = this.form_field_jq[0].disabled;
      if (this.is_disabled) {
        this.container.addClass('chzn-disabled');
        this.search_field[0].disabled = true;
        if (!this.is_multiple) {
          this.selected_item.unbind("focus", this.activate_action);
        }
        return this.close_field();
      } else {
        this.container.removeClass('chzn-disabled');
        this.search_field[0].disabled = false;
        if (!this.is_multiple) {
          return this.selected_item.bind("focus", this.activate_action);
        }
      }
    };

    Chosen.prototype.container_mousedown = function(evt) {
      if (!this.is_disabled) {
        if (evt && evt.type === "mousedown" && !this.results_showing) {
          evt.preventDefault();
        }
        if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) {
          if (!this.active_field) {
            if (this.is_multiple) {
              this.search_field.val("");
            }
            $(document).click(this.click_test_action);
            this.results_show();
          } else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chzn-single").length)) {
            evt.preventDefault();
            this.results_toggle();
          }
          return this.activate_field();
        }
      }
    };

    Chosen.prototype.container_mouseup = function(evt) {
      if (evt.target.nodeName === "ABBR" && !this.is_disabled) {
        return this.results_reset(evt);
      }
    };

    Chosen.prototype.search_results_mousewheel = function(evt) {
      var delta, _ref1, _ref2;
      delta = -((_ref1 = evt.originalEvent) != null ? _ref1.wheelDelta : void 0) || ((_ref2 = evt.originialEvent) != null ? _ref2.detail : void 0);
      if (delta != null) {
        evt.preventDefault();
        if (evt.type === 'DOMMouseScroll') {
          delta = delta * 40;
        }
        return this.search_results.scrollTop(delta + this.search_results.scrollTop());
      }
    };

    Chosen.prototype.blur_test = function(evt) {
      if (!this.active_field && this.container.hasClass("chzn-container-active")) {
        return this.close_field();
      }
    };

    Chosen.prototype.close_field = function() {
      $(document).unbind("click", this.click_test_action);
      this.active_field = false;
      this.results_hide();
      this.container.removeClass("chzn-container-active");
      this.winnow_results_clear();
      this.clear_backstroke();
      this.show_search_field_default();
      return this.search_field_scale();
    };

    Chosen.prototype.activate_field = function() {
      this.container.addClass("chzn-container-active");
      this.active_field = true;
      this.search_field.val(this.search_field.val());
      return this.search_field.focus();
    };

    Chosen.prototype.test_active_click = function(evt) {
      if ($(evt.target).parents('#' + this.container_id).length) {
        return this.active_field = true;
      } else {
        return this.close_field();
      }
    };

    Chosen.prototype.results_build = function() {
      var content, data, _i, _len, _ref1;
      this.parsing = true;
      this.selected_option_count = null;
      this.results_data = root.SelectParser.select_to_array(this.form_field);
      if (this.is_multiple && this.choices_count() > 0) {
        this.search_choices.find("li.search-choice").remove();
      } else if (!this.is_multiple) {
        this.selected_item.addClass("chzn-default").find("span").text(this.default_text);
        if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) {
          this.container.addClass("chzn-container-single-nosearch");
        } else {
          this.container.removeClass("chzn-container-single-nosearch");
        }
      }
      content = '';
      _ref1 = this.results_data;
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        data = _ref1[_i];
        if (data.group) {
          content += this.result_add_group(data);
        } else if (!data.empty) {
          content += this.result_add_option(data);
          if (data.selected && this.is_multiple) {
            this.choice_build(data);
          } else if (data.selected && !this.is_multiple) {
            this.selected_item.removeClass("chzn-default").find("span").text(data.text);
            if (this.allow_single_deselect) {
              this.single_deselect_control_build();
            }
          }
        }
      }
      this.search_field_disabled();
      this.show_search_field_default();
      this.search_field_scale();
      this.search_results.html(content);
      return this.parsing = false;
    };

    Chosen.prototype.result_add_group = function(group) {
      if (!group.disabled) {
        group.dom_id = this.container_id + "_g_" + group.array_index;
        return '<li id="' + group.dom_id + '" class="group-result">' + $("<div />").text(group.label).html() + '</li>';
      } else {
        return "";
      }
    };

    Chosen.prototype.result_do_highlight = function(el) {
      var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
      if (el.length) {
        this.result_clear_highlight();
        this.result_highlight = el;
        this.result_highlight.addClass("highlighted");
        maxHeight = parseInt(this.search_results.css("maxHeight"), 10);
        visible_top = this.search_results.scrollTop();
        visible_bottom = maxHeight + visible_top;
        high_top = this.result_highlight.position().top + this.search_results.scrollTop();
        high_bottom = high_top + this.result_highlight.outerHeight();
        if (high_bottom >= visible_bottom) {
          return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0);
        } else if (high_top < visible_top) {
          return this.search_results.scrollTop(high_top);
        }
      }
    };

    Chosen.prototype.result_clear_highlight = function() {
      if (this.result_highlight) {
        this.result_highlight.removeClass("highlighted");
      }
      return this.result_highlight = null;
    };

    Chosen.prototype.results_show = function() {
      if (this.result_single_selected != null) {
        this.result_do_highlight(this.result_single_selected);
      } else if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
        this.form_field_jq.trigger("liszt:maxselected", {
          chosen: this
        });
        return false;
      }
      this.container.addClass("chzn-with-drop");
      this.form_field_jq.trigger("liszt:showing_dropdown", {
        chosen: this
      });
      this.results_showing = true;
      this.search_field.focus();
      this.search_field.val(this.search_field.val());
      this.winnow_results();
      return this.set_tab_index_on_show();
    };

    Chosen.prototype.results_hide = function() {
      var callback, context;
      this.result_clear_highlight();
      this.container.removeClass("chzn-with-drop");
      this.form_field_jq.trigger("liszt:hiding_dropdown", {
        chosen: this
      });
      this.results_showing = false;
      context = this;
      callback = function() {
        return context.set_tab_index_on_hide();
      };
      return setTimeout(callback, 0);
    };

    Chosen.prototype.set_tab_index_initial = function(el) {
      var ti;
      if (this.form_field_jq.attr("tabindex")) {
        ti = this.form_field_jq.attr("tabindex");
        this.form_field_jq.attr("tabindex", -1);
        return this.selected_item.attr("tabindex", ti);
      }
    };

    Chosen.prototype.set_tab_index_on_show = function(el) {
      var ti;
      if (!this.is_multiple) {
        ti = this.selected_item.attr("tabindex");
        if (ti !== "-1") {
          this.selected_item.attr("tabindex", -1);
          return this.search_field.attr("tabindex", ti);
        }
      }
    };

    Chosen.prototype.set_tab_index_on_hide = function(el) {
      var ti;
      if (!this.is_multiple) {
        ti = this.search_field.attr("tabindex");
        if (ti !== "-1") {
          this.selected_item.attr("tabindex", ti);
          return this.search_field.attr("tabindex", -1);
        }
      }
    };

    Chosen.prototype.set_label_behavior = function() {
      var _this = this;
      this.form_field_label = this.form_field_jq.parents("label");
      if (!this.form_field_label.length && this.form_field.id.length) {
        this.form_field_label = $("label[for='" + this.form_field.id + "']");
      }
      if (this.form_field_label.length > 0) {
        return this.form_field_label.click(function(evt) {
          if (_this.is_multiple) {
            return _this.container_mousedown(evt);
          } else {
            return _this.activate_field();
          }
        });
      }
    };

    Chosen.prototype.show_search_field_default = function() {
      if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
        this.search_field.val(this.default_text);
        return this.search_field.addClass("default");
      } else {
        this.search_field.val("");
        return this.search_field.removeClass("default");
      }
    };

    Chosen.prototype.search_results_mouseup = function(evt) {
      var target;
      target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
      if (target.length) {
        this.result_highlight = target;
        this.result_select(evt);
        return this.search_field.focus();
      }
    };

    Chosen.prototype.search_results_mouseover = function(evt) {
      var target;
      target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
      if (target) {
        return this.result_do_highlight(target);
      }
    };

    Chosen.prototype.search_results_mouseout = function(evt) {
      if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) {
        return this.result_clear_highlight();
      }
    };

    Chosen.prototype.choice_build = function(item) {
      var choice, close_link,
        _this = this;
      choice = $('<li />', {
        "class": "search-choice"
      }).html("<span>" + item.html + "</span>");
      if (item.disabled) {
        choice.addClass('search-choice-disabled');
      } else {
        close_link = $('<a />', {
          href: '#',
          "class": 'search-choice-close',
          rel: item.array_index
        });
        close_link.click(function(evt) {
          return _this.choice_destroy_link_click(evt);
        });
        choice.append(close_link);
      }
      return this.search_container.before(choice);
    };

    Chosen.prototype.choice_destroy_link_click = function(evt) {
      evt.preventDefault();
      evt.stopPropagation();
      if (!this.is_disabled) {
        return this.choice_destroy($(evt.target));
      }
    };

    Chosen.prototype.choice_destroy = function(link) {
      if (this.result_deselect(link.attr("rel"))) {
        this.show_search_field_default();
        if (this.is_multiple && this.choices_count() > 0 && this.search_field.val().length < 1) {
          this.results_hide();
        }
        link.parents('li').first().remove();
        return this.search_field_scale();
      }
    };

    Chosen.prototype.results_reset = function() {
      this.form_field.options[0].selected = true;
      this.selected_option_count = null;
      this.selected_item.find("span").text(this.default_text);
      if (!this.is_multiple) {
        this.selected_item.addClass("chzn-default");
      }
      this.show_search_field_default();
      this.results_reset_cleanup();
      this.form_field_jq.trigger("change");
      if (this.active_field) {
        return this.results_hide();
      }
    };

    Chosen.prototype.results_reset_cleanup = function() {
      this.current_selectedIndex = this.form_field.selectedIndex;
      return this.selected_item.find("abbr").remove();
    };

    Chosen.prototype.result_select = function(evt) {
      var high, high_id, item, position;
      if (this.result_highlight) {
        high = this.result_highlight;
        high_id = high.attr("id");
        this.result_clear_highlight();
        if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
          this.form_field_jq.trigger("liszt:maxselected", {
            chosen: this
          });
          return false;
        }
        if (this.is_multiple) {
          this.result_deactivate(high);
        } else {
          this.search_results.find(".result-selected").removeClass("result-selected");
          this.result_single_selected = high;
          this.selected_item.removeClass("chzn-default");
        }
        high.addClass("result-selected");
        position = high_id.substr(high_id.lastIndexOf("_") + 1);
        item = this.results_data[position];
        item.selected = true;
        this.form_field.options[item.options_index].selected = true;
        this.selected_option_count = null;
        if (this.is_multiple) {
          this.choice_build(item);
        } else {
          this.selected_item.find("span").first().text(item.text);
          if (this.allow_single_deselect) {
            this.single_deselect_control_build();
          }
        }
        if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) {
          this.results_hide();
        }
        this.search_field.val("");
        if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) {
          this.form_field_jq.trigger("change", {
            'selected': this.form_field.options[item.options_index].value
          });
        }
        this.current_selectedIndex = this.form_field.selectedIndex;
        return this.search_field_scale();
      }
    };

    Chosen.prototype.result_activate = function(el) {
      return el.addClass("active-result");
    };

    Chosen.prototype.result_deactivate = function(el) {
      return el.removeClass("active-result");
    };

    Chosen.prototype.result_deselect = function(pos) {
      var result, result_data;
      result_data = this.results_data[pos];
      if (!this.form_field.options[result_data.options_index].disabled) {
        result_data.selected = false;
        this.form_field.options[result_data.options_index].selected = false;
        this.selected_option_count = null;
        result = $("#" + this.container_id + "_o_" + pos);
        result.removeClass("result-selected").addClass("active-result").show();
        this.result_clear_highlight();
        this.winnow_results();
        this.form_field_jq.trigger("change", {
          deselected: this.form_field.options[result_data.options_index].value
        });
        this.search_field_scale();
        return true;
      } else {
        return false;
      }
    };

    Chosen.prototype.single_deselect_control_build = function() {
      if (!this.allow_single_deselect) {
        return;
      }
      if (!this.selected_item.find("abbr").length) {
        this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>");
      }
      return this.selected_item.addClass("chzn-single-with-deselect");
    };

    Chosen.prototype.winnow_results = function() {
      var found, option, part, parts, regex, regexAnchor, result, result_id, results, searchText, startpos, text, zregex, _i, _j, _len, _len1, _ref1;
      this.no_results_clear();
      results = 0;
      searchText = this.search_field.val() === this.default_text ? "" : $('<div/>').text($.trim(this.search_field.val())).html();
      regexAnchor = this.search_contains ? "" : "^";
      regex = new RegExp(regexAnchor + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
      zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
      _ref1 = this.results_data;
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        option = _ref1[_i];
        if (!option.disabled && !option.empty) {
          if (option.group) {
            $('#' + option.dom_id).css('display', 'none');
          } else if (!(this.is_multiple && option.selected)) {
            found = false;
            result_id = option.dom_id;
            result = $("#" + result_id);
            if (regex.test(option.html)) {
              found = true;
              results += 1;
            } else if (this.enable_split_word_search && (option.html.indexOf(" ") >= 0 || option.html.indexOf("[") === 0)) {
              parts = option.html.replace(/\[|\]/g, "").split(" ");
              if (parts.length) {
                for (_j = 0, _len1 = parts.length; _j < _len1; _j++) {
                  part = parts[_j];
                  if (regex.test(part)) {
                    found = true;
                    results += 1;
                  }
                }
              }
            }
            if (found) {
              if (searchText.length) {
                startpos = option.html.search(zregex);
                text = option.html.substr(0, startpos + searchText.length) + '</em>' + option.html.substr(startpos + searchText.length);
                text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
              } else {
                text = option.html;
              }
              result.html(text);
              this.result_activate(result);
              if (option.group_array_index != null) {
                $("#" + this.results_data[option.group_array_index].dom_id).css('display', 'list-item');
              }
            } else {
              if (this.result_highlight && result_id === this.result_highlight.attr('id')) {
                this.result_clear_highlight();
              }
              this.result_deactivate(result);
            }
          }
        }
      }
      if (results < 1 && searchText.length) {
        return this.no_results(searchText);
      } else {
        return this.winnow_results_set_highlight();
      }
    };

    Chosen.prototype.winnow_results_clear = function() {
      var li, lis, _i, _len, _results;
      this.search_field.val("");
      lis = this.search_results.find("li");
      _results = [];
      for (_i = 0, _len = lis.length; _i < _len; _i++) {
        li = lis[_i];
        li = $(li);
        if (li.hasClass("group-result")) {
          _results.push(li.css('display', 'auto'));
        } else if (!this.is_multiple || !li.hasClass("result-selected")) {
          _results.push(this.result_activate(li));
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    };

    Chosen.prototype.winnow_results_set_highlight = function() {
      var do_high, selected_results;
      if (!this.result_highlight) {
        selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : [];
        do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first();
        if (do_high != null) {
          return this.result_do_highlight(do_high);
        }
      }
    };

    Chosen.prototype.no_results = function(terms) {
      var no_results_html;
      no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>');
      no_results_html.find("span").first().html(terms);
      return this.search_results.append(no_results_html);
    };

    Chosen.prototype.no_results_clear = function() {
      return this.search_results.find(".no-results").remove();
    };

    Chosen.prototype.keydown_arrow = function() {
      var first_active, next_sib;
      if (!this.result_highlight) {
        first_active = this.search_results.find("li.active-result").first();
        if (first_active) {
          this.result_do_highlight($(first_active));
        }
      } else if (this.results_showing) {
        next_sib = this.result_highlight.nextAll("li.active-result").first();
        if (next_sib) {
          this.result_do_highlight(next_sib);
        }
      }
      if (!this.results_showing) {
        return this.results_show();
      }
    };

    Chosen.prototype.keyup_arrow = function() {
      var prev_sibs;
      if (!this.results_showing && !this.is_multiple) {
        return this.results_show();
      } else if (this.result_highlight) {
        prev_sibs = this.result_highlight.prevAll("li.active-result");
        if (prev_sibs.length) {
          return this.result_do_highlight(prev_sibs.first());
        } else {
          if (this.choices_count() > 0) {
            this.results_hide();
          }
          return this.result_clear_highlight();
        }
      }
    };

    Chosen.prototype.keydown_backstroke = function() {
      var next_available_destroy;
      if (this.pending_backstroke) {
        this.choice_destroy(this.pending_backstroke.find("a").first());
        return this.clear_backstroke();
      } else {
        next_available_destroy = this.search_container.siblings("li.search-choice").last();
        if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) {
          this.pending_backstroke = next_available_destroy;
          if (this.single_backstroke_delete) {
            return this.keydown_backstroke();
          } else {
            return this.pending_backstroke.addClass("search-choice-focus");
          }
        }
      }
    };

    Chosen.prototype.clear_backstroke = function() {
      if (this.pending_backstroke) {
        this.pending_backstroke.removeClass("search-choice-focus");
      }
      return this.pending_backstroke = null;
    };

    Chosen.prototype.keydown_checker = function(evt) {
      var stroke, _ref1;
      stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode;
      this.search_field_scale();
      if (stroke !== 8 && this.pending_backstroke) {
        this.clear_backstroke();
      }
      switch (stroke) {
        case 8:
          this.backstroke_length = this.search_field.val().length;
          break;
        case 9:
          if (this.results_showing && !this.is_multiple) {
            this.result_select(evt);
          }
          this.mouse_on_container = false;
          break;
        case 13:
          evt.preventDefault();
          break;
        case 38:
          evt.preventDefault();
          this.keyup_arrow();
          break;
        case 40:
          this.keydown_arrow();
          break;
      }
    };

    Chosen.prototype.search_field_scale = function() {
      var div, h, style, style_block, styles, w, _i, _len;
      if (this.is_multiple) {
        h = 0;
        w = 0;
        style_block = "position:absolute; left: -1000px; top: -1000px; display:none;";
        styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing'];
        for (_i = 0, _len = styles.length; _i < _len; _i++) {
          style = styles[_i];
          style_block += style + ":" + this.search_field.css(style) + ";";
        }
        div = $('<div />', {
          'style': style_block
        });
        div.text(this.search_field.val());
        $('body').append(div);
        w = div.width() + 25;
        div.remove();
        if (!this.f_width) {
          this.f_width = this.container.outerWidth();
        }
        if (w > this.f_width - 10) {
          w = this.f_width - 10;
        }
        return this.search_field.css({
          'width': w + 'px'
        });
      }
    };

    Chosen.prototype.selected_item_focus = function(evt) {
      return this.results_show();
    };

    Chosen.prototype.generate_random_id = function() {
      var string;
      string = "sel" + this.generate_random_char() + this.generate_random_char() + this.generate_random_char();
      while ($("#" + string).length > 0) {
        string += this.generate_random_char();
      }
      return string;
    };

    return Chosen;

  })(AbstractChosen);

  root.Chosen = Chosen;

}).call(this);
;
(function (window, $, undefined) {

    // WAVE reports empty links as errors - add hidden span to prevent this behavior
    $(document).ready(function () {
        var addThisTimer = setInterval(function () {
            if (window.addthis && window.addthis.addEventListener) {
                clearInterval(addThisTimer);
                $('.share-button-group svg')
                    .each(function() {
                        $(this).attr('focusable', 'false');
                    });
            }
        }, 100);
    });

})(window, jQuery);;
// Copyright 2013-2014 Kevin Cox

/*******************************************************************************
*                                                                              *
*  This software is provided 'as-is', without any express or implied           *
*  warranty. In no event will the authors be held liable for any damages       *
*  arising from the use of this software.                                      *
*                                                                              *
*  Permission is granted to anyone to use this software for any purpose,       *
*  including commercial applications, and to alter it and redistribute it      *
*  freely, subject to the following restrictions:                              *
*                                                                              *
*  1. The origin of this software must not be misrepresented; you must not     *
*     claim that you wrote the original software. If you use this software in  *
*     a product, an acknowledgment in the product documentation would be       *
*     appreciated but is not required.                                         *
*                                                                              *
*  2. Altered source versions must be plainly marked as such, and must not be  *
*     misrepresented as being the original software.                           *
*                                                                              *
*  3. This notice may not be removed or altered from any source distribution.  *
*                                                                              *
*******************************************************************************/

+function(){
"use strict";

var array = /\[([^\[]*)\]$/;

/// URL Regex.
/**
 * This regex splits the URL into parts.  The capture groups catch the important
 * bits.
 * 
 * Each section is optional, so to work on any part find the correct top level
 * `(...)?` and mess around with it.
 */
var regex = /^(?:([a-z]*):)?(?:\/\/)?(?:([^:@]*)(?::([^@]*))?@)?([0-9a-z-._]+)?(?::([0-9]*))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/i;
//               1 - scheme              2 - user    3 = pass    4 - host           5 - port  6 - path        7 - query    8 - hash

var noslash = ["mailto","bitcoin"];

var self = {
	/** Parse a query string.
	 *
	 * This function parses a query string (sometimes called the search
	 * string).  It takes a query string and returns a map of the results.
	 *
	 * Keys are considered to be everything up to the first '=' and values are
	 * everything afterwords.  Since URL-decoding is done after parsing, keys
	 * and values can have any values, however, '=' have to be encoded in keys
	 * while '?' and '&' have to be encoded anywhere (as they delimit the
	 * kv-pairs).
	 *
	 * Keys and values will always be strings, except if there is a key with no
	 * '=' in which case it will be considered a flag and will be set to true.
	 * Later values will override earlier values.
	 *
	 * Array keys are also supported.  By default keys in the form of `name[i]`
	 * will be returned like that as strings.  However, if you set the `array`
	 * flag in the options object they will be parsed into arrays.  Note that
	 * although the object returned is an `Array` object all keys will be
	 * written to it.  This means that if you have a key such as `k[forEach]`
	 * it will overwrite the `forEach` function on that array.  Also note that
	 * string properties always take precedence over array properties,
	 * irrespective of where they are in the query string.
	 *
	 *   url.get("array[1]=test&array[foo]=bar",{array:true}).array[1]  === "test"
	 *   url.get("array[1]=test&array[foo]=bar",{array:true}).array.foo === "bar"
	 *   url.get("array=notanarray&array[0]=1",{array:true}).array      === "notanarray"
	 *
	 * If array parsing is enabled keys in the form of `name[]` will
	 * automatically be given the next available index.  Note that this can be
	 * overwritten with later values in the query string.  For this reason is
	 * is best not to mix the two formats, although it is safe (and often
	 * useful) to add an automatic index argument to the end of a query string.
	 *
	 *   url.get("a[]=0&a[]=1&a[0]=2", {array:true})  -> {a:["2","1"]};
	 *   url.get("a[0]=0&a[1]=1&a[]=2", {array:true}) -> {a:["0","1","2"]};
	 *
	 * @param{string} q The query string (the part after the '?').
	 * @param{{full:boolean,array:boolean}=} opt Options.
	 *
	 * - full: If set `q` will be treated as a full url and `q` will be built.
	 *   by calling #parse to retrieve the query portion.
	 * - array: If set keys in the form of `key[i]` will be treated
	 *   as arrays/maps.
	 *
	 * @return{!Object.<string, string|Array>} The parsed result.
	 */
	"get": function(q, opt){
		q = q || "";
		if ( typeof opt          == "undefined" ) opt = {};
		if ( typeof opt["full"]  == "undefined" ) opt["full"] = false;
		if ( typeof opt["array"] == "undefined" ) opt["array"] = false;
		
		if ( opt["full"] === true )
		{
			q = self["parse"](q, {"get":false})["query"] || "";
		}
		
		var o = {};
		
		var c = q.split("&");
		for (var i = 0; i < c.length; i++)
		{
			if (!c[i].length) continue;
			
			var d = c[i].indexOf("=");
			var k = c[i], v = true;
			if ( d >= 0 )
			{
				k = c[i].substr(0, d);
				v = c[i].substr(d+1);
				
				v = decodeURIComponent(v);
			}
			
			if (opt["array"])
			{
				var inds = [];
				var ind;
				var curo = o;
				var curk = k;
				while (ind = curk.match(array)) // Array!
				{
					curk = curk.substr(0, ind.index);
					inds.unshift(decodeURIComponent(ind[1]));
				}
				curk = decodeURIComponent(curk);
				if (inds.some(function(i)
				{
					if ( typeof curo[curk] == "undefined" ) curo[curk] = [];
					if (!Array.isArray(curo[curk]))
					{
						//console.log("url.get: Array property "+curk+" already exists as string!");
						return true;
					}
					
					curo = curo[curk];
					
					if ( i === "" ) i = curo.length;
					
					curk = i;
				})) continue;
				curo[curk] = v;
				continue;
			}
			
			k = decodeURIComponent(k);
			
			//typeof o[k] == "undefined" || console.log("Property "+k+" already exists!");
			o[k] = v;
		}
		
		return o;
	},
	
	/** Build a get query from an object.
	 *
	 * This constructs a query string from the kv pairs in `data`.  Calling
	 * #get on the string returned should return an object identical to the one
	 * passed in except all non-boolean scalar types become strings and all
	 * object types become arrays (non-integer keys are still present, see
	 * #get's documentation for more details).
	 *
	 * This always uses array syntax for describing arrays.  If you want to
	 * serialize them differently (like having the value be a JSON array and
	 * have a plain key) you will need to do that before passing it in.
	 *
	 * All keys and values are supported (binary data anyone?) as they are
	 * properly URL-encoded and #get properly decodes.
	 *
	 * @param{Object} data The kv pairs.
	 * @param{string} prefix The properly encoded array key to put the
	 *   properties.  Mainly intended for internal use.
	 * @return{string} A URL-safe string.
	 */
	"buildget": function(data, prefix){
		var itms = [];
		for ( var k in data )
		{
			var ek = encodeURIComponent(k);
			if ( typeof prefix != "undefined" )
				ek = prefix+"["+ek+"]";
			
			var v = data[k];
			
			switch (typeof v)
			{
				case 'boolean':
					if(v) itms.push(ek);
					break;
				case 'number':
					v = v.toString();
				case 'string':
					itms.push(ek+"="+encodeURIComponent(v));
					break;
				case 'object':
					itms.push(self["buildget"](v, ek));
					break;
			}
		}
		return itms.join("&");
	},
	
	/** Parse a URL
	 * 
	 * This breaks up a URL into components.  It attempts to be very liberal
	 * and returns the best result in most cases.  This means that you can
	 * often pass in part of a URL and get correct categories back.  Notably,
	 * this works for emails and Jabber IDs, as well as adding a '?' to the
	 * beginning of a string will parse the whole thing as a query string.  If
	 * an item is not found the property will be undefined.  In some cases an
	 * empty string will be returned if the surrounding syntax but the actual
	 * value is empty (example: "://example.com" will give a empty string for
	 * scheme.)  Notably the host name will always be set to something.
	 * 
	 * Returned properties.
	 * 
	 * - **scheme:** The url scheme. (ex: "mailto" or "https")
	 * - **user:** The username.
	 * - **pass:** The password.
	 * - **host:** The hostname. (ex: "localhost", "123.456.7.8" or "example.com")
	 * - **port:** The port, as a number. (ex: 1337)
	 * - **path:** The path. (ex: "/" or "/about.html")
	 * - **query:** "The query string. (ex: "foo=bar&v=17&format=json")
	 * - **get:** The query string parsed with get.  If `opt.get` is `false` this
	 *   will be absent
	 * - **hash:** The value after the hash. (ex: "myanchor")
	 *   be undefined even if `query` is set.
	 *
	 * @param{string} url The URL to parse.
	 * @param{{get:Object}=} opt Options:
	 *
	 * - get: An options argument to be passed to #get or false to not call #get.
	 *    **DO NOT** set `full`.
	 *
	 * @return{!Object} An object with the parsed values.
	 */
	"parse": function(url, opt) {
		
		if ( typeof opt == "undefined" ) opt = {};
		
		var md = url.match(regex) || [];
		
		var r = {
			"url":    url,
			
			"scheme": md[1],
			"user":   md[2],
			"pass":   md[3],
			"host":   md[4],
			"port":   md[5] && +md[5],
			"path":   md[6],
			"query":  md[7],
			"hash":   md[8],
		};
		
		if ( opt.get !== false )
			r["get"] = r["query"] && self["get"](r["query"], opt.get);
		
		return r;
	},
	
	/** Build a URL from components.
	 * 
	 * This pieces together a url from the properties of the passed in object.
	 * In general passing the result of `parse()` should return the URL.  There
	 * may differences in the get string as the keys and values might be more
	 * encoded then they were originally were.  However, calling `get()` on the
	 * two values should yield the same result.
	 * 
	 * Here is how the parameters are used.
	 * 
	 *  - url: Used only if no other values are provided.  If that is the case
	 *     `url` will be returned verbatim.
	 *  - scheme: Used if defined.
	 *  - user: Used if defined.
	 *  - pass: Used if defined.
	 *  - host: Used if defined.
	 *  - path: Used if defined.
	 *  - query: Used only if `get` is not provided and non-empty.
	 *  - get: Used if non-empty.  Passed to #buildget and the result is used
	 *    as the query string.
	 *  - hash: Used if defined.
	 * 
	 * These are the options that are valid on the options object.
	 * 
	 *  - useemptyget: If truthy, a question mark will be appended for empty get
	 *    strings.  This notably makes `build()` and `parse()` fully symmetric.
	 *
	 * @param{Object} data The pieces of the URL.
	 * @param{Object} opt Options for building the url.
	 * @return{string} The URL.
	 */
	"build": function(data, opt){
		opt = opt || {};
		
		var r = "";
		
		if ( typeof data["scheme"] != "undefined" )
		{
			r += data["scheme"];
			r += (noslash.indexOf(data["scheme"])>=0)?":":"://";
		}
		if ( typeof data["user"] != "undefined" )
		{
			r += data["user"];
			if ( typeof data["pass"] == "undefined" )
			{
				r += "@";
			}
		}
		if ( typeof data["pass"] != "undefined" ) r += ":" + data["pass"] + "@";
		if ( typeof data["host"] != "undefined" ) r += data["host"];
		if ( typeof data["port"] != "undefined" ) r += ":" + data["port"];
		if ( typeof data["path"] != "undefined" ) r += data["path"];
		
		if (opt["useemptyget"])
		{
			if      ( typeof data["get"]   != "undefined" ) r += "?" + self["buildget"](data["get"]);
			else if ( typeof data["query"] != "undefined" ) r += "?" + data["query"];
		}
		else
		{
			// If .get use it.  If .get leads to empty, use .query.
			var q = data["get"] && self["buildget"](data["get"]) || data["query"];
			if (q) r += "?" + q;
		}
		
		if ( typeof data["hash"] != "undefined" ) r += "#" + data["hash"];
		
		return r || data["url"] || "";
	},
};

if ( typeof define != "undefined" && define["amd"] ) define(self);
else if ( typeof module != "undefined" ) module['exports'] = self;
else window["url"] = self;

}();
;
/*!
* inputmask.min.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2019 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.7
*/

(function(factory){if(typeof define==="function"&&define.amd){define(["./dependencyLibs/inputmask.dependencyLib","./global/window"],factory)}else if(typeof exports==="object"){module.exports=factory(require("./dependencyLibs/inputmask.dependencyLib"),require("./global/window"))}else{window.Inputmask=factory(window.dependencyLib||jQuery,window)}})(function($,window,undefined){var document=window.document,ua=navigator.userAgent,ie=ua.indexOf("MSIE ")>0||ua.indexOf("Trident/")>0,mobile=isInputEventSupported("touchstart"),iemobile=/iemobile/i.test(ua),iphone=/iphone/i.test(ua)&&!iemobile;function Inputmask(alias,options,internal){if(!(this instanceof Inputmask)){return new Inputmask(alias,options,internal)}this.el=undefined;this.events={};this.maskset=undefined;this.refreshValue=false;if(internal!==true){if($.isPlainObject(alias)){options=alias}else{options=options||{};if(alias)options.alias=alias}this.opts=$.extend(true,{},this.defaults,options);this.noMasksCache=options&&options.definitions!==undefined;this.userOptions=options||{};this.isRTL=this.opts.numericInput;resolveAlias(this.opts.alias,options,this.opts)}}Inputmask.prototype={dataAttribute:"data-inputmask",defaults:{placeholder:"_",optionalmarker:["[","]"],quantifiermarker:["{","}"],groupmarker:["(",")"],alternatormarker:"|",escapeChar:"\\",mask:null,regex:null,oncomplete:$.noop,onincomplete:$.noop,oncleared:$.noop,repeat:0,greedy:false,autoUnmask:false,removeMaskOnSubmit:false,clearMaskOnLostFocus:true,insertMode:true,clearIncomplete:false,alias:null,onKeyDown:$.noop,onBeforeMask:null,onBeforePaste:function(pastedValue,opts){return $.isFunction(opts.onBeforeMask)?opts.onBeforeMask.call(this,pastedValue,opts):pastedValue},onBeforeWrite:null,onUnMask:null,showMaskOnFocus:true,showMaskOnHover:true,onKeyValidation:$.noop,skipOptionalPartCharacter:" ",numericInput:false,rightAlign:false,undoOnEscape:true,radixPoint:"",_radixDance:false,groupSeparator:"",keepStatic:null,positionCaretOnTab:true,tabThrough:false,supportsInputType:["text","tel","url","password","search"],ignorables:[8,9,13,19,27,33,34,35,36,37,38,39,40,45,46,93,112,113,114,115,116,117,118,119,120,121,122,123,0,229],isComplete:null,preValidation:null,postValidation:null,staticDefinitionSymbol:undefined,jitMasking:false,nullable:true,inputEventOnly:false,noValuePatching:false,positionCaretOnClick:"lvp",casing:null,inputmode:"verbatim",colorMask:false,disablePredictiveText:false,importDataAttributes:true,shiftPositions:true},definitions:{9:{validator:"[0-9\uff11-\uff19]",definitionSymbol:"*"},a:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",definitionSymbol:"*"},"*":{validator:"[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"}},aliases:{},masksCache:{},mask:function(elems){var that=this;function importAttributeOptions(npt,opts,userOptions,dataAttribute){if(opts.importDataAttributes===true){var attrOptions=npt.getAttribute(dataAttribute),option,dataoptions,optionData,p;function importOption(option,optionData){optionData=optionData!==undefined?optionData:npt.getAttribute(dataAttribute+"-"+option);if(optionData!==null){if(typeof optionData==="string"){if(option.indexOf("on")===0)optionData=window[optionData];else if(optionData==="false")optionData=false;else if(optionData==="true")optionData=true}userOptions[option]=optionData}}if(attrOptions&&attrOptions!==""){attrOptions=attrOptions.replace(/'/g,'"');dataoptions=JSON.parse("{"+attrOptions+"}")}if(dataoptions){optionData=undefined;for(p in dataoptions){if(p.toLowerCase()==="alias"){optionData=dataoptions[p];break}}}importOption("alias",optionData);if(userOptions.alias){resolveAlias(userOptions.alias,userOptions,opts)}for(option in opts){if(dataoptions){optionData=undefined;for(p in dataoptions){if(p.toLowerCase()===option.toLowerCase()){optionData=dataoptions[p];break}}}importOption(option,optionData)}}$.extend(true,opts,userOptions);if(npt.dir==="rtl"||opts.rightAlign){npt.style.textAlign="right"}if(npt.dir==="rtl"||opts.numericInput){npt.dir="ltr";npt.removeAttribute("dir");opts.isRTL=true}return Object.keys(userOptions).length}if(typeof elems==="string"){elems=document.getElementById(elems)||document.querySelectorAll(elems)}elems=elems.nodeName?[elems]:elems;$.each(elems,function(ndx,el){var scopedOpts=$.extend(true,{},that.opts);if(importAttributeOptions(el,scopedOpts,$.extend(true,{},that.userOptions),that.dataAttribute)){var maskset=generateMaskSet(scopedOpts,that.noMasksCache);if(maskset!==undefined){if(el.inputmask!==undefined){el.inputmask.opts.autoUnmask=true;el.inputmask.remove()}el.inputmask=new Inputmask(undefined,undefined,true);el.inputmask.opts=scopedOpts;el.inputmask.noMasksCache=that.noMasksCache;el.inputmask.userOptions=$.extend(true,{},that.userOptions);el.inputmask.isRTL=scopedOpts.isRTL||scopedOpts.numericInput;el.inputmask.el=el;el.inputmask.maskset=maskset;$.data(el,"_inputmask_opts",scopedOpts);maskScope.call(el.inputmask,{action:"mask"})}}});return elems&&elems[0]?elems[0].inputmask||this:this},option:function(options,noremask){if(typeof options==="string"){return this.opts[options]}else if(typeof options==="object"){$.extend(this.userOptions,options);if(this.el&&noremask!==true){this.mask(this.el)}return this}},unmaskedvalue:function(value){this.maskset=this.maskset||generateMaskSet(this.opts,this.noMasksCache);return maskScope.call(this,{action:"unmaskedvalue",value:value})},remove:function(){return maskScope.call(this,{action:"remove"})},getemptymask:function(){this.maskset=this.maskset||generateMaskSet(this.opts,this.noMasksCache);return maskScope.call(this,{action:"getemptymask"})},hasMaskedValue:function(){return!this.opts.autoUnmask},isComplete:function(){this.maskset=this.maskset||generateMaskSet(this.opts,this.noMasksCache);return maskScope.call(this,{action:"isComplete"})},getmetadata:function(){this.maskset=this.maskset||generateMaskSet(this.opts,this.noMasksCache);return maskScope.call(this,{action:"getmetadata"})},isValid:function(value){this.maskset=this.maskset||generateMaskSet(this.opts,this.noMasksCache);return maskScope.call(this,{action:"isValid",value:value})},format:function(value,metadata){this.maskset=this.maskset||generateMaskSet(this.opts,this.noMasksCache);return maskScope.call(this,{action:"format",value:value,metadata:metadata})},setValue:function(value){if(this.el){$(this.el).trigger("setvalue",[value])}},analyseMask:function(mask,regexMask,opts){var tokenizer=/(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?(?:\|[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,regexTokenizer=/\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,escaped=false,currentToken=new MaskToken,match,m,openenings=[],maskTokens=[],openingToken,currentOpeningToken,alternator,lastMatch,groupToken;function MaskToken(isGroup,isOptional,isQuantifier,isAlternator){this.matches=[];this.openGroup=isGroup||false;this.alternatorGroup=false;this.isGroup=isGroup||false;this.isOptional=isOptional||false;this.isQuantifier=isQuantifier||false;this.isAlternator=isAlternator||false;this.quantifier={min:1,max:1}}function insertTestDefinition(mtoken,element,position){position=position!==undefined?position:mtoken.matches.length;var prevMatch=mtoken.matches[position-1];if(regexMask){if(element.indexOf("[")===0||escaped&&/\\d|\\s|\\w]/i.test(element)||element==="."){mtoken.matches.splice(position++,0,{fn:new RegExp(element,opts.casing?"i":""),optionality:false,newBlockMarker:prevMatch===undefined?"master":prevMatch.def!==element,casing:null,def:element,placeholder:undefined,nativeDef:element})}else{if(escaped)element=element[element.length-1];$.each(element.split(""),function(ndx,lmnt){prevMatch=mtoken.matches[position-1];mtoken.matches.splice(position++,0,{fn:null,optionality:false,newBlockMarker:prevMatch===undefined?"master":prevMatch.def!==lmnt&&prevMatch.fn!==null,casing:null,def:opts.staticDefinitionSymbol||lmnt,placeholder:opts.staticDefinitionSymbol!==undefined?lmnt:undefined,nativeDef:(escaped?"'":"")+lmnt})})}escaped=false}else{var maskdef=(opts.definitions?opts.definitions[element]:undefined)||Inputmask.prototype.definitions[element];if(maskdef&&!escaped){mtoken.matches.splice(position++,0,{fn:maskdef.validator?typeof maskdef.validator=="string"?new RegExp(maskdef.validator,opts.casing?"i":""):new function(){this.test=maskdef.validator}:new RegExp("."),optionality:false,newBlockMarker:prevMatch===undefined?"master":prevMatch.def!==(maskdef.definitionSymbol||element),casing:maskdef.casing,def:maskdef.definitionSymbol||element,placeholder:maskdef.placeholder,nativeDef:element})}else{mtoken.matches.splice(position++,0,{fn:null,optionality:false,newBlockMarker:prevMatch===undefined?"master":prevMatch.def!==element&&prevMatch.fn!==null,casing:null,def:opts.staticDefinitionSymbol||element,placeholder:opts.staticDefinitionSymbol!==undefined?element:undefined,nativeDef:(escaped?"'":"")+element});escaped=false}}}function verifyGroupMarker(maskToken){if(maskToken&&maskToken.matches){$.each(maskToken.matches,function(ndx,token){var nextToken=maskToken.matches[ndx+1];if((nextToken===undefined||(nextToken.matches===undefined||nextToken.isQuantifier===false))&&token&&token.isGroup){token.isGroup=false;if(!regexMask){insertTestDefinition(token,opts.groupmarker[0],0);if(token.openGroup!==true){insertTestDefinition(token,opts.groupmarker[1])}}}verifyGroupMarker(token)})}}function defaultCase(){if(openenings.length>0){currentOpeningToken=openenings[openenings.length-1];insertTestDefinition(currentOpeningToken,m);if(currentOpeningToken.isAlternator){alternator=openenings.pop();for(var mndx=0;mndx<alternator.matches.length;mndx++){if(alternator.matches[mndx].isGroup)alternator.matches[mndx].isGroup=false}if(openenings.length>0){currentOpeningToken=openenings[openenings.length-1];currentOpeningToken.matches.push(alternator)}else{currentToken.matches.push(alternator)}}}else{insertTestDefinition(currentToken,m)}}function reverseTokens(maskToken){function reverseStatic(st){if(st===opts.optionalmarker[0])st=opts.optionalmarker[1];else if(st===opts.optionalmarker[1])st=opts.optionalmarker[0];else if(st===opts.groupmarker[0])st=opts.groupmarker[1];else if(st===opts.groupmarker[1])st=opts.groupmarker[0];return st}maskToken.matches=maskToken.matches.reverse();for(var match in maskToken.matches){if(maskToken.matches.hasOwnProperty(match)){var intMatch=parseInt(match);if(maskToken.matches[match].isQuantifier&&maskToken.matches[intMatch+1]&&maskToken.matches[intMatch+1].isGroup){var qt=maskToken.matches[match];maskToken.matches.splice(match,1);maskToken.matches.splice(intMatch+1,0,qt)}if(maskToken.matches[match].matches!==undefined){maskToken.matches[match]=reverseTokens(maskToken.matches[match])}else{maskToken.matches[match]=reverseStatic(maskToken.matches[match])}}}return maskToken}function groupify(matches){var groupToken=new MaskToken(true);groupToken.openGroup=false;groupToken.matches=matches;return groupToken}if(regexMask){opts.optionalmarker[0]=undefined;opts.optionalmarker[1]=undefined}while(match=regexMask?regexTokenizer.exec(mask):tokenizer.exec(mask)){m=match[0];if(regexMask){switch(m.charAt(0)){case"?":m="{0,1}";break;case"+":case"*":m="{"+m+"}";break}}if(escaped){defaultCase();continue}switch(m.charAt(0)){case"(?=":break;case"(?!":break;case"(?<=":break;case"(?<!":break;case opts.escapeChar:escaped=true;if(regexMask){defaultCase()}break;case opts.optionalmarker[1]:case opts.groupmarker[1]:openingToken=openenings.pop();openingToken.openGroup=false;if(openingToken!==undefined){if(openenings.length>0){currentOpeningToken=openenings[openenings.length-1];currentOpeningToken.matches.push(openingToken);if(currentOpeningToken.isAlternator){alternator=openenings.pop();for(var mndx=0;mndx<alternator.matches.length;mndx++){alternator.matches[mndx].isGroup=false;alternator.matches[mndx].alternatorGroup=false}if(openenings.length>0){currentOpeningToken=openenings[openenings.length-1];currentOpeningToken.matches.push(alternator)}else{currentToken.matches.push(alternator)}}}else{currentToken.matches.push(openingToken)}}else defaultCase();break;case opts.optionalmarker[0]:openenings.push(new MaskToken(false,true));break;case opts.groupmarker[0]:openenings.push(new MaskToken(true));break;case opts.quantifiermarker[0]:var quantifier=new MaskToken(false,false,true);m=m.replace(/[{}]/g,"");var mqj=m.split("|"),mq=mqj[0].split(","),mq0=isNaN(mq[0])?mq[0]:parseInt(mq[0]),mq1=mq.length===1?mq0:isNaN(mq[1])?mq[1]:parseInt(mq[1]);if(mq0==="*"||mq0==="+"){mq0=mq1==="*"?0:1}quantifier.quantifier={min:mq0,max:mq1,jit:mqj[1]};var matches=openenings.length>0?openenings[openenings.length-1].matches:currentToken.matches;match=matches.pop();if(match.isAlternator){matches.push(match);matches=match.matches;var groupToken=new MaskToken(true);var tmpMatch=matches.pop();matches.push(groupToken);matches=groupToken.matches;match=tmpMatch}if(!match.isGroup){match=groupify([match])}matches.push(match);matches.push(quantifier);break;case opts.alternatormarker:function groupQuantifier(matches){var lastMatch=matches.pop();if(lastMatch.isQuantifier){lastMatch=groupify([matches.pop(),lastMatch])}return lastMatch}if(openenings.length>0){currentOpeningToken=openenings[openenings.length-1];var subToken=currentOpeningToken.matches[currentOpeningToken.matches.length-1];if(currentOpeningToken.openGroup&&(subToken.matches===undefined||subToken.isGroup===false&&subToken.isAlternator===false)){lastMatch=openenings.pop()}else{lastMatch=groupQuantifier(currentOpeningToken.matches)}}else{lastMatch=groupQuantifier(currentToken.matches)}if(lastMatch.isAlternator){openenings.push(lastMatch)}else{if(lastMatch.alternatorGroup){alternator=openenings.pop();lastMatch.alternatorGroup=false}else{alternator=new MaskToken(false,false,false,true)}alternator.matches.push(lastMatch);openenings.push(alternator);if(lastMatch.openGroup){lastMatch.openGroup=false;var alternatorGroup=new MaskToken(true);alternatorGroup.alternatorGroup=true;openenings.push(alternatorGroup)}}break;default:defaultCase()}}while(openenings.length>0){openingToken=openenings.pop();currentToken.matches.push(openingToken)}if(currentToken.matches.length>0){verifyGroupMarker(currentToken);maskTokens.push(currentToken)}if(opts.numericInput||opts.isRTL){reverseTokens(maskTokens[0])}return maskTokens},positionColorMask:function(input,template){input.style.left=template.offsetLeft+"px"}};Inputmask.extendDefaults=function(options){$.extend(true,Inputmask.prototype.defaults,options)};Inputmask.extendDefinitions=function(definition){$.extend(true,Inputmask.prototype.definitions,definition)};Inputmask.extendAliases=function(alias){$.extend(true,Inputmask.prototype.aliases,alias)};Inputmask.format=function(value,options,metadata){return Inputmask(options).format(value,metadata)};Inputmask.unmask=function(value,options){return Inputmask(options).unmaskedvalue(value)};Inputmask.isValid=function(value,options){return Inputmask(options).isValid(value)};Inputmask.remove=function(elems){if(typeof elems==="string"){elems=document.getElementById(elems)||document.querySelectorAll(elems)}elems=elems.nodeName?[elems]:elems;$.each(elems,function(ndx,el){if(el.inputmask)el.inputmask.remove()})};Inputmask.setValue=function(elems,value){if(typeof elems==="string"){elems=document.getElementById(elems)||document.querySelectorAll(elems)}elems=elems.nodeName?[elems]:elems;$.each(elems,function(ndx,el){if(el.inputmask)el.inputmask.setValue(value);else $(el).trigger("setvalue",[value])})};Inputmask.escapeRegex=function(str){var specials=["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^"];return str.replace(new RegExp("(\\"+specials.join("|\\")+")","gim"),"\\$1")};Inputmask.keyCode={BACKSPACE:8,BACKSPACE_SAFARI:127,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,RIGHT:39,SPACE:32,TAB:9,UP:38,X:88,CONTROL:17};Inputmask.dependencyLib=$;function resolveAlias(aliasStr,options,opts){var aliasDefinition=Inputmask.prototype.aliases[aliasStr];if(aliasDefinition){if(aliasDefinition.alias)resolveAlias(aliasDefinition.alias,undefined,opts);$.extend(true,opts,aliasDefinition);$.extend(true,opts,options);return true}else if(opts.mask===null){opts.mask=aliasStr}return false}function generateMaskSet(opts,nocache){function generateMask(mask,metadata,opts){var regexMask=false;if(mask===null||mask===""){regexMask=opts.regex!==null;if(regexMask){mask=opts.regex;mask=mask.replace(/^(\^)(.*)(\$)$/,"$2")}else{regexMask=true;mask=".*"}}if(mask.length===1&&opts.greedy===false&&opts.repeat!==0){opts.placeholder=""}if(opts.repeat>0||opts.repeat==="*"||opts.repeat==="+"){var repeatStart=opts.repeat==="*"?0:opts.repeat==="+"?1:opts.repeat;mask=opts.groupmarker[0]+mask+opts.groupmarker[1]+opts.quantifiermarker[0]+repeatStart+","+opts.repeat+opts.quantifiermarker[1]}var masksetDefinition,maskdefKey=regexMask?"regex_"+opts.regex:opts.numericInput?mask.split("").reverse().join(""):mask;if(Inputmask.prototype.masksCache[maskdefKey]===undefined||nocache===true){masksetDefinition={mask:mask,maskToken:Inputmask.prototype.analyseMask(mask,regexMask,opts),validPositions:{},_buffer:undefined,buffer:undefined,tests:{},excludes:{},metadata:metadata,maskLength:undefined,jitOffset:{}};if(nocache!==true){Inputmask.prototype.masksCache[maskdefKey]=masksetDefinition;masksetDefinition=$.extend(true,{},Inputmask.prototype.masksCache[maskdefKey])}}else masksetDefinition=$.extend(true,{},Inputmask.prototype.masksCache[maskdefKey]);return masksetDefinition}var ms;if($.isFunction(opts.mask)){opts.mask=opts.mask(opts)}if($.isArray(opts.mask)){if(opts.mask.length>1){if(opts.keepStatic===null){opts.keepStatic="auto";for(var i=0;i<opts.mask.length;i++){if(opts.mask[i].charAt(0)!==opts.mask[0].charAt(0)){opts.keepStatic=true;break}}}var altMask=opts.groupmarker[0];$.each(opts.isRTL?opts.mask.reverse():opts.mask,function(ndx,msk){if(altMask.length>1){altMask+=opts.groupmarker[1]+opts.alternatormarker+opts.groupmarker[0]}if(msk.mask!==undefined&&!$.isFunction(msk.mask)){altMask+=msk.mask}else{altMask+=msk}});altMask+=opts.groupmarker[1];return generateMask(altMask,opts.mask,opts)}else opts.mask=opts.mask.pop()}if(opts.mask&&opts.mask.mask!==undefined&&!$.isFunction(opts.mask.mask)){ms=generateMask(opts.mask.mask,opts.mask,opts)}else{ms=generateMask(opts.mask,opts.mask,opts)}return ms}function isInputEventSupported(eventName){var el=document.createElement("input"),evName="on"+eventName,isSupported=evName in el;if(!isSupported){el.setAttribute(evName,"return;");isSupported=typeof el[evName]==="function"}el=null;return isSupported}function maskScope(actionObj,maskset,opts){maskset=maskset||this.maskset;opts=opts||this.opts;var inputmask=this,el=this.el,isRTL=this.isRTL,undoValue,$el,skipKeyPressEvent=false,skipInputEvent=false,ignorable=false,maxLength,mouseEnter=false,colorMask,originalPlaceholder;function getMaskTemplate(baseOnInput,minimalPos,includeMode,noJit,clearOptionalTail){var greedy=opts.greedy;if(clearOptionalTail)opts.greedy=false;minimalPos=minimalPos||0;var maskTemplate=[],ndxIntlzr,pos=0,test,testPos,lvp=getLastValidPosition();do{if(baseOnInput===true&&getMaskSet().validPositions[pos]){testPos=clearOptionalTail&&getMaskSet().validPositions[pos].match.optionality===true&&getMaskSet().validPositions[pos+1]===undefined&&(getMaskSet().validPositions[pos].generatedInput===true||getMaskSet().validPositions[pos].input==opts.skipOptionalPartCharacter&&pos>0)?determineTestTemplate(pos,getTests(pos,ndxIntlzr,pos-1)):getMaskSet().validPositions[pos];test=testPos.match;ndxIntlzr=testPos.locator.slice();maskTemplate.push(includeMode===true?testPos.input:includeMode===false?test.nativeDef:getPlaceholder(pos,test))}else{testPos=getTestTemplate(pos,ndxIntlzr,pos-1);test=testPos.match;ndxIntlzr=testPos.locator.slice();var jitMasking=noJit===true?false:opts.jitMasking!==false?opts.jitMasking:test.jit;if(jitMasking===false||jitMasking===undefined||typeof jitMasking==="number"&&isFinite(jitMasking)&&jitMasking>pos){maskTemplate.push(includeMode===false?test.nativeDef:getPlaceholder(pos,test))}}if(opts.keepStatic==="auto"){if(test.newBlockMarker&&test.fn!==null){opts.keepStatic=pos-1}}pos++}while((maxLength===undefined||pos<maxLength)&&(test.fn!==null||test.def!=="")||minimalPos>pos);if(maskTemplate[maskTemplate.length-1]===""){maskTemplate.pop()}if(includeMode!==false||getMaskSet().maskLength===undefined)getMaskSet().maskLength=pos-1;opts.greedy=greedy;return maskTemplate}function getMaskSet(){return maskset}function resetMaskSet(soft){var maskset=getMaskSet();maskset.buffer=undefined;if(soft!==true){maskset.validPositions={};maskset.p=0}}function getLastValidPosition(closestTo,strict,validPositions){var before=-1,after=-1,valids=validPositions||getMaskSet().validPositions;if(closestTo===undefined)closestTo=-1;for(var posNdx in valids){var psNdx=parseInt(posNdx);if(valids[psNdx]&&(strict||valids[psNdx].generatedInput!==true)){if(psNdx<=closestTo)before=psNdx;if(psNdx>=closestTo)after=psNdx}}return before===-1||before==closestTo?after:after==-1?before:closestTo-before<after-closestTo?before:after}function getDecisionTaker(tst){var decisionTaker=tst.locator[tst.alternation];if(typeof decisionTaker=="string"&&decisionTaker.length>0){decisionTaker=decisionTaker.split(",")[0]}return decisionTaker!==undefined?decisionTaker.toString():""}function getLocator(tst,align){var locator=(tst.alternation!=undefined?tst.mloc[getDecisionTaker(tst)]:tst.locator).join("");if(locator!=="")while(locator.length<align)locator+="0";return locator}function determineTestTemplate(pos,tests){pos=pos>0?pos-1:0;var altTest=getTest(pos),targetLocator=getLocator(altTest),tstLocator,closest,bestMatch;for(var ndx=0;ndx<tests.length;ndx++){var tst=tests[ndx];tstLocator=getLocator(tst,targetLocator.length);var distance=Math.abs(tstLocator-targetLocator);if(closest===undefined||tstLocator!==""&&distance<closest||bestMatch&&!opts.greedy&&bestMatch.match.optionality&&bestMatch.match.newBlockMarker==="master"&&(!tst.match.optionality||!tst.match.newBlockMarker)||bestMatch&&bestMatch.match.optionalQuantifier&&!tst.match.optionalQuantifier){closest=distance;bestMatch=tst}}return bestMatch}function getTestTemplate(pos,ndxIntlzr,tstPs){return getMaskSet().validPositions[pos]||determineTestTemplate(pos,getTests(pos,ndxIntlzr?ndxIntlzr.slice():ndxIntlzr,tstPs))}function getTest(pos,tests){if(getMaskSet().validPositions[pos]){return getMaskSet().validPositions[pos]}return(tests||getTests(pos))[0]}function positionCanMatchDefinition(pos,def){var valid=false,tests=getTests(pos);for(var tndx=0;tndx<tests.length;tndx++){if(tests[tndx].match&&tests[tndx].match.def===def){valid=true;break}}return valid}function getTests(pos,ndxIntlzr,tstPs){var maskTokens=getMaskSet().maskToken,testPos=ndxIntlzr?tstPs:0,ndxInitializer=ndxIntlzr?ndxIntlzr.slice():[0],matches=[],insertStop=false,latestMatch,cacheDependency=ndxIntlzr?ndxIntlzr.join(""):"";function resolveTestFromToken(maskToken,ndxInitializer,loopNdx,quantifierRecurse){function handleMatch(match,loopNdx,quantifierRecurse){function isFirstMatch(latestMatch,tokenGroup){var firstMatch=$.inArray(latestMatch,tokenGroup.matches)===0;if(!firstMatch){$.each(tokenGroup.matches,function(ndx,match){if(match.isQuantifier===true)firstMatch=isFirstMatch(latestMatch,tokenGroup.matches[ndx-1]);else if(match.hasOwnProperty("matches"))firstMatch=isFirstMatch(latestMatch,match);if(firstMatch)return false})}return firstMatch}function resolveNdxInitializer(pos,alternateNdx,targetAlternation){var bestMatch,indexPos;if(getMaskSet().tests[pos]||getMaskSet().validPositions[pos]){$.each(getMaskSet().tests[pos]||[getMaskSet().validPositions[pos]],function(ndx,lmnt){if(lmnt.mloc[alternateNdx]){bestMatch=lmnt;return false}var alternation=targetAlternation!==undefined?targetAlternation:lmnt.alternation,ndxPos=lmnt.locator[alternation]!==undefined?lmnt.locator[alternation].toString().indexOf(alternateNdx):-1;if((indexPos===undefined||ndxPos<indexPos)&&ndxPos!==-1){bestMatch=lmnt;indexPos=ndxPos}})}if(bestMatch){var bestMatchAltIndex=bestMatch.locator[bestMatch.alternation];var locator=bestMatch.mloc[alternateNdx]||bestMatch.mloc[bestMatchAltIndex]||bestMatch.locator;return locator.slice((targetAlternation!==undefined?targetAlternation:bestMatch.alternation)+1)}else{return targetAlternation!==undefined?resolveNdxInitializer(pos,alternateNdx):undefined}}function isSubsetOf(source,target){function expand(pattern){var expanded=[],start,end;for(var i=0,l=pattern.length;i<l;i++){if(pattern.charAt(i)==="-"){end=pattern.charCodeAt(i+1);while(++start<end)expanded.push(String.fromCharCode(start))}else{start=pattern.charCodeAt(i);expanded.push(pattern.charAt(i))}}return expanded.join("")}if(opts.regex&&source.match.fn!==null&&target.match.fn!==null){return expand(target.match.def.replace(/[\[\]]/g,"")).indexOf(expand(source.match.def.replace(/[\[\]]/g,"")))!==-1}return source.match.def===target.match.nativeDef}function staticCanMatchDefinition(source,target){var sloc=source.locator.slice(source.alternation).join(""),tloc=target.locator.slice(target.alternation).join(""),canMatch=sloc==tloc;canMatch=canMatch&&source.match.fn===null&&target.match.fn!==null?target.match.fn.test(source.match.def,getMaskSet(),pos,false,opts,false):false;return canMatch}function setMergeLocators(targetMatch,altMatch){if(altMatch===undefined||targetMatch.alternation===altMatch.alternation&&targetMatch.locator[targetMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation])===-1){targetMatch.mloc=targetMatch.mloc||{};var locNdx=targetMatch.locator[targetMatch.alternation];if(locNdx===undefined)targetMatch.alternation=undefined;else{if(typeof locNdx==="string")locNdx=locNdx.split(",")[0];if(targetMatch.mloc[locNdx]===undefined)targetMatch.mloc[locNdx]=targetMatch.locator.slice();if(altMatch!==undefined){for(var ndx in altMatch.mloc){if(typeof ndx==="string")ndx=ndx.split(",")[0];if(targetMatch.mloc[ndx]===undefined)targetMatch.mloc[ndx]=altMatch.mloc[ndx]}targetMatch.locator[targetMatch.alternation]=Object.keys(targetMatch.mloc).join(",")}return true}}return false}if(testPos>500&&quantifierRecurse!==undefined){throw"Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. "+getMaskSet().mask}if(testPos===pos&&match.matches===undefined){matches.push({match:match,locator:loopNdx.reverse(),cd:cacheDependency,mloc:{}});return true}else if(match.matches!==undefined){if(match.isGroup&&quantifierRecurse!==match){match=handleMatch(maskToken.matches[$.inArray(match,maskToken.matches)+1],loopNdx,quantifierRecurse);if(match)return true}else if(match.isOptional){var optionalToken=match;match=resolveTestFromToken(match,ndxInitializer,loopNdx,quantifierRecurse);if(match){$.each(matches,function(ndx,mtch){mtch.match.optionality=true});latestMatch=matches[matches.length-1].match;if(quantifierRecurse===undefined&&isFirstMatch(latestMatch,optionalToken)){insertStop=true;testPos=pos}else return true}}else if(match.isAlternator){var alternateToken=match,malternateMatches=[],maltMatches,currentMatches=matches.slice(),loopNdxCnt=loopNdx.length;var altIndex=ndxInitializer.length>0?ndxInitializer.shift():-1;if(altIndex===-1||typeof altIndex==="string"){var currentPos=testPos,ndxInitializerClone=ndxInitializer.slice(),altIndexArr=[],amndx;if(typeof altIndex=="string"){altIndexArr=altIndex.split(",")}else{for(amndx=0;amndx<alternateToken.matches.length;amndx++){altIndexArr.push(amndx.toString())}}if(getMaskSet().excludes[pos]){var altIndexArrClone=altIndexArr.slice();for(var i=0,el=getMaskSet().excludes[pos].length;i<el;i++){altIndexArr.splice(altIndexArr.indexOf(getMaskSet().excludes[pos][i].toString()),1)}if(altIndexArr.length===0){getMaskSet().excludes[pos]=undefined;altIndexArr=altIndexArrClone}}if(opts.keepStatic===true||isFinite(parseInt(opts.keepStatic))&&currentPos>=opts.keepStatic)altIndexArr=altIndexArr.slice(0,1);var unMatchedAlternation=false;for(var ndx=0;ndx<altIndexArr.length;ndx++){amndx=parseInt(altIndexArr[ndx]);matches=[];ndxInitializer=typeof altIndex==="string"?resolveNdxInitializer(testPos,amndx,loopNdxCnt)||ndxInitializerClone.slice():ndxInitializerClone.slice();if(alternateToken.matches[amndx]&&handleMatch(alternateToken.matches[amndx],[amndx].concat(loopNdx),quantifierRecurse))match=true;else if(ndx===0){unMatchedAlternation=true}maltMatches=matches.slice();testPos=currentPos;matches=[];for(var ndx1=0;ndx1<maltMatches.length;ndx1++){var altMatch=maltMatches[ndx1],dropMatch=false;altMatch.match.jit=altMatch.match.jit||unMatchedAlternation;altMatch.alternation=altMatch.alternation||loopNdxCnt;setMergeLocators(altMatch);for(var ndx2=0;ndx2<malternateMatches.length;ndx2++){var altMatch2=malternateMatches[ndx2];if(typeof altIndex!=="string"||altMatch.alternation!==undefined&&$.inArray(altMatch.locator[altMatch.alternation].toString(),altIndexArr)!==-1){if(altMatch.match.nativeDef===altMatch2.match.nativeDef){dropMatch=true;setMergeLocators(altMatch2,altMatch);break}else if(isSubsetOf(altMatch,altMatch2)){if(setMergeLocators(altMatch,altMatch2)){dropMatch=true;malternateMatches.splice(malternateMatches.indexOf(altMatch2),0,altMatch)}break}else if(isSubsetOf(altMatch2,altMatch)){setMergeLocators(altMatch2,altMatch);break}else if(staticCanMatchDefinition(altMatch,altMatch2)){if(setMergeLocators(altMatch,altMatch2)){dropMatch=true;malternateMatches.splice(malternateMatches.indexOf(altMatch2),0,altMatch)}break}}}if(!dropMatch){malternateMatches.push(altMatch)}}}matches=currentMatches.concat(malternateMatches);testPos=pos;insertStop=matches.length>0;match=malternateMatches.length>0;ndxInitializer=ndxInitializerClone.slice()}else match=handleMatch(alternateToken.matches[altIndex]||maskToken.matches[altIndex],[altIndex].concat(loopNdx),quantifierRecurse);if(match)return true}else if(match.isQuantifier&&quantifierRecurse!==maskToken.matches[$.inArray(match,maskToken.matches)-1]){var qt=match;for(var qndx=ndxInitializer.length>0?ndxInitializer.shift():0;qndx<(isNaN(qt.quantifier.max)?qndx+1:qt.quantifier.max)&&testPos<=pos;qndx++){var tokenGroup=maskToken.matches[$.inArray(qt,maskToken.matches)-1];match=handleMatch(tokenGroup,[qndx].concat(loopNdx),tokenGroup);if(match){latestMatch=matches[matches.length-1].match;latestMatch.optionalQuantifier=qndx>=qt.quantifier.min;latestMatch.jit=(qndx||1)*tokenGroup.matches.indexOf(latestMatch)>=qt.quantifier.jit;if(latestMatch.optionalQuantifier&&isFirstMatch(latestMatch,tokenGroup)){insertStop=true;testPos=pos;break}if(latestMatch.jit){getMaskSet().jitOffset[pos]=tokenGroup.matches.indexOf(latestMatch)}return true}}}else{match=resolveTestFromToken(match,ndxInitializer,loopNdx,quantifierRecurse);if(match)return true}}else{testPos++}}for(var tndx=ndxInitializer.length>0?ndxInitializer.shift():0;tndx<maskToken.matches.length;tndx++){if(maskToken.matches[tndx].isQuantifier!==true){var match=handleMatch(maskToken.matches[tndx],[tndx].concat(loopNdx),quantifierRecurse);if(match&&testPos===pos){return match}else if(testPos>pos){break}}}}function mergeLocators(pos,tests){var locator=[];if(!$.isArray(tests))tests=[tests];if(tests.length>0){if(tests[0].alternation===undefined){locator=determineTestTemplate(pos,tests.slice()).locator.slice();if(locator.length===0)locator=tests[0].locator.slice()}else{$.each(tests,function(ndx,tst){if(tst.def!==""){if(locator.length===0)locator=tst.locator.slice();else{for(var i=0;i<locator.length;i++){if(tst.locator[i]&&locator[i].toString().indexOf(tst.locator[i])===-1){locator[i]+=","+tst.locator[i]}}}}})}}return locator}if(pos>-1){if(ndxIntlzr===undefined){var previousPos=pos-1,test;while((test=getMaskSet().validPositions[previousPos]||getMaskSet().tests[previousPos])===undefined&&previousPos>-1){previousPos--}if(test!==undefined&&previousPos>-1){ndxInitializer=mergeLocators(previousPos,test);cacheDependency=ndxInitializer.join("");testPos=previousPos}}if(getMaskSet().tests[pos]&&getMaskSet().tests[pos][0].cd===cacheDependency){return getMaskSet().tests[pos]}for(var mtndx=ndxInitializer.shift();mtndx<maskTokens.length;mtndx++){var match=resolveTestFromToken(maskTokens[mtndx],ndxInitializer,[mtndx]);if(match&&testPos===pos||testPos>pos){break}}}if(matches.length===0||insertStop){matches.push({match:{fn:null,optionality:false,casing:null,def:"",placeholder:""},locator:[],mloc:{},cd:cacheDependency})}if(ndxIntlzr!==undefined&&getMaskSet().tests[pos]){return $.extend(true,[],matches)}getMaskSet().tests[pos]=$.extend(true,[],matches);return getMaskSet().tests[pos]}function getBufferTemplate(){if(getMaskSet()._buffer===undefined){getMaskSet()._buffer=getMaskTemplate(false,1);if(getMaskSet().buffer===undefined)getMaskSet().buffer=getMaskSet()._buffer.slice()}return getMaskSet()._buffer}function getBuffer(noCache){if(getMaskSet().buffer===undefined||noCache===true){getMaskSet().buffer=getMaskTemplate(true,getLastValidPosition(),true);if(getMaskSet()._buffer===undefined)getMaskSet()._buffer=getMaskSet().buffer.slice()}return getMaskSet().buffer}function refreshFromBuffer(start,end,buffer){var i,p;if(start===true){resetMaskSet();start=0;end=buffer.length}else{for(i=start;i<end;i++){delete getMaskSet().validPositions[i]}}p=start;for(i=start;i<end;i++){resetMaskSet(true);if(buffer[i]!==opts.skipOptionalPartCharacter){var valResult=isValid(p,buffer[i],true,true);if(valResult!==false){resetMaskSet(true);p=valResult.caret!==undefined?valResult.caret:valResult.pos+1}}}}function casing(elem,test,pos){switch(opts.casing||test.casing){case"upper":elem=elem.toUpperCase();break;case"lower":elem=elem.toLowerCase();break;case"title":var posBefore=getMaskSet().validPositions[pos-1];if(pos===0||posBefore&&posBefore.input===String.fromCharCode(Inputmask.keyCode.SPACE)){elem=elem.toUpperCase()}else{elem=elem.toLowerCase()}break;default:if($.isFunction(opts.casing)){var args=Array.prototype.slice.call(arguments);args.push(getMaskSet().validPositions);elem=opts.casing.apply(this,args)}}return elem}function checkAlternationMatch(altArr1,altArr2,na){var altArrC=opts.greedy?altArr2:altArr2.slice(0,1),isMatch=false,naArr=na!==undefined?na.split(","):[],naNdx;for(var i=0;i<naArr.length;i++){if((naNdx=altArr1.indexOf(naArr[i]))!==-1){altArr1.splice(naNdx,1)}}for(var alndx=0;alndx<altArr1.length;alndx++){if($.inArray(altArr1[alndx],altArrC)!==-1){isMatch=true;break}}return isMatch}function alternate(pos,c,strict,fromSetValid,rAltPos){var validPsClone=$.extend(true,{},getMaskSet().validPositions),lastAlt,alternation,isValidRslt=false,altPos,prevAltPos,i,validPos,decisionPos,lAltPos=rAltPos!==undefined?rAltPos:getLastValidPosition();if(lAltPos===-1&&rAltPos===undefined){lastAlt=0;prevAltPos=getTest(lastAlt);alternation=prevAltPos.alternation}else{for(;lAltPos>=0;lAltPos--){altPos=getMaskSet().validPositions[lAltPos];if(altPos&&altPos.alternation!==undefined){if(prevAltPos&&prevAltPos.locator[altPos.alternation]!==altPos.locator[altPos.alternation]){break}lastAlt=lAltPos;alternation=getMaskSet().validPositions[lastAlt].alternation;prevAltPos=altPos}}}if(alternation!==undefined){decisionPos=parseInt(lastAlt);getMaskSet().excludes[decisionPos]=getMaskSet().excludes[decisionPos]||[];if(pos!==true){getMaskSet().excludes[decisionPos].push(getDecisionTaker(prevAltPos))}var validInputsClone=[],staticInputsBeforePos=0;for(i=decisionPos;i<getLastValidPosition(undefined,true)+1;i++){validPos=getMaskSet().validPositions[i];if(validPos&&validPos.generatedInput!==true){validInputsClone.push(validPos.input)}else if(i<pos)staticInputsBeforePos++;delete getMaskSet().validPositions[i]}while(getMaskSet().excludes[decisionPos]&&getMaskSet().excludes[decisionPos].length<10){var posOffset=staticInputsBeforePos*-1,validInputs=validInputsClone.slice();getMaskSet().tests[decisionPos]=undefined;resetMaskSet(true);isValidRslt=true;while(validInputs.length>0){var input=validInputs.shift();if(!(isValidRslt=isValid(getLastValidPosition(undefined,true)+1,input,false,fromSetValid,true))){break}}if(isValidRslt&&c!==undefined){var targetLvp=getLastValidPosition(pos)+1;for(i=decisionPos;i<getLastValidPosition()+1;i++){validPos=getMaskSet().validPositions[i];if((validPos===undefined||validPos.match.fn==null)&&i<pos+posOffset){posOffset++}}pos=pos+posOffset;isValidRslt=isValid(pos>targetLvp?targetLvp:pos,c,strict,fromSetValid,true)}if(!isValidRslt){resetMaskSet();prevAltPos=getTest(decisionPos);getMaskSet().validPositions=$.extend(true,{},validPsClone);if(getMaskSet().excludes[decisionPos]){var decisionTaker=getDecisionTaker(prevAltPos);if(getMaskSet().excludes[decisionPos].indexOf(decisionTaker)!==-1){isValidRslt=alternate(pos,c,strict,fromSetValid,decisionPos-1);break}getMaskSet().excludes[decisionPos].push(decisionTaker);for(i=decisionPos;i<getLastValidPosition(undefined,true)+1;i++)delete getMaskSet().validPositions[i]}else{isValidRslt=alternate(pos,c,strict,fromSetValid,decisionPos-1);break}}else break}}getMaskSet().excludes[decisionPos]=undefined;return isValidRslt}function isValid(pos,c,strict,fromSetValid,fromAlternate,validateOnly){function isSelection(posObj){return isRTL?posObj.begin-posObj.end>1||posObj.begin-posObj.end===1:posObj.end-posObj.begin>1||posObj.end-posObj.begin===1}strict=strict===true;var maskPos=pos;if(pos.begin!==undefined){maskPos=isRTL?pos.end:pos.begin}function _isValid(position,c,strict){var rslt=false;$.each(getTests(position),function(ndx,tst){var test=tst.match;getBuffer(true);rslt=test.fn!=null?test.fn.test(c,getMaskSet(),position,strict,opts,isSelection(pos)):(c===test.def||c===opts.skipOptionalPartCharacter)&&test.def!==""?{c:getPlaceholder(position,test,true)||test.def,pos:position}:false;if(rslt!==false){var elem=rslt.c!==undefined?rslt.c:c,validatedPos=position;elem=elem===opts.skipOptionalPartCharacter&&test.fn===null?getPlaceholder(position,test,true)||test.def:elem;if(rslt.remove!==undefined){if(!$.isArray(rslt.remove))rslt.remove=[rslt.remove];$.each(rslt.remove.sort(function(a,b){return b-a}),function(ndx,lmnt){revalidateMask({begin:lmnt,end:lmnt+1})})}if(rslt.insert!==undefined){if(!$.isArray(rslt.insert))rslt.insert=[rslt.insert];$.each(rslt.insert.sort(function(a,b){return a-b}),function(ndx,lmnt){isValid(lmnt.pos,lmnt.c,true,fromSetValid)})}if(rslt!==true&&rslt.pos!==undefined&&rslt.pos!==position){validatedPos=rslt.pos}if(rslt!==true&&rslt.pos===undefined&&rslt.c===undefined){return false}if(!revalidateMask(pos,$.extend({},tst,{input:casing(elem,test,validatedPos)}),fromSetValid,validatedPos)){rslt=false}return false}});return rslt}var result=true,positionsClone=$.extend(true,{},getMaskSet().validPositions);if($.isFunction(opts.preValidation)&&!strict&&fromSetValid!==true&&validateOnly!==true){result=opts.preValidation(getBuffer(),maskPos,c,isSelection(pos),opts,getMaskSet())}if(result===true){trackbackPositions(undefined,maskPos,true);if(maxLength===undefined||maskPos<maxLength){result=_isValid(maskPos,c,strict);if((!strict||fromSetValid===true)&&result===false&&validateOnly!==true){var currentPosValid=getMaskSet().validPositions[maskPos];if(currentPosValid&&currentPosValid.match.fn===null&&(currentPosValid.match.def===c||c===opts.skipOptionalPartCharacter)){result={caret:seekNext(maskPos)}}else{if((opts.insertMode||getMaskSet().validPositions[seekNext(maskPos)]===undefined)&&(!isMask(maskPos,true)||getMaskSet().jitOffset[maskPos])){if(getMaskSet().jitOffset[maskPos]&&getMaskSet().validPositions[seekNext(maskPos)]===undefined){result=isValid(maskPos+getMaskSet().jitOffset[maskPos],c,strict);if(result!==false)result.caret=maskPos}else for(var nPos=maskPos+1,snPos=seekNext(maskPos);nPos<=snPos;nPos++){result=_isValid(nPos,c,strict);if(result!==false){result=trackbackPositions(maskPos,result.pos!==undefined?result.pos:nPos)||result;maskPos=nPos;break}}}}}}if(result===false&&opts.keepStatic!==false&&(opts.regex==null||isComplete(getBuffer()))&&!strict&&fromAlternate!==true){result=alternate(maskPos,c,strict,fromSetValid)}if(result===true){result={pos:maskPos}}}if($.isFunction(opts.postValidation)&&result!==false&&!strict&&fromSetValid!==true&&validateOnly!==true){var postResult=opts.postValidation(getBuffer(true),pos.begin!==undefined?isRTL?pos.end:pos.begin:pos,result,opts);if(postResult!==undefined){if(postResult.refreshFromBuffer&&postResult.buffer){var refresh=postResult.refreshFromBuffer;refreshFromBuffer(refresh===true?refresh:refresh.start,refresh.end,postResult.buffer)}result=postResult===true?result:postResult}}if(result&&result.pos===undefined){result.pos=maskPos}if(result===false||validateOnly===true){resetMaskSet(true);getMaskSet().validPositions=$.extend(true,{},positionsClone)}return result}function trackbackPositions(originalPos,newPos,fillOnly){var result;if(originalPos===undefined){for(originalPos=newPos-1;originalPos>0;originalPos--){if(getMaskSet().validPositions[originalPos])break}}for(var ps=originalPos;ps<newPos;ps++){if(getMaskSet().validPositions[ps]===undefined&&!isMask(ps,true)){var vp=ps==0?getTest(ps):getMaskSet().validPositions[ps-1];if(vp){var tests=getTests(ps).slice();if(tests[tests.length-1].match.def==="")tests.pop();var bestMatch=determineTestTemplate(ps,tests);bestMatch=$.extend({},bestMatch,{input:getPlaceholder(ps,bestMatch.match,true)||bestMatch.match.def});bestMatch.generatedInput=true;revalidateMask(ps,bestMatch,true);if(fillOnly!==true){var cvpInput=getMaskSet().validPositions[newPos].input;getMaskSet().validPositions[newPos]=undefined;result=isValid(newPos,cvpInput,true,true)}}}}return result}function revalidateMask(pos,validTest,fromSetValid,validatedPos){function IsEnclosedStatic(pos,valids,selection){var posMatch=valids[pos];if(posMatch!==undefined&&(posMatch.match.fn===null&&posMatch.match.optionality!==true||posMatch.input===opts.radixPoint)){var prevMatch=selection.begin<=pos-1?valids[pos-1]&&valids[pos-1].match.fn===null&&valids[pos-1]:valids[pos-1],nextMatch=selection.end>pos+1?valids[pos+1]&&valids[pos+1].match.fn===null&&valids[pos+1]:valids[pos+1];return prevMatch&&nextMatch}return false}var begin=pos.begin!==undefined?pos.begin:pos,end=pos.end!==undefined?pos.end:pos;if(pos.begin>pos.end){begin=pos.end;end=pos.begin}validatedPos=validatedPos!==undefined?validatedPos:begin;if(begin!==end||opts.insertMode&&getMaskSet().validPositions[validatedPos]!==undefined&&fromSetValid===undefined){var positionsClone=$.extend(true,{},getMaskSet().validPositions),lvp=getLastValidPosition(undefined,true),i;getMaskSet().p=begin;for(i=lvp;i>=begin;i--){if(getMaskSet().validPositions[i]&&getMaskSet().validPositions[i].match.nativeDef==="+"){opts.isNegative=false}delete getMaskSet().validPositions[i]}var valid=true,j=validatedPos,vps=getMaskSet().validPositions,needsValidation=false,posMatch=j,i=j;if(validTest){getMaskSet().validPositions[validatedPos]=$.extend(true,{},validTest);posMatch++;j++;if(begin<end)i++}for(;i<=lvp;i++){var t=positionsClone[i];if(t!==undefined&&(i>=end||i>=begin&&t.generatedInput!==true&&IsEnclosedStatic(i,positionsClone,{begin:begin,end:end}))){while(getTest(posMatch).match.def!==""){if(needsValidation===false&&positionsClone[posMatch]&&positionsClone[posMatch].match.nativeDef===t.match.nativeDef){getMaskSet().validPositions[posMatch]=$.extend(true,{},positionsClone[posMatch]);getMaskSet().validPositions[posMatch].input=t.input;trackbackPositions(undefined,posMatch,true);j=posMatch+1;valid=true}else if(opts.shiftPositions&&positionCanMatchDefinition(posMatch,t.match.def)){var result=isValid(posMatch,t.input,true,true);valid=result!==false;j=result.caret||result.insert?getLastValidPosition():posMatch+1;needsValidation=true}else{valid=t.generatedInput===true||t.input===opts.radixPoint&&opts.numericInput===true}if(valid)break;if(!valid&&posMatch>end&&isMask(posMatch,true)&&(t.match.fn!==null||posMatch>getMaskSet().maskLength)){break}posMatch++}if(getTest(posMatch).match.def=="")valid=false;posMatch=j}if(!valid)break}if(!valid){getMaskSet().validPositions=$.extend(true,{},positionsClone);resetMaskSet(true);return false}}else if(validTest){getMaskSet().validPositions[validatedPos]=$.extend(true,{},validTest)}resetMaskSet(true);return true}function isMask(pos,strict){var test=getTestTemplate(pos).match;if(test.def==="")test=getTest(pos).match;if(test.fn!=null){return test.fn}if(strict!==true&&pos>-1){var tests=getTests(pos);return tests.length>1+(tests[tests.length-1].match.def===""?1:0)}return false}function seekNext(pos,newBlock){var position=pos+1;while(getTest(position).match.def!==""&&(newBlock===true&&(getTest(position).match.newBlockMarker!==true||!isMask(position))||newBlock!==true&&!isMask(position))){position++}return position}function seekPrevious(pos,newBlock){var position=pos,tests;if(position<=0)return 0;while(--position>0&&(newBlock===true&&getTest(position).match.newBlockMarker!==true||newBlock!==true&&!isMask(position)&&(tests=getTests(position),tests.length<2||tests.length===2&&tests[1].match.def===""))){}return position}function writeBuffer(input,buffer,caretPos,event,triggerEvents){if(event&&$.isFunction(opts.onBeforeWrite)){var result=opts.onBeforeWrite.call(inputmask,event,buffer,caretPos,opts);if(result){if(result.refreshFromBuffer){var refresh=result.refreshFromBuffer;refreshFromBuffer(refresh===true?refresh:refresh.start,refresh.end,result.buffer||buffer);buffer=getBuffer(true)}if(caretPos!==undefined)caretPos=result.caret!==undefined?result.caret:caretPos}}if(input!==undefined){input.inputmask._valueSet(buffer.join(""));if(caretPos!==undefined&&(event===undefined||event.type!=="blur")){caret(input,caretPos)}else renderColorMask(input,caretPos,buffer.length===0);if(triggerEvents===true){var $input=$(input),nptVal=input.inputmask._valueGet();skipInputEvent=true;$input.trigger("input");setTimeout(function(){if(nptVal===getBufferTemplate().join("")){$input.trigger("cleared")}else if(isComplete(buffer)===true){$input.trigger("complete")}},0)}}}function getPlaceholder(pos,test,returnPL){test=test||getTest(pos).match;if(test.placeholder!==undefined||returnPL===true){return $.isFunction(test.placeholder)?test.placeholder(opts):test.placeholder}else if(test.fn===null){if(pos>-1&&getMaskSet().validPositions[pos]===undefined){var tests=getTests(pos),staticAlternations=[],prevTest;if(tests.length>1+(tests[tests.length-1].match.def===""?1:0)){for(var i=0;i<tests.length;i++){if(tests[i].match.optionality!==true&&tests[i].match.optionalQuantifier!==true&&(tests[i].match.fn===null||(prevTest===undefined||tests[i].match.fn.test(prevTest.match.def,getMaskSet(),pos,true,opts)!==false))){staticAlternations.push(tests[i]);if(tests[i].match.fn===null)prevTest=tests[i];if(staticAlternations.length>1){if(/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)){return opts.placeholder.charAt(pos%opts.placeholder.length)}}}}}}return test.def}return opts.placeholder.charAt(pos%opts.placeholder.length)}function HandleNativePlaceholder(npt,value){if(ie){if(npt.inputmask._valueGet()!==value&&(npt.placeholder!==value||npt.placeholder==="")){var buffer=getBuffer().slice(),nptValue=npt.inputmask._valueGet();if(nptValue!==value){var lvp=getLastValidPosition();if(lvp===-1&&nptValue===getBufferTemplate().join("")){buffer=[]}else if(lvp!==-1){clearOptionalTail(buffer)}writeBuffer(npt,buffer)}}}else if(npt.placeholder!==value){npt.placeholder=value;if(npt.placeholder==="")npt.removeAttribute("placeholder")}}var EventRuler={on:function(input,eventName,eventHandler){var ev=function(e){var that=this;if(that.inputmask===undefined&&this.nodeName!=="FORM"){var imOpts=$.data(that,"_inputmask_opts");if(imOpts)new Inputmask(imOpts).mask(that);else EventRuler.off(that)}else if(e.type!=="setvalue"&&this.nodeName!=="FORM"&&(that.disabled||that.readOnly&&!(e.type==="keydown"&&(e.ctrlKey&&e.keyCode===67)||opts.tabThrough===false&&e.keyCode===Inputmask.keyCode.TAB))){e.preventDefault()}else{switch(e.type){case"input":if(skipInputEvent===true){skipInputEvent=false;return e.preventDefault()}if(mobile){var args=arguments;setTimeout(function(){eventHandler.apply(that,args);caret(that,that.inputmask.caretPos,undefined,true)},0);return false}break;case"keydown":skipKeyPressEvent=false;skipInputEvent=false;break;case"keypress":if(skipKeyPressEvent===true){return e.preventDefault()}skipKeyPressEvent=true;break;case"click":if(iemobile||iphone){var args=arguments;setTimeout(function(){eventHandler.apply(that,args)},0);return false}break}var returnVal=eventHandler.apply(that,arguments);if(returnVal===false){e.preventDefault();e.stopPropagation()}return returnVal}};input.inputmask.events[eventName]=input.inputmask.events[eventName]||[];input.inputmask.events[eventName].push(ev);if($.inArray(eventName,["submit","reset"])!==-1){if(input.form!==null)$(input.form).on(eventName,ev)}else{$(input).on(eventName,ev)}},off:function(input,event){if(input.inputmask&&input.inputmask.events){var events;if(event){events=[];events[event]=input.inputmask.events[event]}else{events=input.inputmask.events}$.each(events,function(eventName,evArr){while(evArr.length>0){var ev=evArr.pop();if($.inArray(eventName,["submit","reset"])!==-1){if(input.form!==null)$(input.form).off(eventName,ev)}else{$(input).off(eventName,ev)}}delete input.inputmask.events[eventName]})}}};var EventHandlers={keydownEvent:function(e){var input=this,$input=$(input),k=e.keyCode,pos=caret(input);if(k===Inputmask.keyCode.BACKSPACE||k===Inputmask.keyCode.DELETE||iphone&&k===Inputmask.keyCode.BACKSPACE_SAFARI||e.ctrlKey&&k===Inputmask.keyCode.X&&!isInputEventSupported("cut")){e.preventDefault();handleRemove(input,k,pos);writeBuffer(input,getBuffer(true),getMaskSet().p,e,input.inputmask._valueGet()!==getBuffer().join(""))}else if(k===Inputmask.keyCode.END||k===Inputmask.keyCode.PAGE_DOWN){e.preventDefault();var caretPos=seekNext(getLastValidPosition());caret(input,e.shiftKey?pos.begin:caretPos,caretPos,true)}else if(k===Inputmask.keyCode.HOME&&!e.shiftKey||k===Inputmask.keyCode.PAGE_UP){e.preventDefault();caret(input,0,e.shiftKey?pos.begin:0,true)}else if((opts.undoOnEscape&&k===Inputmask.keyCode.ESCAPE||k===90&&e.ctrlKey)&&e.altKey!==true){checkVal(input,true,false,undoValue.split(""));$input.trigger("click")}else if(k===Inputmask.keyCode.INSERT&&!(e.shiftKey||e.ctrlKey)){opts.insertMode=!opts.insertMode;input.setAttribute("im-insert",opts.insertMode)}else if(opts.tabThrough===true&&k===Inputmask.keyCode.TAB){if(e.shiftKey===true){if(getTest(pos.begin).match.fn===null){pos.begin=seekNext(pos.begin)}pos.end=seekPrevious(pos.begin,true);pos.begin=seekPrevious(pos.end,true)}else{pos.begin=seekNext(pos.begin,true);pos.end=seekNext(pos.begin,true);if(pos.end<getMaskSet().maskLength)pos.end--}if(pos.begin<getMaskSet().maskLength){e.preventDefault();caret(input,pos.begin,pos.end)}}opts.onKeyDown.call(this,e,getBuffer(),caret(input).begin,opts);ignorable=$.inArray(k,opts.ignorables)!==-1},keypressEvent:function(e,checkval,writeOut,strict,ndx){var input=this,$input=$(input),k=e.which||e.charCode||e.keyCode;if(checkval!==true&&(!(e.ctrlKey&&e.altKey)&&(e.ctrlKey||e.metaKey||ignorable))){if(k===Inputmask.keyCode.ENTER&&undoValue!==getBuffer().join("")){undoValue=getBuffer().join("");setTimeout(function(){$input.trigger("change")},0)}return true}else{if(k){if(k===46&&e.shiftKey===false&&opts.radixPoint!=="")k=opts.radixPoint.charCodeAt(0);var pos=checkval?{begin:ndx,end:ndx}:caret(input),forwardPosition,c=String.fromCharCode(k),offset=0;if(opts._radixDance&&opts.numericInput){var caretPos=getBuffer().indexOf(opts.radixPoint.charAt(0))+1;if(pos.begin<=caretPos){if(k===opts.radixPoint.charCodeAt(0))offset=1;pos.begin-=1;pos.end-=1}}getMaskSet().writeOutBuffer=true;var valResult=isValid(pos,c,strict);if(valResult!==false){resetMaskSet(true);forwardPosition=valResult.caret!==undefined?valResult.caret:seekNext(valResult.pos.begin?valResult.pos.begin:valResult.pos);getMaskSet().p=forwardPosition}forwardPosition=(opts.numericInput&&valResult.caret===undefined?seekPrevious(forwardPosition):forwardPosition)+offset;if(writeOut!==false){setTimeout(function(){opts.onKeyValidation.call(input,k,valResult,opts)},0);if(getMaskSet().writeOutBuffer&&valResult!==false){var buffer=getBuffer();writeBuffer(input,buffer,forwardPosition,e,checkval!==true)}}e.preventDefault();if(checkval){if(valResult!==false)valResult.forwardPosition=forwardPosition;return valResult}}}},pasteEvent:function(e){var input=this,ev=e.originalEvent||e,$input=$(input),inputValue=input.inputmask._valueGet(true),caretPos=caret(input),tempValue;if(isRTL){tempValue=caretPos.end;caretPos.end=caretPos.begin;caretPos.begin=tempValue}var valueBeforeCaret=inputValue.substr(0,caretPos.begin),valueAfterCaret=inputValue.substr(caretPos.end,inputValue.length);if(valueBeforeCaret===(isRTL?getBufferTemplate().reverse():getBufferTemplate()).slice(0,caretPos.begin).join(""))valueBeforeCaret="";if(valueAfterCaret===(isRTL?getBufferTemplate().reverse():getBufferTemplate()).slice(caretPos.end).join(""))valueAfterCaret="";if(window.clipboardData&&window.clipboardData.getData){inputValue=valueBeforeCaret+window.clipboardData.getData("Text")+valueAfterCaret}else if(ev.clipboardData&&ev.clipboardData.getData){inputValue=valueBeforeCaret+ev.clipboardData.getData("text/plain")+valueAfterCaret}else return true;var pasteValue=inputValue;if($.isFunction(opts.onBeforePaste)){pasteValue=opts.onBeforePaste.call(inputmask,inputValue,opts);if(pasteValue===false){return e.preventDefault()}if(!pasteValue){pasteValue=inputValue}}checkVal(input,false,false,pasteValue.toString().split(""));writeBuffer(input,getBuffer(),seekNext(getLastValidPosition()),e,undoValue!==getBuffer().join(""));return e.preventDefault()},inputFallBackEvent:function(e){function radixPointHandler(input,inputValue,caretPos){if(inputValue.charAt(caretPos.begin-1)==="."&&opts.radixPoint!==""){inputValue=inputValue.split("");inputValue[caretPos.begin-1]=opts.radixPoint.charAt(0);inputValue=inputValue.join("")}return inputValue}function ieMobileHandler(input,inputValue,caretPos){if(iemobile){var inputChar=inputValue.replace(getBuffer().join(""),"");if(inputChar.length===1){var iv=inputValue.split("");iv.splice(caretPos.begin,0,inputChar);inputValue=iv.join("")}}return inputValue}var input=this,inputValue=input.inputmask._valueGet();if(getBuffer().join("")!==inputValue){var caretPos=caret(input);inputValue=radixPointHandler(input,inputValue,caretPos);inputValue=ieMobileHandler(input,inputValue,caretPos);if(getBuffer().join("")!==inputValue){var buffer=getBuffer().join(""),offset=!opts.numericInput&&inputValue.length>buffer.length?-1:0,frontPart=inputValue.substr(0,caretPos.begin),backPart=inputValue.substr(caretPos.begin),frontBufferPart=buffer.substr(0,caretPos.begin+offset),backBufferPart=buffer.substr(caretPos.begin+offset);var selection=caretPos,entries="",isEntry=false;if(frontPart!==frontBufferPart){var fpl=(isEntry=frontPart.length>=frontBufferPart.length)?frontPart.length:frontBufferPart.length,i;for(i=0;frontPart.charAt(i)===frontBufferPart.charAt(i)&&i<fpl;i++);if(isEntry){selection.begin=i-offset;entries+=frontPart.slice(i,selection.end)}}if(backPart!==backBufferPart){if(backPart.length>backBufferPart.length){entries+=backPart.slice(0,1)}else{if(backPart.length<backBufferPart.length){selection.end+=backBufferPart.length-backPart.length;if(!isEntry&&opts.radixPoint!==""&&backPart===""&&frontPart.charAt(selection.begin+offset-1)===opts.radixPoint){selection.begin--;entries=opts.radixPoint}}}}writeBuffer(input,getBuffer(),{begin:selection.begin+offset,end:selection.end+offset});if(entries.length>0){$.each(entries.split(""),function(ndx,entry){var keypress=new $.Event("keypress");keypress.which=entry.charCodeAt(0);ignorable=false;EventHandlers.keypressEvent.call(input,keypress)})}else{if(selection.begin===selection.end-1){selection.begin=seekPrevious(selection.begin+1);if(selection.begin===selection.end-1){caret(input,selection.begin)}else{caret(input,selection.begin,selection.end)}}var keydown=new $.Event("keydown");keydown.keyCode=opts.numericInput?Inputmask.keyCode.BACKSPACE:Inputmask.keyCode.DELETE;EventHandlers.keydownEvent.call(input,keydown)}e.preventDefault()}}},beforeInputEvent:function(e){if(e.cancelable){var input=this;switch(e.inputType){case"insertText":$.each(e.data.split(""),function(ndx,entry){var keypress=new $.Event("keypress");keypress.which=entry.charCodeAt(0);ignorable=false;EventHandlers.keypressEvent.call(input,keypress)});return e.preventDefault();case"deleteContentBackward":var keydown=new $.Event("keydown");keydown.keyCode=Inputmask.keyCode.BACKSPACE;EventHandlers.keydownEvent.call(input,keydown);return e.preventDefault();case"deleteContentForward":var keydown=new $.Event("keydown");keydown.keyCode=Inputmask.keyCode.DELETE;EventHandlers.keydownEvent.call(input,keydown);return e.preventDefault()}}},setValueEvent:function(e){this.inputmask.refreshValue=false;var input=this,value=e&&e.detail?e.detail[0]:arguments[1],value=value||input.inputmask._valueGet(true);if($.isFunction(opts.onBeforeMask))value=opts.onBeforeMask.call(inputmask,value,opts)||value;value=value.toString().split("");checkVal(input,true,false,value);undoValue=getBuffer().join("");if((opts.clearMaskOnLostFocus||opts.clearIncomplete)&&input.inputmask._valueGet()===getBufferTemplate().join("")){input.inputmask._valueSet("")}},focusEvent:function(e){var input=this,nptValue=input.inputmask._valueGet();if(opts.showMaskOnFocus){if(nptValue!==getBuffer().join("")){writeBuffer(input,getBuffer(),seekNext(getLastValidPosition()))}else if(mouseEnter===false){caret(input,seekNext(getLastValidPosition()))}}if(opts.positionCaretOnTab===true&&mouseEnter===false){EventHandlers.clickEvent.apply(input,[e,true])}undoValue=getBuffer().join("")},mouseleaveEvent:function(e){var input=this;mouseEnter=false;if(opts.clearMaskOnLostFocus&&document.activeElement!==input){HandleNativePlaceholder(input,originalPlaceholder)}},clickEvent:function(e,tabbed){function doRadixFocus(clickPos){if(opts.radixPoint!==""){var vps=getMaskSet().validPositions;if(vps[clickPos]===undefined||vps[clickPos].input===getPlaceholder(clickPos)){if(clickPos<seekNext(-1))return true;var radixPos=$.inArray(opts.radixPoint,getBuffer());if(radixPos!==-1){for(var vp in vps){if(radixPos<vp&&vps[vp].input!==getPlaceholder(vp)){return false}}return true}}}return false}var input=this;setTimeout(function(){if(document.activeElement===input){var selectedCaret=caret(input);if(tabbed){if(isRTL){selectedCaret.end=selectedCaret.begin}else{selectedCaret.begin=selectedCaret.end}}if(selectedCaret.begin===selectedCaret.end){switch(opts.positionCaretOnClick){case"none":break;case"select":caret(input,0,getBuffer().length);break;case"ignore":caret(input,seekNext(getLastValidPosition()));break;case"radixFocus":if(doRadixFocus(selectedCaret.begin)){var radixPos=getBuffer().join("").indexOf(opts.radixPoint);caret(input,opts.numericInput?seekNext(radixPos):radixPos);break}default:var clickPosition=selectedCaret.begin,lvclickPosition=getLastValidPosition(clickPosition,true),lastPosition=seekNext(lvclickPosition);if(clickPosition<lastPosition){caret(input,!isMask(clickPosition,true)&&!isMask(clickPosition-1,true)?seekNext(clickPosition):clickPosition)}else{var lvp=getMaskSet().validPositions[lvclickPosition],tt=getTestTemplate(lastPosition,lvp?lvp.match.locator:undefined,lvp),placeholder=getPlaceholder(lastPosition,tt.match);if(placeholder!==""&&getBuffer()[lastPosition]!==placeholder&&tt.match.optionalQuantifier!==true&&tt.match.newBlockMarker!==true||!isMask(lastPosition,opts.keepStatic)&&tt.match.def===placeholder){var newPos=seekNext(lastPosition);if(clickPosition>=newPos||clickPosition===lastPosition){lastPosition=newPos}}caret(input,lastPosition)}break}}}},0)},cutEvent:function(e){var input=this,$input=$(input),pos=caret(input),ev=e.originalEvent||e;var clipboardData=window.clipboardData||ev.clipboardData,clipData=isRTL?getBuffer().slice(pos.end,pos.begin):getBuffer().slice(pos.begin,pos.end);clipboardData.setData("text",isRTL?clipData.reverse().join(""):clipData.join(""));if(document.execCommand)document.execCommand("copy");handleRemove(input,Inputmask.keyCode.DELETE,pos);writeBuffer(input,getBuffer(),getMaskSet().p,e,undoValue!==getBuffer().join(""))},blurEvent:function(e){var $input=$(this),input=this;if(input.inputmask){HandleNativePlaceholder(input,originalPlaceholder);var nptValue=input.inputmask._valueGet(),buffer=getBuffer().slice();if(nptValue!==""||colorMask!==undefined){if(opts.clearMaskOnLostFocus){if(getLastValidPosition()===-1&&nptValue===getBufferTemplate().join("")){buffer=[]}else{clearOptionalTail(buffer)}}if(isComplete(buffer)===false){setTimeout(function(){$input.trigger("incomplete")},0);if(opts.clearIncomplete){resetMaskSet();if(opts.clearMaskOnLostFocus){buffer=[]}else{buffer=getBufferTemplate().slice()}}}writeBuffer(input,buffer,undefined,e)}if(undoValue!==getBuffer().join("")){undoValue=buffer.join("");$input.trigger("change")}}},mouseenterEvent:function(e){var input=this;mouseEnter=true;if(document.activeElement!==input&&opts.showMaskOnHover){HandleNativePlaceholder(input,(isRTL?getBuffer().slice().reverse():getBuffer()).join(""))}},submitEvent:function(e){if(undoValue!==getBuffer().join("")){$el.trigger("change")}if(opts.clearMaskOnLostFocus&&getLastValidPosition()===-1&&el.inputmask._valueGet&&el.inputmask._valueGet()===getBufferTemplate().join("")){el.inputmask._valueSet("")}if(opts.clearIncomplete&&isComplete(getBuffer())===false){el.inputmask._valueSet("")}if(opts.removeMaskOnSubmit){el.inputmask._valueSet(el.inputmask.unmaskedvalue(),true);setTimeout(function(){writeBuffer(el,getBuffer())},0)}},resetEvent:function(e){el.inputmask.refreshValue=true;setTimeout(function(){$el.trigger("setvalue")},0)}};function checkVal(input,writeOut,strict,nptvl,initiatingEvent){var inputmask=this||input.inputmask,inputValue=nptvl.slice(),charCodes="",initialNdx=-1,result=undefined;function isTemplateMatch(ndx,charCodes){var charCodeNdx=getMaskTemplate(true,0,false).slice(ndx,seekNext(ndx)).join("").replace(/'/g,"").indexOf(charCodes);return charCodeNdx!==-1&&!isMask(ndx)&&(getTest(ndx).match.nativeDef===charCodes.charAt(0)||getTest(ndx).match.fn===null&&getTest(ndx).match.nativeDef==="'"+charCodes.charAt(0)||getTest(ndx).match.nativeDef===" "&&(getTest(ndx+1).match.nativeDef===charCodes.charAt(0)||getTest(ndx+1).match.fn===null&&getTest(ndx+1).match.nativeDef==="'"+charCodes.charAt(0)))}resetMaskSet();if(!strict&&opts.autoUnmask!==true){var staticInput=getBufferTemplate().slice(0,seekNext(-1)).join(""),matches=inputValue.join("").match(new RegExp("^"+Inputmask.escapeRegex(staticInput),"g"));if(matches&&matches.length>0){inputValue.splice(0,matches.length*staticInput.length);initialNdx=seekNext(initialNdx)}}else{initialNdx=seekNext(initialNdx)}if(initialNdx===-1){getMaskSet().p=seekNext(initialNdx);initialNdx=0}else getMaskSet().p=initialNdx;inputmask.caretPos={begin:initialNdx};$.each(inputValue,function(ndx,charCode){if(charCode!==undefined){if(getMaskSet().validPositions[ndx]===undefined&&inputValue[ndx]===getPlaceholder(ndx)&&isMask(ndx,true)&&isValid(ndx,inputValue[ndx],true,undefined,undefined,true)===false){getMaskSet().p++}else{var keypress=new $.Event("_checkval");keypress.which=charCode.charCodeAt(0);charCodes+=charCode;var lvp=getLastValidPosition(undefined,true);if(!isTemplateMatch(initialNdx,charCodes)){result=EventHandlers.keypressEvent.call(input,keypress,true,false,strict,inputmask.caretPos.begin);if(result){initialNdx=inputmask.caretPos.begin+1;charCodes=""}}else{result=EventHandlers.keypressEvent.call(input,keypress,true,false,strict,lvp+1)}if(result){writeBuffer(undefined,getBuffer(),result.forwardPosition,keypress,false);inputmask.caretPos={begin:result.forwardPosition,end:result.forwardPosition}}}}});if(writeOut)writeBuffer(input,getBuffer(),result?result.forwardPosition:undefined,initiatingEvent||new $.Event("checkval"),initiatingEvent&&initiatingEvent.type==="input")}function unmaskedvalue(input){if(input){if(input.inputmask===undefined){return input.value}if(input.inputmask&&input.inputmask.refreshValue){EventHandlers.setValueEvent.call(input)}}var umValue=[],vps=getMaskSet().validPositions;for(var pndx in vps){if(vps[pndx].match&&vps[pndx].match.fn!=null){umValue.push(vps[pndx].input)}}var unmaskedValue=umValue.length===0?"":(isRTL?umValue.reverse():umValue).join("");if($.isFunction(opts.onUnMask)){var bufferValue=(isRTL?getBuffer().slice().reverse():getBuffer()).join("");unmaskedValue=opts.onUnMask.call(inputmask,bufferValue,unmaskedValue,opts)}return unmaskedValue}function caret(input,begin,end,notranslate){function translatePosition(pos){if(isRTL&&typeof pos==="number"&&(!opts.greedy||opts.placeholder!=="")&&el){pos=el.inputmask._valueGet().length-pos}return pos}var range;if(begin!==undefined){if($.isArray(begin)){end=isRTL?begin[0]:begin[1];begin=isRTL?begin[1]:begin[0]}if(begin.begin!==undefined){end=isRTL?begin.begin:begin.end;begin=isRTL?begin.end:begin.begin}if(typeof begin==="number"){begin=notranslate?begin:translatePosition(begin);end=notranslate?end:translatePosition(end);end=typeof end=="number"?end:begin;var scrollCalc=parseInt(((input.ownerDocument.defaultView||window).getComputedStyle?(input.ownerDocument.defaultView||window).getComputedStyle(input,null):input.currentStyle).fontSize)*end;input.scrollLeft=scrollCalc>input.scrollWidth?scrollCalc:0;input.inputmask.caretPos={begin:begin,end:end};if(input===document.activeElement){if("selectionStart"in input){input.selectionStart=begin;input.selectionEnd=end}else if(window.getSelection){range=document.createRange();if(input.firstChild===undefined||input.firstChild===null){var textNode=document.createTextNode("");input.appendChild(textNode)}range.setStart(input.firstChild,begin<input.inputmask._valueGet().length?begin:input.inputmask._valueGet().length);range.setEnd(input.firstChild,end<input.inputmask._valueGet().length?end:input.inputmask._valueGet().length);range.collapse(true);var sel=window.getSelection();sel.removeAllRanges();sel.addRange(range)}else if(input.createTextRange){range=input.createTextRange();range.collapse(true);range.moveEnd("character",end);range.moveStart("character",begin);range.select()}renderColorMask(input,{begin:begin,end:end})}}}else{if("selectionStart"in input){begin=input.selectionStart;end=input.selectionEnd}else if(window.getSelection){range=window.getSelection().getRangeAt(0);if(range.commonAncestorContainer.parentNode===input||range.commonAncestorContainer===input){begin=range.startOffset;end=range.endOffset}}else if(document.selection&&document.selection.createRange){range=document.selection.createRange();begin=0-range.duplicate().moveStart("character",-input.inputmask._valueGet().length);end=begin+range.text.length}return{begin:notranslate?begin:translatePosition(begin),end:notranslate?end:translatePosition(end)}}}function determineLastRequiredPosition(returnDefinition){var buffer=getMaskTemplate(true,getLastValidPosition(),true,true),bl=buffer.length,pos,lvp=getLastValidPosition(),positions={},lvTest=getMaskSet().validPositions[lvp],ndxIntlzr=lvTest!==undefined?lvTest.locator.slice():undefined,testPos;for(pos=lvp+1;pos<buffer.length;pos++){testPos=getTestTemplate(pos,ndxIntlzr,pos-1);ndxIntlzr=testPos.locator.slice();positions[pos]=$.extend(true,{},testPos)}var lvTestAlt=lvTest&&lvTest.alternation!==undefined?lvTest.locator[lvTest.alternation]:undefined;for(pos=bl-1;pos>lvp;pos--){testPos=positions[pos];if((testPos.match.optionality||testPos.match.optionalQuantifier&&testPos.match.newBlockMarker||lvTestAlt&&(lvTestAlt!==positions[pos].locator[lvTest.alternation]&&testPos.match.fn!=null||testPos.match.fn===null&&testPos.locator[lvTest.alternation]&&checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","),lvTestAlt.toString().split(","))&&getTests(pos)[0].def!==""))&&buffer[pos]===getPlaceholder(pos,testPos.match)){bl--}else break}return returnDefinition?{l:bl,def:positions[bl]?positions[bl].match:undefined}:bl}function clearOptionalTail(buffer){buffer.length=0;var template=getMaskTemplate(true,0,true,undefined,true),lmnt,validPos;while(lmnt=template.shift(),lmnt!==undefined)buffer.push(lmnt);return buffer}function isComplete(buffer){if($.isFunction(opts.isComplete))return opts.isComplete(buffer,opts);if(opts.repeat==="*")return undefined;var complete=false,lrp=determineLastRequiredPosition(true),aml=seekPrevious(lrp.l);if(lrp.def===undefined||lrp.def.newBlockMarker||lrp.def.optionality||lrp.def.optionalQuantifier){complete=true;for(var i=0;i<=aml;i++){var test=getTestTemplate(i).match;if(test.fn!==null&&getMaskSet().validPositions[i]===undefined&&test.optionality!==true&&test.optionalQuantifier!==true||test.fn===null&&buffer[i]!==getPlaceholder(i,test)){complete=false;break}}}return complete}function handleRemove(input,k,pos,strict,fromIsValid){if(opts.numericInput||isRTL){if(k===Inputmask.keyCode.BACKSPACE){k=Inputmask.keyCode.DELETE}else if(k===Inputmask.keyCode.DELETE){k=Inputmask.keyCode.BACKSPACE}if(isRTL){var pend=pos.end;pos.end=pos.begin;pos.begin=pend}}if(k===Inputmask.keyCode.BACKSPACE&&pos.end-pos.begin<1){pos.begin=seekPrevious(pos.begin);if(getMaskSet().validPositions[pos.begin]!==undefined&&getMaskSet().validPositions[pos.begin].input===opts.groupSeparator){pos.begin--}}else if(k===Inputmask.keyCode.DELETE&&pos.begin===pos.end){pos.end=isMask(pos.end,true)&&(getMaskSet().validPositions[pos.end]&&getMaskSet().validPositions[pos.end].input!==opts.radixPoint)?pos.end+1:seekNext(pos.end)+1;if(getMaskSet().validPositions[pos.begin]!==undefined&&getMaskSet().validPositions[pos.begin].input===opts.groupSeparator){pos.end++}}revalidateMask(pos);if(strict!==true&&opts.keepStatic!==false||opts.regex!==null){var result=alternate(true);if(result){var newPos=result.caret!==undefined?result.caret:result.pos?seekNext(result.pos.begin?result.pos.begin:result.pos):getLastValidPosition(-1,true);if(k!==Inputmask.keyCode.DELETE||pos.begin>newPos){pos.begin==newPos}}}var lvp=getLastValidPosition(pos.begin,true);if(lvp<pos.begin||pos.begin===-1){getMaskSet().p=seekNext(lvp)}else if(strict!==true){getMaskSet().p=pos.begin;if(fromIsValid!==true){while(getMaskSet().p<lvp&&getMaskSet().validPositions[getMaskSet().p]===undefined){getMaskSet().p++}}}}function initializeColorMask(input){var computedStyle=(input.ownerDocument.defaultView||window).getComputedStyle(input,null);function findCaretPos(clientx){var e=document.createElement("span"),caretPos;for(var style in computedStyle){if(isNaN(style)&&style.indexOf("font")!==-1){e.style[style]=computedStyle[style]}}e.style.textTransform=computedStyle.textTransform;e.style.letterSpacing=computedStyle.letterSpacing;e.style.position="absolute";e.style.height="auto";e.style.width="auto";e.style.visibility="hidden";e.style.whiteSpace="nowrap";document.body.appendChild(e);var inputText=input.inputmask._valueGet(),previousWidth=0,itl;for(caretPos=0,itl=inputText.length;caretPos<=itl;caretPos++){e.innerHTML+=inputText.charAt(caretPos)||"_";if(e.offsetWidth>=clientx){var offset1=clientx-previousWidth;var offset2=e.offsetWidth-clientx;e.innerHTML=inputText.charAt(caretPos);offset1-=e.offsetWidth/3;caretPos=offset1<offset2?caretPos-1:caretPos;break}previousWidth=e.offsetWidth}document.body.removeChild(e);return caretPos}var template=document.createElement("div");template.style.width=computedStyle.width;template.style.textAlign=computedStyle.textAlign;colorMask=document.createElement("div");input.inputmask.colorMask=colorMask;colorMask.className="im-colormask";input.parentNode.insertBefore(colorMask,input);input.parentNode.removeChild(input);colorMask.appendChild(input);colorMask.appendChild(template);input.style.left=template.offsetLeft+"px";$(colorMask).on("mouseleave",function(e){return EventHandlers.mouseleaveEvent.call(input,[e])});$(colorMask).on("mouseenter",function(e){return EventHandlers.mouseenterEvent.call(input,[e])});$(colorMask).on("click",function(e){caret(input,findCaretPos(e.clientX));return EventHandlers.clickEvent.call(input,[e])})}function renderColorMask(input,caretPos,clear){var maskTemplate=[],isStatic=false,test,testPos,ndxIntlzr,pos=0;function setEntry(entry){if(entry===undefined)entry="";if(!isStatic&&(test.fn===null||testPos.input===undefined)){isStatic=true;maskTemplate.push("<span class='im-static'>"+entry)}else if(isStatic&&(test.fn!==null&&testPos.input!==undefined||test.def==="")){isStatic=false;var mtl=maskTemplate.length;maskTemplate[mtl-1]=maskTemplate[mtl-1]+"</span>";maskTemplate.push(entry)}else maskTemplate.push(entry)}function setCaret(){if(document.activeElement===input){maskTemplate.splice(caretPos.begin,0,caretPos.begin===caretPos.end||caretPos.end>getMaskSet().maskLength?'<mark class="im-caret" style="border-right-width: 1px;border-right-style: solid;">':'<mark class="im-caret-select">');maskTemplate.splice(caretPos.end+1,0,"</mark>")}}if(colorMask!==undefined){var buffer=getBuffer();if(caretPos===undefined){caretPos=caret(input)}else if(caretPos.begin===undefined){caretPos={begin:caretPos,end:caretPos}}if(clear!==true){var lvp=getLastValidPosition();do{if(getMaskSet().validPositions[pos]){testPos=getMaskSet().validPositions[pos];test=testPos.match;ndxIntlzr=testPos.locator.slice();setEntry(buffer[pos])}else{testPos=getTestTemplate(pos,ndxIntlzr,pos-1);test=testPos.match;ndxIntlzr=testPos.locator.slice();if(opts.jitMasking===false||pos<lvp||typeof opts.jitMasking==="number"&&isFinite(opts.jitMasking)&&opts.jitMasking>pos){setEntry(getPlaceholder(pos,test))}else isStatic=false}pos++}while((maxLength===undefined||pos<maxLength)&&(test.fn!==null||test.def!=="")||lvp>pos||isStatic);if(isStatic)setEntry();setCaret()}var template=colorMask.getElementsByTagName("div")[0];template.innerHTML=maskTemplate.join("");input.inputmask.positionColorMask(input,template)}}function mask(elem){function isElementTypeSupported(input,opts){function patchValueProperty(npt){var valueGet;var valueSet;function patchValhook(type){if($.valHooks&&($.valHooks[type]===undefined||$.valHooks[type].inputmaskpatch!==true)){var valhookGet=$.valHooks[type]&&$.valHooks[type].get?$.valHooks[type].get:function(elem){return elem.value};var valhookSet=$.valHooks[type]&&$.valHooks[type].set?$.valHooks[type].set:function(elem,value){elem.value=value;return elem};$.valHooks[type]={get:function(elem){if(elem.inputmask){if(elem.inputmask.opts.autoUnmask){return elem.inputmask.unmaskedvalue()}else{var result=valhookGet(elem);return getLastValidPosition(undefined,undefined,elem.inputmask.maskset.validPositions)!==-1||opts.nullable!==true?result:""}}else return valhookGet(elem)},set:function(elem,value){var $elem=$(elem),result;result=valhookSet(elem,value);if(elem.inputmask){$elem.trigger("setvalue",[value])}return result},inputmaskpatch:true}}}function getter(){if(this.inputmask){return this.inputmask.opts.autoUnmask?this.inputmask.unmaskedvalue():getLastValidPosition()!==-1||opts.nullable!==true?document.activeElement===this&&opts.clearMaskOnLostFocus?(isRTL?clearOptionalTail(getBuffer().slice()).reverse():clearOptionalTail(getBuffer().slice())).join(""):valueGet.call(this):""}else return valueGet.call(this)}function setter(value){valueSet.call(this,value);if(this.inputmask){$(this).trigger("setvalue",[value])}}function installNativeValueSetFallback(npt){EventRuler.on(npt,"mouseenter",function(event){var $input=$(this),input=this,value=input.inputmask._valueGet();if(value!==getBuffer().join("")){$input.trigger("setvalue")}})}if(!npt.inputmask.__valueGet){if(opts.noValuePatching!==true){if(Object.getOwnPropertyDescriptor){if(typeof Object.getPrototypeOf!=="function"){Object.getPrototypeOf=typeof"test".__proto__==="object"?function(object){return object.__proto__}:function(object){return object.constructor.prototype}}var valueProperty=Object.getPrototypeOf?Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt),"value"):undefined;if(valueProperty&&valueProperty.get&&valueProperty.set){valueGet=valueProperty.get;valueSet=valueProperty.set;Object.defineProperty(npt,"value",{get:getter,set:setter,configurable:true})}else if(npt.tagName!=="INPUT"){valueGet=function(){return this.textContent};valueSet=function(value){this.textContent=value};Object.defineProperty(npt,"value",{get:getter,set:setter,configurable:true})}}else if(document.__lookupGetter__&&npt.__lookupGetter__("value")){valueGet=npt.__lookupGetter__("value");valueSet=npt.__lookupSetter__("value");npt.__defineGetter__("value",getter);npt.__defineSetter__("value",setter)}npt.inputmask.__valueGet=valueGet;npt.inputmask.__valueSet=valueSet}npt.inputmask._valueGet=function(overruleRTL){return isRTL&&overruleRTL!==true?valueGet.call(this.el).split("").reverse().join(""):valueGet.call(this.el)};npt.inputmask._valueSet=function(value,overruleRTL){valueSet.call(this.el,value===null||value===undefined?"":overruleRTL!==true&&isRTL?value.split("").reverse().join(""):value)};if(valueGet===undefined){valueGet=function(){return this.value};valueSet=function(value){this.value=value};patchValhook(npt.type);installNativeValueSetFallback(npt)}}}var elementType=input.getAttribute("type");var isSupported=input.tagName==="INPUT"&&$.inArray(elementType,opts.supportsInputType)!==-1||input.isContentEditable||input.tagName==="TEXTAREA";if(!isSupported){if(input.tagName==="INPUT"){var el=document.createElement("input");el.setAttribute("type",elementType);isSupported=el.type==="text";el=null}else isSupported="partial"}if(isSupported!==false){patchValueProperty(input)}else input.inputmask=undefined;return isSupported}EventRuler.off(elem);var isSupported=isElementTypeSupported(elem,opts);if(isSupported!==false){el=elem;$el=$(el);originalPlaceholder=el.placeholder;maxLength=el!==undefined?el.maxLength:undefined;if(maxLength===-1)maxLength=undefined;if(opts.colorMask===true){initializeColorMask(el)}if(mobile){if("inputmode"in el){el.inputmode=opts.inputmode;el.setAttribute("inputmode",opts.inputmode)}if(opts.disablePredictiveText===true){if("autocorrect"in el){el.autocorrect=false}else{if(opts.colorMask!==true){initializeColorMask(el)}el.type="password"}}}if(isSupported===true){el.setAttribute("im-insert",opts.insertMode);EventRuler.on(el,"submit",EventHandlers.submitEvent);EventRuler.on(el,"reset",EventHandlers.resetEvent);EventRuler.on(el,"blur",EventHandlers.blurEvent);EventRuler.on(el,"focus",EventHandlers.focusEvent);if(opts.colorMask!==true){EventRuler.on(el,"click",EventHandlers.clickEvent);EventRuler.on(el,"mouseleave",EventHandlers.mouseleaveEvent);EventRuler.on(el,"mouseenter",EventHandlers.mouseenterEvent)}EventRuler.on(el,"paste",EventHandlers.pasteEvent);EventRuler.on(el,"cut",EventHandlers.cutEvent);EventRuler.on(el,"complete",opts.oncomplete);EventRuler.on(el,"incomplete",opts.onincomplete);EventRuler.on(el,"cleared",opts.oncleared);if(!mobile&&opts.inputEventOnly!==true){EventRuler.on(el,"keydown",EventHandlers.keydownEvent);EventRuler.on(el,"keypress",EventHandlers.keypressEvent)}else{el.removeAttribute("maxLength")}EventRuler.on(el,"input",EventHandlers.inputFallBackEvent);EventRuler.on(el,"beforeinput",EventHandlers.beforeInputEvent)}EventRuler.on(el,"setvalue",EventHandlers.setValueEvent);undoValue=getBufferTemplate().join("");if(el.inputmask._valueGet(true)!==""||opts.clearMaskOnLostFocus===false||document.activeElement===el){var initialValue=$.isFunction(opts.onBeforeMask)?opts.onBeforeMask.call(inputmask,el.inputmask._valueGet(true),opts)||el.inputmask._valueGet(true):el.inputmask._valueGet(true);if(initialValue!=="")checkVal(el,true,false,initialValue.split(""));var buffer=getBuffer().slice();undoValue=buffer.join("");if(isComplete(buffer)===false){if(opts.clearIncomplete){resetMaskSet()}}if(opts.clearMaskOnLostFocus&&document.activeElement!==el){if(getLastValidPosition()===-1){buffer=[]}else{clearOptionalTail(buffer)}}if(opts.clearMaskOnLostFocus===false||opts.showMaskOnFocus&&document.activeElement===el||el.inputmask._valueGet(true)!=="")writeBuffer(el,buffer);if(document.activeElement===el){caret(el,seekNext(getLastValidPosition()))}}}}var valueBuffer;if(actionObj!==undefined){switch(actionObj.action){case"isComplete":el=actionObj.el;return isComplete(getBuffer());case"unmaskedvalue":if(el===undefined||actionObj.value!==undefined){valueBuffer=actionObj.value;valueBuffer=($.isFunction(opts.onBeforeMask)?opts.onBeforeMask.call(inputmask,valueBuffer,opts)||valueBuffer:valueBuffer).split("");checkVal.call(this,undefined,false,false,valueBuffer);if($.isFunction(opts.onBeforeWrite))opts.onBeforeWrite.call(inputmask,undefined,getBuffer(),0,opts)}return unmaskedvalue(el);case"mask":mask(el);break;case"format":valueBuffer=($.isFunction(opts.onBeforeMask)?opts.onBeforeMask.call(inputmask,actionObj.value,opts)||actionObj.value:actionObj.value).split("");checkVal.call(this,undefined,true,false,valueBuffer);if(actionObj.metadata){return{value:isRTL?getBuffer().slice().reverse().join(""):getBuffer().join(""),metadata:maskScope.call(this,{action:"getmetadata"},maskset,opts)}}return isRTL?getBuffer().slice().reverse().join(""):getBuffer().join("");case"isValid":if(actionObj.value){valueBuffer=actionObj.value.split("");checkVal.call(this,undefined,true,true,valueBuffer)}else{actionObj.value=getBuffer().join("")}var buffer=getBuffer();var rl=determineLastRequiredPosition(),lmib=buffer.length-1;for(;lmib>rl;lmib--){if(isMask(lmib))break}buffer.splice(rl,lmib+1-rl);return isComplete(buffer)&&actionObj.value===getBuffer().join("");case"getemptymask":return getBufferTemplate().join("");case"remove":if(el&&el.inputmask){$.data(el,"_inputmask_opts",null);$el=$(el);el.inputmask._valueSet(opts.autoUnmask?unmaskedvalue(el):el.inputmask._valueGet(true));EventRuler.off(el);if(el.inputmask.colorMask){colorMask=el.inputmask.colorMask;colorMask.removeChild(el);colorMask.parentNode.insertBefore(el,colorMask);colorMask.parentNode.removeChild(colorMask)}var valueProperty;if(Object.getOwnPropertyDescriptor&&Object.getPrototypeOf){valueProperty=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el),"value");if(valueProperty){if(el.inputmask.__valueGet){Object.defineProperty(el,"value",{get:el.inputmask.__valueGet,set:el.inputmask.__valueSet,configurable:true})}}}else if(document.__lookupGetter__&&el.__lookupGetter__("value")){if(el.inputmask.__valueGet){el.__defineGetter__("value",el.inputmask.__valueGet);el.__defineSetter__("value",el.inputmask.__valueSet)}}el.inputmask=undefined}return el;break;case"getmetadata":if($.isArray(maskset.metadata)){var maskTarget=getMaskTemplate(true,0,false).join("");$.each(maskset.metadata,function(ndx,mtdt){if(mtdt.mask===maskTarget){maskTarget=mtdt;return false}});return maskTarget}return maskset.metadata}}}return Inputmask});;
/*!
* jquery.inputmask.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2019 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.7
*/

(function(factory) {
    if (typeof define === "function" && define.amd) {
        define([ "jquery", "./inputmask" ], factory);
    } else if (typeof exports === "object") {
        module.exports = factory(require("jquery"), require("./inputmask"));
    } else {
        factory(jQuery, window.Inputmask);
    }
})(function($, Inputmask) {
    if ($.fn.inputmask === undefined) {
        $.fn.inputmask = function(fn, options) {
            var nptmask, input = this[0];
            if (options === undefined) options = {};
            if (typeof fn === "string") {
                switch (fn) {
                  case "unmaskedvalue":
                    return input && input.inputmask ? input.inputmask.unmaskedvalue() : $(input).val();

                  case "remove":
                    return this.each(function() {
                        if (this.inputmask) this.inputmask.remove();
                    });

                  case "getemptymask":
                    return input && input.inputmask ? input.inputmask.getemptymask() : "";

                  case "hasMaskedValue":
                    return input && input.inputmask ? input.inputmask.hasMaskedValue() : false;

                  case "isComplete":
                    return input && input.inputmask ? input.inputmask.isComplete() : true;

                  case "getmetadata":
                    return input && input.inputmask ? input.inputmask.getmetadata() : undefined;

                  case "setvalue":
                    Inputmask.setValue(input, options);
                    break;

                  case "option":
                    if (typeof options === "string") {
                        if (input && input.inputmask !== undefined) {
                            return input.inputmask.option(options);
                        }
                    } else {
                        return this.each(function() {
                            if (this.inputmask !== undefined) {
                                return this.inputmask.option(options);
                            }
                        });
                    }
                    break;

                  default:
                    options.alias = fn;
                    nptmask = new Inputmask(options);
                    return this.each(function() {
                        nptmask.mask(this);
                    });
                }
            } else if (Array.isArray(fn)) {
                options.alias = fn;
                nptmask = new Inputmask(options);
                return this.each(function() {
                    nptmask.mask(this);
                });
            } else if (typeof fn == "object") {
                nptmask = new Inputmask(fn);
                if (fn.mask === undefined && fn.alias === undefined) {
                    return this.each(function() {
                        if (this.inputmask !== undefined) {
                            return this.inputmask.option(fn);
                        } else nptmask.mask(this);
                    });
                } else {
                    return this.each(function() {
                        nptmask.mask(this);
                    });
                }
            } else if (fn === undefined) {
                return this.each(function() {
                    nptmask = new Inputmask(options);
                    nptmask.mask(this);
                });
            }
        };
    }
    return $.fn.inputmask;
});;
/**
 * Autotab - jQuery plugin 1.9.2
 * https://github.com/Mathachew/jquery-autotab
 * 
 * Copyright (c) 2008, 2015 Matthew Miller
 * 
 * Licensed under the MIT licensing:
 *   http://www.opensource.org/licenses/mit-license.php
 */

(function ($) {
    var platform = navigator.platform,
        settings = {
            tabPause: 800,
            focusChange: null,
            iOS: (platform === 'iPad' || platform === 'iPhone' || platform === 'iPod'),
            firefox: (typeof InstallTrigger !== 'undefined'),
            ie11: !(window.ActiveXObject) && "ActiveXObject" in window
        };

    var setSettings = function (e, settings) {
        if (settings === null || typeof settings === 'undefined') {
            return;
        }

        for (var key in settings) {
            $(e).data('autotab-' + key, settings[key]);
        }
    };

    var getSettings = function (e) {
        var settings = {
            arrowKey: false,
            format: 'all',
            loaded: false,
            disabled: false,
            pattern: null,
            uppercase: false,
            lowercase: false,
            nospace: false,
            maxlength: 2147483647,
            target: null,
            previous: null,
            trigger: null,
            originalValue: '',
            changed: false,
            editable: (e.type === 'text' || e.type === 'password' || e.type === 'textarea' || e.type === 'tel' || e.type === 'number' || e.type === 'email' || e.type === 'search' || e.type === 'url'),
            filterable: (e.type === 'text' || e.type === 'password' || e.type === 'textarea'),
            tabOnSelect: false
        };

        // If $.autotab.selectFilterByClas is true and the format not specified, automatically select an element's format based on a matching class name.
        // The first matched element becomes the selected format for the filter.
        if ($.autotab.selectFilterByClass === true && typeof $(e).data('autotab-format') === 'undefined') {
            var classes = ['all', 'text', 'alpha', 'number', 'numeric', 'alphanumeric', 'hex', 'hexadecimal', 'custom'];

            for (var key in classes) {
                if ($(e).hasClass(classes[key])) {
                    settings.format = classes[key];
                    break;
                }
            }
        }

        for (var key in settings) {
            if (typeof $(e).data('autotab-' + key) !== 'undefined') {
                settings[key] = $(e).data('autotab-' + key);
            }
        }

        // Save settings on first run
        if (!settings.loaded) {
            if (settings.trigger !== null && typeof settings.trigger === 'string') {
                settings.trigger = settings.trigger.toString();
            }

            setSettings(e, settings);
        }

        return settings;
    };

    var queryObject = function (e) {
        return (typeof e !== 'undefined' && (typeof e === 'string' || !(e instanceof jQuery)));
    };

    var getSelection = function (e) {
        var start = 0,
            end = 0,
            selectionType = 0;

        if (e.type === 'text' || e.type === 'password' || e.type === 'textarea') {
            if (typeof e.selectionStart === 'number' && typeof e.selectionEnd === 'number') {
                // Non-IE browsers and IE 9+
                start = e.selectionStart;
                end = e.selectionEnd;
                selectionType = 1;
            }
            else if (document.selection && document.selection.createRange) {
                // For IE up to version 8
                var selectionRange = document.selection.createRange(),
                    textInputRange = e.createTextRange(),
                    precedingRange = e.createTextRange(),
                    bookmark = selectionRange.getBookmark();
                textInputRange.moveToBookmark(bookmark);
                precedingRange.setEndPoint("EndToStart", textInputRange);
                start = precedingRange.text.length;
                end = start + selectionRange.text.length;
                selectionType = 2;
            }
        }

        return {
            start: start,
            end: end,
            selectionType: selectionType
        };
    };

    $.autotab = function (options) {
        if (typeof options !== 'object') {
            options = {};
        }

        $(':input').autotab(options);
    };

    $.autotab.selectFilterByClass = false;

    $.autotab.next = function () {
        var e = $(document.activeElement);

        if (e.length) {
            e.trigger('autotab-next');
        }
    };

    $.autotab.previous = function () {
        var e = $(document.activeElement);

        if (e.length) {
            e.trigger('autotab-previous');
        }
    };

    $.autotab.remove = function (e) {
        queryObject(e) ? $(e).autotab('remove') : $(':input').autotab('remove');
    };

    $.autotab.restore = function (e) {
        queryObject(e) ? $(e).autotab('restore') : $(':input').autotab('restore');
    };

    $.autotab.refresh = function (e) {
        queryObject(e) ? $(e).autotab('refresh') : $(':input').autotab('refresh');
    };

    $.fn.autotab = function (method, options) {
        if (!this.length) {
            return this;
        }

        // Remove hidden fields since tabbing backwards is supported on different form elements
        var filtered = $.grep(this, function (e, i) {
            return e.type != 'hidden';
        });

        // Apply filter options
        if (method == 'filter') {
            if (typeof options === 'string' || typeof options === 'function') {
                options = { format: options };
            }

            for (var i = 0, length = filtered.length; i < length; i++) {
                var defaults = getSettings(filtered[i]),
                    newOptions = options;

                // Retain the established target/previous values as this area is for filtering only
                newOptions.target = defaults.target;
                newOptions.previous = defaults.previous;

                $.extend(defaults, newOptions);

                if (!defaults.loaded) {
                    defaults.disabled = true;
                    autotabBind(filtered[i], newOptions);
                }
                else {
                    setSettings(filtered[i], defaults);
                }
            }
        }
        // Disable auto tab and filtering
        else if (method == 'remove' || method == 'destroy' || method == 'disable') {
            for (var i = 0, length = filtered.length; i < length; i++) {
                var defaults = getSettings(filtered[i]);

                defaults.disabled = true;

                setSettings(filtered[i], defaults);
            }
        }
        // Re-enable auto tab and filtering
        else if (method == 'restore' || method == 'enable') {
            for (var i = 0, length = filtered.length; i < length; i++) {
                var defaults = getSettings(filtered[i]);

                defaults.disabled = false;

                setSettings(filtered[i], defaults);
            }
        }
        // Refresh target/previous elements
        else if (method == 'refresh') {
            for (var i = 0, length = filtered.length; i < length; i++) {
                var defaults = getSettings(filtered[i]),
                    n = i + 1,
                    p = i - 1,
                    selectTarget = function () {
                        if (i > 0 && n < length) {
                            defaults.target = filtered[n];
                        }
                        else if (i > 0) {
                            defaults.target = null;
                        }
                        else {
                            defaults.target = filtered[n];
                        }   
                    },
                    selectPrevious = function () {
                        if (i > 0 && n < length) {
                            defaults.previous = filtered[p];
                        }
                        else if (i > 0) {
                            defaults.previous = filtered[p];
                        }
                        else {
                            defaults.previous = null;
                        }
                    };

                // Nothing was specified for the target element, so automatically set it
                if (defaults.target === null || defaults.target.selector === '') {
                    selectTarget();
                }
                else if (typeof defaults.target === 'string' || defaults.target.selector) {
                    defaults.target = $(typeof defaults.target === 'string' ? defaults.target : defaults.target.selector);

                    if (defaults.target.length === 0) {
                        selectTarget();
                    }
                }

                // Nothing was specified for the previous element, so automatically set it
                if (defaults.previous === null || defaults.previous.selector === '') {
                    selectPrevious();
                }
                else if (typeof defaults.previous === 'string' || defaults.previous.selector) {
                    defaults.previous = $(typeof defaults.previous === 'string' ? defaults.previous : defaults.previous.selector);

                    if (defaults.previous.length === 0) {
                        selectPrevious();
                    }
                }

                if (!defaults.loaded) {
                    autotabBind(filtered[i], defaults);
                }
                else {
                    if (queryObject(defaults.target)) {
                        defaults.target = $(defaults.target);
                    }

                    if (queryObject(defaults.previous)) {
                        defaults.previous = $(defaults.previous);
                    }

                    setSettings(filtered[i], defaults);
                }
            }
        }
        else {
            if (method === null || typeof method === 'undefined') {
                options = {};
            }
            else if (typeof method === 'string' || typeof method === 'function') {
                options = { format: method };
            }
            else if (typeof method === 'object') {
                options = method;
            }

            // Bind key events to element(s) passed
            if (filtered.length > 1) {
                for (var i = 0, length = filtered.length; i < length; i++) {
                    var n = i + 1,
                        p = i - 1,
                        newOptions = options;

                    if (i > 0 && n < length) {
                        newOptions.target = filtered[n];
                        newOptions.previous = filtered[p];
                    }
                    else if (i > 0) {
                        newOptions.target = null;
                        newOptions.previous = filtered[p];
                    }
                    else {
                        newOptions.target = filtered[n];
                        newOptions.previous = null;
                    }

                    autotabBind(filtered[i], newOptions);
                }
            }
            else {
                autotabBind(filtered[0], options);
            }
        }

        return this;
    };

    var filterValue = function (e, value, defaults) {
        if (typeof defaults.format === 'function') {
            return defaults.format(value, e);
        }

        var pattern = null;

        switch (defaults.format) {
            case 'text':
                pattern = new RegExp('[0-9]+', 'g');
                break;

            case 'alpha':
                pattern = new RegExp('[^a-zA-Z]+', 'g');
                break;

            case 'number':
            case 'numeric':
                pattern = new RegExp('[^0-9]+', 'g');
                break;

            case 'alphanumeric':
                pattern = new RegExp('[^0-9a-zA-Z]+', 'g');
                break;

            case 'hex':
            case 'hexadecimal':
                pattern = new RegExp('[^0-9A-Fa-f]+', 'g');
                break;

            case 'custom':
                pattern = new RegExp(defaults.pattern, 'g');
                break;

            case 'all':
            default:
                break;
        }

        if (pattern !== null) {
            value = value.replace(pattern, '');
        }

        if (defaults.nospace) {
            pattern = new RegExp('[ ]+', 'g');
            value = value.replace(pattern, '');
        }

        if (defaults.uppercase) {
            value = value.toUpperCase();
        }

        if (defaults.lowercase) {
            value = value.toLowerCase();
        }

        return value;
    };

    var autotabBind = function (element, options) {
        var defaults = getSettings(element);

        if (defaults.disabled) {
            defaults.disabled = false;
            defaults.target = null;
            defaults.previous = null;
        }

        $.extend(defaults, options);

        // Sets targets to element based on the name or ID passed if they are not currently objects
        if (queryObject(defaults.target)) {
            defaults.target = $(defaults.target);
        }

        if (queryObject(defaults.previous)) {
            defaults.previous = $(defaults.previous);
        }

        var oldMaxlength = element.maxLength;

        if (typeof element.maxLength === 'undefined' && element.type == 'textarea') {
            oldMaxlength = element.maxLength = element.getAttribute('maxlength');
        }

        // defaults.maxlength has not changed and maxlength was specified
        if (defaults.maxlength == 2147483647 && oldMaxlength != 2147483647 && oldMaxlength != -1) {
            defaults.maxlength = oldMaxlength;
        }
        // defaults.maxlength overrides maxlength
        else if (defaults.maxlength > 0) {
            element.maxLength = defaults.maxlength;
        }
        // defaults.maxlength and maxlength have not been specified
        // A target cannot be used since there is no defined maxlength
        else {
            defaults.target = null;
        }

        if (!defaults.loaded) {
            defaults.loaded = true;
            setSettings(element, defaults);
        }
        else {
            setSettings(element, defaults);
            return;
        }

        // Add a change event to select lists only so that we can auto tab when a value is selected
        if (element.type == 'select-one') {
            $(element).on('change', function (e) {
                var defaults = getSettings(this);

                if (defaults.tabOnSelect) {
                    $(this).trigger('autotab-next');
                }
            });
        }

        // The 1ms timeouts allow for keypress events to complete in case a
        // custom function or exterior method calls for a manual auto tab
        $(element).on('autotab-next', function (event, defaults) {
            var self = this;
            setTimeout(function () {
                if (!defaults) {
                    defaults = getSettings(self);
                }

                var target = defaults.target;

                if (!defaults.disabled && target.length) {
                    // Using focus on iOS devices is a pain, so use the browser's next/previous buttons to proceed
                    if (!settings.iOS) {

                        // Field is disabled/readonly, so tab to next element
                        if (target.prop('disabled') || target.prop('readonly')) {
                            target.trigger('autotab-next');
                        }
                        else {
                            // Allows the user to navigate between each charater with arrow keys
                            if (defaults.arrowKey) {
                                target.focus();
                            }
                            else {
                                target.focus().select();
                            }
                        }

                        settings.focusChange = new Date();
                    }
                }
            }, 1);
        }).on('autotab-previous', function (event, defaults) {
            var self = this;
            setTimeout(function () {
                if (!defaults) {
                    defaults = getSettings(self);
                }

                var previous = defaults.previous;

                if (!defaults.disabled && previous.length) {
                    var value = previous.val();

                    // Field is disabled/readonly, so tab to previous element
                    if (previous.prop('disabled') || previous.prop('readonly')) {
                        previous.trigger('autotab-previous');
                    }
                    else if (value.length && previous.data('autotab-editable') && !defaults.arrowKey) {
                        if (settings.ie11) {
                            previous.val(value.substring(0, value.length - 1)).focus();
                        }
                        else {
                            previous.focus().val(value.substring(0, value.length - 1));
                        }

                        setSettings(previous, { changed: true });
                    }
                    else {
                        if (defaults.arrowKey) {
                            setSettings(this, { arrowKey: false });
                        }

                        if (settings.ie11) {
                            previous.val(value).focus();
                        }
                        else {
                            previous.focus().val(value);
                        }
                    }

                    settings.focusChange = null;
                }
            }, 1);
        }).on('focus', function () {
            setSettings(this, { originalValue: this.value });
        }).on('blur', function () {
            var defaults = getSettings(this);

            if (defaults.changed && this.value != defaults.originalValue) {
                setSettings(this, { changed: false });
                $(this).change();
            }
        }).on('keydown.autotab', function (e) {
            var defaults = getSettings(this);

            if (!defaults || defaults.disabled) {
                return true;
            }

            var selection = getSelection(this),
                keyCode = e.which || e.charCode;

            // Go to the previous element when backspace
            // is pressed in an empty input field
            if (keyCode == 8) {
                defaults.arrowKey = false;

                // Prevent the browser from of navigating to the previous page
                if (!defaults.editable) {
                    $(this).trigger('autotab-previous', defaults);
                    return false;
                }

                setSettings(this, { changed: (this.value !== defaults.originalValue) });

                if (this.value.length === 0) {
                    $(this).trigger('autotab-previous', defaults);
                    return;
                }
            }
            else if (keyCode == 9 && settings.focusChange !== null) {
                // Tab backwards
                if (e.shiftKey) {
                    settings.focusChange = null;
                    return;
                }

                if ((new Date().getTime() - settings.focusChange.getTime()) < settings.tabPause) {
                    settings.focusChange = null;
                    return false;
                }
            }
            else if (this.type !== 'range' && this.type !== 'select-one' && this.type !== 'select-multiple') {
                if ((this.type !== 'tel' && this.type !== 'number') || ((this.type === 'tel' || this.type === 'number') && this.value.length == 0)) {
                    if (keyCode == 37 && (!defaults.editable || selection.start == 0)) {
                        defaults.arrowKey = true;
                        $(this).trigger('autotab-previous', defaults);
                    }
                    else if (keyCode == 39 && (!defaults.editable || !defaults.filterable || selection.end == this.value.length || this.value.length == 0)) {
                        defaults.arrowKey = true;
                        $(this).trigger('autotab-next', defaults);
                    }
                }
            }
        }).on('keypress.autotab', function (e) {
            var defaults = getSettings(this),
                keyCode = e.which || e.keyCode;

            // e.charCode == 0 indicates a special key has been pressed, which only Firefox triggers
            if (!defaults || defaults.disabled || (settings.firefox && e.charCode === 0) || e.ctrlKey || e.altKey || keyCode == 13 || this.disabled) {
                return true;
            }

            var keyChar = String.fromCharCode(keyCode);

            if (this.type != 'text' && this.type != 'password' && this.type != 'textarea') {
                // this.value.length is the length before the keypress event was trigged
                if ((this.value.length + 1) >= defaults.maxlength) {
                    defaults.arrowKey = false;
                    $(this).trigger('autotab-next', defaults);
                }

                return !(this.value.length == defaults.maxlength);
            }

            // Prevents auto tabbing when defaults.trigger is pressed
            if (defaults.trigger !== null && defaults.trigger.indexOf(keyChar) >= 0) {
                if (settings.focusChange !== null && (new Date().getTime() - settings.focusChange.getTime()) < settings.tabPause) {
                    settings.focusChange = null;
                }
                else {
                    defaults.arrowKey = false;
                    $(this).trigger('autotab-next', defaults);
                }

                return false;
            }

            settings.focusChange = null;

            var hasValue = document.selection && document.selection.createRange ? true : (keyCode > 0);

            keyChar = filterValue(this, keyChar, defaults);

            if (hasValue && (keyChar === null || keyChar === '')) {
                return false;
            }

            // Many, many thanks to Tim Down for this solution: http://stackoverflow.com/a/3923320/94656
            if (hasValue && (this.value.length <= this.maxLength)) {
                var selection = getSelection(this);

                // Text is fully selected, so it needs to be replaced
                if (selection.start === 0 && selection.end == this.value.length) {
                    this.value = keyChar;
                    setSettings(this, { changed: (this.value != defaults.originalValue) });
                }
                else {
                    if (this.value.length == this.maxLength && selection.start === selection.end) {
                        defaults.arrowKey = false;
                        $(this).trigger('autotab-next', defaults);
                        return false;
                    }

                    this.value = this.value.slice(0, selection.start) + keyChar + this.value.slice(selection.end);
                    setSettings(this, { changed: (this.value != defaults.originalValue) });
                }

                // Prevents the cursor position from being set to the end of the text box
                // This is called even if the text is fully selected and replaced due to an unexpected behavior in IE6 and up (#32)
                if (this.value.length != defaults.maxlength) {
                    selection.start++;

                    if (selection.selectionType == 1) {
                        this.selectionStart = this.selectionEnd = selection.start;
                    }
                    else if (selection.selectionType == 2) {
                        var range = this.createTextRange();
                        range.collapse(true);
                        range.moveEnd('character', selection.start);
                        range.moveStart('character', selection.start);
                        range.select();
                    }
                }
            }


            if (this.value.length == defaults.maxlength) {
                defaults.arrowKey = false;
                $(this).trigger('autotab-next', defaults);
            }

            return false;
        }).on('drop paste', function (e) {
            var defaults = getSettings(this);

            if (!defaults) {
                return true;
            }

            this.maxLength = 2147483647;

            (function (e, originDefaults) {
                setTimeout(function () {
                    var lastIndex = -1,
                        hiddenInput = document.createElement('input');
                    hiddenInput.type = 'hidden';
                    hiddenInput.value = e.value.toLowerCase();
                    hiddenInput.originalValue = e.value;

                    e.value = filterValue(e, e.value, originDefaults).substr(0, originDefaults.maxlength);

                    var handlePaste = function (e, previousValue) {
                        if (!e) {
                            return;
                        }

                        var defaults = getSettings(e);

                        if ($(e).prop('disabled') || $(e).prop('readonly') || !defaults.editable) {
                            $(e).trigger('autotab-next');

                            if (!settings.iOS) {
                                handlePaste(defaults.target[0], previousValue);
                            }
                            return;
                        }

                        for (var i = 0, count = previousValue.length; i < count; i++) {
                            lastIndex = hiddenInput.value.indexOf(previousValue.charAt(i).toLowerCase(), lastIndex) + 1;
                        }

                        var trimmedValue = hiddenInput.originalValue.substr(lastIndex),
                            filteredValue = filterValue(e, trimmedValue, defaults).substr(0, defaults.maxlength);

                        if (!filteredValue) {
                            return;
                        }

                        e.value = filteredValue;

                        if (filteredValue.length == defaults.maxlength) {
                            defaults.arrowKey = false;
                            $(e).trigger('autotab-next', defaults);

                            // Firefox causes all but the first and last elements to retain a select all state, so in order to
                            // effectively support arrow keys, the starting point of the selection is to the last possible cursor
                            if (settings.firefox) {
                                setTimeout(function () {
                                    e.selectionStart = e.value.length;
                                }, 1);
                            }

                            if (!settings.iOS) {
                                handlePaste(defaults.target[0], filteredValue);
                            }
                        }

                    };

                    if (e.value.length == originDefaults.maxlength) {
                        defaults.arrowKey = false;
                        $(e).trigger('autotab-next', defaults);

                        if (!settings.iOS) {
                            handlePaste(originDefaults.target[0], e.value.toLowerCase());
                        }
                    }

                    e.maxLength = originDefaults.maxlength;
                }, 1);
            })(this, defaults);
        });
    };

    // Deprecated, here for backwards compatibility
    $.fn.autotab_magic = function (focus) {
        return $(this).autotab();
    };
    $.fn.autotab_filter = function (options) {
        var defaults = {};

        if (typeof options === 'string' || typeof options === 'function') {
            defaults.format = options;
        }
        else {
            $.extend(defaults, options);
        }

        return $(this).autotab('filter', defaults);
    };

})(jQuery);
;
/*!
* inputmask.extensions.min.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2019 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.7
*/

(function(factory){if(typeof define==="function"&&define.amd){define(["./inputmask"],factory)}else if(typeof exports==="object"){module.exports=factory(require("./inputmask"))}else{factory(window.Inputmask)}})(function(Inputmask){Inputmask.extendDefinitions({A:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",casing:"upper"},"&":{validator:"[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",casing:"upper"},"#":{validator:"[0-9A-Fa-f]",casing:"upper"}});Inputmask.extendAliases({cssunit:{regex:"[+-]?[0-9]+\\.?([0-9]+)?(px|em|rem|ex|%|in|cm|mm|pt|pc)"},url:{regex:"(https?|ftp)//.*",autoUnmask:false},ip:{mask:"i[i[i]].i[i[i]].i[i[i]].i[i[i]]",definitions:{i:{validator:function(chrs,maskset,pos,strict,opts){if(pos-1>-1&&maskset.buffer[pos-1]!=="."){chrs=maskset.buffer[pos-1]+chrs;if(pos-2>-1&&maskset.buffer[pos-2]!=="."){chrs=maskset.buffer[pos-2]+chrs}else chrs="0"+chrs}else chrs="00"+chrs;return new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs)}}},onUnMask:function(maskedValue,unmaskedValue,opts){return maskedValue},inputmode:"numeric"},email:{mask:"*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}.-{1,63}[.-{1,63}][.-{1,63}]",greedy:false,casing:"lower",onBeforePaste:function(pastedValue,opts){pastedValue=pastedValue.toLowerCase();return pastedValue.replace("mailto:","")},definitions:{"*":{validator:"[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5!#$%&'*+/=?^_`{|}~-]"},"-":{validator:"[0-9A-Za-z-]"}},onUnMask:function(maskedValue,unmaskedValue,opts){return maskedValue},inputmode:"email"},mac:{mask:"##:##:##:##:##:##"},vin:{mask:"V{13}9{4}",definitions:{V:{validator:"[A-HJ-NPR-Za-hj-npr-z\\d]",casing:"upper"}},clearIncomplete:true,autoUnmask:true}});return Inputmask});;
/**
  * TextOverflowClamp.js
  *
  * Updated 2013-05-09 to remove jQuery dependency.
  * But be careful with webfonts!
  */

// bind function support for older browsers without it
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP = function () { },
            fBound = function () {
                return fToBind.apply(this instanceof fNOP && oThis
                                       ? this
                                       : oThis,
                                     aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound;
    };
}

(function (w, d) {
    var clamp, measure, text, lineWidth,
		lineStart, lineCount, wordStart,
		line, lineText, wasNewLine,
    ce = d.createElement.bind(d),
    ctn = d.createTextNode.bind(d);

    // measurement element is made a child of the clamped element to get it's style
    measure = ce('span');

    (function (s) {
        s.position = 'absolute'; // prevent page reflow
        s.whiteSpace = 'pre'; // cross-browser width results
        s.visibility = 'hidden'; // prevent drawing
    })(measure.style);

    clamp = function(el, lineClamp) {
        // make sure the element belongs to the document
        if (!el.ownerDocument || !el.ownerDocument === d) return;
        // reset to safe starting values
        lineStart = wordStart = 0;
        lineCount = 1;
        wasNewLine = false;
        lineWidth = el.clientWidth;
        // get all the text, remove any line changes
        text = (el.textContent || el.innerText).replace(/\n/g, ' ');
        // remove all content
        while (el.firstChild !== null)
            el.removeChild(el.firstChild);
        // add measurement element within so it inherits styles
        el.appendChild(measure);
        // http://ejohn.org/blog/search-and-dont-replace/
        text.replace(/ /g, function(m, pos) {
            // ignore any further processing if we have total lines
            if (lineCount === lineClamp) return;
            // create a text node and place it in the measurement element
            measure.appendChild(ctn(text.substr(lineStart, pos - lineStart)));
            // have we exceeded allowed line width?
            if (lineWidth < measure.clientWidth) {
                if (wasNewLine) {
                    // we have a long word so it gets a line of it's own
                    lineText = text.substr(lineStart, pos + 1 - lineStart);
                    // next line start position
                    lineStart = pos + 1;
                } else {
                    // grab the text until this word
                    lineText = text.substr(lineStart, wordStart - lineStart);
                    // next line start position
                    lineStart = wordStart;
                }
                // create a line element
                line = ce('span');
                // add text to the line element
                line.appendChild(ctn(lineText));
                // add the line element to the container
                el.appendChild(line);
                // yes, we created a new line
                wasNewLine = true;
                lineCount++;
            } else {
                // did not create a new line
                wasNewLine = false;
            }
            // remember last word start position
            wordStart = pos + 1;
            // clear measurement element
            measure.removeChild(measure.firstChild);
        });
        // remove the measurement element from the container
        el.removeChild(measure);
        // create the last line element
        line = ce('span');
        // give styles required for text-overflow to kick in
        (function(s) {
            s.display = 'inline-block';
            s.overflow = 'hidden';
            s.textOverflow = 'ellipsis';
            s.whiteSpace = 'nowrap';
            s.width = '100%';
        })(line.style);
        // add all remaining text to the line element
        line.appendChild(ctn(text.substr(lineStart)));
        // add the line element to the container
        el.appendChild(line);
    };
    w.clamp = clamp;
})(window, document);;
(function (window, undefined) {

    var ADJUSTMENT_EVENTS = 'scroll resize';
    var DEFAULT_MAX_MOBILE_SCREEN_WIDTH = 767;
    var EVENT_HANDLER_DATA_KEY = '__fixed_header_window_event_handler';

    function initFixedHeader(options) {

        if (!options.$header) {
            return;
        }

        var $header = options.$header;
        var $contentContainer = options.$contentContainer;
        var headerHeight = $header.outerHeight();
        var fixedClass = options.fixedClassName || 'fixed';
        var floatingHeaderHeight = options.floatingHeaderHeight || headerHeight;
        var maxMobileScreenWidth = options.maxMobileScreenWidth || DEFAULT_MAX_MOBILE_SCREEN_WIDTH;

        function adjustHeader() {
            var heightDifference = headerHeight - $(window).scrollTop() - floatingHeaderHeight;

            if ($header.hasClass(fixedClass)) {
                if (heightDifference > 0 && $(window).width() > maxMobileScreenWidth) {
                    $header.add($contentContainer).toggleClass(fixedClass);
                }
            } else {
                if ((heightDifference < 0) && $(window).width() > maxMobileScreenWidth) {
                    $header.add($contentContainer).toggleClass(fixedClass);
                }
            }
        }

        var eventHandler = function () {
            adjustHeader();
        };

        $(window).on(ADJUSTMENT_EVENTS, eventHandler);
        $header.data(EVENT_HANDLER_DATA_KEY, eventHandler);

        adjustHeader();
    }

    function destroyFixedHeader($element) {
        if ($element.length) {
            var eventHandler = $element.data(EVENT_HANDLER_DATA_KEY);
            if (eventHandler) {
                $(window).off(ADJUSTMENT_EVENTS, eventHandler);
            }
        }
    }

    if (!window.AgencyPatternLibrary) {
        window.AgencyPatternLibrary = {};
    }

    window.AgencyPatternLibrary.FixedHeader = {
        init: initFixedHeader,
        destory: destroyFixedHeader
    };

})(window);;
(function (window, undefined) {

    var ADJUSTMENT_EVENTS = 'scroll resize';
    var TRANSITION_END_EVENTS = 'transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd';
    var DEFAULT_MAX_MOBILE_SCREEN_WIDTH = 767;
    var EVENT_HANDLER_DATA_KEY = '__floating_manage_panel_window_event_handler';

    var defaultOptions = {
        headerFixedClass: 'fixed',
        maxMobileScreenWidth: DEFAULT_MAX_MOBILE_SCREEN_WIDTH,
        missingImageLinkClass: 'missing-image-link'
    };

    function initFloatingManagePanel(options) {

        options = $.extend({}, defaultOptions, options);

        var $managePanel = options.$managePanel;
        var $header = options.$header;
        var $contentContainer = options.$contentContainer;

        if (!$managePanel || !$header || !$contentContainer) {
            return;
        }

        var $headerImage = options.$headerImage || $header.find('.agency-logo-small');
        var fixedSearchFieldClass = options.fixedSearchFieldClass;
        var headerFixedClass = options.headerFixedClass;
        var missingImageLinkClass = options.missingImageLinkClass;
        var maxMobileScreenWidth = options.maxMobileScreenWidth;
        var floatingHeaderHeight = options.floatingHeaderHeight || $header.outerHeight();

        var staticManagePanelOffsetTop = 0;

        function setManagePanelFloating(floating) {
            if (floating) {
                $contentContainer.addClass(fixedSearchFieldClass);
            } else {
                $contentContainer.removeClass(fixedSearchFieldClass);
            }
        }

        function isManagePanelFloating() {
            return $contentContainer.hasClass(fixedSearchFieldClass);
        }

        var eventHandler = function () {
            if ($(window).width() > maxMobileScreenWidth && $header.hasClass(headerFixedClass) && $managePanel.length > 0) {

                if (!isManagePanelFloating()) {
                    staticManagePanelOffsetTop = $managePanel.offset().top - floatingHeaderHeight;
                }

                if (!isManagePanelFloating() && ($(window).scrollTop() > staticManagePanelOffsetTop)) {

                    if ($headerImage.position().left >= 0 || $headerImage.hasClass(missingImageLinkClass)) {
                        setManagePanelFloating(true);
                    } else {
                        //If image has not yet slidden and it is not a missing image (which is hidden and thus does not slide),
                        //we should wait for its animation before making the manage panel float
                        $header.one(TRANSITION_END_EVENTS, function () {
                            if ($header.hasClass(headerFixedClass)) {
                                setManagePanelFloating(true);
                            }
                        });
                    }
                }

                if (isManagePanelFloating() && ($(window).scrollTop() < staticManagePanelOffsetTop)) {
                    setManagePanelFloating(false);
                }
            } else {
                setManagePanelFloating(false);
            }
        };

        $(window).on(ADJUSTMENT_EVENTS, eventHandler);
        $managePanel.data(EVENT_HANDLER_DATA_KEY, eventHandler);
    }
    
    function destroyFloatingManagePanel($element) {
        if ($element.length) {
            var eventHandler = $element.data(EVENT_HANDLER_DATA_KEY);
            if (eventHandler) {
                $(window).off(ADJUSTMENT_EVENTS, eventHandler);
            }
        }
    }

    if (!window.AgencyPatternLibrary) {
        window.AgencyPatternLibrary = {};
    }

    window.AgencyPatternLibrary.FloatingManagePanel = {
        init: initFloatingManagePanel,
        destroy: destroyFloatingManagePanel
    };

})(window);;
(function(window, $, undefined) {
    'use strict';

    var transitionEventNames = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend';

    function getCssClassDefinition(cssClass) {
        var cssClassDefinition = $.type(cssClass) === 'string'
            ? {
                name: cssClass
            } : cssClass;

        cssClassDefinition.causingTransition = (!!cssClassDefinition.causingTransition && areCss3TransitionsSupported());

        return cssClassDefinition;
    }

    var areCss3TransitionsSupported = (function() {
        var thisBody = document.body || document.documentElement,
            thisStyle = thisBody.style,
            support = thisStyle.transition !== undefined
                || thisStyle.WebkitTransition !== undefined
                || thisStyle.MozTransition !== undefined
                || thisStyle.MsTransition !== undefined
                || thisStyle.OTransition !== undefined;

        return function() {
            return support;
        };
    })();

    var createClassesEnumerator = function(array) {
        if (!array || array.length == 0) {
            return undefined;
        }

        var counter = 0;

        return {
            nextClassExists: function() {
                return counter < array.length;
            },
            getNextClass: function() {
                if (counter < array.length) {
                    return array[counter++];
                } else {
                    return undefined;
                }
            }
        };
    };

    var toggleClassAndTransit = function(element, classesEnumerator, callback) {
        if (!classesEnumerator.nextClassExists()) {
            return;
        }

        var cssClass = classesEnumerator.getNextClass();
            
        if (cssClass.causingTransition) {
            var transitionEndHandler = function (e) {
                //call handler just for one time, not for one time for each event
                element.off(transitionEventNames, transitionEndHandler);

                callback(cssClass);

                if (classesEnumerator.nextClassExists()) {
                    toggleClassAndTransit(element, classesEnumerator, callback);
                }
            };

            element.on(transitionEventNames, transitionEndHandler);
        } else {
            callback(cssClass);

            if (classesEnumerator.nextClassExists()) {
                //setTimeout method performs changing css classes by jQuery one by one not all the classes at the same moment
                setTimeout(function() {
                    toggleClassAndTransit(element, classesEnumerator, callback);
                }, 0);
            }
        }

        element.toggleClass(cssClass.name);
    };

    //just toggled class settings object is passed to a callback function
    $.fn.toggleClassSequence = function(cssClasses, isReverseOrder, callback) {
        if (!cssClasses) {
            return;
        }

        if (!$.isArray(cssClasses)) {
            cssClasses = [cssClasses];
        }

        if (!callback && arguments.length > 1) {
            for (var i = 1; i < arguments.length; i++) {
                if ($.isFunction(arguments[i])) {
                    callback = arguments[i];
                    break;
                }
            }
        }

        if ($.isFunction(isReverseOrder)) {
            isReverseOrder = null;
        }

        isReverseOrder = !!isReverseOrder;

        var self = this;

        var cssClassDefinitions = cssClasses.map(getCssClassDefinition);

        if (isReverseOrder) {
            cssClassDefinitions = cssClassDefinitions.reverse();
        }

        var classesEnumerator = createClassesEnumerator(cssClassDefinitions);

        toggleClassAndTransit(self,
            classesEnumerator,
            function () {
                callback && callback.apply(null, arguments);
            });
    };
})(window, window.jQuery);;
(function (window, undefined) {
    /* Some CSS properties like text-rendering are not supported on stock Android browser
       and their support cannot be detected in a Modernizr-like feature detection manner, so
       User Agent detection is the only way to apply CSS fixes */

    var ANDROID_BROWSER_CLASS_NAME = 'android-browser';

    var userAgent = navigator.userAgent;

    if (!userAgent) {
        return;
    }

    // Android Mobile
    var isAndroidMobile = userAgent.indexOf('Android') > -1 &&
                          userAgent.indexOf('Mozilla/5.0') > -1 &&
                          userAgent.indexOf('AppleWebKit') > -1;

    // Apple webkit
    var appleWebKitRegExp = new RegExp(/AppleWebKit\/([\d.]+)/);
    var isAppleWebKit = appleWebKitRegExp.exec(userAgent);
    var appleWebKitVersion = (isAppleWebKit === null ? null : parseFloat(appleWebKitRegExp.exec(userAgent)[1]));

    // Chrome
    var chromeRegExp = new RegExp(/Chrome\/([\d.]+)/);
    var isChrome = chromeRegExp.exec(userAgent);
    var chromeVersion = (isChrome === null ? null : parseFloat(chromeRegExp.exec(userAgent)[1]));

    // Native Android Browser
    var isAndroidBrowser = isAndroidMobile &&
                           (appleWebKitVersion !== null && appleWebKitVersion < 537) ||
                           (chromeVersion !== null && chromeVersion < 37);


    if (isAndroidBrowser) {
        var htmlElement = document.getElementsByTagName('html')[0];
        htmlElement.className += ' ' + ANDROID_BROWSER_CLASS_NAME;
    }

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

    var stylingTagsToStrip = ['STRONG', 'B', 'I', 'BASEFONT', 'BIG', 'FONT', 'IFRAME', 'IMG', 'U', 'SCRIPT', 'PRE', 'SMALL'];

    window.utils = {
        //for usage examples check Utils.Test

        getUrlParameter: function (parameterName, url) {
            if (!url) {
                url = location.search;
            }
            return decodeURI((RegExp(parameterName + '=' + '(.+?)(&|$)').exec(url) || [, ""])[1]);
        },

        formatDateTimeAMPM: function(date) {
            var hours = date.getHours();
            var minutes = date.getMinutes();

            var ampm = hours >= 12 ? 'PM' : 'AM';

            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'

            minutes = minutes < 10 ? '0' + minutes : minutes;

            var strTime = hours + ':' + minutes + ampm;
            return strTime;
        },

        stringEndsWith: function (str, suffix) {
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        },

        removeFromStringEnd: function(str, charactersToRemove) {
            return str.substring(0, str.length - charactersToRemove);
        },

        toTitleCase: function (str) {
            return str.replace(/\w+/g, function (txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            });
        },

        compareYearAndMonth: function (year1, month1, year2, month2) {
            function isNull(value) {
                return !value;
            }

            if (isNull(year1) && isNull(year2))
                return 0;
            if (isNull(year1) && !isNull(year2))
                return -1;
            if (!isNull(year1) && isNull(year2))
                return 1;

            if (year1 < year2)
                return 1;
            if (year1 > year2)
                return -1;

            if (isNull(month1))
                month1 = 0;
            if (isNull(month2))
                month2 = 0;

            return month2 - month1;
        },

        containsDuplicates: function(array) {
            array.sort();
            var containsDuplicates = false;

            var last = array[0];
            for (var i = 1; i < array.length; i++) {
                if (array[i] == last) {
                    containsDuplicates = true;
                }

                last = array[i];
            }

            return containsDuplicates;
        },

        findDuplicates: function (array, resultElementTransition) {
            var elementsWithCountDictionary = {};

            for (var i = 0; i < array.length; i++) {
                var element = array[i];

                if (elementsWithCountDictionary[element] === undefined) {
                    elementsWithCountDictionary[element] = 1;
                } else {
                    elementsWithCountDictionary[element] += 1;
                }
            }

            var duplicates = [];
            for (var p in elementsWithCountDictionary) {
                var count = elementsWithCountDictionary[p];
                if (count > 1) {
                    if (resultElementTransition) {
                        p = resultElementTransition(p);
                    }

                    duplicates.push(p);
                }
            }

            return duplicates;
        },

        firstOrDefault: function(array, condition) {
            var matchingElements = $.grep(array, condition);
            if (matchingElements.length === 0)
                return null;

            return matchingElements[0];
        },

        exists: function(array, condition) {
            return $.grep(array, condition).length > 0;
        },

        jQueryObjectToString: function(object) {
            return $('<div>').append(object.clone()).html();
        },

        replaceLinebreaksWithBrs: function(text) {
            return text.replace(/\n/g, "<br>");
        },
        
        normalizeNewlines: function(text) {
            return String(text).replace(/(\r\n|\n|\r)/gm, "\n");
        },

        stripHtmlStyling: function (text) {
            if (!text) {
                return '';
            }

            text = window.utils.replaceLinebreaksWithBrs(text);

            if (text.indexOf("<") === -1) {
                return text;
            }

            try {
                var stripped = [],
                    allContents = $('<div>').append(text).contents();

                allContents.each(function () {

                    var $this = $(this),
                        node;

                    if ($.inArray(this.tagName, stylingTagsToStrip) > -1) {
                        node = $this.contents();
                    }
                    else {
                        node = $this
                            .removeAttr("style")
                            .removeAttr("class");
                    }

                    stripped.push(
                        window.utils.jQueryObjectToString(node)
                    );
                });

                return stripped.join('');
            }
            catch (e) {
                // error in formatting
                return text;
            }
        },

        stripHtmlTags: function (content) {
            var text = $("<div/>").html(content).text();
            return text;
        },

        stripHtmlTagsAndUnprintedCharacters: function (content) {
            // A regular expression to match characters with ASCII codes from 0 to 31 and 127 to 160
            let text = $("<div/>").html(content).text();
            return text.replace(/[\x00-\x09\x0B-\x1F\x7F-\xA0]/g, '');
        },

        //Returns a new function which calls 'wrapper' function before or after the original function.
        wrapFunction: function (fn, wrapper, after) {
            return function () {
                if (!after) {
                    wrapper.apply(this, arguments);
                }
                fn.apply(this, arguments);
                if (after) {
                    wrapper.apply(this, arguments);
                }
            };
        }
    };
})(window);;
(function (window, undefined) {
    'use strict';

    var namespace = function (name) {
        return (window[name] || (window[name] = {}));
    };

    window.namespace = namespace;

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

    namespace('Areas').AreaNames = {
        gJobs: 'gJobs',
        careerPages: 'careerPages'
    };

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

    var application = {
        templateEngine: {
            setBaseUrl: function (url) {
                infuser.defaults.templateUrl = url;
            }
        }
    };


    window.OnlineApp = application;

})(window);;
(function (window, undefined) {

    function iterateThroughNamespace(parentNamespaceObject, namespaces) {
        for (var namespaceIndex = 0; namespaceIndex < namespaces.length; namespaceIndex++) {

            var childNamespace = namespaces[namespaceIndex];
            var childNamespaceObject = parentNamespaceObject[childNamespace];

            if (typeof (childNamespaceObject) === 'undefined') {
                childNamespaceObject = {};
                parentNamespaceObject[childNamespace] = childNamespaceObject;
            }

            parentNamespaceObject = childNamespaceObject;
        }

        return parentNamespaceObject;
    }

    OnlineApp.Namespace = {

        open: function (parentNamespace) {

            var namespaces = parentNamespace
                .split('.')
                .concat(Array.prototype.slice.call(arguments, 1));

            var parentNamespaceObject = window[namespaces[0]];

            namespaces = namespaces.slice(1);

            return iterateThroughNamespace(parentNamespaceObject, namespaces);
        },

        //TODO : Merge with open method!
        openRelative: function (base, parentNamespace) {

            var namespaces = parentNamespace
                .split('.');

            var parentNamespaceObject = base;

            return iterateThroughNamespace(parentNamespaceObject, namespaces);
        },

        extend: function (parentNamespace, object) {
            var namespace = this.open(parentNamespace);
            return $.extend(namespace, object);
        }
    };

})(window);;
(function (window, undefined) {
    // Note: we do not use strict mode here to allow access callee in function body

    // FROM: http://helephant.com/2007/05/diy-javascript-stack-trace
    // AND: http://joel.net/logging-errors-with-elmah-in-asp.net-mvc-3--part-5--javascript


    //Note: all the special cases when the javascript error logging is not needed should be described in this method
    function isLoggingRequired() {

        var result = true;

        //avoid error handling for GoogleBot requests as GoogleBot cannot execute all the javascript correctly
        if (navigator.userAgent && navigator.userAgent.indexOf('Googlebot') !== -1) {
            result = false;
        }

        return result;
    }

    function getTrace() {
        var trace = [];
        var current = this;
        while (current) {
            trace.push(getSignature.apply(current));
            current = current.caller;
        }
        return trace;
    }

    function getSignature() {
        var signature = {
            name: getName.apply(this),
            params: [],
            toString: function () {

                var params = (this.params || []).length > 0
                    ? "'" + this.params.join("', '") + "'"
                    : "";

                return this.name + "(" + params + ")";
            }
        };

        if (this.arguments) {
            for (var x = 0; x < this.arguments.length; x++)
                signature.params.push(this.arguments[x]);
        }

        return signature;
    }

    function getName() {
        if (this.name) return this.name;

        var definition = this.toString().split("\n")[0];
        var exp = /^function ([^\s(]+).+/;
        if (exp.test(definition))
            return definition.split("\n")[0].replace(exp, "$1") || "anonymous";

        return "anonymous";
    }

    function createLogMessage(err, stack) {
        if (err == null) return undefined;

        var url = err.fileName != null
            ? err.fileName
            : document.location;

        if (stack == null && err.stack != null) {
            stack = err.stack;
        }

        // format output
        var out = err.message != null
            ? err.name + ": " + err.message
            : err;

        out += ": at document path '" + url + "'.";

        if (stack != null) {
            out += "\n  at " + stack.join("\n  at ");
        }

        return out;
    }
    
    function handleError(message, filename, lineNo, columnNo, error) {
        //api url
        var apiUrl = '/api/errorlog';

        var stack;

        if (arguments != null && arguments.callee != null) {
            stack = getTrace.apply(arguments.callee);
        }

        var elmahTrace = '';
        // for blink browsers
        if (error) {
            elmahTrace = error.stack;
        }
            // a guess for other browsers
        else if (stack) {
            for (var i = 0; i < stack.length; ++i) {
                if (!stack[i]) continue;

                var params = stack[i].params;
                for (var j = 0; j < params.length; ++j) {
                    if (!params[j]) continue;

                    if (params[j].stack) {
                        elmahTrace += params[j].stack + "\n\n";
                    }
                }
            }
        }

        var data = {
            errorMsg: message,
            errorLine: lineNo,
            filePath: filename,
            url: document.location.href,
            referrer: document.referrer,
            userAgent: navigator.userAgent,
            elmahLog: createLogMessage(message, stack),
            elmahTrace: elmahTrace
        };

        $.ajax({
            url: apiUrl,
            type: 'POST',
            data: data
        });

        //suppress browser error messages for non-dev environments
        var suppressErrors = $.inArray(window.location.hostname, ['localhost', 'gjobs.local.neogov.net', 'schooljobs.local.neogov.net']) == -1;

        return suppressErrors;
    };

    if (isLoggingRequired()) {
        try {
            window.onerror = handleError;
        } catch(e) {
        }
    }
    
})(window);;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').isTransitionEventSupported = function() {
        var body = document.body || document.documentElement;
        var style = body.style;

        return style.transition !== undefined ||
            style.WebkitTransition !== undefined ||
            style.MozTransition !== undefined ||
            style.MsTransition !== undefined ||
            style.OTransition !== undefined;
    };
})(window);;
(function (window, undefined) {
    'use strict';

    function ExternalFileLoader() {
        var self = this;

        self.load = function (url) {
            var script = document.createElement('script');

            script.type = 'text/javascript';
            script.src = url + '?v=' + Date.now();

            $('head').append(script);
        }
    };

    namespace('gJobs').externalFileLoader = new ExternalFileLoader();

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

    function showAccesibilityStatement() {
        const backgroundContent = document.getElementById('main-container');
        const backgroundContentbody = document.getElementById('body-container');
        let popup = document.getElementById("accesibility-statement-popup");
        if (popup) {
            gJobs.screenReadersService.setAriaLiveNotification(' Accessibility Statement informaion modal is opened.');
            popup.style.display = "block";
            $("#accesibility-statement-popup").addClass("active");
            $("body").addClass("overflowhidden"); 
            if (backgroundContent)
                backgroundContent.setAttribute('aria-hidden', 'true');
            else if (backgroundContentbody)
                backgroundContentbody.setAttribute('aria-hidden', 'true');
            $(".modal-close").focus();
            document.addEventListener('keydown', trapFocus); // Trap focus when modal is open
        }
    }

    function closeaccesbilityStatementModal() {
        const backgroundContent = document.getElementById('main-container');
        const backgroundContentbody = document.getElementById('body-container');

        let popup = document.getElementById("accesibility-statement-popup");
        if (popup) {
            popup.style.display = "none";
            $("#accesibility-statement-popup").removeClass("active");
            gJobs.screenReadersService
                .setAriaLiveNotification(' Accessibility Statement informaion modal is closed.');
            document.removeEventListener('keydown', trapFocus); // Remove focus trapping when modal is closed 
            $("body").removeClass("overflowhidden");
            if (backgroundContent)
                backgroundContent.setAttribute('aria-hidden', 'false');
            else if (backgroundContentbody)
                backgroundContentbody.setAttribute('aria-hidden', 'false');
            $("#lnkAccesibiltyStatement").focus();
        }
    }
       
    // Expose functions to the global scope for access from other HTML pages
    window.showAccesibilityStatement = showAccesibilityStatement;
    window.closeaccesbilityStatementModal = closeaccesbilityStatementModal;

    // Close the modal when the user presses the Escape key
    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && $("#accesibility-statement-popup").hasClass("active")) {
            closeaccesbilityStatementModal();
        }
        if (event.key === 'Tab' && $("#accesibility-statement-popup").hasClass("active")) {          
            $(".modal-close").focus();
            event.preventDefault();
        }
        if (event.key === 'ArrowDown') {
            $('.accesibility-content').animate({
                scrollTop: '+=' + 100 
            }, 0); 
          
        }
        if (event.key === 'ArrowUp') {

            $('.accesibility-content').animate({
                scrollTop: '+=' - 100 
            }, 0);
            
        }
    });

    function trapFocus(event) {
        const focusableElements = document.getElementById('myModal').querySelectorAll('button, a, input, select, textarea, [tabindex]:not([tabindex="-1"])');
        const focusableArray = Array.from(focusableElements);
        const firstFocusableElement = focusableArray[0];
        const lastFocusableElement = focusableArray[focusableArray.length - 1];

        if (event.key === 'Tab') {
            if (event.shiftKey) { // Shift + Tab
                if (document.activeElement === firstFocusableElement) {
                    event.preventDefault();
                    lastFocusableElement.focus(); // Cycle focus to last element             
                }
            } else { // Tab
                if (document.activeElement === lastFocusableElement) {
                    event.preventDefault();
                    firstFocusableElement.focus(); // Cycle focus to first element             
                }
            }
        }
    }

})(window);;
(function (window) {

    namespace('gJobs').ariaAttributes = {
        role: 'role',
        autocomplete: 'aria-autocomplete',
        owns: 'aria-owns',
        controls: 'aria-controls',
        haspopup: 'aria-haspopup',
        disabled: 'aria-disabled',
        invalid: 'aria-invalid',
        expanded: 'aria-expanded',
        hidden: 'aria-hidden',
        activeDescendant: 'aria-activedescendant',
        labelledBy: 'aria-labelledby',
        describedBy: 'aria-describedby',
        multiselectable: 'aria-multiselectable',
        label: 'aria-label',
        selected: 'aria-selected',
        notification: 'data-notification',
        required: 'aria-required',
        tabindex: 'tabindex'
    };

})(window);;
(function(window, undefined) {

    var applicationSettingCodes =
    {
        '1': 'MandatoryEducationHistoryDates',
        '2': 'WorkHistoryDutiesBreakdown',
        '3': 'WorkHistoryCustomMessage',
        '4': 'LicenseHistoryCustomMessage',
        '5': 'AdditionalInfoTypeFilter',
        '6': 'ReferenceCustomMessage',
        '7': 'ShowExtraColumnApplicationStatus',
        '8': 'ShowExtraInformationPrintApplication',
        '9': 'MandatoryEducationHistoryUnits',
        '10': 'PersonalProfileCustomMessage',
        '11': 'ShowApplicationsForThisEmployerOnly'
    };

    function populateFieldSettings(settings) {
        var fieldSettings = {};
        for (var i = 0, length = settings.length; i < length; ++i) {
            var code = settings[i].code;
            var state = settings[i].state;
            fieldSettings[code] = {
                visible: (state < 3),
                required: (state < 2)
            };
        }

        // Note: moved from preferences.html
        // TODO: investigate whether null check required/possible
        var showPreferences =
            fieldSettings.salaryMinYr.visible
                || fieldSettings.salaryMinHr.visible
                || fieldSettings.relocateID.visible
                || fieldSettings.relocateComments.visible
                || fieldSettings.shiftType.visible
                || fieldSettings.positionType.visible
                || fieldSettings.workType.visible
                || fieldSettings.objective.visible;

        fieldSettings['preferences'] = {
            visible: showPreferences
        };

        return fieldSettings;
    }

    function populateApplicationSettings(settings) {
        var applicationSettings = {};
        for (var i = 0, length = settings.length; i < length; ++i) {
            var code = settings[i].code;
            var setting = settings[i].setting;
            var settingName = applicationSettingCodes[code];

            if (settingName) {
                applicationSettings[settingName] = setting;
            }
        }

        return applicationSettings;
    }
    
    function populateCustomFields(settings) {
        var customFields = {};
        
        for (var i = 0, length = settings.length; i < length; ++i) {
            var label = settings[i].fieldLabel;
            var fieldValues = settings[i].fieldValues;
            var data = settings[i].data;
            
            customFields[label] = {
                values: fieldValues,
                data: data
            };
        }
        return customFields;
    }

    function TabSettings() {
        var self = OnlineApp.ViewModels.Base.DataViewModel.apply(this, arguments) || this;

        self.showAdditionalMenu = ko.observable(false);
        self.acceptAdditionalInfo = ko.observable(false);
        self.acceptAttachResume = ko.observable(false);
        self.acceptEducationHistory = ko.observable(false);
        self.acceptLicense = ko.observable(false);
        self.acceptReference = ko.observable(false);
        self.acceptEReferences = ko.observable(false);
        self.eRefRequiredReferences = ko.observable(null);
        self.acceptSkill = ko.observable(false);
        self.acceptTextResume = ko.observable(false);
        self.acceptWorkHistory = ko.observable(false);

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.showAdditionalMenu(data.showAdditionalMenu);
            self.acceptAdditionalInfo(data.acceptAdditionalInfo);
            self.acceptAttachResume(data.acceptAttachResume);
            self.acceptEducationHistory(data.acceptEducationHistory);
            self.acceptLicense(data.acceptLicense);
            self.acceptReference(data.acceptReference);
            self.acceptEReferences(data.acceptEReferences);
            self.eRefRequiredReferences(data.eRefRequiredReferences);
            self.acceptSkill(data.acceptSkill);
            self.acceptTextResume(data.acceptTextResume);
            self.acceptWorkHistory(data.acceptWorkHistory);
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Settings', {
        populateFieldSettings: populateFieldSettings,
        populateApplicationSettings: populateApplicationSettings,
        populateCustomFields: populateCustomFields
    });

    OnlineApp.Namespace.extend('OnlineApp.Settings', {
        TabSettings: TabSettings
    });

    $(document).ready(function () {
        // Configure toastr.js settings
        toastr.options.target = '#aria-live-toastr-container';
    });

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

    OnlineApp.Namespace.extend('OnlineApp.FieldSettings', {   
        //Contact info
        firstName: {
            required: true
        },
        middleName: {
            visible: true,
            required: false
        },
        lastName: {
            required: true
        },
        formerLastName: {
            visible: false,
            required: false
        },
        address1: {
            required: true
        },
        address2: {
            visible: true,
            required: false
        },
        city: {
            required: true
        },
        stateID: {
            required: true
        },
        zip: {
            required: true
        },
        homePhone: {
            visible: true,
            required: false
        },
        alternatePhone: {
            visible: true,
            required: false
        },
        notificationType_cd: {
            visible: true,
            required: false
        },
        countryID: {
            visible: true,
            required: true
        },
        email: {
            required: true
        },

        //Personal info
        driverLicense: {
            visible: true,
            required: false
        },
        driverLicenseStateID: {
            visible: true,
            required: false
        },
        driverLicenseNumber: {
            visible: true,
            required: false
        },
        driverLicenseClassID: {
            visible: true,
            required: false
        },
        monthDayBirth: {
            visible: false,
            required: false
        },
        ssn: {
            visible: false,
            required: false
        },
        legalWork: {
            visible: true,
            required: true
        },
        highestEducationLevelID: {
            visible: true,
            required: true
        },

        //Preferences
        preferences: {
            visible: true,
            required: false
        },
        salaryMinYr: {
            visible: true,
            required: false
        },
        salaryMinHr: {
            visible: true,
            required: false
        },
        relocateID: {
            visible: true,
            required: false
        },
        relocateComments: {
            visible: true,
            required: false
        },
        shiftType: {
            visible: true,
            required: false
        },
        positionType: {
            visible: true,
            required: false
        },
        workType: {
            visible: true,
            required: false
        },
        objective: {
            visible: true,
            required: false
        },

        // WorkExperience
        workExperienceCompanyName: {
            visible: true,
            required: true
        },
        workExperienceAddress: {
            visible: true,
            required: false
        },
        workExperienceCity: {
            visible: true,
            required: true
        },
        workExperienceState: {
            visible: true,
            required: true
        },
        workExperienceZipCode: {
            visible: true,
            required: false
        },
        workExperienceCountry: {
            visible: true,
            required: false
        },
        workExperiencePhone: {
            visible: true,
            required: false
        },
        workExperienceWebsite: {
            visible: true,
            required: false
        },
        workExperienceMayWeContactEmployer: {
            visible: true,
            required: false
        },
        workExperiencePositionTitle: {
            visible: true,
            required: true
        },
        workExperienceHoursPerWeek: {
            visible: true,
            required: true
        },
        workExperienceMonthlySalary: {
            visible: true,
            required: false
        },
        workExperienceEmployeesSupervised: {
            visible: true,
            required: false
        },
        workExperienceStartDate: {
            visible: true,
            required: true
        },
        workExperienceEndDate: {
            visible: true,
            required: true
        },
        workExperienceReasonForLeaving: {
            visible: true
        },
        workExperienceSupervisorName: {
            visible: true
        },
        workExperienceSupervisorTitle: {
            visible: true
        },
        workExperienceDutiesSummary: {
            visible: true,
            required: true
        },

        // Education
        educationSchoolType: {
            visible: true,
            required: true
        },
        educationSchoolName: {
            visible: true,
            required: true
        },
        educationCity: {
            visible: true,
            required: true
        },
        educationState: {
            visible: true,
            required: true
        },
        educationCountry: {
            visible: true,
            required: true
        },
        educationWebsite: {
            visible: true,
            required: false
        },
        educationMajorMinor: {
            visible: true,
            required: false
        },
        educationDegree: {
            visible: true,
            required: true
        },
        educationUnitsCompleted: {
            visible: true,
            required: false
        },
        educationUnitType: {
            visible: true,
            required: false
        },
        educationStartDate: {
            visible: true,
            required: false
        },
        educationEndDate: {
            visible: true,
            required: false
        },
        educationDidYouGraduate: {
            visible: true,
            required: false
        }
    });

})(window);;
(function (window, undefined) {
    'use strict';

    namespace('Events').CommonEventsNames = {
        CloseFlyout: 'closeFlyout',
        TryCloseFlyout: 'tryCloseFlyout',
        FlyoutClosing: 'flyoutClosing',
        HistoryFlyoutOpened: 'historyFlyoutOpened',
        HistoryFlyoutClosed: 'historyFlyoutClosed',
        ScheduleFlyoutOpened: 'scheduleFlyoutOpened',
        ScheduleFlyoutClosed: 'scheduleFlyoutClosed',
        ShowNext: 'showNext',
        ShowPrevious: 'showPrevious',
        ShowJobDetails: 'showJobDetails',
        HideApply: 'hideApply',
        ShowApply: 'showApply',
        ShowMessage: 'showMessage',
        ApplicationSubmitted: 'applicationSubmitted',
        ApplicationLoaded: 'applicationLoaded',
        ShowOnlineApp: 'showOnlineApp',
        Login: 'loginEvent',
        LoginFailed: 'loginFailed',
        Register: 'registerEvent',
        JobsListLoaded: 'jobsListLoaded',
        JobDetailsLoaded: 'jobDetailsLoaded',
        ShowFlyout: 'showFlyout',
        ClassSpecsListLoaded: 'classSpecsListLoaded',
        ShowValidationMessage: 'showValidationMessage',
        AppointmentFlyoutStateChanged: 'appointmentFlyoutStateChanged',
        DecreaseNumberOfUnreadMessages: 'decreaseNumberOfUnreadMessages',
        ShowTermsAndPrivacyPolicyAnnouncement: 'showTermsAndPrivacyPolicyAnnouncement',
        TermsAndPrivacyAccepted: 'termsAndPrivacyAccepted',
        GoogleAnalyticsTrackersInjected: 'googleAnalyticsTrackersInjected',
        ShowAccessMembershipDialog: 'showAccessMembershipDialog',
        CloseAccessMembershipDialog: 'closeAccessMembershipDialog',
        ShowConfirmDialog: 'showConfirmDialog',
        ToTopButtonTopPropertyChanged: 'toTopButtonTopPropertyChanged',
        Angular: {
            Login: 'angularLoginEvent',
            Register: 'angularRegisterEvent'
        },
        ShowStickyHeader: 'showStickyHeader',
        HideStickyHeader: 'hideStickyHeader',
        AccessMembershipEnabled: 'accessMembershipEnabled',
        AccessMembershipDisabled: 'accessMembershipDisabled',
        JobAlertCreated: 'JobAlertCreated',
        JobAlertUpdated: 'JobAlertUpdated',
        ChatbotClosed: 'chatPanelClosed',
        ChatPanelMinimized: 'chatPanelMinimized',
        ChatbotConversationFeedbackTextGiven: 'conversationFeedbackTextGiven',
        ChatBotConversationDeleted: 'conversationDeleted',
        ChatbotPositiveMessageFeedbackGiven: 'positiveMessageFeedbackGiven',
        ChatbotNegativeMessageFeedbackGiven: 'negativeMessageFeedbackGiven',
        HelpAndSupportPageOpened: 'helpAndSupportPageOpened',
        SupplementalAttachmentDocAttached: 'supplementalAttachmentDocAttached',
        SupplementalAttachmentDocDeleted: 'supplementalAttachmentDocDeleted',
        OpenAccessMembershipDialog: 'openAccessMembershipDialog'
    };

})(window);;
(function (window, undefined) {
    'use strict';

    OnlineApp.Namespace.extend('OnlineApp.Events.CommonEventsNames', {
        EditableItemBeginEdit: 'editableItemBeginEdit',
        EditItemComplete: 'editItemComplete',
        EditableCollectionItemDiscarded: 'editableCollectionItemDiscarded',
        TryRemoveItem: 'tryRemoveItem',
        RemoveItemComplete: 'removeItemComplete',
        ItemRemoved: 'itemRemoved',
        ResumeImportComplete: 'resumeImportComplete',
        PreSaveValidationFailed: 'preSaveValidationFailed',
        ApplicationSubmit: 'applicationSubmit',
        Login: 'loginEvent',
        Register: 'registerEvent',
        QuestionsSaved: 'questionsSaved',
        DocumentAttached: 'documentAttached',
        PasswordReset: 'passwordReset',
        ResetPasswordClicked: 'resetPasswordClicked',
        ContactInfomationAvailable: 'contactInformationAvailable',
        RegisterAccountLinkClicked: 'registerAccountLinkClicked',
        RegisterAccountFormOpened: 'registerAccountFormOpened',
        LoginFormOpened: 'loginFormOpened',
        ApplicationRendered: 'applicationRendered',
        TabActivated: 'tabActivated',
        ApplicationClosed: 'applicationClosed',
        ApplyTabOpened: 'applyTabOpened',
        ResourcesLinkClicked: 'resourcesLinkClicked',
        CertifySubmitTabOpened: 'certifySubmitTabOpened',
        EmailVerified: "emailVerified",
        EmailWasChanged: "emailWasChanged",
        ContactInfoEmailVerificationFormClosed: "contactInfoEmailVerificationFormClosed",
        ShowCancelVerificationRequestDialog: 'ShowCancelVerificationRequestDialog',
        InitSearchFieldsWithAutocomplete: "initSearchFieldsWithAutocomplete",
        AutocompleteMenuItemSelect: "menuselect",
        ConfirmEditEmailAddress: "confirmEditEmailAddress",
        CancelEditEmailAddress: "cancelEditEmailAddress",
        OjrMasterJicSubscribe: "ojrMasterJicSubscribe"
    });

})(window);;
(function (window, undefined) {
    'use strict';

    var SessionKeys = {
        EmailWasChangedAndNewVerificationCodeSent: 'emailWasChangedAndNewVerificationCodeSent',
        IsBannerWasClosedInCurrentSession: 'isBannerWasClosedInCurrentSession',
        PostBackUrl: 'postBackUrl',
        IsVerifyIdentityVerificationCodeVerified: 'isVerifyIdentityVerificationCodeVerified',
        ApplicationProcessUrl: 'applicationProcessUrl'
    };

    OnlineApp.Namespace.extend('OnlineApp', {
        SessionKeys: SessionKeys
    });

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

    var LocalStorageKeys = {
        EmailWasChanged: 'emailWasChanged',
        EmailWasChangedAndNewVerificationCodeSent: 'emailWasChangedAndNewVerificationCodeSent',
        EmailWasVerified: 'emailWasVerified',
        ShowJobAlertPopup: 'showJobAlertPopup',
        RedirectToShowJobAlertPopup: 'redirectToShowJobAlertPopup'
    };

    OnlineApp.Namespace.extend('OnlineApp', {
        LocalStorageKeys: LocalStorageKeys
    });

})(window);
;
(function (window, undefined) {

    $(document).ready(function() {
        var areaInfoService = gJobs.areaInfoService;

        var $body = $('body');
        var disableScrollClasses = 'scroll-disable inner-scrollbar';
        var initialBodyClasses = '';

        var $termsAndPrivacyPolicyDialogContainer = $('#terms-and-privacy-policy-update-confirmation');

        var isCareerPages = areaInfoService.getCurrentArea() === areaInfoService.areaNames.Career;

        var TermsAndPrivacyAnnouncementViewModel = function (options) {
            var self = OnlineApp.ViewModels.Base.ValidatableViewModel.call(this) || this;

            self.visible = ko.observable(false);
            self.isBusy = ko.observable(false);
            
            self.hasAcceptedTerms = ko.observable(false).extend({ required: {} });

            self.options = options || {};

            self.hasError = function () {
                self.hasAcceptedTerms.validate();
                return self.hasAcceptedTerms.hasError();
            };

            self.visible.subscribe(function(value) {
                showHideElementsOnDialog(value);
            })

            self.acceptTermsAndPrivacyPolicy = function() {
                self.isBusy(true);

                if (!self.hasError()) {
                    $.post('/user/acceptTermsAndPrivacyPolicy')
                        .done(function (data) {
                            if (!data.isSuccess) {
                                toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                            } else {
                                showHideElementsOnDialog(false);

                                $(document).trigger(Events.CommonEventsNames.TermsAndPrivacyAccepted);
                                gJobs.screenReadersService.setAriaLiveNotification(
                                    'You have successfully accepted the changes to the terms of service and privacy policy. Term & use Modal Dialog has been closed.'
                                );
                                $("#skip-to-content-button").focus();
                                sessionStorage.setItem("isTermsDeclined", "1");
                                $('body').removeClass('scroll-disable inner-scrollbar');
                                $('body').css("overflow-y", "auto");
                                $('#body-shadow').addClass('hidden');
                                const urlParams = new URLSearchParams(window.location.search);
                                const vettedLoginSessionStorage = sessionStorage.getItem('isVettedLogin') ?? false;
                                const isVettedLogin = urlParams.get('isVettedLogin');
                                if (data.isAccessMembershipEnabled && (isVettedLogin || vettedLoginSessionStorage)) {
                                    window.location.replace('/vetted/RedirectToVetted');
                                }
                            }
                        
                    })
                    .always(function() {
                        self.isBusy(false);
                        self.visible(false);
                        $termsAndPrivacyPolicyDialogContainer.removeClass('active');
                        $termsAndPrivacyPolicyDialogContainer.css("display", "none");
                        localStorage.setItem("istermsAndPrivacyPolicyDialogContainer", "0");
                        $("#skip-to-content-button").focus();
                        if (isCareerPages) {
                            AgencyPages.bodyScrollingAdjustmentService.enableBodyScrolling();
                        } else {
                            $body.attr('class', initialBodyClasses);
                        }
                        if (options.closeCallback && typeof options.closeCallback === "function") {
                            options.closeCallback();
                        }
                    });
                } else {
                    self.isBusy(false);
                    OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement(
                        $termsAndPrivacyPolicyDialogContainer.find('form')
                    );
                }
            }

            self.declineTermsAndPrivacyPolicy = function () {
                const urlParams = new URLSearchParams(window.location.search);
                const isVettedLogin = urlParams.get('isVettedLogin');

                if (isVettedLogin) {
                    sessionStorage.setItem("isVettedLogin", true);
                }

                var redirectUrl = '/applications/accountsettings?declined=true#delete';
                if (isCareerPages) {
                    redirectUrl = AgencyPages.pageInfoService.getCurrentAgencyHomePageUrl() + redirectUrl;
                }
                sessionStorage.setItem("isTermsDeclined", "1");
                localStorage.setItem("istermsAndPrivacyPolicyDialogContainer", "1");

                var popup = document.getElementById("terms-and-privacy-policy-update-confirmation");
                if (popup) {
                    popup.style.display = "none";
                }

                window.location.replace(redirectUrl);                
            }

            function showHideElementsOnDialog(hide) {
                gJobs.dialogHelper.showHideElementsOnDialog(
                    {
                        selector: '#body-container, #main-container,'
                                  + '#footer, .new-job-flyout, #skip-to-content-button,'
                                  + '#last-focusable-element, #cookie-consent',
                        shouldDisableRestoreTabIndex: true,
                        hide: hide
                    }
                );
            }
        }

        $(document).on(Events.CommonEventsNames.ShowTermsAndPrivacyPolicyAnnouncement, function(e, data) {
            var currentQueryParams = url.get(window.location.search.slice(1), { array: true });
            if (currentQueryParams.declined !== 'true' && !$('html').hasClass('error-page')) {
                $element = $termsAndPrivacyPolicyDialogContainer.get(0);
                termsAndPrivacyAnnouncementViewModel = new TermsAndPrivacyAnnouncementViewModel(data);

                if (!ko.dataFor($element)) {
                    ko.applyBindings(termsAndPrivacyAnnouncementViewModel, $element);
                }

                if (isCareerPages) {
                    AgencyPages.bodyScrollingAdjustmentService.disableBodyScrolling();
                } else {
                    if (!$termsAndPrivacyPolicyDialogContainer.hasClass('active')) {
                        initialBodyClasses = $body.attr('class') || '';
                        $body.addClass(disableScrollClasses);
                    }
                }
                localStorage.setItem("istermsAndPrivacyPolicyDialogContainer", "1");
                $termsAndPrivacyPolicyDialogContainer.addClass('active');
                termsAndPrivacyAnnouncementViewModel.visible(true);
                gJobs.focusService.setFocus($('.terms-of-use-modal'));
            }
        });
    });

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

    namespace('Resources').NotificationMessages = {
        EncounteredProblem: "Sorry, we've encountered a problem! Please try again.",
        LoadTemplateFail: "Application could not load settings for selected job.",
        ServiceUnavailable: "Service unavailable.",
        SessionTimeoutExpires: "Your session is going to expire in ",
        SessionTimeoutResume: "Click here or press any key to continue.",
        LoginFail: "Could not log in to system. Please contact administrator for support.",
        RegistrationFail: "Registration failed. Please contact administrator for support.",
        ServerConnectionFailed: "Could not connect to server.",
        LoginSuccess: "You are logged in.",
        RegistrationSuccess: "Account successfully created. You are logged in.",
        SessionExpired: 'Your session has expired. Please refresh the page and try again.'
    };

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

    namespace('Resources').EndpointUrls = {
        KeepAlive: '/Application/KeepAlive'
    };

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

    OnlineApp.Namespace.extend('OnlineApp.FlyoutWrapperClasses', {
        convictionQuestionnaire: {
            className: 'conviction-questionnaire-flyout',
            selector: '.conviction-questionnaire-flyout'
        }
    });

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

    namespace('Resources').FileUploadMessages = {
        invalidFile: "The file you're trying to upload is invalid or empty.",
        unsupportedExtension: "The file you are trying to upload has an extension that is not allowed.",
        unsupportedExtensionWithAllowed: function (supportedFileTypes) {
            return "The file you are trying to upload has an extension that is not allowed. You can only upload " + supportedFileTypes + " files.";
        },
        fileTooLarge: function() {
            return "The file you're trying to upload is too large. Maximum file size is " + Math.round(maximumFileUploadSizeInKB / 1024) + " MB."
        }
    };

})(window);;
(function (window, undefined) {

    function LayoutHelper() {

        var lockCounter = 0;

        var self = this;

        self.$loadingSpinner = null;

        self.showOnlineAppSpinner = function () {
            self.getOnlineAppLoadingSpinner().show();
        };

        self.hideOnlineAppSpinner = function () {
            if (lockCounter == 0) {
                self.getOnlineAppLoadingSpinner().hide();
            }
        };

        self.forceHideOnlineAppSpinner = function () {
            lockCounter = 0;
            self.getOnlineAppLoadingSpinner().hide();
        };

        self.showOnlineAppInnerSpinner = function (lock) {
            self.getOnlineAppLoadingSpinner().addClass('inline').show();

            if (lock) {
                lockCounter++;
            }
        };

        self.hideOnlineAppInnerSpinner = function (unlock) {
            if (unlock) {
                lockCounter--;
            }

            if (lockCounter == 0) {
                self.getOnlineAppLoadingSpinner().removeClass('inline').hide();
            }
        };

        self.getOnlineAppLoadingSpinner = function () {

            self.$loadingSpinner = $('#onlineapp-loading-spinner, .loading-spinner');

            return self.$loadingSpinner;
        };

        self.getOnlineAppContainer = function () {
            return $('.onlineapp-wrapper');
        };

        self.updateSchoolDegreeCustomSelect = function () {
            $(".edit-dialog select[name='school-degree']").trigger("liszt:updated");
        };

        self.isOnlineAppInsideFlyout = function () {
            if ($(".flyout-window,#job-details-flyout").length > 0) {
                return true;
            }

            return false;
        };

        self.isCareerPagesApp = function () {
            return $(".career-pages-header") && $(".career-pages-header").length > 0;
        }

        self.tabbing = {

            // todo: implement caching for getting tabbable elements

            getTabbableElements: function (parentContainer) {
                var elements,
                    tabbableElementsSelector = '.box a,' +
                        'input[type=text],input[type=radio],input[type=checkbox],' +
                        'input[type=checkbox],input[type=tel],input[type=email],input[type=password],' +
                        'textarea,button,div.chzn-container,' +
                        '.instruction,' +
                        '.screenreader-link-required,label[aria-label],' + '.nav a,' +
                        '.floating-header a,' + '#title-bar a,' + '.terms-and-privacy-policy a,';

                var additionalTabbableElementsSelector = '.left-menu-nav a,' +
                    '.flyout-header-tabs a, .btn, .item-edit-button,' +
                    '.share a,' + '.entity-details-buttons.tab-buttons a,' +
                    '.form-signin a,' + '.job-details-agency-info a,' +
                    '.job-details-content a,' + '.job-details-summary .popover-trigger,' +
                    '.profiles .profile-item,' + '.disability-form a,' + '.apply-tab-header-content a,' +
                    '#skip-to-content-button,' + '.invisible-chosen-input,' + '.note.popover-trigger,' + '.content.dialog-content' + ',.dynamic-tabindex' +
                    ', .flyout-content span[data-toggle="popover"]:not(.tab-aux-icon)' +
                    ', .profiles > li.profile-item' +
                    ', .submitted a.application-advertisement-link' +
                    ', .top-resume-result' +
                    ', .description a' + ', .note';

                var jobApplyTab = $('.job-apply-tab');

                if (self.isOnlineAppInsideFlyout() && !(parentContainer && parentContainer.length)) {
                    if (self.isCareerPagesApp()) {
                        parentContainer = $(".flyout-window,#job-details-flyout");
                    }
                    else {
                        parentContainer = $("#header,.flyout-window,#job-details-flyout");
                    }
                } else {
                    parentContainer = $(parentContainer || (jobApplyTab.length ? jobApplyTab : $(document)));
                }
                elements = parentContainer.find(tabbableElementsSelector + additionalTabbableElementsSelector);

                elements = elements
                    .filter(":visible")
                    .filter(function () {
                        return ($(this).css("visibility") !== "hidden");
                    });

                return elements;
            },

            updateIndices: function (parentContainer, avoidSetTabOrder) {
                var tabbableElements = this.getTabbableElements(parentContainer);

                tabbableElements = $('#skip-to-content-button').add(tabbableElements);
                var $lastFocusableElement = $('#last-focusable-element');
                if ($lastFocusableElement.length !== 0) {
                    tabbableElements.add($lastFocusableElement);
                }

                function ariaSelectedAllowed(element) {
                    var allowedRoles = ['gridcell', 'option', 'row', 'tab', 'columnheader', 'menuitemradio', 'rowheader', 'treeitem'];
                    return allowedRoles.indexOf(element.getAttribute('role')) > -1
                }

                tabbableElements = tabbableElements.each(function () {
                    var $this = $(this);
                    if (!$this.hasClass('ignore-tabindex-update')) {
                        $this.attr('tabindex', 0);
                    }
                    if (ariaSelectedAllowed($this.get(0))) {
                        if ($this.parent().hasClass('active')) {
                            $this.attr('aria-selected', 'true');
                        }
                        else {
                            $this.attr('aria-selected', 'false');
                        }
                    }
                });
                ko.bindingHandlers.tabIndex.setCheckAndRadioBehavior(tabbableElements);

                if ($('.onlineapp-tabs').is(':visible') && !avoidSetTabOrder) {
                    OnlineApp.Helpers.applicationTabOrderHelper.setTabOrder();
                }
            },

            resetOrder: function (parentContainer) {
                var tabbing = this;
                $(document).one("keydown", function (e) {
                    var keyCode = e.keyCode || e.which;

                    if (keyCode == 9) {
                        e.preventDefault();

                        tabbing.getTabbableElements(parentContainer)
                            .filter(":visible:first")
                            .focus();
                    }
                });
            },

            shouldForceDropdownOpening: function ($element) {
                return $element.closest('.select-validation-error').length !== 0;
            },

            getFirstElement: function (parentContainer) {
                parentContainer = parentContainer || $('.box-container.edit-dialog:visible, .login-tab form:visible');

                var $tabbableElements = this.getTabbableElements(parentContainer).filter(':visible');
                var $uploadButton = $tabbableElements.filter('.attachment-upload-button:first');
                var $first = $tabbableElements.filter(':first');
                var hasError = false;
                var length = $tabbableElements.length;

                if ($uploadButton.length) {
                    return $uploadButton;
                }

                for (var i = 0; i < length; i++) {
                    var $element = $($tabbableElements[i]);

                    hasError = $element.hasClass('validation-error');
                    if (!hasError) {
                        isElementDropdown = hasError = $element.closest('.select-validation-error').length !== 0;
                    }

                    if (!hasError) { // case for radiogroup or checkboxes group
                        var inputSet = $element.closest('.radio-set, .checkbox-set');
                        hasError = inputSet.hasClass('validation-error') || inputSet.parent().hasClass('validation-error');
                    }

                    if (hasError) {
                        $first = $element;
                        break;
                    }
                }

                var $inputSet = $first.closest('.radio-set');

                if ($inputSet.length) {
                    var $checkedRadio = $inputSet.find('input[type=\'radio\']:checked');
                    if ($checkedRadio.length) {
                        $first = $checkedRadio;
                    }
                }

                return $first;
            },

            activateFirstElement: function (parentContainer, callback) {
                var $first = this.getFirstElement(parentContainer);

                // If the validation was caused by pressing some button, we need 
                // to wait for all events, otherwise we can immediately lose focus.
                setTimeout(function () {
                    $first.focus();

                    if (callback !== undefined)
                        callback($first);
                });
            }
        };

        self.updateFloatingMenu = function () {
            if ($('html').is('.job-page')) return;

            var $wrapper = self.getOnlineAppContainer(),
                $navTabs = $wrapper.find('.nav-tabs');

            $wrapper = $wrapper.has($navTabs[0]);

            if (!$navTabs.is(":visible")) return;

            var firstItem = $navTabs.children('li:visible:first'),
                menuItemsCount = $navTabs.children('li:visible').length;

            var menuHeight = firstItem.outerHeight(true) * menuItemsCount;
            var navTabsPaddingTop = parseInt($navTabs.css('padding-top'), 10);
            var scrollContainerRect = $wrapper.scrollParent()[0].getBoundingClientRect();
            var fullHeight = menuHeight + scrollContainerRect.top + navTabsPaddingTop;

            if (fullHeight < $(window).height()) {
                $navTabs.addClass('fixed');

                var positionStyleValue = $navTabs.css('position');

                if (positionStyleValue === 'fixed') {
                    $navTabs.css('top', 'auto');
                } else {
                    $navTabs.css('top', 0);
                }
            } else {
                $navTabs.removeClass('fixed');
                $navTabs.css('top', 0);
            }
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        layoutHelper: new LayoutHelper()
    });

})(window);;
(function(window, undefined) {
    function ApplicationTabOrderHelper() {
        var self = this;

        var $lastActiveMenuItem = null,
            $currentFirstTabbableElement = null,
            $currentLastTabbableElement = null,
            $currentTabLink = null,
            $previousTab = null;

        var containerSelector = '.onlineapp-app-container';

        self.setLastMenuItemFocusBehaviour = function() {
            var $container = $(containerSelector);
            var $lastMenuItem =
                $container.find('ul.left-menu-nav li a:not(.disabled)').last();
            var $nextFocusableElement = $('#last-focusable-element');

            if (!$nextFocusableElement.length) {
                var footerSelector = window.revampedDesign
                    ? '#footer,footer,#footer-new,#sjobs-footer-new'
                    : '#footer,footer';
                var $footer = $(footerSelector);
                $nextFocusableElement = $($footer.find(':tabbable').first());

                gJobs.focusService.setFocusOnKeydown({
                    $element: $nextFocusableElement,
                    $targetElement: $lastMenuItem,
                    $previousElement: $lastActiveMenuItem,
                    shift: true
                });
            } else {
                gJobs.focusService.setFocusOnKeydown({
                    $element: $nextFocusableElement,
                    $targetElement: $lastMenuItem,
                    shift: true
                });
            }

            gJobs.focusService.setFocusOnKeydown({
                $element: $lastMenuItem,
                $targetElement: $nextFocusableElement,
                $previousElement: $lastActiveMenuItem
            });

            $lastActiveMenuItem = $lastMenuItem;
        };

        self.setTabOrder = function () {

            self.setLastMenuItemFocusBehaviour();

            var activeTab = OnlineApp.Controllers.navigationMenuController.getActiveTab();

            if (!activeTab.tab.length) return;

            var $activeTabLink = $('ul.left-menu-nav [href="#' + activeTab.tabId + '"]');
            var $tabbableElements = activeTab.tab.find(':tabbable');
            var $lastTabbableElement = $($tabbableElements.last());
            var $firstTabbableElement = $($tabbableElements.first());
            var $nextTab = $activeTabLink.parent().next().find('a:not(.disabled)');

            gJobs.focusService.setFocusOnKeydown({
                $element: $activeTabLink,
                $targetElement: $firstTabbableElement,
                $previousElement: $currentTabLink
            });

            gJobs.focusService.setFocusOnKeydown({
                $element: $firstTabbableElement,
                $targetElement: $activeTabLink,
                $previousElement: $currentFirstTabbableElement,
                shift: true
            });

            gJobs.focusService.setFocusOnKeydown({
                $element: $lastTabbableElement,
                $targetElement: $nextTab,
                $previousElement: $currentLastTabbableElement
            });

            if ($nextTab.length) {
                gJobs.focusService.setFocusOnKeydown({
                    $element: $nextTab,
                    $targetElement: $lastTabbableElement,
                    $previousElement: $previousTab,
                    shift: true
                });
            } else {
                gJobs.focusService.removeFocusOnKeydownHandler($previousTab, true);
            }

            $currentFirstTabbableElement = $firstTabbableElement;
            $currentLastTabbableElement = $lastTabbableElement;
            $currentTabLink = $activeTabLink;
            $previousTab = $nextTab;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Helpers',
    {
        applicationTabOrderHelper: new ApplicationTabOrderHelper()
    });
})(window);
;
(function (window, undefined) {
    'use strict';


    function DateTimeFormatter() {

        var self = this;


        self.getMilitaryTime = function (dateTime) {

            function pad(number, length) {

                var str = '' + number;

                while (str.length < length) {
                    str = '0' + str;
                }

                return str;

            }
            
            var militaryHours = dateTime.getHours();
            var isAfterNoon = (militaryHours >= 12);

            var hours = (militaryHours % 12);
            hours = hours ? hours : 12;

            var minutes = dateTime.getMinutes();

            return pad(hours, 2) + ':' + pad(minutes, 2) + ' ' + (isAfterNoon ? 'PM' : 'AM');
        },

        self.getFullDate = function (dateTime) {

            var months = [
                'January', 'February', 'March', 'April', 'May',
                'June', 'July', 'August', 'September', 'October',
                'November', 'December'
            ];

            var weekDays = [
                'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
            ];


            var formattedDate =
                weekDays[dateTime.getDay()] + ', ' +
                months[dateTime.getMonth()] + ' ' +
                dateTime.getDate();

            return formattedDate;
        },

        self.getFullDateNoDay = function (dateTime) {

            var months = [
                'January', 'February', 'March', 'April', 'May',
                'June', 'July', 'August', 'September', 'October',
                'November', 'December'
            ];
            
            var formattedDate =
                months[dateTime.getMonth()] + ' ' +
                dateTime.getDate();

            return formattedDate;
        },

        self.getShortDate = function (dateTime) {
            var day = dateTime.getDate();
            var month = dateTime.getMonth() + 1;
            var year = dateTime.getFullYear();

            var dateComponents = [month, day, year];
            var dateOutput = dateComponents.join('/');

            return dateOutput;
        },

        self.getShortDateTime = function (dateTime) {
            var date = self.getShortDate(dateTime);
            var time = self.getMilitaryTime(dateTime);

            var formattedDateTime = (date + ' ' + time);

            return formattedDateTime;
        }
    }



    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        DateTimeFormatter: new DateTimeFormatter()
    });

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

    function Notifications() {
        var self = this;

        self.showResponseMessages = function (response) {
            var messagesToShow = [];
            
            if (typeof response == 'string' || response instanceof String) {
                messagesToShow = [response];
            } else if ($.isArray(response)) {
                for (var i = 0; i < response.length; i++) {
                    var error = response[i];
                    if (error && error.errorMessage) {
                        messagesToShow.push(error.errorMessage);
                    }
                }
            }
            if (messagesToShow.length === 0) {
                messagesToShow = [Resources.NotificationMessages.EncounteredProblem];
            }
            
            for (var i = 0; i < messagesToShow.length; i++) {
                toastr.warning(messagesToShow[i]);
            }
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        Notifications: new Notifications()
    });

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

    var debounce = function (func, wait) {
        var timeout,
            args,
            context,
            timestamp,
            result,
            later = function () {
                var last = getNowDate() - timestamp;
                if (last < wait) {
                    timeout = setTimeout(later, wait - last);
                } else {
                    timeout = null;
                    result = func.apply(context, args);
                    context = args = null;
                }
            },
            getNowDate = Date.now || function () {
                return new Date().getTime();
            };

        return function () {
            context = this;
            args = arguments;
            timestamp = getNowDate();
            if (!timeout) {
                timeout = setTimeout(later, wait);
            }

            return result;
        };
    };

    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        FunctionUtilities: {
            debounce: debounce
        }
    });

})(window);;
(function (window, undefined) {

    function CaptchaHelper(container) {

        var self = this;
        var captchaContainerSelector = 'captcha-container';
        var captchaContainerClassSelector = '.' + captchaContainerSelector;
        var captchaContainerIdSelector = '#' + captchaContainerSelector;
        var currentCaptchaIndices = [];

        self.isCaptchaSubmitted = false;
        self.container = container || 'document';

        function enableLoginButtonForSubmitedRecaptcha() {
            var recaptchaContainers = $(self.container).find(captchaContainerClassSelector);
            for (var captchaIndex = 0; captchaIndex < recaptchaContainers.length; captchaIndex++) {
                if (grecaptcha.getResponse(currentCaptchaIndices[captchaIndex]).length > 0) {
                    var captchaContainer = $(captchaContainerIdSelector + captchaIndex);
                    captchaContainer.parent().next('button').prop('disabled', false);
                    captchaContainer.attr('aria-label', 'Recaptcha challenge solved');
                }
            }
        }

        self.setCaptchaResponse = function(response) {
            self.captchaResponse = response;
            self.isCaptchaSubmitted = true;

            enableLoginButtonForSubmitedRecaptcha();
        }

        self.expiredResponseCallback = function() {
            self.isCaptchaSubmitted = false;
        }

        self.resetCaptcha = function () {
            var recaptchaContainers = $(self.container).find(captchaContainerClassSelector);
            for (var captchaIndex = 0; captchaIndex < recaptchaContainers.length; captchaIndex++) {
                var captchaContainer = $(captchaContainerIdSelector + captchaIndex);
                captchaContainer.parent().next('button').prop('disabled', true);
                captchaContainer.attr('aria-label', 'Plеase, solve captcha challenge');
                self.captchaResponse = null;
                self.isCaptchaSubmitted = false;
                grecaptcha.reset(currentCaptchaIndices[captchaIndex]);
            }
        }

        self.renderCaptcha = function () {
            grecaptcha.ready(function() {
                currentCaptchaIndices = [];
                var recaptchaContainers = $(self.container).find(captchaContainerClassSelector);
                for (var i = 0; i < recaptchaContainers.length; ++i) {
                    if ($(recaptchaContainers[i]).is(':empty')) {
                        $(recaptchaContainers[i]).attr('id', captchaContainerSelector + i);
                        var captchaIndex = grecaptcha.render($(recaptchaContainers[i]).attr('id'),
                            {
                                'sitekey': window.recaptchaPublicKey,
                                'callback': self.setCaptchaResponse,
                                'expired-callback': self.expiredResponseCallback
                            });
                        $(recaptchaContainers[i]).find('iframe').attr('title', 'Captcha Challenge');
                        $(recaptchaContainers[i]).parent().next('button').prop('disabled', true);
                        currentCaptchaIndices.push(captchaIndex);
                    }
                }
            });
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        CaptchaHelper: CaptchaHelper,
        loginCaptchaHelper: new CaptchaHelper('.login-tab')
    });

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

    function TextSearchWithAutocompleteLabelsComponentHelper() {
        var self = this;

        var fullWidthClassName = 'full-width';

        function createSelectedAutocompleteLabel(labelText,originalLabel,name) {
            var labelMarkup = '<div class="selected-search-label-container">' +
                                '<span class="selected-search-label-text popover-trigger" ' +
                                      'data-toggle="popover" ' +
                                      'data-trigger="hover focus" ' +
                                      'data-placement="bottom" ' +
                                      'data-container="body" ' +
                                      'data-selector="true" ' +
                'data-original-title=" ">' +
                                    labelText +
                                '</span>' +
                '<button class="selected-search-label-remove-button ss-delete popover-trigger" aria-label="Remove ' + name + ' &quot;' + originalLabel + '&quot;" data-trigger="hover focus" data-toggle="popover" data-container="body" data-placement="bottom" title="Remove ' + name + ' &quot;' + originalLabel +'&quot;"></button>' +
                              '</div>';

            return $(labelMarkup);
        }

        function removeSelectedAutocompleteLabelFromLabelsContainer(event) {
            var $removeButton = $(event.target);

            $removeButton.parent('.selected-search-label-container').remove();
        }

        function recalculateSearchFieldWidthAfterRemovingSelectedLabel(searchComponentContainerSelector) {
            var $searchFieldContainer = $(searchComponentContainerSelector + ' .search-field-container');
            var $searchField = $searchFieldContainer.find('.search-field');

            $searchFieldContainer.removeClass(fullWidthClassName);

            if ($searchField[0].clientHeight < $searchField[0].scrollHeight) {
                $searchFieldContainer.addClass(fullWidthClassName);
            }
        }

        self.addSelectedAutocompleteLabelToSearchComponent = function(labelText, searchComponentContainerSelector, removeSelectedAutocompleteLabelCallback,name,fieldSelector) {
            var truncatedLabelText = labelText;

            if (labelText.length > window.selectedLabelTextLengthForAdvancedJobInterestCard) {
                truncatedLabelText = labelText.substring(0, window.selectedLabelTextLengthForAdvancedJobInterestCard) + '...';
            }
            $(fieldSelector).removeAttr("aria-label");
            var $selectedLabel = createSelectedAutocompleteLabel(truncatedLabelText, labelText, name);
            $(fieldSelector).attr("aria-label", name + " " + labelText + " " + 'selected');           
            var buttonToolTipText = "Remove " + name + ' "' + labelText+'"';

            $selectedLabel.find('button[data-toggle="popover"]').attr('data-content', buttonToolTipText);
            $selectedLabel.find('button[data-toggle="popover"]').popover();

            $selectedLabel.find('span[data-toggle="popover"]').attr('data-content', labelText);
            $selectedLabel.find('span[data-toggle="popover"]').popover();

            $selectedLabel.find('.selected-search-label-remove-button').click(function(event) {
                if (removeSelectedAutocompleteLabelCallback) removeSelectedAutocompleteLabelCallback();

                removeSelectedAutocompleteLabelFromLabelsContainer(event);
                recalculateSearchFieldWidthAfterRemovingSelectedLabel(searchComponentContainerSelector);
            });
           

            var $containerForSelectedLabel = $(searchComponentContainerSelector + ' .search-labels-container');

            if ($containerForSelectedLabel && $containerForSelectedLabel.length)
                $containerForSelectedLabel.append($selectedLabel);
        };

        self.initScrollHandlersForSearchField = function(searchComponentContainerSelector) {
            var $searchFieldContainer = $(searchComponentContainerSelector + ' .search-field-container');
            var $searchField = $searchFieldContainer.find('.search-field');

            if ($searchField && $searchField.length) {
                $searchField.on('input', function(event) {
                    if ($searchField[0].clientHeight < $searchField[0].scrollHeight) {
                        if ($searchFieldContainer.hasClass(fullWidthClassName)) {
                            $searchField.height($searchField[0].scrollHeight);
                        }

                        $searchFieldContainer.addClass(fullWidthClassName);
                    }
                });

                $searchField.on('keydown', function(event) {
                    if ($searchField[0].clientHeight >= $searchField[0].scrollHeight) {
                        var key = event.keyCode || event.charCode;

                        if (key === $.ui.keyCode.BACKSPACE || key === $.ui.keyCode.DELETE) {
                            $searchFieldContainer.removeClass(fullWidthClassName);
                        }
                    }
                });
            }
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        textSearchWithAutocompleteLabelsComponentHelper: new TextSearchWithAutocompleteLabelsComponentHelper()
    });

})(window);
;
(function (window, undefined) {
    'use strict';
    /*
        Sometimes when server is misconfigured, it may respond with HTTP 302 status code instead of HTTP 401 when user session is expired.
        As Ajax requests automatically follow these redirects, the response may end up being 200 OK, so we need to perform validation
        of the response body to be sure it is really a valid success response from the API.
    */

    var isValidSuccessResponse = function (responseData) {
        return (responseData &&
            (responseData.isSuccess === true || !!responseData.dateSubmittedText));
    };

    var ensurePromiseFailsOnInvalidData = function (promise, customSuccessResponseValidator) {
        var deferred = $.Deferred();

        var validate = customSuccessResponseValidator || isValidSuccessResponse;

        promise.done(function (data) {
            if (validate(data)) {
                deferred.resolveWith(this, arguments);
            } else {
                deferred.rejectWith(this, arguments);
            }
        }).fail(function () {
            deferred.rejectWith(this, arguments);
        });

        var resultPromise = deferred.promise();

        //If the original promise is a jQuery XHR object, then legacy subscribers may expect it to have
        //'success' and 'error' methods which are actually the same as 'done' and 'fail'
        if (typeof promise.error === 'function') {
            resultPromise.error = resultPromise.fail;
        }
        if (typeof promise.success === 'function') {
            resultPromise.success = resultPromise.done;
        }

        return resultPromise;
    };

    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        ajaxResponseValidator: {
            ensurePromiseFailsOnInvalidData: ensurePromiseFailsOnInvalidData
        }
    });

})(window);;
(function (window, undefined) {

    function PopoverHelper() {

        var self = this;

        self.initializePopover = function (container, button) {
            $(container).on('click', function (event) {
                var $button = $(button);
                var $target = $(event.target);
                var isTheSameElement = $target.closest($button).length != 0;
                var $popover = $button.siblings('.popover');

                if (isTheSameElement) {
                    if ($popover.length && !$popover.is(':visible')) {
                        $button.popover('show');
                    }
                } else {
                    $button.popover('hide');
                }
            });
        };

        self.accountInitializePopover = function (container, button) {
            $(container).mouseover(function (event) {
                var $button = $(button);
                var $target = $(event.target);
                var isTheSameElement = $target.closest($button).length != 0;
                var $popover = $button.siblings('.popover');

                if (isTheSameElement) {
                    if (!$popover.is(':visible')) {
                        $button.popover('show');
                    }
                } else {
                    $button.popover('hide');
                }
            });
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Helpers', {
        popoverHelper: new PopoverHelper()
    });

})(window);;
(function (window, undefined) {
    'use strict';
    
    function renderTemplateToString(templateName, viewModel, shouldStripHtmlTags) {
        var $virtualElement = $('<div>');
        var bindingContext = viewModel;

        ko.renderTemplate(templateName,
                         bindingContext,
                         { templateEngine: ko.KoExternalTemplateEngine() },
                         $virtualElement.get(0),
                         'replaceChildren');

        var templateString = $virtualElement.html();
        if (shouldStripHtmlTags) {
            templateString = $(templateString).text();
        }

        $virtualElement.remove();
        return templateString;
    }

    OnlineApp.Namespace.extend('OnlineApp.Helpers.Templates', {
        renderTemplateToString: renderTemplateToString
    });

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

    function CachedAjaxRequest(options) {
        var self = this;

        var request = null;
        var data = null;

        self.send = function() {

            if (data === null) {
                if (request === null) {
                    request = $.ajax(options)
                        .then(function (data) {
                            data = data;
                            return data;
                        })
                        .always(function () {
                            request = null;
                        });
                    return request;
                } else {
                    return request;
                }
            }

            return $.when(data);
        }

        self.resetCache = function() {
            data = null;
        }
    }

    namespace('gJobs').CachedAjaxRequest = CachedAjaxRequest;

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

    function LocalStorageHelper() {
        var self = this;

        self.updateItemForMultipleTabs = function (key, value) {
            localStorage.removeItem(key);
            localStorage.setItem(key, value);
        }
    }

    namespace('gJobs').LocalStorageHelper = LocalStorageHelper;
    namespace('gJobs').localStorageHelper = new LocalStorageHelper();

})(window);
;
 function getListOfElmentsToBeExcluded() {
        var elementsToExclude = ['showNewResetPassword', 'hideNewResetPassword', 'showResetPassword', 'hideResetPassword',
            'showPassword', 'hidePassword', 'showCurrentPassword', 'hideCurrentPassword',
            'showNewPassword', 'hideNewPassword', 'showConfirmPassword', 'hideConfirmPassword',
            'showCurrentEditEmailPassword', 'hideCurrentEditEmailPassword', 'showSignUpPassword', 'hideSignUpPassword',
            'showSignUpConfirmPassword', 'hideSignUpConfirmPassword', 'search-button', 'clear-field-button', 'closeMap', 'openMap', 'top-resume-upload', 'att-send-to-top-resume',
            'action-grid-view', 'action-list-view', 'keyword-search-input', 'location-search-input', 'header-keyword-search-input', 'header-location-search-input','chatbase-bubble-button'];
        return elementsToExclude;
    }
    
;
'use strict';

class TabsManual {
    constructor(groupNode) {
        this.tablistNode = groupNode;

        this.tabs = [];

        this.firstTab = null;
        this.lastTab = null;

        this.tabs = Array.from(this.tablistNode.querySelectorAll('a'));        

        for (var i = 0; i < this.tabs.length; i ++) {
            var tab = this.tabs[i];           

            tab.tabIndex = -1;
            tab.setAttribute('aria-selected', 'false');            

            tab.addEventListener('keydown', this.onKeydown.bind(this));
            tab.addEventListener('click', this.onClick.bind(this));

            if (!this.firstTab) {
                this.firstTab = tab;
            }
            this.lastTab = tab;
        }

        this.setSelectedTab(this.firstTab);
    }

    setSelectedTab(currentTab) {
        for (var i = 0; i < this.tabs.length; i += 1) {
            var tab = this.tabs[i];
            if (currentTab === tab) {
                tab.setAttribute('aria-selected', 'true');
                tab.removeAttribute('tabindex');                
            } else {
                tab.setAttribute('aria-selected', 'false');
                tab.tabIndex = -1;                
            }
        }
    }

    moveFocusToTab(currentTab) {
        currentTab.focus();
    }

    moveFocusToPreviousTab(currentTab) {
        var index;

        if (currentTab === this.firstTab) {
            this.moveFocusToTab(this.lastTab);
        } else {
            index = this.tabs.indexOf(currentTab);
            this.moveFocusToTab(this.tabs[index - 1]);
        }
    }

    moveFocusToNextTab(currentTab) {
        var index;

        if (currentTab === this.lastTab) {
            this.moveFocusToTab(this.firstTab);
        } else {
            index = this.tabs.indexOf(currentTab);
            this.moveFocusToTab(this.tabs[index + 1]);
        }
    }

    /* EVENT HANDLERS */

    onKeydown(event) {
        var tgt = event.currentTarget,
            flag = false;

        switch (event.key) {
            case 'ArrowLeft':
                this.moveFocusToPreviousTab(tgt);
                flag = true;
                break;

            case 'ArrowRight':
                this.moveFocusToNextTab(tgt);
                flag = true;
                break;

            case 'Home':
                this.moveFocusToTab(this.firstTab);
                flag = true;
                break;

            case 'End':
                this.moveFocusToTab(this.lastTab);
                flag = true;
                break;

            default:
                break;
        }

        if (flag) {
            event.stopPropagation();
            event.preventDefault();
        }
    }

    // Since this example uses buttons for the tabs, the click onr also is activated
    // with the space and enter keys
    onClick(event) {
        this.setSelectedTab(event.currentTarget);
    }
}




;
(function (window, undefined) {
    'use strict';

    function AccountSettingsHelper() {
        var self = this;

        self.getLinkForAccountSettings = function () {
            var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();

            var ACCOUNT_SETTINGS_URL = "/Applications/AccountSettings";
            
            var linkForAccountSettings = "";
            var currentArea = gJobs.areaInfoService.getCurrentArea();

            if (currentArea === abstractAreaInfoService.areaNames.GJobs) {
                linkForAccountSettings = ACCOUNT_SETTINGS_URL;
            } else {
                if (currentArea === abstractAreaInfoService.areaNames.Career) {
                    linkForAccountSettings = AgencyPages.pageInfoService.getCurrentAgencyHomePath() + ACCOUNT_SETTINGS_URL;
                } else if (currentArea === abstractAreaInfoService.areaNames.Agency) {
                    var agencyFolderName = AgencyPages.pageInfoService ?
                        AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                        gJobs.pageInfoService.getCurrentAgencyPageFolderName();

                    linkForAccountSettings = ACCOUNT_SETTINGS_URL + "/" + agencyFolderName;
                }
            }

            return linkForAccountSettings;
        }
    }

    namespace('gJobs').AccountSettingsHelper = AccountSettingsHelper;
    namespace('gJobs').accountSettingsHelper = new AccountSettingsHelper();

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

    function EmailVerificationHelper() {
        if (window.enableEmailVerification && !window.enableEmailVerificationRefinements) {
            var EMAIL_VERIFICATION_BANNER_WRAPPER_ID = "email-verification-banner-wrapper";
            var EMAIL_VERIFICATION_BANNER_ID = "email-verification-banner";
            var CAREERS_FOOTER_SELECTOR = "#main-container footer";
            var GJOBS_FOOTER_SELECTOR = "#footer-new";
            var ACCOUNT_SETTINGS_LINK_SELECTOR = ".account-settings-link";
            var TO_TOP_BUTTON_SELECTOR = "#to-top-panel";

            var mainScrollableElement = document;
            var emailVerificationWrapper = $("#" + EMAIL_VERIFICATION_BANNER_WRAPPER_ID);
            var emailVerificationBanner = emailVerificationWrapper.children("#" + EMAIL_VERIFICATION_BANNER_ID);
            var accountSettingsLink = emailVerificationBanner.find(ACCOUNT_SETTINGS_LINK_SELECTOR);
            var toTopButton = $(TO_TOP_BUTTON_SELECTOR);
            var footer;

            var isEmailVerified = false;
            var isCareersPage = false;
            var isInitiated = false;
            var isBannerWasClosedInCurrentSession = (sessionStorage.getItem(OnlineApp.SessionKeys.IsBannerWasClosedInCurrentSession) === 'true');
            var isInboxPage = false;
            var isAgencyPages;
            var isFlyoutOpen = false;
            var isScheduleFlyoutOpen = false;

            var areaNames;
            var pageTypes;
            var currentPageType;
            var currentArea;
            var pageInfoService;
            var documentHeight = $(document).height();
            var mainScrollableElementHeight;

            function isJobPage() {
                return Boolean(($('.job-page').length || $('.standalone-job-page').length) && !$('.job-page-access-membership').length);
            }

            function isAgencyPagesApplicationProcess() {
                return isAgencyPages && pageInfoService.isOnApplyPage();
            }

            function isEmailVerificationBannerEnabled () {
                return !isEmailVerified && !isBannerWasClosedInCurrentSession;
            }

            function updateStylesForEmailVerificationBanner () {
                if (isEmailVerificationBannerEnabled()) {
                    if (isCareersPage) {
                        footer.css('margin-top', '');
                        emailVerificationWrapper.css('margin-top', footer.css('margin-top'));
                        emailVerificationWrapper.css('height', emailVerificationBanner.outerHeight() + "px");
                        footer.css('margin-top', '0');
                    } else {
                        emailVerificationWrapper.css('height', emailVerificationBanner.outerHeight() + "px");
                    }
                }
            }

            function closeEmailVerificationBanner () {
                sessionStorage.setItem(OnlineApp.SessionKeys.IsBannerWasClosedInCurrentSession, 'true');
                isBannerWasClosedInCurrentSession = true;

                emailVerificationWrapper.css('display', 'none');

                if (isCareersPage) {
                    footer.css('margin-top', '');
                }
            }

            function recalculateEmailVerificationBannerPosition () {
                if (isEmailVerificationBannerEnabled() && !isScheduleFlyoutOpen) {
                    if (isScrolledIntoView(footer)) {
                       emailVerificationBanner.css('position', 'absolute');
                       updateStylesForEmailVerificationBanner();
                    } else {
                       emailVerificationBanner.css('position', 'fixed');
                    }
                }
            }

            function showEmailVerificationBanner (fromLoginEvent) {
                if (fromLoginEvent || !isBannerWasClosedInCurrentSession) {
                    emailVerificationWrapper.css('display', 'block');
                    updateStylesForEmailVerificationBanner();
                }
            }

            function tryMakeEmailVerificationBannerAbsoluteBeforeShow () {
                var isProfileSettingsPage = currentPageType === pageTypes.profileSettings.type;

                if (currentPageType && (isProfileSettingsPage || documentHeight === $(window).height())) {
                    if (!isCareersPage && isProfileSettingsPage) {
                        /*
                            It's needed because on Gjobs "Profile Settings" page "onlineapp-loading-spinner"
                            will overlap email verification banner
                        */
                        emailVerificationBanner.css('z-index', 8);
                    }

                    emailVerificationBanner.css('position', 'absolute');

                    return true;
                }

                return false;
            }

            function isScrolledIntoView(el) {
                var rect = el[0].getBoundingClientRect();
                var elemTop = rect.top;
                var elemBottom = rect.bottom;
            
                var isVisible = elemTop < window.innerHeight && elemBottom >= 0;
                
                return isVisible;
            }

            function initEmailVerificationBanner () {
                if (!isEmailVerified && !isInitiated) {
                    var accountSettingsLinkHref = gJobs.accountSettingsHelper.getLinkForAccountSettings();

                    accountSettingsLink.attr('href', accountSettingsLinkHref);
                                
                    if (isInboxPage) {
                        (function startCheckingScrollableElementHeightChange () {
                            setInterval(function() {
                                var currentMainScrollableElementHeight = $(mainScrollableElement)[0].scrollHeight;
                                if (mainScrollableElementHeight !== currentMainScrollableElementHeight) {
                                    recalculateEmailVerificationBannerPosition();
                                    mainScrollableElementHeight = currentMainScrollableElementHeight;
                                }
                            }, 600);  
                        })();
                    } else if ((isCareersPage && currentPageType && currentPageType !== pageTypes.jobOpportunitiesJobs.type)
                                || (!isCareersPage && currentPageType && currentPageType !== pageTypes.homePage.type && currentPageType !== pageTypes.searchPage.type)
                    ) {
                        (function startCheckingDocumentHeightChange () {
                            setInterval(function() {
                                var currentDocumentHeight = $(mainScrollableElement).height();
                                if (!isFlyoutOpen && !isScheduleFlyoutOpen && documentHeight !== currentDocumentHeight) {
                                    recalculateEmailVerificationBannerPosition();
                                    documentHeight = currentDocumentHeight;
                                }
                            }, 600);    
                        })();
                    }
            
                    $(document).delegate('.close-email-verification-banner', 'click', closeEmailVerificationBanner);
                    $(document).on('resize', updateStylesForEmailVerificationBanner);
                    $(mainScrollableElement).scroll(recalculateEmailVerificationBannerPosition);

                    $(document).on(Events.CommonEventsNames.ToTopButtonTopPropertyChanged, function () {
                        if (isEmailVerificationBannerEnabled()) {
                            if (!toTopButton.length) {
                                toTopButton = $(TO_TOP_BUTTON_SELECTOR);
                            }

                            /* 
                                It's needed because email verification banner 
                                will overlap "to-top-panel" button
                            */
                           toTopButton.css('top',  (parseFloat(toTopButton.css('top')) - emailVerificationBanner.outerHeight()) + 'px');
                        }
                    });

                    $(document).on(Events.CommonEventsNames.ShowFlyout, function () {
                        isFlyoutOpen = true;
                        accountSettingsLink.attr('aria-hidden', 'true');
                        accountSettingsLink.attr('tabindex', -1);
                    });

                    $(document).on(Events.CommonEventsNames.FlyoutClosing, function () {
                        isFlyoutOpen = false;
                        accountSettingsLink.removeAttr('aria-hidden tabindex');
                    });

                    $(document).on(Events.CommonEventsNames.HistoryFlyoutOpened + " " + Events.CommonEventsNames.ScheduleFlyoutOpened, function () {
                        if (!isCareersPage) {
                            isFlyoutOpen = true;
                            emailVerificationBanner.css('position', 'fixed');
                        }
                    });

                    $(document).on(Events.CommonEventsNames.HistoryFlyoutClosed, function () {
                        if (!isCareersPage) {
                            isFlyoutOpen = false;
                            recalculateEmailVerificationBannerPosition();
                        }
                    });

                    $(document).on(Events.CommonEventsNames.ScheduleFlyoutOpened, function () {
                        if (!isCareersPage) {
                            isScheduleFlyoutOpen = true;
                        }
                    });

                    $(document).on(Events.CommonEventsNames.ScheduleFlyoutClosed, function () {
                        if (!isCareersPage) {
                            isFlyoutOpen = false;
                            isScheduleFlyoutOpen = false;
                        }
                    });

                    isInitiated = true;

                    if (!tryMakeEmailVerificationBannerAbsoluteBeforeShow()) {
                        emailVerificationBanner.css('position', 'fixed');
                    }
                }
            }

            function tryShowEmailVerificationBanner (fromLoginEvent) {
                var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();

                pageInfoService = gJobs.pageInfoService ? gJobs.pageInfoService : AgencyPages.pageInfoService;
                pageTypes = pageInfoService.getPageTypes();
                var currentPage = pageInfoService.getCurrentPageType();
                areaNames = abstractAreaInfoService.areaNames;
                currentArea = gJobs.areaInfoService.getCurrentArea();
                isAgencyPages = currentArea === areaNames.Agency;

                if (currentArea === areaNames.Career) {
                    isCareersPage = true;
                    footer = $(CAREERS_FOOTER_SELECTOR);
                    emailVerificationWrapper.css('position', 'relative');
                } else {
                    footer = $(GJOBS_FOOTER_SELECTOR);
                }

                if (currentPage) {
                    currentPageType = currentPage.type;
                }

                if (currentPageType === pageTypes.inbox.type || (isAgencyPages && currentPageType === pageTypes.agencyInbox.type)) {
                    isInboxPage = true;

                    if (isCareersPage) {
                        mainScrollableElement = $('#sizer');
                    } else {
                        mainScrollableElement = $('#body-container');
                    }

                    mainScrollableElementHeight = mainScrollableElement[0].scrollHeight;
                }

                if ((!currentPageType || currentPageType !== pageTypes.accountSettings.type) && !isAgencyPagesApplicationProcess() && !isJobPage()) {
                    OnlineApp.Services.authenticationService.isLoggedIn()
                        .done(function (isLoggedIn) {
                            if (isLoggedIn) {
                                OnlineApp.Services.emailVerificationService.isEmailVerified()
                                .then(function(response) {
                                    var data = response.data;
            
                                    if (data.isEmailVerified !== true) {
                                        initEmailVerificationBanner();
                                        showEmailVerificationBanner(fromLoginEvent);
                                    } else {
                                        isEmailVerified = true;
                                    }
                                });
                            }
                        });
                }
            }


            $(document).ready(function () {
                tryShowEmailVerificationBanner();
            });

            $(document).on(Events.CommonEventsNames.Login + " " + Events.CommonEventsNames.Register, function () {
                isEmailVerified = false;

                isBannerWasClosedInCurrentSession = false;
                sessionStorage.setItem(OnlineApp.SessionKeys.IsBannerWasClosedInCurrentSession, "false");
                
                tryShowEmailVerificationBanner(true);
            });
            $(document).on(OnlineApp.Events.CommonEventsNames.EmailVerified, function () {
                emailVerificationWrapper.css('display', 'none');

                if (isCareersPage) {
                    footer.css('margin-top', '');
                }
                
                isEmailVerified = true;
            });
        }
    }

    namespace('gJobs').emailVerificationHelper = new EmailVerificationHelper();

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

    function AccountVerificationHelper() {
        var self = this,
            showBannerAfterSuccessfulVerificationQueryParameter = "showBannerAfterSuccessfulVerification",
            showBannerAfterFailedVerificationQueryParameter = "showBannerAfterFailedVerification",
            emailAddressQueryParameter = "emailAddress",
            failVerificationLinkNotificationClassName = "fail-verification-link-notification";
        
        self.showNotification = function(htmlContent, options) {
            var successEmailNotificationEventName = "successEmailNotification";
            var successEmailNotificationSelector = "success-email-notification";
            var successEmailNotification = $('#' + successEmailNotificationSelector);

            if (successEmailNotification.length !== 0) {
                successEmailNotification.html(htmlContent);
                if (options && options.additionalCssClassNames) {
                    successEmailNotification.addClass(options.additionalCssClassNames);
                }
                successEmailNotification.css("display", "flex");
            } else {
                $('body').append(
                    "<div class='uses-gjobs-styles'><div id='" + successEmailNotificationSelector + "'>" + htmlContent + "</div></div>"
                );

                successEmailNotification = $('#' + successEmailNotificationSelector);

                if (options && options.additionalCssClassNames) {
                    successEmailNotification.addClass(options.additionalCssClassNames);
                }
            }

            gJobs.screenReadersService.setAriaLiveNotification(successEmailNotification.text());

            $(document).on('click.' + successEmailNotificationEventName, function () {
                successEmailNotification.css("display", "none");
                if (options && options.additionalCssClassNames) {
                    successEmailNotification.removeClass(options.additionalCssClassNames);
                }
            });

            setTimeout(function () {
                successEmailNotification.css("display", "none");
                if (options && options.additionalCssClassNames) {
                    successEmailNotification.removeClass(options.additionalCssClassNames);
                }
                $(document).off('click.' + successEmailNotificationEventName);
            }, 20000)
        };

        //Mimic to serve Banner for Resend Link
        self.showNotificationMimic = function (htmlContent, options, isSuccess) {
            var successEmailNotificationEventName = "successEmailNotification";
            var emailNotificationSelector = isSuccess ? "success-email-notification" : "fail-email-notification";
            var successEmailNotification = $('#' + emailNotificationSelector);

            if (successEmailNotification.length !== 0) {
                successEmailNotification.html(htmlContent);
                if (options && options.additionalCssClassNames) {
                    successEmailNotification.addClass(options.additionalCssClassNames);
                }
                successEmailNotification.css("display", "flex");
            } else {
                $('body').append(
                    "<div class='uses-gjobs-styles'><div id='" + emailNotificationSelector + "'>" + htmlContent + "</div></div>"
                );

                successEmailNotification = $('#' + emailNotificationSelector);

                if (options && options.additionalCssClassNames) {
                    successEmailNotification.addClass(options.additionalCssClassNames);
                }
            }

            gJobs.screenReadersService.silenceScreenreaderForBanner(successEmailNotification.text());            
            $(document).on('click.' + successEmailNotificationEventName, function () {
                successEmailNotification.css("display", "none");
                if (options && options.additionalCssClassNames) {
                    successEmailNotification.removeClass(options.additionalCssClassNames);
                }
            });

            setTimeout(function () {
                successEmailNotification.css("display", "none");
                if (options && options.additionalCssClassNames) {
                    successEmailNotification.removeClass(options.additionalCssClassNames);
                }
                $(document).off('click.' + successEmailNotificationEventName);
            }, 20000)
        };

        self.showAccountVerificationNotification = function (userEmail, verificationResult) {
            var isSuccess = verificationResult == "true";
            var htmlContentSuccess = "<div class='success-email-notification-holder'><img class='email-verification-success-icon' src='/Content/Images/email-verification-success-notification-icon-white.svg' /><span role='alert'>Your account (" + userEmail + ") is verified</span></div>";
            var htmlContentFail = "<div class='fail-verification-link-notification'><img class='email-verification-success-icon' src='/Content/Images/email-verification-success-notification-icon-white.svg' /><span role='alert'>Sorry, your request is invalid. This email address is already in use</span></div>";

            self.showNotificationMimic(isSuccess ? htmlContentSuccess : htmlContentFail, null, isSuccess);
        }

        self.showResendCodeSuccessNotification = function () {
            var htmlContent = "<div class='success-email-notification-holder'><span>A new verification code has been sent to your email address</span></div>";

            self.showNotification(htmlContent);
        }

        self.showVerificationLinkFailNotification = function() {
            var htmlContent = "<div class='success-email-notification-holder'><span>Your verification link is expired</span></div>";

            var options = {
                additionalCssClassNames: failVerificationLinkNotificationClassName
            };

            self.showNotification(htmlContent, options);
        };

        self.showVerificationLinkSendSuccessNotification = function() {
            var htmlContent = "<div class='success-email-notification-holder'><span>Confirmation link sent!</span></div>";

            self.showNotificationMimic(htmlContent, null, true);
        };

        self.showVerificationLinkSendFailNotification = function() {
            var htmlContent = "<div class='success-email-notification-holder'><span>Confirmation link wasn't sent. Please try again</span></div>";

            var options = {
                additionalCssClassNames: failVerificationLinkNotificationClassName
            };

            self.showNotification(htmlContent, options);
        };

        function removeEmailVerificationParametersFromUrl() {
            var currentUrl = window.location.href.replace(/&?(showBannerAfterSuccessfulVerification|showBannerAfterFailedVerification)=([^&]$|[^&]*)/ig, "");

            return currentUrl;
        }

        $(document).ready(function() {
            if (window.enableEmailVerificationRefinements) {
                var currentUrl = removeEmailVerificationParametersFromUrl();
                var verificationResult = window.utils.getUrlParameter(showBannerAfterSuccessfulVerificationQueryParameter);

                if (verificationResult) {
                    var userEmail = decodeURIComponent(window.utils.getUrlParameter(emailAddressQueryParameter));

                    self.showAccountVerificationNotification(userEmail, verificationResult);

                    history.pushState(null, "", currentUrl);
                }

                if (window.utils.getUrlParameter(showBannerAfterFailedVerificationQueryParameter)) {
                    self.showVerificationLinkFailNotification();
                    history.pushState(null, "", currentUrl);
                }
            }
        });
    }

    OnlineApp.Namespace.extend('gJobs.Helpers', {
        accountVerificationHelper: new AccountVerificationHelper()
    });

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

    var $verifyIdentityEl = $('#verify-identity');

    //
    // Initializer
    //
    $(function () {
        if ($verifyIdentityEl.get(0)) {
            $('.common-notification').text('');
            var verifyIdentityViewModel = new gJobs.ViewModels.VerifyIdentityViewModel();
            ko.applyBindings(verifyIdentityViewModel, $verifyIdentityEl.get(0));
        }
    });

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

    var $verifyAccountEl = $('#verify-account');

    //
    // Initializer
    //
    $(function() {
        if ($verifyAccountEl.get(0)) {
            $('.common-notification').text('');
            var verifyAccountViewModel = new gJobs.ViewModels.VerifyAccountViewModel();
            ko.applyBindings(verifyAccountViewModel, $verifyAccountEl.get(0));
        }
    });

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

    var expiredVerificationLinkContainer = $('#expired-verification-link-container');

    //
    // Initializer
    //
    $(function() {
        if (expiredVerificationLinkContainer.get(0)) {

            var expiredVerificationLinkViewModel = new gJobs.ViewModels.ExpiredVerificationLinkViewModel();

            ko.applyBindings(expiredVerificationLinkViewModel, expiredVerificationLinkContainer.get(0));
        }
    });

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

    function EditEmailAddressViewModel() {
        var SESSION_EXPIRED_REASON = "SessionExpired";
        var self = this,
            editEmailLinkSelector = "#editEmailLink",
            verifyAccountDataContainerSelector = "#verify-account-data-container",
            dataVerifyAccountExternalLoginAttribute = "data-verify-account-external-login";


        self.emailAddress = ko.observable('').extend({ required: {}, email: {} });
        self.isEmailAddressNotAvailable = ko.observable(false);
        self.hasEmailChangedAfterError = ko.observable(true);
        self.emailAddressCopy = ko.observable('').extend({ required: {}, email: {} });
        self.isEmailAddressCopyNotAvailable = ko.observable(false);
        self.isEmailIdNotMatch = ko.observable(false);
        self.isEditEmailAddressSubmitButtonEnabled = ko.observable(false);
        self.isEditEmailAddressSubmitButtonBusy = ko.observable(false);
        self.credential = ko.observable(null);
        self.currentPassword = ko.observable().extend({ required: {} });
        self.isEmailAddressValidated = ko.observable(false);
        self.isExternalLogin = ko.observable(false);
        self.emailAddress.subscribe(function (value) {
            self.isEmailAddressNotAvailable(false);
            self.isEmailAddressValidated(self.validateEmailAddresses());
            if (!self.isExternalLogin()) {
                self.isEditEmailAddressSubmitButtonEnabled(self.validateEmailAddresses() && (self.currentPassword() != undefined && self.currentPassword() != '' && self.currentPassword() != null));
            }
            else {
                self.isEditEmailAddressSubmitButtonEnabled(self.validateEmailAddresses())
            }
        });

        self.emailAddressCopy.subscribe(function (value) {
            self.isEmailAddressCopyNotAvailable(false);
            self.isEmailAddressValidated(self.validateEmailAddresses());
            if (!self.isExternalLogin()) {
                self.isEditEmailAddressSubmitButtonEnabled(self.validateEmailAddresses() && (self.currentPassword() != undefined && self.currentPassword() != '' && self.currentPassword() != null));
            }
            else {
                self.isEditEmailAddressSubmitButtonEnabled(self.validateEmailAddresses())
            }
        });
        self.currentPassword.subscribe(function (value) {
            if (!self.isExternalLogin()) {
                self.isEmailAddressValidated(self.validateEmailAddresses());
                self.isEditEmailAddressSubmitButtonEnabled(self.validateEmailAddresses() && self.validateCurrentPassword());
            }
        });

        self.isEditEmailAddressSubmitButtonEnabled.subscribe(function (value) {
            self.isEditEmailAddressSubmitButtonBusy(false);
        });
        self.outOfEmailBlock = function () {
            setTimeout(function () {
                self.emailAddress.validate();
            }, 0);
            if (self.emailAddress() == "") {
                self.emailAddress.validationMessage('Error: This field is required');
                self.emailAddress.hasError(true);
                self.emailAddress.isValidationMessageVisible(true);
            }
        };
        var validationAnnounced = false;

        self.checkEmailCopyFocus = function () {
            validationAnnounced = false;
            if (self.emailAddressCopy() != "" && self.emailAddress() != self.emailAddressCopy()) {
                $("#aria-live-message-container").text('');
                setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Email ID does not match', $("#aria-live-message-container"), false); }, 300);
                self.isEmailIdNotMatch(true);
            }
        }
        self.checkEmailCopy = function () {
            setTimeout(function () {
                self.emailAddressCopy.validate();
            }, 0);
            if (self.emailAddressCopy() != "" && self.emailAddress() != self.emailAddressCopy()) {
                if (!validationAnnounced) {
                    gJobs.screenReadersService.setAriaLiveNotification('Email ID does not match');
                    validationAnnounced = true;
                }
                self.emailAddressCopy.validationMessage('Email ID does not match');
                self.emailAddressCopy.hasError(true);
                self.emailAddressCopy.isValidationMessageVisible(true);
                self.isEmailIdNotMatch(true);
            }
            return true;
        }
        self.checkEmailCopyFocusOut = function () {
            validationAnnounced = false;
            self.isEmailIdNotMatch(false);
            setTimeout(function () {
                self.emailAddressCopy.validate();
            }, 0);
            if (self.emailAddressCopy() == "") {
                self.emailAddressCopy.validationMessage('Error: This field is required');
                self.emailAddressCopy.hasError(true);
                self.emailAddressCopy.isValidationMessageVisible(true);
            }
            else if (self.emailAddressCopy() != "" && self.emailAddress() != self.emailAddressCopy()) {
                var emailRegEx = /^['_a-zA-Z0-9-+]+(\.['_a-zA-Z0-9-+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([a-zA-Z]+))$/;
                if (emailRegEx.test(self.emailAddressCopy())) {
                    self.isEmailIdNotMatch(true);
                    //self.emailAddressCopy.validationMessage('Email ID does not match');
                    //self.emailAddressCopy.hasError(true);
                    //self.emailAddressCopy.isValidationMessageVisible(true);
                }
            }
        }

        //Commenting this code temporarily For ONLINE-13234
        self.confirmEmailAddress = function () {
            self.isEditEmailAddressSubmitButtonBusy(true);

            if (!self.validateEmailAddresses()) {
                if (self.emailAddress() !== self.emailAddressCopy()) {
                    self.isEmailAddressCopyNotAvailable(true);
                }

                self.isEditEmailAddressSubmitButtonEnabled(false);
            } else {
                var isEmailAllowedRequestData = {
                    email: self.emailAddress(),
                    credential: self.credential(),
                    captchaAnswer: null,
                    password: self.currentPassword()
                };

                OnlineApp.Services.authenticationService
                    .isEmailAllowed(isEmailAllowedRequestData)
                    .then(
                        function (data) {
                            if (data.success) {
                                self.emailAddress.hasError(!data.isEmailAllowed);
                                self.isEmailAddressNotAvailable(!data.isEmailAllowed);
                                self.isEditEmailAddressSubmitButtonEnabled(data.isEmailAllowed);

                                if (data.isEmailAllowed) {
                                    OnlineApp.Services.emailVerificationService
                                        .updateEmailAddressByCredential(self.credential(), self.emailAddress())
                                        .then(
                                            function (response) {
                                                var options = { emailAddress: self.emailAddress() };

                                                self.resetEmailAddressElements();

                                                $(document).trigger(OnlineApp.Events.CommonEventsNames.ConfirmEditEmailAddress, options);

                                                $(editEmailLinkSelector).focus();
                                                gJobs.screenReadersService.setAriaLiveNotification('Edited email successfully ');

                                            },
                                            function (xhr) {
                                                if (xhr.status === 403 && xhr.statusText === SESSION_EXPIRED_REASON) {
                                                    toastr.error(Resources.NotificationMessages.SessionExpired);
                                                    gJobs.screenReadersService.setAriaLiveNotification(Resources.NotificationMessages.SessionExpired);
                                                    self.isEditEmailAddressSubmitButtonBusy(false);
                                                } else {
                                                    toastr.warning(Resources.NotificationMessages.ServiceUnavailable);
                                                    self.isEditEmailAddressSubmitButtonBusy(false);
                                                }
                                            }
                                        );
                                }
                                else {
                                    self.emailAddress.validationMessage('Email address not available!');
                                    self.emailAddress.hasError(true);
                                    self.emailAddress.isValidationMessageVisible(true);
                                    $('#edit-email-address-input-field').focus();
                                }
                            } else {
                                if (data.errorPropertyName == 'Password') {
                                    self.currentPassword.validationMessage(data.errorMessage);
                                    self.currentPassword.hasError(true);
                                    self.currentPassword.isValidationMessageVisible(true);
                                    self.isEditEmailAddressSubmitButtonBusy(false);
                                    $('#currentPassword').focus();
                                }
                                else {
                                    toastr.warning(Resources.NotificationMessages.ServiceUnavailable);
                                }
                            }
                        },
                        function (xhr) {
                            if (xhr.status === 403 && xhr.statusText === SESSION_EXPIRED_REASON) {
                                toastr.error(Resources.NotificationMessages.SessionExpired);
                                gJobs.screenReadersService.setAriaLiveNotification(Resources.NotificationMessages.SessionExpired);
                                self.isEditEmailAddressSubmitButtonBusy(false);
                            } else {
                                toastr.warning(Resources.NotificationMessages.ServiceUnavailable);
                                self.isEditEmailAddressSubmitButtonBusy(false);
                            }
                        }
                    );
            }
        };

        self.cancelEditEmailAddress = function () {

            self.resetEmailAddressElements();

            $(document).trigger(OnlineApp.Events.CommonEventsNames.CancelEditEmailAddress);
            $(editEmailLinkSelector).focus();
            gJobs.screenReadersService.setAriaLiveNotification('Current email is not changed');
        };

        self.validateEmailAddresses = function () {
            return self.emailAddress.validate() && self.emailAddress() === self.emailAddressCopy();
        };

        self.validateCurrentPassword = function () {
            return self.currentPassword.validate();
        }

        self.resetEmailAddressElements = function () {
            self.emailAddress('');
            self.emailAddressCopy('');
            self.currentPassword('');
            self.isEmailAddressNotAvailable(false);
            self.isEmailAddressCopyNotAvailable(false);
            self.isEmailIdNotMatch(false);
            self.isEditEmailAddressSubmitButtonEnabled(false);
            updateFieldErrorState(self.emailAddress);
            updateFieldErrorState(self.currentPassword);
        };

        function updateFieldErrorState(field, hasError, errorMessage) {
            field.hasError(hasError);
            field.isValidationMessageVisible(hasError);

            if (hasError && errorMessage) {
                field.validationMessage(errorMessage);
            }
        }

        $(document).ready(function () {
            var isExternal = $(verifyAccountDataContainerSelector).attr(dataVerifyAccountExternalLoginAttribute) == 'true' ? true : false
            self.isExternalLogin(isExternal);
        })
    }

    OnlineApp.Namespace.extend('gJobs.ViewModels', {
        EditEmailAddressViewModel: EditEmailAddressViewModel
    });

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

    function VerifyIdentityViewModel() {
        var RESEND_VERIFICATION_CODE_ATTEMPTS_COUNT_WITHOUT_CAPTCHA = window.twoStepVerificationResendAttempts;
        var VERIFICATION_ATTEMPTS_COUNT_WITHOUT_CAPTCHA = window.twoStepVerificationVerifyAttempts;
        var KEY_FOR_TEXT_VERIFICATION_CODE_CAPTHA_ANSWER = "VerifyTwoStepVerificationCodeAnswer";
        var KEY_FOR_TEXT_RESEND_VERIFICATION_CODE_CAPTCHA_ANSWER = "ResendTwoStepVerificationCodeAnswer";
        var CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFICATION_CODE = "captcha-user-answer-for-verify-code";
        var CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE = "captcha-user-answer-for-resend-code";
        var CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE = "<span>Please answer the question to <strong>verify</strong> a code again</span>";
        var CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE = "<span>Please answer the question to <b>resend</b> a code again</span>";

        var wasVerificationCodeValueInitiaded = false;

        var verificationCodeContainerId = "verify-identity-code-container";
        var verificationCodeContainerSelector = "#" + verificationCodeContainerId;
        var rememberThisDeviceCheckboxSelector = "#remember-this-device-checkbox";
        var rememberThisDeviceLabelContainerSelector = "#remember-this-device-label-container";
        var rememberThisDeviceCheckableItemSelector = ".checkable-item";
        var verificationCodeCaptchaSelector = "#" + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFICATION_CODE;
        var credentialSelector = "#verify-identity-credential";

        var $verificationCodeContainer;
        var $rememberThisDeviceCheckbox;
        var $rememberThisDeviceCheckableItem;
        var $rememberThisDeviceLabelContainer;
        var $lastFocusableElement;
        var $verificationCodeInputs;

        var credential;

        var accountVerificationHelper = gJobs.Helpers.accountVerificationHelper;

        var self = this;
        self.isCareerPageHeadingStyle = ko.observable(false);
        function unsetField (field, hasError) {
            field("");
            
            self.accountVerificationViewModel.updateFieldErrorState(
                field,
                hasError,
                field.validationMessage()
            );
        }

        function onVerificationCodeValuesChange (newValue, index) {
                var digits = newValue.replace(/[^A-Za-z0-9]/g,'').split(""); // replace all non-alphanumeric characters with nothing

                if (digits.length) {
                    var lastIndexForIterate = index + digits.length > 6 ? 6 : index + digits.length;
                    
                    for (var i = index; i < lastIndexForIterate; i++) {
                        self.verificationCodeValues[i](digits.shift());
                    }

                    wasVerificationCodeValueInitiaded = true;
                } else {
                    unsetField(
                        self.verificationCodeValues[index], 
                        wasVerificationCodeValueInitiaded
                    );
                }

            if (newValue == '') {
                var textid = 'txt' + (index + 1 - 1).toString();
                if (document.getElementById(textid)) {
                    document.getElementById(textid).focus();
                }
            }
            else {
                if (newValue.length == 1) {
                    var textid = 'txt' + (index + 1 + 1).toString();
                    if (document.getElementById(textid)) {
                        document.getElementById(textid).focus()
                    }
                }
            }
           


            self.isNeedToDisplayErrorMessage(false);
        }
       
        function initVerificationCodeValues () {
            var verificationCodeValues = [];

            for (var i = 0; i < 6; i++) {
                verificationCodeValues.push(
                    ko.observable('').extend({required: {}, number: {}})
                );
            }

            return verificationCodeValues;
        }

        function subscribeVerificationCodeValues(verificationCodeValues) {
            verificationCodeValues.forEach(function(observableItem, index) {
                observableItem.subscribe(function (newValue) { onVerificationCodeValuesChange(newValue, index) });
            });
        }

        self.accountVerificationViewModel = new gJobs.ViewModels.AccountVerificationViewModel(
            {
                keyForTextCaptchaAnswer: KEY_FOR_TEXT_VERIFICATION_CODE_CAPTHA_ANSWER,
                captchaUserAnswerInputId: CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFICATION_CODE,
                captchaLabelHtmlContent: CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                attemptsCountWithoutCaptcha: VERIFICATION_ATTEMPTS_COUNT_WITHOUT_CAPTCHA


            },
            {
                keyForTextCaptchaAnswer: KEY_FOR_TEXT_RESEND_VERIFICATION_CODE_CAPTCHA_ANSWER,
                captchaUserAnswerInputId: CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE,
                captchaLabelHtmlContent: CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                attemptsCountWithoutCaptcha: RESEND_VERIFICATION_CODE_ATTEMPTS_COUNT_WITHOUT_CAPTCHA
            }
        );

        self.textCaptchaEnabled = window.textCaptcha;
        self.verificationCodeAttemptsCount = ko.observable(0);
        self.resendVerificationCodeAttemptsCount = ko.observable(0);
        self.isNeedToDisplayErrorMessage = ko.observable(false);
        self.errorMessage = ko.observable("");
        self.verificationCodeValues = initVerificationCodeValues();
        self.shouldRememberThisDevice = ko.observable(false);
        self.userEmailAddress = ko.observable("");
        self.isVerificationCodeInProcess = ko.observable(false);
        self.isUserInfoLoaded = ko.observable(false);
        self.verificationCodeServerErrorMessage = ko.observable("");

        subscribeVerificationCodeValues(self.verificationCodeValues);

        self.verificationCode = ko.computed({
            read: function () {
                var verificationCode = "";

                self.verificationCodeValues.forEach(function (value) {
                    verificationCode += value();
                });

                return verificationCode;
            }
        }).extend({
            verificationCode: { 
                validationMessage: OnlineApp.Validation.validationMessages.invalidTwoStepVerificationCode
            } 
        });

        self.init = function () {
            return gJobs.Services.verifyIdentityService.getUserData(credential);
        };

        

        $(document).ready(function () {
            self.onReady();
            
        });

        self.onReady = function () {
            var link = window.location.href;
            if (link.indexOf("/careers/") !== -1) {
                self.isCareerPageHeadingStyle = ko.observable(true);
            }

            credential = $(credentialSelector).attr("data-verify-identity-credential");

            $("#content").css('position', 'static');

            $verificationCodeContainer = $(verificationCodeContainerSelector);
            $verificationCodeInputs = $verificationCodeContainer.find("input");
            $rememberThisDeviceCheckbox = $(rememberThisDeviceCheckboxSelector);
            $rememberThisDeviceLabelContainer = $(rememberThisDeviceLabelContainerSelector);
            $rememberThisDeviceCheckableItem = $rememberThisDeviceLabelContainer.find(rememberThisDeviceCheckableItemSelector);

            $($verificationCodeInputs).on('blur', function (e) {
                if ($(e.relatedTarget).parents(verificationCodeContainerSelector).length === 0) {
                    if (wasVerificationCodeValueInitiaded && !self.verificationCode.validate()) {
                        self.isNeedToDisplayErrorMessage(true);
                    }
                }
            });

            $rememberThisDeviceLabelContainer.on('mousedown', function () {
                setTimeout(function () {
                    $rememberThisDeviceCheckbox.focus();
                });
            });

            $rememberThisDeviceCheckbox.on('focus', function () {
                $rememberThisDeviceCheckableItem.addClass('focus');
            });

            $rememberThisDeviceCheckbox.on('focusout', function () {
                $rememberThisDeviceCheckableItem.removeClass('focus');
            });

            $verificationCodeInputs.autotab('alphanumeric');

            self.init().then(function (data) {
                if (data) {
                    self.verificationCodeAttemptsCount(data.verificationAttempts);
                    self.resendVerificationCodeAttemptsCount(data.resendAttempts);
                    self.userEmailAddress(data.email);

                    if (self.isNeedToShowVerificationCodeCaptcha()) {
                        self.accountVerificationViewModel.resetVerificationCodeCaptcha();
                    }

                    if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                        self.accountVerificationViewModel.resetResendVerificationCodeCaptcha();
                    }

                    self.isUserInfoLoaded(true);

                    $verificationCodeInputs.first().focus();
                    
                }
            });
            
        };

        self.isNeedToMarkVerificationCodeDigitWithError = function (verificationCodeDigitIndex) {
            return self.verificationCodeValues[verificationCodeDigitIndex].hasError()
                || self.isNeedToDisplayErrorMessage();
        };

        self.isNeedToShowCaptchasContainer = function () {
            return self.isNeedToShowVerificationCodeCaptcha() 
                || self.isNeedToShowResendVerificationCodeCaptcha();
        }

        self.isNeedToShowVerificationCodeCaptcha = function () {
            return self.textCaptchaEnabled 
                && self.accountVerificationViewModel.isNeedToShowVerificationCodeCaptcha(self.verificationCodeAttemptsCount());
        };

        self.isNeedToShowResendVerificationCodeCaptcha = function () {
            return self.textCaptchaEnabled
                && self.accountVerificationViewModel.isNeedToShowResendVerificationCodeCaptcha(self.resendVerificationCodeAttemptsCount());
        };

        self.getHomePageUrl = function() {
            var homePageUrl = "/";

            if (AgencyPages && AgencyPages.pageInfoService) {
                homePageUrl = AgencyPages.pageInfoService.getCurrentAgencyHomePath();
            }

            return homePageUrl;
        };

        self.verifyCode = function () {
            $('#colr').attr('style', ' background-color:#267a90');
            self.isVerificationCodeInProcess(true);

            if (self.isNeedToShowVerificationCodeCaptcha()) {
                if (!self.accountVerificationViewModel.textCaptchaViewModelForVerificationCode.validate()) {
                    var captchaSelector = self.accountVerificationViewModel.getVerificationCodeCaptchaSelector();
                    $(captchaSelector).focus();
                    self.isVerificationCodeInProcess(false);
                    return;
                };
            }  

            gJobs.Services.verifyIdentityService.verifyCode(
                self.verificationCode(),
                self.shouldRememberThisDevice(),
                self.accountVerificationViewModel.textCaptchaViewModelForVerificationCode.userAnswer(),
                credential
            ).then(function (data) {
                if (data) {
                    if (data.isVerificationSucceeded) {
                        var $announcementContainer = $(".verify-identity-form-container");
                        OnlineApp.Helpers.layoutHelper.tabbing.updateIndices($announcementContainer);

                        gJobs.screenReadersService.setNotification($announcementContainer.find('.sr-notification'), 'Identity verified, redirecting to home page', null, true);

                        var postBackUrl = sessionStorage.getItem(OnlineApp.SessionKeys.PostBackUrl);
                        sessionStorage.removeItem(OnlineApp.SessionKeys.PostBackUrl);

                        var postBackUrlLower = postBackUrl.toLowerCase();
                        

                        if (!postBackUrl || postBackUrlLower.includes("verifyidentity", postBackUrlLower)) {
                            postBackUrl = self.getHomePageUrl();
                        }
                        if (data.isVettedSite) {
                            postBackUrl = data.vettedPostUrl;
                        }
                        sessionStorage.setItem(OnlineApp.SessionKeys.IsVerifyIdentityVerificationCodeVerified, "true");

                        if (sessionStorage.getItem(OnlineApp.LocalStorageKeys.RedirectToShowJobAlertPopup) === "true") {
                            sessionStorage.setItem(OnlineApp.LocalStorageKeys.ShowJobAlertPopup, "true");
                        }
                        setTimeout(() => window.location.href = postBackUrl, 1000);
                    } else {
                        var isCaptchaInvalid = false;

                        var newVerificationAttemptsCount = self.verificationCodeAttemptsCount() + 1;
                        self.verificationCodeAttemptsCount(newVerificationAttemptsCount);

                        if (data.errorFieldName === "captcha") {
                            isCaptchaInvalid = true;

                            self.accountVerificationViewModel.updateFieldErrorState(
                                self.accountVerificationViewModel.textCaptchaViewModelForVerificationCode.userAnswer,
                                true
                            );

                            self.isVerificationCodeInProcess(false);
                        } else {
                            self.isNeedToDisplayErrorMessage(true);
                            self.verificationCodeServerErrorMessage(data.errorMessage);

                            self.accountVerificationViewModel.updateFieldErrorState(
                                self.verificationCode,
                                true,
                                data.errorMessage
                            );

                            self.isVerificationCodeInProcess(false);
                            $verificationCodeInputs.first().focus();
                            $('#txt1').focus(); 
                        }

                        if (self.isNeedToShowVerificationCodeCaptcha()) {
                            self.accountVerificationViewModel.resetVerificationCodeCaptchaWithTryingFocusing(
                                null,
                                true,
                                isCaptchaInvalid,
                                data.updatedCaptcha
                            );
                        }
                        
                    }
                }
            });
        };

        self.resendVerificationCode = function () {
            if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                if (!self.accountVerificationViewModel.textCaptchaViewModelForResendCode.validate()) {
                    var captchaSelector = self.accountVerificationViewModel.getResendVerificationCodeCaptchaSelector();
                    $(captchaSelector).focus();
                    return;
                }
            }

            gJobs.Services.verifyIdentityService.resendVerificationCode(
                credential,
                self.accountVerificationViewModel.textCaptchaViewModelForResendCode.userAnswer()
            ).then(function(data) {
                var isCaptchaInvalid = false;

                var newResendVerificationCount = data.resendAttempts;
                self.resendVerificationCodeAttemptsCount(newResendVerificationCount);

                if (data.isResendSucceeded === false) {
                    if (data.isCaptchaInvalid === true) {
                        isCaptchaInvalid = true;
                        self.accountVerificationViewModel.updateFieldErrorState(
                            self.accountVerificationViewModel.textCaptchaViewModelForResendCode.userAnswer,
                            true, 
                            OnlineApp.Validation.validationMessages.captchaInvalidMessage
                        );
                    }
                } else {
                    accountVerificationHelper.showResendCodeSuccessNotification();
                }

                if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                    self.accountVerificationViewModel.resetResendVerificationCodeCaptchaWithTryingFocusing(
                        null,
                        true,
                        isCaptchaInvalid,
                        data.updatedCaptcha
                    );
                }
            });
        };

        OnlineApp.Services.authenticationService.isLoggedIn().done(function(isLoggedIn) {
            if (isLoggedIn) {
                window.location.href = self.getHomePageUrl();
            }
        });

        $(window).focus(function () {
            if (self.isNeedToShowVerificationCodeCaptcha()) {
                
                    self.accountVerificationViewModel.resetVerificationCodeCaptchaWithTryingFocusing(
                        $lastFocusableElement,
                        true
                    );
                
            };
            // commenting this one - not sure why we need to refresh this on focus as it is triggered by action - self.resendVerificationCode
            //if (self.isNeedToShowResendVerificationCodeCaptcha()) {
            //    self.accountVerificationViewModel.resetResendVerificationCodeCaptchaWithTryingFocusing(
            //        $lastFocusableElement,
            //        true
            //    );
            //}
        });

        $(window).blur(function () {
            $lastFocusableElement = $(document.activeElement);
        });

        var loginEvents = OnlineApp.Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;

        $(document)
            .on(loginEvents, function(event) {
                window.location.href = self.getHomePageUrl();
            });
    }

    OnlineApp.Namespace.extend('gJobs.ViewModels', {
        VerifyIdentityViewModel: VerifyIdentityViewModel
    });

})(window);

function keydown(event) {
    if (event.keyCode == $.ui.keyCode.BACKSPACE) {

        $('#colr').removeAttr('style');
        
        var id = event.target.id;
        if (id == 'txt2') {
            if (document.getElementById('txt2').value == '') {
                document.getElementById('txt1').focus();
                document.getElementById('txt1').value = '';
            }
            
        }
         else if (id == 'txt3') {
            if (document.getElementById('txt3').value == '') {
                document.getElementById('txt2').focus();
                document.getElementById('txt2').value = '';
            }
            
        }
         else if (id == 'txt4') {
            if (document.getElementById('txt4').value == '') {
                document.getElementById('txt3').focus();
                document.getElementById('txt3').value = '';
            }
           
        }

        else if (id == 'txt5') {
            if (document.getElementById('txt5').value == '') {
                document.getElementById('txt4').focus();
                document.getElementById('txt4').value = '';
            }
            
        }
        else if (id == 'txt6') {
            if (document.getElementById('txt6').value == '') {
                document.getElementById('txt5').focus();
                document.getElementById('txt5').value = '';
            }
            
        }
    }
}
;
(function (window, undefined) {
    'use strict';

    function AccountVerificationViewModel(verificationCodeInfo, resendVerificationCodeInfo) {
        verificationCodeInfo = verificationCodeInfo ? verificationCodeInfo : {};
        resendVerificationCodeInfo = resendVerificationCodeInfo ? resendVerificationCodeInfo : {};
        
        var CAPTCHA_INVALID_MESSAGE = "Captcha is invalid";
        var captchaUserAnswerInputIdForVerifyCode = verificationCodeInfo.captchaUserAnswerInputId;
        var captchaUserAnswerInptutIdForResendCode = resendVerificationCodeInfo.captchaUserAnswerInputId;
        var captchaLabelHtmlContentForResendCode = resendVerificationCodeInfo.captchaLabelHtmlContent;
        var captchaLabelHtmlContentForVerificationCode = verificationCodeInfo.captchaLabelHtmlContent;
        var resendVerificationAttemptsCountWithoutCaptcha = resendVerificationCodeInfo.attemptsCountWithoutCaptcha;
        var verificationAttemptsCountWithoutCaptcha = verificationCodeInfo.attemptsCountWithoutCaptcha;
        var verificationCodeCaptchaSelector = "#" + captchaUserAnswerInputIdForVerifyCode;
        var resendVerificationCodeCaptchaSelector = "#" + captchaUserAnswerInptutIdForResendCode;

        var self = this;

        self.textCaptchaViewModelForVerificationCode = new OnlineApp.ViewModels.TextCaptchaViewModel(
            verificationCodeInfo.keyForTextCaptchaAnswer
        );
        self.textCaptchaViewModelForResendCode = new OnlineApp.ViewModels.TextCaptchaViewModel(
            resendVerificationCodeInfo.keyForTextCaptchaAnswer
        );

        self.getVerificationCodeCaptchaSelector = function () {
            return verificationCodeCaptchaSelector;
        }

        self.getResendVerificationCodeCaptchaSelector = function () {
            return resendVerificationCodeCaptchaSelector;
        }

        self.showSuccessNotification = function (htmlContent) {
            var successEmailNotificationEventName = "successEmailNotification";
            var successEmailNotificationSelector = "success-email-notification";
            var successEmailNotification = $('#' + successEmailNotificationSelector);

            if (successEmailNotification.length !== 0) {
                successEmailNotification.html(htmlContent);
                successEmailNotification.css("display", "flex");
            } else {
                $('body').append(
                    "<div class='uses-gjobs-styles'><div id='" + successEmailNotificationSelector + "'>" + htmlContent + "</div></div>"
                );

                successEmailNotification = $('#' + successEmailNotificationSelector);
            }

            gJobs.screenReadersService.setAriaLiveNotification(successEmailNotification.text());

            $(document).on('click.' + successEmailNotificationEventName, function () {
                if (successEmailNotification.is(":visible")) {
                    successEmailNotification.css("display", "none");
                }
            });

            setTimeout(function () {
                if (successEmailNotification.is(":visible")) {
                    successEmailNotification.css("display", "none");
                }

                $(document).off('click.' + successEmailNotificationEventName);
            }, 10000)
        };

        self.updateFieldErrorState = function (field, hasError, errorMessage) {
            field.hasError(hasError);
            field.isValidationMessageVisible(hasError);

            if (hasError && errorMessage) {
                field.validationMessage(errorMessage);
            }
        };

        self.resetCaptcha = function (textCaptchaViewModel, htmlContentForLabel, captchaUserAnswerId, updatedCaptchaQuestion) {
            textCaptchaViewModel.setCustomLabelHtmlContent(htmlContentForLabel);
            textCaptchaViewModel.setCustomUserAnswerInputId(captchaUserAnswerId);

            return textCaptchaViewModel.resetCaptcha(
                textCaptchaViewModel.userAnswer.hasError(),
                CAPTCHA_INVALID_MESSAGE,
                '',
                updatedCaptchaQuestion
            );
        };

        self.resetVerificationCodeCaptcha = function () {
            self.resetCaptcha(
                self.textCaptchaViewModelForVerificationCode, 
                captchaLabelHtmlContentForVerificationCode, 
                captchaUserAnswerInputIdForVerifyCode
            ); 
        };

        self.resetResendVerificationCodeCaptcha = function () {
            self.resetCaptcha(
                self.textCaptchaViewModelForResendCode, 
                captchaLabelHtmlContentForResendCode, 
                captchaUserAnswerInptutIdForResendCode
            );
        };

        self.isRefreshCaptchaQuestionLinkWasFocusedLast = function (lastFocusableElement, captchaUserAnswerInputId) {
            return lastFocusableElement
                && lastFocusableElement.hasClass('reset-captcha') 
                && lastFocusableElement.parents('.text-captcha-container').find("#" + captchaUserAnswerInputId).length;
        };

        self.resetCaptchaWithTryingFocusing = function (
            captchaViewModel, 
            captchaLabelHtmlContent, 
            captchaUserAnswerInputId, 
            lastFocusableElement,
            isVerificationContainerVisible,
            shouldFocusOnCaptcha,
            updatedCaptchaQuestion
        ) {
            if (self.resetCaptcha(
                captchaViewModel,
                captchaLabelHtmlContent,
                captchaUserAnswerInputId,
                updatedCaptchaQuestion
            )) {
                self.resetCaptcha(
                    captchaViewModel,
                    captchaLabelHtmlContent,
                    captchaUserAnswerInputId,
                    updatedCaptchaQuestion
                ).always(function () {
                    if (isVerificationContainerVisible) {
                        if (
                            shouldFocusOnCaptcha
                            || (lastFocusableElement && lastFocusableElement.attr('id') === captchaUserAnswerInputId)) {
                            $(verificationCodeCaptchaSelector).focus();
                        } else if (
                            self.isRefreshCaptchaQuestionLinkWasFocusedLast(lastFocusableElement, captchaUserAnswerInputId)
                        ) {
                            lastFocusableElement.focus();
                        }
                    }
                });
            }
        };

        self.resetVerificationCodeCaptchaWithTryingFocusing = function (
            lastFocusableElement, 
            isVerificationContainerVisible,
            shouldFocusOnCaptcha,
            updatedCaptchaQuestion
        ) {
            self.resetCaptchaWithTryingFocusing(
                self.textCaptchaViewModelForVerificationCode, 
                captchaLabelHtmlContentForVerificationCode, 
                captchaUserAnswerInputIdForVerifyCode, 
                lastFocusableElement,
                isVerificationContainerVisible,
                shouldFocusOnCaptcha,
                updatedCaptchaQuestion
            ); 
        };

        self.resetResendVerificationCodeCaptchaWithTryingFocusing = function (
            lastFocusableElement, 
            isVerificationContainerVisible,
            shouldFocusOnCaptcha,
            updatedCaptchaQuestion
        ) {
            self.resetCaptchaWithTryingFocusing(
                self.textCaptchaViewModelForResendCode, 
                captchaLabelHtmlContentForResendCode, 
                captchaUserAnswerInptutIdForResendCode, 
                lastFocusableElement,
                isVerificationContainerVisible,
                shouldFocusOnCaptcha,
                updatedCaptchaQuestion
            );
        };

        self.isNeedToShowVerificationCodeCaptcha = function (currentAttemptsCount) {
            return currentAttemptsCount > verificationAttemptsCountWithoutCaptcha;
        };

        self.isNeedToShowResendVerificationCodeCaptcha = function (currentAttemptsCount) {
            return currentAttemptsCount >= resendVerificationAttemptsCountWithoutCaptcha;
        };

    }

    OnlineApp.Namespace.extend('gJobs.ViewModels', {
        AccountVerificationViewModel: AccountVerificationViewModel
    });

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


    function VerifyAccountViewModel() {

        var self = this,
            resendEmailVerificationAttemptsCountWithoutCaptcha = window.emailVerificationResendAttempts,
            keyForTextResendEmailVerificationCaptchaAnswer = "ResendEmailVerificationCodeAnswer",
            captchaUserAnswerInputIdForResendEmailVerification = "captcha-user-answer-for-resend-code",
            captchaLabelHtmlContentForResendEmailVerification = "<span>Please answer the question to <b>resend</b> a link again</span>",
            verifyAccountDataContainerSelector = "#verify-account-data-container",
            dataVerifyAccountCredentialAttribute = "data-verify-account-credential",
            dataVerifyAccountEmailAttribute = "data-verify-account-email",
            dataVerifyAccountResendAttemptsAttribute = "data-verify-account-resend-attempts",
            dataVerifyAccountChangedEmailAddressWasAdded = "data-verify-account-changed-email-address-was-added",
            dataVerifyAccountIsOjrMasterAttribute = "data-verify-account-is-ojr-master",
            dataVerifyAccountIsGoogleSignIn = "data-verify-account-google-login",
            $lastFocusableElement,
            credential;

        var accountVerificationHelper = gJobs.Helpers.accountVerificationHelper;

        self.accountVerificationViewModel = new gJobs.ViewModels.AccountVerificationViewModel(
            null,
            {
                keyForTextCaptchaAnswer: keyForTextResendEmailVerificationCaptchaAnswer,
                captchaUserAnswerInputId: captchaUserAnswerInputIdForResendEmailVerification,
                captchaLabelHtmlContent: captchaLabelHtmlContentForResendEmailVerification,
                attemptsCountWithoutCaptcha: resendEmailVerificationAttemptsCountWithoutCaptcha
            }
        );

        self.textCaptchaEnabled = window.textCaptcha;
        self.resendVerificationEmailAttemptsCount = ko.observable(0);
        
        self.userEmailAddress = ko.observable("");
        self.isUserInfoLoaded = ko.observable(false);
        self.isCareerPageHeadingStyle = ko.observable(false);
        self.changedEmailAddressWasAdded = ko.observable(false);
        self.isOjrMaster = ko.observable(false);
        self.isGoogleSignIn = ko.observable(false);

        self.isEditEmailAddressModeActive = ko.observable(false);
        self.editEmailAddressViewModel = new gJobs.ViewModels.EditEmailAddressViewModel();

        $(document).ready(function () {
            self.onReady();
        });

        self.onReady = function() {
            if (self.isUserInfoLoaded()) return;

            var link = window.location.href;
            if (link.indexOf("/careers/") !== -1) {
                self.isCareerPageHeadingStyle = ko.observable(true);
            }

            credential = $(verifyAccountDataContainerSelector).attr(dataVerifyAccountCredentialAttribute);
            self.editEmailAddressViewModel.credential(credential);
           
            self.userEmailAddress($(verifyAccountDataContainerSelector).attr(dataVerifyAccountEmailAttribute));
            self.resendVerificationEmailAttemptsCount($(verifyAccountDataContainerSelector).attr(dataVerifyAccountResendAttemptsAttribute));
            self.changedEmailAddressWasAdded($(verifyAccountDataContainerSelector).attr(dataVerifyAccountChangedEmailAddressWasAdded));
            self.isOjrMaster($(verifyAccountDataContainerSelector).attr(dataVerifyAccountIsOjrMasterAttribute));
            self.isGoogleSignIn($(verifyAccountDataContainerSelector).attr(dataVerifyAccountIsGoogleSignIn));
            if (self.isNeedToShowResendVerificationEmailCaptcha()) {
                self.accountVerificationViewModel.resetResendVerificationCodeCaptcha();
            }

            self.isUserInfoLoaded(true);
        };

        self.shouldHideEditEmailAddressLink = function () {
            if (window.window.enableGoogleSSO) {
                return (self.isGoogleSignIn() === true || self.isGoogleSignIn() === 'true') || (self.isOjrMaster() === true || self.isOjrMaster() === 'true') ;
            }
            return self.isOjrMaster() === true || self.isOjrMaster() === 'true';
        };

        self.isNeedToShowCaptchasContainer = function() {
            return self.isNeedToShowResendVerificationEmailCaptcha();
        };

        self.isNeedToShowResendVerificationEmailCaptcha = function() {
            return self.textCaptchaEnabled
                && self.accountVerificationViewModel.isNeedToShowResendVerificationCodeCaptcha(self.resendVerificationEmailAttemptsCount());
        };

        self.getHomePageUrl = function() {
            var homePageUrl = "/";

            if (AgencyPages && AgencyPages.pageInfoService) {
                homePageUrl = AgencyPages.pageInfoService.getCurrentAgencyHomePath();
            }

            return homePageUrl;
        };

        self.resendVerificationLink = function() {
            if (self.isNeedToShowResendVerificationEmailCaptcha()) {
                if (!self.accountVerificationViewModel.textCaptchaViewModelForResendCode.validate()) {
                    var captchaSelector = self.accountVerificationViewModel.getResendVerificationCodeCaptchaSelector();
                    $(captchaSelector).focus();
                    return;
                }
            }

            gJobs.Services.verifyAccountService.resendVerificationLink(
                credential,
                self.accountVerificationViewModel.textCaptchaViewModelForResendCode.userAnswer(),
                self.changedEmailAddressWasAdded(),
                self.isOjrMaster()
            ).then(function(response) {
                var data = response.data;

                if (!data) {
                    accountVerificationHelper.showVerificationLinkSendFailNotification();
                    return;
                }

                var isCaptchaInvalid = false;

                self.resendVerificationEmailAttemptsCount(data.resendAttempts);

                if (data.isResendSucceeded === false) {
                    if (data.isCaptchaInvalid === true) {
                        isCaptchaInvalid = true;
                        self.accountVerificationViewModel.updateFieldErrorState(
                            self.accountVerificationViewModel.textCaptchaViewModelForResendCode.userAnswer,
                            true,
                            OnlineApp.Validation.validationMessages.captchaInvalidMessage
                        );
                    }
                } else {
                    accountVerificationHelper.showVerificationLinkSendSuccessNotification();
                }

                if (self.isNeedToShowResendVerificationEmailCaptcha()) {
                    self.accountVerificationViewModel.resetResendVerificationCodeCaptchaWithTryingFocusing(
                        null,
                        true,
                        isCaptchaInvalid,
                        data.updatedCaptcha
                    );
                }
            });
        };

        self.showEditEmailAddressPage = function () {
            $("#skip-to-content-button").focus();
            self.isEditEmailAddressModeActive(true);
            gJobs.screenReadersService.setAriaLiveNotification('Edit Email page has been loaded');
        };

        $(window).blur(function() {
            $lastFocusableElement = $(document.activeElement);
        });

        
        var loginEvents = OnlineApp.Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;
        
        var editEmailAddressEvents = OnlineApp.Events.CommonEventsNames.CancelEditEmailAddress + ' ' + OnlineApp.Events.CommonEventsNames.ConfirmEditEmailAddress;

        $(document)
            .on(loginEvents, function (event) {
            
                window.location.href = self.getHomePageUrl();
            })
            .on(editEmailAddressEvents, function (event, data) {
                
                if (data && data.emailAddress) {
                   var emailAddress= getMsakedEmail(data.emailAddress)
                    self.userEmailAddress(emailAddress);
                    self.changedEmailAddressWasAdded(true);
                }

                self.isEditEmailAddressModeActive(false);
            });

        function getMsakedEmail(myemailId) {

            
            var index = myemailId.lastIndexOf("@");
            var prefix = myemailId.substring(0, index);
            var postfix = myemailId.substring(index);

            var mask = prefix.split('').map(function (o, i) {
                if (i == 0 || i == (index - 1)) {
                    return o;
                } else {
                    return '*';
                }
            }).join('');

            var maskedid = mask + postfix;
            return maskedid;
        }

    }


    OnlineApp.Namespace.extend('gJobs.ViewModels', {
        VerifyAccountViewModel: VerifyAccountViewModel
    });

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

    function ExpiredVerificationLinkViewModel() {

        var self = this,
            resendEmailVerificationAttemptsCountWithoutCaptcha = window.emailVerificationResendAttempts,
            keyForTextResendEmailVerificationCaptchaAnswer = "ResendEmailVerificationCodeAnswer",
            captchaUserAnswerInputIdForResendEmailVerification = "captcha-user-answer-for-resend-code",
            captchaLabelHtmlContentForResendEmailVerification = "<span>Please answer the question to <b>resend</b> a link again</span>",
            expiredVerificationLinkDataContainerSelector = "#expired-verification-link-data-container",
            dataExpiredVerificationLinkCredentialAttribute = "data-expired-verification-link-credential",
            dataExpiredVerificationLinkResendAttemptsAttribute = "data-expired-verification-link-resend-attempts",
            dataExpiredVerificationLinkIsOjrMasterAttribute = "data-expired-verification-link-is-ojr-master",
            $lastFocusableElement,
            credential;

        var accountVerificationHelper = gJobs.Helpers.accountVerificationHelper;

        self.accountVerificationViewModel = new gJobs.ViewModels.AccountVerificationViewModel(
            null,
            {
                keyForTextCaptchaAnswer: keyForTextResendEmailVerificationCaptchaAnswer,
                captchaUserAnswerInputId: captchaUserAnswerInputIdForResendEmailVerification,
                captchaLabelHtmlContent: captchaLabelHtmlContentForResendEmailVerification,
                attemptsCountWithoutCaptcha: resendEmailVerificationAttemptsCountWithoutCaptcha
            }
        );

        self.textCaptchaEnabled = window.textCaptcha;
        self.resendVerificationEmailAttemptsCount = ko.observable(0);
        self.isUserInfoLoaded = ko.observable(false);
        self.isCareerPageHeadingStyle = ko.observable(false);
        self.isOjrMaster = ko.observable(false);

        $(document).ready(function () {
            self.onReady();
        });

        self.onReady = function() {
            if (self.isUserInfoLoaded()) return;

            var link = window.location.href;
            if (link.indexOf("/careers/") !== -1) {
                self.isCareerPageHeadingStyle = ko.observable(true);
            }

            credential = $(expiredVerificationLinkDataContainerSelector).attr(dataExpiredVerificationLinkCredentialAttribute);
            self.resendVerificationEmailAttemptsCount($(expiredVerificationLinkDataContainerSelector).attr(dataExpiredVerificationLinkResendAttemptsAttribute));
            self.isOjrMaster($(expiredVerificationLinkDataContainerSelector).attr(dataExpiredVerificationLinkIsOjrMasterAttribute));

            if (self.isNeedToShowResendVerificationEmailCaptcha()) {
                self.accountVerificationViewModel.resetResendVerificationCodeCaptcha();
            }

            self.isUserInfoLoaded(true);
        };

        self.isNeedToShowCaptchasContainer = function() {
            return self.isNeedToShowResendVerificationEmailCaptcha();
        };

        self.isNeedToShowResendVerificationEmailCaptcha = function() {
            return self.textCaptchaEnabled
                && self.accountVerificationViewModel.isNeedToShowResendVerificationCodeCaptcha(self.resendVerificationEmailAttemptsCount());
        };

        self.getHomePageUrl = function() {
            var homePageUrl = "/";

            if (AgencyPages && AgencyPages.pageInfoService) {
                homePageUrl = AgencyPages.pageInfoService.getCurrentAgencyHomePath();
            }

            return homePageUrl;
        };

        self.resendVerificationLink = function() {
            if (self.isNeedToShowResendVerificationEmailCaptcha()) {
                if (!self.accountVerificationViewModel.textCaptchaViewModelForResendCode.validate()) {
                    var captchaSelector = self.accountVerificationViewModel.getResendVerificationCodeCaptchaSelector();
                    $(captchaSelector).focus();
                    return;
                }
            }

            gJobs.Services.verifyAccountService.resendVerificationLink(
                credential,
                self.accountVerificationViewModel.textCaptchaViewModelForResendCode.userAnswer(),
                true,
                self.isOjrMaster()
            ).then(function(response) {
                var data = response.data;

                if (!data) {
                    accountVerificationHelper.showVerificationLinkSendFailNotification();
                    return;
                }

                var isCaptchaInvalid = false;

                self.resendVerificationEmailAttemptsCount(data.resendAttempts);

                if (data.isResendSucceeded === false) {
                    if (data.isCaptchaInvalid === true) {
                        isCaptchaInvalid = true;
                        self.accountVerificationViewModel.updateFieldErrorState(
                            self.accountVerificationViewModel.textCaptchaViewModelForResendCode.userAnswer,
                            true,
                            OnlineApp.Validation.validationMessages.captchaInvalidMessage
                        );
                    }
                } else {
                    window.location.href = data.forceRedirectUrl ? data.forceRedirectUrl : "/";
                }

                if (self.isNeedToShowResendVerificationEmailCaptcha()) {
                    self.accountVerificationViewModel.resetResendVerificationCodeCaptchaWithTryingFocusing(
                        null,
                        true,
                        isCaptchaInvalid
                    );
                }
            });
        };

        $(window).blur(function() {
            $lastFocusableElement = $(document.activeElement);
        });

        var loginEvents = OnlineApp.Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;

        $(document)
            .on(loginEvents, function(event) {
                window.location.href = self.getHomePageUrl();
            });
    }

    OnlineApp.Namespace.extend('gJobs.ViewModels', {
        ExpiredVerificationLinkViewModel: ExpiredVerificationLinkViewModel
    });

})(window);
;
ko.extenders.ignoreOnSerialization = function(target, value) {
    target.ignoreOnSerialization = value;
    return target;
};;
function canHaveProperties(unwrappedObservable) {
    return (typeof unwrappedObservable == "object") && (unwrappedObservable !== null) &&
        (unwrappedObservable !== undefined) && (!(unwrappedObservable instanceof Date)) &&
        (!(unwrappedObservable instanceof String)) && (!(unwrappedObservable instanceof Number)) &&
        (!(unwrappedObservable instanceof Boolean));
}

var visitModel = function (rootObject, isArrayElement) {
    if (!isArrayElement && ko.isObservable(rootObject) && rootObject.ignoreOnSerialization === true) {
        return undefined;
    }

    var unwrappedRootObject = ko.utils.unwrapObservable(rootObject);

    if (!canHaveProperties(unwrappedRootObject)) {
        return unwrappedRootObject;
    } else if (unwrappedRootObject.constructor === Array) {
        return unwrappedRootObject.map(function (o) { return visitModel(o, true); });
    } else {
        var result = {};
        for (var property in unwrappedRootObject) {
            if (ko.utils.unwrapObservable(unwrappedRootObject[property]) !== unwrappedRootObject) {
                var mappedValue = visitModel(unwrappedRootObject[property]);
                if (mappedValue !== undefined) {
                    result[property] = mappedValue;
                }
            }
        }
        return result;
    }
}


ko.toCleanJSON = function (rootObject) {
    // visit each view model property to ignore unnecessary properties
    var cleanRootObject = visitModel(rootObject);

    return ko.toJSON(cleanRootObject);
};;
// source: http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html

function toJSON(useCleanJSON, root) {
    return useCleanJSON ? ko.toCleanJSON(root) : ko.toJSON(root)
}

ko.dirtyFlag = function (root, isInitiallyDirty, useCleanJSON, deferEvaluation) {
    var initialState = toJSON(useCleanJSON, root),
        deferEvaluationValue = deferEvaluation === undefined ? true : deferEvaluation;

    var result = function () { },
        _initialState = ko.observable(initialState),
        _isInitiallyDirty = ko.observable(isInitiallyDirty);

    result.isDirty = ko.computed({
        read: function () {
            return _isInitiallyDirty() || _initialState() !== toJSON(useCleanJSON, root);
        },
        deferEvaluation: deferEvaluationValue
    });

    result.reset = function () {
        _initialState(toJSON(useCleanJSON, root));
        _isInitiallyDirty(false);
    };

    return result;
};;
// source: https://stackoverflow.com/a/18184016

ko.subscribable.fn.subscribeChanged = function (callback) {
    var oldValue;
    this.subscribe(function (_oldValue) {
        oldValue = _oldValue;
    }, this, 'beforeChange');

    this.subscribe(function (newValue) {
        callback(newValue, oldValue);
    });
};;
(function (window, undefined) {
    'use strict';
    
    var maxMobileScreenWidth = 767;

    ko.bindingHandlers.adjustSignInFormHeight = {
        init: function (element) {
            var $element = $(element);
            var $formSignIn = $(element).closest('.form-signin');

            //protect from incorrect using of the binding
            if ($formSignIn.length == 0) {
                return;
            }

            $element.onFirst('focusin', function (event) {
                if ($(window).width() < maxMobileScreenWidth) {
                    $formSignIn.css('margin-bottom', $(window).height() + 'px');
                }
            });

            $element.onFirst('focusout', function (event) {
                $formSignIn.css('margin-bottom', 'auto');
            });
        }
    };
})(window);;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.selectedOption = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var $element = $(element);
            var hasChanged = false;

            $element.change(function () {
                hasChanged = true;

                var allBindings = allBindingsAccessor();
                var valueId = $element.val();
                var options = ko.unwrap(allBindings.options || allBindings.isolatedOptions);
                var optionsValue = ko.unwrap(allBindings.optionsValue);

                var selectedOption = ko.utils.arrayFirst(options, function(item) {
                    return (ko.unwrap(item[optionsValue]) == valueId);
                });

                if (selectedOption === null) {
                    selectedOption = {};
                    selectedOption[optionsValue] = valueId;
                }

                var value = valueAccessor();

                if (typeof value.fromDataModel === 'function') {
                    value.fromDataModel(selectedOption);
                }
                else if (ko.isObservable(value)) {
                    var unwrappedValue = ko.unwrap(value),
                        isObject = jQuery.isPlainObject(unwrappedValue);

                    if (isObject) {
                        // Not implemented
                    }
                    else {
                        if (selectedOption != null && selectedOption != undefined) {
                            value(selectedOption[optionsValue]);
                        }
                    }
                }
                else {
                    $.extend(true, value, selectedOption);
                }
            });

            $element.parent().on('keydown', 'input', function (e) {
                var isEnter = e.keyCode === $.ui.keyCode.ENTER;
                var isTab = e.keyCode === $.ui.keyCode.TAB;
                if ((!e.shiftKey && isTab) || isEnter) {
                    var value = valueAccessor();

                    var allBindings = allBindingsAccessor();
                    var optionsValue = ko.unwrap(allBindings.optionsValue);
                    var optionsText = ko.unwrap(allBindings.optionsText);
                    var validators = value.validators || value[optionsValue].validators || [];

                    var selectedValue;
                    if (isEnter) {
                        // Chozen dropdown hasn't been closed yet. We should search actual value in the search results.
                        var options = ko.unwrap(allBindings.options || allBindings.isolatedOptions);
                        var selectedTextValue = $element.parent().find('.active-result.highlighted').text();

                        for (var i = 0; i < options.length; ++i) {
                            if (options[i][optionsText].toString() === selectedTextValue) {
                                selectedValue = options[i][optionsValue];
                                break;
                            }
                        }
                    } else {
                        // Chozen dropdown has been closed, so actual value is in the select element.
                        selectedValue = $element.val();
                    }
                }

                return true;
            });
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.checkedOption = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var $element = $(element);

            $element.change(function () {
                var allBindings = allBindingsAccessor();
                var valueId = $(':radio[name=' + $element.attr('name') + ']:checked').val();
                var options = ko.utils.unwrapObservable(allBindings.radioOptions);
                var optionsValue = ko.utils.unwrapObservable(allBindings.radioOptionsValue);

                var selectedOption = ko.utils.arrayFirst(options, function (item) {
                    return (ko.utils.unwrapObservable(item[optionsValue]) == valueId);
                });

                if (selectedOption === null) {
                    selectedOption = {};
                    selectedOption[optionsValue] = valueId;
                }

                var value = valueAccessor();

                if (typeof value.fromDataModel === 'function') {
                    value.fromDataModel(selectedOption);
                } else {
                    $.extend(true, value, selectedOption);
                }

            });
        },

        update: function (element, valueAccessor, allBindingsAccessor) {
            var value = valueAccessor();
            var allBindings = allBindingsAccessor();
            var optionsValue = ko.utils.unwrapObservable(allBindings.radioOptionsValue);

            var valueId = ko.utils.unwrapObservable(value[optionsValue]);

            var $element = $(element);
            var isChecked = ($element.val() == valueId);

            $element.prop('checked', isChecked);
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.optionValueId = {
        init: function (element, valueAccessor) {
            var $element = $(element);
            
            $element.change(function() {
                var valueId = $element.val();
                
                if (valueId === "")
                    valueId = null;

                valueAccessor()(valueId);
            });
        },

        update: function (element, valueAccessor) {
            var valueId = valueAccessor()();
            if (!valueId)
                valueId = "";

            $(element).val(valueId);
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.disableClick = {
        init: function (element, valueAccessor) {
            $(element).one('click', function (event) {
                var value = ko.utils.unwrapObservable(valueAccessor());
                if (value) {
                    event.preventDefault();
                    event.stopPropagation();
                    event.stopImmediatePropagation();
                }
            });
        },

        update: function (element, valueAccessor) {
            // apply disabled style if necessary
            var value = ko.utils.unwrapObservable(valueAccessor());
            ko.bindingHandlers.css.update(element, function() {
                 return { "disabled": value };
            });
            
            //added disabled attribute for IE
            if (value) {
                $(element).attr('disabled', 'disabled');
            } else {
                $(element).removeAttr('disabled');
            }
        }
    };
})();;
(function (window, undefined) {
    'use strict';
    
    ko.bindingHandlers.initialize = {
        init: function (element, valueAccessor) {
            valueAccessor()(element);
        },

        update: function (element, valueAccessor) {
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.placeholder = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var $element = $(element);

            var placeholderValue = valueAccessor();

            var placeholder = ko.utils.unwrapObservable(placeholderValue.text);

            $element.attr('placeholder', placeholder);

            if (placeholderValue.removeOnFocus) {
                $element.on('focus', function () {
                    $element.attr('placeholder', '');
                });
                $element.on('blur', function () {
                    setTimeout(function () { // Prevent reading placeholder by screenreaders
                        $element.attr('placeholder', placeholder);
                    });
                });
            }

            if ($.fn.placeholder) {
                $element.placeholder();
            }

            var excludeEdge = true;
            if (gJobs.browserDetector.isIE(excludeEdge)) {
                initFakePlaceholder($element, placeholder);
            }
        },

        update: function (element, valueAccessor, allBindingsAccessor) {
            var $element = $(element);
            if (!$element.is(':focus'))
                $element.triggerHandler('blur.placeholder');
        }
    };

    function initFakePlaceholder($element, placeholder) {

        var $placeholderFake = $('<span class="placeholder-ie"></span>');
        $placeholderFake.html(placeholder);

        $placeholderFake.hide();
        $element.closest('.field-container').append($placeholderFake);

        var isFocused = false;

        var addPlaceholder = function () {
            if ($placeholderFake !== undefined) {
                $placeholderFake.css({
                    'display': 'inline-block',
                    'left': 0
                });

                $placeholderFake.closest('.field-container').css({
                    'position': 'relative'
                });
            }
        };

        var removePlaceholder = function () {
            if ($placeholderFake !== undefined) {
                $placeholderFake.hide();
            }
        };

        $element.focus(function () {
            if ($element.val()) {
                return;
            }

            addPlaceholder();

            isFocused = true;
        });

        $element.blur(function () {
            removePlaceholder();

            isFocused = false;
        });

        $element.on('input', function () {

            if (isFocused) {
                if ($element.val()) {
                    removePlaceholder();
                } else {
                    addPlaceholder();
                }
            }
        });

        // Specially for IE 8
        $element.on('propertychange', function () {

            if (isFocused) {
                if ($element.val()) {
                    removePlaceholder();
                } else {
                    addPlaceholder();
                }
            }
        });
    }

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

    // solution of perfomance issues with options binding was taken from
    // http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html
    ko.bindingHandlers.isolatedOptions = {
        init: function (element, valueAccessor) {
            var args = arguments;
            ko.computed({
                read: function () {
                    ko.utils.unwrapObservable(valueAccessor());
                    ko.bindingHandlers.options.update.apply(this, args);
                },
                owner: this,
                disposeWhenNodeIsRemoved: element
            });
        }
    };
})();

;
(function (window, undefined) {
    'use strict';

    var invisibleChosenInputForMobilesafari = '<input class="invisible-chosen-input"></input>';
    var aria = gJobs.ariaAttributes;

    ko.bindingHandlers.chosen = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var $element = $(element);

            var options = ko.unwrap(valueAccessor());
            $element.chosen(options);

            var allBindings = allBindingsAccessor();

            var isOpenedAfterInit = ko.unwrap(allBindings.isOpenedAfterInit);
            if (isOpenedAfterInit) {
                $element.one('liszt:updated', function () {
                    $element.siblings('.chzn-container').find('a').attr("aria-label", "");
                    $element.siblings('.chzn-container').find('a').trigger('focus');
                });
            }
            $element.on('change', function (e, params) {
                if (params && params.selected) {
                    $element.siblings('.chzn-container').find('a').last().focus();
                }
            });

            let $chosenContainer = $element.siblings('.chzn-container.chzn-container-single');
            let $chosenMultiContainer = $element.siblings('.chzn-container.chzn-container-multi');
            let $chosenSearchInput = $chosenContainer.find('.chzn-search > input');
            let $chosenLink = $chosenContainer.find('.chzn-single');
            let $chosenChoices = $chosenMultiContainer.find('ul.chzn-choices');
            let $chosenChoicesInput = $chosenMultiContainer.find('.chzn-choices > .search-field > input');


            if ($chosenSearchInput) {
                $chosenSearchInput.attr('role', 'textbox');
                if ($element && $element.length > 0) {
                    $chosenSearchInput.attr('aria-label', element[0].innerHTML);
                }
            }

            if ($chosenChoicesInput) {
                $chosenChoicesInput.attr('role', 'textbox');
                let label = $chosenChoices.attr('data-notification');
                if (label) {
                    $chosenChoicesInput.attr('aria-label', label);
                }
            }

            if ($('.chzn-results').length > 0) {
                $chosenContainer.find('.chzn-results').attr('role', 'listbox');
                if ($element && $element.length > 0) {
                    if (!options.isDropdownTrigger) {
                        $chosenContainer.find('.chzn-results').attr('aria-label', element[0].innerHTML);
                    }
                }
            }
            if (!options.isDropdownTrigger) {
                $chosenLink.attr('role', 'option');
            }

            if (gJobs.browserDetector.isMobileSafari()) {

                var onInvisibleElementFocus = function (e) {
                    $chosenLink.trigger('focus');
                    $invisibleElement.remove();
                }

                var $invisibleElement = $(invisibleChosenInputForMobilesafari);

                $chosenContainer.prepend($invisibleElement);

                $invisibleElement.focus(onInvisibleElementFocus);

                $chosenSearchInput.blur(function () {
                    $chosenContainer.prepend($invisibleElement);
                    $invisibleElement.focus(onInvisibleElementFocus);
                });
            }
        },

        update: function (element, valueAccessor, allBindingsAccessor) {

            var validatableValue = valueAccessor().validatableValue;

            /*
                Registering dependency tracking engine with dropdown options updates.
                    This is crucial for deferred async loading or conditional loading of options.
            */
            ko.unwrap(
                allBindingsAccessor().isolatedOptions ||
                allBindingsAccessor().options
            );

            var allBindings = allBindingsAccessor(),
                optionsValue = ko.unwrap(allBindings.optionsValue),
                selectedOption = ko.unwrap(allBindings.selectedOption),
                selectedOptions = ko.unwrap(allBindings.selectedOptions);

            var $chznContainer = $(element).parent().find('.chzn-container');

            var validatableValue = valueAccessor().validatableValue;
            if (validatableValue) {
                var hasError = ko.utils.unwrapObservable(validatableValue.hasError);
                $chznContainer.setAttributes([
                    [aria.invalid, hasError]
                ]);
            }

            if (selectedOption) {
                if (typeof (selectedOption) === 'object') {
                    selectedOption = ko.unwrap(selectedOption[optionsValue]);
                }

                $(element)
                    .val(selectedOption)
                    .trigger("liszt:updated");
            }
            // case for multiselects
            else if (selectedOptions) {
                $(element).trigger("liszt:updated");
                OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();
            }

            if (selectedOption || selectedOptions) {
                $chznContainer.removeClass('chzn-options-caption-set');
            } else {
                $chznContainer.addClass('chzn-options-caption-set');
            }
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.popover = {
        init: function (element, valueAccessor) {
            var $element = $(element);

            var value = valueAccessor();

            if (value.content) {
                $element.popover({
                    content: ko.unwrap(value.content),
                    template: '<div class="popover ' + (value.className || '') + '" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
                });
            } else {
                $element.popover();
            }

            if (value.containerStyle != undefined) {
                var $container = $element.closest('.' + value.containerStyle);

                var topPlacement = false;
                var placement = $element.attr('data-placement');
                if (placement === 'top') {
                    topPlacement = true;
                }

                $element.on('mouseenter', function (e) {

                    $element.popover('show');

                    var $popover = $('.popover.fade.in');

                    var adjustmentFinished = false;

                    while (!adjustmentFinished) {
                        var elementOffset = $container.outerWidth()
                            - (($popover.offset().left - $container.offset().left)
                                + $popover.outerWidth() + parseInt($popover.css('margin-left')));

                        var oldTop = parseInt($popover.css('top'));
                        var oldLeft = parseInt($popover.css('left'));
                        var oldHeight = $popover.height();
                        var oldWidth = $popover.width();

                        $popover.css('width', oldWidth + elementOffset + 'px');

                        var newHeight = $popover.height();
                        var newWidth = $popover.width();

                        var heightOffset = (newHeight - oldHeight) / 2;
                        var widthOffset = (newWidth - oldWidth) / 2;

                        $popover.css('top', oldTop - heightOffset);

                        if (topPlacement) {
                            $popover.css('left', oldLeft - widthOffset);
                        }

                        var newTop = parseInt($popover.css('top'));
                        var newLeft = parseInt($popover.css('left'));

                        if (oldTop == newTop && oldLeft == newLeft) {
                            adjustmentFinished = true;
                        }
                    }
                });

                
            }
        },
        update: function (element, valueAccessor) {
            var $element = $(element);
            var value = valueAccessor();
            if (value.content) {
                var newValue = ko.unwrap(value.content);
                if (newValue !== $element.data('content')) {
                    $element.popover('destroy');
                    $element.popover({
                        content: newValue,
                        template: '<div class="popover ' + (value.className || '') + '" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
                    });
                }
            }
        }
    };
})(window);;
(function (window, undefined) {
    'use strict';


    var stickElementToBottomOnce = function ($element, $scrollableContainer) {

        /*
            Following properties may vary at runtime, so its not safe to cache them. 
        */
        var scrollOffset = $scrollableContainer.scrollTop();
        var containerHeight = $scrollableContainer.height();
        var elementHeight = $element.height();

        var elementTop = (containerHeight + scrollOffset - elementHeight);

        if (scrollOffset) {
            $element.css({
                'top': elementTop,
                'height': elementHeight
            });
        } else {
            $element.css({
                'top': '',
            });
        }
    };

    var stickElementToBottomOnScroll = function ($element, $scrollableContainer) {

        var stickFunction = function () {
            /*
                Ignore invisible elements.
            */
            if (!$element.is(':visible')) {
                return;
            }

            stickElementToBottomOnce($element, $scrollableContainer);
        };

        $scrollableContainer.scroll(stickFunction);
    };

    var stickElementToBottomOnResize = function ($element, $scrollableContainer) {

        var stickFunction = function () {
            // set handling to the end of event queue (for IE9)
            setTimeout(function () {
                stickElementToBottomOnce($element, $scrollableContainer);
            }, 0);
        };
        $(window).resize(stickFunction);
    };


    ko.bindingHandlers.stickyElement = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var options = valueAccessor();

            var $element = $(element);
            var $scrollableContainer = $element.closest(options.container);

            stickElementToBottomOnScroll($element, $scrollableContainer);
            stickElementToBottomOnResize($element, $scrollableContainer);
        }
    };
})(window);;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.slideVisible = {
        init: function (element, valueAccessor, allBindings, viewModel) {
            var value = valueAccessor();
            if (!gJobs.browserDetector.isIE() || !viewModel || !viewModel.disableSlideVisibleBinding) {
                $(element).toggle(ko.utils.unwrapObservable(value));
            }
        },

        update: function (element, valueAccessor, allBindings, viewModel) {
            var value = valueAccessor();
            var duration = 600;
            if (!gJobs.browserDetector.isIE() || !viewModel || !viewModel.disableSlideVisibleBinding) {
                ko.utils.unwrapObservable(value) ? $(element).slideDown(duration) : $(element).slideUp(duration);
            }
        }
    };
})();
;
/*
    Custom binding that joins three bindings inside:
        1 - common value binding
        2 - validation binding on hasError observable
        3 - behavioral binding to hide validation message when element is in focus

    Use cases:
         data-bind="validatableValue: observable"
         data-bind="validatableValue: { value: observable, errorClass: 'validation-error' }"
         data-bind="validatableValue: { value: observable, errorClass: false }"
*/

(function (window, undefined) {
    'use strict';


    var normazileBinding = function (valueAccessor) {

        var binding = valueAccessor();

        var normalizedBinding = {
            value: null,
            errorValue: null,
            errorClass: 'validation-error'
        };


        if (typeof binding === 'object') {
            $.extend(normalizedBinding, binding);

            if (!('errorValue' in binding)) {
                binding.errorValue = binding.value.hasError;
            }
        }
        else {
            normalizedBinding.value = binding;
            normalizedBinding.errorValue = binding.hasError;
        }

        return normalizedBinding;
    };

    var preventIeFlickering = function ($element) {
        var disableFlickeringClass = 'disable-flickering-on-focus';

        if (!$element.hasClass('btn')) {
            return;
        }

        $element.addClass(disableFlickeringClass);
        setTimeout(function() {
            $element.removeClass(disableFlickeringClass);
        });
    };

    var initFocusBehavior = function (normalizedBinding, enclosingBindingArguments) {

        var value = normalizedBinding.value;
        var errorClass = normalizedBinding.errorClass;
        var keypressEvent = null;

        $(enclosingBindingArguments.element)
            .keydown(function (e) {
                keypressEvent = e;
            })
            .focusout(function (e) {
                if (value.isValidationMessageVisible && value.hasError && value.hasError()) {
                    value.isValidationMessageVisible(true);
                    if (keypressEvent && !keypressEvent.shiftKey && (keypressEvent.keyCode === $.ui.keyCode.TAB)) {
                        preventIeFlickering($(e.relatedTarget));
                        if (!errorClass) {
                            var $target = $(e.relatedTarget);
                            var $element = $(enclosingBindingArguments.element);
                            if ($element.find($target).length !== 0) {
                                return;
                            }
                        }
                        $(document).trigger(Events.CommonEventsNames.ShowValidationMessage, enclosingBindingArguments.element);
                        keypressEvent = null;
                    }
                }
            });
    };

    var initValueBehavior = function (normalizedBinding, enclosingBindingArguments) {

        var valueAccessor = function () {
            return normalizedBinding.value;
        };

        ko.bindingHandlers.value.init(
            enclosingBindingArguments.element,
            valueAccessor,
            enclosingBindingArguments.allBindingsAccessor,
            enclosingBindingArguments.viewModel,
            enclosingBindingArguments.bindingContext);
    };

    var initMaxLengthBehavior = function(normalizedBinding, enclosingBindingArguments) {
        if (normalizedBinding.value && normalizedBinding.value.validators) {
            for (var i = 0; i < normalizedBinding.value.validators.length; i++) {
                var validator = normalizedBinding.value.validators[i];
                if (validator.name === "length" && validator.options.max) {
                    $(enclosingBindingArguments.element).attr('maxlength', validator.options.max);
                }
            }
        }
    };


    var updateCssBehavior = function (normalizedBinding, enclosingBindingArguments) {

        if (!normalizedBinding.errorClass) {
            return;
        }


        var cssAccessor = function () {
            var css = {};
            css[normalizedBinding.errorClass] = normalizedBinding.errorValue;

            return css;
        };

        // Some binding do not have init functionality, so simply subscribe and update them

        ko.bindingHandlers.css.update(
            enclosingBindingArguments.element,
            cssAccessor,
            enclosingBindingArguments.allBindingsAccessor,
            enclosingBindingArguments.viewModel,
            enclosingBindingArguments.bindingContext);
    };

    var updateValueBehavior = function (normalizedBinding, enclosingBindingArguments) {

        var valueAccessor = function () {
            return normalizedBinding.value;
        };

        // Simple wrapper binding update
        ko.bindingHandlers.value.update(
            enclosingBindingArguments.element,
            valueAccessor,
            enclosingBindingArguments.allBindingsAccessor,
            enclosingBindingArguments.viewModel,
            enclosingBindingArguments.bindingContext);
    };


    
    ko.bindingHandlers.validatableValue = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

            var binding = normazileBinding(valueAccessor);

            var enclosingBindingArgumens = {
                element: element,
                valueAccessor: valueAccessor,
                allBindingsAccessor: allBindingsAccessor,
                viewModel: viewModel,
                bindingContext: bindingContext
            };


            initFocusBehavior(binding, enclosingBindingArgumens);
            initValueBehavior(binding, enclosingBindingArgumens);
            initMaxLengthBehavior(binding, enclosingBindingArgumens);
        },

        update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

            var binding = normazileBinding(valueAccessor);

            var enclosingBindingArgumens = {
                element: element,
                valueAccessor: valueAccessor,
                allBindingsAccessor: allBindingsAccessor,
                viewModel: viewModel,
                bindingContext: bindingContext
            };


            updateCssBehavior(binding, enclosingBindingArgumens);
            updateValueBehavior(binding, enclosingBindingArgumens);
        }
    };
})();



;
(function (ko, $) {
    'use strict';

    var ARIA_DESCRIBEDBY = 'aria-describedby',
        ARIA_LABELLEDBY = 'aria-labelledby';

    ko.bindingHandlers.validationMessage = {
        init: function (element, valueAccessor) {
            var options = valueAccessor();
            var $element = $(element);
            var isDropdown = $element.is('select');

            if (isDropdown) {
                $element = $element.parent().find('div.chzn-container');
            }

            if (options.field && options.field.hasError) {
                var savedFieldLabelledby = null;
                options.field.hasError.subscribe(function (newValue) {
                    if (isDropdown) {
                        savedFieldLabelledby = $element.attr(ARIA_LABELLEDBY) || '';
                        if (newValue && options.field.validationMessage()) {
                            $element.attr(
                                ARIA_LABELLEDBY, savedFieldLabelledby + ' ' + options.validationMessageId
                            );
                        }

                        if (!newValue) {
                            $element.attr(ARIA_LABELLEDBY, savedFieldLabelledby);
                        }
                    } else {
                        if (newValue) {
                            $element.attr(ARIA_DESCRIBEDBY, options.validationMessageId);
                        } else {
                            $element.removeAttr(ARIA_DESCRIBEDBY);
                        }
                    }
                });
            }

            if (options.additionalValidationValue && options.additionalValidationValue.hasError) {
                var savedAdditionalValueLabelledby = null;
                var latestValue = null;
                
                options.additionalValidationValue.hasError.subscribe(function (newValue) {
                    if (newValue === latestValue) {
                        return;
                    }
                    if (newValue) {
                        savedAdditionalValueLabelledby = $element.attr(ARIA_LABELLEDBY);
                        $element.attr(
                            ARIA_LABELLEDBY,
                            savedAdditionalValueLabelledby + ' ' + options.additionalValidationValueId
                        );
                    } else {
                        $element.attr(ARIA_LABELLEDBY, savedAdditionalValueLabelledby);
                    }
                });

                options.additionalValidationValue.hasError.subscribe(function (oldValue) {
                    latestValue = oldValue;
                }, null, "beforeChange");
            }
        }
    };
})(ko, jQuery);;
(function (window, undefined) {
    'use strict';


    var equalizeSize = function (element, valueAccessor, allBindingsAccessor) {

        var options = valueAccessor();

        ko.unwrap(options.enabled);

        var $contentElement = $(element);
        var $element = $contentElement.closest(options.parentElement);

        if (gJobs.browserDetector.isIE()  == 8) {
            $element.css('width', '100%');
        }

        if ($element.width() < $contentElement.width()) {
            $element.width($contentElement.width());
        }
    };


    ko.bindingHandlers.sizeToContent = {

        init: function (element, valueAccessor, allBindingsAccessor) {
            equalizeSize(element, valueAccessor, allBindingsAccessor);
        },

        update: function (element, valueAccessor, allBindingsAccessor) {
            equalizeSize(element, valueAccessor, allBindingsAccessor);
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    var getTemplateName = function () {
        var currentArea = gJobs.areaInfoService && gJobs.areaInfoService.getCurrentArea();

        if (currentArea === gJobs.areaInfoService.areaNames.Career) {
            return 'Templates/DottedSpinner';
        } else {
            return 'Templates/RoundSpinner';
        }
    };

    var getOrCreateLoadingElement = function (element) {

        var $loadingElement = $('.loading-element', element);

        if ($loadingElement.length === 0) {

            $loadingElement = $('<div></div>')
                .addClass('loading-element')
                .appendTo(element);

            var templateName = getTemplateName();

            ko.applyBindingsToNode($loadingElement.get(0), { template: { name: templateName } });
        }

        return $loadingElement[0];
    };

    var getOrCreateTextElement = function (element) {

        var $element = $(element);
        var $textElement = $('.text-element', element);

        if ($textElement.length === 0) {
            var buttonText = $element.html();

            $textElement =
                $('<span>')
                    .addClass('text-element')
                    .html(buttonText);

            $element
                .empty()
                .append($textElement);
        }

        return $textElement[0];
    };


    var negateObservable = function (observable) {
        return ko.computed(function () {
            return !ko.utils.unwrapObservable(observable);
        });
    };



    ko.bindingHandlers.busy = {

        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            
            var value = valueAccessor();


            var textElement =
                getOrCreateTextElement(element);

            ko.applyBindingsToNode(textElement, {
                visible: negateObservable(value)
            });


            var loadingElement =
                getOrCreateLoadingElement(element);

            ko.applyBindingsToNode(loadingElement, {
                visible: value
            });


            return { controlsDescendantBindings: true };
        },

        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var value = valueAccessor();
            
            if (ko.utils.unwrapObservable(value)) {
                
                if (element.id !== 'onlineSaveButton') {
                    var $emptyFocusableSpan = $('<span class="hide-notification no-restrict-focus" tabindex="-1">&nbsp;</span>');
                    $(element).append($emptyFocusableSpan);
                    $emptyFocusableSpan.focus();
                    $emptyFocusableSpan.one('focusout', function () {
                        $emptyFocusableSpan.remove();
                    });
                }
               
            }

            ko.bindingHandlers.disable.update(
                element,
                valueAccessor,
                allBindingsAccessor,
                viewModel);
        }
    };
})(window);;
(function (window, undefined) {
    'use strict';


    var applyTextBinding = function (element, valueAccessor) {
        var binding = valueAccessor();

        var isPropertyRequired = checkIsPropertyRequired(binding.field);


        var text;

        if (isPropertyRequired) {
            text = ko.utils.unwrapObservable(binding.text);
        }

        $(element)
            .text(text)
            .toggleClass('required', isPropertyRequired);

        if (isPropertyRequired) {
            $(element).show();
        } else {
            $(element).hide();
        }
    };


    var findRequiredValidator = function (observableProperty) {

        var requiredValidator =
            ko.utils.arrayFirst(observableProperty.validators, function (validator) {
                return (validator.name === 'required');
            });

        return requiredValidator;
    };

    var checkIsPropertyRequired = function (observableProperty) {

        var requiredValidator = findRequiredValidator(observableProperty);

        if (!requiredValidator) {
            return false;
        }

        return requiredValidator.enabled();
    };


    ko.bindingHandlers.requiredText = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            applyTextBinding(element, valueAccessor);
        },

        update: function (element, valueAccessor, allBindingsAccessor) {
            applyTextBinding(element, valueAccessor);
        }
    };


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

    var tabIndexApplicants;

    function parentContainerIsTheSame(el1, el2, containerSelector) {
        if (!el1 || !el2) {
            return false;
        }

        var parent1 = $(el1).closest(containerSelector),
            parent2 = $(el2).closest(containerSelector);

        return parent1.get(0) === parent2.get(0);
    }

    function setCheckAndRadioBehavior($elements) {
        $elements
            .filter("input[type=radio],input[type=checkbox]")
            .off("focus blur")
            .focus(function (event) {
                if(!event.target ||
                   !event.originalEvent)

                if (parentContainerIsTheSame(
                        event.target,
                        !!event.originalEvent ? event.originalEvent.explicitOriginalTarget : undefined,
                        "label")) {
                    return false;
                }

                var $this = $(this);
                $this.closest('.labelled-input').addClass('focus');

                // check box on pressing "Space" (default browser behavior)
                // and "Enter"
                if ($this.attr("type") === "checkbox") {
                    $this.on("keypress", function (e) {
                        var code = (e.keyCode ? e.keyCode : e.which);
                        if (code == 13) {
                            // here we'd need to manually update ko "checked" binding
                            //var checked = $this.is(":checked");
                            //$this.prop('checked', !checked);

                            // click makes "checked" binding to update
                            $this.click();
                        }
                    });
                }
            })
            .blur(function () {
                var $this = $(this);
                $this.closest('.labelled-input').removeClass('focus');

                if ($this.attr("type") === "checkbox") {
                    $this.off("keypress");
                }
            });
    }

    function setTabIndex(element) {
        var index = tabIndexApplicants ? tabIndexApplicants.index(element) : -1;

        if (index === -1) {
            tabIndexApplicants = $("input[type=text],input[type=radio],input[type=checkbox],textarea,button")
                .filter(":visible")
                .add("select");

            index = tabIndexApplicants.index(element);

            // if element is still not fount (might be invisible)
            if (index === -1) {
                return;
            }

            // iterate over sequence and assign everyone proper tabindex
            tabIndexApplicants.each(function(i) {
                var $this = $(this);
                // tabindex can't be 0
                $this.attr("tabindex", ++i);
            });
            setCheckAndRadioBehavior(tabIndexApplicants);
        }

        // tabindex can't be 0
        // $(element).attr("tabindex", ++index);

        // more robust would be iterate over sequence and assign everyone proper tabindex
    }

    ko.bindingHandlers.tabIndex = {

        init: function (element, valueAccessor) {

            // postpone is used for elements that should be evaluated at later point
            // e.g. we have "save/cancel buttons" html template which loads prior to any other controls
            // but should have last tabindex
            // EDIT: more robust solution is to iterate over sequence and assign everyone proper tabindex
            /*
            var postpone = valueAccessor().postpone;
            if (postpone) {
                window.setTimeout(function () {
                    setTabIndex(element);
                }, 0);

                return;
            }
            */

            setTabIndex(element);
        },

        setCheckAndRadioBehavior: setCheckAndRadioBehavior
    };
})(window);;
(function (window, undefined) {
    'use strict';


    ko.bindingHandlers.autoFill = {

        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {

            var autoFillTargetsSelector = ':input';
            var submitControlSelector = 'button[type="submit"]';


            var $element = $(element);

            $element.on('blur', autoFillTargetsSelector, function (e) {
                $(e.target).change();
            });

            $element.on('click', submitControlSelector, function (e) {
                $(e.delegateTarget).find(autoFillTargetsSelector).change();
            });
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    function KnockoutValidationExtender() {
        var self = this;

        /*
            Constants.
        */
        var DEFAULT_VALIDATION_OPTIONS = {
            validationMessage: '',
            isValidationMessageVisible: true
        };


        /*
            Private members.
        */

        /*
            Ensures that observable property has necessary validation properties.
        */
        var ensureStructure = function (observableProperty) {
            observableProperty.hasError = observableProperty.hasError || ko.observable(false);
            observableProperty.validationMessage = observableProperty.validationMessage || ko.observable('');
            observableProperty.validators = observableProperty.validators || [];
            observableProperty.isValidationMessageVisible = (observableProperty.isValidationMessageVisible || ko.observable(false)).extend({ throttle: 1 });
        };

        /*
            Registers validator with observable property. 
        */
        var registerValidator = function (observableProperty, validatorName, validatorObject, options) {
            ensureStructure(observableProperty);

            options = $.extend({},
                DEFAULT_VALIDATION_OPTIONS,
                options);

            var validator = {
                name: validatorName,
                action: validatorObject.validate,
                options: options,
                observableProperty: observableProperty,
                enabled: function () {
                    if (typeof validatorObject.isEnabled !== 'function') {
                        return true;
                    }

                    return validatorObject.isEnabled(options);
                }
            };

            observableProperty.validators.push(validator);

            applyValidatorBehavior(validator);
        };

        /*
            Applies runtime validation behavior.
        */
        var applyValidatorBehavior = function (validator) {

            /*
                Apply on property change behavior.
                    Due to performance reasons all validator actions will be fired at once.
            */
            if (validator.observableProperty.validators.length === 1) {
                validator.observableProperty.subscribe(function () {
                    validate(validator);
                });
            }

            /*
                Apply on demand validation method.
            */
            validator.observableProperty.validate = function (supressValidationError) {
                return validate(validator, supressValidationError);
            };
        };


        /*
            Core method that triggers validation and related validation property changes.
        */
        var validate = function (validator, supressValidationError) {
            var isValid = true;
            var failedValidator;

            var value = validator.observableProperty();
            var validators = validator.observableProperty.validators;


            for (var i = 0; i < validators.length; i++) {
                isValid = isValid && validators[i].action(value, validators[i].options);

                if (!isValid) {
                    failedValidator = validators[i];
                    break;
                }
            }

            if (!supressValidationError) {
                if (isValid) {
                    validator.observableProperty.validationMessage(null);
                    validator.observableProperty.hasError(false);
                    validator.observableProperty.isValidationMessageVisible(false);
                }
                else {
                    validator.observableProperty.validationMessage(failedValidator.options.validationMessage);
                    validator.observableProperty.hasError(true);
                    validator.observableProperty.isValidationMessageVisible(failedValidator.options.isValidationMessageVisible);
                }
            }

            return isValid;
        };


        /*
            Public members.
        */
        self.registerExtension = function (extenderName, extender) {

            ko.extenders[extenderName] = function (target, options) {
                options = $.extend({},
                    extender.defaultOptions,
                    options);

                registerValidator(target, extenderName, extender.validator, options);

                return target;
            };
        };

        self.registerExtensions = function (extenders) {
            $.each(extenders, function (extenderName, extender) {
                self.registerExtension(extenderName, extender);
            });
        };

        // maxDigits validation extension: validates that the value has at most options.max digits
        self.registerExtension('maxDigits', {
            defaultOptions: {
                max: 4,
                validationMessage: 'Value cannot have more than 4 digits.'
            },
            validator: {
                validate: function (value, options) {
                    if (value == null || value === '') return true;
                    var digits = value.toString().replace(/[^0-9]/g, '');
                    return digits.length <= options.max;
                }
            }
        });

        // minValue validation extension: validates that the value is at least options.min
        self.registerExtension('minValue', {
            defaultOptions: {
                min: 1,
                validationMessage: 'Value must be greater than 0.'
            },
            validator: {
                validate: function (value, options) {
                    if (value == null || value === '') return true;
                    return parseFloat(value) >= options.min;
                }
            }
        });
    };



    OnlineApp.Namespace.extend('OnlineApp.Extensions.Knockout', {
        KnockoutValidationExtender: KnockoutValidationExtender
    });

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

    ko.bindingHandlers.directDropdown = {

        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {

            var options = valueAccessor() || {};

            if (options.container == undefined) {
                return;
            }

            var $element = $(element);

            if (!options.topMargin) {
                var $label = $element.siblings('label.inline-text, span.inline-text');
                if (!$label.length) {
                    $label = $element.parents('.question-item').find('.question-text');
                }
                if ($label.length) {
                    var labelMargin = parseInt($label.css('margin-top')) || parseInt($label.css('margin-bottom'));
                    options.topMargin = $label.height() + labelMargin;
                }
            }

            var containerClass = "." + options.container;

            var wrapper = $element.siblings('.chzn-container');
            var dropDown = wrapper.find(".chzn-drop");
            var input = wrapper.find("input");

            var container = wrapper.closest(containerClass);

            var choices = dropDown.find("li");

            var isContainerHeightChanged = false;

            input.on("focus", function () {
                // That means if drop down is visible due to chosen.jquery.js plugin.
                if (parseInt(dropDown.css("left")) >= 0) {
                    // Calculate position of the drop down to decide
                    // what should be the direction (up or down).
                    var scrollTop = $(window).scrollTop();
                    var wrapperOffset = $(wrapper).offset().top;
                    var windowHeight = $(window).height();

                    // windowTopOffset - offset between wrapper top and current window top
                    var windowTopOffset = wrapperOffset - scrollTop;
                    var windowCenter = windowHeight / 2 - wrapper.height();

                    if (windowTopOffset > windowCenter) {
                        dropDown.addClass("chzn-drop-up");
                    } else {
                        dropDown.removeClass("chzn-drop-up");
                    }

                    // Check, if drop down is lower height than container.
                    // If not, then make container bigger.
                    var dropDownOffset = dropDown.offset().top;
                    var containerOffset = container.offset().top;

                    // dropDownOffsetBottom - offset of dropdown top from container bottom
                    var dropDownOffsetBottom = container.height() - (dropDownOffset - containerOffset);
                    var dropDownOverflowHeight = dropDown.outerHeight() - dropDownOffsetBottom;

                    if (dropDownOverflowHeight > 0) {
                        var newHeight = container.height() + dropDownOverflowHeight;
                        container.css("height", newHeight + "px");
                        isContainerHeightChanged = true;
                    }

                    // If window height is smaller than 650px, scroll to the input to make whole selection visible
                    if(windowHeight < 650) {
                        scrollToView(wrapper, options.topMargin);
                        dropDown.removeClass("chzn-drop-up");
                    }
                    
                } else {
                    input.trigger("blur");
                }
            });

            var isOver = false;
            dropDown.mouseover(function () {
                isOver = true;
            }).mouseleave(function () {
                isOver = false;
            });

            choices.on("click", function () {
                isOver = false;

                input.trigger("blur");
            });

            input.on("blur", function () {
                if (!isOver && isContainerHeightChanged) {
                    container.css("height", "");
                    isContainerHeightChanged = false;
                }
            });
        }
    };

    function scrollToView(view, topMargin) {
        var $flyoutBody = $(".flyout-scroll-view");
        var isFlyout = $flyoutBody.length > 0;
        var container = isFlyout ? $flyoutBody : $("html, body");

        var newScrollPosition = isFlyout 
            ? view.position().top
            : view.offset().top - $('.floating-header, .navbar').height();

        if (!isNaN(topMargin)) {
            newScrollPosition -= topMargin;
        }

        container.animate({ scrollTop: newScrollPosition }, 500);
    }

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

    function getRadioButtonsExceptCurrent(radioElement) {

        var radioGroupName = radioElement.attr('name');
        // TODO: refactoring anf optimization required
        var otherRadios = $('input[name="' + radioGroupName + '"]').not(radioElement);

        return otherRadios;
    }

    ko.bindingHandlers.checkRadio = {

        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {

            var radioElement = $(element);
            var checkValue = valueAccessor();

            var otherRadios = getRadioButtonsExceptCurrent(radioElement);

            radioElement.on('click', function () {

                // TODO: FIND A BETTER EXPRESSION
                checkValue(radioElement.is(':checked'));

                if (radioElement.is(':checked')) {
                    checkValue(true);
                } else {
                    checkValue(false);
                }

                // Trigger other radios to change their observables to false.
                otherRadios.trigger('changeToFalse');
            });

            radioElement.on('changeToFalse', function () {

                checkValue(false);
            });
        },

        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {

            var radioElement = $(element);
            var checkValue = valueAccessor();
            var value = ko.unwrap(checkValue);

            var otherRadios = getRadioButtonsExceptCurrent(radioElement);

            if (value) {
                otherRadios.trigger('changeToFalse');
                radioElement.prop('checked', true);
                
            } else {

                radioElement.prop('checked', false);
            }
        }
    };
})(window);
;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.updateTabIndex = {
        update: function (element, valueAccessor) {
            OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.hasFocusOneWay = {

        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {

            var options = valueAccessor() || {};

            if (options.observable == undefined) {
                return;
            }

            var observable = options.observable;

            if (options.readOrWrite === 'write') {
                var writeObservable = function (isFocus) {
                    if (ko.isObservable(observable)) {
                        observable(isFocus);
                    }
                };

                ko.applyBindingsToNode(element, {
                    event: {
                        focus: function () {
                            writeObservable(true);
                        },
                        blur: function () {
                            writeObservable(false);
                        }
                    }
                });
            } else if (options.readOrWrite === 'read') {
                observable.subscribe(function(newValue) {
                    if (newValue) {
                        var $element = $(element);
                        $element.focus();
                    }
                });
            }
        }
    };
})();;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.ieFixKeyboardNavigation = {
        init: function (element, valueAccessor) {
            if (!gJobs.browserDetector.isIE()) {
                return;
            }

            var $element = $(element);

            $element.on('keydown', function (e) {
                if (e.which == $.ui.keyCode.TAB) {
                    e.preventDefault();

                    var offset = e.shiftKey ? -1 : 1;
                    var tabindex = parseInt($element.attr('tabindex'), 10);
                    var targetTabindex = tabindex + offset;

                    $('[tabindex="' + targetTabindex + '"]').focus();
                } else if (e.which == $.ui.keyCode.ENTER) {
                    e.preventDefault();
                    $element.trigger('click');
                }
            });
        }
    };
})();
;
(function (window, undefined) {
    'use strict';

    var cache = {};
    var instanceCount = 1;
    var doesLastFocusableElementExist = false;

    ko.bindingHandlers.modalRestrictFocus = {
        init: function (element) {
            var $element = $(element);
            $element.data('unrestrict-index', instanceCount);
            instanceCount++;
        },
        update: function (element, valueAccessor) {
            var value = valueAccessor();
            var $element = $(element);
            var $modalDialogWrapper = $element.parent();
            var unrestrictFunction;
            var index;

            if (value()) {
                gJobs.focusService.setFocus($element);

                unrestrictFunction = gJobs.focusService.restrictFocus($modalDialogWrapper, null, true);

                index = $element.data('unrestrict-index');
                cache[index] = unrestrictFunction;
            } else {
                index = $element.data('unrestrict-index');

                if (index && cache.hasOwnProperty(index)) {
                    $modalDialogWrapper.find('[tabindex]').attr('tabindex', -1);

                    if (!doesLastFocusableElementExist) {
                        gJobs.focusService.restoreBrowserControlsFocusBehavior();
                    }

                    unrestrictFunction = cache[index];
                    unrestrictFunction();
                    $.removeData($element, 'unrestrict-index');
                    gJobs.focusService.restoreFocus();
                }
            }
        }
    };
})();
;
(function (window, undefined) {
    'use strict';

    var TRANSITION_END_EVENT_NAMES = 'webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd';

    var isTransitionEventSupported = gJobs.isTransitionEventSupported
        && gJobs.isTransitionEventSupported();

    function findContentWrapper($element) {
        var scrollContainer = $element.scrollParent();
        return scrollContainer.children().has($element);
    }

    ko.bindingHandlers.slideDownOnce = {
        init: function (element, valueAccessor) {
            var $element = $(element);
            var submittedAppFlyout = getFlyout();
            var isOpen = submittedAppFlyout && submittedAppFlyout.isOpen();

            if (!$element.is(':visible') || isOpen) {
                return;
            }

            var options = valueAccessor();
            var renderEvent = options.renderEvent;
            var $container = findContentWrapper($element);
            // Hiding element to prevent flashing in IE
            $element.css('opacity', '0');

            if (renderEvent) {
                $(document).on(renderEvent, startAnimation);
            } else {
                startAnimation();
            }

            function startAnimation() {
                var containerHeight = $container.outerHeight();
                $container.css('min-height', containerHeight);
                $element.css('opacity', '');

                var height = $element.outerHeight();

                $element.addClass('slidedown');

                // Reading a CSS property forces the layout to be computed.
                // After that browser is able to recognize the property changes, which triggers the transition.
                $element.css('max-height');
                $element.css('max-height', height);

                if (isTransitionEventSupported) {
                    $element.one(TRANSITION_END_EVENT_NAMES, performFadeIn);
                } else {
                    performFadeIn();
                }
            }

            function performFadeIn() {
                
                $element.addClass('fadein');

                $element.removeClass('slidedown');
                $element.css('max-height', '');
                $container.css('min-height', '');

                $(document).off(renderEvent, startAnimation);

                if (namespace('AgencyPages').Ios8Detector.IsIos8()) {
                    $element.hide(0).show(0);
                }
            }
        }
    };

    function getFlyout() {
        return AgencyPages.submittedAppFlyout;
    }
})(window);;
(function (window, undefined) {
    'use strict';

    function isElementFullyInViewport(element, viewport) {
        var rect = element.getBoundingClientRect();

        return rect.top >= viewport.top &&
            rect.left >= viewport.left &&
            rect.right <= viewport.left + viewport.width &&
            rect.bottom <= viewport.top + viewport.height;
    }

    function shouldScrollOnInit($element) {
        if (!$element.is(':visible')) {
            return false;
        }

        var $searchArea = $element.parent();

        var $firstElementWithScrollBinding = $searchArea
            .children('[data-bind]')
            .filter(function (index, element) {
                return $(element).attr('data-bind').indexOf('scrollIntoView') + 1;
            });

        return $element[0] == $firstElementWithScrollBinding[0];
    }

    ko.bindingHandlers.scrollIntoView = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var $element = $(element);

            var options = valueAccessor();
            var shouldScrollToChildElement = options.hasOwnProperty('fieldContainerSelector');

            var alignFunction = function ($target) {
                var isElementInsideFixedElement = $element
                    .parents()
                    .toArray()
                    .some(function (item) {
                        return $(item).css('position') == 'fixed';
                    }
                    );

                var $container = $element.scrollParent();
                if ($container[0] == $('body')[0] && gJobs.browserDetector.isFirefox()) {
                    $container = $('html');
                }

                var elementRect = $element[0].getBoundingClientRect();
                var elementOffset = elementRect.top;
                var elementHeight = elementRect.height;
                var currentScrollPosition = $container.scrollTop();

                var viewport = {
                    height: 0,
                    width: 0,
                    top: 0,
                    left: 0
                };

                if (isElementInsideFixedElement) {
                    var containerRect = $container[0].getBoundingClientRect();
                    elementOffset -= containerRect.top;

                    viewport.top = containerRect.top;
                    viewport.left = containerRect.left;
                    viewport.width = containerRect.width;
                    viewport.height = containerRect.height;

                } else {
                    viewport.width = $(window).width();
                    viewport.height = $(window).height();
                }

                if (isElementFullyInViewport($element[0], viewport)) {
                    return;
                }

                var offset;
                if (elementHeight <= viewport.height) {
                    offset = elementOffset - ((viewport.height / 2) - (elementHeight / 2));
                }
                else {
                    $target = shouldScrollToChildElement ?
                        $target.closest(options.fieldContainerSelector) :
                        $target;

                    var target = $target[0];

                    if (target) {
                        var targetRect = target.getBoundingClientRect();
                        if (!isElementFullyInViewport(target, viewport)) {
                            offset = targetRect.height < viewport.height ?
                                targetRect.top - viewport.top - ((viewport.height / 2) - (targetRect.height / 2)) :
                                targetRect.top - viewport.top;
                        } else {
                            return;
                        }
                    }
                }

                $container.scrollTop(currentScrollPosition + offset);
            }

            if (shouldScrollOnInit($element)) {
                alignFunction($(element).find(":tabbable").first());
            }

            $element.on('keyup', ':tabbable', function (event) {
                if (event.which === $.ui.keyCode.TAB) {
                    alignFunction($(event.target));
                }
            });
        }
    };
})(window);;
(function (window, undefined) {
    'use strict';

    ko.bindingHandlers.checkMark = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var $element = $(element);
            var options = valueAccessor();

            var $triggerElement = $element.closest(options.container).find(options.triggerElementSelector);

            $element.on('click', function () {
                if (options.type === 'radio') {
                    $triggerElement.prop('checked', true);
                }

                $triggerElement.trigger('click').focus();
            });
        }
    };
})(window);
;
(function (window, undefined) {
    'use strict';
    var layoutHelper = OnlineApp.Helpers.layoutHelper,
        commonEventsNames = OnlineApp.Events.CommonEventsNames;

    function getTargetEditableElement(editableItemContainer) {
        var $nextEditableItem;
        var $nextEditableItemContainer = $('.box-container.edit-dialog:visible:first');
        if ($nextEditableItemContainer.length) {
            $nextEditableItem =
                layoutHelper.tabbing.getFirstElement($nextEditableItemContainer);
        } else {
            var $editableItemContainer = $(editableItemContainer);
            $nextEditableItem = $editableItemContainer.find('.item-edit-button:visible');
        }
        return $nextEditableItem;
    }

    function successSaveSectionNotification (e) {
        var $nextEditableItem = getTargetEditableElement(e.editableItemContainer);

        if (e && e.data && e.data.sectionName) {
            var notificationMessage = e.data.sectionName + ' section has been saved.';
            gJobs.screenReadersService.setAriaLiveNotification(notificationMessage);
        }
        $nextEditableItem.focus();
    }

    function validationFailedOnSaveSectionNotification (e) {
        var $nextEditableItem = getTargetEditableElement(e.editableItemContainer); 

        var notificationMessage = 'Unable to save ' + e.data.sectionName +
            ' section.';

        gJobs.screenReadersService.setNotificationOnElement({
            text: notificationMessage,
            $element: $nextEditableItem
        });
    }

    function formOpeningNotification(e, data) {        
        if (!data.isQuestionsItem && !data.editModeOnly) {
            var $firstFocusableElement = layoutHelper.tabbing.getFirstElement();

            var notificationMessage =
                (data.editEvent ? 'Edit ' : 'Add ') +
                e.data.sectionName +
                ' form has been opened.';            
            
            $firstFocusableElement.focus();
            setTimeout(function () {
                gJobs.screenReadersService.setAriaLiveNotification(notificationMessage);
            }, 200);
        }    
    }

    function successRemoveEditableItemComplete(e, data) {
        var notificationMessage = e.data.sectionName + ' section item has been removed.';

        var $section = $('.onlineapp-app-container .tab-pane.active:visible');
        if (e.data.sectionId)
            $section = $section.find('#' + e.data.sectionId);
        var $focusableElement;

        var $sectionListItems = $section.find('ul li');
        if ($sectionListItems.length) {
            var index = e.index == $sectionListItems.length ? e.index - 1 : e.index;
            $focusableElement = $sectionListItems.eq(index).find('.item-edit-button');
        } else {
            $focusableElement = $section.find('.btn-add-resume-item');
        }

        gJobs.screenReadersService.setNotificationOnElement({
            text: notificationMessage,
            $element: $focusableElement
        });
    }

    ko.bindingHandlers.sectionNotification = {
        init: function (element, valueAccessor) {
            var sectionName = valueAccessor();
            var sectionId = $(element).closest('ul').parent().attr('id');
            $(document)
                .off(commonEventsNames.EditItemComplete, successSaveSectionNotification)
                .off(commonEventsNames.PreSaveValidationFailed, validationFailedOnSaveSectionNotification)
                .off(commonEventsNames.EditableItemBeginEdit, formOpeningNotification)
                .off(commonEventsNames.ItemRemoved, successRemoveEditableItemComplete)
                .on(commonEventsNames.EditItemComplete,
                    { sectionName: sectionName },
                    successSaveSectionNotification)
                .on(commonEventsNames.PreSaveValidationFailed,
                    { sectionName: sectionName },
                    validationFailedOnSaveSectionNotification)
                .on(commonEventsNames.EditableItemBeginEdit,
                    { sectionName: sectionName },
                    formOpeningNotification)
                .on(commonEventsNames.ItemRemoved,
                    { 
                        sectionName: sectionName,
                        sectionId: sectionId
                    },
                    successRemoveEditableItemComplete);
        }
    }

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

    var commonEventTypes = OnlineApp.Events.CommonEventsNames;

    var eventTypes = {
        edit: 'edit',
        add: 'add',
        cancel: 'cancel',
        save: 'save'
    }

    var eventOptions = {
        save: {
            metric4: 1,
            metric6: 1
        },
        add: {
            metric4: 1,
            metric5: 1
        },
        edit: {
            metric4: 1
        },
        cancel: {
            metric4: 1
        }
    }

    function sendGoogleAnalyticsEvent (e) {
        var options = e.data;

        var data = $.extend({ }, eventOptions[options.eventType]);

        if (options.data) {
            var optionsData = options.data;

            if (optionsData.schoolType) {
                data.dimension16 = optionsData.schoolType();
            }

            if (optionsData.licenceType) {
                data.dimension16 = optionsData.licenceType();
            }

            if (optionsData.positionTitle) {
                data.dimension15 = optionsData.positionTitle();
            }
        }

        gJobs.common.analytics.trackApplicationEvent({
            action: options.eventType,
            eventLabel: options.sectionCode,
            sendToAllTrackers: true,
            data: data
        });
    }

    function attachGoogleAnalyticsEventHandler (element, options) {
        $(element)
            .off('click', sendGoogleAnalyticsEvent)
            .on('click', options, sendGoogleAnalyticsEvent);
    } 

    ko.bindingHandlers.googleAnalyticsEvent = {
        init: function (element, valueAccessor) {
            var options = valueAccessor();
            if (options.sectionCode) {
                if (options.eventType == eventTypes.save) {
                    $(document)
                        .off(commonEventTypes.EditItemComplete, sendGoogleAnalyticsEvent)
                        .on(commonEventTypes.EditItemComplete, options, sendGoogleAnalyticsEvent);
                } else {
                    attachGoogleAnalyticsEventHandler(element, options);
                }
            }
        }
    }

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

    function BaseValidator() {
        var self = this;

        var defaultValidationOptions = {
            enabled: true
        };

        var checkEnabled = function(conditions) {
            var enabled = true;

            for (var i = 0; i < conditions.length; i++) {
                if ($.isFunction(conditions[i])) {
                    enabled = enabled && conditions[i]();
                } else {
                    enabled = enabled && ko.utils.unwrapObservable(conditions[i]);
                }
            }

            return enabled;
        };

        var normalizeValidationOptions = function(validationOptions) {
            var normalizedValidationOptions =
                $.extend({}, defaultValidationOptions, validationOptions);

            if (!$.isArray(normalizedValidationOptions.enabled)) {
                normalizedValidationOptions.enabled = [normalizedValidationOptions.enabled];
            }

            return normalizedValidationOptions;
        };


        self.isEnabled = function (validationOptions) {
            validationOptions = normalizeValidationOptions(validationOptions);
            return checkEnabled(
                validationOptions.enabled
            );
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        BaseValidator: BaseValidator
    });


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

    function RegularExpressionValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        self.validate = function(value, validationOptions) {
            var isValid = true;
            
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (value != undefined && value !== "") {
                if (validationOptions && validationOptions.pattern) {
                    isValid = validationOptions.pattern.test(value);
                }
            }

            return isValid;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        regularExpressionValidator: new RegularExpressionValidator()
    });

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

    function EmailValidator() {
        var self = this;

        var emailRegExp = /^['_a-zA-Z0-9-+]+(\.['_a-zA-Z0-9-+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([a-zA-Z]+))$/;
        
        self.validate = function(value, validationOptions) {
            validationOptions.pattern = emailRegExp;
            return OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        emailValidator: new EmailValidator()
    });

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

    function ConfirmFieldValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            return value === validationOptions.fieldToConfirm();
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        confirmFieldValidator: new ConfirmFieldValidator()
    });

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

    function timespanStartIsNotAfterEndValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            var startMonth = parseInt(validationOptions.startMonth());
            var startYear = parseInt(validationOptions.startYear());
            var endMonth = parseInt(validationOptions.endMonth());
            var endYear = parseInt(validationOptions.endYear());

            startMonth = startMonth || 1;       //startMonth and endMonth can be not selected, so
            endMonth = endMonth || 12;          //startMonth default value is the first month of the year
                                                //and endMonth default value is the last month of the year

            var yearFieldsAreNonZeroNumbers = startYear && endYear;
            if (!yearFieldsAreNonZeroNumbers) {
                return true;
            }

            var endMonthIsNotSpecialCase = endMonth >= 1 && endMonth <= 12;     //don't validate if endMonth is special case (e.g. Present, No expiration)
            if (!endMonthIsNotSpecialCase) {
                return true;
            }

            var isStartDateBeforeOrEqualEndDate = new Date(startYear, startMonth - 1) <= new Date(endYear, endMonth - 1);

            return isStartDateBeforeOrEqualEndDate;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        timespanStartIsNotAfterEndValidator: new timespanStartIsNotAfterEndValidator()
    });

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

    function isNotFutureDateValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            var month = parseInt(validationOptions.month());
            var year = parseInt(validationOptions.year());

            if (!year) { return true; }

            month = month || 1;       //startMonth can be not selected, so default value is the first month of the year

            var isFutureDate = new Date(year, month - 1) > Date.now();

            return !isFutureDate;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        isNotFutureDateValidator: new isNotFutureDateValidator()
    });

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

    function validate(value) {
        //all changes must be  applied on server side PasswordValidator.cs
        var isLongEnough = value.length >= 12;
        var hasLetter = (/[a-z]+/.test(value));
        var hasDigit = (/[0-9]+/.test(value));
        var hasUpperCaseLetter = (/[A-Z]+/.test(value));
        var hasNonAlphaNumericChars = (/[\W]+/.test(value));
        return isLongEnough && hasLetter && hasDigit && hasUpperCaseLetter && hasNonAlphaNumericChars;
    }

    //exposed solely for unit testing purposes (PasswordValidatorTests.js)
    window.UnitTestsPasswordValidatorValidate = validate;

    function passwordValidator() {
        var self = this;

        self.validate = function (value) {
            return validate(value);
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        passwordValidator: new passwordValidator()
    });
})(window);;
(function (window, undefined) {
    'use strict';

    function RequiredValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;


        var defaultValidationOptions = {
            onlyIf: function () { return true; }
        };

        var normalizeValidationOptions = function (validationOptions) {
            var normalizedValidationOptions =
                $.extend({}, defaultValidationOptions, validationOptions);

            return normalizedValidationOptions;
        };


        self.validate = function (value, validationOptions) {

            validationOptions = normalizeValidationOptions(validationOptions);


            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (!validationOptions.onlyIf()) {
                return true;
            }

            if (typeof value === 'number') {
                return true;
            }

            if ($.isArray(value) && value.length === 0) {
                return false;
            }

            if (typeof value === 'string' && $.trim(value).length === 0) {
                return false;
            }

            return (!!value);
        };

    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        requiredValidator: new RequiredValidator()
    });

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

    function RequiredFieldValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        self.validate = function (value, validationOptions) {
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            var objectValue = ko.unwrap(validationOptions.objectField),
                subjectValue = ko.unwrap(validationOptions.subjectField);

            if (objectValue) {
                return OnlineApp.Validation.requiredValidator.validate(
                    subjectValue,
                    validationOptions);
            }

            return true;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        requiredFieldValidator: new RequiredFieldValidator()
    });

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

    function NumericValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var integerRegExp = /^\d+$/;
        var floatRegExp = /^(\d*[.])?\d+$/;

        self.validate = function (value, validationOptions) {

            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (typeof value !== 'number' && !value) {
                return true;
            }


            validationOptions.pattern = validationOptions.allowFloat === true ? floatRegExp : integerRegExp;

            var isValid = OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);

            var numericValue = Number(value);

            if (validationOptions.min != null) {
                isValid = isValid && (numericValue >= validationOptions.min);
            }

            if (validationOptions.max != null) {
                isValid = isValid && (numericValue <= validationOptions.max);
            }

            return isValid;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        numericValidator: new NumericValidator()
    });

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

    function YearValidator() {
        var self = this;

        var yearRegExp = /^[1-9][0-9]{3}$/;


        self.validate = function (value, validationOptions) {
            validationOptions.pattern = yearRegExp;
            return OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        yearValidator: new YearValidator()
    });

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

    function MonthValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            if (value) {
                if (OnlineApp.ViewModels.applicationViewModel.definitionsViewModel) {
                    return OnlineApp.ViewModels.applicationViewModel.definitionsViewModel
                        .month.findItemById(value).hasOwnProperty('id');
                }

                //use server validation if definitions vm is unavailable
                return true;
            }
            
            return true;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        monthValidator: new MonthValidator()
    });

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

    function ExtendedMonthValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            if (value) {
                if (OnlineApp.ViewModels.applicationViewModel.definitionsViewModel) {
                    return OnlineApp.ViewModels.applicationViewModel.definitionsViewModel
                        .extendedMonth.findItemById(value).hasOwnProperty('id');
                }

                //use server validation if definitions vm is unavailable
                return true;
            }
            
            return true;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        extendedMonthValidator: new ExtendedMonthValidator()
    });

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

    function VerificationCodeValidator() {
        var VERIFICATION_CODE_LENGTH = 6;
        
        var self = this;

        self.validate = function (value, validationOptions) {
            var validatableValue = value;

            if (validationOptions.regExpForValueTransform) {
                var charsForReplace = "";

                if (validationOptions.charsForReplace) {
                    charsForReplace = validationOptions.charsForReplace;
                }

                validatableValue = validatableValue.replace(validationOptions.regExpForValueTransform, charsForReplace);
            }

            return validatableValue.length === VERIFICATION_CODE_LENGTH ? true : false;
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        verificationCodeValidator: new VerificationCodeValidator()
    });

})(window);
;
(function (window, undefined) {
    'use strict';

    function MonthWithNoExpirationValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            if (value) {
                if (OnlineApp.ViewModels.applicationViewModel.definitionsViewModel) {
                    return OnlineApp.ViewModels.applicationViewModel.definitionsViewModel
                        .monthWithNoExpiration.findItemById(value).hasOwnProperty('id');
                }

                //use server validation if definitions vm is unavailable
                return true;
            }
            
            return true;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        monthWithNoExpirationValidator: new MonthWithNoExpirationValidator()
    });

})(window);
;
(function (window, undefined) {
    'use strict';

    function MaxValueValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            if (!value)
                return true;
            
            if (isNaN(value))
                return false;
            
            validationOptions = validationOptions || {};
            var numericValue = parseInt(value);
            return numericValue <= validationOptions.maxValue;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        maxValueValidator: new MaxValueValidator()
    });

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

    function LengthValidator() {

        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        self.validate = function (value, validationOptions) {
            
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (typeof value === 'number') {
                value = String(value);
            }
            else if (value == null) {
                value = "";
            }


            var valueLength = value.length;
            var isValid = true;

            validationOptions = validationOptions || {};

            if (validationOptions.min != null) {
                isValid = isValid && (valueLength >= validationOptions.min);
            }

            if (validationOptions.max != null) {
                isValid = isValid && (valueLength <= validationOptions.max);
            }

            return isValid;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        lengthValidator: new LengthValidator()
    });

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

    function AlphaNumericWithUnderscoreValidator() {
        var self = this;

        var alphaNumericWithUnderscoreRegex = /^[a-z0-9_]*$/i;


        self.validate = function(value, validationOptions) {
            validationOptions.pattern = alphaNumericWithUnderscoreRegex;
            return OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        alphaNumericWithUnderscoreValidator: new AlphaNumericWithUnderscoreValidator()
    });

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

    function UrlValidator() {
        var self = this;

        var urlRegExp = /^(http(s)?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w- ;,./?%&=]*)?$/;


        self.validate = function (value, validationOptions) {
            if (!value) {
                return true;
            }

            validationOptions.pattern = urlRegExp;
            return OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        urlValidator: new UrlValidator()
    });

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

    function ZipValidator() {
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var zipRegExpUs = /^\d{5}(-\d{4})?$/;
        var zipRegExpCanada =
            /^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\ ?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/;

        var usCode = 1;
        var canadaCode = 39;

        var defaultValidationOptions = {
            onlyIf: function () { return true; }
        };

        var normalizeValidationOptions = function (validationOptions) {
            var normalizedValidationOptions =
                $.extend({}, defaultValidationOptions, validationOptions);

            return normalizedValidationOptions;
        };

        self.validate = function (value, validationOptions) {
            if (!value) {
                return true;
            }

            validationOptions = normalizeValidationOptions(validationOptions);

            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (!validationOptions.onlyIf()) {
                return true;
            }

            if (validationOptions && validationOptions.countryId && validationOptions.countryId()) {
                var isUs = validationOptions.countryId() === usCode;
                var isCanada = validationOptions.countryId() === canadaCode;

                if (!isUs && !isCanada) {
                    return true;
                }

                validationOptions.pattern = isUs ? zipRegExpUs : zipRegExpCanada;
                return OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
            }

            return true;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        zipValidator: new ZipValidator()
    });

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

    function PhoneValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var phoneRegExp = /^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/i;

        self.validate = function (value, validationOptions) {
            
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            validationOptions.pattern = phoneRegExp;
            if (validationOptions && validationOptions.countryID && validationOptions.countryID() == 1) {
                return OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
            }
            return true;
        };
    }
    
    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        phoneValidator: new PhoneValidator()
    });

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

    function StateValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        self.validate = function (value, validationOptions) {
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (!validationOptions.onlyIf()) {
                return true;
            }

            if (validationOptions && validationOptions.countryId && validationOptions.countryId()) {
                var state = validationOptions.states.filter(function(s) { return s.id === value })[0];

                return state && 
                    ((state.countryId === 0 && validationOptions.countryId() !== 1 && validationOptions.countryId() !== 39) ||
                        state.countryId === validationOptions.countryId());
            }
            return true;
        };
    }
    
    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        stateValidator: new StateValidator()
    });

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

    function SsnValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        // ONLINE-4287: https://stackoverflow.com/a/1517044

        var ssnRegex =
            /^(?!(000|666))[0-8]{1}[0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$/;
        var ssnLength = {
            max: 11
        };
        
        self.validate = function (value, validationOptions) {
            
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            validationOptions.length = ssnLength;
            validationOptions.pattern = ssnRegex;

            var isValid = true;
            isValid = isValid
                && OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions)
                && OnlineApp.Validation.lengthValidator.validate(value, validationOptions);

            if (OnlineApp.ViewModels.applicationViewModel.definitionsViewModel &&
                OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.invalidSsnValues) {                
                isValid = isValid
                    && OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.invalidSsnValues.indexOf(value) === -1;
            }
            return isValid;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        ssnValidator: new SsnValidator()
    });

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

    function ServerSsnValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        self.validate = function (value, validationOptions) {
            
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            var isSsnValid = ko.utils.unwrapObservable(validationOptions.isSsnValid);

            var isValid = true;

            isValid = isValid && isSsnValid;

            return isValid;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        serverSsnValidator: new ServerSsnValidator()
    });

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

    function SalaryValidator() {
        
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var salaryRegex = /^\$?\d{1,15}(,?\d{1,3})*(\.\d{1,2})?\$?$/;
        var salaryLength = {
            max: 22
        };
        var MAX_SALARY_VALUE = 100000000000000;

        self.validate = function (value, validationOptions) {
            
            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            validationOptions.pattern = salaryRegex;
            validationOptions.length = salaryLength;

            var isValid = true;
            isValid = isValid && OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
            isValid = isValid && OnlineApp.Validation.lengthValidator.validate(value, validationOptions.length);

            if (value != undefined && value !== "") 
            {
                isValid = isValid && MAX_SALARY_VALUE > +(value.replace(/,/g, '').replace('$', ''));
            }

            return isValid;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        salaryValidator: new SalaryValidator()
    });

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

    function DefinitionAwareValueValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            if (!value) {
                return true;
            }

            var items = ko.unwrap(validationOptions.definitionItems) || [];
            var fieldName = ko.unwrap(validationOptions.definitionFieldName) || 'id';

            var matchingItems = $.grep(items, function (item) {
                return item[fieldName] == value;
            });

            return matchingItems.length;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        definitionAwareValueValidator: new DefinitionAwareValueValidator()
    });

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

    function DeferredDefinitionAwareValueValidator() {
        var self = this;

        self.validate = function (value, validationOptions) {
            var deferredDefinitionViewModel = validationOptions.deferredDefinitionViewModel;
            var items = ko.unwrap(deferredDefinitionViewModel.items);
            var fieldName = ko.unwrap(validationOptions.definitionFieldName) || 'id';

            if (!value || deferredDefinitionViewModel.get().state() === 'pending') {
                return true;
            }

            var matchingItems = $.grep(items, function (item) {
                return item[fieldName] == value;
            });

            return matchingItems.length;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        deferredDefinitionAwareValueValidator: new DeferredDefinitionAwareValueValidator()
    });

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

    // Thanks to author of : https://github.com/iHwy/jQuery-Validation-Extension
    function mod10Check(number){
        var checksum = 0,
            j = 1, i;

        var calc;
        for (i = number.length - 1; i >= 0; i--) {
            calc = Number(number.charAt(i)) * j;
            if (calc > 9) {
                checksum = checksum + 1;
                calc = calc - 10;
            }

            checksum = checksum + calc;

            if (j == 1) {
                j = 2;
            } else {
                j = 1;
            };
        }

        if (checksum % 10 != 0) {
            // not mod-10
            return false;
        } else
            return true;
    }

    function CreditCardNumberValidator() {
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        //dictionary of regular expresisons for credit card types
        var creditCardNumbersRegularExpressions = [];
        //add American Express Credit Card Number regular expression
        creditCardNumbersRegularExpressions[1] = /^(?:3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11})$/;
        //add Discover Credit Card Number regular expression
        creditCardNumbersRegularExpressions[2] = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/;
        //add MasterCard Credit Card Number regular expression
        creditCardNumbersRegularExpressions[3] = /^(?:5[1-5][0-9]{14})$/;
        //add Visa Credit Card Number regular expression
        creditCardNumbersRegularExpressions[4] = /^(?:4[0-9]{15})$/;

        self.validate = function (value, validationOptions) {
            var isValid = true;

            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            var currentCardType = ko.unwrap(validationOptions.cardType),
                filteredNumber = value.replace(/[\s-]/g, ""); // removing spaces and dashes

            if (currentCardType != null && creditCardNumbersRegularExpressions[currentCardType] != null) {
                validationOptions.pattern = creditCardNumbersRegularExpressions[currentCardType];
                isValid = OnlineApp.Validation.regularExpressionValidator.validate(filteredNumber, validationOptions);
            }

            if (isValid) {
                isValid = mod10Check(filteredNumber);
            }

            return isValid;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        creditCardNumberValidator: new CreditCardNumberValidator()
    });

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

    function CsvValidator() {
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var americanExpressCsvRegularExpression = /^(?:[0-9]{4})$/,
            threeCharsCsvRegularExpression = /^(?:[0-9]{3})$/;

        self.validate = function (value, validationOptions) {
            var isValid = true;

            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            var currentCardType = ko.unwrap(validationOptions.cardType);

            if (currentCardType != null) {
                if (currentCardType == 1) {
                    validationOptions.pattern = americanExpressCsvRegularExpression;
                } else {
                    validationOptions.pattern = threeCharsCsvRegularExpression;
                }

                isValid = isValid && OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
            }

            return isValid;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        csvValidator: new CsvValidator()
    });

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

    function DisallowHtmlValidator() {

        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var xssRegex = /<[a-zA-Z]+/;

        self.validate = function (value, validationOptions) {
            validationOptions.pattern = xssRegex;
            
            if (!value){
                return true;
            }

            return !OnlineApp.Validation.regularExpressionValidator.validate(value, validationOptions);
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        disallowHtmlValidator: new DisallowHtmlValidator()
    });

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

    function CompositeValidator() {
        var self = this;

        self.validate = function(value, validationOptions) {

            var validatorDefinition = validationOptions.validators;
            var validators = Object.keys(validatorDefinition).map(function(validatorDefinition) {
                var validatorExtension = OnlineApp.Validation.validationExtensions[validatorDefinition];
                var validatorOptions = $.extend({}, validatorExtension.defaultOptions, validatorDefinition.validatorOptions);
                return {
                    validate: validatorExtension.validator.validate, 
                    validatorOptions: validatorOptions 
                };
            });

            var isValid = false;

            if (validationOptions.operator === 'and'){
                isValid = validators.every(function(validator) {
                    return validator.validate(value, validator.validatorOptions);
                });
            }
            else {
                isValid = validators.some(function(validator) {
                    return validator.validate(value, validator.validatorOptions);
                });
            }

            return isValid;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        compositeValidator: new CompositeValidator()
    });

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

    function MinValueValidator() {
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var defaultValidationOptions = {
            min: 1,
            validationMessage: 'Value must be greater than 0.',
            onlyIf: function () { return true; }
        };

        var normalizeValidationOptions = function (validationOptions) {
            var normalizedValidationOptions =
                $.extend({}, defaultValidationOptions, validationOptions);
            return normalizedValidationOptions;
        };

        self.validate = function (value, validationOptions) {
            validationOptions = normalizeValidationOptions(validationOptions);

            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (!validationOptions.onlyIf()) {
                return true;
            }

            if (value == null || value === '') return true;
            return parseFloat(value) >= validationOptions.min;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        minValueValidator: new MinValueValidator()
    });

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

    function MaxDigitsValidator() {
        var self = OnlineApp.Validation.BaseValidator.apply(this, arguments) || this;

        var defaultValidationOptions = {
            max: 4,
            validationMessage: 'Value cannot have more than 4 digits.',
            onlyIf: function () { return true; }
        };

        var normalizeValidationOptions = function (validationOptions) {
            var normalizedValidationOptions =
                $.extend({}, defaultValidationOptions, validationOptions);
            return normalizedValidationOptions;
        };

        self.validate = function (value, validationOptions) {
            validationOptions = normalizeValidationOptions(validationOptions);

            if (!self.isEnabled(validationOptions)) {
                return true;
            }

            if (!validationOptions.onlyIf()) {
                return true;
            }

            if (value == null || value === '') return true;
            var digits = value.toString().replace(/[^0-9]/g, '');
            return digits.length <= validationOptions.max;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        maxDigitsValidator: new MaxDigitsValidator()
    });

})(window);
;
(function (window, undefined) {
    'use strict';

    /*
        Registration of actual extensions.
    */
    var VALIDATION_MESSAGES = {
        required: "Error: This field is required",
        invalidEmail: "Email is invalid",
        invalidTwoStepVerificationCode: "Invalid code",
        invalidEmailVerificationCode: "Invalid verification code",
        invalidPassword: "Invalid password",
        invalidUrl: "Invalid url address",
        invalidNumeric: "Value is not a valid number",
        invalidZip: "Invalid Zip/Postal Code",
        invalidLength: "The text is too long",
        invalidSsn: "Invalid Social Security Number",
        invalidSalary: 'Invalid Salary',
        invalidConfirmation: 'Fields do not match',
        invalidPhone: 'Invalid phone number',
        invalidYear: 'Invalid year',
        invalidMonth: 'Invalid month',
        invalidCreditCardNumber: 'Invalid Credit Card Number',
        invalidCsv: 'Invalid CVV',
        invalidDefinitionValue: 'Value is invalid',
        containHtml: 'Field can\'t contain html tags',
        state: 'State is invalid',
        captchaInvalidMessage: "Captcha is invalid",
        invalidClassSpecificationsSearchString: "Please select a "
    };


    var extensions = {
        required: {
            validator: OnlineApp.Validation.requiredValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.required
            }
        },
        regexp: {
            validator: OnlineApp.Validation.regularExpressionValidator
        },
        email: {
            validator: OnlineApp.Validation.emailValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidEmail
            }
        },
        verificationCode: {
            validator: OnlineApp.Validation.verificationCodeValidator,
            defaultOptions: {
                isValidationMessageVisible: false
            }
        },
        confirmField: {
            validator: OnlineApp.Validation.confirmFieldValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidConfirmation
            }
        },
        requiredField: {
            validator: OnlineApp.Validation.requiredFieldValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.required
            }
        },
        timespanStartIsNotAfterEnd: {
            validator: OnlineApp.Validation.timespanStartIsNotAfterEndValidator,
            defaultOptions: {
                isValidationMessageVisible: false
            }
        },
        isNotFutureDate: {
            validator: OnlineApp.Validation.isNotFutureDateValidator,
            defaultOptions: {
                isValidationMessageVisible: false
            }
        },
        password: {
            validator: OnlineApp.Validation.passwordValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidPassword
            }
        },
        url: {
            validator: OnlineApp.Validation.urlValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidUrl
            }
        },
        zip: {
            validator: OnlineApp.Validation.zipValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidZip
            }
        },
        numeric: {
            validator: OnlineApp.Validation.numericValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidNumeric
            }
        },
        length: {
            validator: OnlineApp.Validation.lengthValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidLength
            }
        },
        year: {
            validator: OnlineApp.Validation.yearValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidYear
            }
        },
        month: {
            validator: OnlineApp.Validation.monthValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidMonth
            }
        },
        extendedMonth: {
            validator: OnlineApp.Validation.extendedMonthValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidMonth
            }
        },
        monthWithNoExpiration: {
            validator: OnlineApp.Validation.monthWithNoExpirationValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidMonth
            }
        },
        alphaNumericWithUnderscore: {
            validator: OnlineApp.Validation.alphaNumericWithUnderscoreValidator
        },
        ssn: {
            validator: OnlineApp.Validation.ssnValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidSsn
            }
        },
        serverSsn: {
            validator: OnlineApp.Validation.serverSsnValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidSsn
            }
        },
        salary: {
            validator: OnlineApp.Validation.salaryValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidSalary
            }
        },
        minValue: {
            validator: OnlineApp.Validation.minValueValidator,
            defaultOptions: {
                validationMessage: 'Error: Enter a number greater than 0'
            }
        },
        maxDigits: {
            validator: OnlineApp.Validation.maxDigitsValidator,
            defaultOptions: {
                validationMessage: 'Value cannot have more than 4 digits.'
            }
        },
        maxValue: {
            validator: OnlineApp.Validation.maxValueValidator,
            defaultOptions: {}
        },
        phone: {
            validator: OnlineApp.Validation.phoneValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidPhone
            }
        },
        creditCardNumber: {
            validator: OnlineApp.Validation.creditCardNumberValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidCreditCardNumber
            }
        },
        csv: {
            validator: OnlineApp.Validation.csvValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidCsv
            }
        },
        definitionAwareValue: {
            validator: OnlineApp.Validation.definitionAwareValueValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidDefinitionValue
            }
        },
        deferredDefinitionAwareValue: {
            validator: OnlineApp.Validation.deferredDefinitionAwareValueValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.invalidDefinitionValue
            }
        },
        disallowHtml: {
            validator: OnlineApp.Validation.disallowHtmlValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.containHtml
            }
        },
        composite: {
            validator: OnlineApp.Validation.compositeValidator,
            defaultOptions: {}
        },
        state: {
            validator: OnlineApp.Validation.stateValidator,
            defaultOptions: {
                validationMessage: VALIDATION_MESSAGES.state
            }
        }
    };


    var validationExtender = new OnlineApp.Extensions.Knockout.KnockoutValidationExtender();
    validationExtender.registerExtensions(extensions);

    OnlineApp.Namespace.extend('OnlineApp.Validation', {
        validationExtensions: extensions,
        validationMessages: VALIDATION_MESSAGES
    });

})();
;
(function (window, undefined) {
    'use strict';

    function TabIndexService() {

        var self = this;

        var dataSaveTabIndex = 'save-tab-index',
            $skipToContentButton = $('#skip-to-content-button');

        var getSettings = function (settings) {
            settings = settings || {};

            if (settings.containerSelector) {
                settings.containerSelector = settings.containerSelector;
            } else {
                settings.containerSelector = gJobs.areaInfoService && gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.Career
                    ? "#main-container"
                    : '#body-container, #main-container,'
                    + '#footer, #footer-new, #sjobs-footer-new, .new-job-flyout, #skip-to-content-button,'
                    + '#last-focusable-element, #cookie-consent';
            }

            settings.tabIndexElementsSelector = settings.tabIndexElementsSelector || ':focusable, iframe';
            settings.useVisibilityFilter = settings.useVisibilityFilter || true;
            settings.hideSkipButton = settings.hideSkipButton || false;

            return settings;
        };

        self.disableTabIndex = function (settings) {
            settings = getSettings(settings);

            var tabIndexElements = $(settings.containerSelector).find(settings.tabIndexElementsSelector);

            if (settings.useVisibilityFilter) {
                tabIndexElements = tabIndexElements.filter(':visible');
            }

            if (settings.hideSkipButton) {
                tabIndexElements = $skipToContentButton.add(tabIndexElements);
            }

            tabIndexElements.each(function () {
                var element = $(this);

                var savedTabIndex = element.data(dataSaveTabIndex);
                if (savedTabIndex) {
                    return;
                }

                var tabIndex = element.attr('tabindex');

                if (tabIndex) {
                    element.data(dataSaveTabIndex, tabIndex);
                }

                element.attr("tabindex", -1);
                element.attr("aria-hidden", "true");
                $(".pager-container").attr("aria-hidden", "true");
            });
        };

        var excludeElementsFromRemovingTabIndex = function (element) {
            var excludedBaseURIs = ['inbox', 'resetpassword', 'recoverusername'];
            var excludedIds = ['applicant-menu-expander', 'login-menu-expander','close-job-alert'];

            var baseURI = element.baseURI.toLowerCase();
            var id = element.id;

            if (excludedBaseURIs.some(uri => baseURI.includes(uri)) || excludedIds.includes(id)) {
                return true;
            } else {
                return false;
            }
        }

        self.restoreTabIndex = function (settings) {
            settings = getSettings(settings);

            var tabIndexElements = $(settings.containerSelector).find(settings.tabIndexElementsSelector);

            if (settings.useVisibilityFilter) {
                tabIndexElements = tabIndexElements.filter(':visible');
            }

            var firstElement = tabIndexElements.get(0);

            tabIndexElements = $skipToContentButton.add(tabIndexElements);
           
            tabIndexElements.each(function () {
                var element = $(this);
                element.attr("aria-hidden", "false");
                $(".pager-container").attr("aria-hidden", "false");
                var tabIndex = element.data(dataSaveTabIndex);

                if (tabIndex) {
                    element.attr("tabindex", tabIndex);
                    element.removeData(dataSaveTabIndex);
                } else if (!element.is($skipToContentButton) && !excludeElementsFromRemovingTabIndex(element[0])) {
                    element.removeAttr("tabindex");
                }
            });

            if (firstElement) {
                if (firstElement.id != 'header-menu-action' && !excludeElementsFromRemovingTabIndex(firstElement)) {
                    firstElement.focus();
                }
            }
        };

    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        tabIndexService: new TabIndexService()
    });

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

    var ANTIFORGERY_ID = '__RequestVerificationToken';
    var API_URL_PREFIXES = ['/api/', '/user/', '/JobAlerts/updatePreference', '/JobAlerts/update'];

    var inputSelector = 'input[name="' + ANTIFORGERY_ID + '"]';

    function AntiForgeryService() {
        var self = this;

        self.updateToken = function () {
            return $.ajax({
                type: 'GET',
                url: '/antiForgery/updateToken',
                cache: false,
                success: function (data) {
                    var newToken = $(data).val();
                    $(inputSelector).val(newToken);
                }
            });
        };
    };

    AntiForgeryService.setupAjax = function () {
        var isMethodCsrfSafe = function (method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        };
        var isUrlSafe = function (url) {
            for (var i = 0; i < API_URL_PREFIXES.length; ++i) {
                if (url.indexOf(API_URL_PREFIXES[i]) === 0) {
                    return false;
                }
            }
            return true;
        };
        var extractAntiForgeryToken = function () {
            return $(inputSelector).val();
        };
        $.ajaxSetup({
            beforeSend: function (jqXhr, settings) {
                if (!isMethodCsrfSafe(settings.type) && settings.url && !isUrlSafe(settings.url)) {
                    var antiForgeryToken = extractAntiForgeryToken();
                    jqXhr.setRequestHeader(ANTIFORGERY_ID, antiForgeryToken);
                }
            }
        });
    };

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        antiForgeryService: new AntiForgeryService()
    });

    AntiForgeryService.setupAjax();

})(window);;
(function (window, undefined) {


    function AuthenticationService() {
        var self = this;

        /* private urls */
        var isLoggedInUrl = '/api/authenticate/isLoggedIn',
            loginUrl = '/api/authenticate/login',
            logoutUrl = '/api/authenticate/logout',
            registerUrl = '/api/authenticate/register',
            confirmExternalLoginUrl = '/oauth/confirmCredentials',
            isEmailAllowedUrl = '/api/authenticate/isEmailAllowed',
            getUserDataUrl = '/api/authenticate/getUserData',
            getAppSettingsUrl = '/api/applicationTemplate/GetAppSettings',
            getAllResumeTemplatesForJobSeekerUrl = '/api/applicationTemplate/GetAllResumeTemplatesForJobSeeker',
            canApplyForJobUrl = '/api/applicationTemplate/CanApplyForJob',
            checkEmployeeIdUrl = '/api/applicationTemplate/CheckEmployeeId';

        /* urls to be overridden from outer script */
        self.getHtmlTemplatesUrl = '/api/htmlTemplates/GetApplicationTemplates';
        self.getAccountSettingsPageHtmlTemplatesUrl = '/api/accountSettings/GetAccountSettingsPageTemplates';

        var isLoggedInCachedRequest = new gJobs.CachedAjaxRequest({
            type: 'GET',
            cache: false,
            url: isLoggedInUrl
        });

        var getUserDataCachedRequest = new gJobs.CachedAjaxRequest({
            type: 'GET',
            cache: false,
            url: getUserDataUrl
        });

        /* public methods */

        self.getUserData = function () {
            return getUserDataCachedRequest.send();
        }

        self.isLoggedIn = function () {
            return isLoggedInCachedRequest.send();
        };

        //Accepts either username or email address for login.
        self.login = function (username, password, captchaAnswer, options) {
            $(".form-signin").find("button[type=submit]").attr("aria-hidden", true);
            return $.ajax({
                type: 'POST',
                url: loginUrl,
                data: $.extend({
                    username: username,
                    password: password,
                    captchaAnswer: captchaAnswer,
                    returnUrl: self.getCurrentUrl()
                }, options)
            }).then(function (data) {

                if (window.showRedesignedUI) {
                    // Hide access membership section in search page if accessMembership is enabled for user
                    var hasToggleAccessMembershipSection = typeof window.toggleAccessMembershipSection === 'function';
                    var accessMembershipEnabled = data && data.jobSeeker && data.jobSeeker.accessMembershipEnabled;

                    if (hasToggleAccessMembershipSection && accessMembershipEnabled) {
                        window.toggleAccessMembershipSection(!data.jobSeeker.accessMembershipEnabled);
                    }
                }

                isLoggedInCachedRequest.resetCache();
                return OnlineApp.Services.antiForgeryService.updateToken().then(function () {
                    return data;
                });
            });
        };

        self.logout = function (options) {
            var deffered = $.Deferred();
            sessionStorage.removeItem("isTermsDeclined");
            sessionStorage.removeItem("isVettedLogin");
            localStorage.removeItem("isPopupOpen");
            localStorage.removeItem("istermsAndPrivacyPolicyDialogContainer");
            $.ajax({
                type: 'POST',
                url: logoutUrl,
                success: function (response) {
                    var data = response.data;

                    var isExternalLogin,
                        providerName;

                    if (data.isUserDeleted) {
                        isExternalLogin = options.isExternalLogin;
                        providerName = options.providerName;
                    }
                    else {
                        isExternalLogin = data.isExternalLogin;
                        providerName = data.providerName;
                    }

                    if (!isExternalLogin) {
                        deffered.resolve();

                        return;
                    }

                    switch (providerName) {
                        case 'Facebook':
                            FB.getLoginStatus(function facebookLogoutCallback(facebookResponse) {
                                if (facebookResponse.status !== 'connected') {
                                    deffered.resolve();

                                    return;
                                }

                                FB.logout(facebookLogoutCallback);
                            });

                            break;
                        default:
                            deffered.resolve();
                            break;
                    }
                }
            });

            removeItemFromLocalStorage("updatedEmail");
            removeItemFromLocalStorage(OnlineApp.LocalStorageKeys.EmailWasChanged);
            removeItemFromLocalStorage(OnlineApp.LocalStorageKeys.EmailWasChangedAndNewVerificationCodeSent);
            removeItemFromLocalStorage(OnlineApp.LocalStorageKeys.EmailWasVerified);
            removeItemFromSessionStorage(OnlineApp.SessionKeys.IsBannerWasClosedInCurrentSession);
            removeItemFromSessionStorage(OnlineApp.SessionKeys.ApplicationProcessUrl);
            isLoggedInCachedRequest.resetCache();
            return deffered;
        };

        self.register = function (username, password, email, captchaAnswer, options) {
            return $.ajax({
                type: 'POST',
                url: registerUrl,
                data: $.extend({
                    username: username,
                    password: password,
                    email: email,
                    captchaAnswer: captchaAnswer,
                    registrationLimitKey: localStorage.getItem("registrationLimitKey"),
                    returnUrl: self.getCurrentUrl()
                }, options)
            }).then(function (data) {
                return OnlineApp.Services.antiForgeryService.updateToken().then(function () {
                    return data;
                });
            });
        };

        self.confirmExternalLogin = function (username, password) {
            return $.ajax({
                type: 'POST',
                url: confirmExternalLoginUrl,
                data: {
                    username: username,
                    password: password
                }
            }).then(function (data) {
                return OnlineApp.Services.antiForgeryService.updateToken().then(function () {
                    return data;
                });
            });
        };

        self.isEmailAllowed = function (data) {
            return $.ajax({
                type: 'POST',
                url: isEmailAllowedUrl,
                data: data
            });
        };

        self.getUserData = function (resetCache) {
            if (resetCache) {
                getUserDataCachedRequest.resetCache();
            }
            return getUserDataCachedRequest
                .send()
                .then(function (response) {

                    var showAccessMembershipDialog = function () {
                        $(document).trigger(
                            Events.CommonEventsNames.ShowAccessMembershipDialog
                        );
                    }

                    var showTermsAndPrivacyPolicyDialog = function (closeCallBack) {
                        $(document).trigger(
                            Events.CommonEventsNames.ShowTermsAndPrivacyPolicyAnnouncement,
                            { closeCallback: closeCallBack }
                        );
                    }

                    var pageInfoService = AgencyPages.pageInfoService ? AgencyPages.pageInfoService : gJobs.pageInfoService;
                    var currentPage = pageInfoService.getCurrentPageType();
                    var isOnAccessMembershipLandingPage = currentPage === pageInfoService.getPageTypes().accessMembershipLandingPage;

                    if (isOnAccessMembershipLandingPage &&
                        response.data.showAccessMembership &&
                        !response.data.showTermsAndPrivacyPolicyAnnouncement) {
                        return response.data;
                    }
                    else if (response.data.showTermsAndPrivacyPolicyAnnouncement && response.data.showAccessMembership) {
                        showTermsAndPrivacyPolicyDialog(showAccessMembershipDialog);
                    } else if (response.data.showTermsAndPrivacyPolicyAnnouncement) {
                        showTermsAndPrivacyPolicyDialog();
                    } else if (response.data.showAccessMembership) {
                        showAccessMembershipDialog();
                    }

                    return response.data;
                });
        }

        self.getAppSettings = function (id) {
            return $.ajax({
                type: 'GET',
                url: getAppSettingsUrl,
                cache: false,
                data: { jobId: id }
            });
        };

        self.getAllResumeTemplatesForJobSeeker = function () {
            return $.ajax({
                type: 'GET',
                url: getAllResumeTemplatesForJobSeekerUrl,
                cache: false
            });
        };

        self.canApplyForJob = function (id) {
            return $.ajax({
                type: 'GET',
                url: canApplyForJobUrl,
                cache: false,
                data: { jobId: id }
            });
        };

        self.checkEmployeeId = function (id, employerFolderName) {
            return $.ajax({
                type: 'GET',
                url: checkEmployeeIdUrl,
                cache: false,
                data: {
                    employeeId: id,
                    employerFolderName: employerFolderName
                }
            });
        };

        self.getHtmlTemplates = function () {
            return $.ajax({
                type: 'GET',
                url: self.getHtmlTemplatesUrl,
                cache: true
            });
        };

        self.getAccountSettingsPageHtmlTemplates = function () {
            return $.ajax({
                type: 'GET',
                url: self.getHtmlTemplatesUrl,
                cache: true
            });
        };

        self.getCurrentUrl = function () {
            var currentUrl = encodeURIComponent(window.location.href);

            if (window.location.hash) {
                currentUrl = encodeURIComponent(window.location.href.split('#')[0]);
            }

            return currentUrl;
        };
    };

    function removeItemFromLocalStorage(key) {
        localStorage.removeItem(key);
    }

    function removeItemFromSessionStorage(key) {
        sessionStorage.removeItem(key);
    }

    OnlineApp.Namespace.extend('OnlineApp.Services.Test', {
        AuthenticationService: AuthenticationService
    });

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        authenticationService: new AuthenticationService()
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function AttachmentsService() {
        var self = this;

        self.setAttachmentFromHistory = function (jobId, attachmentTypeId, attachmentHistoryId) {
            return $.ajax({
                type: "POST",
                url: "/api/attachments/setAttachmentFromHistory",
                data: { jobId: jobId, attachmentTypeId: attachmentTypeId, attachmentHistoryId: attachmentHistoryId }
            });
        };

        self.deleteAttachment = function(jobId, attachmentId) {
            return $.ajax({
                type: "POST",
                url: "/api/attachments/deleteAttachment",
                data: { jobId: jobId, attachmentId: attachmentId }
            });
        };

        self.deleteSupplementalAttachment = function (jobApplicationId, attachmentId, jobId) {
            return $.ajax({
                type: "POST",
                url: "/api/attachments/deleteRequestedSupplementalAttachment",
                data: { jobId: jobId, attachmentId: attachmentId, jobApplicationId: jobApplicationId }
            });
        };
    };


    OnlineApp.Namespace.extend('OnlineApp.Services.Test', {
        AttachmentsService: AttachmentsService
    });

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        attachmentsService: new AttachmentsService()
    });

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

    function AuditService() {
        var self = this,
            endpoint = '/api/audit/';

        self.setCurrentStep = function (jobId, menuStep, jobTargetApplicantGuid, jobTargetUtmMedium) {
            return $.ajax({
                type: 'POST',
                url: endpoint + 'setCurrentStep',
                data: {
                    jobId: jobId,
                    menuStep: menuStep,
                    jobTargetApplicantGuid: jobTargetApplicantGuid,
                    jobTargetUtmMedium: jobTargetUtmMedium
                }
            });
        };

        self.setAction = function (jobId, menuStep) {
            return $.ajax({
                type: 'POST',
                url: endpoint + 'setAction',
                data: {
                    jobId: jobId,
                    menuStep: menuStep
                }
            });
        };
    };

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        auditService: new AuditService()
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function JobApplicationService() {
        var self = this,
            endpoint = '/api/jobapplication';

        self.addResumeTemplateToDraft = function (jobId, resumeTemplateId) {
            return $.ajax({
                type: 'POST',
                url: endpoint + '/addResumeTemplateToDraft',
                data: {
                    jobId: jobId,
                    resumeTemplateId: resumeTemplateId
                }
            });
        }

        self.getJobApplication = function (jobApplicationId) {
            if (!jobApplicationId) {
                toastr.warning("Parameter 'jobApplicationId' is required");
            }

            return $.ajax({
                type: 'GET',
                url: endpoint + '/getJobApplication',
                data: {
                    jobApplicationId: jobApplicationId
                }
            });
        };

        self.getActiveJobApplication = function (jobId) {
            return $.ajax({
                type: 'GET',
                url: endpoint + '/getActiveJobApplication',
                data: {
                    jobId: jobId
                }
            });
        };

        self.getActiveOrNewJobApplication = function (resumeTemplateId, jobId, employeeId, jobReferrer, departmentFolder) {
            var path = window.location.search;
            var searchPageRegex = /pagetype=searchPage/i;
            var isSearchPage = searchPageRegex.test(path);
            return $.ajax({
                type: 'GET',
                url: endpoint + '/getActiveOrNewJobApplication',
                data: {
                    resumeTemplateId: resumeTemplateId,
                    jobId: jobId,
                    employeeId: employeeId,
                    jobReferrer: jobReferrer,
                    pagetype: isSearchPage ? 'searchPage' : null,
                    departmentFolder: departmentFolder ? departmentFolder : null
                }
            });
        };

        self.startNewResumeTemplate = function () {
            return $.ajax({
                type: 'GET',
                url: endpoint + '/startNewResumeTemplate'
            });
        };
    };

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        jobApplicationService: new JobApplicationService()
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function DataServiceEndpoint(controller, settings) {

        // todo: discuss this approach of enabling-disabling endpoints
        var controllerSettings = {
            GET: settings && settings.GET !== undefined ? settings.GET : true,
            POST: settings && settings.POST !== undefined ? settings.POST : true,
            DELETE: settings && settings.DELETE !== undefined ? settings.DELETE : true,
            skipResumeTemplateId: settings && settings.skipResumeTemplateId !== undefined ? settings.skipResumeTemplateId : false
        };

        var self = this,
            endpointBase = ('/api/' + controller);

        self.pathname = controller;

        var toQueryString = function (object) {
            var queryStringSections = [],
                e = encodeURIComponent;

            for (var propertyName in object) {
                queryStringSections.push(e(propertyName) + "=" + e(object[propertyName]));
            }

            return queryStringSections.join("&");
        };

        if (controllerSettings.GET) {
            self.get = function (routeData, queryStringData, useCache) {
                var methodUrl = endpointBase;

                if (routeData != null) {
                    methodUrl += ('/' + routeData);
                }

                if (queryStringData != null) {
                    methodUrl += '?' + toQueryString(queryStringData);
                }

                return $.ajax({
                    url: methodUrl,
                    type: 'GET',
                    cache: useCache !== undefined ? useCache : true
                });
            };
        }

        if (controllerSettings.POST) {
            self.post = function (data, queryStringData) {
                var queryString = "";

                if (queryStringData) {
                    queryString = '?' + toQueryString(queryStringData);
                }

                return $.post(endpointBase + queryString, data);
            };
        }

        if (controllerSettings.DELETE) {
            self['delete'] = function (id, queryStringData) {
                var methodUrl = endpointBase + '/delete';

                if (id != null) {
                    methodUrl += "?id=" + id;
                }

                if (!controllerSettings.skipResumeTemplateId && OnlineApp.ViewModels.applicationViewModel.resumeTemplateViewModel) {
                    var resumeTemplateId = OnlineApp.ViewModels.applicationViewModel.resumeTemplateViewModel.resumeTemplateId();

                    if (resumeTemplateId != null) {
                        methodUrl += "&resumeTemplateID=" + resumeTemplateId;
                    }
                }

                if (queryStringData != null) {
                    var delimiter = (methodUrl.lastIndexOf('?') === -1) ? '?' : '&';
                    methodUrl += delimiter + toQueryString(queryStringData);
                }


                return $.ajax({
                    type: "DELETE",
                    url: methodUrl
                });
            };
        }

        self.action = function (actionName, data) {
            var methodUrl =
                (endpointBase + '/' + actionName);

            return $.post(methodUrl, data);
        };
    }

    function DataService() {
        var self = this;
        self.applicationData = new DataServiceEndpoint("applicationData/all");
        self.applicationDataForProfileSettings = new DataServiceEndpoint("applicationData/forProfileSettings");
        self.dataStorage = {};

        self.loadApplicationData = function (jobId, resumeTemplateId) {
            var promise = self.applicationData
                .get(undefined, { jobId: jobId, resumeTemplateId: resumeTemplateId })
                .done(function (data) {
                    self.dataStorage = data;
                })
                .fail(function () {
                    toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                });

            return promise;
        };

        self.loadApplicationDataForProfileSettings = function (resumeTemplateId) {
            var promise = self.applicationDataForProfileSettings
                .get(undefined, { resumeTemplateId: resumeTemplateId })
                .done(function (data) {
                    // todo: use separate storage
                    self.dataStorage = data;
                })
                .fail(function () {
                    toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                });

            return promise;
        };

        self.educations = new DataServiceEndpoint("education");
        self.workExperience = new DataServiceEndpoint("workExperience");

        /* Note: generalInfo endpoint is not linked to service directly */
        self.generalInfo = new DataServiceEndpoint("generalInfo");
        self.generalInfoAll = new DataServiceEndpoint("generalInfo/all");
        self.contactInfo = new DataServiceEndpoint("generalInfo/contactInfo");
        self.personalInfo = new DataServiceEndpoint("generalInfo/personalInfo");
        self.preferences = new DataServiceEndpoint("generalInfo/preferences");
        self.externalLoginInfo = new DataServiceEndpoint("generalInfo/externalLoginInfo");
        self.emailPreferences = new DataServiceEndpoint("generalInfo/emailPreferences", { cache: false });
        self.disability = new DataServiceEndpoint("disability");
        self.twoFactorAuthenticationPreferences = new DataServiceEndpoint("generalInfo/twoFactorAuthenticationPreferences");


        self.textMessagingPreferences = new DataServiceEndpoint("textMessagingPreferences");

        self.agencyWideQuestions = new DataServiceEndpoint("questions/agencyWide");
        self.supplementaryQuestions = new DataServiceEndpoint("questions/supplementary");
        self.convictionQuestions = new DataServiceEndpoint("questions/conviction");

        self.licenses = new DataServiceEndpoint("licenses");
        self.skills = new DataServiceEndpoint("skills");
        self.officeskill = new DataServiceEndpoint("additionalInfo/officeSkill");
        self.supplementalInfo = new DataServiceEndpoint("supplementalInfo");
        self.languages = new DataServiceEndpoint("languages");

        self.references = new DataServiceEndpoint("references");

        self.submit = new DataServiceEndpoint("submit");

        // Check before submission for payment
        self.checkBeforeSubmit = new DataServiceEndpoint("submitcheck/CheckAppForSubmission");
        self.checkPaymentType = new DataServiceEndpoint("payment/CheckPaymentType");

        self.setInitials = new DataServiceEndpoint("payment/UpsertUserInitialsOnSubmit");
        self.checkCaptcha = new DataServiceEndpoint("submitcheck/IsCaptchaRequiredForApplicationSubmission");
        self.validateCaptcha = new DataServiceEndpoint("submitcheck/ValidateCaptcha");

        self.changePassword = new DataServiceEndpoint("user/changePassword");

        self.compositeDefinitions = new DataServiceEndpoint("definitions/composite");
        self.PastFutureRange = new DataServiceEndpoint("definitions/PastFutureRange");
        self.InvalidSsnValues = new DataServiceEndpoint("definitions/InvalidSsnValues");
        self.sessionExpirationData = new DataServiceEndpoint("definitions/sessionExpirationData");

        self.updateAdSenseDisplayInfo = new DataServiceEndpoint("adsense/updateAdSenseDisplayInfo");

        self.accountSettingsData = new DataServiceEndpoint("accountSettingsData/getAccountSettingsData");

        // talent search
        self.talentSearchPreferences = new DataServiceEndpoint("talentSearchPreferences/talentSearchPreferences");

        self.definitions = {
            states: new DataServiceEndpoint("definitions/states"),
            countries: new DataServiceEndpoint("definitions/countries"),
            educationLevels: new DataServiceEndpoint("definitions/educationLevels"),
            schoolDegrees: new DataServiceEndpoint("definitions/schoolDegrees"),
            schoolTypes: new DataServiceEndpoint("definitions/schoolTypes"),
            languageSkills: new DataServiceEndpoint("definitions/languageSkills"),
            driversLicenseClasses: new DataServiceEndpoint("definitions/driversLicenseClasses"),
            highSchoolHighestLevels: new DataServiceEndpoint("definitions/highschoolhighestlevels"),
            supplementalInfoTypes: new DataServiceEndpoint("definitions/supplementalinfotypes")
        };

        self.attachments = new DataServiceEndpoint("attachments");

        self.exam = new DataServiceEndpoint("exam", {
            GET: true,
            POST: true,
            DELETE: true,
            skipResumeTemplateId: true
        });

        self.offer = new DataServiceEndpoint("offer");

        self.canvassForm = new DataServiceEndpoint("canvass");

        self.paymentInfo = new DataServiceEndpoint("paymentInfo");

        self.testData = new DataServiceEndpoint("testData");

        self.paymentType = new DataServiceEndpoint("payment/setPaymentType");
        self.creditCardPayment = new DataServiceEndpoint("payment/InitiatePaymentSessionTransfer");
        self.waiverForm = new DataServiceEndpoint("payment/deleteForm");

        self.paymentCategory = new DataServiceEndpoint("payment/setPaymentCategory");
        self.paymentTransactionInfo = new DataServiceEndpoint("payment/PaymentTransactionInfo");
        self.accessMembership = new DataServiceEndpoint("accessMembership");
    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        dataService: new DataService()
    });

})(window);;
(function (window, undefined) {

    function FileUploadService() {

        var self = this;


        self.uploadFormData = function (url, fileInput, progressHandler) {
            var $fileInput = $(fileInput);
            var formData = new FormData($fileInput[0].form);

            var promise = $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,

                xhr: function () {
                    var xhr = $.ajaxSettings.xhr();

                    if (xhr.upload) {
                        xhr.upload.addEventListener('progress', progressHandler, false);
                    }

                    return xhr;
                }
            });

            return promise;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.Services', {
        fileUploadService: new FileUploadService()
    });

})(window);;
(function (window, mixpanel, undefined) {
    'use strict';


    function AnalyticsService() {

        function _injectTrackingCode(token) {
            _injectMixpanelScript(token);
        };

        function _injectMixpanelScript(token) {
            /*
             *  Implementation copied "as is" from Mixpanel web page.
             */
            (function (e, b) {
                if (!b.__SV) {
                    var a, f, i, g; window.mixpanel = b; b._i = []; b.init = function (a, e, d) {
                        function f(b, h) { var a = h.split("."); 2 == a.length && (b = b[a[0]], h = a[1]); b[h] = function () { b.push([h].concat(Array.prototype.slice.call(arguments, 0))) } } var c = b; "undefined" !== typeof d ? c = b[d] = [] : d = "mixpanel"; c.people = c.people || []; c.toString = function (b) { var a = "mixpanel"; "mixpanel" !== d && (a += "." + d); b || (a += " (stub)"); return a }; c.people.toString = function () { return c.toString(1) + ".people (stub)" }; i = "disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" ");
                        for (g = 0; g < i.length; g++) f(c, i[g]); b._i.push([a, e, d])
                    }; b.__SV = 1.2; a = e.createElement("script"); a.type = "text/javascript"; a.async = !0; a.src = ("https:" === e.location.protocol ? "https:" : "http:") + '//cdn.mxpnl.com/libs/mixpanel-2.2.min.js'; f = e.getElementsByTagName("script")[0]; f.parentNode.insertBefore(a, f)
                }
            })(document, window.mixpanel || []);

            mixpanel.init(token);
        };

        function _getParametersFromUrl(url, parameters) {
            var queryString = {};
            var regex = /([^?=&]+)(=([^&]*))?/g;

            url.replace(regex, function ($0, $1, $2, $3) {
                var key = decodeURIComponent($1);
                var value = decodeURIComponent($3);

                if (!parameters || (parameters.indexOf(key) > -1)) {
                    queryString[key] = value;
                }
            });

            return queryString;
        };


        return {
            inject: function (token) {
                _injectTrackingCode(token);
            },

            trackPageView: function (url) {
                return;
            },

            trackCurrentPageView: function () {
                return;
            },

            trackEvent: function (action, data, callback) {
                if (mixpanel) {
                    mixpanel.track(action, data, callback || $.noop);
                }
            },

            trackEventWithUrlParameters: function (action) {
                this.trackEvent(action, _getParametersFromUrl(window.location.search));
            },

            setUserIdentity: function (identity) {
                if (mixpanel) {
                    mixpanel.identify(identity.userName);
                }
            },

            setUserInfo: function (user) {
                if (mixpanel) {
                    mixpanel.identify();

                    if (user.firstName) {
                        mixpanel.people.set('$first_name', user.firstName);
                    }

                    if (user.lastName) {
                        mixpanel.people.set('$last_name', user.lastName);
                    }

                    if (user.email) {
                        mixpanel.people.set('$email', user.email)
                    }
                }
            },

            registerUserIdentity: function (identity) {
                if (mixpanel) {
                    mixpanel.alias(identity.userName);

                    mixpanel.people.set({
                        userName: identity.userName,
                        '$first_name': identity.userName,
                        '$email': identity.email
                    });
                }
            },

            parametersFromUrl: function (url) {
                return _getParametersFromUrl(url);
            }
        };
    };


    OnlineApp.Namespace.extend('OnlineApp.Services', {
        analyticsService: new AnalyticsService()
    });

})(window, window.mixpanel);;
(function (window, undefined) {    
    'use strict';
    function EmailVerificationService() {
        var self = this;
                 
        var emailVerificationUrl = '/api/emailverification/verify',
            resendEmailVerificationCodeUrl = '/api/emailverification/resendEmail',
            getUserDataUrl = '/api/emailverification/getUserData',
            getRedirectLinkForSuccessfullEmailVerificationUrl = '/api/emailVerification/getRedirectLinkForSuccessfullEmailVerification',
            isEmailVerifiedUrl = '/api/emailVerification/isEmailVerified',
            trySendEmailVerificationCodeUrl = '/api/emailVerification/TrySendEmail',
            deactivateEmailVerificationCodeUrl = '/api/emailVerification/deactivateEmailVerificationCode',           
            updateEmailAddressByCredentialUrl = '/api/emailVerification/updateEmailAddressByCredential';

        function getAgencyFolderName() {
            var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();
            var currentArea = gJobs.areaInfoService.getCurrentArea();

            var agencyFolderName = "";

            if (currentArea !== abstractAreaInfoService.areaNames.GJobs) {
                agencyFolderName = AgencyPages.pageInfoService ?
                    AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                    gJobs.pageInfoService.getCurrentAgencyPageFolderName();
            }

            return agencyFolderName;
        }

        self.verifyEmail = function (jobSeekerVerificationCode, captchaAnswer, changedEmailAddressWasAdded) {
            return $.ajax({
                type: 'POST',
                url: emailVerificationUrl,
                data: {
                    jobSeekerVerificationCode: jobSeekerVerificationCode,
                    captchaAnswer: captchaAnswer,
                    changedEmailAddressWasAdded: changedEmailAddressWasAdded
                }
            });
        }

        self.resendEmailVerificationCode = function (captchaAnswer, changedEmailAddressWasAdded) {
            var agencyFolderName = getAgencyFolderName();

            return $.ajax({
                type: 'POST',
                url: resendEmailVerificationCodeUrl,
                data: {
                    captchaAnswer: captchaAnswer,
                    agencyFolderName: agencyFolderName,
                    changedEmailAddressWasAdded: changedEmailAddressWasAdded
                }
            });
        }

        self.getUserData = function () {
            return $.ajax({
                type: 'GET',
                url: getUserDataUrl
            });
        }

        self.trySendEmailVerificationCode = function () {
            var agencyFolderName = getAgencyFolderName();

            return $.ajax({
                type: 'GET',
                url: trySendEmailVerificationCodeUrl + "?agencyFolderName=" + agencyFolderName
            });
        }

        self.getRedirectLinkForSuccessfullEmailVerification = function () {
            return $.ajax({
                type: 'GET',
                url: getRedirectLinkForSuccessfullEmailVerificationUrl
            });
        }

        self.isEmailVerified = function () {
            return $.ajax({
                type: 'GET',
                url: isEmailVerifiedUrl
            });
        }

        self.deactivateEmailVerificationCode = function() {
            return $.ajax({
                type: 'POST',
                url: deactivateEmailVerificationCodeUrl
            });
        };

        
        self.updateEmailAddressByCredential = function(credential, emailAddress) {
            return $.ajax({
                type: 'POST',
                url: updateEmailAddressByCredentialUrl,
                data: {
                    credential: credential,
                    emailAddress: emailAddress
                }
                
            });
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        emailVerificationService: new EmailVerificationService()
    });

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

    function CaptchaService() {
        var self = this,
            endpoint = '/api/textCaptcha/';

        self.getCaptcha = function (keyForTextCaptchaAnswer) {
            var queryString = "";

            if (keyForTextCaptchaAnswer) {
                queryString = "?keyForTextCaptchaAnswer=" + keyForTextCaptchaAnswer;
            }

            return $.ajax({
                type: 'GET',
                url: endpoint + 'getCaptcha' + queryString
            });
        };

        self.isCaptchaRequiredForRegister = function() {
            return $.ajax({
                type: 'POST',
                url: endpoint + 'isCaptchaRequiredForRegister'
            });
        }

        self.isCaptchaRequiredForLogin = function () {
            return $.ajax({
                type: 'POST',
                url: endpoint + 'isCaptchaRequiredForLogin'
            });
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        captchaService: new CaptchaService()
    });

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

    function JobAlertService() {
        var self = this;

        var endpoint = '/JobAlerts/';
        var addJobAlertUrl = endpoint + 'save';
        var deleteJobAlertUrl = endpoint + 'delete';
        var getAllJobAlertsUrl = endpoint + 'getAll';
        var generateJobAlertAlreadyAddedViewUrl = endpoint + 'generateJobAlertAlreadyAddedView';
        var isJobAlertCanBeCreatedUrl = endpoint + 'isJobAlertCanBeCreated';
        var isJobAlertsEnabledUrl = endpoint + 'isJobAlertsEnabled';
        var generateNoFilterSetViewUrl = endpoint + 'generateNoFilterSetView';
        var getJobAlertEditModel = endpoint + 'getEditModel';
        var updateJobAlertEditModel = endpoint + 'updateJobAlertEditFilters';
        var updateJobAlertUrl = endpoint + 'update';
        var updateJobAlertPreferencesUrl = endpoint + 'updatePreferences';
        var isAccessMembershipEnabledUrl = '/api/accessMembership/isAccessMembershipEnabled';

        self.getAll = function () {
            return $.ajax({
                type: 'GET',
                url: getAllJobAlertsUrl,
                cache: false,
            }).done(function (response) {
                return response;
            })
        }

        self.addJobAlert = function (searchCriteria) {
            return $.ajax({
                type: 'POST',
                url: addJobAlertUrl,
                data: {
                    location: searchCriteria.Location,
                    organization: searchCriteria.Organization,
                    category: searchCriteria.Category,
                    salary: searchCriteria.MinimumSalary,
                    distance: searchCriteria.Distance,
                    keyword: searchCriteria.Keyword,
                    remoteWorkOptionId: searchCriteria.RemoteWorkOptionId,
                    remoteWorkOptionIds: searchCriteria.RemoteWorkOptionIds,
                    jobType: searchCriteria.JobType
                }

            });
        }

        self.updateJobAlert = function (searchCriteria) {
            return $.ajax({
                type: 'POST',
                url: updateJobAlertUrl,
                data: {
                    location: searchCriteria.Location,
                    organization: searchCriteria.Organization,
                    category: searchCriteria.Category,
                    salary: searchCriteria.MinimumSalary,
                    distance: searchCriteria.Distance,
                    keyword: searchCriteria.Keyword,
                    jobAlertId: searchCriteria.JobAlertId,
                    remoteWorkOptionId: searchCriteria.RemoteWorkOptionId,
                    remoteWorkOptionIds: searchCriteria.RemoteWorkOptionIds,
                    jobType: searchCriteria.JobType
                }
            });
        }

        self.updateJobAlertPreferences = function (sentJobAlertsFrequency, isJobAlertEnabled) {
            return $.ajax({
                type: 'POST',
                url: updateJobAlertPreferencesUrl,
                data: {
                    jobSeekerId: 0,
                    sentJobAlertsFrequency: sentJobAlertsFrequency,
                    isJobAlertEnabled: isJobAlertEnabled
                }
            });
        }

        self.getJobAlertEditModel = function (jobAlert) {
            return $.ajax({
                type: 'GET',
                url: getJobAlertEditModel,
                data: {
                    location: jobAlert.Location,
                    organization: jobAlert.Organizations,
                    category: jobAlert.Categories,
                    salary: jobAlert.MinimumSalary,
                    distance: jobAlert.MaxDistance || jobAlert.Distance,
                    keyword: jobAlert.Keyword,
                    jobAlertId: jobAlert.JobAlertId,
                    remoteWorkOptionId: jobAlert.RemoteWorkOptionIds && jobAlert.RemoteWorkOptionIds.length > 0 ? jobAlert.RemoteWorkOptionIds[0] : null,
                    remoteWorkOptionIds: jobAlert.RemoteWorkOptionIds,
                    jobType: jobAlert.JobTypes,
                    isSchoolJobs: jobAlert.SiteSource == 1 ? true : false,
                    isEditClicked: false
                }
            });
        }

        self.updateJobAlertEditModel = function (jobAlert) {
            return $.ajax({
                type: 'GET',
                url: updateJobAlertEditModel,
                data: {
                    location: jobAlert.Location,
                    organization: jobAlert.Organizations,
                    category: jobAlert.Categories,
                    salary: jobAlert.MinimumSalary,
                    distance: jobAlert.Distance,
                    keyword: jobAlert.Keyword,
                    jobAlertId: jobAlert.JobAlertId,
                    remoteWorkOptionId: jobAlert.RemoteWorkOptionId,
                    remoteWorkOptionIds: jobAlert.RemoteWorkOptionIds,
                    jobType: jobAlert.JobTypes
                }
            });
        }

        self.deleteJobAlert = function (jobAlertId, disableJobAlert, jobSeekerId) {
            return $.ajax({
                type: 'DELETE',
                url: deleteJobAlertUrl,
                data: {
                    jobAlertId: jobAlertId,
                    disableJobAlert: disableJobAlert,
                    jobSeekerid: jobSeekerId
                }
            });
        }

        self.generateJobAlertAlreadyAddedView = function () {
            return $.ajax({
                type: 'GET',
                url: generateJobAlertAlreadyAddedViewUrl
            });
        }

        self.generateNoFilterSetView = function (needsToApplySearchFilter) {
            return $.ajax({
                type: 'GET',
                url: generateNoFilterSetViewUrl,
                data: {
                    needsToApplySearchFilter: needsToApplySearchFilter
                }
            });
        }

        self.isJobAlertCanBeCreated = function (searchCriteria) {
            return $.ajax({
                type: 'GET',
                url: isJobAlertCanBeCreatedUrl,
                data: {
                    location: searchCriteria.location,
                    organization: searchCriteria.organization,
                    category: searchCriteria.category,
                    salary: searchCriteria.salary,
                    distance: searchCriteria.distance,
                    keyword: searchCriteria.keyword,
                    remoteWorkOptionId: searchCriteria.remoteWorkOptionId,
                    remoteWorkOptionIds: searchCriteria.remoteWorkOptionIds,
                    jobType: searchCriteria.jobType
                }
            });
        }

        self.isJobAlertsEnabled = function () {
            return $.ajax({
                type: 'GET',
                url: isJobAlertsEnabledUrl
            });
        }

        self.isAccessMembershipEnabled = function () {
            return $.ajax({
                url: isAccessMembershipEnabledUrl,
                type: 'GET',
                cache: false
            })
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        jobAlertService: new JobAlertService()
    });
})(window);;
(function (window, undefined) {
    'use strict';

    function SessionTrackingService() {
        var self = this;
        var defaults = {
            minutesSessionExpiration: 10,
            minutesBeforeWarning : 5
        }

        var authenticationEventNames = 'loginEvent registerEvent';

        var minutesSessionExpiration;
        var minutesBeforeWarning;
        var secondsKeepAliveInterval = 60;
        var logoutUrl;

        function initialize() {
            logoutUrl = OnlineApp.Services.pageContextService.getHomePageUrl();

            OnlineApp.Services.authenticationService
                .isLoggedIn()
                .done(function(data) {
                    if (data) {
                        activateTracking();
                    }
                })
                .always(function() {
                    $(document).one(authenticationEventNames, activateTracking);
                });
        }

        function logOutAction() {
            OnlineApp.Services.authenticationService.logout().done(function() {
                // Clear sessionStorage for jobIds and paginationData if present
                sessionStorage.removeItem('jobIds');
                sessionStorage.removeItem('paginationData');
                sessionStorage.removeItem('searchQuery');
                window.location.href = logoutUrl;
            });

            return true;
        }

        function setInitialValues(expirationData) {
            minutesSessionExpiration = expirationData.timeout;
            minutesBeforeWarning = expirationData.remainingTime;
        }

        function setDefaultValues() {
            minutesSessionExpiration = defaults.minutesSessionExpiration;
            minutesBeforeWarning = defaults.minutesBeforeWarning;
        }

        function activateTracking() {
            var secondsDelay = (minutesSessionExpiration - minutesBeforeWarning) * 60;
            var secondsRemaining = minutesBeforeWarning * 60;

            $(document).idleTimeout({
                idleTimeLimit: secondsDelay,
                dialogDisplayLimit: secondsRemaining,
                sessionKeepAliveTimer: secondsKeepAliveInterval,
                sessionKeepAliveUrl: Resources.EndpointUrls.KeepAlive,
                activityEvents: 'click keyup scroll wheel mousewheel',
                redirectUrl: false,
                customCallback: logOutAction,
                dialogText: Resources.NotificationMessages.SessionTimeoutExpires,
                dialogStayLoggedInButton: Resources.NotificationMessages.SessionTimeoutResume
            });
        }

        $(document).ready(function () {
            var definitionsViewModel = new OnlineApp.ViewModels.DefinitionsViewModel();

            definitionsViewModel.sessionExpirationData.get()
                .done(setInitialValues)
                .fail(setDefaultValues)
                .always(initialize);
        });
    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        sessionTrackingService: new SessionTrackingService()
    });

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

    var CANVASS_FORM_LINK_TEMPLATE =
        '<div class="submitted-canvass referred-candidate-submitted-form">' +
            '<span class="submitted-form-status">Canvass Submitted</span>' +
            '<div class="submitted-date"></div>' +
            '<div class="view-link">' +
                '<i class="ss-standard ss-view"></i>' +
                '<a class="canvass-link" href="#">' +
                    'View Canvass' +
                '</a>' +
            '</div>' +
        '</div>'
    ;

    function CanvassFlyoutService() {
        var self = this;

        self.openCanvassFormFlyout = function (canvassFormId, canvassFormFlyout, canvassViewModel) {      
            window.isCurrentOptionChecked = false;
            window.isValidCurrentPositions = false;
            self.getCanvassForm(canvassFormId)
                    .then(function (data) {
                        var originalTitle = window.document.title;
                        var releaseFocus = [];

                        window.document.title = originalTitle + ' – Canvass Form';

                        var $content = $('#canvass-flyout-content');
                        var $overlay = $('.canvass-flyout-overlay');
                        var $canvassFlyout = canvassFormFlyout.getView();
                        var $responsiveSignature = $('#responsive-signature');
                        var $closeButton = $canvassFlyout.find('.close');

                        ko.cleanNode($content[0]);
                        ko.cleanNode($responsiveSignature[0]);

                        self.setupCanvassFlyout(data.description, data.isReadOnly);

                        ko.applyBindings(canvassViewModel, $content[0]);
                        ko.applyBindings(canvassViewModel.signatureViewModel, $responsiveSignature[0]);
                        canvassViewModel.fromDataModel(data);

                        gJobs.skipToContentService.showOnNextTab();

                        canvassFormFlyout.setSubtitle(data.jobTitle);

                        canvassFormFlyout.open($(document.activeElement));
                        if (data.isReadOnly) {
                            gJobs.screenReadersService.setAriaLiveNotification('View Canvass form flyout is opened');
                        }
                        else {
                            gJobs.screenReadersService.setAriaLiveNotification('Canvass form flyout is opened');
                        }
                        
                        $('.popover-trigger').popover();

                        $overlay.add($closeButton).on('click', function () {
                            if (releaseFocus) {
                                releaseFocus[0]();
                                releaseFocus[1]();
                                releaseFocus = undefined;
                            }
                            gJobs.focusService.dontRestoreFocus = undefined;
                    
                            window.document.title = originalTitle;
                        });
                        releaseFocus[0] = gJobs.focusService.restrictFocus($canvassFlyout);
                        releaseFocus[1] = gJobs.flyoutTabService.restrictTabbing($canvassFlyout);
                        gJobs.focusService.dontRestoreFocus = true;
                        gJobs.focusService.enableFocusForBrowserControls();
                    })
                    .fail(function() {
                        toastr.error(Resources.NotificationMessages.EncounteredProblem);
                    });
        }

        self.closeCanvassFormFlyout = function () {            
            if (gJobs.areaInfoService.getCurrentArea() == gJobs.areaInfoService.areaNames.Career) {
                AgencyPages.canvassFlyout.close();
            } else {
                gJobs.applicationsPage ?
                    gJobs.applicationsPage.canvassFormFlyout.close() :
                    gJobs.searchPage.canvassFormFlyout.close();
            }
        }

        self.getCanvassForm = function (canvassFormId) {            
            window.isCurrentOptionChecked = false;
            window.isValidCurrentPositions = false;
            return OnlineApp.Services.dataService.canvassForm.get(canvassFormId)
                .then(function(canvassData) {
                    return $.extend(canvassData, {
                        isReadOnly: !!canvassData.dateAnswered
                    })
                });
        }

        self.setupCanvassFlyout = function(initialBody, isReadOnly) {
            var $canvassBody = $('#canvass-body .canvass-main-container').html(
                replaceCanvassFormPlaceholders(initialBody)
            );

            var requiredFields = $canvassBody.find('.required-fields-notification-wrapper')
            var asterisk = $canvassBody.find('.required-asterisk');
            if (gJobs.browserDetector.isMobileBrowser()) {
                $canvassBody.find('.general').find('.general .contacts, .general .department').unwrap();
                $canvassBody
                    .find('.container-body .logo, .container-body .department')
                    .wrapAll('<div class=\'company-general-info\'></div>');
            }

            if (isReadOnly) {
                // Hiding required areas for submitted canvass forms (ONLINE-7315)
                asterisk.replaceWith('');
                requiredFields.replaceWith('');
            } else {
                var isBuffalo = $canvassBody.find('.buffalo').length;
                if (!isBuffalo && isBuffalo <1) {

                    asterisk.removeClass('required-asterisk').addClass('required');
                    requiredFields
                        .replaceWith(
                            '<div class="required-description">' +
                            '<p>Fields marked with an asterisk (<span class="required">*</span>) are required</p>' +
                            '</div>'
                        );
                }
            }
        }

        self.changeCanvassFormStatus = function (canvassFormId, dateAnswered, jobTitle) {
            var $canvassFormLink = $('.canvass-container[data-canvass-id="' + canvassFormId + '"]');

            $canvassFormLink.html(CANVASS_FORM_LINK_TEMPLATE);
            $canvassFormLink.find('.submitted-date').text(dateAnswered);
            $canvassFormLink.find('.canvass-link').attr('aria-label', 'Click to view canvass submitted for ' + jobTitle);
        }

        function replaceCanvassFormPlaceholders (initialBody){
            var body = initialBody;

            body = body.replace('<%placeholder-questionnaire%>',
                '<!-- ko template: "Templates/Canvassing/CanvassQuestionnaire" --><!-- /ko -->'
            );
            
            body = body.replace('<%placeholder-questionnaire capacity="3"%>',
                '<!-- ko template: "Templates/Canvassing/BuffaloCanvassQuestionnaireForCurrentPosition" --><!-- /ko -->'
            );
           

            body = body.replace('<%placeholder-sign-form%>',
                '<!-- ko template: { name: "Templates/Canvassing/CanvassFormFields", afterRender: phoneFieldAfterRender } --><!-- /ko -->'
            );

            body = body.replace('<%placeholder-sign-form-with-date%>',
                '<!-- ko template: { name: "Templates/Canvassing/CanvassFormFieldsWithDate", afterRender: phoneFieldAfterRender } --><!-- /ko -->'
            );

            body = body.replace('<%placeholder-page-break%>',
                '<!-- ko template: "Templates/Canvassing/PageBreak" --><!-- /ko -->'
            );

            return body;
        }      

       
    }




    OnlineApp.Namespace.extend('OnlineApp.Services', {
        canvassFlyoutService: new CanvassFlyoutService()
    });

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

    function OfferFlyoutService() {
        var self = this;

        self.changeOfferStatus = function (offerId, isOfferAccepted) {
            var $offer = $('.offer-container[data-offer-id="' + offerId + '"]');

            var $submittedOffer = $offer.find('.inactive-offer');

            var offerStatus = isOfferAccepted
                ? 'Offer Accepted'
                : 'Offer Rejected';
            $submittedOffer.find('.submitted-form-status').text(offerStatus);

            var answerDate = OnlineApp.Helpers.DateTimeFormatter.getShortDate(new Date());
            $submittedOffer.find('.submitted-date').text(answerDate);

            $offer.find('.active-offer').addClass('hide');
            $submittedOffer.removeClass('hide');
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        offerFlyoutService: new OfferFlyoutService()
    });

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

    function BrowserDetector() {
        var self = this;

        self.isIE = function(excludeEdge) {
            var userAgent = window.navigator.userAgent;

            var msie = userAgent.indexOf('MSIE ');
            if (msie > 0) {
                // IE 10 or older => return version number
                return parseInt(userAgent.substring(msie + 5, userAgent.indexOf('.', msie)), 10);
            }

            var trident = userAgent.indexOf('Trident/');
            if (trident > 0) {
                // IE 11 => return version number
                var rv = userAgent.indexOf('rv:');
                return parseInt(userAgent.substring(rv + 3, userAgent.indexOf('.', rv)), 10);
            }

            if (!excludeEdge) {
                var edge = userAgent.indexOf('Edge/');
                if (edge > 0) {
                    // IE 12 (aka Edge) => return version number
                    return parseInt(userAgent.substring(edge + 5, userAgent.indexOf('.', edge)), 10);
                }    
            }

            // other browser
            return false;
        }

        self.isFirefox = function() {
            return window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
        }

        self.isMobileSafari = function () {
            return navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/) ? true : false;
        }

        self.isMobileBrowser = function () {
            return /android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase())
        }
    };

    namespace('gJobs').browserDetector = new BrowserDetector();

})(window);
;
(function () {

    function CustomLabelService() {

        var self = this;

        self.updateCustomLabels = function ($container, customLabels) {
            var $labelledElements = $container.find('[data-custom-label-key][data-custom-label-type]');
            $labelledElements.each(function (index, element) {
                var $element = $(element);
                var key = $element.data('custom-label-key');
                var type = $element.data('custom-label-type');
                var text = customLabels[key][type];
                if (text) {
                    $element.text(text);
                }
            });
        }
    }

    namespace('gJobs').customLabelService = new CustomLabelService();
})();;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').subjects = {
        EmailUpdated: 'emailUpdated'
    }

    namespace('gJobs').crossWindowCommunicationService = {
        _initialized: false,

        // { subject: string, messageReceivedCallback: function }
        _handlers: [],

        _init: function () {
            var self = this;
            this._initialized = true;
            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
            var eventer = window[eventMethod];
            var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

            eventer(messageEvent, function (e) {
                if (window.location.origin != event.origin) {
                    return;
                }

                var key = e.message ? "message" : "data";
                var data = e[key];

                var handler = self._handlers.filter(function (handler) {
                    return handler.subject == data.subject;
                })[0];

                if (handler != null && typeof handler.messageReceivedCallback === 'function') {
                    handler.messageReceivedCallback(data.message);
                }
            }, false);
        },

        sendMessage: function (subject, message) {
            var opener = window.opener;
            if (opener != null) {
                opener.postMessage({ subject: subject, message: message }, '*');
            }
        },

        setListener: function (subject, callback) {
            if (!this._initialized) {
                this._init();
            }

            this._handlers.push({ subject: subject, messageReceivedCallback: callback });
        }
    }
})(window);;
(function (window, undefined) {
    'use strict';

    function AnalyticsHub() {

        function on(eventName, eventSource, listener) {
            if (arguments.length < 3) {
                listener = arguments[1];
                eventSource = null;
            }


            if (eventSource) {
                $(document).on(eventName, eventSource, listener);
            }
            else {
                $(document).on(eventName, listener);
            }
        }


        function listenForLogin() {
            on(OnlineApp.Events.CommonEventsNames.Login, function (e, data) {
                OnlineApp.Services.analyticsService.setUserIdentity(data.identity);
                OnlineApp.Services.analyticsService.trackEvent('Login', {
                    isInJobContext: data.isInJobContext
                });

                // We do that in order to obtain contact info as soon as user login.
                var contactInfo = new OnlineApp.ViewModels.ContactInfoViewModel({ get: 'contactInfo' });
                contactInfo.load(true);
            });
        }

        function listerForRegister() {
            on(OnlineApp.Events.CommonEventsNames.Register, function (e, data) {
                OnlineApp.Services.analyticsService.registerUserIdentity(data.identity);
                OnlineApp.Services.analyticsService.trackEvent('Account Created', {
                    isInJobContext: data.isInJobContext
                });
            });
        }

        function listenForRegisterLinkClicked() {
            on(OnlineApp.Events.CommonEventsNames.RegisterAccountLinkClicked, function (e, sourceEvent) {
                var isInJobContext = ($(sourceEvent.target).parents('.onlineapp-app-container').length > 0);

                OnlineApp.Services.analyticsService.trackEvent('Create Account (link clicked)', {
                    isInJobContext: isInJobContext
                });
            });
        }

        function listenForContactInformationAvailable() {
            on(OnlineApp.Events.CommonEventsNames.ContactInfomationAvailable, function (e, user) {
                OnlineApp.Services.analyticsService.setUserInfo(user);
            });
        }

        function listenForApplicationSubmit() {
            on(OnlineApp.Events.CommonEventsNames.ApplicationSubmit, function () {
                OnlineApp.Services.analyticsService.trackEvent('Application Received');
            });
        }

        function listenForResumeImportComplete() {
            on(OnlineApp.Events.CommonEventsNames.ResumeImportComplete, function (e) {
                var method;

                switch (e.source) {
                    case 'fileUpload':
                        method = 'Resume Import';
                        break;

                    case 'skipSection':
                        method = 'Profile Created without Import';
                        break;
                }

                var isInJobContext = (e.application === 'Application');

                OnlineApp.Services.analyticsService.trackEvent('Profile Created', {
                    method: method,
                    isInJobContext: isInJobContext
                });
            });
        }

        function listenForCertifyAndSubmitVisible() {
            on('show', 'a[href="#submit-tab"]', function () {
                OnlineApp.Services.analyticsService.trackEvent('Certify & Submit');
            });
        }

        function listenForPasswordResetLinkClickedFromEmail() {
            on(OnlineApp.Events.CommonEventsNames.ResetPasswordClicked, function (e, referrer) {
                if (!referrer.match(location.origin)) {
                    OnlineApp.Services.analyticsService.trackEvent('Set New Password (link clicked)');
                }
            });
        }

        function listenForPasswordResetLinkClicked() {
            on('click', 'a[data-role="reset-password"]', function (e) {
                e.preventDefault();

                OnlineApp.Services.analyticsService.trackEvent('Reset Password (link clicked)', null, function () {
                    location.href = $(e.target).attr('href');
                });
            });
        }

        function listenForSetNewPasswordButtonClicked() {
            on('click', 'button[data-role="set-new-password"]', function (e) {
                e.preventDefault();

                OnlineApp.Services.analyticsService.trackEvent('New Password Set', null, function () {
                    $(e.target).parent('form').submit();
                });
            });
        }

        function listenForUserNameRecoveryLinkClicked() {
            on('click', 'a[data-role="recover-username"]', function (e) {
                e.preventDefault();

                OnlineApp.Services.analyticsService.trackEvent('Forgot Username (link clicked)', null, function () {
                    location.href = $(e.target).attr('href');
                });
            });
        }

        function listenForUserNameRecoveryButtonClicked() {
            on('click', 'button[data-role="recover-username"]', function () {
                OnlineApp.Services.analyticsService.trackEvent('Forgot Username (button clicked)');
            });
        }

        function listenForRecoverySuccess() {
            on(OnlineApp.Events.CommonEventsNames.PasswordReset, function (e, recoveryType) {
                var eventName;

                switch (recoveryType) {
                    case "reset-password":
                        eventName = 'Reset Password (email sent)';
                        break;

                    case "recover-username":
                        eventName = "Forgot Username (email sent)";
                        break;
                }

                OnlineApp.Services.analyticsService.trackEvent(eventName);
            });
        }


        /* turned off listeners to check perfomance issues on Release env
        (function () {
            listenForLogin();
            listerForRegister();
            listenForRegisterLinkClicked();
            listenForContactInformationAvailable();
            listenForApplicationSubmit();
            listenForResumeImportComplete();
            listenForCertifyAndSubmitVisible();
            listenForPasswordResetLinkClickedFromEmail();
            listenForPasswordResetLinkClicked();
            listenForSetNewPasswordButtonClicked();
            listenForUserNameRecoveryLinkClicked();
            listenForUserNameRecoveryButtonClicked();
            listenForRecoverySuccess();
        })(); */
    }


    OnlineApp.Namespace.extend('OnlineApp.Hubs', {
        analyticsHub: new AnalyticsHub()
    });

})(this);;
(function (window, undefined) {
    'use strict';

    /*
        Top-level abstract ViewModel base class.
    */
    function BaseViewModel() {
        var self = this;

        /*
            Makes provided event name unique to actual class.
         */
        self.scopeEventToClass = function (event) {
            return event + '.' + self.constructor.name;
        };

        /*
            Returns equalizes current instance of ViewModel based on passed ViewModel.
                Remark: This method is a template method and expects concrete implementation 
                        of fromDataModel in derived ViewModels. 
        */
        self.fromViewModel = function (viewModel) {
            var data = ko.toJS(viewModel);
            return self.fromDataModel(data);
        };


        /*
            Fills ViewModel properties based on specified data model. 
        */
        self.fromDataModel = function (dataModel) {
        };


        /*
            Converts ViewModel to plain JavaScript object.
        */
        self.toDataModel = function () {
            var jsonData = ko.toCleanJSON(self);
            return ko.utils.parseJson(jsonData);
        };

        /*
            Returns deep copy of ViewModel.
                Remark: This method is a template method and expects concrete implementation 
                        of fromDataModel in derived ViewModels.
        */
        self.clone = function () {
            if (typeof (self.fromDataModel) !== 'function') {
                return self;
            }

            var data = ko.toJS(self);

            var viewModel = new self.constructor();
            viewModel.fromDataModel(data);

            return viewModel;
        };
        
        self.isVisited = ko.observable(false).extend({ ignoreOnSerialization: true });
    }


    OnlineApp.Namespace.extend('OnlineApp.ViewModels.Base', {
        BaseViewModel: BaseViewModel
    });

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


    function ValidatableViewModel(config) {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        function registerFieldGroups(fieldGroupsConfig) {
            for (var fieldGroupName in fieldGroupsConfig) {

                if (fieldGroupsConfig.hasOwnProperty(fieldGroupName)) {
                    var fieldGroupConfig = fieldGroupsConfig[fieldGroupName];
                    registerFieldGroup(fieldGroupName, fieldGroupConfig);
                }
            }
        };

        function registerFieldGroup(fieldGroupName, fieldGroupConfig) {
            var fields = registerFields(fieldGroupConfig);
            registerFieldGroupValidationApi(fieldGroupName, fields);
        };

        function registerFields(fieldGroupConfig) {
            var registeredFields = {};

            for (var fieldName in fieldGroupConfig) {
                var fieldSettings = fieldGroupConfig[fieldName];
                var field = OnlineApp.Namespace.openRelative(self, fieldName);

                field.extend(fieldSettings);

                // Note: Subscribe to dependency observables to trigger dependent field validation
                if (fieldSettings.hasOwnProperty('dependsOn') && fieldSettings.dependsOn.length) {
                    fieldSettings.dependsOn.forEach(function(dependencyObservable) {
                        var currentField = field;
                        dependencyObservable.subscribe(function() {
                            currentField.validate();
                        });
                    });
                }

                registeredFields[fieldName] = field;
            }

            return registeredFields;
        };

        function registerFieldGroupValidationApi(fieldGroupName, fields) {
            var validate = function(suppressValidationErrors) {
                var isValid = true;

                for (var fieldName in fields) {
                    // Note: made validation be invoked for all fields and do not skip validation
                    //       when first invalid field was found
                    isValid = fields[fieldName].validate(suppressValidationErrors) && isValid;
                }

                return !isValid;
            };

            var fieldGroup = {
                validate: validate
            };

            self.hasErrorPureComputed = ko.computed({
                read: function () {
                    return validate(true);
                },
                deferEvaluation: true
            }).extend({ ignoreOnSerialization: true });

            self.validation.fieldGroups[fieldGroupName] = fieldGroup;
        };


        self.validation = {
            fieldGroups: {}
        };


        /*
            Determines whether current ViewModel has validation errors.
        */
        self.hasError = ko.observable(false).extend({ ignoreOnSerialization: true });


        self.showCheckValidationIcon = ko.computed(function() {
            return (self.isVisited() && !self.hasError()) ||
                (OnlineApp.ViewModels.applicationViewModel && OnlineApp.ViewModels.applicationViewModel.isShowAllValidationIcons
                    && OnlineApp.ViewModels.applicationViewModel.isShowAllValidationIcons() && !self.hasError());
        }).extend({ ignoreOnSerialization: true });

        self.showAlertValidationIcon = ko.computed(function () {
            return (self.isVisited() && self.hasError()) ||
                (OnlineApp.ViewModels.applicationViewModel &&
                 OnlineApp.ViewModels.applicationViewModel.isShowAllValidationIcons
                    && OnlineApp.ViewModels.applicationViewModel.isShowAllValidationIcons() && self.hasError());
        }).extend({ ignoreOnSerialization: true });

        /*
            Triggers validation for all field groups.
        */
        self.validate = function () {
            var isValid = true;

            for (var fieldGroupName in self.validation.fieldGroups) {
                isValid = !self.validation.fieldGroups[fieldGroupName].validate() && isValid;
            }

            if (self.editableItem !== undefined && self.editableItem() != null) {
                isValid = isValid && self.editableItem().validate();
            }

            if (self.hasDisability !== undefined && !self.hasDisability()) {
                isValid = false;
            }

            self.hasError(!isValid);

            return isValid;
        };

        /*
            Registers ViewModel fields with Validation Framework.
        */
        self.registerValidation = function (config) {
            registerFieldGroups(config);
        };


        /* Suppress all errors */
        self.suppressValidationErrorsFor = function(context) {
            var suppress = function (obj) {
                for (var field in obj) {
                    if (obj.hasOwnProperty(field) && obj[field] && field !== 'validation') {
                        if (obj[field].hasError != null) {
                            obj[field].hasError(false);

                            if (typeof obj[field].isValidationMessageVisible === 'function') {
                                obj[field].isValidationMessageVisible(false);
                            }
                        }

                        if (typeof obj[field] !== 'function' && !Array.isArray(obj[field])) {
                            suppress(obj[field]);
                        }
                    }
                }
            };

            suppress(context);
        };

        self.suppressValidationErrors = function () {
            self.hasError(false);

            self.suppressValidationErrorsFor(self);
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.ViewModels.Base', {
        ValidatableViewModel: ValidatableViewModel
    });


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

    /*
        Abstract ViewModel base class giving functionality of loading and saving.
    */

    function DataViewModel(config) {
        var dataService = OnlineApp.Services.dataService;

        var self = OnlineApp.ViewModels.Base.ValidatableViewModel.apply(this, arguments) || this;

        self.isBusy = ko.observable(false).extend({ ignoreOnSerialization: true });

        self.getPostDataKey = function () {
            return config.postDataKey;
        }

        var defaultEndpoints = {
            get: null,
            post: null
        };

        var callChildren = function(object, methodName) {
            for (var propertyName in object) {
                var child = object[propertyName];
                var method = child[methodName];

                if (child instanceof jQuery)
                {
                    continue;
                }

                if (typeof method === 'function') {
                    method.call(child);
                }
            }
        };

        /*
            Normalizes constructor parameters.
        */
        (function() {
            config = config || {};

            if (typeof config.endpoint === 'string') {
                config.endpoint = {
                    // todo: discuss this approach of enabling-disabling endpoints
                    // endpoints are enabled by default
                    get:    config.get    === undefined ? config.endpoint : config.get,
                    post:   config.post   === undefined ? config.endpoint : config.post,
                    'delete': config['delete'] === undefined ? config.endpoint : config['delete']
                };
            }

            config.endpoint =
                $.extend(defaultEndpoints, config.endpoint);
        })();

        var getQueryStringData = function() {
            var queryStringData = {};

            if (config.passResumeTemlateId && OnlineApp.ViewModels.applicationViewModel.resumeTemplateViewModel) {
                queryStringData.resumeTemplateId = OnlineApp.ViewModels.applicationViewModel.resumeTemplateViewModel.resumeTemplateId();
            }

            if (config.passJobId && OnlineApp.ViewModels.applicationViewModel.jobId) {
                queryStringData.jobId = OnlineApp.ViewModels.applicationViewModel.jobId();
            }
            
            if (config.passAgencyFolderName) {
                queryStringData.agencyFolderName =
                    AgencyPages.pageInfoService && AgencyPages.pageInfoService.getCurrentAgencyFolderName();
            }

            if (config.jobApplicationId !== undefined) {
                queryStringData.jobApplicationId = config.jobApplicationId;
            }

            queryStringData = $.isEmptyObject(queryStringData) ? undefined : queryStringData;

            return queryStringData;
        };

        var getRouteData = function() {
            return undefined;
        };

        var getPostData = function(viewModel) {
            var postData = {};

            if (config.passResumeTemlateId || config.passJobId || config.passAgencyFolderName || config.jobApplicationId !== undefined) {
                postData.model = viewModel;
            }

            if (config.passResumeTemlateId && OnlineApp.ViewModels.applicationViewModel.resumeTemplateViewModel) {
                postData.resumeTemplateId = OnlineApp.ViewModels.applicationViewModel.resumeTemplateViewModel.resumeTemplateId();
            }

            if (config.passJobId && OnlineApp.ViewModels.applicationViewModel.jobId) {
                postData.jobId = OnlineApp.ViewModels.applicationViewModel.jobId();
            }
            
            if (config.passAgencyFolderName) {
                postData.agencyFolderName = getAgencyFolderName();
            }

            if (config.jobApplicationId !== undefined) {
                postData.jobApplicationId = config.jobApplicationId;
            }

            postData = $.isEmptyObject(postData) ? undefined : postData;

            return postData;
        };

        function getAgencyFolderName() {
            if (AgencyPages.pageInfoService) {
                return AgencyPages.pageInfoService.getCurrentAgencyFolderName();
            }

            return AgencyPages.pageInfoService ?
                AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                gJobs.pageInfoService.getCurrentAgencyPageFolderName();
        }

        /*
            Loads data for ViewModel and its children.
        */
        self.load = function(forceLoadFromServer) {
            var success = function(data) {
                self.fromDataModel(data);
            };

            var fail = function() {
                console.log("Service unavailable: " + config.endpoint.get);
                toastr.warning(Resources.NotificationMessages.ServiceUnavailable);
            };

            var promise = $.when();

            if (config.endpoint.get) {
                if (forceLoadFromServer) {
                    OnlineApp.Helpers.layoutHelper.showOnlineAppInnerSpinner(true);
                    promise = dataService[config.endpoint.get]
                        .get(getRouteData(), getQueryStringData())
                        .fail(fail)
                        .done(success)
                        .always(function() {
                            OnlineApp.Helpers.layoutHelper.hideOnlineAppInnerSpinner(true);
                        });
                } else {
                    var path = dataService[config.endpoint.get].pathname.split('/');
                    var data = dataService.dataStorage;
                    for (var i = 0, length = path.length; i < length; i++) {
                        data = data[path[i]];
                    }

                    if (data) {
                        success(data);
                    } else {
                        fail();
                    }
                }
            }

            callChildren(self, 'load');

            return promise;
        };

        /*
            Saves data by pushing it to endpoint.
        */
        self.save = function(viewModel, bypassValidation, dontShowDefaultToastrMessage, queryStringData) {
            if (!bypassValidation && !self.validate()) {
                return null;
            }

            var promise;

            if (config.endpoint.post) {
                var postData = getPostData(viewModel) || viewModel;

                promise = OnlineApp.Helpers.ajaxResponseValidator.ensurePromiseFailsOnInvalidData(
                    dataService[config.endpoint.post].post(postData, queryStringData))
                    .fail(function (data) {
                        if (!dontShowDefaultToastrMessage) {
                            // loop through all server validation errors
                            if (data && data.responseText && JSON) {
                                var response = JSON.parse(data.responseText);
                                OnlineApp.Helpers.Notifications.showResponseMessages(response);
                            } else {
                                toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                            }
                        }
                    });
            }

            return promise;
        };

        /*
            Deletes item by id.
        */
        self['delete'] = function(id) {
            var promise;

            if (config.endpoint['delete']) {
                promise = OnlineApp.Helpers.ajaxResponseValidator.ensurePromiseFailsOnInvalidData(dataService[config.endpoint['delete']]['delete'](id))
                    .fail(function () {
                        toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                    });
            }

            return promise;
        };
    }


    OnlineApp.Namespace.extend('OnlineApp.ViewModels.Base', {
        DataViewModel: DataViewModel
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function EditableViewModel() {

        var self = OnlineApp.ViewModels.Base.DataViewModel.apply(this, arguments) || this;

        /* 
            Consider refactoring by moving this code to custom binding.
            No UI code should be seen in ViewModels according to MVVM.
        */
        function getParentContainerMetrics(child) {

            var $container = getParentContainer(child);

            if (!$container) {
                return null;
            }

            var metrics = {
                offset: $container.offset(),
                position: $container.position(),
                padding: parseInt($container.css('padding-top') || 0),
                containerScroll: $container??$container.scrollParent().scrollTop()
            };

            return metrics;
        }

        function getParentContainer(child) {
            if (!child) {
                return null;
            }

            var $container = $(child).closest('.edit-dialog');

            return $container;
        }

        var sendEndEditEvent = function (containerMetrics, $container, dontScrollAfterEditing) {
            var editCompleteEvent = jQuery.Event(OnlineApp.Events.CommonEventsNames.EditItemComplete);
            editCompleteEvent.targetMetrics = containerMetrics;
            editCompleteEvent.editableItemContainer = $container;
            editCompleteEvent.dontScrollAfterEditing = dontScrollAfterEditing;
            $(document).trigger(editCompleteEvent);
        };

        var dirtyFlag;
        var $mainContainer;

        self.editableItem = ko.observable();

        self.isInEditMode = ko.observable(false).extend({ ignoreOnSerialization: true });

        self.validateChanges = function () {
            if (self.editableItem() != null) {
                return self.editableItem().validate();
            }
           
            return true;
        };

        self.beginEdit = function (item, e, dontValidate, editModeOnly) {
            $mainContainer = $('[role="main"]');
            if ($mainContainer.length) {
                $mainContainer.removeAttr('role');
            }
            var editableItem = item.clone();

            item.isInEditMode(true);
            editableItem.isInEditMode(true);

            self.editableItem(editableItem);

            if (!dontValidate) {
                self.editableItem().validate();
            }

            dirtyFlag = new ko.dirtyFlag({
                editableItem: self.editableItem
            }, null, true);

            if (OnlineApp.Events) {
                $(document).trigger(
                    OnlineApp.Events.CommonEventsNames.EditableItemBeginEdit,
                    {
                        editEvent: e,
                        item: item,
                        editModeOnly: editModeOnly
                    });
            }  

            let $chosenContainer = $('.chzn-container');
            if ($chosenContainer && $chosenContainer.length > 0) {
                $chosenContainer.each(function (index, elem) {
                    if (elem) {
                        let element = $(elem).find('a').find('span');
                        if ($(element)[0]) {
                            let $element = $(element)[0].innerText;
                            $(elem).find('.chzn-results').attr('aria-label', $element);
                        }
                    }
                });
            }
        };

        self.endEdit = function (item) {
            if ($mainContainer && $mainContainer.length) {
                $mainContainer.attr('role', 'main');
            }            
            var editedItem = self.editableItem();

            item.isInEditMode(false);
            self.editableItem(null);

            return editedItem;
        };

        self.discardChanges = function (item, e) {
            // find container being edited, before e.target gets removed from DOM

            var target = e && e.target,
                cancelableItem = item || self,
                containerMetrics = getParentContainerMetrics(target),
                $editableItemContainer = getParentContainer(target).parent();

            self.endEdit(cancelableItem);

            if ((item) && (!item.accepted || item.accepted())) {
                sendEndEditEvent(containerMetrics, $editableItemContainer, e.dontScrollAfterEditing);
            }
        };

        self.saveChanges = function (item, e, queryStringData) {

            var target = e && e.target;

            function triggerValidationFailedEvent() {
                if (OnlineApp.Events) {
                    var validationFailedEvent =
                        jQuery.Event(OnlineApp.Events.CommonEventsNames.PreSaveValidationFailed);
                    validationFailedEvent.target = e.target;
                    $(document).trigger(validationFailedEvent);
                }
               
            }

            // Focus on an empty span to prevent focus lost in IE after section saving.
            if (gJobs.browserDetector.isIE()) {
                gJobs.screenReadersService.silenceScreenreader();
            }

            item.isBusy(true);

            if (typeof self.editableItem().validate === 'function') {
                if (!self.editableItem().validate()) {
                    item.isBusy(false);
                    triggerValidationFailedEvent();
                    return window.undefined;
                }
            }

            var editedItem = self.editableItem();
            var viewModelData = editedItem.toDataModel();

            return self.save(viewModelData, true /* skip validation, already validated */, null, queryStringData)
                .done(function (data) {
                    // find container being edited, before e.target gets removed from DOM

                    if (target) {
                        var containerMetrics = getParentContainerMetrics(target);
                        var $editableItemContainer = getParentContainer(target).parent();
                    }

                    item.fromViewModel(editedItem);
                    self.endEdit(item);

                    if (target) {
                        sendEndEditEvent(containerMetrics, $editableItemContainer);
                    }

                    if (data && data.payload && data.payload.isEmailChanged) {

                        if (!data.payload.isImpersonatedJobSeeker) {
                            OnlineApp.Services
                                .emailVerificationService
                                .getRedirectLinkForSuccessfullEmailVerification()
                                .done(function (response) {
                                    var data = response.data;

                                    if (data.redirectedLink !== "") {
                                        window.location = data.redirectedLink;
                                    }
                                });
                        } else {
                            window.location.reload();
                        }
                    }
                })
                .always(function () {
                    if (OnlineApp.Events) {
                        item.isBusy(false);
                    }
                });
        };

        self.isDataChanged = function () {
            return dirtyFlag && dirtyFlag.isDirty();
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels.Base', {
        EditableViewModel: EditableViewModel
    });
})(window);;
(function (window, undefined) {
    'use strict';

    function EditableCollectionViewModel() {

        var self = OnlineApp.ViewModels.Base.EditableViewModel.apply(this, arguments) || this;

        /* 
            Consider refactoring by moving this code to custom binding.
            No UI code should be seen in ViewModels according to MVVM.
        */
        function getAddButtonMetrics(child) {
            if (!child) {
                return null;
            }

            var $container = $(child).closest('.box-container');
            if (!$container) {
                return null;
            }

            var $addButton = $container.parent().parent().parent().find('.btn-app-add');
            if (!$addButton) {
                return null;
            }

            var metrics = {
                offset: $addButton.offset(),
                position: $addButton.position(),
                padding: parseInt($addButton.css('padding-top') || 0),
                containerScroll: $addButton ?? $addButton.scrollParent().scrollTop(),
                element: $addButton
            };

            return metrics;
        }


        function createItem() {
            var itemTemplate = self.itemTemplate(),
                newItem = new itemTemplate();

            // mark item as "not accepted" so that we can cancel its creation
            newItem.accepted = ko.observable(false);

            return newItem;
        };

        var sendRemoveItemEvent = function (e, index, itemsCount) {
            var editCompleteEvent = jQuery.Event(OnlineApp.Events.CommonEventsNames.RemoveItemComplete);
            editCompleteEvent.target = e.target;
            editCompleteEvent.index = index;
            editCompleteEvent.itemsCount = itemsCount;
            $(document).trigger(editCompleteEvent);
        };

        var sendItemRemovedEvent = function (index) {
            var itemRemovedEvent = jQuery.Event(OnlineApp.Events.CommonEventsNames.ItemRemoved);
            itemRemovedEvent.index = index;
            $(document).trigger(itemRemovedEvent);
        }

        self.items = ko.observableArray([]);
        self.sortedItems = ko.computed(function () { return self.items(); });

        self.hasUnsavedItem = ko.observable(false);

        self.itemsCount = ko.computed(function () {
            return self.items().length;
        });

        self.savedItemsCount = ko.computed(function () {
            // unsaved items are not tracked in items count
            var itemsCount =
                self.hasUnsavedItem()
                    ? self.itemsCount() - 1
                    : self.itemsCount();

            return itemsCount;
        });

        self.add = function () {
            var newItem = createItem();

            self.hasUnsavedItem(true);
            self.items.unshift(newItem);
            self.beginEdit(newItem, null, true);
        };

        self.saveChanges = (function (base) {
            return function (item) {
                var promise = base.apply(this, arguments);
                if (!promise) {
                    return window.undefined;
                }

                promise
                    .done(function (data) {
                        if (data && data.id) {
                            item.id(data.id);

                            self.hasUnsavedItem(false);

                            // mark item as "accepted" so that when we want to cancel our changes
                            // item won't be deleted from items collection
                            if (item.accepted) {
                                item.accepted(true);
                            }
                        }
                    });

                return promise;
            };
        })(self.saveChanges);

        self.discardChanges = (function (base) {
            return function (item, event) {
                var cancelChanges = function (item, event) {
                    var targetMetrics = getAddButtonMetrics(event.target);

                    base.apply(this, arguments);
                    if (item.accepted && !item.accepted()) {
                        var itemDiscardedEvent = jQuery.Event(OnlineApp.Events.CommonEventsNames.EditableCollectionItemDiscarded);
                        itemDiscardedEvent.item = item;
                        itemDiscardedEvent.targetMetrics = targetMetrics;
                        itemDiscardedEvent.dontScrollAfterEditing = event.dontScrollAfterEditing;
                        self.items.remove(item);
                        self.hasUnsavedItem(false);

                        $(document).trigger(itemDiscardedEvent);
                    }
                };

                if (!item && self.items) {
                    var cancelableItem = ko.utils.arrayFirst(self.items(), function (item) {
                        return item.isInEditMode();
                    });
                    cancelChanges(cancelableItem, event);
                } else {
                    cancelChanges(item, event);
                }
            };
        })(self.discardChanges);

        self.removeItem = function (item, e) {

            function successCallback() {
                var index = $.inArray(item, self.sortedItems());
                var length = self.items().length;
                
                // call delete service
                self['delete'](item.id())
                    .done(function () {
                        sendRemoveItemEvent(e, index, length);

                        // remove from collection
                        self.items.remove(item);

                        // clear editable item for EditableCollectionViewModel class
                        self.editableItem(null);

                        self.hasUnsavedItem(false);

                        sendItemRemovedEvent(index);
                    });
            }

            var tryRemoveEvent = jQuery.Event(OnlineApp.Events.CommonEventsNames.TryRemoveItem);
            tryRemoveEvent.successCallback = successCallback;

            $(document).trigger(tryRemoveEvent);
        };

        self.fromDataModel = function (data) {
            var viewModels = ko.utils.arrayMap(data, function (x) {
                var itemTemplate = self.itemTemplate(),
                    emptyItem = new itemTemplate();

                emptyItem.fromDataModel(x);

                return emptyItem;
            });

            self.items(viewModels);
        };

        /*
            Don't show remove btn when new item is added and being edited
        */
        self.isRemoveButtonVisible = function (item) {
            if (!item.accepted ||
                item.accepted && item.accepted() === true) {
                return true;
            }

            return false;
        };

        self.isInEditMode = ko.computed(function () {
            var isInEditMode = false;

            ko.utils.arrayForEach(self.items(), function (item) {
                if (item.isInEditMode()) {
                    isInEditMode = true;
                }
            });

            return isInEditMode;
        });

        self.validate = function () {
            var invalidItem;
            var items = self.items();

            invalidItem = ko.utils.arrayFirst(items, function (item) {
                return !item.validate();
            });

            return !invalidItem;
        };

        // TODO: we may refactor this
        self.hasError = ko.computed(function () {
            var isValid = self.validate();
            var hasError = !isValid;

            return hasError;
        });

        self.isDataChanged = (function (base) {
            return function () {
                if (self.editableItem()) {
                    return base();
                }
                return false;
            }
        })(self.isDataChanged);
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels.Base', {
        EditableCollectionViewModel: EditableCollectionViewModel
    });

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


    function CompositeEditableViewModel() {

        var self = OnlineApp.ViewModels.Base.EditableViewModel.apply(this, arguments) || this;


        var any = function (predicate) {
            var result = false;

            ko.utils.arrayForEach(self.parts(), function (part) {
                result = predicate(part) || result;
            });

            return result;
        };

        self.any = any;

        var all = function (predicate) {
            var result = true;

            ko.utils.arrayForEach(self.parts(), function (part) {
                result = predicate(part) && result;
            });

            return result;
        };

        self.all = all;

        self.parts = ko.observableArray([]);

        self.dirtyFlag = {};

        self.addPart = function (viewModel) {
            self.parts.push(viewModel);
        };

        self.addParts = function (viewModels) {
            ko.utils.arrayPushAll(self.parts(), viewModels);
            self.parts.valueHasMutated();
        };

        self.getParts = function () {
            return self.parts().slice(0);
        };

        self.beginEditAll = function () {
            var i = 0,
                editableItems = {};

            all(function (part) {
                part.beginEdit(part);
                editableItems[i++] = part.editableItem;
            });

            self.dirtyFlag = new ko.dirtyFlag(editableItems, null, true, false);
        };

        self.isInEditMode = ko.computed(function () {
            var isInEditMode = any(function (part) {
                return part.isInEditMode();
            });

            return isInEditMode;
        });


        self.hasError = ko.computed(function () {
            var hasError = any(function (part) {
                return part.hasError();
            });

            return hasError;
        });

        self.validate = function () {
            var isValid = all(function (part) {
                return part.validate();
            });

            return isValid;
        };

        self.validateChanges = function () {
            var isValid = all(function (part) {
                return part.validateChanges();
            });

            return isValid;
        };

        self.save = (function (base) {
            return function () {
                var postData = { };

                all(function (part) {
                    var editableItem = part.editableItem();
                    var postDataKey = part.getPostDataKey();

                    if (postDataKey) {
                        if (editableItem) {
                            postData[postDataKey] = editableItem.toDataModel();
                        } else {
                            postData[postDataKey] = null;
                        }
                    }
                });

                return base(postData, true);
            };
        })(self.save);

        self.saveChanges = function () {
            return self.save().done(function (response) {
                all(function (part) {
                    if (part.isInEditMode()) {
                        part.fromViewModel(part.editableItem());
                        part.endEdit(part);
                    }
                });

                return response;
            });
        };

        self.discardChanges = function (item, e) {
            all(function (part) {
                if (part.isInEditMode()) {
                    part.discardChanges(item, e);
                }
            });
        };

        self.isDataChanged = function () {
            var editableViewModel = this.parts().filter(
                function (part) {
                    return part.isInEditMode();
            })[0];

            return editableViewModel && editableViewModel.isDataChanged();
        }
    };


    OnlineApp.Namespace.extend('OnlineApp.ViewModels.Base', {
        CompositeEditableViewModel: CompositeEditableViewModel
    });

}());;
(function(window, undefined) {
    'use strict';

    function NameViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;

        self.firstName = ko.observable();
        self.middleName = ko.observable();
        self.lastName = ko.observable();
        self.formerName = ko.observable();
        self.fullName = ko.computed(function () {
            return ((self.firstName() || '') + ' ' + (self.lastName() || '')).trim();
        }).extend({ ignoreOnSerialization: true });

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }
            self.firstName(data.firstName);
            self.middleName(data.middleName);
            self.lastName(data.lastName);
            self.formerName(data.formerName);
        };
        self.normalize = function() {
            self.firstName($.trim(self.firstName()));
            self.middleName($.trim(self.middleName()));
            self.lastName($.trim(self.lastName()));
            self.formerName($.trim(self.formerName()));
        }
    }

    function AddressViewModel(prefix) {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;
        var fieldSettings = OnlineApp.FieldSettings || {};

        self.address1 = ko.observable();
        self.address2 = ko.observable();
        self.city = ko.observable();
        self.state = new StateViewModel();
        self.zipCode = ko.observable();
        self.country = new CountryViewModel();
        self.filteredStates = ko.observableArray([]);

        self.visible = function () {
            var visible = false;
            if (!prefix) {
                visible = (fieldSettings['address1'] === undefined || fieldSettings['address1'].visible)
                    || (fieldSettings['address2'] === undefined || fieldSettings['address2'].visible)
                    || (fieldSettings['city'] === undefined || fieldSettings['city'].visible)
                    || (fieldSettings['stateID'] === undefined || fieldSettings['stateID'].visible)
                    || (fieldSettings['countryID'] === undefined || fieldSettings['countryID'].visible)
                    || (fieldSettings['zip'] === undefined || fieldSettings['zip'].visible);
            } else if (prefix === 'education') {
                visible = (fieldSettings[prefix + 'City'] === undefined || fieldSettings[prefix + 'City'].visible)
                    || (fieldSettings[prefix + 'State'] === undefined || fieldSettings[prefix + 'State'].visible)
                    || (fieldSettings[prefix + 'Country'] === undefined || fieldSettings[prefix + 'Country'].visible);
            } else if (prefix === 'workExperience') {
                visible = (fieldSettings[prefix + 'Address'] === undefined || fieldSettings[prefix + 'Address'].visible)
                    || (fieldSettings[prefix + 'City'] === undefined || fieldSettings[prefix + 'City'].visible)
                    || (fieldSettings[prefix + 'State'] === undefined || fieldSettings[prefix + 'State'].visible)
                    || (fieldSettings[prefix + 'ZipCode'] === undefined || fieldSettings[prefix + 'ZipCode'].visible)
                    || (fieldSettings[prefix + 'Country'] === undefined || fieldSettings[prefix + 'Country'].visible);
            }
            return visible;
        }

        self.country.id.subscribe(function(value) {
            var states = OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.states.items();

            if (value && value !== 1 && value !== 39) {
                states = states.filter(function(s) { return s.countryId !== 1 && s.countryId !== 39 });
            } else if(value) {
                states = states.filter(function(s) { return s.countryId === value });
            }

            if (!states.filter(function(s) {return s.id === self.state.id()}).length) {
                self.state.id(undefined);
                self.state.name(undefined);
                self.state.abbrvState(undefined);
                self.state.countryId(undefined);
            }

            if (self.zipCode.validate && !self.zipCode.validate()) {
                self.zipCode(undefined);
            }

            self.filteredStates(states);
        });

        self.cityStateZip = ko.computed(function () {
            var city = '';
            var abbrvState = '';
            var zip = '';

            if (fieldSettings[prefix + 'City'] === undefined || fieldSettings[prefix + 'City'].visible) {
                city = self.city() || '';
            }

            if (fieldSettings[prefix + 'State'] === undefined || fieldSettings[prefix + 'State'].visible) {
                abbrvState = self.state != undefined ? self.state.abbrvState() || '' : '';
            }

            if (fieldSettings[prefix + 'ZipCode'] === undefined || fieldSettings[prefix + 'ZipCode'].visible) {
                zip = self.zipCode() || '';
            }

            return city
                + (city != '' && (abbrvState != '' || zip != '') ? ', ' : '')
                + abbrvState
                + (abbrvState != '' && zip != '' ? ' ' : '')
                + zip;
        }).extend({ ignoreOnSerialization: true });

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.filteredStates(OnlineApp.ViewModels.applicationViewModel.definitionsViewModel ?
                OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.states.items() :
                []);
            self.address1(data.address1);
            self.address2(data.address2);
            self.city(data.city);
            self.country.fromDataModel(data.country);
            self.state.fromDataModel(data.state);
            self.zipCode(data.zipCode);

            return self;
        };
    }

    function PhoneViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;

        self.primaryPhone = ko.observable();
        self.primaryPhoneExt = ko.observable();
        self.alternatePhone = ko.observable();
        self.alternatePhoneExt = ko.observable();

        var getPhoneWithExt = function (phone, ext) {
            return (phone || '')
                + (ext ? ' ext. ' + ext : '');
        };

        self.fullPrimaryPhone = ko.computed(function () {
            return getPhoneWithExt(self.primaryPhone(), self.primaryPhoneExt());
        }).extend({ ignoreOnSerialization: true });
        self.fullAlternatePhone = ko.computed(function () {
            return getPhoneWithExt(self.alternatePhone(), self.alternatePhoneExt());
        }).extend({ ignoreOnSerialization: true });

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }
            self.primaryPhone(data.primaryPhone);
            self.primaryPhoneExt(data.primaryPhoneExt);
            self.alternatePhone(data.alternatePhone);
            self.alternatePhoneExt(data.alternatePhoneExt);

            return self;
        };
    }

    function SupervisorViewModel(prefix) {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;
        var fieldSettings = OnlineApp.FieldSettings || {};

        self.name = ko.observable();
        self.title = ko.observable();
        self.fullName = ko.computed(function() {
            var name = '',
                title = '',
                fullName = '';

            if (fieldSettings[prefix + 'SupervisorName'] === undefined || fieldSettings[prefix + 'SupervisorName'].visible) {
                name = self.name() || '';
            }

            if (fieldSettings[prefix + 'SupervisorTitle'] === undefined || fieldSettings[prefix + 'SupervisorTitle'].visible) {
                title = self.title() || '';
            }

            if (name && title) {
                fullName = name + ', ' + title;
            }
            else if (!name || !title) {
                fullName = name || title || '';
            }

            return fullName;
        }).extend({ ignoreOnSerialization: true });

        self.visible = function() {
            return (fieldSettings[prefix + 'SupervisorName'] === undefined || fieldSettings[prefix + 'SupervisorName'].visible) ||
                   (fieldSettings[prefix + 'SupervisorTitle'] === undefined || fieldSettings[prefix + 'SupervisorTitle'].visible);
        }

        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.name(data.name);
            self.title(data.title);
        };
    }

    function CountryViewModel() {
        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        self.id = ko.observable();
        self.name = ko.observable();


        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.id(data.id);
            self.name(data.name);
        };
    }

    function SchoolTypeViewModel() {
        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        self.id = ko.observable();
        self.name = ko.observable();


        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.id(data.id);
            self.name(data.name);
        };
    }

    function StateViewModel() {
        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        self.id = ko.observable();
        self.abbrvState = ko.observable();
        self.name = ko.observable();
        self.countryId = ko.observable();


        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.id(data.id);
            self.abbrvState(data.abbrvState);
            self.name(data.name);
            self.countryId(data.countryId);
        };
    }

    function SchoolDegreeViewModel() {
        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        self.id = ko.observable();
        self.title = ko.observable();


        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.id(data.id);
            self.title(data.title);
        };
    }

    function HighSchoolHighestLevelViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;

        self.id = ko.observable();
        self.name = ko.observable();

        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.id(data.id);
            self.name(data.name);
        };
    }

    function SupplementalInfoTypeViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;

        self.id = ko.observable();
        self.name = ko.observable();

        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.id(data.id);
            self.name(data.name);
        };
    }


    /* View Models' Extenders */
    function PasswordExtender(ext) {
        var self = ko.observable('');
        if (ext) {
            self.extend(ext);
        }

        self.mismatchMessage = "Passwords don't match!";

        self.confirmPassword = ko.observable('').extend({ required: {} });
        self.isConfirmPasswordSelected = ko.observable(false);

        self.isPasswordConfirmed = ko.computed(function () {
            return self() === self.confirmPassword();
        });

        self.showPasswordMismatch = ko.observable(false);

        self.confirmPassword.subscribe(function () {
            var passwordMismatch = self.confirmPassword() && self() && self() != self.confirmPassword();
            self.showPasswordMismatch(passwordMismatch ? true : false); //so we enforce proper boolean value
        });

        self.validate = (function (baseValidate) {
            return function () {
                var isValid = baseValidate();

                var isConfirmed = self.confirmPassword.validate() && (self.confirmPassword() && self() && self.isPasswordConfirmed());
                self.showPasswordMismatch(!isConfirmed && self());
                self.isPasswordConfirmed.notifySubscribers();

                self.hasError(!isValid);

                return isValid;
            };
        })(self.validate);

        self.clearFields = function () {
            self("");
            self.hasError(false);

            self.confirmPassword("");
            self.confirmPassword.hasError(false);

            self.showPasswordMismatch(false);
        };

        return self;
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        Common: {
            NameViewModel: NameViewModel,
            AddressViewModel: AddressViewModel,
            PhoneViewModel: PhoneViewModel,
            SupervisorViewModel: SupervisorViewModel,
            CountryViewModel: CountryViewModel,
            SchoolTypeViewModel: SchoolTypeViewModel,
            StateViewModel: StateViewModel,
            SchoolDegreeViewModel: SchoolDegreeViewModel,
            HighSchoolHighestLevelViewModel: HighSchoolHighestLevelViewModel,
            SupplementalInfoTypeViewModel: SupplementalInfoTypeViewModel,

            PasswordExtender: PasswordExtender
        }
    });

})(window);;
(function (window, undefined) {
    'use strict';



    function SignatureViewModel() {
        var SIGNATURE_PAD_SELECTOR = '.signature-pad:visible';

        var SIGNATURE_TOOLBAR_HEIGHT = 50,
            SIGNATURE_TOOLBAR_WIDTH = 25,
            SIGNATURE_NAME_CONTAINER_HEIGHT = 41;

        var fullScreenChangeEvents = 'fullscreenchange mozfullscreenchange webkitfullscreenchange msfullscreenchange';

        var signaturePad;
        var canvas;

        var self = this;

        self.isMobile = gJobs.browserDetector.isMobileBrowser();

        self.signature = ko.observable('');

        self.isReadOnlyView = ko.observable(true);

        self.username = ko.observable('');
        self.dateAnswered = ko.observable('');

        self.isSignatureCompleted = ko.observable(false);
        self.isSignatureInEditMode = ko.observable(false);
        self.isSignatureInputed = ko.observable(false);

        self.isSignatureInEditModeMobile = ko.computed(function () {
            return self.isMobile && self.isSignatureInEditMode();
        });

        self.fromDataModel = function (signature, isReadOnlyView, dateAnswered, username) {
            self.signature(signature);
            self.isReadOnlyView(isReadOnlyView);

            if (username) {
                self.username(username);
            } else {
                loadUserName();
            }

            self.dateAnswered(dateAnswered);

            self.isSignatureInEditMode(false);
            self.isSignatureCompleted(false);
        }

        self.generateMobileSignatureClick = function () { };
        self.editSignatureClick = function () { };

        self.isSignatureInEditMode.subscribe(function (isInEditMode) {
            if (self.isMobile && !gJobs.browserDetector.isMobileSafari() && !isInEditMode) {
                goOutFullscreen();
                screen.orientation && screen.orientation.unlock();
            }
        });

        self.drawSignatureClick = function () {
            signaturePad.clear();
            signaturePad.on();
            self.isSignatureInputed(false);
        }

        self.generateSignatureClick = function () {
            signaturePad.clear();
            signaturePad.off();

            var canvasContext = canvas[0].getContext('2d');

            OnlineApp.Services.authenticationService.getUserData()
                .then(function (data) {
                    if (data.username) {
                        generateSignatureOnCanvas(canvasContext, data.username);
                    } else {
                        generateSignatureOnCanvas(canvasContext, self.username());
                    }
                    $("#aria-live-message-container").text('');
                    $("#aria-live-message-container").attr('aria-label', '');
                    setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Signature is Auto Generated.', $("#aria-live-message-container"), false, $('#generate-signature-button')); }, 300);    
                });

            self.isSignatureInputed(true);
        }

        self.clearSignatureClick = function () {
            $("#aria-live-message-container").text('');
            $("#aria-live-message-container").attr('aria-label', '');            
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Signature is cleared', $("#aria-live-message-container"), false, $("#btnClearSignature")); }, 300);  
        }

        self.generateMobileSignatureClick = function () {
            var newCanvas = $('<canvas width="496" height="150"/>')[0];

            OnlineApp.Services.authenticationService.getUserData()
                .then(function (data) {
                    var canvasContext = newCanvas.getContext('2d');
                    clearCanvas(canvasContext);

                    generateSignatureOnCanvas(canvasContext, data.username);

                    self.signature(newCanvas.toDataURL());
                    self.isSignatureCompleted(true);
                });
        }

        self.editSignatureMobileClick = function () {
            if (self.isReadOnlyView()) {
                return;
            }

            self.isSignatureInEditMode(true);

            var $signaturePad = $(SIGNATURE_PAD_SELECTOR);

            canvas = $signaturePad.find('canvas');

            var potraitOrientation = window.matchMedia('(orientation: portrait)');
            rotateSignatureToolbar(potraitOrientation.matches);
            setCanvasSize(potraitOrientation.matches);

            initSignaturePad($signaturePad);

            // handle orientation change for mobile Safari manually as it 
            // is not supporting Fullscreen API and Screen Orientation API
            if (gJobs.browserDetector.isMobileSafari()) {
                potraitOrientation.addListener(function (e) {
                    handleOrientationChange(e);
                });
            } else {
                // add orientation change handle if the user decides to go out of fullscreen mode
                $(document).on(fullScreenChangeEvents, function () {

                    // this timeout is needed to recalculate document height and width after fullscreen transition end
                    setTimeout(function () {
                        rotateSignatureToolbar(potraitOrientation.matches);
                        setCanvasSize(potraitOrientation.matches);
                    }, 150);

                    if (!document.fullscreenElement) {
                        potraitOrientation.addListener(function (e) {
                            handleOrientationChange(e);
                        });
                    }
                });

                goInFullscreen($('.signature-pad-responsive').get(0));
                screen.orientation && screen.orientation.lock(potraitOrientation.matches ? 'portrait' : 'landscape');
            }

            self.isSignatureInputed(false);
        }

        self.saveSignatureMobileClick = function () {
            if (signaturePad.isEmpty()) {
                return;
            }

            var img = new Image();

            img.onload = function () {
                var tempCanv = document.createElement('canvas')

                tempCanv.height = 150;
                tempCanv.width = 496;
                tempCanv.style.position = "absolute";

                var isPortaitOrientaion = window.matchMedia('(orientation: portrait)').matches;
                var scaleRate = isPortaitOrientaion ? tempCanv.height / img.width : tempCanv.height / img.height;

                var ctx = tempCanv.getContext("2d");

                clearCanvas(ctx);

                ctx.scale(scaleRate, scaleRate);

                ctx.imageSmoothingEnabled = false;

                if (isPortaitOrientaion) {
                    ctx.translate(img.height / img.width, img.width);
                    ctx.rotate(-Math.PI / 2);
                }

                ctx.drawImage(img, isPortaitOrientaion ? 0 : img.width * scaleRate / 2, isPortaitOrientaion ? img.height * scaleRate / 2 : 0);

                var res = tempCanv.toDataURL();

                self.signature(res);
                self.isSignatureCompleted(true);
                self.isSignatureInEditMode(false);
            }

            img.src = canvas[0].toDataURL();
        }

        self.editSignatureClick = function () {
            self.isSignatureInEditMode(true);

            var $signaturePad = $(SIGNATURE_PAD_SELECTOR);
            var sigWrapper = $signaturePad.find('.sig-wrapper');

            $signaturePad.find(':tabbable').first().focus();

            canvas = $signaturePad.find('canvas');

            canvas[0].width = sigWrapper.width();
            canvas[0].height = sigWrapper.height();

            initSignaturePad($signaturePad);
            self.isSignatureInputed(false);
        }

        self.saveSignatureClick = function () {
            self.signature(canvas[0].toDataURL());
            self.isSignatureCompleted(true);
            self.isSignatureInEditMode(false);
            $("#aria-live-message-container").text('');
            $("#aria-live-message-container").attr('aria-label', '');
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Signature saved.', $("#aria-live-message-container"), false); }, 300);            
            setFocusOnEditSignatureButton();
            if ($('#canvass-form-date')) {
                var now = new Date();
                var day = ("0" + now.getDate()).slice(-2);
                var month = ("0" + (now.getMonth() + 1)).slice(-2);
                var today = now.getFullYear() + "-" + (month) + "-" + (day);
                $('#canvass-form-date').val(today);
                $('#canvass-form-date').keydown();
                //OnlineApp.ViewModels.CanvassViewModel.maskedDate = today;

            }
        }

        self.cancelSignatureClick = function () {
            self.isSignatureInEditMode(false);
            setFocusOnEditSignatureButton();
            $("#aria-live-message-container").text('');
            $("#aria-live-message-container").attr('aria-label', '');
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Signature cancelled', $("#aria-live-message-container"), false); }, 300);
        }

        function setFocusOnEditSignatureButton() {
            $('.edit-signature-button').focus();
        }

        var initSignaturePad = function ($signaturePad) {
            signaturePad = new SignaturePad(canvas[0], {
                penColor: '#145394',
                backgroundColor: 'transparent'
            });

            self.isSignatureInputed(false);

            $signaturePad.find('.clear-button').on('click', function () {
                signaturePad.clear();
                signaturePad.on();
                self.isSignatureInputed(false);
                handleActionAnnouncement('Signature cleared', 1);
            });

            canvas.on('mousedown', function () {
                self.isSignatureInputed(true);
            });
        }

        var rotateImage = function (img, angleRad) {
            var tempCanv = document.createElement('canvas');

            tempCanv.height = img.width;
            tempCanv.width = img.height;
            tempCanv.style.position = "absolute";

            var ctx = tempCanv.getContext("2d");
            ctx.imageSmoothingEnabled = false;

            if (angleRad > 0) {
                ctx.translate(img.height, img.width / img.height);
            } else {
                ctx.translate(img.height / img.width, img.width);
            }

            ctx.rotate(angleRad);
            ctx.drawImage(img, 0, 0);

            return tempCanv.toDataURL();
        }

        var handleOrientationChange = function (e) {
            var angleRad = Math.PI / 2;
            var image = new Image();
            var isPortaitOrientaion = e.matches;

            image.onload = function () {

                rotateSignatureToolbar(isPortaitOrientaion);
                setCanvasSize(isPortaitOrientaion);
                var rotatedImageDataURL = rotateImage(image, isPortaitOrientaion ? angleRad : -angleRad);

                var rotatedImage = new Image();

                rotatedImage.onload = function () {
                    var canvasContext = canvas[0].getContext('2d');
                    clearCanvas(canvasContext);
                    canvasContext.drawImage(rotatedImage, 0, 0);
                }

                rotatedImage.src = rotatedImageDataURL;
            }

            image.src = canvas[0].toDataURL();
        }

        var goInFullscreen = function (element) {
            if (element.requestFullscreen)
                return element.requestFullscreen();
            else if (element.mozRequestFullScreen)
                return element.mozRequestFullScreen();
            else if (element.webkitRequestFullscreen)
                return element.webkitRequestFullscreen();
            else if (element.msRequestFullscreen)
                return element.msRequestFullscreen();
        }

        var goOutFullscreen = function () {
            if (document.exitFullscreen)
                document.exitFullscreen();
            else if (document.mozCancelFullScreen)
                document.mozCancelFullScreen();
            else if (document.webkitExitFullscreen)
                document.webkitExitFullscreen();
            else if (document.msExitFullscreen)
                document.msExitFullscreen();
        }

        var getScreenSize = function () {

            return {
                height: document.documentElement.clientHeight,
                width: document.documentElement.clientWidth
            };
        }

        var rotateSignatureToolbar = function (isPortaitOrientaion) {
            var $signaturePad = $(SIGNATURE_PAD_SELECTOR);
            var signatureComponentsContainer = $signaturePad.find('.signature-components-container');
            var screenSize = getScreenSize();

            signatureComponentsContainer.find('.sig-name-container').attr('style', 'top: ' +
                ((isPortaitOrientaion ? screenSize.width : screenSize.height) - 50) + 'px');

            if (isPortaitOrientaion) {
                var canvasHeight = screenSize.height - SIGNATURE_TOOLBAR_WIDTH;
                signatureComponentsContainer.attr('style', 'transform: rotate(90deg) translate(' + canvasHeight + 'px,' + SIGNATURE_TOOLBAR_WIDTH + 'px); width: ' + screenSize.height + 'px;');
                $signaturePad.find('.sig-wrapper').removeClass('signature-toolbar-padding');
            } else {
                signatureComponentsContainer.attr('style', 'width: ' + screenSize.width + 'px;');
                $signaturePad.find('.sig-wrapper').addClass('signature-toolbar-padding');
            }
        }

        var setCanvasSize = function (isPortaitOrientaion) {
            var screenSize = getScreenSize();

            if (isPortaitOrientaion) {
                canvas[0].height = screenSize.height;
                canvas[0].width = screenSize.width - SIGNATURE_TOOLBAR_HEIGHT;
            } else {
                canvas[0].height = screenSize.height - SIGNATURE_TOOLBAR_HEIGHT;
                canvas[0].width = screenSize.width;
            }
        }

        var clearCanvas = function (ctx) {
            ctx.fillStyle = "transparent";
            ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        }

        var generateSignatureOnCanvas = function (canvasContext, username) {
            handleActionAnnouncement('Signature generated successfully', 1);

            canvasContext.textAlign = 'center';
            canvasContext.fillStyle = '#145394';
            canvasContext.font = 'normal 300 40px "La Belle Aurore", cursive';

            if (!self.isMobile && canvasContext.canvas.clientWidth < 200) {
                canvasContext.fillText(username, canvasContext.canvas.clientWidth / 2, 2 * canvasContext.canvas.clientHeight / 3);
            }
            else {
                canvasContext.fillText(username, canvasContext.canvas.width / 2, 2 * canvasContext.canvas.height / 3);
            }
            return canvasContext;
        }

        var loadUserName = function () {
            OnlineApp.Services.authenticationService.getUserData()
                .then(function (data) {
                    self.username(data.username);
                });
        }

        var handleActionAnnouncement = function (message, index) {
            var signatureContainer = $('.signature-container')[0];
            var announcementText = $(signatureContainer).find('.sr-notification')[index];

            OnlineApp.Helpers.layoutHelper.tabbing.updateIndices(signatureContainer);

            gJobs.screenReadersService.setNotification($(announcementText), message, null, true);
        }

    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        SignatureViewModel: SignatureViewModel
    });
})(window);
;
(function (window, undefined) {
    'use strict';


    var controlStates = {
        loading: 'loading',
        scheduling: 'scheduling',
        schedulingLoaded: 'scheduling-loaded',
        scheduled: 'scheduled',
        confirmed: 'confirmed',
        eligible: 'eligible',
        notimeslots: 'no-time-slots'
    };


    function ScheduleExamViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;

        self.applicationId = ko.observable();

        self.evaluationStep = ko.observable();

        self.evaluationStepId = ko.observable();

        self.state = ko.observable(controlStates.scheduling);

        self.exams = ko.observableArray();

        self.customMessage = ko.observable();
        
        self.timeZoneText = ko.observable();

        self.isBusy = ko.observable(false);

        self.calendarEventLinks = ko.observable('');

        self.selectedExam = ko.computed(function () {
            return ko.utils.arrayFirst(self.exams(), function (exam) {
                return exam.selectedTimeSlot();
            });
        });

        self.hasFreeTimeSlots = ko.computed(function () {
            var freeTimeSlots = 0;

            ko.utils.arrayForEach(self.exams(), function (exam) {
                ko.utils.arrayForEach(exam.daySlots(), function (daySlot) {
                    freeTimeSlots += daySlot.timeSlots().length;
                });
            });

            return (freeTimeSlots > 0);
        });

        self.selectTimeSlot = function (timeSlot) {
            var selectedExam = self.selectedExam();
            var selectedTimeSlot = selectedExam && selectedExam.selectedTimeSlot();

            if (selectedTimeSlot) {
                self.unselectTimeSlot(selectedTimeSlot);
            }

            timeSlot.isSelected(true);            
        };

        self.unselectTimeSlot = function (timeSlot) {
            timeSlot.isSelected(false);
        };

        self.scheduleExamAsync = function () {

            self.isBusy(true);

            var promise = OnlineApp.Services.dataService.exam.post({
                examId: self.selectedExam().selectedTimeSlot().examId(),
                examDateTime: self.selectedExam().selectedTimeSlot().dateTime(),
                applicationId: self.applicationId(),
                evaluationStep: self.evaluationStep(),
                evaluationStepId: self.evaluationStepId()
            });

            OnlineApp.Helpers.ajaxResponseValidator.ensurePromiseFailsOnInvalidData(promise)
                .done(function (data) {
                    self.calendarEventLinks(data.calendarLinks);
                    self.state(controlStates.confirmed);

                    attachHandlersToCalendarEventLinks();
                })
                .fail(function () {
                    toastr.error('Exam scheduling has failed! Try again later.');
                })
                .always(function () {
                    self.isBusy(false);
                });

            return promise;
        };

        self.unsheduleExamAsync = function () {

            self.isBusy(true);

            var examData = {
                applicationId: self.applicationId(),
                evaluationStep: self.evaluationStep(),
                evaluationStepId: self.evaluationStepId()
            };
            var promise = OnlineApp.Services.dataService.exam['delete'](null, examData);

            OnlineApp.Helpers.ajaxResponseValidator.ensurePromiseFailsOnInvalidData(promise)
                .done(function () {
                    gJobs.screenReadersService.silenceScreenreader();
                    self.state(controlStates.scheduling);
                    gJobs.applicationsPage && gJobs.applicationsPage.scheduleExamViewModel.state('loading');
                    OnlineApp.Services.dataService.exam.get(null, examData)
                        .always(function () {
                            if (gJobs.applicationsPage && gJobs.applicationsPage.currentExamSubscription) {
                                gJobs.applicationsPage.currentExamSubscription.dispose();
                                gJobs.applicationsPage.currentExamSubscription = null;
                            }
                        })
                        .done(function (data) {
                            $.extend(data, examData);
                            if (gJobs.applicationsPage) {
                                var scheduleExamViewModel = gJobs.applicationsPage.scheduleExamViewModel;
                                scheduleExamViewModel.fromDataModel(data);
                                gJobs.applicationsPage.currentExamSubscription = scheduleExamViewModel.state.subscribe(gJobs.applicationsPage.stateChangeHandler);
                            }
                            $(document).trigger(Events.CommonEventsNames.AppointmentFlyoutStateChanged, {
                                state: controlStates.schedulingLoaded
                            });
                        });
                })
                .fail(function () {
                    toastr.error('Exam unscheduling has failed! Try again later.');
                })
                .always(function () {
                    self.isBusy(false);
                });

            return promise;
        };

        self.isSelfSchedulingDeadlineExpired = ko.computed(function () {
            if (!self.selectedExam())
                return false;

            return self.selectedExam().isSelfSchedulingDeadlineExpired();
        });

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.applicationId(data.applicationId);
            self.evaluationStep(data.evaluationStep);
            self.evaluationStepId(data.evaluationStepId);
            self.customMessage(data.customMessage);
            self.timeZoneText(data.timeZoneText);
            self.calendarEventLinks(data.calendarLinks);

            self.exams(ko.utils.arrayMap(data.examList, function (item) {
                var viewModel = new ExamViewModel();
                viewModel.fromDataModel(item);

                return viewModel;
            }));

            var state = controlStates.scheduling;

            if (!self.hasFreeTimeSlots()) {
                state = controlStates.notimeslots;
            }

            if (data.customMessage) {
                state = controlStates.eligible;
            }

            if (data.isScheduledForExam) {
                state = controlStates.scheduled;
            }

            self.isScheduledForExam = data.isScheduledForExam;
            self.state(state);

            if (!!data.calendarLinks) {
                attachHandlersToCalendarEventLinks();
            }
        };

        self.state.subscribe(function (oldValue) {
            self.lastState = oldValue;
        }, null, "beforeChange");

        self.state.subscribe(function (state) {
            $(document).trigger(Events.CommonEventsNames.AppointmentFlyoutStateChanged, {
                state: state,
                lastState: self.lastState,
                isScheduledForExam: self.isScheduledForExam
            });
        });

        var attachHandlersToCalendarEventLinks = function () {
            $('.add-to-calendar a').on('click', function (e) {
                var $target = $(e.target);
                gJobs.common.analytics.trackEvent(
                    gJobs.common.analytics.categories.application,
                    'SelfSchedule',
                    $target.text()
                );
            });
        }
    };

    function ExamViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;

        self.location = new ExamLocationViewModel();

        self.daySlots = ko.observableArray();

        self.selectedTimeSlot = ko.computed(function () {

            var daySlot = ko.utils.arrayFirst(self.daySlots(), function (daySlot) {
                return daySlot.selectedTimeSlot();
            });


            if (daySlot) {
                return daySlot.selectedTimeSlot();
            }
        });

        self.displaySheduledDateTime = ko.computed(function () {
            if (!self.selectedTimeSlot()) {
                return;
            }

            var daySlot = ko.utils.arrayFirst(self.daySlots(), function (daySlot) {
                return daySlot.selectedTimeSlot();
            });

            var displayString =
                daySlot.displayDate() + ', ' +
                self.selectedTimeSlot().localDateTime().getFullYear() + ' at ' +
                self.selectedTimeSlot().displayTime();

            return displayString;
        });

        self.isSelfSchedulingDeadlineExpired = ko.computed(function () {
            if (!self.selectedTimeSlot())
                return false;

            return self.selectedTimeSlot().isSelfSchedulingDeadlineExpired();
        });

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.location.fromDataModel(data.examLocation);
            self.daySlots((function () {

                var timeSlotViewModels = ko.utils.arrayMap(data.timeSlots, function (item) {
                    var timeSlotViewModel = new TimeSlotViewModel();
                    timeSlotViewModel.fromDataModel(item);

                    return timeSlotViewModel;
                });

                var daySlotsObject = (function () {
                    var daySlotsObject = {};

                    ko.utils.arrayForEach(timeSlotViewModels, function (item) {
                        var timeSlotHash = item.localDateTime().toDateString()
                        var daySlotViewModel = daySlotsObject[timeSlotHash];

                        if (!daySlotViewModel) {
                            daySlotViewModel = new DaySlotViewModel();
                            daySlotViewModel.date(new Date(timeSlotHash));
                        }

                        daySlotViewModel.timeSlots.push(item);

                        daySlotsObject[timeSlotHash] = daySlotViewModel;
                    });

                    return daySlotsObject;
                })();

                var daySlots = (function () {
                    var daySlots = [];

                    for (var propertyName in daySlotsObject) {
                        if (daySlotsObject.hasOwnProperty(propertyName)) {
                            daySlots.push(daySlotsObject[propertyName]);
                        }
                    }

                    return daySlots;
                })();

                return daySlots;
            })());
        }
    };


    function ExamLocationViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        self.address = new OnlineApp.ViewModels.Common.AddressViewModel();

        self.title = ko.observable();

        self.phone = ko.observable();


        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.address.fromDataModel(data.address);
            self.title(data.locationTitle);
            self.phone(data.phone);
        }
    };


    function DaySlotViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        self.date = ko.observable(new Date());

        self.displayDate = ko.computed(function () {
            var dateTime = self.date();
            var formattedDate = OnlineApp.Helpers.DateTimeFormatter.getFullDate(dateTime);

            return formattedDate;
        });
        
        self.timeSlots = ko.observableArray();

        self.selectedTimeSlot = ko.computed(function () {
            var timeSlots = self.timeSlots();

            var timeSlot = ko.utils.arrayFirst(timeSlots, function (timeSlot) {
                return timeSlot.isSelected();
            });

            return timeSlot;
        });
    };

    function TimeSlotViewModel() {

        var self = OnlineApp.ViewModels.Base.BaseViewModel.apply(this, arguments) || this;


        self.isSelected = ko.observable();
        
        self.examId = ko.observable();

        self.dateTime = ko.observable();

        self.localDateTime = ko.observable(new Date());

        self.displayDate = null;

        self.displayTime = ko.computed(function () {
            var dateTime = self.localDateTime();
            var formattedTime = OnlineApp.Helpers.DateTimeFormatter.getMilitaryTime(dateTime);

            return formattedTime;
        });

        self.label = ko.computed(function () {
            return (self.isSelected() ? '' : 'Schedule appointment for ')
                + OnlineApp.Helpers.DateTimeFormatter.getFullDateNoDay(self.localDateTime()) + ' ' + self.displayTime()
                + (self.isSelected() ? ' selected' : '');
        });

        self.isSelfSchedulingDeadlineExpired = ko.observable();

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.examId(data.examId);
            self.isSelected(data.isSelected);
            self.dateTime(data.date);
            self.localDateTime(new Date(data.dateWithAppliedTimeZonesForDisplayInUi));
            self.isSelfSchedulingDeadlineExpired(data.isSelfSchedulingDeadlineExpired);

            self.displayDate = data.dateWithAppliedTimeZonesForDisplayInUi;
        };
    };

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        ScheduleExamViewModel: ScheduleExamViewModel
    });

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

    function OfferViewModel() {
        var self = OnlineApp.ViewModels.Base.DataViewModel.apply(this, arguments) || this;

        var offerStatusEnum = { Rejected: 0, Accepted: 1, AnswerPending: 2 };

        self.isMobile = gJobs.browserDetector.isMobileBrowser();
        self.offerId = ko.observable(0);
        self.jobTitle = ko.observable('');
        self.description = ko.observable('');
        self.dueDate = ko.observable('');
        self.offerStatus = ko.observable();
        self.attachments = ko.observableArray([]);
        self.dateAnswered = ko.observable('');
        self.isRejected = offerStatusEnum.Rejected;
        self.signatureViewModel = new OnlineApp.ViewModels.SignatureViewModel();

        self.isSubmitted = false;

        self.isRejectReasonSectionVisible = ko.observable(false);
        self.rejectReason = ko.observable('').extend({
            length: {
                max: 1000,
                validationMessage: 'Reject reason is too long and is limited to 1000 characters'
            }
        });

        self.fileDownloadUrl = function(attachmentId) {
            return '/api/attachments/downloadAttachmentForOffer?offerId=' + 
                self.offerId() + '&attachmentId=' + attachmentId;
        };

        self.isReadOnlyView = ko.computed(function () { 
            return self.offerStatus() === offerStatusEnum.Rejected || self.offerStatus() === offerStatusEnum.Accepted;
        });

        self.isReadOnlyView.subscribe(function (value) {
            self.signatureViewModel.isReadOnlyView(value);
        });

        self.fromDataModel = function(data) {
            self.offerId(data.offerId);
            self.jobTitle(data.jobTitle);
            self.description(data.description);
            self.dueDate(data.dueDate);
            self.offerStatus(data.offerStatus);
            self.attachments(data.attachments);
            self.dateAnswered(data.dateAnswered);
            self.isSubmitted = false;

            self.signatureViewModel.fromDataModel(data.signature, self.isReadOnlyView(), data.dateAnswered);

            var isMobile = gJobs.browserDetector.isMobileBrowser();
            $('a.ss-print.popover-trigger')
                .attr('href', '/applications/offerletter/print/' + self.offerId())
                .attr('hidden', isMobile);
            $('a.ss-download.popover-trigger')
                .attr('href', '/api/offer/downloadOffer?offerId=' + self.offerId());
        };

        self.acceptClick = function() {
            if (self.isSubmitted) {
                return;
            }

            self.isSubmitted = true;

            var signature = self.signatureViewModel.signature();
            OnlineApp.Services.dataService.offer.post({
                id: self.offerId(),
                offerStatus: offerStatusEnum.Accepted,
                signature: signature
            }).then(function (data) {
                if (data.isSuccess) {
                    OnlineApp.Services.offerFlyoutService.changeOfferStatus(self.offerId(), true);
                    closeFlyout();
                    toastr.success('Offer Accepted');
                }
            }).fail(function () {
                self.isSubmitted = false;
            });
        }

        self.rejectOffer = function () {
            if (self.isSubmitted) {
                return;
            }

            self.isSubmitted = true;

            if (!self.rejectReason.validate()) {
                return;
            }

            OnlineApp.Services.dataService.offer.post({
                id: self.offerId(),
                offerStatus: offerStatusEnum.Rejected,
                rejectReason: self.rejectReason()
            }).then(function (data) {
                if (data.isSuccess) {
                    OnlineApp.Services.offerFlyoutService.changeOfferStatus(self.offerId(), false);
                    closeFlyout();
                    toastr.success('Offer Rejected');
                    self.hideRejectReasonSection();
                }
            }).fail(function (data) {
                var response = JSON.parse(data.responseText);
                OnlineApp.Helpers.Notifications.showResponseMessages(response);
                self.isSubmitted = false;
            });
        }

        self.hideRejectReasonSection = function () {
            self.isRejectReasonSectionVisible(false);
            $('#reject-offer-button').focus();
        }

        self.showRejectReasonSection = function () {
            self.isRejectReasonSectionVisible(true);
            $('#reject-reason').focus();
        }

        self.showRejectReasonModal = function () {
            var rejectReasonTextArea =
                '<textarea id="reject-reason-modal-textarea" maxlength="1000"'
                + 'type="text" placeholder="Input your reject reason here">'
                + ko.utils.unwrapObservable(self.rejectReason)
                + '</textarea>';

            $(document).trigger(
                Events.CommonEventsNames.ShowConfirmDialog,
                {
                    header: 'Reject Offer Letter',
                    subHeader: 'Are you sure you want to reject this offer letter?',
                    confirmButtonText: 'Reject',
                    additionalCssClassName: 'reject-offer-letter-dialog',
                    innerHtml: rejectReasonTextArea,
                    confirmClick: function () {
                        populateRejectReasonFromModalTextarea();
                        self.rejectOffer();
                    },
                    cancelClick: function () {
                        populateRejectReasonFromModalTextarea();
                    }
                }
            );
        }

        function populateRejectReasonFromModalTextarea() {
            var $rejectReasonModalTextarea = $('#reject-reason-modal-textarea');
            if ($rejectReasonModalTextarea.length) {
                self.rejectReason($rejectReasonModalTextarea.val());
            }
        }

        function closeFlyout() {
            if (gJobs.areaInfoService.getCurrentArea() == gJobs.areaInfoService.areaNames.Career) {
                AgencyPages.offerFlyout.close();
            } else {
                gJobs.applicationsPage.offerFlyout.close();
            }
        }
    };

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        OfferViewModel: OfferViewModel
    });
})(window);;
(function (window, undefined) {
    'use strict';


    function DefinitionViewModel() {
        var self = this;

        self.items = ko.observableArray();

        self.findItemByField = function (fieldName, fieldValue) {
            var items = self.items();
            for (var i in items) {
                var item = items[i];

                if (item.hasOwnProperty(fieldName) && item[fieldName] == fieldValue) {
                    return item;
                }
            }
            return {};
        };

        self.findItemById = function (id) {
            return self.findItemByField("id", id);
        };
    }


    function ConstantDefinitionViewModel(items) {
        var self = DefinitionViewModel.apply(this, arguments) || this;

        self.items(items);
    }


    function ServiceBasedDefinitionViewModel(dataServiceEndpoint) {
        var self = DefinitionViewModel.apply(this, arguments) || this;


        var items = [];


        var loadItemsAsync = function () {
            dataServiceEndpoint
                .get()
                .done(function (data) {
                    items = data;
                    self.isLoaded(true);
                });
        };


        self.isLoaded = ko.observable(false);

        self.items = ko.computed(function () {
            if (!self.isLoaded()) {
                loadItemsAsync();
            }

            return items;
        });
    }

    function DeferredDefinitionViewModel() {
        var self = DefinitionViewModel.apply(this, arguments) || this;

        var deferred = $.Deferred();
        var promise = deferred.promise();

        self.setItems = function (definition) {
            deferred.resolve(definition);
            self.variableItems(definition);
        }

        self.resetItems = function() {
            deferred.reject();
        }

        self.variableItems = ko.observableArray([]);

        self.items = ko.computed(function () {
            return self.variableItems();
        });

        self.get = function() {
            return promise;
        }
    }

    function DefinitionsViewModel(fetchDeferredDefinitions) {
        var self = this;

        var endpoints = OnlineApp.Services.dataService.definitions;

        // todo: combine this logic into CompositeDefinitionsViewModel
        for (var endpointName in endpoints) {
            if (endpoints.hasOwnProperty(endpointName)) {
                self[endpointName] = new DeferredDefinitionViewModel();
            }
        }

        if (fetchDeferredDefinitions) {

            OnlineApp.Services.dataService.PastFutureRange
                .get()
                .done(function (range) {
                    var currentTime = new Date();
                    var currentYear = currentTime.getFullYear();

                    var pastRange = new Array();
                    for (var i = currentYear; i >= range.data.minYear; i--) {
                        pastRange.push({ id: i, text: i });
                    }
                    self.PastToPresentYear.setItems(pastRange);
                    
                    var pastFutureRange = new Array();
                    for (var i = range.data.maxYear; i >= range.data.minYear; i--) {
                        pastFutureRange.push({ id: i, text: i });
                    }
                    self.PastToFutureYear.setItems(pastFutureRange);
                });

            OnlineApp.Services.dataService.compositeDefinitions
                .get()
                .done(function(definitions) {
                    for (var endpointName in endpoints) {
                        if (endpoints.hasOwnProperty(endpointName)) {
                            self[endpointName].setItems(definitions[endpointName]);
                        }
                    }
                })
                .fail(function() {
                    for (var endpointName in endpoints) {
                        if (endpoints.hasOwnProperty(endpointName)) {
                            self[endpointName].resetItems();
                        }
                    }
                });
                
            OnlineApp.Services.dataService.InvalidSsnValues
                .get()
                .done(function (invalidSsnValues) {
                    self.invalidSsnValues = invalidSsnValues;
                });
        }

        //fetch required data
        OnlineApp.Services.dataService.sessionExpirationData
            .get()
            .done(function (sessionExpirationData){
                self.sessionExpirationData.setItems(sessionExpirationData);
            })
            .fail(function() {
                self.sessionExpirationData.resetItems();
            })

        self.PastToPresentYear = new DeferredDefinitionViewModel();
        self.PastToFutureYear = new DeferredDefinitionViewModel();
        self.sessionExpirationData = new DeferredDefinitionViewModel();

        self.invalidSsnValues = new Array();

        self.menuStepIds = {
            loginSuccess: 0,
            loginFailure: 1,
            resume: 2,
            info: 3,
            work: 4,
            education: 5,
            additional: 6,
            references: 7,
            questions: 8,
            attachments: 9,
            review: 10,
            submit: 11,
            profile: 12,
            register: 13,
            payment: 14,
            contactInfo: 15,
            changePassword: 16,
            deleteAccount: 17,
            emailPreferences: 18,
            preferences: 19,
            textMessagingPreferences: 20,
            twoFactorPreferences: 21
        };

        self.menuStep = new ConstantDefinitionViewModel([
            { id: self.menuStepIds.loginSuccess, text: 'LoginSuccess'},
            { id: self.menuStepIds.loginFailure, text: 'LoginFailure'},
            { id: self.menuStepIds.resume, text: 'Resume', tabId:'#resume-tab'},
            { id: self.menuStepIds.info, text: 'Info', tabId: '#general-info-tab'},
            { id: self.menuStepIds.work, text: 'Work', tabId: '#work-tab' },
            { id: self.menuStepIds.education, text: 'Education', tabId: '#education-tab' },
            { id: self.menuStepIds.additional, text: 'Additional', tabId: '#additional-info-tab' },
            { id: self.menuStepIds.references, text: 'References', tabId: '#references-tab' },
            { id: self.menuStepIds.questions, text: 'Questions', tabId: '#questions-tab' },
            { id: self.menuStepIds.attachments, text: 'Attachments', tabId:  '#attachments-tab'},
            { id: self.menuStepIds.review, text: 'Review', tabId: '#review-tab' },
            { id: self.menuStepIds.submit, text: 'Submit', tabId: '#submit-tab' },
            { id: self.menuStepIds.profile, text: 'Profile', tabId: '#profile-tab' },
            { id: self.menuStepIds.register, text: 'Register' },
            { id: self.menuStepIds.payment, text: 'Payment', tabId: '#payment-tab' },
            { id: self.menuStepIds.contactInfo, text: 'Contact Info', tabId: '#contact-info-tab' },
            { id: self.menuStepIds.changePassword, text: 'Change Password', tabId: '#change-password-tab' },
            { id: self.menuStepIds.deleteAccount, text: 'DeleteAccount', tabId: '#delete-account-tab' },
            { id: self.menuStepIds.emailPreferences, text: 'Email Preferences', tabId: '#email-preferences-tab' },
            { id: self.menuStepIds.preferences, text: 'Preferences', tabId: '#preferences-tab' },
            { id: self.menuStepIds.textMessagingPreferences, text: 'Text Messaging Preferences', tabId: '#text-messaging-preferences-tab' },
            { id: self.menuStepIds.twoFactorPreferences, text: 'Two Factor Preferences', tabId: '#two-step-verification-tab' }
        ]);

        // generate days array
        var days = [];
        for (var i = 1; i <= 31; i++) {
            days.push({
                id: i,
                text: i + ''
            });
        }
        self.day = new ConstantDefinitionViewModel(days);

        self.month = new ConstantDefinitionViewModel([
            { id: 1, text: 'January' },
            { id: 2, text: 'February' },
            { id: 3, text: 'March' },
            { id: 4, text: 'April' },
            { id: 5, text: 'May' },
            { id: 6, text: 'June' },
            { id: 7, text: 'July' },
            { id: 8, text: 'August' },
            { id: 9, text: 'September' },
            { id: 10, text: 'October' },
            { id: 11, text: 'November' },
            { id: 12, text: 'December' }
        ]);
        
        self.educationUnitType = new ConstantDefinitionViewModel([
            { id: 'Semester', text: 'Semester Units' },
            { id: 'Quarter', text: 'Quarter Units' }
        ]);

        self.extendedMonth = new ConstantDefinitionViewModel([
            { id: 1, text: 'January' },
            { id: 2, text: 'February' },
            { id: 3, text: 'March' },
            { id: 4, text: 'April' },
            { id: 5, text: 'May' },
            { id: 6, text: 'June' },
            { id: 7, text: 'July' },
            { id: 8, text: 'August' },
            { id: 9, text: 'September' },
            { id: 10, text: 'October' },
            { id: 11, text: 'November' },
            { id: 12, text: 'December' },
            { id: 14, text: 'Present' }
        ]);

        self.monthWithNoExpiration = new ConstantDefinitionViewModel([
            { id: 1, text: 'January' },
            { id: 2, text: 'February' },
            { id: 3, text: 'March' },
            { id: 4, text: 'April' },
            { id: 5, text: 'May' },
            { id: 6, text: 'June' },
            { id: 7, text: 'July' },
            { id: 8, text: 'August' },
            { id: 9, text: 'September' },
            { id: 10, text: 'October' },
            { id: 11, text: 'November' },
            { id: 12, text: 'December' },
            { id: 15, text: 'No Expiration' }
        ]);
        
        self.year = new ConstantDefinitionViewModel([
            { id: 2013, text: '2013' },
            { id: 2012, text: '2012' },
            { id: 2011, text: '2011' },
            { id: 2010, text: '2010' },
            { id: 2009, text: '2009' },
            { id: 2008, text: '2008' },
            { id: 2007, text: '2007' },
            { id: 2006, text: '2006' },
            { id: 2005, text: '2005' },
            { id: 2004, text: '2004' },
            { id: 2003, text: '2003' },
            { id: 2002, text: '2002' },
            { id: 2001, text: '2001' },
            { id: 2000, text: '2000' },
            { id: 1999, text: '1999' },
            { id: 1998, text: '1998' },
            { id: 1997, text: '1997' },
            { id: 1996, text: '1996' },
            { id: 1995, text: '1995' },
            { id: 1994, text: '1994' },
            { id: 1993, text: '1993' },
            { id: 1992, text: '1992' },
            { id: 1991, text: '1991' },
            { id: 1990, text: '1990' },
            { id: 1989, text: '1989' },
            { id: 1988, text: '1988' },
            { id: 1987, text: '1987' },
            { id: 1986, text: '1986' },
            { id: 1985, text: '1985' },
            { id: 1984, text: '1984' },
            { id: 1983, text: '1983' },
            { id: 1982, text: '1982' },
            { id: 1981, text: '1981' },
            { id: 1980, text: '1980' },
            { id: 1979, text: '1979' },
            { id: 1978, text: '1978' },
            { id: 1977, text: '1977' },
            { id: 1976, text: '1976' },
            { id: 1975, text: '1975' },
            { id: 1974, text: '1974' },
            { id: 1973, text: '1973' },
            { id: 1972, text: '1972' },
            { id: 1971, text: '1971' },
            { id: 1970, text: '1970' }
        ]);

        var expirationYears = [];
        var maxExpirationYearSeed = 15;
        var currentYear = new Date().getFullYear();
        var maxExpirationYear = currentYear + maxExpirationYearSeed;
        for (var i = currentYear; i < maxExpirationYear; i++) {
            expirationYears.push({ id: i, text: i.toString() });
        }
        self.expirationYear = new ConstantDefinitionViewModel(expirationYears);
        
        self.notificationType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Email' },
            { id: 2, text: 'Paper' }
        ]);

        self.relocationType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Yes' },
            { id: 2, text: 'No' },
            { id: 3, text: 'Maybe' },
            { id: 4, text: 'No Response' }
        ]);

        self.shiftType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Day' },
            { id: 2, text: 'Evening' },
            { id: 3, text: 'Night' },
            { id: 4, text: 'Rotating' },
            { id: 5, text: 'Weekends' },
            { id: 6, text: 'On Call' }
        ]);

        self.positionType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Regular' },
            { id: 2, text: 'Temporary' },
            { id: 3, text: 'Seasonal' },
            { id: 4, text: 'Internship' }
        ]);

        self.workType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Full Time' },
            { id: 2, text: 'Part Time' },
            { id: 3, text: 'Per Diem' }
        ]);

        self.level = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Beginner' },
            { id: 2, text: 'Intermediate' },
            { id: 3, text: 'Expert' }
        ]);

        self.referenceType = new ConstantDefinitionViewModel([
            { id: 0, text: 'Personal' },
            { id: 1, text: 'Professional' }
        ]);

        self.creditCardType = new ConstantDefinitionViewModel([
            { id: 1, text: 'American Express' },
            { id: 2, text: 'Discover' },
            { id: 3, text: 'MasterCard' },
            { id: 4, text: 'Visa' }
        ]);
        
        self.disabilityAnswer = new ConstantDefinitionViewModel([
            { id: 1, text: 'No' },
            { id: 2, text: 'Yes' },
            { id: 3, text: 'NoAnswer' }
        ]);
    }


    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        DefinitionsViewModel: DefinitionsViewModel
    });

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        ServiceBasedDefinitionViewModel: ServiceBasedDefinitionViewModel
    });

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

    function FileUploadViewModel() {

        var self = this;

        self.currentlyUploadingFile = ko.observable('');
        self.fileUploadComplete = ko.observable(false);
        self.fileUploadError = ko.observable('');
        self.progressPercent = ko.observable(0);

        self.supportsUploadProgress = ko.observable(true);
        self.fileUploadCancelable = ko.observable(true);

        self.fileIsPasswordProtected = ko.observable(false);
        self.fileIsDuplicate = ko.observable(false);

        /**
         * Should be overriden in Attachments.
         */
        self.showFileSelect = function (data, evnt) {
            $(evnt.target).closest('form').find('input').get(0).click();
        };

        /**
         * Should be overriden and called at the end to start uploading.
         * $(this).data('blueimpFileupload').options.url should be changed.
         */
        self.onFileAdd = function (e, data) {

            self.fileUploadJQXHR = data.submit();

            //return focus to main frame. Needed in case of iframe uploads because otherwise clicking buttons doesn't work
            window.focus();
        };

        self.onFileSend = function (e, data) {
            self.currentlyUploadingFile(data.files[0].name);
            self.fileUploadCancelable(true);
            self.fileUploadComplete(false);
            self.fileUploadError('');
            self.progressPercent(0);
            self.fileIsPasswordProtected(false);

            if (data.dataType && data.dataType.substr(0, 6) === 'iframe') {
                self.supportsUploadProgress(false);
            } else {
                self.supportsUploadProgress(true);
            }
        };

        self.onUploadProgress = function (e, data) {
            if (self.supportsUploadProgress()) {
                self.progressPercent(parseInt(data.loaded / data.total * 100, 10));
            }
        };

        /**
         * Should be overriden and called at the end to finish uploading.
         */
        self.onUploadDone = function (e, data) {

            if (data.result && data.result.status === 'OK') {
                self.fileUploadComplete(true);
            } else {
                self.fileUploadError(data.errorThrown || self.getDefaultUploadErrorMessage());
            }
        };

        self.onUploadFail = function (e, data) {
            self.fileUploadError(data.errorThrown);
        };

        self.cancelFileUpload = function () {
            self.fileUploadJQXHR.abort();
            self.currentlyUploadingFile('');
        };

        self.goBackFromError = function () {
            self.currentlyUploadingFile('');
            OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
        };
        self.goBackFromErrorSupplementalAttachment = function () {
            self.currentlyUploadingFile('');
            
        };
        
        self.getDefaultUploadErrorMessage = function () {
            return "An error occurred uploading file " + self.currentlyUploadingFile() + ".";
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        FileUploadViewModel: FileUploadViewModel
    });
    
})(window);
;
(function (window, undefined) {
    'use strict';

    var captchaHelper = new OnlineApp.Helpers.CaptchaHelper('#contact-info-tab');
    var layoutHelper = OnlineApp.Helpers.layoutHelper;

    function ContactInfoViewModel(config) {
        var config = $.extend({}, {
            endpoint: "contactInfo",
            get: false // data is loaded in parent View-Model
        }, config);

        var contactInfoSaveButtonSelector = '#contact-info-tab .form-actions .btn-app-primary-save';

        var pageInfoService = gJobs.pageInfoService ? gJobs.pageInfoService : AgencyPages.pageInfoService;
        var currentPage = pageInfoService.getCurrentPageType();
        var currentPageType;
        var pageTypes = pageInfoService.getPageTypes();

        if (currentPage) {
            currentPageType = currentPage.type;
        }

        var self = OnlineApp.ViewModels.Base.EditableViewModel.call(this, config) || this;

        self.isDiscardChange = ko.observable(false);

        self.radioButtonOptions = ko.observable({
            notificationPreference: [
                {
                    value: '1',
                    id: 'contact-info-notification-preference-email',
                    name: 'ci-radioSet-notify',
                    label: 'Email'
                },
                {
                    value: '2',
                    id: 'contact-info-notification-preference-paper',
                    name: 'ci-radioSet-notify',
                    label: 'Paper'
                }
            ]
        }).extend({ ignoreOnSerialization: true });

        self.enableEmailVerification = ko.observable(window.enableEmailVerification);
        self.fromAppProcess = ko.observable(window.utils.getUrlParameter("fromAppProcess").trim() === 'true'  ? true : false);
        self.isEmailVerified = ko.observable();
        self.isAccountSettingsPage  = ko.observable(currentPageType === pageTypes.accountSettings.type);

        var initialFullName;
        self.name = new OnlineApp.ViewModels.Common.NameViewModel();
        self.address = new OnlineApp.ViewModels.Common.AddressViewModel();
        self.phone = new OnlineApp.ViewModels.Common.PhoneViewModel();
        self.textCaptchaViewModel = new OnlineApp.ViewModels.TextCaptchaViewModel();


        self.initContactInfoEmailVerificationViewModel = function (options) {
            if (!self.contactInfoEmailVerificationViewModel) {
                self.contactInfoEmailVerificationViewModel = new OnlineApp.ViewModels.ContactInfoEmailVerificationViewModel();
            }

            if (options) {
                self.contactInfoEmailVerificationViewModel
                    .emailVerificationViewModel
                    .changedEmailAddressWasAdded = ko.observable(options.changedEmailAddressWasAdded);
            }

            self.contactInfoEmailVerificationViewModel.emailVerificationViewModel.initUserData();

            OnlineApp.Services.emailVerificationService.isEmailVerified().then(function(response) {
                var data = response.data;

                self.isEmailVerified(data.isEmailVerified);
            });
        };
        
        if (self.enableEmailVerification() && self.isAccountSettingsPage() && !self.fromAppProcess()) {
            OnlineApp.Services.authenticationService.isLoggedIn()
            .done(function (isLoggedIn) {
                if (isLoggedIn) {
                   self.initContactInfoEmailVerificationViewModel();
                }
            });
        }


        // todo: implement EmailAvailabilityValidator (promise-based)
        // todo: combine all email-related funtionality into one place
        self.initialEmail = ko.observable(null);
        self.emailAddress = ko.observable('').extend({ required: {}, email: {} });
        self.isEmailNotAvailable = ko.observable(false).extend({ ignoreOnSerialization: true });
        self.isEmailEditable = ko.observable(config.isEmailEditable || false).extend({ ignoreOnSerialization: true });
        self.isPasswordSet = true;
        self.textCaptchaEnabled = window.textCaptcha;

        self.isEmailVerificationNotificationEnabled = ko.observable(config.isEmailVerificationNotificationEnabled);
        self.isEmailVerificationMode = ko.observable(false);
        self.isEmailChanged = ko.observable(false).extend({ ignoreOnSerialization: true });
        self.showCaptchaValidationMessage = ko.observable(false);

        self.currentPassword = ko.observable().extend({ required: {} });
        self.isEmailAddressAvailable = ko.observable(true);
        self.isGoogleSignIn = ko.observable(false);

        self.emailAddress.subscribe(function (value) {
            //we assume that user changed email correctly
            self.isEmailNotAvailable(false);
            if (!value) {
                self.isEmailAddressAvailable(false);
            }
            else {
                self.isEmailAddressAvailable(true);
            }
            if (value !== self.initialEmail()) {
                self.isEmailChanged(true);
                
                if (!self.enableEmailVerification()) {
                    if (self.textCaptchaEnabled) {
                        self.textCaptchaViewModel.resetCaptcha(
                            self.textCaptchaViewModel.hasError(),
                            self.textCaptchaViewModel.userAnswer.validationMessage()
                        );
                    } else {
                        captchaHelper.renderCaptcha();
                    }
                }
            }
        });

        self.goToAccountSettingsPage = function () {
            var accountSettingsPagePath = gJobs.accountSettingsHelper.getLinkForAccountSettings();
            accountSettingsPagePath += '?changeEmail=true';

            var pageInfoService = gJobs.pageInfoService ? gJobs.pageInfoService : AgencyPages.pageInfoService;

            if (self.enableEmailVerification() && pageInfoService.isOnApplyPage()) {
                accountSettingsPagePath += '&redirectToVerifyAccountPage=true';
                sessionStorage.setItem(OnlineApp.SessionKeys.ApplicationProcessUrl, window.location.href);
            }

            window.location = accountSettingsPagePath;
        };

        self.changeEmailNotification = ko.computed({
            read: function () {
                return 'Your current email address is ' + self.initialEmail() +
                '. To change the email address, please visit account settings page.';
            },
            deferEvaluation: true
        })

        self.notificationPreference = ko.observable();
        self.jobId = ko.observable();

        self.notificationPreferenceText = ko.computed({
            read: function () {
                // todo: use same approach for every enum
                /* This approach for setting Enum values 
                uses client side enum-like dictionaries
                (see definitionsViewModel) */
                // $root.definitionsViewModel.notificationType.items()[1].id - might be input values

                var prefValue = self.notificationPreference();
                if (!prefValue) {
                    return "";
                }

                var notificationTypes = OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.notificationType.items();
                var pref = notificationTypes[prefValue];

                if (!pref) {
                    return "";
                }

                return pref.text;
            },
            write: function (value) {
                var definition = ko.utils.arrayFirst(
                    OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.notificationType.items(),
                    function(item) {
                        return item.text == value;
                    });

                self.notificationPreference(definition.id);
            }
        }).extend({ ignoreOnSerialization: true });

        self.getValidationConfig = function () {

            var fieldSettings = OnlineApp.FieldSettings;

            var getPrimaryPhone = function () {
                return {
                    subjectField: self.phone.primaryPhone,
                    objectField: self.phone.primaryPhoneExt,
                };
            };

            var getAlternatePhone = function () {
                return {
                    subjectField: self.phone.alternatePhone,
                    objectField: self.phone.alternatePhoneExt,
                };
            };

            var config = {
                'all': {
                    'name.firstName': {
                        required: {},
                        length: {
                            max: 50
                        },
                        regexp: {
                            pattern: /^[a-zA-Z\-\'~\u00C0-\u017F ]*$/,
                            validationMessage: "Invalid first name",
                            isValidationMessageVisible: true
                        }
                    },
                    'name.lastName': {
                        required: {},
                        length: {
                            max: 50
                        },
                        regexp: {
                            pattern: /^[a-zA-Z\-\'~\u00C0-\u017F ]*$/,
                            validationMessage: "Invalid last name",
                            isValidationMessageVisible: true
                        }
                    },
                    'name.middleName': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.middleName.required : false
                        },
                        length: {
                            max: 50,
                            enabled: !!fieldSettings ? fieldSettings.middleName.visible : true
                        },
                        disallowHtml: {}
                    },
                    'name.formerName': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.formerLastName.required : false
                        },
                        length: {
                            max: 50,
                            enabled: !!fieldSettings ? fieldSettings.formerLastName.visible : true
                        },
                        regexp: {
                            pattern: /^[a-zA-Z\-\'~\u00C0-\u017F ]*$/,
                            validationMessage: "Invalid former last name",
                            isValidationMessageVisible: true,
                            enabled: !!fieldSettings ? fieldSettings.formerLastName.visible : true
                        }
                    },
                    'address.address1': {
                        required: {},
                        length: {
                            max: 100
                        },
                        disallowHtml: {}
                    },
                    'address.address2': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.address2.required : false
                        },
                        length: {
                            max: 50,
                            enabled: !!fieldSettings ? fieldSettings.address2.visible : true
                        },
                        disallowHtml: {}
                    },
                    'address.city': {
                        required: {},
                        length: {
                            max: 50
                        },
                        disallowHtml: {}
                    },
                    'address.state.id': {
                        required: {
                            validationMessage: "Please select a state",
                            isValidationMessageVisible: true
                        },
                        regexp: {
                            pattern: /^[1-9]\d*$/,
                            validationMessage: "Please select a state",
                            isValidationMessageVisible: true
                        },
                        deferredDefinitionAwareValue: {
                            deferredDefinitionViewModel: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.states
                        },
                        state: {
                            onlyIf: function () {
                                return self.address.country.id() && self.address.state.id();
                            },
                            states: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.states.items(),
                            countryId: self.address.country.id
                        }
                    },
                    'address.country.id': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.countryID.required : false,
                            validationMessage: "Please select a country",
                            isValidationMessageVisible: true
                        },
                        regexp: {
                            pattern: !!fieldSettings && fieldSettings.countryID.required ? /^[1-9]\d*$/ : null,
                            validationMessage: "Please select a country",
                            isValidationMessageVisible: true,
                            enabled: !!fieldSettings ? fieldSettings.countryID.visible : true
                        },
                        deferredDefinitionAwareValue: {
                            deferredDefinitionViewModel: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.countries
                        }
                    },
                    'address.zipCode': {
                        required: {},
                        length: {
                            max: 20
                        },
                        zip: {
                            onlyIf: function () {
                                return self.address.country.id();
                            },
                            countryId: self.address.country.id
                        }
                    },
                    'phone.primaryPhoneExt': {
                        requiredField: $.extend({}, getPrimaryPhone(), {
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        }),
                        length: {
                            max: 10,
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'phone.primaryPhone': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.homePhone.required : false
                        },
                        requiredField: $.extend({}, getPrimaryPhone(), {
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        }),
                        phone: {
                            countryID: function () {
                                var phoneNumberAllowed = !!fieldSettings ? fieldSettings.homePhone.visible : true;
                                if (phoneNumberAllowed) {
                                    if (self.editableItem() != undefined) {
                                        if (self.editableItem().address && self.editableItem().address.country)
                                            return self.editableItem().address.country.id();
                                    } else {
                                        if (self.address && self.address.country)
                                            return self.address.country.id();
                                    }
                                }
                            },
                        },
                        length: {
                            //phone number and extension are concatenated into a single field which is maximum 50 chars long.
                            //10 chars are reserved for the extension and 6 for the ' ext. ' text
                            max: 34,
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'phone.alternatePhoneExt': {
                        requiredField: $.extend({}, getAlternatePhone(), {
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        }),
                        length: {
                            max: 10,
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'phone.alternatePhone': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.required : false
                        },
                        requiredField: $.extend({}, getAlternatePhone(), {
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        }),
                        phone: {
                            countryID: function () {
                                var phoneNumberAllowed = !!fieldSettings ? fieldSettings.alternatePhone.visible : true;
                                if (phoneNumberAllowed) {
                                    if (self.editableItem() != undefined) {
                                        if (self.editableItem().address && self.editableItem().address.country)
                                            return self.editableItem().address.country.id();
                                    } else {
                                        if (self.address && self.address.country)
                                            return self.address.country.id();
                                    }
                                }
                            },
                        },
                        length: {
                            max: 34,
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'notificationPreference': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.notificationType_cd.required : false
                        },
                        definitionAwareValue: {
                            definitionItems: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.notificationType.items
                        }
                    },
                    'emailAddress': {
                        required: {},
                        email: {}
                    }
                }
            };

            return config;
        };


        self.beginEmailVerificationMode = function () {
            self.contactInfoEmailVerificationViewModel.emailAddress(self.emailAddress());
            self.contactInfoEmailVerificationViewModel.initEmailVerification();
            self.isEmailVerificationMode(true);
        } 

        self.cancelEmailVerificationMode = function () {
            self.isEmailVerificationMode(false);
            $('#verify-email-contact-info-link').focus();
            layoutHelper.tabbing.updateIndices();
        }

        self.resetEmailAddress = function(newEmailAddress) {
            self.emailAddress(newEmailAddress);

            if (self.editableItem()) {
                self.editableItem().emailAddress(newEmailAddress);
            }
        };

        self.updateContactInfoAfterEmailChange = function (options) {

            self.isEmailVerified(false);
            if (options && options.isEmailChanged) self.resetEmailAddress(self.initialEmail());

            if (window.utils.getUrlParameter("redirectToVerifyAccountPage")) {
                window.location = options.forceRedirectUrl;
            } else {
                self.beginEmailVerificationMode();
            }

        };

        self.goToApplicationProcess = function() {
            var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

            if (applicationProcessUrl) {
                sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                window.location = applicationProcessUrl;
            }
        };

        self.updateAccessToContactInfoSaveButton = function(isSaveButtonDisabled) {
            if ($(contactInfoSaveButtonSelector).length) $(contactInfoSaveButtonSelector).prop('disabled', isSaveButtonDisabled);
        };

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.name.fromDataModel(data.name);
            initialFullName = self.name.fullName();
            self.address.fromDataModel(data.address);
            self.phone.fromDataModel(data.phone);
            self.notificationPreference(data.notificationPreference ? data.notificationPreference.toString():"1"); // Email is default

            self.initialEmail(data.initialEmail || data.emailAddress);
            self.emailAddress(data.emailAddress);
            self.isGoogleSignIn(data.isGoogleSignIn);

            self.isEmailEditable(self.isEmailEditable() || data.isEmailEditable || !data.emailAddress || false);

            if (data.isPasswordSet != undefined)
            {
                self.isPasswordSet = data.isPasswordSet;
            }

            if (OnlineApp.ViewModels != null
                && OnlineApp.ViewModels.applicationViewModel != null
                && OnlineApp.ViewModels.applicationViewModel.jobId != null
                && OnlineApp.ViewModels.applicationViewModel.jobId() > 0) {
                self.jobId(OnlineApp.ViewModels.applicationViewModel.jobId());
            }

            self.registerValidation(self.getValidationConfig());

            $(document).trigger(OnlineApp.Events.CommonEventsNames.ContactInfomationAvailable, {
                firstName: self.name.firstName(),
                lastName: self.name.lastName(),
                email: self.emailAddress()
            });
        };

        var baseDiscardChanges = self.discardChanges;
        self.discardChanges = function (item, e) {            
            self.isDiscardChange(true);
            baseDiscardChanges.call(self, item, e);
            self.goToApplicationProcess();
        };

        self.saveChanges = (function(base) {
            return function(item) {
                var editableItem = self.editableItem(),
                    that = this,
                    saveChangesArguments = arguments,
                    promise;

                item.isBusy(true);
                self.updateAccessToContactInfoSaveButton(true);


                /*
                   Switch for email verification. The logic is similar the default but conditions related to the captcha were deleted 
                   and the final promise on getting saving result changed

                */
                if (self.enableEmailVerification()) {

                    if (editableItem.isEmailChanged() && self.isEmailEditable()) {


                        var isPasswordValid = (OnlineApp.ViewModels.accountSettingsViewModel 
                                && OnlineApp.ViewModels.accountSettingsViewModel.isImpersonatedJobSeeker) ||
                            !self.isPasswordSet ||
                            editableItem.currentPassword.validate();

                        if (!self.hasErrorPureComputed() && !isPasswordValid) {
                            self.isBusy(false);
                            self.updateAccessToContactInfoSaveButton(false);
                            triggerValidationFailedEvent(saveChangesArguments);
                            return false;
                        }
                    }

                    promise = $.when(function() { return true; });

                    //send request to email check service
                    if (editableItem && editableItem.emailAddress() !== self.initialEmail() && self.isEmailEditable()) {
                        editableItem.emailAddress.validate();

                        var isEmailAllowedRequestData = {
                            email: editableItem.emailAddress(),
                            captchaAnswer: editableItem.textCaptchaViewModel.userAnswer(),
                            password: editableItem.currentPassword()
                        }

                        if (!editableItem.emailAddress.hasError()) {
                            promise = promise.then(function() {
                                return OnlineApp.Services.authenticationService
                                    .isEmailAllowed(isEmailAllowedRequestData)
                                    .then(
                                        function(data) {
                            
                                            if (data.success) {
                                                editableItem.emailAddress.hasError(!data.isEmailAllowed);
                                                editableItem.isEmailNotAvailable(!data.isEmailAllowed);

                                                return data.isEmailAllowed;
                                            } else {

                                                var innerPromise;

                                                innerPromise = $.when(function() { return true; });

                                                innerPromise = innerPromise.then(function() {
                                                    if (data.errorPropertyName == 'Password') {
                                                        editableItem.currentPassword.validationMessage(data.errorMessage);
                                                        editableItem.currentPassword.hasError(true);
                                                        editableItem.currentPassword.isValidationMessageVisible(true);
                                                    }

                                                    return false;
                                                });
                                                
                                                return innerPromise;
                                            }


                                        },
                                        //fail callback
                                        function() {
                                            toastr.warning(Resources.NotificationMessages.ServiceUnavailable);

                                            return window.undefined;
                                        }
                                    );
                            });
                        }
                    }

                    editableItem.name.normalize();

                    var isResumeLoadedInCurrentSession = OnlineApp.ViewModels.applicationViewModel.importResumeViewModel &&
                        OnlineApp.ViewModels.applicationViewModel.importResumeViewModel.resumeUploadComplete();
                    if (!isResumeLoadedInCurrentSession && initialFullName && editableItem && editableItem.name.fullName() !== initialFullName) {
                        var deferred = $.Deferred();
                        OnlineApp.Controllers.notificationController.showCreateNewAccountNotification(function () {
                            deferred.then(function () {
                                return OnlineApp.Services.authenticationService.logout().done(
                                    function() {
                                        sessionStorage.setItem('shouldCreateNewAccount', "true");
                                        $(window).on('beforeunload', function () {
                                            $(window).scrollTop(0);
                                        });
                                        location.reload();
                                    });
                            });

                            deferred.resolve(false);
                        }, function () {
                            deferred.resolve(true);
                        });
                        promise = promise.then(function(isValid) {
                            if (isValid) {
                                return deferred; 
                            }
                            return false;
                        });
                    }

                    promise = promise.then(function (saveAllowed) {
                        if (saveAllowed) {
                            if (editableItem.isEmailChanged() && self.isEmailEditable()) {
                                gJobs.crossWindowCommunicationService.sendMessage(
                                    gJobs.subjects.EmailUpdated,
                                    editableItem.emailAddress()
                                );
                            }

                            var queryStringData = { 
                            fromAppProcess: self.fromAppProcess(),
                            returnUrl: encodeURIComponent(window.location.href)
                        };

                            if (self.enableEmailVerification()) {
                                if (window.utils.getUrlParameter("redirectToVerifyAccountPage")) {
                                    queryStringData.sendAccountVerifEmail = true;
                                }

                                var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                                if (applicationProcessUrl) {
                                    queryStringData.redirectionUrl = applicationProcessUrl;
                                    //sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);
                                }
                                 
                            }

                        var agencyFolderName = AgencyPages.pageInfoService ?
                            AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                            gJobs.pageInfoService.getCurrentAgencyPageFolderName();
                        
                        if (agencyFolderName) {
                            queryStringData.agencyFolderName = agencyFolderName;
                        }

                        var args = Array.prototype.slice.call(saveChangesArguments);
                        args.push(queryStringData);
                        
                        return base.apply(that, args);
                        } else {
                            triggerValidationFailedEvent(saveChangesArguments);
                        }

                        return window.undefined;
                    });

                    promise = promise
                        .done(function (data) {
                            if (self.isAccountSettingsPage()) {
                                if (data && data.isSuccess && data.payload && !data.payload.isImpersonatedJobSeeker) {
                                    if (data.payload.forceRedirectUrl) {
                                        window.location = data.payload.forceRedirectUrl;
                                        return;
                                    }

                                    var options = null;

                                    if (data.payload.isEmailChanged) {
                                        options = { changedEmailAddressWasAdded: true, isEmailChanged: data.payload.isEmailChanged, forceRedirectUrl: data.payload.forceRedirectUrl };
                                        gJobs.localStorageHelper.updateItemForMultipleTabs(OnlineApp.LocalStorageKeys.EmailWasChanged, "true");
                                        localStorage.setItem('updatedEmail', data.payload.updatedEmail);
                                    }

                                    if (self.fromAppProcess() || window.utils.getUrlParameter("changeEmail")) {
                                        if (data.payload.isEmailChanged) {
                                            gJobs.localStorageHelper.updateItemForMultipleTabs(
                                                OnlineApp.LocalStorageKeys.EmailWasChangedAndNewVerificationCodeSent,
                                                "true"
                                            );

                                            self.updateContactInfoAfterEmailChange(options);
                                        } else {
                                            self.goToApplicationProcess();
                                        }
                                    } else if (data.payload.isEmailChanged) {
                                        self.updateContactInfoAfterEmailChange(options);
                                    }

                                    if (window.enableTwoFactorAuthentication && data.payload.isEmailChanged) {
                                        $(document).trigger(OnlineApp.Events.CommonEventsNames.EmailWasChanged, options);
                                    }
                                }
                            }
                        })
                    .always(function() {
                        item.isBusy(false);
                        self.updateAccessToContactInfoSaveButton(false);
                        self.validate();
                    });

                    return promise;
            } else {
                if (editableItem.isEmailChanged() && self.isEmailEditable()) {

                    var isCaptchaSubmitted = captchaHelper.isCaptchaSubmitted;
                    editableItem.showCaptchaValidationMessage(!isCaptchaSubmitted);

                    var isPasswordValid = (OnlineApp.ViewModels.accountSettingsViewModel 
                            && OnlineApp.ViewModels.accountSettingsViewModel.isImpersonatedJobSeeker) ||
                        !self.isPasswordSet ||
                        editableItem.currentPassword.validate();

                    if (!self.hasErrorPureComputed() && 
                        !(isPasswordValid && ((isCaptchaSubmitted && !window.textCaptcha) || 
                            (window.textCaptcha && editableItem.textCaptchaViewModel.validate())))) {
                        self.isBusy(false);
                        self.updateAccessToContactInfoSaveButton(false);
                        triggerValidationFailedEvent(saveChangesArguments);
                        return false;
                    }
                }

                promise = $.when(function() { return true; });

                //send request to email check service
                if (editableItem && editableItem.emailAddress() !== self.initialEmail() && self.isEmailEditable()) {
                    editableItem.emailAddress.validate();

                    var isEmailAllowedRequestData = {
                        email: editableItem.emailAddress(),
                        captchaAnswer: editableItem.textCaptchaViewModel.userAnswer(),
                        password: editableItem.currentPassword()
                    }

                    if (!editableItem.emailAddress.hasError()) {
                        promise = promise.then(function() {
                            return OnlineApp.Services.authenticationService
                                .isEmailAllowed(isEmailAllowedRequestData)
                                .then(
                                    function(data) {
                                        if (editableItem.isEmailChanged() && !self.textCaptchaEnabled) {
                                            captchaHelper.resetCaptcha();
                                        }

                                        if (data.success) {
                                            editableItem.emailAddress.hasError(!data.isEmailAllowed);
                                            editableItem.isEmailNotAvailable(!data.isEmailAllowed);

                                            return data.isEmailAllowed;
                                        } else {
                                            var resetTextCaptcha = editableItem.textCaptchaViewModel.validate();

                                            var innerPromise;

                                            if (resetTextCaptcha) {
                                                innerPromise = editableItem.textCaptchaViewModel.resetCaptcha();
                                            } else {
                                                innerPromise = $.when(function() { return true; });
                                            }

                                            innerPromise = innerPromise.then(function() {
                                                if (data.errorPropertyName == 'Password') {
                                                    editableItem.currentPassword.validationMessage(data.errorMessage);
                                                    editableItem.currentPassword.hasError(true);
                                                    editableItem.currentPassword.isValidationMessageVisible(true);
                                                } else if (data.errorPropertyName == 'Captcha') {
                                                    editableItem.textCaptchaViewModel.userAnswer.hasError(true);
                                                    if (resetTextCaptcha) {
                                                        editableItem.textCaptchaViewModel.userAnswer.validationMessage('Captcha is invalid');
                                                    } else {
                                                        editableItem.textCaptchaViewModel.userAnswer.validationMessage('This field is required');
                                                    }
                                                    editableItem.textCaptchaViewModel.userAnswer.isValidationMessageVisible(true);
                                                }

                                                return false;
                                            });
                                            
                                            return innerPromise;
                                        }


                                    },
                                    //fail callback
                                    function() {
                                        toastr.warning(Resources.NotificationMessages.ServiceUnavailable);

                                        return window.undefined;
                                    }
                                );
                        });
                    }
                }

                editableItem.name.normalize();

                var isResumeLoadedInCurrentSession = OnlineApp.ViewModels.applicationViewModel.importResumeViewModel &&
                    OnlineApp.ViewModels.applicationViewModel.importResumeViewModel.resumeUploadComplete();
                if (!isResumeLoadedInCurrentSession && initialFullName && editableItem && editableItem.name.fullName() !== initialFullName) {
                    var deferred = $.Deferred();
                    OnlineApp.Controllers.notificationController.showCreateNewAccountNotification(function () {
                        deferred.then(function () {
                            return OnlineApp.Services.authenticationService.logout().done(
                                function() {
                                    sessionStorage.setItem('shouldCreateNewAccount', "true");
                                    $(window).on('beforeunload', function () {
                                        $(window).scrollTop(0);
                                    });
                                    location.reload();
                                });
                        });

                        deferred.resolve(false);
                    }, function () {
                        deferred.resolve(true);
                    });
                    promise = promise.then(function(isValid) {
                        if (isValid) {
                            return deferred; 
                        }
                        return false;
                    });
                }

                promise = promise.then(function (saveAllowed) {
                    if (saveAllowed) {
                        if (editableItem.isEmailChanged() && self.isEmailEditable()) {
                            gJobs.crossWindowCommunicationService.sendMessage(
                                gJobs.subjects.EmailUpdated,
                                editableItem.emailAddress()
                            );
                        }

                        var queryStringData = { fromAppProcess: self.fromAppProcess(), fromAccountSettings: self.isAccountSettingsPage() };

                        if (self.fromAppProcess()) {

                            var agencyFolderName = AgencyPages.pageInfoService ?
                                AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                                gJobs.pageInfoService.getCurrentAgencyPageFolderName();

                            if (agencyFolderName) {
                                queryStringData.agencyFolderName = agencyFolderName;
                            }
                        }

                            var args = Array.prototype.slice.call(saveChangesArguments);
                            args.push(queryStringData);

                            return base.apply(that, args);
                        } else {
                            triggerValidationFailedEvent(saveChangesArguments);
                        }

                        return window.undefined;
                    
                });

                promise = promise
                    .done(function (data) {
                        if (data && data.payload && data.payload.isEmailChanged) {
                            if (self.fromAppProcess()) {
                                localStorage.setItem('updatedEmail', data.payload.updatedEmail);
                                sessionStorage.setItem('emailWasChangedAndNewVerificationCodeSent', 'true');
                            }
                        }
                    })
                .always(function() {
                    item.isBusy(false);
                    self.updateAccessToContactInfoSaveButton(false);
                    self.validate();
                });

                return promise;
            }
        }
        })(self.saveChanges);

        function triggerValidationFailedEvent(event) {
            if (OnlineApp.Events) {
                var validationFailedEvent =
                    jQuery.Event(OnlineApp.Events.CommonEventsNames.PreSaveValidationFailed);
                validationFailedEvent.target = event.target;
                $(document).trigger(validationFailedEvent);
            }
        }

        gJobs.crossWindowCommunicationService.setListener(
            gJobs.subjects.EmailUpdated,
            function (newEmail) {
                self.emailAddress(newEmail);
                if (self.editableItem()) {
                    self.editableItem().emailAddress(newEmail);
                }
            }
        );

        self.emailFieldLoaded = function (elements) { 
            var emailInputField = $(elements).find('input');
            emailInputField.keydown(function(e) {
                var keyCode = e.keyCode || e.which;
                var isShiftPressed = e.shiftKey;
                setTimeout(function() {
                    if (!isShiftPressed && keyCode === $.ui.keyCode.TAB && self.isEmailEditable() && self.isEmailChanged()) {
                        $('#currentPassword').focus();
                    }
                });
            });
        }
        
        self.showHideAriaLabel = function () {
            if ($("fieldset.radio-set.css3-radio").length > 0) {
                $("fieldset.radio-set.css3-radio").each(function (i) {
                    $("fieldset.radio-set.css3-radio")[i].removeAttribute("aria-required");
                });
            }
        }

        if (self.enableEmailVerification()) {
            OnlineApp.Services.authenticationService.isLoggedIn()
            .done(function(isLoggedIn) {
                if (isLoggedIn) {
                    OnlineApp.Services.emailVerificationService.isEmailVerified()
                        .then(function(response) {
                        var data = response.data;
        
                        self.isEmailVerified(data.isEmailVerified);
                        });
                }
            });

            $(document).on(OnlineApp.Events.CommonEventsNames.EmailVerified, function (event, data) {
                self.isEmailVerificationMode(false);
                self.isEmailVerified(true);

                if (self.contactInfoEmailVerificationViewModel) {
                    self.contactInfoEmailVerificationViewModel
                        .emailVerificationViewModel
                        .changedEmailAddressWasAdded = ko.observable(false);
                }

                if (data && data.changedEmailAddress) {
                    self.initialEmail(data.changedEmailAddress);
                    self.resetEmailAddress(data.changedEmailAddress);
                }

                var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                if (applicationProcessUrl) {
                    sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                    window.location = applicationProcessUrl;
                }
            });

            $(document).on(OnlineApp.Events.CommonEventsNames.ContactInfoEmailVerificationFormClosed, self.cancelEmailVerificationMode);

            var loginEvents = Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;

            $(document).on(loginEvents, function () {
                self.initContactInfoEmailVerificationViewModel();
            });
        }
    };


    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        ContactInfoViewModel: ContactInfoViewModel
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function EmailVerificationViewModel(options) {
        var options = options ? options : {};
        
        var RESEND_VERIFICATION_CODE_ATTEMPTS_COUNT_WITHOUT_CAPTCHA = window.emailVerificationResendAttempts;
        var VERIFICATION_CODE_VERIFY_ATTEMPTS_COUNT_WITHOUT_CAPTCHA = window.emailVerificationVerifyAttempts;
        var CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE = "<span>Please answer the question to <b>resend</b> a code again</span>";
        var CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE = "<span>Please answer the question to <b>verify</b> a code again</span>";
        var CAPTCHA_INVALID_MESSAGE = "Captcha is invalid";
        var CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE = "captcha-user-answer-for-verify-code";
        var CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE = "captcha-user-answer-for-resend-code";
        var INSTRUCTIONS_MESSAGE_FOR_SENT_CODE = "We've sent a " + window.emailVerificationCodeLength +
            " digit code to your email address and the code is only valid for " + window.emailVerificationCodeDurationInMins +
            " minutes. Please enter the code below. ";

        var verificationCodeInput;
        var lastFocusableElement;

        var isUserDataInitiated = false;
        var emailWasChangedAndNewVerificationCodeSent = false;

        var self = OnlineApp.ViewModels.Base.ValidatableViewModel.apply(this, arguments) || this;

        self.enableEmailVerification = ko.observable(window.enableEmailVerification);

        self.isNeedToHideHeader = ko.observable(options.isNeedToHideHeader);
        self.isNeedToHideInstructions = ko.observable(options.isNeedToHideInstructions);
        self.verificationCodeLabelText = ko.observable(options.verificationCodeLabelText ? options.verificationCodeLabelText : "Verification code");
        self.verificationCodeAriaLabelText = ko.observable(
            options.isNeedToHideInstructions
            ? INSTRUCTIONS_MESSAGE_FOR_SENT_CODE + self.verificationCodeLabelText()
            : self.verificationCodeLabelText());
        self.useCustomVerifyButton = ko.observable(options.useCustomVerifyButton);
        
        var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();

        self.textCaptchaViewModelForResendCode = new OnlineApp.ViewModels.TextCaptchaViewModel("ResendEmailVerificationCodeAnswer");
        self.textCaptchaViewModelForVerificationCode = new OnlineApp.ViewModels.TextCaptchaViewModel("VerifyEmailVerificationCodeAnswer");

        self.textCaptchaEnabled = window.textCaptcha;
        self.isNeedToShowEmailVerificationForm = ko.observable(false);
        self.isEmailVerified = ko.observable();
        self.userEmail = ko.observable();
        self.verificationAttemptsCount = ko.observable(0);
        self.resendEmailVerificationCount = ko.observable(0);
        self.isEmailVerificationSubmitButtonEnabled = ko.observable(false);
        self.emailVerificationCode = ko.observable("").extend({
            required: {},
            verificationCode: {
                regExpForValueTransform: /_/g,
                validationMessage: OnlineApp.Validation.validationMessages.invalidEmailVerificationCode
            }
        });

        self.emailVerificationCode.subscribe(function(newValue) {
            if (newValue !== "" && self.emailVerificationCode.validate(newValue)) {
                self.isEmailVerificationSubmitButtonEnabled(true);
            } else {
                self.isEmailVerificationSubmitButtonEnabled(false);
            }
            
            OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();
        });

        self.changedEmailAddressWasAdded = ko.observable(false);

        function updateFieldErrorState (field, hasError, errorMessage) {
            field.hasError(hasError);
            field.isValidationMessageVisible(hasError);

            if (hasError && errorMessage) {
                field.validationMessage(errorMessage);
            }
        };

        function resetCaptcha (textCaptchaViewModel, htmlContentForLabel, captchaUserAnswerId) {
            textCaptchaViewModel.setCustomLabelHtmlContent(htmlContentForLabel);
            textCaptchaViewModel.setCustomUserAnswerInputId(captchaUserAnswerId);

            return textCaptchaViewModel.resetCaptcha(
                textCaptchaViewModel.userAnswer.hasError(),
                CAPTCHA_INVALID_MESSAGE
            );
        };

        function removeItemFromLocalStorage(key, delay) {
            setTimeout(function () {
                localStorage.removeItem(key);
            }, delay);
        }

        function checkEmailForUpdate() {
            setInterval(function() {
                if (localStorage.getItem('updatedEmail')  && localStorage.getItem('updatedEmail') !== self.userEmail()) {
                    self.userEmail(localStorage.getItem('updatedEmail'));
                    removeItemFromLocalStorage('updatedEmail', 5000);
                }
            }, 5000)
        }

        function tryFocusOnErrorCaptcha (isEmailVerificationContainerVisible, captchaUserAnswerInputId) {
            if (isEmailVerificationContainerVisible
                && lastFocusableElement.length
                && lastFocusableElement.attr('id') === captchaUserAnswerInputId
            ) {
                $("#" + captchaUserAnswerInputId).focus();
            }
        }

        self.initUserData = function (options) {
            self.emailVerificationCode('');
            updateFieldErrorState( self.emailVerificationCode, false);
            updateFieldErrorState(self.textCaptchaViewModelForResendCode.userAnswer, false);
            updateFieldErrorState(self.textCaptchaViewModelForVerificationCode.userAnswer, false);

            OnlineApp.Services.emailVerificationService
            .getUserData()
            .then(function (response) {
                var data = response.data;

                self.isEmailVerified(data.isEmailVerified);
                self.userEmail(data.userEmail);
                self.verificationAttemptsCount(data.verificaitonAttempts)
                self.resendEmailVerificationCount(data.resendEmailVerificationCount);

                if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                    resetCaptcha(
                        self.textCaptchaViewModelForResendCode, 
                        CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                        CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                    );
                }

                if (self.isNeedToShowVerificationCodeCaptcha()) {
                    resetCaptcha(
                        self.textCaptchaViewModelForVerificationCode, 
                        CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                        CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                    );
                }

                if (!self.isEmailVerified()) {
                    checkEmailForUpdate();
                    self.isNeedToShowEmailVerificationForm(true);
                }

                isUserDataInitiated = true;

                if (options && options.changedEmailAddressWasAdded) {
                    self.isEmailVerified(false);
                    updateFieldErrorState(self.emailVerificationCode, false);
                    self.emailVerificationCode('');
                }

                self.onReady();
            });
        }

        self.onReady = function () {
            verificationCodeInput = $('#verification-code');
            verificationCodeInput.inputmask({'mask': '999999'});

            if (verificationCodeInput.length) verificationCodeInput.focus();
        }

        self.init = function () {
            if (self.enableEmailVerification()) {
                if (!isUserDataInitiated) {
                    self.initUserData();
                }

                OnlineApp.Services.emailVerificationService.trySendEmailVerificationCode();
            }
        }

        self.resetForm = function () {
            if (self.isNeedToShowVerificationCodeCaptcha()) {
                updateFieldErrorState(self.textCaptchaViewModelForVerificationCode.userAnswer, false);

                resetCaptcha(
                    self.textCaptchaViewModelForVerificationCode,
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                );
            }

            if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                updateFieldErrorState(self.textCaptchaViewModelForResendCode.userAnswer, false);

                resetCaptcha(
                    self.textCaptchaViewModelForResendCode,
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                );
            }

            self.emailVerificationCode("");
            updateFieldErrorState(self.emailVerificationCode, false);
        }

        self.goToAccountSettingsPage = function() {
            var QUERY_PARAMETERS = '?fromAppProcess=true#contact';

            var linkForAccountSettings = gJobs.accountSettingsHelper.getLinkForAccountSettings();
            linkForAccountSettings += QUERY_PARAMETERS;

            sessionStorage.setItem(OnlineApp.SessionKeys.ApplicationProcessUrl, window.location.href);

            window.location = linkForAccountSettings;
        };

        self.showSuccessNotification = function (htmlContent) {
            var successEmailNotificationEventName = "successEmailNotification";
            var successEmailNotificationSelector = "success-email-notification";
            var successEmailNotification = $('#' + successEmailNotificationSelector);

            if (successEmailNotification.length !== 0) {
                successEmailNotification.html(htmlContent);
                successEmailNotification.css("display", "flex");
            } else {
                $('body').append(
                    "<div class='uses-gjobs-styles'><div id='" + successEmailNotificationSelector + "'>" + htmlContent + "</div></div>"
                );

                successEmailNotification = $('#' + successEmailNotificationSelector);
            }

            gJobs.screenReadersService.setAriaLiveNotification(successEmailNotification.text());

            $(document).on('click.' + successEmailNotificationEventName, function () {
                if (successEmailNotification.is(":visible")) {
                    successEmailNotification.css("display", "none");
                }
            });

            setTimeout(function () {
                if (successEmailNotification.is(":visible")) {
                    successEmailNotification.css("display", "none");
                }

                $(document).off('click.' + successEmailNotificationEventName);
            }, 10000)
        }

        self.showResendCodeSuccessNotification = function () {
            var htmlContent = "<div class='success-email-notification-holder'><span>A new verification code has been sent to your email address</span></div>";

            self.showSuccessNotification(htmlContent);
        }

        self.showResendCodeOnNewEmailNotification = function () {
            var htmlContent = "<div class='success-email-notification-holder'><span>A new verification code has been sent to your new email address</span></div>";
        
            self.showSuccessNotification(htmlContent);
        }

        self.showSuccessEmailVerifcationNotification = function () {
            var htmlContent = "<div class='success-email-notification-holder'><img class='email-verification-success-icon' src='/Content/Images/email-verification-success-notification-icon-white.svg' /><span>Your account (" + self.userEmail() + ") is verified</span></div>";
        
            self.showSuccessNotification(htmlContent);
        }

        self.isNeedToShowResendVerificationCodeCaptcha = function () {
            return !self.isEmailVerified() && self.textCaptchaEnabled && (self.resendEmailVerificationCount() > RESEND_VERIFICATION_CODE_ATTEMPTS_COUNT_WITHOUT_CAPTCHA);
        }

        self.isNeedToShowVerificationCodeCaptcha = function () {
            return !self.isEmailVerified() && self.textCaptchaEnabled && (self.verificationAttemptsCount() > VERIFICATION_CODE_VERIFY_ATTEMPTS_COUNT_WITHOUT_CAPTCHA);
        }

        self.resendEmailVerificationCode = function () {
            if (self.isEmailVerified()) {
                return;
            }

            if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                if (!self.textCaptchaViewModelForResendCode.validate()) {
                    $('#' + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE).focus();
                    return;
                };
            }

            OnlineApp.Services.emailVerificationService
            .resendEmailVerificationCode(self.textCaptchaViewModelForResendCode.userAnswer(), self.changedEmailAddressWasAdded())
            .then(function (response) {
                var isCaptchaInvalid = false;
                var data = response.data;
                var newResendEmailVerificationCount = data.resendEmailVerificationCount;
                self.resendEmailVerificationCount(newResendEmailVerificationCount);

                if (data.isResendEmailSucceeded === false) {
                    if (data.isCaptchaInvalid === true) {
                        isCaptchaInvalid = true;
                        updateFieldErrorState(self.textCaptchaViewModelForResendCode.userAnswer, true, CAPTCHA_INVALID_MESSAGE);
                    }
                } else {
                    self.showResendCodeSuccessNotification();
                }

                if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                    resetCaptcha(
                        self.textCaptchaViewModelForResendCode, 
                        CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                        CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                    ).always(function () {
                        if (isCaptchaInvalid) {
                            $('#' + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE).focus();
                        }
                    });
                }
            });
        }


        self.getRedirectLinkForSuccessfullEmailVerification = function() {
                OnlineApp.Services
                .emailVerificationService
                .getRedirectLinkForSuccessfullEmailVerification()
                .done(function (response) {
                    var data = response.data;

                    if (data.redirectedLink !== "") {
                        window.location = data.redirectedLink;
                    }
                });
        }
        
        self.submitVerifyEmail = function () {
            self.isEmailVerificationSubmitButtonEnabled(false);

            if (self.isNeedToShowVerificationCodeCaptcha()) {
                if (!self.textCaptchaViewModelForVerificationCode.validate()) {
                    $("#" + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE).focus();
                    self.isEmailVerificationSubmitButtonEnabled(true);
                    return;
                };
            }            

            /*
                The default behavior assumes that the verify email button is not available until 
                a 6-digit code is entered, when the custom verify email button is used we cannot
                guarantee the same behavior, in this case we need to validate the email verification code

            */
            if (self.useCustomVerifyButton() && !self.emailVerificationCode.validate()) {
                updateFieldErrorState(self.emailVerificationCode, true);
                verificationCodeInput.focus();
                self.isEmailVerificationSubmitButtonEnabled(true);
                return;
            }

            var dataResponse = OnlineApp.Services
            .emailVerificationService
            .verifyEmail(self.emailVerificationCode(), self.textCaptchaViewModelForVerificationCode.userAnswer(), self.changedEmailAddressWasAdded())
            .done(function (response) {
                var isCaptchaInvalid = false;
                var data = response.data;
            
                if (data.isVerificationSucceeded === true) {   
                    self.isEmailVerified(true);

                    if (self.changedEmailAddressWasAdded()) {
                        self.userEmail(data.changedEmailAddress);
                    }

                    self.showSuccessEmailVerifcationNotification();
                    $(document).trigger(OnlineApp.Events.CommonEventsNames.EmailVerified, { changedEmailAddress: data.changedEmailAddress });
                    gJobs.localStorageHelper.updateItemForMultipleTabs(OnlineApp.LocalStorageKeys.EmailWasVerified, "true");
                } else {
                    var newVerificationAttemptsCount = self.verificationAttemptsCount() + 1;
                    self.verificationAttemptsCount(newVerificationAttemptsCount);

                    if (data.errorFieldName === "captcha") {
                        isCaptchaInvalid = true;
                        self.isEmailVerificationSubmitButtonEnabled(true);
                        updateFieldErrorState(self.textCaptchaViewModelForVerificationCode.userAnswer, true, CAPTCHA_INVALID_MESSAGE);
                    } else {
                        var errorMessage;

                        if (data.errorMessage === "error") {
                            errorMessage = "Invalid verification code";
                        } else if (data.errorMessage === "expired") {
                            errorMessage = "Code is expired. Please resend an email to get a new code";
                        }

                        updateFieldErrorState(self.emailVerificationCode, true, errorMessage);

                        verificationCodeInput.focus();
                    }

                    if (self.isNeedToShowVerificationCodeCaptcha()) {
                        resetCaptcha(
                            self.textCaptchaViewModelForVerificationCode, 
                            CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                            CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                        ).always(function() {
                            if (isCaptchaInvalid) {
                                $("#" + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE).focus();
                            }
                        });
                    }
                }
            });
        }

        self.updateVerificationCodeFormAfterEmailChange = function() {
            self.isEmailVerified(false);
            self.emailVerificationCode('');
        };

        window.onstorage = function (e) {
            if (e.key === OnlineApp.LocalStorageKeys.EmailWasChanged && e.newValue === "true") {
                self.initUserData();
            } else if (e.key === OnlineApp.LocalStorageKeys.EmailWasChangedAndNewVerificationCodeSent && e.newValue === "true") {
                emailWasChangedAndNewVerificationCodeSent = true;
            } else if (e.key === OnlineApp.LocalStorageKeys.EmailWasVerified && e.newValue === "true") {
                self.isEmailVerified(true);
                self.isNeedToShowEmailVerificationForm(false);
            }
        };

        $(window).focus(function () {
            var isEmailVerificationContainerVisible = $("#verify-email-container").is(":visible");
            
            if (emailWasChangedAndNewVerificationCodeSent) {
                if (isEmailVerificationContainerVisible) {
                    OnlineApp.Services.emailVerificationService.trySendEmailVerificationCode();
                }

                self.updateVerificationCodeFormAfterEmailChange();
                emailWasChangedAndNewVerificationCodeSent = false;
            }

            if (self.isNeedToShowVerificationCodeCaptcha()) {
                resetCaptcha(
                    self.textCaptchaViewModelForVerificationCode, 
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                ).always(function () {
                    tryFocusOnErrorCaptcha(isEmailVerificationContainerVisible, CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE);
                });
            }

            if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                resetCaptcha(
                    self.textCaptchaViewModelForResendCode, 
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                ).always(function () {
                    tryFocusOnErrorCaptcha(isEmailVerificationContainerVisible, CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE);
                });
            }
        });

        $(window).blur(function () {
            lastFocusableElement = $(document.activeElement);
        });
        
        $(document).on(OnlineApp.Events.CommonEventsNames.CertifySubmitTabOpened, function () {
            self.init();
        });

        $(document).on(OnlineApp.Events.CommonEventsNames.EmailWasChanged, function (event, data) {
            self.initUserData(data);
        });
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        EmailVerificationViewModel: EmailVerificationViewModel
    });

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

    function ContactInfoEmailVerificationViewModel() {
        var layoutHelper = OnlineApp.Helpers.layoutHelper;
        
        var self = this;

        self.emailAddress = ko.observable('');

        self.onReady = function () {
            layoutHelper.tabbing.activateFirstElement($('#contact-info-email-verification .email-verification-form-container'));
            layoutHelper.tabbing.updateIndices();
        }
        
        self.emailVerificationViewModel = new OnlineApp.ViewModels.EmailVerificationViewModel(
            { 
                isNeedToHideHeader: true, 
                isNeedToHideInstructions: true,
                verificationCodeLabelText: "Please enter the 6 digit code sent to your email address.",
                useCustomVerifyButton: true
            }
        ); 

        self.cancelEmailVerification = function () {
            if (self.emailVerificationViewModel.changedEmailAddressWasAdded()) {
                $(document).trigger(OnlineApp.Events.CommonEventsNames.ShowCancelVerificationRequestDialog);
            } else {
                self.emailVerificationViewModel.resetForm();

                $(document).trigger(OnlineApp.Events.CommonEventsNames.ContactInfoEmailVerificationFormClosed);

                var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                if (applicationProcessUrl) {
                    sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                    window.location = applicationProcessUrl;
                }
            }
        }

        self.initEmailVerification = function () {
            self.emailVerificationViewModel.init();
        }

        $(document).on(OnlineApp.Events.CommonEventsNames.ContactInfoEmailVerificationFormClosed, function() {
            if (self.emailVerificationViewModel.changedEmailAddressWasAdded()) {
                self.emailVerificationViewModel.resetForm();
            }

            self.emailVerificationViewModel.changedEmailAddressWasAdded = ko.observable(false);
        });
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        ContactInfoEmailVerificationViewModel: ContactInfoEmailVerificationViewModel
    });

})(window);
;
function TextMessagingPreferencesViewModel(config) {
    var defaultConfig = {
        endpoint: "textMessagingPreferences",
        passAgencyFolderName: true
    };

    var config = $.extend({}, defaultConfig, config);

    var self = OnlineApp.ViewModels.Base.EditableViewModel.call(this, config) || this;

    var TERMS_OF_USE_PAGE_PATH = window.CCPAChanges ? '/termsofuse' : '/legalprivacy';

    self.subscribedToTextMessages = ko.observable(false);

    self.isPhoneFieldVisible = ko.observable(false).extend({ ignoreOnSerialization: true });

    self.agencyName = ko.observable('');

    self.isOnGJobs = gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.GJobs;

    if (self.isOnGJobs) {
        self.agencyFolderName = gJobs.pageInfoService.getCurrentAgencyPageFolderName();
    }

    self.subscribedToTextMessages.subscribe(function(value) {
        self.isPhoneFieldVisible(value === true);

        if (value === true) {
            gJobs.screenReadersService.setAriaLiveNotification("Phone section has been opened.");
        } else if (value === false){
            gJobs.screenReadersService.setAriaLiveNotification("Phone section has been closed.");
        }
    });

    self.textMessagingPhone = ko.computed({
        read: function () {
            if (self.maskedTextMessagingPhone()) {
                return ko.utils.unwrapObservable(self.maskedTextMessagingPhone).replace(/-/g, '');
            }

            return '';
        },
        deferEvaluation: true
    });

    self.maskedTextMessagingPhone = ko.observable('').extend({
        required: {
            onlyIf: function () {
                return ko.utils.unwrapObservable(self.isPhoneFieldVisible) === true;
            }
        },
        regexp: {
            onlyIf: function () {
                return ko.utils.unwrapObservable(self.isPhoneFieldVisible) === true;
            },
            pattern: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/,
            validationMessage: 'Phone number should be 10 digits long'
        },
        ignoreOnSerialization: true
    });

    self.phoneFieldAfterRender = function () {
        $('#text-messaging-phone').inputmask({'mask': '999-999-9999'});
    }

    self.linkToTermsAndPrivacy = ko.computed({
        read: function () {
            var agencyHomePagePath = AgencyPages && AgencyPages.pageInfoService
                && AgencyPages.pageInfoService.getCurrentAgencyHomePath();

            if (agencyHomePagePath) {
                return agencyHomePagePath + TERMS_OF_USE_PAGE_PATH;
            }

            return '/home' + TERMS_OF_USE_PAGE_PATH;
        },
        deferEvaluation: true
    }).extend({ ignoreOnSerialization: true });

    self.toggleButtonText = function (toggleValue) {
        return toggleValue ? 'ON' : 'OFF';
    };

    self.validate = function () {
        return self.isPhoneFieldVisible() ? self.maskedTextMessagingPhone.validate() : true;
    }

    self.fromDataModel = function (data) {
        if (!data) {
            return;
        }

        if (data.subscribedToTextMessages !== null) {
            self.subscribedToTextMessages(data.subscribedToTextMessages);
        }

        if (data.agencyName !== null) {
            self.agencyName(data.agencyName);
        }

        self.maskedTextMessagingPhone(textMessagingPhoneToMaskedPhone(data.textMessagingPhone));

        return self;
    };

    var textMessagingPhoneToMaskedPhone = function(textMessagingPhone) {
        return textMessagingPhone
            ? textMessagingPhone.slice(0, 3) + '-' + textMessagingPhone.slice(3, 6) + '-' + textMessagingPhone.slice(6)
            : null;
    }
};

OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
    TextMessagingPreferencesViewModel: TextMessagingPreferencesViewModel
});;
(function (window, undefined) {
    'use strict';

    function CanvassQuestionViewModel() {
        var self = OnlineApp.ViewModels.Base.ValidatableViewModel.apply(this, arguments) || this;

        // Prevent invalid characters in number input (only allow whole numbers)
        self.onNumberInputKeydown = function (data, event) {
            // Allow navigation and editing keys
            if (
                event.ctrlKey || event.metaKey ||
                event.key === 'Backspace' || event.key === 'Tab' ||
                event.key === 'ArrowLeft' || event.key === 'ArrowRight' ||
                event.key === 'Delete' || event.key === 'Home' || event.key === 'End'
            ) {
                return true;
            }
            // Allow only digits (0-9)
            if (!/^[0-9]$/.test(event.key)) {
                event.preventDefault();
                return false;
            }
            return true;
        };

        // Prevent pasting non-numeric values
        self.onNumberInputPaste = function (data, event) {
            var paste = (event.clipboardData || window.clipboardData).getData('text');
            if (!/^[0-9]+$/.test(paste)) {
                event.preventDefault();
                return false;
            }
            return true;
        };

        self.id = ko.observable('');
        self.parentId = ko.observable('');
        self.question = ko.observable('');
        self.questionTypeId = ko.observable(0);
        self.name = ko.observable('');
        self.answer = ko.observable('');
        self.answerForTextArea = ko.observable('');
        self.checkBoxOneChecked = ko.observable('');
        self.checkBoxTwoChecked = ko.observable('');
        self.checkBoxThreeChecked = ko.observable('');
        self.children = ko.observableArray();
        self.attribute = ko.observable('');
        self.attributeValue = ko.observable('');
        self.level = ko.observable(0);
        self.sortOrder = ko.observable(0);
        self.isTouched = ko.observable(false);
        self.futureOptionRadioValue = ko.observable('');
        var isTouched = true;

        self.fromDataModel = function (data) {
            self.id(data.objectEntityId);
            self.question(data.question);
            self.children(data.children);
            self.questionTypeId(data.questionTypeId);
            self.name(data.name);
            self.parentId(data.parentId);
            self.attribute(data.attribute);
            self.attributeValue(data.attributeValue);
            self.level(data.level);
            self.sortOrder(data.sortOrder);
            self.answer(data.answer);
            self.answerForTextArea(data.answerForTextArea);
            self.checkBoxOneChecked(data.checkBoxOneChecked);
            self.checkBoxTwoChecked(data.checkBoxTwoChecked);
            self.checkBoxThreeChecked(data.checkBoxThreeChecked);
            self.futureOptionRadioValue(data.futureOptionRadioValue);

        }

        self.answer.isValidationMessageVisible = ko.computed({
            read: function () {
                var $canvassBody = $('#canvass-body');
                var isBuffalo = $canvassBody.find('.buffalo');

                if (isBuffalo) {
                    if (self.children()[3])
                        return self.hasError() && (self.children()[3].isTouched());
                    else if (self.children()[2]  && self.children()[2].children()[0])
                        return self.hasError() && self.children()[2].children()[0].isTouched() && window.checkBoxThreeChecked;
                    else if (self.children()[0])
                        return self.hasError() && self.children()[0].isTouched();
                    
                    else
                        return self.hasError()

                }
                else {
                    return self.hasError() && self.children()[0].isTouched();
                }
            },
            write: function () { }
        });

        self.onRadioGroupEnter = function (context, ev) {
            gJobs.screenReadersService.onceNotification({
                $element: $(ev.target),
                message: self.question()
            });
        }

        //subscription to answer observable to notify root view model that it needs to be validated
        self.answer.subscribe(function () {
            var questionnaireViewModel = null;
            if (self.answer()) {
                window.isCurrentOptionChecked = true;
            }

            if (gJobs.areaInfoService.getCurrentArea() == gJobs.areaInfoService.areaNames.Career) {
                questionnaireViewModel = agencyPages.canvassViewModel.questionnaireViewModel;
            } else {
                questionnaireViewModel = gJobs.applicationsPage ?
                    gJobs.applicationsPage.canvassViewModel.questionnaireViewModel :
                    gJobs.searchPage.canvassViewModel.questionnaireViewModel;
            }

            questionnaireViewModel.validateQuestionnaire();
            questionnaireViewModel.emptyChildNodesAnswers();
        });

        self.futureOptionRadioValue.subscribe(function () {
            var questionnaireViewModel = null;
            window.futureOptionRadioValue = self.futureOptionRadioValue();
            isTouched = false;            
            if (gJobs.areaInfoService.getCurrentArea() == gJobs.areaInfoService.areaNames.Career) {
                questionnaireViewModel = agencyPages.canvassViewModel.questionnaireViewModel;
            } else {
                questionnaireViewModel = gJobs.applicationsPage ?
                    gJobs.applicationsPage.canvassViewModel.questionnaireViewModel :
                    gJobs.searchPage.canvassViewModel.questionnaireViewModel;
            }

            

        });

        self.checkBoxOneChecked.subscribe(function () {
            var questionnaireViewModel = null;
            window.checkBoxOneChecked = self.checkBoxOneChecked();
            if (gJobs.areaInfoService.getCurrentArea() == gJobs.areaInfoService.areaNames.Career) {
                questionnaireViewModel = agencyPages.canvassViewModel.questionnaireViewModel;
            } else {
                questionnaireViewModel = gJobs.applicationsPage ?
                    gJobs.applicationsPage.canvassViewModel.questionnaireViewModel :
                    gJobs.searchPage.canvassViewModel.questionnaireViewModel;
            }

            questionnaireViewModel.validateQuestionnaire();
            questionnaireViewModel.emptyChildNodesAnswers();
        });

        self.checkBoxTwoChecked.subscribe(function () {
            var questionnaireViewModel = null;
            window.checkBoxTwoChecked = self.checkBoxTwoChecked();
            if (gJobs.areaInfoService.getCurrentArea() == gJobs.areaInfoService.areaNames.Career) {
                questionnaireViewModel = agencyPages.canvassViewModel.questionnaireViewModel;
            } else {
                questionnaireViewModel = gJobs.applicationsPage ?
                    gJobs.applicationsPage.canvassViewModel.questionnaireViewModel :
                    gJobs.searchPage.canvassViewModel.questionnaireViewModel;
            }

            questionnaireViewModel.validateQuestionnaire();
            questionnaireViewModel.emptyChildNodesAnswers();
        });

        self.checkBoxThreeChecked.subscribe(function () {
            var questionnaireViewModel = null;
            window.checkBoxThreeChecked = self.checkBoxThreeChecked();
            if (gJobs.areaInfoService.getCurrentArea() == gJobs.areaInfoService.areaNames.Career) {
                questionnaireViewModel = agencyPages.canvassViewModel.questionnaireViewModel;
            } else {
                questionnaireViewModel = gJobs.applicationsPage ?
                    gJobs.applicationsPage.canvassViewModel.questionnaireViewModel :
                    gJobs.searchPage.canvassViewModel.questionnaireViewModel;
            }

            questionnaireViewModel.validateQuestionnaire();
            questionnaireViewModel.emptyChildNodesAnswers();
        });


        self.registerValidation({
            'all': {
                'answer': {
                    required: {
                        onlyIf: function () {
                            return self.children() && self.children().length;
                        }
                    },
                    minValue: {
                        min: 1,
                        validationMessage: 'Error: Enter a number greater than 0',
                        onlyIf: function () {                              
                            return self.children() && self.children().length && self.children()[0].attributeValue() == 'number';
                        }
                    },
                    maxDigits: {
                        max: 5,
                        validationMessage: 'Error: Enter a number less than or equal to 99999',
                        onlyIf: function () {                            
                            return self.children() && self.children().length && self.children()[0].attributeValue() == 'number';
                        }
                    }
                }
            }
        });
    };

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        CanvassQuestionViewModel: CanvassQuestionViewModel
    });
})(window);;
(function (window, undefined) {
    'use strict';

    function CanvassQuestionnaireViewModel() {
        var self = this;

        self.dueDate = ko.observable('');
        self.selectedAnswer = ko.observable('');

        //questions array of question view models
        self.questionViewModels = ko.observableArray();
        self.questionViewModelsForFuturePosition = ko.observableArray();
        self.questionViewModelsForCurrentPosition = ko.observableArray();
        self.originalQuestions = [];
        self.isReadOnlyView = ko.observable(false);
        var isCheckBoxOneChecked = false;
        var isCheckBoxTwoChecked = false;
        var isCheckBoxThreeChecked = false;
        var answerForTextArea = '';
        var futureOptionRadioValue = '';
        var valueForCheckBoxOne = '';
        var valueForCheckBoxTwo = '';
        var valueForCheckBoxThree = '';


        self.fromDataModel = function (data, isReadOnlyView) {
            self.dueDate(data.dueDate);
            self.isReadOnlyView(isReadOnlyView);

            if (data.questions) {

                isCheckBoxOneChecked = false;
                isCheckBoxTwoChecked = false;
                isCheckBoxThreeChecked = false;
                answerForTextArea = '';
                futureOptionRadioValue = '';
                self.originalQuestions = data.questions;
                self.questionViewModels.removeAll();
                self.questionViewModels.push(generateQuestionsTree(data.questions));


            }

            self.isValid(false);
        }

        function filterQuestions(questions, start, count) {
            var childQuestions = questions.filter(function (q) {
                return q.parentQuestionnaireId != null;
            });

            var mainQuestions = questions.filter(function (q) {
                return q.parentQuestionnaireId == null;
            });

            mainQuestions.sort(function (a, b) {
                return a.sortOrder - b.sortOrder;
            });

            return mainQuestions.slice(start, start + count).concat(childQuestions);
        }

        self.getAnswers = function () {
            var questionsWithAnswers = flattenQuestionsTree();

            self.originalQuestions.forEach(function (question) {
                var isAnswered = questionsWithAnswers.some(function (answer) {
                    return answer.questionnaireId === question.questionnaireId;
                });

                if (!isAnswered) {
                    // TODO: Add enum for Radio checked/unchecked state
                    var answerForType = (question.questionTypeId === 5)
                        ? '0'  // In case it's a radiobutton with no selection
                        : '';
                    questionsWithAnswers.push({
                        questionnaireId: question.questionnaireId,
                        answer: answerForType,
                        isRequired: false,
                        questionTypeId: question.questionTypeId,
                        sortOrder: question.sortOrder
                    });
                }
            });

            var $canvassBody = $('#canvass-body .canvass-main-container');
            var isBuffalo = $canvassBody.find('.buffalo').length;
            if (isBuffalo >= 1) {
                for (var i = 0; i < questionsWithAnswers.length; i++) {
                    if (questionsWithAnswers[i].questionTypeId == 4 && (questionsWithAnswers[i].sortOrder == 0 || questionsWithAnswers[i].sortOrder == 3)) {

                        questionsWithAnswers[i].answer = window.checkBoxOneChecked == true ? "1" : "0";
                        questionsWithAnswers[i].isRequired = window.checkBoxOneChecked == true ? true : false;
                    }
                    if (questionsWithAnswers[i].questionTypeId == 4 && (questionsWithAnswers[i].sortOrder == 1 || questionsWithAnswers[i].sortOrder == 4)) {

                        questionsWithAnswers[i].answer = window.checkBoxTwoChecked == true ? "1" : "0";;
                        questionsWithAnswers[i].isRequired = window.checkBoxOneChecked == true ? true : false;
                    }
                    if (questionsWithAnswers[i].questionTypeId == 4 && (questionsWithAnswers[i].sortOrder == 2 || questionsWithAnswers[i].sortOrder == 5)) {

                        questionsWithAnswers[i].answer = window.checkBoxThreeChecked == true ? "1" : "0";;
                        questionsWithAnswers[i].isRequired = window.checkBoxOneChecked == true ? true : false;
                    }
                    if (questionsWithAnswers[i].questionTypeId == 5 && questionsWithAnswers[i].sortOrder == 3) {

                        questionsWithAnswers[i].answer = window.futureOptionRadioValue == questionsWithAnswers[i].questionnaireId ? "1" : "0";
                        questionsWithAnswers[i].isRequired = true;
                    }
                    if (questionsWithAnswers[i].questionTypeId == 5 && questionsWithAnswers[i].sortOrder == 4) {

                        questionsWithAnswers[i].answer = window.futureOptionRadioValue == questionsWithAnswers[i].questionnaireId ? "1" : "0";
                        questionsWithAnswers[i].isRequired = true;
                    }
                    if (questionsWithAnswers[i].questionTypeId == 1 && questionsWithAnswers[i].sortOrder == 6 && window.checkBoxThreeChecked) {

                        questionsWithAnswers[i].answer = window.textForTextArea;
                    }

                }
            }
            return questionsWithAnswers;
        }

        self.emptyChildNodesAnswers = function () {

            var questions = self.questionViewModels();


            if (questions && questions.length > 0) {
                emptyChildNodesAnswersRecursive(questions[0]);
            }

        }

        self.isValid = ko.observable(false);

        self.validateQuestionnaire = function () {
            var $canvassBody = $('#canvass-body');
            var isBuffalo = $canvassBody.find('.buffalo');
            if (isBuffalo.length == 0) {
                var isValid = true;
                var questions = self.questionViewModels();
                if (questions && questions.length > 0) {
                    isValid = isValidRecursive(questions[0]);
                    self.isValid(isValid);
                } else {
                    self.isValid(true);
                }
            }
            else {
                var isValid = true;
                var isValidCheckBox = true;
                var questions = self.questionViewModels();
                if (questions && questions.length > 0) {
                    isValid = isValidRecursive(questions[0]);
                    for (var i = 0; i < self.originalQuestions.length; i++) {
                        if (questions[0].answer() == self.originalQuestions[i].questionnaireId && self.originalQuestions[i].questionTypeId == 5 && self.originalQuestions[i].sortOrder == 2) {

                            if (window.checkBoxOneChecked || window.checkBoxTwoChecked || window.checkBoxThreeChecked) {
                                isValidCheckBox = true;
                            }
                            else {
                                isValidCheckBox = false;
                            }
                            break;

                        }                        
                    }
                    for (var i = 0; i < self.originalQuestions.length; i++) {
                        if (self.originalQuestions[i].questionTypeId == 1 && self.originalQuestions[i].sortOrder == 6 && !window.checkBoxThreeChecked) {
                            isValid = true;
                        }
                    }
                    if (isValid && isValidCheckBox) {
                        self.isValid(true);
                    }
                    else {
                        self.isValid(false);
                    }

                } else {
                    self.isValid(true);
                }


            }



        };



        // to do: make reusable recursive function
        function emptyChildNodesAnswersRecursive(parent, grandparent) {

            var children = parent.children();
            if (children) {
                children.forEach(function (item) {
                    if (grandparent && grandparent.answer && grandparent.answer() != parent.id()) {
                        parent.answer('');
                        parent.checkBoxOneChecked('');
                        parent.checkBoxTwoChecked('');
                        parent.checkBoxThreeChecked('');
                        item.isTouched(false);
                    }
                    emptyChildNodesAnswersRecursive(item, parent);
                });
            }

        }

        function flattenQuestionsTree() {

            var questions = [];

            ko.utils.arrayForEach(self.questionViewModels(), function (vm) {
                flattenNode(vm, questions);
            });


            return questions;
        }

        function flattenNode(node, arr) {
            if (!node) return;

            if (node.id()) {
                var answerForType = (node.questionTypeId() === 5 || node.questionTypeId() === 4)
                    ? '1'  // In case it's a selected radiobutton
                    : node.answer();
                arr.push({
                    questionnaireId: node.id(),
                    answer: answerForType,
                    isRequired: true,
                    questionTypeId: node.questionTypeId(),
                    sortOrder: node.sortOrder()
                });
            }

            if (node.children()) {
                // Searching for a text field or a radio button with answer among children
                var filteredNodes = node.children().filter(function (childNode) {
                    return (childNode.questionTypeId() === 1)
                        || (childNode.id() == node.answer());
                });
                var answerNode = filteredNodes ? filteredNodes[0] : null;

                if (answerNode && answerNode.questionTypeId() === 1) {
                    arr.push({
                        questionnaireId: answerNode.id(),
                        answer: node.answer(),
                        isRequired: true
                    });
                } else {
                    flattenNode(answerNode, arr);
                }
            }
        }

        function isValidRecursive(parent, grandparent) {
            var isValid = true;

            if (grandparent && grandparent.answer && grandparent.answer() == parent.id()) {
                isValid = parent.validate();
            }

            var children = parent.children();
            if (children && isValid) {
                children.forEach(function (item) {
                    var isValidChild = isValidRecursive(item, parent);
                    isValid = isValid && isValidChild;
                });
            }

            return isValid;
        }

        function generateQuestionsTree(questions) {
            return generateNode(questions, {}, 0, null);
        }


        function getAnswerAmongChildren(children) {
            if (children) {
                for (var i = 0; i < children.length; i++) {
                    var item = children[i];

                    if (item.questionTypeId == 1) {
                        return item.answer;
                    } else if ((item.questionTypeId == 5 || item.questionTypeId == 4) && (item.answer == 1)) {
                        return item.questionnaireId;
                    }
                }
            }
        }

        function generateNode(questions, nodeQuestion, level, parentId, answer) {
            var children = getChildren(questions, nodeQuestion.questionnaireId, level);
            var vm = new OnlineApp.ViewModels.CanvassQuestionViewModel();

            var $canvassBody = $('#canvass-body .canvass-main-container');
            var isBuffalo = $canvassBody.find('.buffalo').length;


            if (isBuffalo == 1) {
                if (nodeQuestion.questionTypeId == 4 && (nodeQuestion.sortOrder == 0 || nodeQuestion.sortOrder == 3) && nodeQuestion.answer == "1") {
                    isCheckBoxOneChecked = true;
                    valueForCheckBoxOne = nodeQuestion.questionnaireId;
                }
                if (nodeQuestion.questionTypeId == 4 && (nodeQuestion.sortOrder == 1 || nodeQuestion.sortOrder == 4) && nodeQuestion.answer == "1") {
                    isCheckBoxTwoChecked = true;
                    valueForCheckBoxTwo = nodeQuestion.questionnaireId;
                }
                if (nodeQuestion.questionTypeId == 4 && (nodeQuestion.sortOrder == 2 || nodeQuestion.sortOrder == 5) && nodeQuestion.answer == "1") {
                    isCheckBoxThreeChecked = true;
                    valueForCheckBoxThree = nodeQuestion.questionnaireId;
                }
                if (nodeQuestion.questionTypeId == 1 && nodeQuestion.sortOrder != 0) {
                    answerForTextArea = nodeQuestion.answer;
                }
                if (nodeQuestion.questionTypeId == 5 && nodeQuestion.sortOrder == 3 && nodeQuestion.answer == "1") {
                    futureOptionRadioValue = nodeQuestion.questionnaireId;
                }
                if (nodeQuestion.questionTypeId == 5 && nodeQuestion.sortOrder == 4 && nodeQuestion.answer == "1") {
                    futureOptionRadioValue = nodeQuestion.questionnaireId;
                }

                var treeNode = {
                    id: nodeQuestion.questionnaireId,
                    objectEntityId: nodeQuestion.questionnaireId,
                    parentId: parentId,
                    question: ConvertStringToHTML(nodeQuestion.question),
                    questionTypeId: nodeQuestion.questionTypeId,
                    attribute: nodeQuestion.questionnaireAttributeTypeCode,
                    attributeValue: nodeQuestion.attributeValue,
                    level: level,
                    required: true,
                    children: children.childNodes,
                    name: nodeQuestion.questionTypeId == 5 ? "cf-" + window.capacity : "cf-" + level,
                    sortOrder: nodeQuestion.sortOrder,
                    answer: nodeQuestion.questionTypeId == 4 ? undefined : children.answer != undefined ? children.answer.toString() : "",
                    checkBoxOneChecked: isCheckBoxOneChecked == true ? valueForCheckBoxOne : undefined,
                    checkBoxTwoChecked: isCheckBoxTwoChecked == true ? valueForCheckBoxTwo : undefined,
                    checkBoxThreeChecked: isCheckBoxThreeChecked == true ? valueForCheckBoxThree : undefined,
                    answerForTextArea: answerForTextArea,
                    futureOptionRadioValue: futureOptionRadioValue


                };
                vm.fromDataModel(treeNode);
            }
            else {
                var treeNode = {
                    id: nodeQuestion.questionnaireId,
                    objectEntityId: nodeQuestion.questionnaireId,
                    parentId: parentId,
                    question: nodeQuestion.question,
                    questionTypeId: nodeQuestion.questionTypeId,
                    attribute: nodeQuestion.questionnaireAttributeTypeCode,
                    attributeValue: nodeQuestion.attributeValue,
                    level: level,
                    required: true,
                    children: children.childNodes,
                    name: "cf-" + level,
                    sortOrder: nodeQuestion.sortOrder,
                    answer: children.answer != undefined ? children.answer.toString() : "",
                };
                vm.fromDataModel(treeNode);
            }

            return vm;
        }

        let ConvertStringToHTML = function (str) {
            let parser = new DOMParser();
            let doc = parser.parseFromString(str, 'text/html');
            return doc.body;
        };

        function getChildren(questions, id, level) {
            var childQuestions = questions.filter(function (q) {
                return q.parentQuestionnaireId == id;
            });

            childQuestions = childQuestions.sort(function (a, b) {
                return a.sortOrder - b.sortOrder;
            });

            var answer = getAnswerAmongChildren(childQuestions);
            var childNodes = childQuestions.map(function (q) {
                return generateNode(questions, q, level + 1, id);
            });

            return { childNodes: childNodes, answer: answer };
        }
    };

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        CanvassQuestionnaireViewModel: CanvassQuestionnaireViewModel
    });
})(window);
function blurRadio(radioName, radioValidationClass, event) {
    var radio = document.getElementsByName(radioName);
    var flag = false;
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            flag = true;
        }
    }
    if (!flag) {
        $('.' + radioValidationClass).removeAttr('hidden');
        if (event.relatedTarget.name != radioName) {
            gJobs.screenReadersService.setAriaLiveNotification("Error:This field is required");
        }
    }
    else {
        $('.' + radioValidationClass).attr('hidden', 'true');
    }
}
function focusRadio(radioName, radioValidationClass) {
    setTimeout(function () {
        if (!($('.' + radioValidationClass).attr('hidden') == 'hidden' || $('.' + radioValidationClass).attr('hidden') == 'true')) {
            gJobs.screenReadersService.setAriaLiveNotification("Error: This field is required");
        }
    }, 1000);
}
function getRadioValue(radioName, radioValidationClass) {
    $('.' + radioValidationClass).attr('hidden', 'true');
    var radio = document.getElementsByName(radioName);
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {

            document.getElementById(radio[i].id).setAttribute('aria-checked', 'true');
        }
        else {
            document.getElementById(radio[i].id).setAttribute('aria-checked', 'false');
        }
    }
}

function getCheckBoxValue() {

    var checkBox = document.getElementsByName('buffaloCheckBox');
    for (var i = 0; i < checkBox.length; i++) {
        if (checkBox[i].checked) {

            document.getElementById(checkBox[i].id).setAttribute('aria-checked', 'true');
        }
        else {
            document.getElementById(checkBox[i].id).setAttribute('aria-checked', 'false');
        }
    }
}

function textAreaValidation(event) {
    var id = event.target.id;
    var deferementTextArea = document.getElementById(id);
    if (deferementTextArea) {
        var text = document.getElementById(id).value;
        if (text != null && text != undefined && text != '') {
            document.getElementById(id).removeAttribute('aria-describedby');
            window.textForTextArea = text;
        }
        else {
            document.getElementById(id).setAttribute('aria-describedby', id + '-canvass-form-field-error-message');

        }
    }
}
function numberInputValidation(event) {
    var id = event.target.id;
    var inputElem = document.getElementById(id);
    if (inputElem) {
        var value = inputElem.value;
        // If the value is empty or invalid, set aria-describedby to the error message ID
        if (value == null || value === '' || isNaN(value) || parseFloat(value) < 1 || value.length > 5) {
            inputElem.setAttribute('aria-describedby', id + '-canvass-form-field-error-message');
        } else {
            inputElem.removeAttribute('aria-describedby');
        }
    }
};
(function (window, undefined) {
    'use strict';

    function CanvassViewModel() {
        var self = this;

        self.questionnaireViewModel = new OnlineApp.ViewModels.CanvassQuestionnaireViewModel();
        self.signatureViewModel = new OnlineApp.ViewModels.SignatureViewModel();

        self.isMobile = gJobs.browserDetector.isMobileBrowser();
        self.canvassId = ko.observable(0);
        self.title = ko.observable('');
        self.jobTitle = ko.observable('');
        self.dueDate = ko.observable('');
        self.dateAnswered = ko.observable('');
        self.description = ko.observable('');

        self.isBusy = ko.observable(false);
        self.isReadOnlyView = ko.observable(false);
        self.isSubmitted = false;

        self.phone = ko.computed({
            read: function () {
                if (self.maskedPhone()) {
                    return ko.utils.unwrapObservable(self.maskedPhone).replace(/-/g, '');
                }

                return '';
            },
            deferEvaluation: true
        });

        self.date = ko.computed({
            read: function () {
                if (self.maskedDate()) {
                    return ko.utils.unwrapObservable(self.maskedDate);
                }

                return '';
            },
            deferEvaluation: true
        });

        self.maskedPhone = ko.observable('').extend({
            required: {},
            regexp: {
                pattern: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/,
                validationMessage: 'Phone number should be 10 digits long'
            },
            ignoreOnSerialization: true
        });
        self.maskedDate = ko.observable('').extend({
            required: {},
            ignoreOnSerialization: true
        });

        self.phoneFieldAfterRender = function () {
            $('#canvass-form-phone').inputmask({ 'mask': '999-999-9999' });
        }
        self.dateFieldAfterRender = function () {
            $('#canvass-form-date').inputmask({ 'mask': 'MM/DD/YYYY' });                

        }



        self.isTemporaryUnavailabilitySectionVisible = ko.observable(false);
        self.TemporaryUnavailabilityReason = ko.observable('').extend({
            length: {
                max: 114,
                validationMessage: 'Unavailability reason is too long and is limited to 114 characters'
            }
        });

        self.isValid = ko.computed(function () {
            return self.isReadOnlyView()
                || (self.maskedPhone().trim() !== "" && !self.maskedPhone.hasError() && self.maskedDate().trim() !== "" && !self.maskedDate.hasError()
                    && self.questionnaireViewModel.isValid()
                    && self.signatureViewModel.isSignatureCompleted()
                    && !self.signatureViewModel.isSignatureInEditMode());
        });

        self.submit = function () {
            if (self.isSubmitted) {
                return;
            }

            self.isSubmitted = true;
            self.isBusy(true);
            var signature = self.signatureViewModel.signature();
            var answers = self.questionnaireViewModel.getAnswers();           

            OnlineApp.Services.dataService.canvassForm.post({
                sentCanvassFormId: self.canvassId(),
                signature: signature,
                phoneNumber: self.phone(),
                questionAnswers: answers
            })
                .then(function (data) {
                    if (data.isSuccess) {
                        OnlineApp.Services.canvassFlyoutService.closeCanvassFormFlyout();
                        OnlineApp.Services.canvassFlyoutService.changeCanvassFormStatus(self.canvassId(), data.dateAnswered, self.jobTitle());
                        toastr.success('Canvass form submitted');
                        gJobs.screenReadersService.setAriaLiveNotification('Canvass form submitted');
                        setTimeout(function () {
                            var $canvassFormLink = $('.canvass-container[data-canvass-id="' + self.canvassId() + '"]');
                            $canvassFormLink.find('.canvass-link').focus();
                        }, 1000);
                    }
                })
                .always(function () {
                    self.isSubmitted = false;
                    self.isBusy(false);
                    window.textForTextArea = "";
                });
        }

        self.fromDataModel = function (data) {
            self.canvassId(data.canvassFormId);
            self.jobTitle(data.jobTitle);
            self.dueDate(data.dueDate);
            self.dateAnswered(data.dateAnswered);
            self.description(data.description);
            self.isReadOnlyView(data.isReadOnly);
            var dateAnswered = new Date();

           
            $('#canvass-form-date').val(dt)
            
            if (self.isReadOnlyView()) {
                dateAnswered = new Date(data.dateAnswered);
               
                
                self.maskedPhone(formatAsPhoneNumber(data.phoneNumber));

                $('a.ss-print.popover-trigger')
                    .attr('href', '/applications/canvass/print/' + self.canvassId());
                $('a.ss-print.popover-trigger').show();
                $('a.ss-download.popover-trigger').show();
            } else {
                $('a.ss-print.popover-trigger').hide();
                $('a.ss-download.popover-trigger').hide();
            }

            var month = dateAnswered.getMonth() + 1;
            var day = dateAnswered.getDate();
            var year = dateAnswered.getFullYear();
            if (month < 10)
                month = '0' + month.toString();
            if (day < 10)
                day = '0' + day.toString();

            var dt = year + '-' + month + '-' + day;
            $('#canvass-form-date').attr('min', dt);
            $('#canvass-form-date').val(dt)
            $('#canvass-form-date').keydown();
            self.maskedDate(dt);

            self.questionnaireViewModel.fromDataModel(data, self.isReadOnlyView());
            self.signatureViewModel.signature(null);
            self.signatureViewModel.fromDataModel(data.signature, self.isReadOnlyView(), data.dateAnswered, data.applicantName);
            self.maskedPhone.isValidationMessageVisible(false);
            self.maskedPhone.hasError(false);
            self.maskedDate.isValidationMessageVisible(false);
            self.maskedDate.hasError(false);
        }

        function formatAsPhoneNumber(phone) {
            return phone.slice(0, 3) + '-' + phone.slice(3, 6) + '-' + phone.slice(6);
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        CanvassViewModel: CanvassViewModel
    });
})(window);;
typeof JSON != "object" && (JSON = {}), function () { "use strict"; function f(e) { return e < 10 ? "0" + e : e } function quote(e) { return escapable.lastIndex = 0, escapable.test(e) ? '"' + e.replace(escapable, function (e) { var t = meta[e]; return typeof t == "string" ? t : "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4) }) + '"' : '"' + e + '"' } function str(e, t) { var n, r, i, s, o = gap, u, a = t[e]; a && typeof a == "object" && typeof a.toJSON == "function" && (a = a.toJSON(e)), typeof rep == "function" && (a = rep.call(t, e, a)); switch (typeof a) { case "string": return quote(a); case "number": return isFinite(a) ? String(a) : "null"; case "boolean": case "null": return String(a); case "object": if (!a) return "null"; gap += indent, u = []; if (Object.prototype.toString.apply(a) === "[object Array]") { s = a.length; for (n = 0; n < s; n += 1) u[n] = str(n, a) || "null"; return i = u.length === 0 ? "[]" : gap ? "[\n" + gap + u.join(",\n" + gap) + "\n" + o + "]" : "[" + u.join(",") + "]", gap = o, i } if (rep && typeof rep == "object") { s = rep.length; for (n = 0; n < s; n += 1) typeof rep[n] == "string" && (r = rep[n], i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i)) } else for (r in a) Object.prototype.hasOwnProperty.call(a, r) && (i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i)); return i = u.length === 0 ? "{}" : gap ? "{\n" + gap + u.join(",\n" + gap) + "\n" + o + "}" : "{" + u.join(",") + "}", gap = o, i } } typeof Date.prototype.toJSON != "function" && (Date.prototype.toJSON = function (e) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null }, String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (e) { return this.valueOf() }); var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { "\b": "\\b", "	": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\" }, rep; typeof JSON.stringify != "function" && (JSON.stringify = function (e, t, n) { var r; gap = "", indent = ""; if (typeof n == "number") for (r = 0; r < n; r += 1) indent += " "; else typeof n == "string" && (indent = n); rep = t; if (!t || typeof t == "function" || typeof t == "object" && typeof t.length == "number") return str("", { "": e }); throw new Error("JSON.stringify") }), typeof JSON.parse != "function" && (JSON.parse = function (text, reviver) { function walk(e, t) { var n, r, i = e[t]; if (i && typeof i == "object") for (n in i) Object.prototype.hasOwnProperty.call(i, n) && (r = walk(i, n), r !== undefined ? i[n] = r : delete i[n]); return reviver.call(e, t, i) } var j; text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function (e) { return "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4) })); if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) return j = eval("(" + text + ")"), typeof reviver == "function" ? walk({ "": j }, "") : j; throw new SyntaxError("JSON.parse") }) }(), function (e, t) { "use strict"; var n = e.History = e.History || {}, r = e.jQuery; if (typeof n.Adapter != "undefined") throw new Error("History.js Adapter has already been loaded..."); n.Adapter = { bind: function (e, t, n) { r(e).bind(t, n) }, trigger: function (e, t, n) { r(e).trigger(t, n) }, extractEventData: function (e, n, r) { var i = n && n.originalEvent && n.originalEvent[e] || r && r[e] || t; return i }, onDomLoad: function (e) { r(e) } }, typeof n.init != "undefined" && n.init() }(window), function (e, t) { "use strict"; var n = e.document, r = e.setTimeout || r, i = e.clearTimeout || i, s = e.setInterval || s, o = e.History = e.History || {}; if (typeof o.initHtml4 != "undefined") throw new Error("History.js HTML4 Support has already been loaded..."); o.initHtml4 = function () { if (typeof o.initHtml4.initialized != "undefined") return !1; o.initHtml4.initialized = !0, o.enabled = !0, o.savedHashes = [], o.isLastHash = function (e) { var t = o.getHashByIndex(), n; return n = e === t, n }, o.isHashEqual = function (e, t) { return e = encodeURIComponent(e).replace(/%25/g, "%"), t = encodeURIComponent(t).replace(/%25/g, "%"), e === t }, o.saveHash = function (e) { return o.isLastHash(e) ? !1 : (o.savedHashes.push(e), !0) }, o.getHashByIndex = function (e) { var t = null; return typeof e == "undefined" ? t = o.savedHashes[o.savedHashes.length - 1] : e < 0 ? t = o.savedHashes[o.savedHashes.length + e] : t = o.savedHashes[e], t }, o.discardedHashes = {}, o.discardedStates = {}, o.discardState = function (e, t, n) { var r = o.getHashByState(e), i; return i = { discardedState: e, backState: n, forwardState: t }, o.discardedStates[r] = i, !0 }, o.discardHash = function (e, t, n) { var r = { discardedHash: e, backState: n, forwardState: t }; return o.discardedHashes[e] = r, !0 }, o.discardedState = function (e) { var t = o.getHashByState(e), n; return n = o.discardedStates[t] || !1, n }, o.discardedHash = function (e) { var t = o.discardedHashes[e] || !1; return t }, o.recycleState = function (e) { var t = o.getHashByState(e); return o.discardedState(e) && delete o.discardedStates[t], !0 }, o.emulated.hashChange && (o.hashChangeInit = function () { o.checkerFunction = null; var t = "", r, i, u, a, f = Boolean(o.getHash()); return o.isInternetExplorer() ? (r = "historyjs-iframe", i = n.createElement("iframe"), i.setAttribute("id", r), i.setAttribute("title", "t"), i.setAttribute("src", "#"), i.style.display = "none", n.body.appendChild(i), i.contentWindow.document.open(), i.contentWindow.document.close(), u = "", a = !1, o.checkerFunction = function () { if (a) return !1; a = !0; var n = o.getHash(), r = o.getHash(i.contentWindow.document); return n !== t ? (t = n, r !== n && (u = r = n, i.contentWindow.document.open(), i.contentWindow.document.close(), i.contentWindow.document.location.hash = o.escapeHash(n)), o.Adapter.trigger(e, "hashchange")) : r !== u && (u = r, f && r === "" ? o.back() : o.setHash(r, !1)), a = !1, !0 }) : o.checkerFunction = function () { var n = o.getHash() || ""; return n !== t && (t = n, o.Adapter.trigger(e, "hashchange")), !0 }, o.intervalList.push(s(o.checkerFunction, o.options.hashChangeInterval)), !0 }, o.Adapter.onDomLoad(o.hashChangeInit)), o.emulated.pushState && (o.onHashChange = function (t) { var n = t && t.newURL || o.getLocationHref(), r = o.getHashByUrl(n), i = null, s = null, u = null, a; return o.isLastHash(r) ? (o.busy(!1), !1) : (o.doubleCheckComplete(), o.saveHash(r), r && o.isTraditionalAnchor(r) ? (o.Adapter.trigger(e, "anchorchange"), o.busy(!1), !1) : (i = o.extractState(o.getFullUrl(r || o.getLocationHref()), !0), o.isLastSavedState(i) ? (o.busy(!1), !1) : (s = o.getHashByState(i), a = o.discardedState(i), a ? (o.getHashByIndex(-2) === o.getHashByState(a.forwardState) ? o.back(!1) : o.forward(!1), !1) : (o.pushState(i.data, i.title, encodeURI(i.url), !1), !0)))) }, o.Adapter.bind(e, "hashchange", o.onHashChange), o.pushState = function (t, n, r, i) { r = encodeURI(r).replace(/%25/g, "%"); if (o.getHashByUrl(r)) throw new Error("History.js does not support states with fragment-identifiers (hashes/anchors)."); if (i !== !1 && o.busy()) return o.pushQueue({ scope: o, callback: o.pushState, args: arguments, queue: i }), !1; o.busy(!0); var s = o.createStateObject(t, n, r), u = o.getHashByState(s), a = o.getState(!1), f = o.getHashByState(a), l = o.getHash(), c = o.expectedStateId == s.id; return o.storeState(s), o.expectedStateId = s.id, o.recycleState(s), o.setTitle(s), u === f ? (o.busy(!1), !1) : (o.saveState(s), c || o.Adapter.trigger(e, "statechange"), !o.isHashEqual(u, l) && !o.isHashEqual(u, o.getShortUrl(o.getLocationHref())) && o.setHash(u, !1), o.busy(!1), !0) }, o.replaceState = function (t, n, r, i) { r = encodeURI(r).replace(/%25/g, "%"); if (o.getHashByUrl(r)) throw new Error("History.js does not support states with fragment-identifiers (hashes/anchors)."); if (i !== !1 && o.busy()) return o.pushQueue({ scope: o, callback: o.replaceState, args: arguments, queue: i }), !1; o.busy(!0); var s = o.createStateObject(t, n, r), u = o.getHashByState(s), a = o.getState(!1), f = o.getHashByState(a), l = o.getStateByIndex(-2); return o.discardState(a, s, l), u === f ? (o.storeState(s), o.expectedStateId = s.id, o.recycleState(s), o.setTitle(s), o.saveState(s), o.Adapter.trigger(e, "statechange"), o.busy(!1)) : o.pushState(s.data, s.title, s.url, !1), !0 }), o.emulated.pushState && o.getHash() && !o.emulated.hashChange && o.Adapter.onDomLoad(function () { o.Adapter.trigger(e, "hashchange") }) }, typeof o.init != "undefined" && o.init() }(window), function (e, t) { "use strict"; var n = e.console || t, r = e.document, i = e.navigator, s = !1, o = e.setTimeout, u = e.clearTimeout, a = e.setInterval, f = e.clearInterval, l = e.JSON, c = e.alert, h = e.History = e.History || {}, p = e.history; try { s = e.sessionStorage, s.setItem("TEST", "1"), s.removeItem("TEST") } catch (d) { s = !1 } l.stringify = l.stringify || l.encode, l.parse = l.parse || l.decode; if (typeof h.init != "undefined") throw new Error("History.js Core has already been loaded..."); h.init = function (e) { return typeof h.Adapter == "undefined" ? !1 : (typeof h.initCore != "undefined" && h.initCore(), typeof h.initHtml4 != "undefined" && h.initHtml4(), !0) }, h.initCore = function (d) { if (typeof h.initCore.initialized != "undefined") return !1; h.initCore.initialized = !0, h.options = h.options || {}, h.options.hashChangeInterval = h.options.hashChangeInterval || 100, h.options.safariPollInterval = h.options.safariPollInterval || 500, h.options.doubleCheckInterval = h.options.doubleCheckInterval || 500, h.options.disableSuid = h.options.disableSuid || !1, h.options.storeInterval = h.options.storeInterval || 1e3, h.options.busyDelay = h.options.busyDelay || 250, h.options.debug = h.options.debug || !1, h.options.initialTitle = h.options.initialTitle || r.title, h.options.html4Mode = h.options.html4Mode || !1, h.options.delayInit = h.options.delayInit || !1, h.intervalList = [], h.clearAllIntervals = function () { var e, t = h.intervalList; if (typeof t != "undefined" && t !== null) { for (e = 0; e < t.length; e++) f(t[e]); h.intervalList = null } }, h.debug = function () { (h.options.debug || !1) && h.log.apply(h, arguments) }, h.log = function () { var e = typeof n != "undefined" && typeof n.log != "undefined" && typeof n.log.apply != "undefined", t = r.getElementById("log"), i, s, o, u, a; e ? (u = Array.prototype.slice.call(arguments), i = u.shift(), typeof n.debug != "undefined" ? n.debug.apply(n, [i, u]) : n.log.apply(n, [i, u])) : i = "\n" + arguments[0] + "\n"; for (s = 1, o = arguments.length; s < o; ++s) { a = arguments[s]; if (typeof a == "object" && typeof l != "undefined") try { a = l.stringify(a) } catch (f) { } i += "\n" + a + "\n" } return t ? (t.value += i + "\n-----\n", t.scrollTop = t.scrollHeight - t.clientHeight) : e || c(i), !0 }, h.getInternetExplorerMajorVersion = function () { var e = h.getInternetExplorerMajorVersion.cached = typeof h.getInternetExplorerMajorVersion.cached != "undefined" ? h.getInternetExplorerMajorVersion.cached : function () { var e = 3, t = r.createElement("div"), n = t.getElementsByTagName("i"); while ((t.innerHTML = "<!--[if gt IE " + ++e + "]><i></i><![endif]-->") && n[0]); return e > 4 ? e : !1 }(); return e }, h.isInternetExplorer = function () { var e = h.isInternetExplorer.cached = typeof h.isInternetExplorer.cached != "undefined" ? h.isInternetExplorer.cached : Boolean(h.getInternetExplorerMajorVersion()); return e }, h.options.html4Mode ? h.emulated = { pushState: !0, hashChange: !0 } : h.emulated = { pushState: !Boolean(e.history && e.history.pushState && e.history.replaceState && !/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent) && !/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)), hashChange: Boolean(!("onhashchange" in e || "onhashchange" in r) || h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 8) }, h.enabled = !h.emulated.pushState, h.bugs = { setHash: Boolean(!h.emulated.pushState && i.vendor === "Apple Computer, Inc." && /AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)), safariPoll: Boolean(!h.emulated.pushState && i.vendor === "Apple Computer, Inc." && /AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)), ieDoubleCheck: Boolean(h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 8), hashEscape: Boolean(h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 7) }, h.isEmptyObject = function (e) { for (var t in e) if (e.hasOwnProperty(t)) return !1; return !0 }, h.cloneObject = function (e) { var t, n; return e ? (t = l.stringify(e), n = l.parse(t)) : n = {}, n }, h.getRootUrl = function () { var e = r.location.protocol + "//" + (r.location.hostname || r.location.host); if (r.location.port || !1) e += ":" + r.location.port; return e += "/", e }, h.getBaseHref = function () { var e = r.getElementsByTagName("base"), t = null, n = ""; return e.length === 1 && (t = e[0], n = t.href.replace(/[^\/]+$/, "")), n = n.replace(/\/+$/, ""), n && (n += "/"), n }, h.getBaseUrl = function () { var e = h.getBaseHref() || h.getBasePageUrl() || h.getRootUrl(); return e }, h.getPageUrl = function () { var e = h.getState(!1, !1), t = (e || {}).url || h.getLocationHref(), n; return n = t.replace(/\/+$/, "").replace(/[^\/]+$/, function (e, t, n) { return /\./.test(e) ? e : e + "/" }), n }, h.getBasePageUrl = function () { var e = h.getLocationHref().replace(/[#\?].*/, "").replace(/[^\/]+$/, function (e, t, n) { return /[^\/]$/.test(e) ? "" : e }).replace(/\/+$/, "") + "/"; return e }, h.getFullUrl = function (e, t) { var n = e, r = e.substring(0, 1); return t = typeof t == "undefined" ? !0 : t, /[a-z]+\:\/\//.test(e) || (r === "/" ? n = h.getRootUrl() + e.replace(/^\/+/, "") : r === "#" ? n = h.getPageUrl().replace(/#.*/, "") + e : r === "?" ? n = h.getPageUrl().replace(/[\?#].*/, "") + e : t ? n = h.getBaseUrl() + e.replace(/^(\.\/)+/, "") : n = h.getBasePageUrl() + e.replace(/^(\.\/)+/, "")), n.replace(/\#$/, "") }, h.getShortUrl = function (e) { var t = e, n = h.getBaseUrl(), r = h.getRootUrl(); return h.emulated.pushState && (t = t.replace(n, "")), t = t.replace(r, "/"), h.isTraditionalAnchor(t) && (t = "./" + t), t = t.replace(/^(\.\/)+/g, "./").replace(/\#$/, ""), t }, h.getLocationHref = function (e) { return e = e || r, e.URL === e.location.href ? e.location.href : e.location.href === decodeURIComponent(e.URL) ? e.URL : e.location.hash && decodeURIComponent(e.location.href.replace(/^[^#]+/, "")) === e.location.hash ? e.location.href : e.URL.indexOf("#") == -1 && e.location.href.indexOf("#") != -1 ? e.location.href : e.URL || e.location.href }, h.store = {}, h.idToState = h.idToState || {}, h.stateToId = h.stateToId || {}, h.urlToId = h.urlToId || {}, h.storedStates = h.storedStates || [], h.savedStates = h.savedStates || [], h.normalizeStore = function () { h.store.idToState = h.store.idToState || {}, h.store.urlToId = h.store.urlToId || {}, h.store.stateToId = h.store.stateToId || {} }, h.getState = function (e, t) { typeof e == "undefined" && (e = !0), typeof t == "undefined" && (t = !0); var n = h.getLastSavedState(); return !n && t && (n = h.createStateObject()), e && (n = h.cloneObject(n), n.url = n.cleanUrl || n.url), n }, h.getIdByState = function (e) { var t = h.extractId(e.url), n; if (!t) { n = h.getStateString(e); if (typeof h.stateToId[n] != "undefined") t = h.stateToId[n]; else if (typeof h.store.stateToId[n] != "undefined") t = h.store.stateToId[n]; else { for (; ;) { t = (new Date).getTime() + String(Math.random()).replace(/\D/g, ""); if (typeof h.idToState[t] == "undefined" && typeof h.store.idToState[t] == "undefined") break } h.stateToId[n] = t, h.idToState[t] = e } } return t }, h.normalizeState = function (e) { var t, n; if (!e || typeof e != "object") e = {}; if (typeof e.normalized != "undefined") return e; if (!e.data || typeof e.data != "object") e.data = {}; return t = {}, t.normalized = !0, t.title = e.title || "", t.url = h.getFullUrl(e.url ? e.url : h.getLocationHref()), t.hash = h.getShortUrl(t.url), t.data = h.cloneObject(e.data), t.id = h.getIdByState(t), t.cleanUrl = t.url.replace(/\??\&_suid.*/, ""), t.url = t.cleanUrl, n = !h.isEmptyObject(t.data), (t.title || n) && h.options.disableSuid !== !0 && (t.hash = h.getShortUrl(t.url).replace(/\??\&_suid.*/, ""), /\?/.test(t.hash) || (t.hash += "?"), t.hash += "&_suid=" + t.id), t.hashedUrl = h.getFullUrl(t.hash), (h.emulated.pushState || h.bugs.safariPoll) && h.hasUrlDuplicate(t) && (t.url = t.hashedUrl), t }, h.createStateObject = function (e, t, n) { var r = { data: e, title: t, url: n }; return r = h.normalizeState(r), r }, h.getStateById = function (e) { e = String(e); var n = h.idToState[e] || h.store.idToState[e] || t; return n }, h.getStateString = function (e) { var t, n, r; return t = h.normalizeState(e), n = { data: t.data, title: e.title, url: e.url }, r = l.stringify(n), r }, h.getStateId = function (e) { var t, n; return t = h.normalizeState(e), n = t.id, n }, h.getHashByState = function (e) { var t, n; return t = h.normalizeState(e), n = t.hash, n }, h.extractId = function (e) { var t, n, r, i; return e.indexOf("#") != -1 ? i = e.split("#")[0] : i = e, n = /(.*)\&_suid=([0-9]+)$/.exec(i), r = n ? n[1] || e : e, t = n ? String(n[2] || "") : "", t || !1 }, h.isTraditionalAnchor = function (e) { var t = !/[\/\?\.]/.test(e); return t }, h.extractState = function (e, t) { var n = null, r, i; return t = t || !1, r = h.extractId(e), r && (n = h.getStateById(r)), n || (i = h.getFullUrl(e), r = h.getIdByUrl(i) || !1, r && (n = h.getStateById(r)), !n && t && !h.isTraditionalAnchor(e) && (n = h.createStateObject(null, null, i))), n }, h.getIdByUrl = function (e) { var n = h.urlToId[e] || h.store.urlToId[e] || t; return n }, h.getLastSavedState = function () { return h.savedStates[h.savedStates.length - 1] || t }, h.getLastStoredState = function () { return h.storedStates[h.storedStates.length - 1] || t }, h.hasUrlDuplicate = function (e) { var t = !1, n; return n = h.extractState(e.url), t = n && n.id !== e.id, t }, h.storeState = function (e) { return h.urlToId[e.url] = e.id, h.storedStates.push(h.cloneObject(e)), e }, h.isLastSavedState = function (e) { var t = !1, n, r, i; return h.savedStates.length && (n = e.id, r = h.getLastSavedState(), i = r.id, t = n === i), t }, h.saveState = function (e) { return h.isLastSavedState(e) ? !1 : (h.savedStates.push(h.cloneObject(e)), !0) }, h.getStateByIndex = function (e) { var t = null; return typeof e == "undefined" ? t = h.savedStates[h.savedStates.length - 1] : e < 0 ? t = h.savedStates[h.savedStates.length + e] : t = h.savedStates[e], t }, h.getCurrentIndex = function () { var e = null; return h.savedStates.length < 1 ? e = 0 : e = h.savedStates.length - 1, e }, h.getHash = function (e) { var t = h.getLocationHref(e), n; return n = h.getHashByUrl(t), n }, h.unescapeHash = function (e) { var t = h.normalizeHash(e); return t = decodeURIComponent(t), t }, h.normalizeHash = function (e) { var t = e.replace(/[^#]*#/, "").replace(/#.*/, ""); return t }, h.setHash = function (e, t) { var n, i; return t !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.setHash, args: arguments, queue: t }), !1) : (h.busy(!0), n = h.extractState(e, !0), n && !h.emulated.pushState ? h.pushState(n.data, n.title, n.url, !1) : h.getHash() !== e && (h.bugs.setHash ? (i = h.getPageUrl(), h.pushState(null, null, i + "#" + e, !1)) : r.location.hash = e), h) }, h.escapeHash = function (t) { var n = h.normalizeHash(t); return n = e.encodeURIComponent(n), h.bugs.hashEscape || (n = n.replace(/\%21/g, "!").replace(/\%26/g, "&").replace(/\%3D/g, "=").replace(/\%3F/g, "?")), n }, h.getHashByUrl = function (e) { var t = String(e).replace(/([^#]*)#?([^#]*)#?(.*)/, "$2"); return t = h.unescapeHash(t), t }, h.setTitle = function (e) { var t = e.title, n; t || (n = h.getStateByIndex(0), n && n.url === e.url && (t = n.title || h.options.initialTitle)); try { r.getElementsByTagName("title")[0].innerHTML = t.replace("<", "&lt;").replace(">", "&gt;").replace(" & ", " &amp; ") } catch (i) { } return r.title = t, h }, h.queues = [], h.busy = function (e) { typeof e != "undefined" ? h.busy.flag = e : typeof h.busy.flag == "undefined" && (h.busy.flag = !1); if (!h.busy.flag) { u(h.busy.timeout); var t = function () { var e, n, r; if (h.busy.flag) return; for (e = h.queues.length - 1; e >= 0; --e) { n = h.queues[e]; if (n.length === 0) continue; r = n.shift(), h.fireQueueItem(r), h.busy.timeout = o(t, h.options.busyDelay) } }; h.busy.timeout = o(t, h.options.busyDelay) } return h.busy.flag }, h.busy.flag = !1, h.fireQueueItem = function (e) { return e.callback.apply(e.scope || h, e.args || []) }, h.pushQueue = function (e) { return h.queues[e.queue || 0] = h.queues[e.queue || 0] || [], h.queues[e.queue || 0].push(e), h }, h.queue = function (e, t) { return typeof e == "function" && (e = { callback: e }), typeof t != "undefined" && (e.queue = t), h.busy() ? h.pushQueue(e) : h.fireQueueItem(e), h }, h.clearQueue = function () { return h.busy.flag = !1, h.queues = [], h }, h.stateChanged = !1, h.doubleChecker = !1, h.doubleCheckComplete = function () { return h.stateChanged = !0, h.doubleCheckClear(), h }, h.doubleCheckClear = function () { return h.doubleChecker && (u(h.doubleChecker), h.doubleChecker = !1), h }, h.doubleCheck = function (e) { return h.stateChanged = !1, h.doubleCheckClear(), h.bugs.ieDoubleCheck && (h.doubleChecker = o(function () { return h.doubleCheckClear(), h.stateChanged || e(), !0 }, h.options.doubleCheckInterval)), h }, h.safariStatePoll = function () { var t = h.extractState(h.getLocationHref()), n; if (!h.isLastSavedState(t)) return n = t, n || (n = h.createStateObject()), h.Adapter.trigger(e, "popstate"), h; return }, h.back = function (e) { return e !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.back, args: arguments, queue: e }), !1) : (h.busy(!0), h.doubleCheck(function () { h.back(!1) }), p.go(-1), !0) }, h.forward = function (e) { return e !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.forward, args: arguments, queue: e }), !1) : (h.busy(!0), h.doubleCheck(function () { h.forward(!1) }), p.go(1), !0) }, h.go = function (e, t) { var n; if (e > 0) for (n = 1; n <= e; ++n) h.forward(t); else { if (!(e < 0)) throw new Error("History.go: History.go requires a positive or negative integer passed."); for (n = -1; n >= e; --n) h.back(t) } return h }; if (h.emulated.pushState) { var v = function () { }; h.pushState = h.pushState || v, h.replaceState = h.replaceState || v } else h.onPopState = function (t, n) { var r = !1, i = !1, s, o; return h.doubleCheckComplete(), s = h.getHash(), s ? (o = h.extractState(s || h.getLocationHref(), !0), o ? h.replaceState(o.data, o.title, o.url, !1) : (h.Adapter.trigger(e, "anchorchange"), h.busy(!1)), h.expectedStateId = !1, !1) : (r = h.Adapter.extractEventData("state", t, n) || !1, r ? i = h.getStateById(r) : h.expectedStateId ? i = h.getStateById(h.expectedStateId) : i = h.extractState(h.getLocationHref()), i || (i = h.createStateObject(null, null, h.getLocationHref())), h.expectedStateId = !1, h.isLastSavedState(i) ? (h.busy(!1), !1) : (h.storeState(i), h.saveState(i), h.setTitle(i), h.Adapter.trigger(e, "statechange"), h.busy(!1), !0)) }, h.Adapter.bind(e, "popstate", h.onPopState), h.pushState = function (t, n, r, i) { if (h.getHashByUrl(r) && h.emulated.pushState) throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors)."); if (i !== !1 && h.busy()) return h.pushQueue({ scope: h, callback: h.pushState, args: arguments, queue: i }), !1; h.busy(!0); var s = h.createStateObject(t, n, r); return h.isLastSavedState(s) ? h.busy(!1) : (h.storeState(s), h.expectedStateId = s.id, p.pushState(s.id, s.title, s.url), h.Adapter.trigger(e, "popstate")), !0 }, h.replaceState = function (t, n, r, i) { if (h.getHashByUrl(r) && h.emulated.pushState) throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors)."); if (i !== !1 && h.busy()) return h.pushQueue({ scope: h, callback: h.replaceState, args: arguments, queue: i }), !1; h.busy(!0); var s = h.createStateObject(t, n, r); return h.isLastSavedState(s) ? h.busy(!1) : (h.storeState(s), h.expectedStateId = s.id, p.replaceState(s.id, s.title, s.url), h.Adapter.trigger(e, "popstate")), !0 }; if (s) { try { h.store = l.parse(s.getItem("History.store")) || {} } catch (m) { h.store = {} } h.normalizeStore() } else h.store = {}, h.normalizeStore(); h.Adapter.bind(e, "unload", h.clearAllIntervals), h.saveState(h.storeState(h.extractState(h.getLocationHref(), !0))), s && (h.onUnload = function () { var e, t, n; try { e = l.parse(s.getItem("History.store")) || {} } catch (r) { e = {} } e.idToState = e.idToState || {}, e.urlToId = e.urlToId || {}, e.stateToId = e.stateToId || {}; for (t in h.idToState) { if (!h.idToState.hasOwnProperty(t)) continue; e.idToState[t] = h.idToState[t] } for (t in h.urlToId) { if (!h.urlToId.hasOwnProperty(t)) continue; e.urlToId[t] = h.urlToId[t] } for (t in h.stateToId) { if (!h.stateToId.hasOwnProperty(t)) continue; e.stateToId[t] = h.stateToId[t] } h.store = e, h.normalizeStore(), n = l.stringify(e); try { s.setItem("History.store", n) } catch (i) { if (i.code !== DOMException.QUOTA_EXCEEDED_ERR) throw i; s.length && (s.removeItem("History.store"), s.setItem("History.store", n)) } }, h.intervalList.push(a(h.onUnload, h.options.storeInterval)), h.Adapter.bind(e, "beforeunload", h.onUnload), h.Adapter.bind(e, "unload", h.onUnload)); if (!h.emulated.pushState) { h.bugs.safariPoll && h.intervalList.push(a(h.safariStatePoll, h.options.safariPollInterval)); if (i.vendor === "Apple Computer, Inc." || (i.appCodeName || "") === "Mozilla") h.Adapter.bind(e, "hashchange", function () { h.Adapter.trigger(e, "popstate") }), h.getHash() && h.Adapter.onDomLoad(function () { h.Adapter.trigger(e, "hashchange") }) } }, (!h.options || !h.options.delayInit) && h.init() }(window);
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as anonymous module.
		define(['jquery'], factory);
	} else {
		// Browser globals.
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\+/g;

	function decode(s) {
		if (config.raw) {
			return s;
		}
		return decodeURIComponent(s.replace(pluses, ' '));
	}

	function decodeAndParse(s) {
		if (s.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape...
			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
		}

		s = decode(s);

		try {
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

	var config = $.cookie = function (key, value, options) {

		// Write
		if (value !== undefined) {
			options = $.extend({}, config.defaults, options);

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = config.json ? JSON.stringify(value) : String(value);

			return (document.cookie = [
				config.raw ? key : encodeURIComponent(key),
				'=',
				config.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// Read
		var cookies = document.cookie.split('; ');
		var result = key ? undefined : {};
		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decode(parts.shift());
			var cookie = parts.join('=');

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

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

		return result;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		if ($.cookie(key) !== undefined) {
			// Must not alter options, thus extending a fresh object...
			$.cookie(key, '', $.extend({}, options, { expires: -1 }));
			return true;
		}
		return false;
	};

}));
;
/*
    jQuery Switch Plugin
*/

(function($) {
    'use strict';

    var config = $.fn.switchButton = function(options) {
        var opts = {};

        function createMarkup($container) {
            var label = $('<span>')
                .addClass('switch-label')
                .addClass(opts.labelStyle)
                .text(opts.label);
            var button = $('<div>')
                .addClass('switch-button')
                .addClass(opts.buttonStyle);
            var frame = $('<div>')
                .addClass('switch-frame')
                .addClass(opts.frameStyle)
                .append(button)
                .hide();

            $container
                .append(label)
                .append(frame);
        }

        function subscribeToEvents($frame, $button) {
            $frame
                .on('click', function() {
                    $button.click();
                });

            $button.toggle(function() {
                $(this).addClass('off').html(opts.offLabel);

                if (typeof(opts.offCallback) === 'function') {
                    opts.offCallback();
                }
            }, function() {
                $(this).removeClass('off').html(opts.onLabel);

                if (typeof(opts.onCallback) === 'function') {
                    opts.onCallback();
                }
            });
        }

        function setInitialState($button) {
            if (opts.initialState === 'off') {
                $button.click();
                $button.html(opts.offLabel);
            } else {
                $button.html(opts.onLabel);
            }
        }

        function updateSettings($container) {
            opts = $.extend({}, $.fn.switchButton.defaults, options);

            opts.label = $container.data('label') || opts.label;

            opts.onLabel = $container.data('on-label') || 'ON';
            opts.offLabel = $container.data('off-label') || 'OFF';

            opts.labelStyle = $container.data('label-style') || opts.labelStyle;
            opts.frameStyle = $container.data('frame-style') || opts.frameStyle;
            opts.buttonStyle = $container.data('button-style') || opts.buttonStyle;
        }

        return this.each(function() {
            var $container = $(this);

            // create initial settings
            updateSettings($container);

            // init markup
            createMarkup($container);

            var $frame = $container.find('.switch-frame');
            var $button = $frame.find('.switch-button');

            // add event subscription
            subscribeToEvents($frame, $button);

            // set initial state
            setInitialState($button);

            // fix flickering
            $frame.show();

            // prevent reinitialization of switch
            $container.removeClass('make-switch');
        });
    };

    config.defaults = {
        initialState: 'on',
    };
})(jQuery);;
(function ($) {
    'use strict';

    $.fn.visibleOnFocus = function() {

        if (!this) {
            return;
        }

        var self = this;

        var visibleCss = {
            'z-index': self.css('zIndex'),
            'opacity': self.css('opacity')
        };

        var hiddenCss = {
            'z-index': '-1',
            'opacity': '0'
        };
        
        function hideElement() {
            self.css(hiddenCss);
        }

        function showElement() {
            self.css(visibleCss);
            self.one('click', hideElement);
        }

        self
            .css(hiddenCss)
            .on('focus', showElement)
            .on('blur', hideElement);
    }
})(jQuery);;
(function ($) {
    'use strict';

    //Sets attributes passed as key-value pairs on an element.
    $.fn.setAttributes = function (attributes) {

        if (!this) {
            return;
        }

        var self = this;

        $.each(attributes, function (index, value) {
            self.attr(value[0], value[1]);
        });
    };
})(jQuery);;

/*
Copyright (C) <2012> <haithem bel haj>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

(function() {
    'use strict';

  window.Router = (function() {

    Router.namedParam = /:\w+/g;

    Router.splatParam = /\*\w+/g;

    Router.prototype.trigger = true;

    function Router(routes) {
      var _this = this;
      this.routes = routes != null ? routes : {};
      History.Adapter.bind(window, 'statechange', function() {
        return _this.checkRoutes(History.getState());
      });
    }

    Router.prototype.route = function(route, callback, name) {
        route = route.replace(Router.namedParam, '([^\/^\?]+)').replace(Router.splatParam, '(.*?)');
        name = name || null;

        return this.routes["^" + route + "$"] = { callback: callback, name: name };
    };

    Router.prototype.checkRoutes = function(state) {
        var callback, regex, regexText, url, _ref;

        if (this.trigger) {
            _ref = this.routes;

            // There is need to add backslash in case of state.data object is null and url goes from state.hash when hashes fallback is used
            url = state.data.url || (window.history && window.history.pushState ? state.hash : '/' + state.hash);

            // sometimes state.data.url comes as a full url "http://gjobs.dev.neogov.net/jobs/258114/accounting-clerk"
            // for routing to work we only need a pathname part "/jobs/258114/accounting-clerk"
            // IE 8- uses hash-based urls - leave them as is
            // todo: investigate IE8 behaviour
            //if (!History.emulated.pushState) {
            // Chrome, FF
            var a = document.createElement('a');
            a.href = url;
            url = a.pathname + a.search + a.hash;

            // ensure that url starts with a slash
            url = url.indexOf('/') === 0 ? url : '/' + url;
            //} else {
            // IE 8 and below (hash based)
            // use original url
            //}

            var urlParts = url.split('?');
            urlParts[0] = urlParts[0];
            url = urlParts.join('?');

            for (regexText in _ref) {
                callback = _ref[regexText].callback;
                regex = new RegExp(regexText);

                if (regex.test(url)) {
                    callback.apply(window, regex.exec(url).slice(1));
                    // When there is a match break the cycle not to fire other matching routes
                    break;
                }
            }
        }

        return this.trigger = true;
    };

    Router.prototype.isCurrentUrlMatchedToRoute = function (routeName) {
        var _ref = this.routes;
        var url = window.location.pathname.toLowerCase() + window.location.search;

        for (var regexText in _ref) {
            var regex = new RegExp(regexText);
            var name = _ref[regexText].name;

            if (name === routeName && regex.test(url)) {
                return true;
            }
        }

        return false;
    };

    Router.prototype.cutQueryString = function (url) {
        return url.replace(/\?.+/, '');
    }

    Router.prototype.removePageTypeFromQuery = function (url) {
        var index = url.indexOf('pagetype=');
        var regexp = /pagetype=.*/;
        if (url.charAt(index - 1) === '&') {
            regexp = /&pagetype=.*/;
        }
        return url.replace(regexp, '');
    }

    Router.prototype.addQueryString = function (url) {
        return url + window.location.search;
    }

    Router.prototype.navigate = function (url, trigger, replace, name, innerData, saveQueryString) {
        if (trigger == null) trigger = true;
        if (replace == null) replace = false;
        if (name == null) name = null;
        if (saveQueryString) url = Router.prototype.addQueryString(url);
        this.trigger = trigger;
        if (replace) {
            return History.replaceState({
                'url': url,
                innerData: innerData
            }, document.title, url);
        } else {
            return History.pushState({
                'url': url,
                innerData: innerData
            }, document.title, url);
        }
    };

    Router.prototype.go = function(num) {
      return History.go(num);
    };

    Router.prototype.back = function() {
      return History.back();
    };

    return Router;

  })();

}).call(this);
;
(function (window, undefined) {
    'use strict';

    var JOB_DETAILS_TAB = 1;
    var APPLY_TAB = 2;

    var AGENCY_PAGES_PREFIX = AgencyPages.routePrefix;

    $(document).ready(function () {
        namespace('AgencyPages').router = (function () {

            var router = new Router();

            router.routePrefix = AGENCY_PAGES_PREFIX;

            var jobDetailsFlyoutUrlSuffix = '/jobdetails';

            function getDataFromHistory () {
                var state = History.getState();
                var data = {};
                if (state && state.data && state.data.innerData) {
                    data = state.data.innerData;
                }

                return data;
            }

            function getFlyout() {
                //gets the flyout depending on which page we are
                return AgencyPages.jobFlyout || AgencyPages.incompleteAppFlyout || AgencyPages.standaloneJob || AgencyPages.classSpecFlyout;
            }

            function getOfferFlyout() {
                return AgencyPages.offerFlyout;
            }

            function getCanvassFlyout() {
                return AgencyPages.canvassFlyout;
            }

            function getSearchPage() {
                return AgencyPages.searchPage || AgencyPages.classSpecificationsPage;
            }

            function closeJobDetailsFlyout() {
                var states = History.savedStates;

                if (states.length && states.length > 1) {
                    var prevStateIndex = states.length - 2,
                        previousState = History.getStateByIndex(prevStateIndex);

                    if (previousState.url && RegExp(jobDetailsFlyoutUrlSuffix).test(previousState.url)) {
                        AgencyPages.onlineAppJobDetailsFlyout && AgencyPages.onlineAppJobDetailsFlyout.closeFlyout();
                    }
                }
            }

            function showJobFlyout(jobId, jobTitle, tab) {
                closeJobDetailsFlyout();

                var data = getDataFromHistory();

                var job = {
                    id: data.id || jobId,
                    title: data.jobTitle || data.title || jobTitle,
                    tab: data.tab || tab
                };

                getFlyout().showJob(job);

                if (job.tab == APPLY_TAB) {
                    OnlineApp.Services.authenticationService.isLoggedIn()
                        .done(function (isLoggedIn) {
                            if (isLoggedIn) {
                                OnlineApp.Services.authenticationService.getUserData()
                                    .done(function (getUserData) {
                                        if (getUserData) {
                                            var baseUrl = window.location.href;
                                            baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf("jobs"));
                                            if (!getUserData.email) {
                                                window.location.href = baseUrl + "Applications/AccountSettings#contact";
                                            }
                                        }
                                    });
                            }
                            });
                }
                if (job.tab == JOB_DETAILS_TAB) {
                    gJobs.skipToContentService.showOnNextTab();
                }
            }

            function showOfferFlyout(offerId) {
                getOfferFlyout().showOffer({
                    offerId: offerId
                });
            }

            function showCanvassFlyout(canvassFormId) {
                getCanvassFlyout().showCanvass({
                    canvassFormId: canvassFormId
                });
            }

            function appPageTabRouteHandler(tabName, queryString) {
                closeFlyout();
                agencyPages.applicationsPage.switchTab(tabName);

                var page = AgencyPages.getUrlParams(queryString).page || 1;
                agencyPages.applicationsPage.goToPage(page);
            }

            function applicationFlyoutRouteHandler(jobId, jobApplicationId, tabName) {
                var state = History.getState();
                var submittedApplicationInfo = {
                    id: jobId,
                    jobApplicationId: jobApplicationId,
                    title: ''
                }

                if (state.data.innerData && state.data.innerData.title) {
                    submittedApplicationInfo.title = state.data.innerData.title;
                }

                showSubmittedAppFlyout(submittedApplicationInfo, tabName);
            }

            function showSubmittedAppFlyout(applicationInfo, tabName) {
                var submittedApplicationTabs = namespace('AgencyPages').submittedAppFlyout.tabs;
                if (tabName === submittedApplicationTabs.applicationTab.urlPart) {
                    applicationInfo.tab = APPLY_TAB;
                    namespace('AgencyPages')
                        .submittedAppFlyout.showJob(applicationInfo);
                } else if (tabName === submittedApplicationTabs.jobDetailsTab.urlPart) {
                    applicationInfo.tab = JOB_DETAILS_TAB;
                    namespace('AgencyPages')
                        .submittedAppFlyout.showJob(applicationInfo);
                }
            };

            function showClassSpecFlyout(classSpecId) {
                var classSpec = {
                    id: classSpecId
                };
                getFlyout().showClassSpec(classSpec);
            }

            function closeFlyout() {
                if (getFlyout().isOpen()) {
                    getFlyout().close();
                }
            }

            function getKeywordsFromUrl(queryString) {
                var currentState = History.getState();
                var innerData = currentState.data.innerData;
                var keywords = '';

                if (innerData) {
                    keywords = innerData.keywords || '';
                } else if (queryString) {
                    keywords = AgencyPages.getUrlParams(queryString).keywords || '';
                }

                return keywords;
            }

            function changePageTitle(jobTitle, isJobDetailsTab) {
                var tabName = isJobDetailsTab ? 'Job Details tab' : 'Apply tab';
                var data = getDataFromHistory();
                var jobTitle = data.jobTitle || data.title || jobTitle;
                if (jobTitle) {
                    var applyTabPageTitle = jobTitle + ' | ' + tabName + ' | Career Pages';
                    var currentPageTitle = document.title;
                    if (currentPageTitle !== applyTabPageTitle) {
                        document.title = applyTabPageTitle;
                        AgencyPages.savedPageTitle = currentPageTitle;
                    }
                } else if (AgencyPages.savedPageTitle) {
                    document.title = AgencyPages.savedPageTitle;
                    AgencyPages.savedPageTitle = null;
                }
            }

            function sendVirtualPageViewEvent (jobTitle, tabName) {
                var data = getDataFromHistory();
                jobTitle = data.title || data.jobTitle || jobTitle;
                var currentVirtualPageType =
                    AgencyPages.pageInfoService.getCurrentVirtualPageProperties(tabName);
                if (currentVirtualPageType) {
                    var options = {
                        title: 'Job Opportunities | ' + jobTitle + currentVirtualPageType.title,
                        page: currentVirtualPageType.page,
                        sendToAllTrackers: true
                    }

                    gJobs.common.analytics.trackVirtualPageView(options);
                }
            }

            router.route(AGENCY_PAGES_PREFIX + '/:agency/applications/submitted/offer/:offerId/?\\??*queryString',
                function (agency, offerId) {
                    showOfferFlyout(offerId);
                }, 'offerLetterRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/applications/submitted/offer/:offerId/?\\??*queryString',
                function (agency, department, offerId) {
                    showOfferFlyout(offerId);
                }, 'offerLetterDepartmentRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/applications/submitted/canvass/:canvassFormId/?\\??*queryString',
                function (agency, canvassFormId) {
                    showCanvassFlyout(canvassFormId);
                }, 'canvassFormRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/applications/submitted/canvass/:canvassFormId/?\\??*queryString',
                function (agency, department, canvassFormId) {
                    showCanvassFlyout(canvassFormId);
                }, 'canvassFormDepartmentRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/classspecs/:classSpecId/?\\??*queryString', function (agency, department, classSpecId, queryString) {
                showClassSpecFlyout(classSpecId);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/classspecs/:classSpecId/?\\??*queryString', function (agency, classSpecId, queryString) {
                showClassSpecFlyout(classSpecId);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/applications/submitted/:jobId/:jobApplicationId/:tabName/?\\??*queryString',
                function (agency, department, jobId, jobApplicationId, tabName) {

                    applicationFlyoutRouteHandler(jobId, jobApplicationId, tabName);
                }, 'submittedApplicationDepartmentRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/applications/submitted/:jobId/:jobApplicationId/:tabName/?\\??*queryString', function (agency, jobId, jobApplicationId, tabName) {
                applicationFlyoutRouteHandler(jobId, jobApplicationId, tabName);
            }, 'submittedApplicationRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/canvass/:canvassFormId/?\\??*queryString',
                function (agency, canvassFormId) {
                    showCanvassFlyout(canvassFormId);
                }, 'careersCanvassFormRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/canvass/:canvassFormId/?\\??*queryString',
                function (agency, canvassFormId) {
                    showCanvassFlyout(canvassFormId);
                }, 'careersCanvassFormDepartmentRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/jobs/:jobId/:jobTitle/apply/jobdetails/?\\??*queryString', function (agency, department, jobId, jobTitle, queryString) {
                AgencyPages.onlineAppJobDetailsFlyout && AgencyPages.onlineAppJobDetailsFlyout.openFlyoutForJobWithId(jobId);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/jobs/:jobId/:jobTitle/apply/jobdetails/?\\??*queryString', function (agency, jobId, jobTitle, queryString) {
                AgencyPages.onlineAppJobDetailsFlyout && AgencyPages.onlineAppJobDetailsFlyout.openFlyoutForJobWithId(jobId);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/jobs/:jobId/:jobTitle/apply/:tabName/?\\??*queryString', function (agency, department, jobId, jobTitle, tabName, queryString) {
                if (!getFlyout().isOnlineAppLoaded()) {
                    //specifying tab explicitly before OnlineApp is initialized breaks OnlineApp, so the tabName section is removed
                    router.navigate(AGENCY_PAGES_PREFIX + agency + '/jobs/' + jobId + '/' + jobTitle + '/apply' + queryString, false, true, null, History.getState().data.innerData);
                }
                showJobFlyout(jobId, jobTitle, APPLY_TAB);
            }, 'onlineApplicationDepartmentStepsRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/jobs/:jobId/:jobTitle/apply/:tabName/?\\??*queryString', function (agency, jobId, jobTitle, tabName, queryString) {
                if (!getFlyout().isOnlineAppLoaded()) {
                    //specifying tab explicitly before OnlineApp is initialized breaks OnlineApp, so the tabName section is removed
                    router.navigate(AGENCY_PAGES_PREFIX + agency + '/jobs/' + jobId + '/' + jobTitle + '/apply' + queryString, false, true, null, History.getState().data.innerData);
                }
                showJobFlyout(jobId, jobTitle, APPLY_TAB);
                sendVirtualPageViewEvent(jobTitle, tabName);
            }, 'onlineApplicationStepsRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/jobs/:jobId/:jobTitle/apply/?\\??*queryString', function (agency, department, jobId, jobTitle, queryString) {
                var title = History.getState().data.innerData && History.getState().data.innerData.jobTitle
                    ? History.getState().data.innerData.jobTitle
                    : jobTitle;
                showJobFlyout(jobId, title, APPLY_TAB);
                changePageTitle(jobTitle);
            }, 'jobApplyDepartmentRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/jobs/:jobId/:jobTitle/apply/?\\??*queryString', function (agency, jobId, jobTitle, queryString) {
                var title = History.getState().data.innerData && History.getState().data.innerData.jobTitle
                    ? History.getState().data.innerData.jobTitle
                    : jobTitle;
                showJobFlyout(jobId, title, APPLY_TAB);
                changePageTitle(jobTitle);
            }, 'jobApplyRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/jobs/:jobId/:jobTitle/?\\??*queryString', function (agency, department, jobId, jobTitle, queryString) {
                showJobFlyout(jobId, jobTitle, JOB_DETAILS_TAB);
                changePageTitle();
            }, 'jobDetailsDepartmentRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/jobs/:jobId/:jobTitle/?\\??*queryString', function (agency, jobId, jobTitle, queryString) {
                showJobFlyout(jobId, jobTitle, JOB_DETAILS_TAB);
                changePageTitle(jobTitle, true);
            }, 'jobDetailsRoute');

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:department/applications/:tabName/?\\??*queryString', function (agency, department, tabName, queryString) {
                appPageTabRouteHandler(tabName, queryString);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/applications/:tabName/?\\??*queryString', function (agency, tabName, queryString) {
                appPageTabRouteHandler(tabName, queryString);
            });

            router.route(AGENCY_PAGES_PREFIX + "/:agency/inbox/:messageId/:messageSource/:filterType?\\??*queryString",
                function(agency, messageId, messageSource, filterType) {
                    try {
                        AgencyPages.inboxPage.loadInboxMessage(messageId, messageSource, filterType);
                    } catch (ex) {
                        toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                    }
                });

            router.route(AGENCY_PAGES_PREFIX + "/:agency/:department/inbox/:messageId/:messageSource/:filterType?\\??*queryString",
                function (messageId, messageSource, filterType) {
                    try {
                        AgencyPages.inboxPage.loadInboxMessage(messageId, messageSource, filterType);
                    } catch (ex) {
                        toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                    }
                });

            router.route(AGENCY_PAGES_PREFIX + "/:agency/:department/inbox/?\\??*queryString",
                function () {
                    try {
                        AgencyPages.inboxPage.getMessages();
                    } catch (ex) {
                        toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                    }
                });

            router.route(AGENCY_PAGES_PREFIX + "/:agency/inbox/?\\??*queryString",
                function () {
                    try {
                        AgencyPages.inboxPage.getMessages();
                    } catch (ex) {
                        toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                    }
                });


            router.route(AGENCY_PAGES_PREFIX + '/:agency/:jobsTypeName/?\\??*queryString', function (agency, jobsTypeName, queryString) {
                changePageTitle();

                var keywords = getKeywordsFromUrl(queryString);
                var page = AgencyPages.getUrlParams(queryString).page || null;
                var searchPage = getSearchPage();
                closeFlyout();

                searchPage.search(keywords);

                searchPage.goToPage(page);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/classspecs/?\\??*queryString', function (agency, queryString) {
                var page = AgencyPages.getUrlParams(queryString).page || null;
                getSearchPage().goToPage(page);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/:jobsTypeName/?', closeFlyout);

            router.route(AGENCY_PAGES_PREFIX + '/:agency/?\\??*queryString', function (agency, queryString) {
                changePageTitle();

                var keywords = getKeywordsFromUrl(queryString);
                var page = AgencyPages.getUrlParams(queryString).page || null;
                var searchPage = getSearchPage();
                closeFlyout();

                searchPage.search(keywords);

                searchPage.goToPage(page);
            });

            router.route(AGENCY_PAGES_PREFIX + '/:agency/?', closeFlyout);

            router.route(AGENCY_PAGES_PREFIX + '/:agency/applications/index', closeFlyout);

            /* apply/:tabName routes are handled within Online Application itself,
               but Online Application communicates with old gJobs.router and this reference is hardcoded,
               so we expose our router also as gJobs.router for OnlineApp, and adjust the states it creates to meet AgencyPages routes requirements. */
            namespace('gJobs').router = {
                navigate: function () {
                    if (utils.stringEndsWith(arguments[0], '/apply')) {
                        return; //do not let OnlineApp to store '..jobs/../apply' route as it is already created by jobFlyout
                    } else {
                        //arguments[4] is state's inner data. Here we enrich the data stored by OnlineApp with job parameters required for jobFlyout
                        arguments[4].id = getFlyout().activeJobId;
                        arguments[4].title = getFlyout().activeJobTitle;
                        arguments[4].tab = 2;
                        router.navigate.apply(router, arguments);
                    }
                },

                addQueryString: router.addQueryString,

                cutQueryString: router.cutQueryString
            };


            return router;
        })();
    });

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

    namespace('gJobs').ajax = (function () {

        var _ajaxGet = function (url, data) {
            return $.ajax({
                url: url,
                type: 'GET',
                contentType: 'text/html',
                cache: false,
                data: data
            });
        };

        var _ajaxGetWithLoadingElement = function (url, loadingElementSelector, data) {
            var $loadingElement = $(loadingElementSelector);

            $loadingElement.show();

            return _ajaxGet(url, data).always(function () {
                $loadingElement.hide();
            });
        };

        var ajaxGet = function(url, loadingElementSelector, data) {
            if (loadingElementSelector) {
                return _ajaxGetWithLoadingElement(url, loadingElementSelector, data);
            }

            return _ajaxGet(url, data);
        };

        var redirectUnauthorized = function () {
            localStorage.setItem('action', 'redirect');
            localStorage.setItem('reason', 'nonauthorized');

            window.location.reload(false);
        };

        (function () {
            $.ajaxSetup({
                error: function (xhr) {
                    var isAuthorized = (xhr.status !== 401);

                    if (!isAuthorized) {
                        redirectUnauthorized();
                    }
                },
                success: function (data) {
                    var isAuthorized = data !== "NotAuthorized";

                    if (!isAuthorized) {
                        redirectUnauthorized();
                        return;
                    }
                }
            });
        })();


        return {
            ajaxGet: ajaxGet
        };
    })();

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

    var AutocompleteFieldKinds = {
        ClassSpecificationTitleForJobInterestCard: 'ClassSpecificationTitleForJobInterestCard',
        DepartmentTitleForJobInterestCard: 'DepartmentTitleForJobInterestCard',
        LocationTitleForJobInterestCard: 'LocationTitleForJobInterestCard',
        ClassSpecificationsTitleForFilterCategory: 'ClassSpecificationsTitleForFilterCategory'
    };

    OnlineApp.Namespace.extend('OnlineApp', {
        AutocompleteFieldKinds: AutocompleteFieldKinds
    });

})(window);;
(function (window, undefined) {
    'use strict';

    var maxMobileScreenWidth = 767;

    function getOriginatorUrl() {
        var pageTypes = namespace('gJobs').pageInfoService.getPageTypes();
        var isSubmittedApplicationsTab = false;
        var urlParams = url.get(window.location.search.slice(1), { array: true });
        var currentPageType = urlParams.pagetype;
        delete urlParams.pagetype;

        if (!currentPageType) {
            currentPageType = namespace('gJobs').pageInfoService.getCurrentPageType().type;
            isSubmittedApplicationsTab = currentPageType === pageTypes.applications.type;
        }

        for (var param in urlParams) {
            var paramValue = urlParams[param];
            urlParams[param] = paramValue.replace(/\+/g, ' ');
        }

        var newQuery = url.buildget(urlParams);
        newQuery = newQuery ? '?' + newQuery : '';

        // IE10 does not have window.location.origin.
        if (!window.location.origin) {
            window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
        }

        var originator = window.location.origin;
        if (currentPageType === pageTypes.searchPage.type) {
            originator += '/' + pageTypes.searchPage.urlPart + newQuery;
        } else if (currentPageType === pageTypes.applications.type) {
            if (!isSubmittedApplicationsTab) {
                originator += '/' + pageTypes.applications.urlPart + '/incomplete' + newQuery;
            } else {
                originator += '/' + pageTypes.applications.urlPart + '/submitted' + newQuery;
            }
        } else if (currentPageType === pageTypes.inbox.type) {
            originator += "/" + pageTypes.inbox.urlPart + newQuery;
        } else if (currentPageType === pageTypes.categorySearchPage.type) {
            originator += "/" + pageTypes.categorySearchPage.urlPart + '/' + urlParams.category;
        }

        return originator;
    }

    /* TODO: unify, copy-pasted from SearchPage.js */

    function tryRaiseEvent(tryEventName, eventName, eventCallback) {
        var e = jQuery.Event(tryEventName);

        e.canRaiseEvent = true;
        e.callbackEventName = eventName;

        $(document).trigger(e);

        if (e.canRaiseEvent) {
            eventCallback();
        }
    }

    namespace('gJobs').Flyout = function (view) {

        var self = this;
        const currentUrl = window.location.hostname;
        let flyoutBody = ".flyout-window-body";
        let flyoutHeader = ".flyout-window-header";
        if (currentUrl && currentUrl.toLowerCase().includes("schooljobs")) {
            flyoutBody = ".sjobs-flyout-window-body";
            flyoutHeader = ".sjobs-flyout-window-header";
        }
        var elements = {
            $view: $(view),
            $body: $('body'),
            $flyoutBody: $(view).find(flyoutBody),
            $flyoutHeader: $(view).find(flyoutHeader),
            $closeButton: $(view).find('button.close'),
            $title: $(view).find('.flyout-window-header-title'),
            $subtitle: $(view).find('.flyout-window-header-subtitle'),
            $flyoutOverlay: $(view + '-overlay')
        };

        elements.$view.addClass('hide');

        /*
            In Internet Explorer versions prior to 11, height is not correctly calculated for the nested table.
        */
        var applyIEFix = gJobs.browserDetector.isIE() <= 10;

        /*
            Set of methods for manipulation with Master Page.
        */
        var master = {
            masterPageTitle: document.title,

            setScrollable: function (scrollable) {
                elements.$body.toggleClass('inner-scrollbar', !scrollable);

                // Adds padding right to handle contents to stay at its original place
                // in Windows and Firefox in Mac when hiding the scrollbar.
                if (!scrollable) {
                    elements.$body.css('padding-right', this.getScrollbarWidth());
                } else {
                    elements.$body.css('padding-right', 0);
                }
            },
            saveOriginatorUrl: function () {
                self.originator = getOriginatorUrl();
            },
            navigateToOriginatorUrl: function () {
                if (gJobs && gJobs.router && self.originator) {
                    gJobs.router.navigate(self.originator, false);
                }
            },
            getScrollbarWidth: function () {
                var parent,
                    child,
                    width;

                parent = $('<div style="width:50px; height:50px; overflow:auto"><div/></div>').appendTo(elements.$body);
                child = parent.children();
                width = child.innerWidth() - child.height(99).innerWidth();
                parent.remove();

                return width;
            },
        };

        /*
            Set of methods for visibility control of the flyout window.
        */
        var visibility = {
            show: function () {
                elements.$view.removeClass('hide');
                elements.$view.removeClass('inactive');
                elements.$view.addClass('active');
            },
            hide: function (callback) {
                elements.$view.addClass('inactive');
                elements.$view.removeClass('active');

                elements.$view.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {
                    if (!visibility.isVisible()) {
                        elements.$view.addClass('hide');
                        if (typeof callback === 'function') {
                            callback();
                        }
                    }
                });
            },
            isVisible: function () {
                return elements.$view.hasClass('active');
            },
            //specific to IE 8-10
            setContentHeight: function () {
                var $maximizedRelativeBlock = elements.$flyoutBody.find('.position-relative-maximized');

                $maximizedRelativeBlock.height(0);

                var $contentHeader = elements.$flyoutBody.find('.content-header');
                var computedHeight = elements.$flyoutBody.height() - $contentHeader.height();

                $maximizedRelativeBlock.height(computedHeight);
            }
        };

        /*
            Set of methods for state control.
        */
        var state = {
            close: function () {
                if (!state.isActive()) {
                    return;
                }

                $(document).trigger(Events.CommonEventsNames.FlyoutClosing);

                master.setScrollable(true);
                master.navigateToOriginatorUrl();

                if (applyIEFix) {
                    $(window).off('resize deviceClassChanged', visibility.setContentHeight);
                }

                visibility.hide(function () {
                    gJobs.focusService.restoreBrowserControlsFocusBehavior();
                    setTimeout(function () {
                        gJobs.focusService.restoreFocus({
                            focusRestoringCallback: function ($restoringElement) {
                                gJobs.screenReadersService.onceNotification({
                                    $element: $restoringElement,
                                    message: 'Flyout has been closed. '
                                });
                            }
                        });
                    });
                });
            },

            tryClose: function () {
                if (!state.isActive()) {
                    return;
                }

                tryRaiseEvent(
                    Events.CommonEventsNames.TryCloseFlyout,
                    Events.CommonEventsNames.CloseFlyout,
                    self.close
                );

                if (window.enableStickyHeader) {
                    $(document).trigger(Events.CommonEventsNames.ShowStickyHeader);
                }
            },

            open: function () {
                master.saveOriginatorUrl();
                master.setScrollable(false);

                state.restoreDefaultSize();
                visibility.show();
                if (applyIEFix) {
                    visibility.setContentHeight();
                    $(window).on('resize', visibility.setContentHeight);
                }
                $(document).trigger(Events.CommonEventsNames.ShowFlyout, Areas.AreaNames.gJobs);
                gJobs.skipToContentService.showOnNextTab();
            },

            isActive: function () {
                return visibility.isVisible();
            },

            setSize: function (sizeValue) {
                if (sizeValue == parseInt(sizeValue)) {
                    elements.$view.attr('width', sizeValue);
                } else {
                    //the size is 'maximized' / 'fixed'
                    elements.$view.attr('data-size', sizeValue);
                }
                if (applyIEFix) {
                    visibility.setContentHeight();
                }
            },

            restoreDefaultSize: function () {
                elements.$view.attr('data-size', self.defaultSize);
            }
        };

        /*
            Set of methods for input handling.
        */
        var input = {
            registerBehavioralEventsHandlers: function () {
                $(document)
                    .off(Events.CommonEventsNames.CloseFlyout, null, self.close)
                    .on(Events.CommonEventsNames.CloseFlyout, null, self.close);
            },
            registerMouseEventHandlers: function () {

                elements.$closeButton.off('click').click(function () {
                    state.tryClose();
                });

                elements.$flyoutOverlay.off('click').click(function () {
                    state.tryClose();
                });
            }
        };

        self.getView = function () {
            return elements.$view;
        };

        self.create = function () {
            input.registerBehavioralEventsHandlers();
            input.registerMouseEventHandlers();

            self.defaultSize = elements.$view.attr('data-size');
        };

        self.destroy = function () {

        };

        self.open = function ($focusTarget) {
            if ($focusTarget) {
                gJobs.focusService.setFocus($focusTarget);
            }

            state.open();
            $(document).on('keydown', arrowKeyScrollingHandler);

            SetAriaVisibility(true);
            $("#sjobs-footer-new").hide();
            $("#footer-new").hide();
            $(".twitter-timeline").hide();
        };

        self.close = function () {
            state.close();
            $(document).off('keydown', arrowKeyScrollingHandler);

            SetAriaVisibility(false);
            $("#footer-new").show();
            $("#sjobs-footer-new").show();
            $(".twitter-timeline").show();

            document.title = master.masterPageTitle;
        };

        self.isActive = function () {
            return state.isActive();
        };

        self.getTitle = function () {
            return elements.$title.html();
        };

        self.setTitle = function (title) {
            elements.$title.html(title);
        };

        self.getSubtitle = function () {
            return elements.$subtitle.html();
        };

        self.setSubtitle = function (subtitle) {
            if (!subtitle)
                elements.$subtitle.addClass("hide");
            else {
                elements.$subtitle.removeClass("hide");
                elements.$subtitle.html(subtitle);
            }
        };

        self.maximize = function () {
            state.setSize('maximized');
        };

        var $tabbableElements;

        function arrowKeyScrollingHandler(e) {
            var event = e || window.event;
            var keyCode = event.keyCode || event.which;
            var target = event.target || event.srcElement;
            if (keyCode === $.ui.keyCode.UP || keyCode === $.ui.keyCode.DOWN || keyCode === $.ui.keyCode.PAGE_UP || keyCode === $.ui.keyCode.PAGE_DOWN) {
                var isScrollView = $(target).closest('.flyout-scroll-view').length > 0;
                if (!isScrollView) {
                    event.preventDefault();
                }
            }
        }

        function SetAriaVisibility(hide) {
            var $containersToHide = $('#job-list-container, #content-container .top-resume-external-new,' +
                '#content-container .city-info-container, #sidebar-container, #cookie-consent, #applications, #applications-container,.application-container, .applications-tab-header,.applications-tab-buttons,.pager-container');
            $containersToHide.attr('aria-hidden', hide);

            const applicationsDiv = document.getElementById('applications');
            if (applicationsDiv) {
                const elements = applicationsDiv.querySelectorAll('*');
                if (elements) {
                    elements.forEach(element => {
                        element.setAttribute('aria-hidden', hide);
                    });
                }
            }

            if (hide) {
                $tabbableElements = $containersToHide
                    .find(':tabbable')
                    .add($('#job-list-container .share-button, #cookie-consent'));
            }

            if ($tabbableElements) {
                $tabbableElements.attr('tabindex', hide ? '-1' : '0');
            }
        }
    };
})(window);;
(function () {
    'use strict';

    var KEY_CODES = {
        TAB: 9,
        SHIFT: 16
    };

    var TABBABLE_ELEMENT_SELECTOR = ':tabbable',
        FOCUSABLE_ELEMENT_SELECTOR = ':focusable';

    function skipToContentService() {
        var self = this;
        var $document = $(document);
        var $skipToContentButton = $('#skip-to-content-button');

        var isJobSearchPage;
        checkForJobSearchPage();

        $skipToContentButton
            .on('click', onSkipToContentClick)
            .visibleOnFocus();

        $skipToContentButton.on('keyup', onKeyUp);
        function onKeyUp() {

            $skipToContentButton.focus();
        }

        self.showOnNextTab = function (callbackAfterShow, focusRestoreCallback) {
            $document.on('keydown', showOnNextTabHandler);
            $document.on('mousedown', showOnNextTabHandler);

            function showOnNextTabHandler(e) {
                $document.off('keydown', showOnNextTabHandler);
                $document.off('mousedown', showOnNextTabHandler);

                if (!e.keyCode || e.keyCode !== KEY_CODES.TAB) {
                    return;
                }

                e.stopPropagation();
                e.preventDefault();
                var $lastFocused = $(document.activeElement);
                $skipToContentButton.focus();
                if (typeof (focusRestoreCallback) == 'function') {
                    $skipToContentButton.one('keydown', function (e) {
                        if (e.keyCode !== KEY_CODES.TAB) {
                            return;
                        }
                        e.stopPropagation();
                        e.preventDefault();
                        focusRestoreCallback($lastFocused);
                    });
                }
                callbackAfterShow && callbackAfterShow();
            }
        };

        $(window).on('statechange', checkForJobSearchPage);

        function checkForJobSearchPage() {
            isJobSearchPage = window.location.pathname === '/jobs' || window.location.pathname === '/jobs/';
            var buttonText = isJobSearchPage ? 'Skip to search results' : 'Skip to main content';
            $skipToContentButton.find('.visible-on-focus-text').text(buttonText);
        }

        function getFirstFocusableElementSelector($contentContainer) {
            return $contentContainer.hasClass('no-tabbable-main-content')
                ? FOCUSABLE_ELEMENT_SELECTOR
                : TABBABLE_ELEMENT_SELECTOR;
        }

        function onSkipToContentClick() {
            var $contentContainer = getContentContainer();
            var firstFocusableElemetSelector = getFirstFocusableElementSelector($contentContainer);
            var $focusTarget = $contentContainer.find(firstFocusableElemetSelector).first();
            if ($focusTarget.length && $focusTarget[0].id == "el-candidate-keyword-search-input") {
                $("#back-eligible-list-link").focus();
            }
            else if ($contentContainer[0] && $contentContainer[0].id == "canvass-body" && $focusTarget.length == 0)
            {
                $("#last-focusable-element").focus();
            }
            else if ($focusTarget.length) {
                $focusTarget.focus();
                if ($focusTarget.data('bs.popover')) {
                    setTimeout(function () {
                        $focusTarget.popover('show');
                    }, 100);
                }
            } else {
                $contentContainer.focus();
            }
        }

        function getContentContainer() {
            var $termsAndPrivacyPolicyChangeAnnouncement = $('#terms-and-privacy-policy-update-confirmation.active');
            if ($termsAndPrivacyPolicyChangeAnnouncement.length) {
                return $termsAndPrivacyPolicyChangeAnnouncement;
            }

            if (isJobSearchPage) {
                return $('#content-container');
            }

            var $sortFlyoutContainer = $('.new-filter-flyout.active .sort-panel').closest('.flyout');
            if ($sortFlyoutContainer.length) {
                // If there's an already selected element within the flyout, focus the first selected one.
                var $selectedLabel = $sortFlyoutContainer.find('input:checked').first();
                if ($selectedLabel.length) {
                    return $selectedLabel.parent().closest('div');
                }

                return $sortFlyoutContainer;
            }

            var $filterFlyoutContainer = $('.new-filter-flyout.active .filter-flyout-container');
            if ($filterFlyoutContainer.length) {
                return $filterFlyoutContainer;
            }

            var $flyoutDetailsContainer = $('#job-flyout-content .entity-info:visible');
            if ($flyoutDetailsContainer.length) {
                return $flyoutDetailsContainer;
            }

            var $classSpecFlyoutContent = $('.class-specs-flyout.active #class-specs-flyout-content .active .onlineapp-wrapper:visible');
            if ($classSpecFlyoutContent.length) {
                return $classSpecFlyoutContent;
            }

            var $classSpecificationsFlyout = $('.tab-content #info .info-content');
            if ($classSpecificationsFlyout.length) {
                return $classSpecificationsFlyout;
            }

            var $incompleteAppFlyoutDetailsContainer = $('#incomplete-application-flyout-content .entity-info:visible');
            if ($incompleteAppFlyoutDetailsContainer.length) {
                return $incompleteAppFlyoutDetailsContainer;
            }

            var $jobFlyoutApplicationSubmitContent = $('#online-application-block:visible > .submitted');
            if ($jobFlyoutApplicationSubmitContent.length) {
                return $jobFlyoutApplicationSubmitContent;
            }

            var $jobFlyoutContent = $('#online-application-block:visible');
            if ($jobFlyoutContent.length) {
                return $jobFlyoutContent.find('.tab-content.onlineapp-tabs');
            }

            var $infoView = $('.tab-content #info-view:visible');
            if ($infoView.length) {
                return $infoView;
            }

            var $applyTab = $('.tab-content #apply:visible');
            if ($applyTab.length) {
                return $applyTab;
            }

            var $jobInterestCardFlyoutContent = $('.job-interest-card-flyout.active #job-interest-card-flyout-content .active .onlineapp-wrapper:visible');
            if ($jobInterestCardFlyoutContent.length) {
                return $jobInterestCardFlyoutContent;
            }

            var $jobSearchHeaderContainer = $('.job-search-header-container');
            if ($jobSearchHeaderContainer.find(':focusable').length) {
                return $jobSearchHeaderContainer;
            }

            var $gJobsApplicationView = $('.application-view-page.active .flyout-content .job-details-container.active');
            if ($gJobsApplicationView.length) {
                return $gJobsApplicationView;
            }

            var $onlineApplicationView = $('.new-job-flyout.active #submitted-application-flyout-content .flyout-tab.active .entity-info, ' +
                '.new-job-flyout.active #submitted-application-flyout-content .flyout-tab.active .application-container');
            if ($onlineApplicationView.length) {
                return $onlineApplicationView;
            }

            var $jobAlertEditFlyout = $('.job-alert-edit-content #search-form:visible');
            if ($jobAlertEditFlyout.length) {
                return $jobAlertEditFlyout;
            }

            var $settings = $('#account-settings:visible, #profile-settings:visible');
            if ($settings.length) {
                return $settings.find('.tab-content');
            }

            var $convictionQuestions = $('.conviction-questionnaire-page #questions-tab, .conviction-questions:visible .box-container.edit-dialog');
            if ($convictionQuestions.length) {
                return $convictionQuestions;
            }

            var $careersScheduleFlyoutContent = $('.schedule-exam-flyout.active .content');
            if ($careersScheduleFlyoutContent.find(':focusable').length) {
                return $careersScheduleFlyoutContent;
            }

            var $careersScheduleFlyout = $('.schedule-exam-flyout.active');
            if ($careersScheduleFlyout.length) {
                return $careersScheduleFlyout;
            }

            var $careersHistoryFlyout = $('.app-history-flyout.active');
            if ($careersHistoryFlyout.length) {
                return $careersHistoryFlyout.find('.flyout-content');
            }

            var $homePageContent = $('#search-form, .search-form');
            if ($homePageContent.length) {
                return $homePageContent;
            }

            var $inboxMessageDetailsContainerBody = $(".inbox-message-view-page #inbox-message-body");
            if ($inboxMessageDetailsContainerBody.length) {
                return $inboxMessageDetailsContainerBody;
            }

            var $inboxMessageDetailsContainer = $(".inbox-message-view-page");
            if ($inboxMessageDetailsContainer.length) {
                return $inboxMessageDetailsContainer;
            }

            var $inboxContainer = $(".inbox-container");
            if ($inboxContainer.length) {
                return $inboxContainer;
            }

            var $helpAndSupport = $('.info-body:visible');
            if ($helpAndSupport.length) {
                return $helpAndSupport;
            }

            var $offerLetterFlyoutContent = $('#offer-flyout-content .header-offer-response-container:visible,' +
                '#offer-flyout-content .flyout-tab-body:visible:not(.readonly)');
            if ($offerLetterFlyoutContent.length) {
                return $offerLetterFlyoutContent;
            }

            var $offerLetterFlyoutAttachmentsContent = $('#offer-flyout-content .flyout-tab-footer:visible');
            if ($offerLetterFlyoutAttachmentsContent.length) {
                return $offerLetterFlyoutAttachmentsContent;
            }

            var $canvassFormFlyoutContent = $('#canvass-flyout-content .flyout-tab-body:visible');
            if ($canvassFormFlyoutContent.length) {
                return $canvassFormFlyoutContent;
            }

            var $addSupplementalAttachmentsFlyoutContent = $('.flyout-content.supplemental-attachments-flyout-content:visible');
            if ($addSupplementalAttachmentsFlyoutContent.length) {
                return $addSupplementalAttachmentsFlyoutContent;
            }

            var $contentContainer = $('.content-container:visible');
            if ($contentContainer.length) {
                return $contentContainer;
            }

            var $scheduleFlyoutContent = $('.flyout-window.schedule-exam-page.active .content');
            if ($scheduleFlyoutContent.find(':focusable').length) {
                return $scheduleFlyoutContent;
            }

            var $scheduleFlyout = $('.flyout-window.schedule-exam-page.active');
            if ($scheduleFlyout.length) {
                return $scheduleFlyout;
            }

            if (window.enableJobDetailRedesign) {
                var $jobHeaderContent = $('.entity-standalone-header .job-header-content');
                if ($jobHeaderContent.length) {
                    return $jobHeaderContent;
                }
            } 

            var $jobDetailsFlyoutContent = $('.tab-content.job-details-tabs.flyout-content');
            if ($jobDetailsFlyoutContent.length) {
                return $jobDetailsFlyoutContent;
            }

            var $applicationHistoryContent = $('.application-history-content:visible');
            if ($applicationHistoryContent.length) {
                return $applicationHistoryContent;
            }

            var $content = $('#content:visible');
            if ($content.length) {
                return $content;
            }

            var $header = $('#header');
            if(!$header.hasClass('mobile-collapsed')){
                return $header;
            }
        }

        return self;
    };

    namespace('gJobs').skipToContentService = new skipToContentService();
})();;
(function (window, $, ko, undefined) {
    'use strict';

    if (!$ || !ko) {
        throw new Error("jQuery and Knockout should be defined");
    }

    var ApplicationMenu = function () {
        var self = this;

        self.incompleteApplicationsCount = ko.observable();

        self.unreadMessagesCount = ko.observable();
        self.displayedUnreadMessagesCount = ko.computed(function () {
            return self.unreadMessagesCount() > 99 ? "99+" : self.unreadMessagesCount();
        });

        self.showIcon = ko.computed(function () {
            var count = parseInt(self.incompleteApplicationsCount());
            return !isNaN(count) && count > 0;
        });
        self.showUnreadMessagesCount = ko.computed(function() {
            var count = parseInt(self.unreadMessagesCount());
            return !isNaN(count) && count > 0;
        });

        self.unreadMessagesLabelText = ko.computed(function(){
            var count = parseInt(self.unreadMessagesCount());
            var message = 'Inbox';
            if (!isNaN(count) && count > 0) {
                message += ', ' + count + ' unread messages';
            }
            return message;
        });
    };

    var employerFolderName;
    //Defaulting this to one when user logs in
    var siteFilterType = 1;
    namespace('gJobs').applicationMenu = (function () {
        
        var instance;

        return {
            getInstance: function () {
                if (!instance) {
                    instance = new ApplicationMenu();
                }

                return instance;
            },
            updateIncompleteApplicationsCount: function (value) {
                var countObservable = this.getInstance().incompleteApplicationsCount;
                var url = '/Applications/GetIncompleteApplicationsCount' +
                          (!!employerFolderName ? '?employerFolderName=' + employerFolderName : '');

                if (value != null) {
                    countObservable(value);
                } else {
                    gJobs
                        .ajax
                        .ajaxGet(url)
                        .done(function (count) {
                            if (count) {
                                countObservable(count);
                            }
                        });
                }
            },
            incrementIncompleteApplicationsCount: function() {
                var countObservable = this.getInstance().incompleteApplicationsCount;
                countObservable(countObservable() + 1);
            },
            decrementIncompleteApplicationsCount: function() {
                var countObservable = this.getInstance().incompleteApplicationsCount;
                countObservable(countObservable() - 1);
            },

            updateUnreadMessagesCount: function () {
                var countObservable = this.getInstance().unreadMessagesCount;

                OnlineApp.Services.authenticationService.isLoggedIn()
                    .done(function (isLoggedIn) {
                        if (isLoggedIn) {
                            $.ajax({
                                url: "/api/inbox/GetNumberOfMessagesInCategories",
                                type: "GET",
                                data: { siteFilterType: siteFilterType, employerFolderName: employerFolderName }
                                })
                                .done(function (data) {
                                    try {
                                        var numberOfUnreadMessages = parseInt(data.numberOfUnreadMessages);
                                        countObservable(numberOfUnreadMessages);
                                    }
                                    catch(ex){}
                                })
                                .fail(function (error) {
                                    console.log(error);
                                });
                        }
                    });
            },
            decrementUnreadMessagesCount: function () {
                var countObservable = this.getInstance().unreadMessagesCount;
                countObservable(countObservable() - 1);
            },
            getApplicationUserMenu: function() {
                if (revampedDesign) {
                    return $("#header .nav.right-nav");
                }

                return $("#header .application-menu-link");
            },
            isApplicationUserMenuShown: function () {
                var $applicationUserMenu = this.getApplicationUserMenu();
                return $applicationUserMenu.length ? !$applicationUserMenu.hasClass('hide') : false;
            },
            initApplicationUserMenu: function () {
                var $appMenu = this.getApplicationUserMenu();
                var appMenuElement = $appMenu.get(0);

                this.updateApplicationUserMenu();

                if (ko.dataFor(appMenuElement)) {
                    return;
                }

                var appMenuInstance = this.getInstance();

                employerFolderName = AgencyPages.pageInfoService ?
                    AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                    gJobs.pageInfoService.getCurrentAgencyPageFolderName();

                $appMenu.removeClass('hide');

                // Apply knockout bindings when DOM is ready
                ko.applyBindings(
                    appMenuInstance,
                    appMenuElement);
            },
            updateApplicationUserMenu: function() {
                gJobs.applicationMenu.updateIncompleteApplicationsCount();
                gJobs.applicationMenu.updateUnreadMessagesCount();               
            }
        };
    })();

    $(function () {
        // After document is loaded and user is loggedin need to init application user menu
        if (gJobs.applicationMenu.isApplicationUserMenuShown()) {
            gJobs.applicationMenu.initApplicationUserMenu();
        }

        if (revampedDesign && gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.GJobs) {
            gJobs.nonFlickeringPopover($('.inbox-link a'), 'header-nav-popover visible-desktop');
        }
    });

    var initAsyncEventsNames =
        OnlineApp.Events.CommonEventsNames.Login + ' ' +
        Events.CommonEventsNames.Register;

    var updateAsyncEventNames =
        Events.CommonEventsNames.ApplicationSubmitted + ' ' +
        Events.CommonEventsNames.CloseFlyout;

    $(document)
        .on(initAsyncEventsNames,
            function () {
                gJobs.applicationMenu.initApplicationUserMenu();
            })
        .on(updateAsyncEventNames,
            function() {
                if (gJobs.applicationMenu.isApplicationUserMenuShown()) {
                    gJobs.applicationMenu.updateApplicationUserMenu();
                }
            })
        .on(Events.CommonEventsNames.DecreaseNumberOfUnreadMessages,
            function() {
                gJobs.applicationMenu.decrementUnreadMessagesCount();
            });

})(window, jQuery, ko);;
(function(window, undefined) {
    'use strict';

    var $detailsContainer = $('#content-container');

    /**
     * Gets a URL leading to Online Application scripts.
     *
     * @return {String} The URL leading to Online Application scripts.
     */
    var getOnlineApplicationScriptsUrl = function () {
        return $('#online-application-link').attr('href');
    };

    /**
     * Gets current job id.
     *
     * @return {Number} Id of currently selected job.
     */

    var initialTabId;

    /**
     * Converts html text into set of script elements
     *
     * @return {jQuery<HTMLScriptElement>} The jQuery array of script tags.
     */
    var getScriptTagsFromText = function (text) {
        var elements = $.parseHTML(text, document, true);
        var $scriptElements = $(elements).filter('script');

        return $scriptElements;
    };


    /**
     * Loads scripts asynchronously with respect to ordering.  
     *
     * @param {jQuery<HTMLScriptElement>} $scriptElements List of scripts.
     * @return {Promise} Empty.
     */
    var loadScriptsFromListAsync = function ($scriptElements) {
        var chain = $LAB.sandbox();
        var deferred = $.Deferred();

        $scriptElements.each(function () {
            var $scriptElement = $(this);
            var scriptUrl = $scriptElement.attr('src');
            var scriptContent = $scriptElement.text();

            if (scriptUrl) {
                chain = chain.script(scriptUrl).wait();
            }
            else {
                var inlineScript = new Function(scriptContent);

                chain.wait(inlineScript);
            }
        });

        chain.wait(function () {
            deferred.resolve();
        });


        return deferred.promise();
    };


    /**
     * Retrives list of Online Application scripts.
     *
     * @return {Promise} The jQuery array of script tags. 
     */
    var getListOfOnlineApplicationScriptsAsync = function () {
        var onlineApplicationScriptsUrl = getOnlineApplicationScriptsUrl();

        var promise = gJobs.ajax
            .ajaxGet(onlineApplicationScriptsUrl)
            .then(function (text) {
                return getScriptTagsFromText(text);
            });

        return promise;
    };


    /**
     * Initializes Online Application.
     */
    var initOnlineApplication = function (isOnlineAppInitAllowed) {

        //In some cases, for example when user closes the online app flyout in the middle of loading process, we should avoid initializing after the data is loaded.
        if (typeof(isOnlineAppInitAllowed) === 'function' && !isOnlineAppInitAllowed()) {
            return;
        }

        //var $apply = $('.onlineapp-wrapper');
        var $apply = $('#online-application-block');

        $apply.data('onlineApplicationLoaded', true);

        if ($apply.length !== 0) {
            var viewModel = OnlineApp.ViewModels.applicationViewModel;
            var element = $apply.get(0);

            //ko.cleanNode(element);
            ko.applyBindings(viewModel, element);
        }

        var currentJobId = gJobs.jobsDetails.getCurrentJobId();

        OnlineApp.ViewModels.applicationViewModel.jobId(currentJobId);
        if (initialTabId) {
            OnlineApp.ViewModels.applicationViewModel.initialTabId(initialTabId);
        }
    };

    namespace('gJobs').jobsDetails = {

        /*
            TODO: 
                This method clearly needs to be rewritten. As far as I can tell it was written for DEMO purposes
                and somehow managed to survive till UAC.

                Curently I see: 
                    few violations of styling guidelines, 
                    text constant abuse, 
                    code dublication, 
                    SRP violations,
                    redundant jQuery selectors.
        */
        loadOnlineApplication: function (isOnlineAppInitAllowed) {
            if (gJobs.searchPage.apply) {
                if ($('#apply').data('onlineApplicationLoaded'))
                    return;
            }

            var $onlineApplicationLink = $('#online-application-link');


            if ($onlineApplicationLink.length) {

                getListOfOnlineApplicationScriptsAsync()
                    .then(loadScriptsFromListAsync)
                    .then(function () {
                        initOnlineApplication(isOnlineAppInitAllowed);
                    });
            }
        },
        getCurrentJobId: function () {
            var jobAttribute = $('#online-application-link').attr('job');
            var jobId = parseInt(jobAttribute);
    
            return jobId;
        }
    };

    updateLinksWithIncreaseClickCountFunc($('#details-info').find('a'));

    //
    // Initializer
    //
    $(function() {
        $($detailsContainer)
            .find('#apply-button')
            .one('show', function () {
                gJobs.jobsDetails.loadOnlineApplication();
            })
            .on('click', function () {
                displayStickyHeader(true);
                increaseClickCount(true, getJobIdFromUri());
            });

        if (gJobs && gJobs.router && History) {
            var initialState = History.getState();
            if (!!initialState.url.match(/\/apply(\/|#[a-z,-]+|\?|\?[\w,\-,\.,\&,\=,\%]+)?$/)
                && gJobs.searchPage
                && gJobs.searchPage.setTab) {

                gJobs.searchPage.setTab(1);
                var hash = History.getHash();
                if (hash) {
                    initialTabId = hash;
                    gJobs.router.checkRoutes(initialState);
                }
            }
        }
    });

    function updateLinksWithIncreaseClickCountFunc(linksFromDescription) {
        var jobId = getJobIdFromUri();
        if (jobId) {

            for (var i = 0; i < linksFromDescription.length; i++) {
                linksFromDescription[i].setAttribute('onmousedown', 'increaseClickCount(false, "' + jobId + '")')
            }
        }
    }

    function getJobIdFromUri() {
        var jobAttr = $('#job-details-button').attr('data-job-url');
        return jobAttr ? jobAttr.split('/')[2] : null;
    }

    $(document).keydown(function(e) {
        if (e.keyCode === $.ui.keyCode.ESCAPE) {
            if ($(e.target).hasClass('job-details-location-icon')
                || $(e.target).hasClass('job-details-salary-icon')) {
                $(e.target).popover('hide');
            }
        }
    });

    
    document.addEventListener('DOMContentLoaded', function () {
        let tablists = document.querySelectorAll('[role=tablist]');
        for (let i = 0; i < tablists.length; i++) {
            new TabsManual(tablists[i]);
        }
    });
})(window);;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').InitIncompleteAppView = initIncompleteAppView;

    // nextJobCallback, prevJobCallback, checkJobPositionCallback
    function initIncompleteAppView(settings) {

        var FLYOUT_EXPANDED_TEXT = 'Flyout was expanded';

        var incompleteAppFlyout = new gJobs.Flyout('.incomplete-app-view-page');
        incompleteAppFlyout.create();

        var incompleteAppView = incompleteAppFlyout.getView();

        var $jobDetailsContainer = incompleteAppView.find('.job-details-view-container');
        var applicationContainer = incompleteAppView.find('.job-apply-container');
        var openedNotification = $('.opened-notification');
        var loadedNotification = $('.loaded-notification');
        var commonNotification = $('.common-notification');
        var additionalContentContainer = incompleteAppView.find('.additional-content-container');
        var tabsContainer = incompleteAppView.find('.flyout-header-tabs');
        var tabs = incompleteAppView.find('.flyout-header-tabs a:visible');
        var applyButton = incompleteAppView.find('#applyButton');
        var $externalApplyButtonContainer = incompleteAppView.find('#external-apply');
        var jobDetailsButton = incompleteAppView.find('#jobDetailsButton');
        var infoViewAdditionalContent = additionalContentContainer
            .find('div[data-content-bind="info-view"]');
        var autosaveMessage = $('.autosave');
        var jobInfoUrl = '/jobInfo/jobDetails/';
        var appUrl = '/jobInfo/apply/';
        var jobDetailsUrl = undefined;
        var jobTitle = undefined;
        var jobPositionOnPage = undefined;
        var activeJobId;
        var areShareButtonsInitialized = false;
        var layoutHelper = OnlineApp.Helpers.layoutHelper;
        var stickyHeader = '#sticky-header';

        var arrEventHolder = [];

        var incompleteAppLinksContainer = $('#job-list-container');

        var showStickyHeaderEvents = Events.CommonEventsNames.CloseFlyout +
            ' ' + Events.CommonEventsNames.ShowStickyHeader;

        function addCommonNotification(text) {
            commonNotification.text(' ').text(text);
        }

        $(document)
            .on(Events.CommonEventsNames.ShowOnlineApp, function () {
                gJobs.router.navigate(jobDetailsUrl + '/apply', null, null, null, {
                    jobTitle: jobTitle
                }, true);
            })
            .on(Events.CommonEventsNames.FlyoutClosing, function () {
                gJobs.searchPage.searchResults.setActiveItem();
                gJobs.screenReadersService.clearNotification(loadedNotification);
                gJobs.screenReadersService.clearNotification(openedNotification);
            })
            .on(showStickyHeaderEvents, function () {
                handleDisplayOfApplicationProcessWithStickyHeader(false);
            })
            .on(Events.CommonEventsNames.HideStickyHeader, function () {
                handleDisplayOfApplicationProcessWithStickyHeader(true);
            });

        // For switching between jobs.
        var nextButton = incompleteAppView.find('button.navigate-down');
        var prevButton = incompleteAppView.find('button.navigate-up');

        var switchJobsButtonsExist = (nextButton.length !== 0) && (prevButton.length !== 0);

        incompleteAppView
            .on('keydown', '#description', function (event) {
                if (event.key == "Enter") {
                    $('#description').attr('tabindex', '0');
                    $('#applyButton').attr('tabindex', '-1');
                    let benefitsButton = $('#benefits');
                    let questionsButton = $('#questions');
                    if (benefitsButton) {
                        benefitsButton.attr('tabindex', '-1');
                    }
                    if (questionsButton) {
                        questionsButton.attr('tabindex', '-1');
                    }
                    applyTabSettings();
                }
            })
            .on('click', '#description', function () {
                $('#description').attr('tabindex', '0');
                $('#applyButton').attr('tabindex', '-1');
                let benefitsButton = $('#benefits');
                let questionsButton = $('#questions');
                if (benefitsButton) {
                    benefitsButton.attr('tabindex', '-1');
                }
                if (questionsButton) {
                    questionsButton.attr('tabindex', '-1');
                }
                applyTabSettings();
            })

            .on('keydown', '#benefits', function (event) {
                if (event.key == "Enter") {
                    $('#benefits').attr('tabindex', '0');
                    $('#applyButton').attr('tabindex', '-1');
                    let descButton = $('#description');
                    let questionsButton = $('#questions');
                    if (descButton) {
                        descButton.attr('tabindex', '-1');
                    }
                    if (questionsButton) {
                        questionsButton.attr('tabindex', '-1');
                    }
                }
                applyTabSettings();
            })
            .on('click', '#benefits', function () {
                $('#benefits').attr('tabindex', '0');
                $('#applyButton').attr('tabindex', '-1');
                let descButton = $('#description');
                let questionsButton = $('#questions');
                if (descButton) {
                    descButton.attr('tabindex', '-1');
                }
                if (questionsButton) {
                    questionsButton.attr('tabindex', '-1');
                }
                applyTabSettings();
            })

            .on('keydown', '#questions', function (event) {
                if (event.key == "Enter") {
                    $('#questions').attr('tabindex', '0');
                    $('#applyButton').attr('tabindex', '-1');
                    let descButton = $('#description');
                    let benefitsButton = $('#benefits');
                    if (descButton) {
                        descButton.attr('tabindex', '-1');
                    }
                    if (benefitsButton) {
                        benefitsButton.attr('tabindex', '-1');
                    }
                }
                applyTabSettings();
            })
            .on('click', '#questions', function () {
                $('#questions').attr('tabindex', '0');
                $('#applyButton').attr('tabindex', '-1');
                let descButton = $('#description');
                let benefitsButton = $('#benefits');
                if (descButton) {
                    descButton.attr('tabindex', '-1');
                }
                if (benefitsButton) {
                    benefitsButton.attr('tabindex', '-1');
                }
                applyTabSettings();
            })

            .on('keydown', '#jobDetailsButton', function (event) {
                if (event.key == "Enter") {
                    clickJobDetailsButton();
                }
            })
            .on('keydown', '#applyButton', function (event) {
                if (event.key == "Enter") {
                    $('#jobDetailsButton').attr('tabindex', '-1');
                    clickApplyButton();
                }
            })
            .on('click', '#jobDetailsButton', function () {
                clickJobDetailsButton();
            })
            .on('click', '#applyButton', function () {
                $('#jobDetailsButton').attr('tabindex', '-1');
                clickApplyButton();

            })
            .on('show', '#jobDetailsButton', function (e) {
                autosaveMessage.hide();
            })
            .on('show', '#applyButton', function (e) {
                autosaveMessage.hide();
            });

        // Add listener to 'shown' event for switching between content.
        incompleteAppView.on('shown', '.flyout-header-tabs', switchAdditionalContent);
        if (switchJobsButtonsExist) {
            incompleteAppView.on('shown', '.flyout-header-tabs', switchSwitchButtons);
        }

        window.increaseClickCount = function (isApplyClick, jobId) {
            let splittedJobId = jobId && jobId.split('-') || activeJobId.split('-');
            if (splittedJobId[1] === '1') {                
                $.ajax({
                    type: 'GET',
                    url: '/jobInfo/IncreaseApplyClickCount/' + splittedJobId[0] + '/' + isApplyClick,
                    async: true
                });
            }
        };

        window.displayStickyHeader = function (isApplicationProcessStarted) {
            handleDisplayOfApplicationProcessWithStickyHeader(isApplicationProcessStarted)
        }

        window.increaseHitsCount = function (jobId) {
            let splittedJobId = jobId && jobId.split('-');
            if (splittedJobId[1] === '1') {
                $.ajax({
                    type: 'GET',
                    url: '/jobInfo/IncreaseHitsJobCount/' + splittedJobId[0],
                    async: true
                });
            }
        };

        function applyTabSettings() {
            setTimeout(function () {
                let desc_li = $('.description');
                let questions_li = $('.questions');
                let benefits_li = $('.benefits');
                let descButton = $('#description');
                let benefitsButton = $('#benefits');
                let questionsButton = $('#questions');
                if (desc_li) {
                    let isDescActive = desc_li.hasClass('active');
                    if (isDescActive == true) {
                        descButton.attr('tabindex', '0');
                        questionsButton.attr('tabindex', '-1');
                        benefitsButton.attr('tabindex', '-1');
                    }
                }
                if (benefits_li) {
                    let isBenefitsActive = benefits_li.hasClass('active');
                    if (isBenefitsActive == true) {
                        descButton.attr('tabindex', '-1');
                        questionsButton.attr('tabindex', '-1');
                        benefitsButton.attr('tabindex', '0');
                    }
                }
                if (questions_li) {
                    let isQuestionsActive = questions_li.hasClass('active');
                    if (isQuestionsActive == true) {
                        descButton.attr('tabindex', '-1');
                        questionsButton.attr('tabindex', '0');
                        benefitsButton.attr('tabindex', '-1');
                    }
                }
            }, 200);
        }

        function clickJobDetailsButton() {
            if (jobDetailsUrl != undefined) {
                gJobs.router.navigate(jobDetailsUrl, null, null, null, {
                    jobTitle: jobTitle
                }, true);
            }
            $('#applyButton').attr('aria-selected', 'false');
            $('#applyButton').attr('tabindex', '-1');
            $('#jobDetailsButton').attr('aria-selected', 'true');
            $('#jobDetailsButton').attr('tabindex', '0');
            let tablists = document.querySelectorAll('[role=tablist]');
            for (let i = 0; i < tablists.length; i++) {
                new TabsManual(tablists[i]);
            }
            applyTabSettings();
        }

        function clickApplyButton() {
            handleDisplayOfApplicationProcessWithStickyHeader(true);

            increaseClickCount(true);

            OnlineApp.Services.analyticsService.trackEvent('Apply Link Clicked');
            $(document).trigger(OnlineApp.Events.CommonEventsNames.ApplyTabOpened);

            if (jobDetailsUrl != undefined) {
                var applicationUrl = jobDetailsUrl + '/apply';
                gJobs.router.navigate(applicationUrl, null, null, null, {
                    jobTitle: jobTitle
                }, true);
            }
            OnlineApp.Services.authenticationService.isLoggedIn()
                .done(function (isLoggedIn) {
                    $("#skip-to-content-button").show();
                    $("#skip-to-content-button").focus();

                    if (isLoggedIn) {
                        OnlineApp.Services.authenticationService.getUserData()
                            .done(function (getUserData) {
                                if (getUserData) {
                                    var baseUrl = window.location.origin;
                                    if (!getUserData.email) {
                                        window.location.href = baseUrl + "/Applications/AccountSettings#contact";
                                    }
                                    let tablists = document.querySelectorAll('[role=tablist]');
                                    for (let i = 0; i < tablists.length; i++) {
                                        new TabsManual(tablists[i]);
                                    }
                                    $('#jobDetailsButton').attr('aria-selected', 'false');
                                    $('#applyButton').attr('aria-selected', 'true');
                                    $('#applyButton').attr('tabindex', '0');
                                    $('#jobDetailsButton').attr('tabindex', '-1');
                                }
                            });
                    }
                });

            let tablists = document.querySelectorAll('[role=tablist]');
            for (let i = 0; i < tablists.length; i++) {
                new TabsManual(tablists[i]);
            }
            $('#jobDetailsButton').attr('aria-selected', 'false');
            $('#applyButton').attr('aria-selected', 'true');
            $('#applyButton').attr('tabindex', '0');
            $('#jobDetailsButton').attr('tabindex', '-1');

        }

        function initShareButtons(jobRelativePath, jobTitle, location) {
            var jobUrl = window.location.protocol
                + '//'
                + window.location.host
                + removeApplyFromUrl(jobRelativePath);

            if (jobTitle && jobTitle == jobTitle.toUpperCase()) {
                //If job title is set to ALL CAPS, need to convert it to Title Case
                jobTitle = window.utils.toTitleCase(jobTitle);
            }

            var $addthisToolbox = infoViewAdditionalContent.find('.share-button-group');
            if ($addthisToolbox.length) {
                gJobs.common.social.init($addthisToolbox, jobTitle, jobUrl, location);
            }

            infoViewAdditionalContent
                .on('click', '.share-button', function (e) {
                    infoViewAdditionalContent.find('.share-button-group').toggle(400, function () {
                        if (!window.enableShareThis) {
                            var linkedInButton = $(this).children('a')[0];
                            $(linkedInButton).focus();
                        } else {
                            $(this).children('button')[0].focus();
                        }
                    });
                    OnlineApp.Helpers.layoutHelper.tabbing.updateIndices(incompleteAppFlyout);
                    e.preventDefault();
                });
        }

        if (nextButton.lenght != 0) {
            nextButton.removeClass('hide');

            if (settings && settings.nextJobCallback) {
                nextButton.on('click', function () {
                    settings.nextJobCallback();
                });
            }
        }
        if (prevButton.lenght != 0) {
            prevButton.removeClass('hide');

            if (settings && settings.prevJobCallback) {
                prevButton.on('click', function () {
                    settings.prevJobCallback();
                });
            }
        }

        gJobs.accessibilityHtmlTransformer.makeElementContentAccessible($('.job-details-content'));

        //In backfilled search results, all links have target=_blank, and they should not open the flyout.
        incompleteAppLinksContainer.on('click', '.job-details-link[target!="_blank"]', function (e) {
            var link = $(this);

            var jobUrl = link.attr('href');
            var title = link.text();
            jobTitle = title;
          
            if (window.enableJobDetailRedesign === true) {
                const searchQuery = window.location.search; 
                sessionStorage.setItem('searchQuery', searchQuery);
                const fullJobUrl = jobUrl;              
                window.location.href = fullJobUrl;
            }
            else {
                // Flyout behavior
                infoViewAdditionalContent.off('click').find('.share-button-group').hide();

                var $jobLocation = link.parent().siblings('.job-location');
                if ($jobLocation.length) {
                    // On Search Page, it is possible to get the Location from the link container
                    var location = $jobLocation.text();
                    initShareButtons(jobUrl, jobTitle, location);
                    areShareButtonsInitialized = true;
                } else {
                    // For pages like Applications Page it's not possible,
                    // so we postpone initialization of the share buttons until the Job Details are loaded
                    areShareButtonsInitialized = false;
                }

            incompleteAppFlyout.setTitle(title);
            gJobs.searchPage.details.originator = History.getLastStoredState().url;
            var pageType = namespace('gJobs').pageInfoService.getCurrentPageType().type;
            var newQuery;
            if (pageType == 'categorySearchPage') {                
                var pathParts = window.location.pathname.split('/').filter(function (part) { return part.length > 0; });
                var lastPart = pathParts.length > 0 ? pathParts[pathParts.length - 1] : '';
                newQuery = '?category=' + encodeURIComponent(lastPart) + '&pagetype=' + pageType;
            }
            else newQuery = window.location.search ? window.location.search + '&pagetype=' + pageType : '?pagetype=' + pageType;

            gJobs.router.navigate(jobUrl + newQuery, null, null, null, {
                jobTitle: jobTitle
            });
            attachOnTabChangeEvent();
            let tablists = document.querySelectorAll('[role=tablist]');
            for (let i = 0; i < tablists.length; i++) {
                new TabsManual(tablists[i]);
            }

                $('#applyButton').attr('tabindex', '-1');
                $('#jobDetailsButton').attr('tabindex', '0');
            }

            e.preventDefault();
        });

        function handleDisplayOfApplicationProcessWithStickyHeader(isApplicationProcessStarted) {
            if (window.enableStickyHeader) {
                OnlineApp.Services.authenticationService.isLoggedIn()
                    .done(function (isLoggedIn) {
                        if (isLoggedIn) {
                            var stickyHeaderHeight = $(stickyHeader).outerHeight();

                            var $currentFlyout = $('#content .flyout-window.incomplete-app-view-page');
                            var currentFlyoutTopStyling = parseInt($currentFlyout.css('top'));

                            var $maximizedRelativeBlock = $('.position-relative-maximized');
                            var maximizedRelativeBlockHeightStyling = $maximizedRelativeBlock.height();

                            if (isApplicationProcessStarted && $(stickyHeader).is(':visible')) {
                                currentFlyoutTopStyling -= stickyHeaderHeight;
                                maximizedRelativeBlockHeightStyling += stickyHeaderHeight;
                                $(stickyHeader).hide();
                            } else if (!isApplicationProcessStarted && !$(stickyHeader).is(':visible')
                                && !$currentFlyout.hasClass('active')) {
                                currentFlyoutTopStyling += stickyHeaderHeight;
                                maximizedRelativeBlockHeightStyling -= stickyHeaderHeight;
                                $(stickyHeader).show();
                            }

                            $currentFlyout.css('top', currentFlyoutTopStyling + 'px');
                            $maximizedRelativeBlock.height(maximizedRelativeBlockHeightStyling);
                        }
                    });
            }
        }

        function handleFocusOnOpen() {
            arrEventHolder[0] = gJobs.focusService.restrictFocus(incompleteAppView, function () {
                layoutHelper.tabbing.updateIndices();
            });
            arrEventHolder[1] = gJobs.flyoutTabService.restrictTabbing(incompleteAppView);

            gJobs.focusService.enableFocusForBrowserControls();
        }

        function detachEventsAfterClosing() {
            $.each(arrEventHolder, function (key, value) {
                if (arrEventHolder[key]) {
                    arrEventHolder[key]();
                    arrEventHolder[key] = undefined;
                }
            });
        }

        function attachOnTabChangeEvent() {
            if (gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.GJobs) {
                $(document).on('shown', 'a[data-toggle="tab"]', function () {
                    OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();
                });
            }
        }

        // Function for updating flyout with new data.
        // tabIndex - opening tab.
        function updateFlyout(jobId, title, jobUrl, tabIndex, jobIsFeatured) {

            autosaveMessage.hide();

            if (switchJobsButtonsExist && settings && settings.checkJobPositionCallback) {
                jobPositionOnPage = settings.checkJobPositionCallback(jobId);
                setSwitchVisible();
            }

            activeJobId = jobId;
            jobDetailsUrl = removeApplyFromUrl(jobUrl);
            jobTitle = title;
            incompleteAppFlyout.setTitle(title);

            if (typeof tabIndex === 'number') {
                // Apply tab index in incomplete applications section.
                if (tabIndex === 1) {
                    handleDisplayOfApplicationProcessWithStickyHeader(true);
                }

                // This function is used to set active tab on the flyout before it is shown.
                activateTabByIndex(tabIndex);
            } else {
                activateDefaultTab(tabs);
            }

            incompleteAppFlyout.open();
            gJobs.screenReadersService.setNotification(openedNotification, jobTitle, 'is loading', true, true);

            $(document).one(Events.CommonEventsNames.FlyoutClosing, detachEventsAfterClosing);

            document.title = title + ' | Job Details tab | Government Jobs';

            load(jobId, tabIndex, jobIsFeatured || false);
        }

        function removeApplyFromUrl(url) {

            var index = url.indexOf('/apply');

            if (index > 0) {
                return url.substring(0, index);
            }

            return url;
        }

        function setSwitchVisible() {
            if (switchJobsButtonsExist) {
                if (!jobPositionOnPage.isLast) {
                    nextButton.removeClass('hide');
                } else {
                    nextButton.addClass('hide');
                }
                if (!jobPositionOnPage.isFirst) {
                    prevButton.removeClass('hide');
                } else {
                    prevButton.addClass('hide');
                }
            }
        }

        function setSwitchNotVisible() {
            if (switchJobsButtonsExist) {
                nextButton.addClass('hide');
                prevButton.addClass('hide');
            }
        }

        function activateDefaultTab(tabs) {

            tabs.each(function () {

                var tab = $(this);
                if (isTabActiveByDefault(tab)) {
                    tab.tab('show');
                }
            });
        }

        function activateTabByIndex(tabIndex) {
            var tabs = incompleteAppView.find('.flyout-header-tabs a');
            $(tabs[tabIndex]).tab('show');
        }

        function isTabActive(tab) {
            var tabContainer = tab.parent();
            return tabContainer.hasClass('active');
        }

        function isTabActiveByDefault(tab) {

            var isActiveTab = tab.data('active-by-default').toLowerCase();

            return isActiveTab === 'true';
        }

        function switchSwitchButtons(e) {
            var contentHref = $(e.target).attr('href');
            if (contentHref == '#info-view') {
                setSwitchVisible();
            } else {
                setSwitchNotVisible();
            }
        }

        function switchAdditionalContent(e) {

            var contentHref = $(e.target).attr('href');
            if (contentHref) {

                contentHref = contentHref.substr(1);

                var additionalContent = additionalContentContainer
                    .find('div[data-content-bind="' + contentHref + '"]');
                additionalContent.removeClass('hide');
            }

            var prevContentHref = $(e.relatedTarget).attr('href');
            if (prevContentHref) {

                prevContentHref = prevContentHref.substr(1);

                var prevAdditionalContent = additionalContentContainer
                    .find('div[data-content-bind="' + prevContentHref + '"]');
                prevAdditionalContent.addClass('hide');
            }
        }

        // Load all data.
        function load(jobId, tabIndex, jobIsFeatured) {
            applyButton.show();
            applyButton.parent().show();
            $externalApplyButtonContainer.hide();
            var jobInfo = {};
            loadJobInfo(jobId, jobIsFeatured || false, jobInfo);

            if (jobInfo.topUSAJobUrl) {
                applyButton.parent().hide();
                createTopUSAJobApplyLink(jobInfo.topUSAJobUrl);
            } else {
                loadApplication(jobId, tabIndex === 1);
            }
            $('#jobDetailsButton').attr('role', 'tab');
            $('#applyButton').attr('role', 'tab');
        }

        var defaultJobInfoContent = undefined;
        function loadJobInfo(jobId, jobIsFeatured, jobInfo) {

            if (!defaultJobInfoContent) {
                defaultJobInfoContent = $jobDetailsContainer.html();
            } else {
                $jobDetailsContainer.html(defaultJobInfoContent);
            }

            if (!$jobDetailsContainer.length) {
                return;
            }

            var $dummy = $('<div>');
            var url = jobInfoUrl + jobId + '?isFeatured=' + (jobIsFeatured || false) + '&isSubmittedApplicationPage=false';
            $.ajax({
                type: 'GET',
                url: url,
                async: false
            })
                .done(function (response) {
                    $dummy.html(response);

                    updateLinksWithIncreaseClickCountFunc($dummy.find('#details-info').find('a'));

                    $jobDetailsContainer.html($dummy.html());

                    var titleElement = $jobDetailsContainer.find('#pretty-job-title');
                    var jobSource = $dummy
                        .find('#jobDetailsTitle')
                        .data('jobsource');

                    if (titleElement && titleElement.length > 0)
                        incompleteAppFlyout.setTitle(titleElement.html());

                    var descriptionElement = $jobDetailsContainer.find('.entity-details-buttons');
                    var isDescriptionTabvisible = false;
                    if (descriptionElement && descriptionElement.length > 0) {
                        isDescriptionTabvisible = true;
                    }

                    if (isTabActive(applyButton)) {
                        OnlineApp.Services.authenticationService.isLoggedIn().done(function (isLoggedIn) {
                            var applyNotification = applyButton.attr('data-selected-notification');
                            if (!isLoggedIn) {
                                applyNotification += ' Signin form is opened';
                            }

                        });
                    } else {
                        gJobs.screenReadersService.clearNotificationsOnBlur(true, loadedNotification, openedNotification);

                        gJobs.screenReadersService.setNotification(
                            loadedNotification,
                            jobTitle,
                            'flyout is opened, job details tab has been activated' + (jobSource === 'TopUsa' || !isDescriptionTabvisible ? '' : ' and description tab is selected' + '  ' + getWarningText()),
                            true, false, true);


                    }
                    $("#jobDetailsButton").attr("role", "");
                    //initialize popovers over the salary and location flieds
                    gJobs.nonFlickeringPopover(incompleteAppView.find('[data-toggle="popover"]'), 'job-details-popover');

                    if (areShareButtonsInitialized !== true) {
                        var location = $jobDetailsContainer.find('.job-details-summary .job-location').text();
                        initShareButtons(jobDetailsUrl, jobTitle, location);
                        areShareButtonsInitialized = true;
                    }

                    var printingUrl = $dummy
                        .find('#jobDetailsTitle')
                        .data('printingurl');

                    if (jobSource === 'TopUsa') {
                        jobInfo.topUSAJobUrl = $dummy
                            .find('#jobDetailsTitle')
                            .data('url');
                    }

                    // compose url for printing
                    additionalContentContainer
                        .find('div[data-content-bind="info-view"]')
                        .find('a.print-button')
                        .attr('href', printingUrl);

                    if (isTabActiveByDefault(jobDetailsButton)) {
                        setSwitchVisible();
                    }

                    gJobs.accessibilityHtmlTransformer.makeElementContentAccessible($('.job-details-content'));

                    $dummy.remove();

                    increaseHitsCount(jobId);
                })
                .fail(function () {
                    $jobDetailsContainer.html('<h1>Job details cannot be retrieved.</h1>');
                });
        }
        function getWarningText() {
            if ($("#closingInfo") && $("#closingInfo").length > 0) {
                return $("#closingInfo").text();
            }
            return '';
        }

        function loadApplication(jobId, setActive) {
            if (applicationContainer[0] != undefined || tabsContainer[0] !== undefined) {
                var $dummy = $('<div>');
                if (applicationContainer[0] != undefined || (tabsContainer[0] !== undefined)) {
                    $dummy.load(appUrl + jobId, function (response, status, xhr) {
                        if (status != 'success') {
                            applyButton.parent().hide();
                            applyButton.hide();
                            applicationContainer.html('<h1>Cannot apply.</h1>');
                        } else {
                            if ($dummy.html()) {
                                if ($dummy.find('.job-details-grid').length || $dummy.find('.how-to-apply-container').length) {
                                    applyButton.parent().show();
                                    applyButton.show();
                                    applicationContainer.html($dummy.html());

                                    applyButton.off();

                                    if (isTabActive(applyButton)) {
                                        document.title = document.title.replace('Job Details tab', 'Apply tab');

                                        loadOnlineApp();
                                    } else {
                                        // Use '.on' instead of '.one' and manual disabling event
                                        // to support refreshing on JobDetails tab and closing flyout scenario.
                                        applyButton.on('show', loadOnlineApp);
                                        $(document).one(Events.CommonEventsNames.FlyoutClosing, function () {
                                            applyButton.off('show', loadOnlineApp);
                                        });
                                    }

                                    if (setActive) {
                                        applyButton.tab('show');
                                    }
                                } else {
                                    if ($externalApplyButtonContainer[0] === undefined) {
                                        $externalApplyButtonContainer = $('<li id="external-apply">');
                                        tabsContainer.append($externalApplyButtonContainer);
                                    }
                                    $externalApplyButtonContainer.show();
                                    $externalApplyButtonContainer.html($dummy.html());
                                }
                            } else {
                                jobDetailsButton.tab('show');
                                applyButton.parent().hide();
                                applyButton.hide();
                            }
                        }
                        $dummy.remove();
                    });
                } else {
                    applyButton.parent().hide();
                    applyButton.hide();
                }
            } else {
                applyButton.parent().hide();
                applyButton.hide();
            }
        }

        function createTopUSAJobApplyLink(topUSAJobUrl) {
            if (tabsContainer[0] !== undefined) {
                if ($externalApplyButtonContainer[0] === undefined) {
                    $externalApplyButtonContainer = $('<li id="external-apply">');
                    $externalApplyButtonContainer.append(
                        $('<a>').text('Apply')
                    );
                    $externalApplyButtonContainer.find('a').on('click', function () {
                        gJobs.common.analytics.trackEvent(
                            gJobs.common.analytics.categories.jobSearch,
                            "TopUsaJob Apply Clicks"
                        );
                    })
                    tabsContainer.append($externalApplyButtonContainer);
                }
                var $applyLinkElement = $externalApplyButtonContainer.find('a');
                $applyLinkElement.attr('href', topUSAJobUrl);
                $applyLinkElement.attr('target', '_blank');
                $applyLinkElement.attr('aria-label', 'Apply Link. Top USA job will open in a new tab.');

                $externalApplyButtonContainer.show();
            }
        }

        function loadOnlineApp() {
            applyButton.off('show', loadOnlineApp);
            setSwitchNotVisible();
            incompleteAppFlyout.maximize();
            gJobs.jobsDetails.loadOnlineApplication(function () {
                return incompleteAppFlyout.isActive();
            });
            addCommonNotification(FLYOUT_EXPANDED_TEXT);
        }


        function updateLinksWithIncreaseClickCountFunc(linksFromDescription) {
            for (var i = 0; i < linksFromDescription.length; i++) {
                linksFromDescription[i].setAttribute('onmousedown', 'increaseClickCount(false)')
            }
        }

        if (!String.prototype.format) {
            String.prototype.format = function () {
                var args = arguments;
                return this.replace(/{(\d+)}/g, function (match, number) {
                    return typeof args[number] != 'undefined'
                        ? args[number]
                        : match
                        ;
                });
            };
        }

        return {
            load: function (jobId, jobTitle, jobUrl, tabIndex, jobIsFeatured) {
                updateFlyout(jobId, jobTitle, jobUrl, tabIndex, jobIsFeatured);
                handleFocusOnOpen();
            },

            showJobDetails: function () {
                jobDetailsButton.tab('show');
            },

            showOnlineApp: function () {
                applyButton.tab('show');
            },

            getActiveJobId: function () {
                return activeJobId;
            },

            isActive: function () {
                return incompleteAppFlyout.isActive();
            },

            isApplyTabActive: function () {
                var result = isTabActive(applyButton);
                return result;
            }
        };
    }
})(window);
;
(function (window, undefined) {
    'use strict';

    var AUTOCOMPLETE_DELAY = 200,
        AUTOCOMPLETE_MINLENGTH = 1,
        ITEM_HEIGHT = 40;

    var keywordSearch = $('#keyword-search-input'),        
        locationSearch = $('#location-search-input');
    var headerKeywordSearch = $('#header-keyword-search-input'),
        headerLocationSearch = $('#header-location-search-input');

    var aria = gJobs.ariaAttributes;

    (function($) {
        $.fn.ellipsis = function(defaultOptions)
        {
            // todo: use smart logic for retrieving element's width & height
            // todo: sth. like http://jsfiddle.net/sbedulin/wXdJF/

            var maxCharacters = defaultOptions.maxCharacters || 30;

            return this.each(function()
            {
                var el = $(this);
                var text = el.html();
                var openTagIndex = 0; //current open tag start character index
                var closeTagIndex = 0; //current close tag start character index
                var currentTagsLength = 0; //current length of all tags, found in the string before
                var openTag = "<b>";
                var closeTag = "</b>";
                var textEnd = ""; //end of string which is added to cutted string

                //check if it's necessary to cut initial string and add ellipsis
                if (text.replace(openTag, '').replace(closeTag, '').length > maxCharacters) {

                    //search for tags and cut initial string
                    while (true) {
                        openTagIndex = text.indexOf(openTag, openTagIndex);
                        
                        //check if there are no other highlight tags in the string and add not bold dots
                        if (openTagIndex == -1) {
                            textEnd = "...";
                            break;
                        }
                        
                        //check if there are any other highlight tags in the string and add bold dots
                        //that condition also means that we're not cutting string between open and close highlight tags
                        if (openTagIndex > maxCharacters + currentTagsLength - 1) {
                            textEnd = openTag + "..." + closeTag;
                            break;
                        }
                        
                        //increment length of current tags by start tag length
                        currentTagsLength += openTag.length;
                        
                        closeTagIndex = text.indexOf(closeTag, closeTagIndex);
                        
                        if (closeTagIndex > maxCharacters + currentTagsLength) {
                            textEnd = "..." + closeTag;
                            break;
                        }
                        
                        //increment length of current tags by end tag length
                        currentTagsLength += closeTag.length;

                        //set current open and close tags start characters indexes for searching next tags
                        openTagIndex += openTag.length;
                        closeTagIndex += closeTag.length;
                    }

                    //building final string with highlighted tags
                    text = text.substring(0, maxCharacters + currentTagsLength) + textEnd;
                }
                el.html(text);
            });
        };

        // Add special tags to text for highlighting
        $.fn.highlightKeyword = function (substring) {
            return this.each(function () {
                substring = substring.toLowerCase();
                var el = $(this);
                var autocompleteText = el.text();
                var autocompleteTextLowCase = autocompleteText.toLowerCase();
                var newAutocompleteText = ""; //new text with highlight tags
                var substringLength = substring.length;
                var openTag = "<b>";
                var closeTag = "</b>";
                var index = 0; //substring start index from previous search 
                
                //search and replace substrings in autocomplete text with no case missing
                while (true) {
                    //current substring start index
                    var newIndex = autocompleteTextLowCase.indexOf(substring, index);

                    //check if there are no other substrings in text and copy end of initial text to new text
                    if (newIndex == -1) {
                        newAutocompleteText = newAutocompleteText.concat(autocompleteText.substring(index));
                        break;
                    }

                    //copy to new text part between previous substring end and current substring start from initial text
                    newAutocompleteText = newAutocompleteText.concat(autocompleteText.substring(index, newIndex));

                    //copy to new text substring with case from initial text and adding open and close tags to highlight
                    newAutocompleteText = newAutocompleteText.concat(
                        openTag,
                        autocompleteText.substring(newIndex, newIndex + substringLength),
                        closeTag);
                    
                    //update previous substring start index
                    index = newIndex + substringLength;
                }

                el.html(newAutocompleteText);
            });
        };
    })(jQuery);

    // Initialize autocomplete
    $(function () {
        if (!$.ui || !$.ui.autocomplete) {
            return;
        }

        $.widget('custom.catcomplete', $.ui.autocomplete, {
            options: {
                create: function () {
                    $(this).setAttributes([
                        [aria.expanded,'false'],
                        [ aria.role, 'combobox' ],
                        [ aria.autocomplete, 'list' ]
                    ]);
                }
            },
            _renderMenu: function (ul, items) {
                var that = this,
                    currentCategory = '',
                    allAutocompleteItemsHaveJobInterestCardCategory = true,
                    allAutocompleteItemsHaveClassSpecificationsTitleForFilterCategory = true;
                ul.addClass('popover bottom');

                this._on(this.menu.element, {
                    menufocus: function (event, ui) {
                        var item = ui.item.data("ui-autocomplete-item");

                        var activeElementId = ui.item.find('a').attr('id') + '_li';

                        this.element.setAttributes([
                            [ aria.activeDescendant, activeElementId ]
                        ]);

                        this.menu.activeMenu.find('li').setAttributes([
                            [ aria.selected, 'false']
                        ]);

                        ui.item.find('a').setAttributes([
                            [ aria.label, item.category + ' ' + item.label]
                        ]);

                        ui.item.setAttributes([
                            [ aria.selected, 'true' ]
                        ]);

                        if (!item.hiddenLabel) {
                            return;
                        }

                        // #7024 - Prevent accidental activation of menu items in Firefox
                        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;
                            }
                        }

                        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.element.attr("description")).text(item.hiddenLabel);
                            }
                        }
                    }
                });
                
                function isJobInterestCardCategory(category) {
                    return category === OnlineApp.AutocompleteFieldKinds.ClassSpecificationTitleForJobInterestCard ||
                        category === OnlineApp.AutocompleteFieldKinds.DepartmentTitleForJobInterestCard ||
                        category === OnlineApp.AutocompleteFieldKinds.LocationTitleForJobInterestCard;
                }

                function isClassSpecificationsTitleForFilterCategory(category) {
                    return category === OnlineApp.AutocompleteFieldKinds.ClassSpecificationsTitleForFilterCategory;
                }

                $.each(items, function (index, item) {
                    if (!isJobInterestCardCategory(item.category)) {
                        allAutocompleteItemsHaveJobInterestCardCategory = false;
                    }

                    if (!isClassSpecificationsTitleForFilterCategory(item.category)) {
                        allAutocompleteItemsHaveClassSpecificationsTitleForFilterCategory = false;
                    }

                    if (isJobInterestCardCategory(item.category)
                        || isClassSpecificationsTitleForFilterCategory(item.category)) {
                        item.category = '';
                    }

                    if (item.category != currentCategory) {
                        if (index != 0) {
                            ul.append('<li class="category-placeholder"></li>');
                        }
                        ul.append('<li class="ui-autocomplete-category">' + item.category + '</li>');
                        currentCategory = item.category;
                        
                    }

                    that._renderItemData(ul, item);
                });
                ul.append('<div class="arrow"></div>');
                ul.append('<div class="category-placeholder"></div>');

                if ((allAutocompleteItemsHaveJobInterestCardCategory && window.enableAdvancedJobInterestCards)
                    || allAutocompleteItemsHaveClassSpecificationsTitleForFilterCategory) {
                    var $currentAutocompleteMenuListItems = $('.ui-autocomplete li');

                    if ($currentAutocompleteMenuListItems && $currentAutocompleteMenuListItems.length) {
                        $currentAutocompleteMenuListItems.addClass('ui-menu-item-without-category');
                    }
                }
            },
            _suggest: function (items) {
                function resetHeight(element) {
                    element.css('height', 'auto');
                    element.css('overflow-y', 'auto');
                }
                keywordSearch.setAttributes([
                    [aria.expanded, 'true']
                ]);
                locationSearch.setAttributes([
                    [aria.expanded, 'true']
                ]);
                headerKeywordSearch.setAttributes([
                    [aria.expanded, 'true']
                ]);
                headerLocationSearch.setAttributes([
                    [aria.expanded, 'true']
                ]);
                function recalculateHeight(element) {
                    var lowerBound = element.height() + element.offset().top - $(document).scrollTop();
                    var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
                    if (viewportHeight < lowerBound) {
                        var elementHeight = element.height() - (lowerBound - viewportHeight) - 20;

                        if (elementHeight < ITEM_HEIGHT) {
                            elementHeight = ITEM_HEIGHT;
                        }

                        element.css('height', elementHeight);
                        element.css('overflow-y', 'scroll');
                    }
                }

                if ($('html').hasClass('device-phone')) {

                    var newScrollPosition = this.element.offset().top;

                    var $header = $('.floating-header, .navbar');

                    if (window.revampedDesign === true) {
                        $header = $('#header');
                    }

                    if ($header.length && $header.is(':visible')) {
                        newScrollPosition -= $header.height();
                    }

                    $('html, body').animate({ scrollTop: newScrollPosition }, 500);
                }

                function hideInputPopovers() {
                    keywordSearch.popover("hide");
                    locationSearch.popover("hide");
                    headerKeywordSearch.popover("hide");
                    headerLocationSearch.popover("hide");
                }

                var ul = this.menu.element.empty(),
                    overwriteTop,
                    marginTop = 15;

                resetHeight(ul);

                this._renderMenu(ul, items);
                this.menu.refresh();

                // size and position menu
                ul.show();
                this._resizeMenu();
                ul.position($.extend({
                    of: this.element
                }, this.options.position));

                // Overwrites bootstrap styles. Needs to do in JS because jQueryUI calculates dimension and position dynamically.
                overwriteTop = parseInt(ul.css('top')) + marginTop;
                ul.css('top', (overwriteTop + "px"));
                ul.css('max-width', this.element.outerWidth());

                recalculateHeight(ul);

                if (locationSearch.width() < 237) {
                    ul.css('width', (locationSearch.css('width')));
                    ul.addClass('small-autocomplete');
                }

                if (this.options.autoFocus) {
                    this.menu.next();
                }

                if (this.options.additionalCssClassNames) {
                    // attach some additional styles to autocomplete
                    ul.addClass(this.options.additionalCssClassNames);
                }

                // todo: add this.options.useEllipsis
                ul.find("a").highlightKeyword(this.term).ellipsis({
                    maxCharacters: (Math.floor(ul.css("width").replace("px", "")) / 8)
                });

                ul.setAttributes([
                    [ aria.role, 'listbox' ],
                    [ aria.tabindex, '-1' ]
                ]);
                $('#job-alert-keyword-search-input').setAttributes([
                    [aria.expanded, 'true']
                ]);
                $('#job-alert-location-search-input').setAttributes([
                    [aria.expanded, 'true']
                ]);
                $('#keyword-search-input').setAttributes([
                    [aria.expanded, 'true']
                ]);
                $('#location-search-input').setAttributes([
                    [aria.expanded, 'true']
                ]);
                $('#header-keyword-search-input').setAttributes([
                    [aria.expanded, 'true']
                ]);
                $('#header-location-search-input').setAttributes([
                    [aria.expanded, 'true']
                ]);

                
                const liElements = ul.find('li');
                const liArray = Array.from(liElements);

                // Iterate over each <li> element
                liArray.forEach(li => {
                    // Check if the <li> does not have the class 'ui-autocomplete-category'
                    if (!li.classList.contains('ui-autocomplete-category')) {
                        // Set the ARIA attributes
                        li.setAttribute('role', 'option');
                        li.setAttribute('tabindex', '-1');
                        li.setAttribute('aria-selected', 'false');
                    }
                    else {
                        li.classList.remove('ui-menu-item');
                    }
                });

                ul.find('li').each(function () {
                    var $this = $(this);
                    $this.attr('id', $this.find('a').attr('id') + '_li');
                });

                this.element.setAttributes([
                    [ aria.controls, ul.attr('id') ]
                ]);

                hideInputPopovers();
            },
            _normalize: function (items) {
                var that = this;
                // 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({
                        label: (item.label || item.value),
                        //Adding space to suggested value that matches search term to tell Jaws` virtual focus that focus is still in dropdown (ONLINE-2976)
                        value: (item.value || item.label) + (that.term === (item.value || item.label) ? " " : "")
                    }, item);
                });
            },

            close: function () {                
                $('#keyword-search-input').setAttributes([
                    [aria.expanded, 'false']
                ]);
                $('#location-search-input').setAttributes([
                    [aria.expanded, 'false']
                ]);
                $('#header-keyword-search-input').setAttributes([
                    [aria.expanded, 'false']
                ]);
                $('#header-location-search-input').setAttributes([
                    [aria.expanded, 'false']
                ]);
                $('#job-alert-keyword-search-input').setAttributes([
                    [aria.expanded, 'false']
                ]);
                $('#job-alert-location-search-input').setAttributes([
                    [aria.expanded, 'false']
                ]);
                this._super();
            }
        });

        // sidebar exists => autocompletes are inside
        var isSidebarAutocomplete = $("#sidebar-container").length > 0 ? true : false;

        function initSearchFieldWithAutocomplete($searchField, options) {
            var additionalCssClassNames = undefined;
            var responseCallback = options ? options.responseCallback : undefined;

            if (isSidebarAutocomplete) {
                additionalCssClassNames = "sidebar-autocomplete";
            } else if (options && options.additionalCssClassNames) {
                additionalCssClassNames = options.additionalCssClassNames;
            }

            if ($searchField && $searchField.length && $searchField.length > 0) {
                $searchField.catcomplete({
                    minLength: AUTOCOMPLETE_MINLENGTH,
                    delay: AUTOCOMPLETE_DELAY,
                    source: $searchField.data('action'),
                    additionalCssClassNames: additionalCssClassNames,
                    response: responseCallback
                });
            }
        }

        initSearchFieldWithAutocomplete(keywordSearch);

        initSearchFieldWithAutocomplete(locationSearch);
        initSearchFieldWithAutocomplete(headerKeywordSearch);

        initSearchFieldWithAutocomplete(headerLocationSearch);

        $(document).on(OnlineApp.Events.CommonEventsNames.InitSearchFieldsWithAutocomplete, function(event, options) {
            if (options && options.searchFieldSelectors) {
                options.searchFieldSelectors.forEach(function(searchFieldSelector) {
                    var $searchField = $(searchFieldSelector);

                    initSearchFieldWithAutocomplete($searchField, options);
                });
            }
        });
    });
})(window);;
(function (window, undefined) {
    'use strict';

    $(function () {

        // Enable placeholder for search bar location input for IE8/9
        if (!("placeholder" in document.createElement("input"))) {
            $('input[placeholder]').each(function () {

                var input = $(this);

                if (input.val() == "") {
                    input.addClass('placeholder');
                    $(input).val(input.attr('placeholder'));
                }

                $(input).focus(function () {
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                        input.removeClass('placeholder');
                    }
                });

                $(input).blur(function () {
                    if (input.val() == '' || input.val() == input.attr('placeholder')) {
                        input.val(input.attr('placeholder'));
                        input.addClass('placeholder');
                    }
                });
            });
            // Clear placeholder values upon submit
            $("#main-search-criteria form").submit(function () {
                $('input[placeholder]').each(function () {
                    var input = $(this);

                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });
            });
        }

        // Due to Bootstrap overwriting inline img tags (breaks customers html), need to append width/height to imgs to show correct sizes
        $("#info img").each(function (index) {
            if ($(this).attr("width") != null) {
                $(this).css("width", $(this).attr("width") + "px");
            }
            if ($(this).attr("height") != null) {
                $(this).css("height", $(this).attr("height") + "px");
            }
        });
    });



    // Messaging

    $(document).on(Events.CommonEventsNames.ShowMessage, function (_, messageCode) {
        var messageCodeToMessageMap = {
            'nonauthorized': 'Your session has expired. Please sign in again'
        };

        var message = messageCodeToMessageMap[messageCode];

        toastr.warning(message);
    });

    $(document).ready(function () {
        var action = localStorage.getItem('action'),
            reason = localStorage.getItem('reason');

        if (action !== undefined && action === 'redirect' && reason !== undefined) {
            window.onpageshow = function () {
                localStorage.removeItem('action');
                localStorage.removeItem('reason');
            }

            $(document).trigger(Events.CommonEventsNames.ShowMessage, reason);
        }

        if (sessionStorage.getItem(OnlineApp.SessionKeys.IsVerifyIdentityVerificationCodeVerified) === "true") {
            gJobs.screenReadersService.setAriaLiveNotification("Code is verified");
            sessionStorage.removeItem(OnlineApp.SessionKeys.IsVerifyIdentityVerificationCodeVerified);
        }
    });

    var updateFooterPosition = function () {
        var $window = $(window);
        var $content = $('#main-content-container, .page-container');

        if (window.revampedDesign) {
            var $header = $('#header');
            var $footer = $('#footer-new');
        }
        else {
            var $header = $('#header > .navbar');
            var $footer = $('#footer');
        }
        if (window.location.href.indexOf("schooljobs") != -1) {
            var $footer = $('#sjobs-footer-new');
        }

        var expectedContentHeight = $window.height() - $footer.outerHeight() - $header.outerHeight();

        if (window.enableStickyHeader) {
            var $stickyHeader = $('#sticky-header');
            if ($stickyHeader.length) {
                expectedContentHeight += $stickyHeader.outerHeight();
            }
        }

        var actualContentHeight = $content.outerHeight();

        if (actualContentHeight > expectedContentHeight) {
            expectedContentHeight = actualContentHeight;
        }

        $('#content').css('min-height', expectedContentHeight);
    };

    $(window).resize(function () {
        updateFooterPosition();
    });

    $(document).ready(function () {
        updateFooterPosition();
    });

    $(document).on('layoutUpdated', function () {
        //need a 1ms delay of computation for IE8 support
        setTimeout(updateFooterPosition, 1);
    });

    $(function() {
         $('#screen-reader-message').focus();
    });

    $(document).keydown(function(e) {
        if (e.keyCode === $.ui.keyCode.ESCAPE) {
            if ($(e.target).hasClass('inbox-header-id')) {
                $(e.target).popover('hide');
            }

            if ($(e.target).hasClass('flag-left')
                && $(e.target).siblings('.bs-tooltip-right').length) {
                $(e.target).siblings('.bs-tooltip-right').hide();
            }
        }
    });

})(window);

// Define global share buttons settings
var injectAddthisConfig = function (googleAnalyticsId) {
    window.addthis_config = {
        ui_508_compliant: true,
        data_track_clickback: false,
        data_ga_property: googleAnalyticsId
    };
};

const clearFacebookStorage = () => {
    Object.keys(sessionStorage)
        .filter(key => key.startsWith('fbssls_'))
        .forEach(key => sessionStorage.removeItem(key));
};

var addthis_share =
{
    url_transforms: {
        shorten: {
            twitter: 'bitly'
        }
    },
    templates: {
        twitter: '{{title}} {{url}} ' + window.Resources.SocialLinks.twitterLink
    }
};;
(function (window, undefined) {
    'use strict';

    var releaseFocusFn;

    namespace('gJobs').common = {
        social: (function () {
            return {
                init: function ($element, title, url, location) {
                    var socialLinkTitle = location + ' ' + title;

                    if (window.addthis) {
                        if ($element) {
                            if (!window.enableShareThis) {
                                $element
                                    .attr('addthis:title', socialLinkTitle)
                                    .attr('addthis:url', url);
                            }
                        }

                        if (!window.enableShareThis) window.addthis.toolbox('.addthis_toolbox');
                    }

                    if (window.enableShareThis) {
                        if ($element) {
                            var $shareThisButtons = $element.find('.st-custom-button');

                            $shareThisButtons.attr('data-title', socialLinkTitle); 

                            $shareThisButtons.attr('data-url', url); 

                            var $shareThislinkedinButton = $element.find('.st-custom-button.linkedin-share-button');
                            $shareThislinkedinButton.attr('data-url', encodeURI(url + "?1"));

                            var $shareThisEmailButton = $element.find('.st-custom-button.email-share-button');

                            $shareThisEmailButton.attr('data-email-subject', socialLinkTitle);
                        }

                        if (window.__sharethis__) window.__sharethis__.initialize();
                    }
                }
            };
        })()
    };

    if (window.addthis && window.addthis.addEventListener) {
        window.addthis.addEventListener('addthis.menu.open', onAddThisModalOpen);
        window.addthis.addEventListener('addthis.menu.close', onAddThisModalClose);
    }

    function onAddThisModalOpen() {
        gJobs.focusService.restrictFocus($('#at3win'));
    }

    function onAddThisModalClose() {
        if (typeof releaseFocusFn === 'function') {
            releaseFocusFn();
        }
    }

    $(document).keydown(function (e) {
        if (e.keyCode === $.ui.keyCode.ESCAPE) {
            if ($(e.target).hasClass('st-custom-button')) {
                $(e.target).popover('hide');
            }
        }
    });

})(window);;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').signInTemplatesService = {
        getTemplates: function () {
            var signInTemplatesPath = window.signInTemplatesPath;

            return $.ajax({
                url: signInTemplatesPath,
                type: 'GET',
                cache: true
            }).done(function (data) {
                $('head').append(data);
            }).then();
        }
    };

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

    function VerifyIdentityService() {
        var self = this;
                 
        var verifyCodeUrl = '/api/twoFactorAuthentication/verify',
            resendVerificationCodeUrl = '/api/twoFactorAuthentication/resendEmail',
            getUserDataUrl = '/api/twoFactorAuthentication/getUserData';

        function getAgencyFolderName() {
            var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();
            var currentArea = gJobs.areaInfoService.getCurrentArea();

            var agencyFolderName = "";

            if (currentArea !== abstractAreaInfoService.areaNames.GJobs) {
                agencyFolderName = AgencyPages.pageInfoService ?
                    AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                    gJobs.pageInfoService.getCurrentAgencyPageFolderName();
            }

            return agencyFolderName;
        }

        self.verifyCode = function (
            verificationCode,
            rememberDevice,
            captchaAnswer,
            credential
        ) {
            return $.ajax({
                type: 'POST',
                url: verifyCodeUrl,
                data: {
                    alphanumericVerificationCode: verificationCode,
                    rememberDevice: rememberDevice,
                    captchaAnswer: captchaAnswer,
                    credential: credential
                }
            });
        };

        self.resendVerificationCode = function (credential, captchaAnswer) {
            var agencyFolderName = getAgencyFolderName();

            return $.ajax({
                type: 'POST',
                url: resendVerificationCodeUrl,
                data: {
                    captchaAnswer: captchaAnswer,
                    credential: credential
                }
            });
        };

        self.getUserData = function (credential) {
            return $.ajax({
                type: 'GET',
                url: getUserDataUrl + "?credential=" + credential
            });
        };
    }

    OnlineApp.Namespace.extend('gJobs.Services', {
        verifyIdentityService: new VerifyIdentityService()
    });

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

    function VerifyAccountService() {
        var self = this;

        var resendVerificationLinkUrl = '/api/emailVerification/resendVerificationLink';

        function getAgencyFolderName() {
            var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();
            var currentArea = gJobs.areaInfoService.getCurrentArea();

            var agencyFolderName = "";

            if (currentArea !== abstractAreaInfoService.areaNames.GJobs) {
                agencyFolderName = AgencyPages.pageInfoService
                    ? AgencyPages.pageInfoService.getCurrentAgencyFolderName()
                    : gJobs.pageInfoService.getCurrentAgencyPageFolderName();
            }

            return agencyFolderName;
        }

        self.resendVerificationLink = function(credential, captchaAnswer, changedEmailAddressWasAdded, isOjrMaster) {
            return $.ajax({
                type: 'POST',
                url: resendVerificationLinkUrl,
                data: {
                    captchaAnswer: captchaAnswer,
                    credential: credential,
                    changedEmailAddressWasAdded: changedEmailAddressWasAdded,
                    isOjrMaster: isOjrMaster
                }
                                
            });
        };
    }

    OnlineApp.Namespace.extend('gJobs.Services', {
        verifyAccountService: new VerifyAccountService()
    });

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

    var MSEC_TO_HIDE_MESSAGE = 5000;

    var $signInBlock = $('#sign-in-block'),
        $signInLink = $('.sign-in-link'),
        $signOutLink = $('.sign-out'),
        $standaloneSignInBlock = $('#standalone-sign-in-block'),
        $togglers = $signInBlock.find('.togglers a'),
        $usernameContainerMobile = $('.user-name-container-mobile'),
        $usernameBlock = $('.username'),
        $userSigninFormContainer = $('.user-signin-form-container'),
        $userNameContainer = $('.user-name-container'),
        $messageContainer = $('.notification'),
        loginRegisterEvents = Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;

    namespace('gJobs').signInForm = {

        init: function () {
            var self = this;

            OnlineApp.Services.authenticationService.isLoggedIn().done(function (data) {
                if (data) {
                    $signInLink.addClass('hidden');
                    self.updateUsername();
                } else {
                    $userSigninFormContainer.removeClass('hidden');
                }
            });
        },

        toggleLogInAndRegister: function (e) {
            var self = this;

            $togglers.toggleClass('hide');

            $(document).trigger("toggleLogInAndRegister", e);

            self.focusFirstTabbableElement();            
        },

        isOpen: function () {
            return $signInBlock.is(':visible') || !$signInBlock.is(':hidden');
        },

        updateUsername: function () {
            OnlineApp.Services.authenticationService.getUserData().done(function (data) {
                $usernameBlock.text(data.username);
                $usernameContainerMobile.attr('data-content', data.username);
                $userNameContainer.removeClass('hidden');

                if (data.isVettedLinkVisible) {                    
                    $("#onlineMenuWithoutVettedLink").remove();
                }
                else {
                    $("#onlineMenuWithVettedLink").remove();
                }
            });
        },

        focusFirstTabbableElement: function () {
            $signInBlock.find(':tabbable').first().focus();
        }
    };

    //
    // Initializer
    //
    $(function () {

        gJobs.signInTemplatesService.getTemplates().done(function () {
            if ($userSigninFormContainer.get(0)) {
                ko.applyBindings(OnlineApp.ViewModels.applicationViewModel, $userSigninFormContainer.get(0));
            }

            if ($standaloneSignInBlock.get(0)) {
                ko.applyBindings(OnlineApp.ViewModels.applicationViewModel, $standaloneSignInBlock.get(0));
            }
        });

        //init login and register vm's text
        OnlineApp.ViewModels.applicationViewModel.loginViewModel.signInViewModel.signInFormHeadingText('Sign In');
        OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.createAccountFormHeadingText('Create Account');

        gJobs.signInForm.init();

        $togglers.on('click', function (e) {
            gJobs.signInForm.toggleLogInAndRegister(e);
        });

        $messageContainer.removeClass('hide');

        function updateHeader(screenReaderNotificationText) {

            $userSigninFormContainer.addClass('hidden'),

                $signInLink.addClass('hidden');

            gJobs.screenReadersService.setLogInNotification(screenReaderNotificationText);
        }

        function loginEventHandler() {
            gJobs.signInForm.updateUsername();

            updateHeader(Resources.NotificationMessages.LoginSuccess);
        }

        function registerEventHandler() {
            gJobs.signInForm.updateUsername();

            $messageContainer.fadeIn();

            setTimeout(function () {
                $messageContainer.fadeOut();
            }, MSEC_TO_HIDE_MESSAGE);

            updateHeader(Resources.NotificationMessages.RegistrationSuccess);

            gJobs.signInForm.toggleLogInAndRegister();
        }

        function navigateByLogoutUrl() {
            var shouldNavigateToHomePage = AgencyPages && AgencyPages.pageInfoService && AgencyPages.pageInfoService.getCurrentPageType()!=undefined && 
                AgencyPages.pageInfoService.getCurrentAgencyHomePageUrl &&
                (AgencyPages.pageInfoService.getCurrentPageType().type ==
                    AgencyPages.pageInfoService.getPageTypes().accountSettings.type ||
                    AgencyPages.pageInfoService.getCurrentPageType().type ==
                    AgencyPages.pageInfoService.getPageTypes().profileSettings.type ||
                    AgencyPages.pageInfoService.getCurrentPageType().type ==
                    AgencyPages.pageInfoService.getPageTypes().applications.type ||
                    AgencyPages.pageInfoService.getCurrentPageType().type ==
                    AgencyPages.pageInfoService.getPageTypes().inbox.type);

            if (shouldNavigateToHomePage) {
                window.location.href = AgencyPages.pageInfoService.getCurrentAgencyHomePageUrl();
            } else {
                location.reload();
            }
        }

        $signOutLink.on('click', function () {
            OnlineApp.Services.authenticationService.logout().done(function () {
                // Clear sessionStorage for jobIds and paginationData if present
                sessionStorage.removeItem('jobIds');
                sessionStorage.removeItem('paginationData');
                sessionStorage.removeItem('searchQuery');
                navigateByLogoutUrl();
            });
        });

        $usernameContainerMobile.on('click', function (e) {
            e.preventDefault();

            $usernameContainerMobile.popover('toggle');
        });

        $(document).on(Events.CommonEventsNames.Login, function () {
            loginEventHandler();
        });

        $(document).on(Events.CommonEventsNames.Register, function () {
            registerEventHandler();
        });

        $(document).on(loginRegisterEvents, function () {
            $('.sign-in-block-container').hide();
        });

        $(document).on(OnlineApp.Events.CommonEventsNames.RegisterAccountFormOpened, function () {
            $("#aria-live-message-container").text('');
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Create account form is opened.', $("#aria-live-message-container"), false); }, 500);
        });

        $(document).on(OnlineApp.Events.CommonEventsNames.LoginFormOpened, function () {
            $("#aria-live-message-container").text('');
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Sign in form is opened.', $("#aria-live-message-container"), false); }, 500);
        });        
    });

    $(window).focus(function () {
        if (localStorage.getItem('updatedEmail')) {
            gJobs.signInForm.updateUsername()
        }
    });

})(window);

;
(function (window, undefined) {
    'use strict';

    $(document).on(OnlineApp.Events.CommonEventsNames.ResumeImportComplete, function (e) {
        var method = '',
            eventAction = '',
            eventLabel = '';

        switch (e.source) {
            case 'fileUpload':
                method = 'Resume Import';
                eventAction = 'submit';
                eventLabel = 'resume';
                break;

            case 'skipSection':
                method = 'Profile Created without Import';
                eventAction = 'skip';
                eventLabel = 'manual input';
                break;
        }

        gJobs.common.analytics.trackProfileCreationEvent(method, e.application);
        gJobs.common.analytics.trackApplicationEvent({
            action: eventAction,
            eventLabel: eventLabel,
            name: 'customEmployerTracker'
        });
    });

    $(document).on(OnlineApp.Events.CommonEventsNames.ResourcesLinkClicked, function (e, data) {
        var eventCategory = "Resources " + data.linkType + " link";

        gJobs.common.analytics.trackEvent(eventCategory, 'click');
    });

    namespace('gJobs').common.analytics = (function () {

        var self = {};        

        var categories = {
            application: 'Application',
            profileCreation: 'Profile Creation',
            login: 'Login',
            jobSearch: 'Job Search',
            appSubmission: 'Application Submission',
            homePage: 'Home Page',
            careerJobSearch: 'Career Job Search'
        }

        var prefixes = {
            virtualPagePrefix: '/vr/',
            virtualDimensionPrefix: 'neogov|'
        }

        function _injectGoogleAnalyticsScript(options) {
            window.GoogleAnalyticsObject = 'ga';
            if (self.isGA4Enabled) {
                var configOptions = {
                    send_page_view: false//prevent page_view as part of initial config
                }
                if (options.cookieName)
                    configOptions.cookie_prefix = options.cookieName;
                gtag('config', options.trackingId,configOptions);
            }
            else
                ga('create', options);
        }


        function _injectPageChangeTrackingCode(options, context) {
            History.Adapter.bind(window, 'statechange', function () {
                context.trackCurrentPageView(options);
            });
        }

        function _applyTracker(trackerName) {
            return trackerName ? trackerName + '.' : '';
        }

        function _suppressTrack(options, context) {
            var router = namespace('AgencyPages').router;

            if (router) {
                var isExcludedRoute = false;

                if (options.excludedRouteNames) {
                    for (var i = 0; i < options.excludedRouteNames.length; i++) {
                        if (router.isCurrentUrlMatchedToRoute(options.excludedRouteNames[i])) {
                            isExcludedRoute = true;
                            break;
                        }
                    }
                }
                if (self.isGA4Enabled)
                    return (context.ga4Trackers.map(t => t.name).indexOf(options.name) === 1) && isExcludedRoute;
                else
                    return (context.trackers.indexOf(options.name) === 1) && isExcludedRoute;
            }

            return false;
        }

        function _getCurrentArea() {
            return gJobs && gJobs.areaInfoService ? gJobs.areaInfoService.getCurrentArea() : '';
        }

        self.sendToAllTrackers = function (eventHandlerName, options) {
            delete options.sendToAllTrackers;
            if (self.isGA4Enabled)
                self.ga4Trackers.forEach(function (element) {
                    options.trackingId = element.trackingId;
                    options.name = element.name
                    self[eventHandlerName](options);
                });
            else
                self.trackers.forEach(function (element) {
                    options.name = element;
                    self[eventHandlerName](options);
                });
        }

        self.inject = function (options) {
            options = $.extend({}, options);
            options.sendPageViewEvent = (typeof options.sendPageViewEvent !== 'undefined') ?
                options.sendPageViewEvent :
                true;

            if (location.hostname === 'localhost') {
                options.cookieDomain = 'none';
            }

            if (self.isGA4Enabled) {
                if (options.trackingId)
                    self.ga4Trackers.push(options);
            }
            else {
                if (options.name) {
                    self.trackers.push(options.name);
                } else {
                    self.trackers.push(null);
                }
            }

            if (options.sampleRate) {
                options.sampleRate = Number(options.sampleRate);
            }

            _injectGoogleAnalyticsScript(options);

            if (options.properties) {
                self.setProperties({
                    properties: options.properties,
                    trackerName: options.name,
                    name: options.name,
                    trackingId: options.trackingId
                });
            }

            _injectPageChangeTrackingCode(options, self);

            if (options.sendPageViewEvent) {
                self.trackCurrentPageView(options);
            }
        }

        self.setProperties = function (options) {
            if (options.sendToAllTrackers) {
                self.sendToAllTrackers('setProperties', options);
                return;
            }

            if (self.isGA4Enabled) {
                if (!options.trackingId) {
                    if (options.name)
                        options.trackingId = self.findTrackingId(options.name);
                }
                var trackerPropertiesExist = self.trackerProperties.map(o => o.trackingId);
                if (trackerPropertiesExist && trackerPropertiesExist.indexOf(options.trackingId) == -1) {//insert tracker properties
                    var trackerProperty = { name: options.name, trackingId: options.trackingId };
                    if (options.properties)
                        trackerProperty.properties = Object.assign({}, options.properties);
                    self.trackerProperties.push(trackerProperty);
                }
                else if (options.properties) {//update tracker properties
                    var properties = findpropertiesForCurrentTracking(options.trackingId);
                    if (properties) {
                        for (const [key, value] of Object.entries(options.properties)) {
                            if (Object.keys(properties).indexOf(key) == -1)
                                properties[key] = value;
                            else if (properties[key] != options.properties[key])
                                properties[key] = options.properties[key];
                        }
                    }
                }
            }
            else {
                var trackerName = _applyTracker(options.name);
                ga(trackerName + 'set', options.properties);
            }
        }

        self.trackPageView = function (url, trackerName, trackingId) {
            if (self.isGA4Enabled) {
                if (!trackingId) {
                    if (trackerName)
                        trackingId = self.findTrackingId(trackerName);
                }
                var eventData = {
                    send_to: trackingId, page_location: url
                }
                var properties = findpropertiesForCurrentTracking(trackingId);
                if (properties)
                    $.extend(eventData, properties);
                gtag('event', 'page_view', eventData);
            }
            else {
                trackerName = _applyTracker(trackerName);
                ga(trackerName + 'send', 'pageview', {
                    'page': url
                });
            }
        }

        self.trackCurrentPageView = function (options) {
            if (_suppressTrack(options, self) && !options.ignoreExcludedRoutes) {
                return;
            }
            if(self.isGA4Enabled)
                self.trackPageView(window.location.href, options.name, options.trackingId);
            else
                self.trackPageView(window.location.href, options.name);
        }

        self.trackVirtualPageView = function (options) {

            if (options.sendToAllTrackers) {
                self.sendToAllTrackers('trackVirtualPageView', options);
                return;
            }
            if (self.isGA4Enabled) {
                if (!options.trackingId) {
                    if (options.name)
                        options.trackingId = self.findTrackingId(options.name);
                }
                options.properties = { dimension4: prefixes.virtualDimensionPrefix + options.page };
                self.setProperties(options);
                var eventData = {
                    send_to: options.trackingId,
                    page_location: prefixes.virtualPagePrefix + options.page,
                    page_title: options.title
                };
                var properties = findpropertiesForCurrentTracking(options.trackingId);
                if (properties)
                    $.extend(eventData, properties);                
                gtag('event', 'page_view', eventData);
            }
            else {
                var trackerName = _applyTracker(options.name);
                self.setProperties({
                    properties: { dimension4: prefixes.virtualDimensionPrefix + options.page },
                    name: options.name
                });
                ga(trackerName + 'send', 'pageview', {
                    page: prefixes.virtualPagePrefix + options.page,
                    title: options.title
                });
            }
        }

        function findpropertiesForCurrentTracking(trackingId) {
            var options = self.trackerProperties.find(opt => opt.trackingId === trackingId);
            return options && options.properties;
        }

        self.trackEvent = function (category, action, eventLabel, trackerName, data) {
            if (self.isGA4Enabled) {
                var trackingId;
                if (!trackerName)
                    trackingId = self.ga4Trackers[0].trackingId;//Neogov tracker to get first registered, if no tracker present
                else
                    trackingId = self.findTrackingId(trackerName);
                var eventData = {
                    'send_to': trackingId,
                    'event_category': category,
                    'event_label': eventLabel
                };
                var properties = findpropertiesForCurrentTracking(trackingId);
                if (properties)
                    $.extend(eventData, properties);
                if (data)
                    $.extend(eventData, data);
                gtag('event', action, eventData);
            }
            else {
                trackerName = _applyTracker(trackerName);

                ga(trackerName + 'send', 'event', category, action, eventLabel, data);
            }
        }

        self.findTrackingId = function (trackerName) {
            var ga4Tracker = self.ga4Trackers.find(t => t.name == trackerName);
            return ga4Tracker && ga4Tracker.trackingId;
        }

        self.trackTiming = function (category, variable, value, trackerName) {
            if (self.isGA4Enabled)//ONLINE-12843 - Timing not available in GA4, captured as custom event
            {
                self.trackEvent(
                    category,
                    'user_timings',
                    variable,
                    trackerName,
                    { user_timing: value / 1000 } //To display value in seconds in  user_timing custom dimension
                );
            }
            else {
                trackerName = _applyTracker(trackerName);

                ga(trackerName + 'send', 'timing', category, variable, value);
            }
        }

        self.trackApplicationEvent = function (options) {
            if (options.sendToAllTrackers) {
                self.sendToAllTrackers('trackApplicationEvent', options);
                return;
            }

            if (!options.eventLabel) {
                options.eventLabel = _getCurrentArea();
            }

            self.trackEvent(
                self.categories.application,
                options.action,
                options.eventLabel,
                options.name,
                options.data
            );
        }

        self.trackJobSearchEvent = function (action, eventLabel, trackerName) {
            if (!eventLabel) {
                eventLabel = _getCurrentArea();
            }
            self.trackEvent(self.categories.jobSearch, action, eventLabel, trackerName);
        }

        self.trackCareerJobSearchEvent = function (action, eventLabel, trackerName) {
            if (!eventLabel) {
                eventLabel = _getCurrentArea();
            }   
            self.trackEvent(self.categories.careerJobSearch, action, eventLabel, trackerName);
        }

        self.trackLoginEvent = function (action, eventLabel, trackerName) {
            if (!eventLabel) {
                eventLabel = _getCurrentArea();
            }
            self.trackEvent(self.categories.login, action, eventLabel, trackerName);
        }

        self.trackProfileCreationEvent = function (action, eventLabel, trackerName) {
            eventLabel += " " + _getCurrentArea();
            self.trackEvent(gJobs.common.analytics.categories.profileCreation, action, eventLabel, trackerName);
        }

        self.setUserIdentity = function (identity) {
            throw new Error('self action is not supported');
        }

        self.registerUserIdentity = function (identity) {
            throw new Error('This action is not supported');
        }
        self.removeProperty = function (trackerName, propertyName) {
            var trackingId = self.findTrackingId(trackerName);
            if (trackingId) {
                var properties = findpropertiesForCurrentTracking(trackingId);
                if (properties[propertyName])
                    delete properties[propertyName];
            }
        }

        self.messages = {
            captchaMessage: 'Captcha Modal Shown'
        }

        self.trackers = [];
        self.ga4Trackers = [];
        self.categories = categories
        self.trackerProperties = [];        

        return self;
    })();

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


    var currentDeviceClass;


    var toggleDeviceClass = function (deviceClass, deviceOrientation, state) {
        if (state) {
            currentDeviceClass = deviceClass;
        }

        $('html')
            .toggleClass('device-' + deviceClass, state)
            .toggleClass('device-orientation-' + deviceOrientation, state);
    };

    var getCurrentDeviceClasses = function () {
        var classes = $('html').attr('class');
        var classNames = classes.split(/\s+/);

        var deviceClasses = $.map(classNames, function (className) {
            var matches = className.match(/device-(\w[\w-]*)/) || [];
            var deviceClass = matches[1];

            return deviceClass;
        });

        return deviceClasses;
    };

    var resetDeviceClasses = function () {
        var deviceClasses = getCurrentDeviceClasses();

        $.each(deviceClasses, function () {
            toggleDeviceClass(this, null, false);
        });
    };



    /*
        Initialization
    */
    (function () {
        resetDeviceClasses();
    }());


    
    /*
        Large Desktop
    */
    enquire.register('screen and (min-width: 1500px)', {

        match: function () {
            toggleDeviceClass('large-desktop', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('large-desktop', 'portrait', false);
        }

    });


    /*
        Desktop
            Matches all medium-sized desktop screens (Laptops).
    */
    enquire.register('screen and (min-width: 1200px) and (max-width: 1499px)', {

        match: function () {
            toggleDeviceClass('desktop', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('desktop', 'portrait', false);
        }

    });


    /*
        Small Desktop
            Matches small desktop screens.
    */
    enquire.register('screen and (min-width: 980px) and (max-width: 1199px)', {

        match: function () {
            toggleDeviceClass('small-desktop', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('small-desktop', 'portrait', false);
        }

    });


    /*
        Tablets
    */
    enquire.register('screen and (min-width: 768px) and (max-width: 979px)', {

        match: function () {
            toggleDeviceClass('tablet', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('tablet', 'portrait', false);
        }

    });


    /*
        Phone
    */
    enquire.register('screen and (max-width: 767px)', {

        match: function () {
            toggleDeviceClass('phone', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('phone', 'portrait', false);
        }
    });
    
    /*
        Small Phone
    */
    enquire.register('screen and (max-width: 480px)', {

        match: function () {
            toggleDeviceClass('small-phone', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('small-phone', 'portrait', false);
        }
    });


    namespace('gJobs').common.responsive = {
        is: function (deviceClass) {
            return (deviceClass === currentDeviceClass);
        }
    };


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

    function FocusService() {
        var self = this;

        var NO_RESTRICT_CLASS = 'no-restrict-focus',
            LAST_FOCUSABLE_ELEMENT_ID = 'last-focusable-element',
            TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT = 'keydown.tabFocusNavigation',
            SHIFT_TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT = 'keydown.shiftTabFocusNavigation';


        var $previousElement = [];
        var restrictFocusStack = [];

        var currentFocusedElement = $();

        self.LAST_TABBABLE_ELEMENT_CLASS = 'last-tabble-element';

        self.setFocus = function ($focusTarget) {
            $previousElement.push($(document.activeElement));
            $focusTarget.focus();
        };

        self.setFocusOnEmptyElement = function (element, onRemove) {
            var $emptyFocusableSpan = $('<span class="hide-notification no-restrict-focus" tabindex="-1">&nbsp;</span>');
            
            if (element) {
                $(element).append($emptyFocusableSpan);
            } else {
                $('body').append($emptyFocusableSpan);
            }

            $emptyFocusableSpan.focus();
            $emptyFocusableSpan.one('focusout', function () {
                $emptyFocusableSpan.remove();
                
                if (onRemove) {
                    onRemove();
                }
            });
        }

        self.restoreFocus = function (options) {
            if ($previousElement.length !== 0 && !self.dontRestoreFocus) {
                var $restoringElement = $previousElement.pop();
                var isLastElement = $previousElement.length === 0;
                if (options && $.isFunction(options.focusRestoringCallback)) {
                    options.focusRestoringCallback($restoringElement, isLastElement);
                }
                setTimeout(() => $restoringElement.focus(), 200);
                if (options && $.isFunction(options.focusRestoredCallback)) {
                    options.focusRestoredCallback($restoringElement, isLastElement);
                }
            }
        };

        self.replaceLastElement = function ($newElement) {
            if ($previousElement.length) {
                $previousElement[$previousElement.length - 1] = $newElement;
            }
        };

        self.restrictFocus = function ($container, onOutsideElementFocused, isModal) {
            if (!$container || $container.length === 0) {
                return null;
            }

            if (restrictFocusStack.length === 0) {
                document.addEventListener('focus', restrictFocusHandler, true);
            }

            var firstTabbable, lastTabbable = null;
            if (isModal) {
                firstTabbable = getFirstTabbableElement($container);
                lastTabbable = getLastTabbableElement($container);
                self.setFocusOnKeydown({ $element: firstTabbable, $targetElement: lastTabbable, shift: true });
                self.setFocusOnKeydown({ $element: lastTabbable, $targetElement: firstTabbable, shift: false });
            }

            restrictFocusStack.push({
                $container: $container,
                onOutsideElementFocused: onOutsideElementFocused,
                isModal: isModal,
            });

            return function () {
                var entry = restrictFocusStack.pop();
                if (restrictFocusStack.length === 0) {
                    //when no elements are left in stack, there's no point in handling document's focus events anymore
                    document.removeEventListener('focus', restrictFocusHandler, true);
                }
            };
        };

        self.restoreBrowserControlsFocusBehavior = function () {
            $('#' + LAST_FOCUSABLE_ELEMENT_ID).parent().remove();
        };

        self.enableFocusForBrowserControls = function () {
            self.restoreBrowserControlsFocusBehavior();

            var notification = "Press tab to move to the browser's controls";
            var notificationTextElement =
                $('<p>')
                    .attr({
                        'class': 'visible-on-focus-text'
                    })
                    .text(notification);
            var lastFocusableElementContainer =
                $('<div>')
                    .attr({
                        'aria-label': notification,
                        'role': 'navigation'
                    })
                    .appendTo('body');
            var lastFocusableElement =
                $('<div>')
                    .attr({
                        'id': LAST_FOCUSABLE_ELEMENT_ID,
                        'class': NO_RESTRICT_CLASS + ' visible-on-focus',
                        'tabindex': '0',
                        'role': 'link'
                    })
                    .append(notificationTextElement)
                    .on('keydown', keydownHandler)
                    .appendTo(lastFocusableElementContainer)
                    .visibleOnFocus();
        };

        self.setFocusOnKeydown = function(options) {
            if (!(options.$element && options.$element.length) ||
                !(options.$targetElement && options.$targetElement.length)) {
                return;
            }

            options.shift = options.shift || false;

            if (options.$previousElement && options.$previousElement.length) {
                self.removeFocusOnKeydownHandler(options.$previousElement, options.shift)
            }

            function targetFocusHandler(e) {
                if (options.$targetElement.is(':visible')) {
                    if (e.keyCode == $.ui.keyCode.TAB) {
                        if (options.shift === e.shiftKey) {
                            e.preventDefault();
                            options.$targetElement.focus();
                        }
                    }
                }
            }

            self.removeFocusOnKeydownHandler(options.$element, options.shift);

            options.$element.on(
                options.shift ? TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT : SHIFT_TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT,
                targetFocusHandler
            );
        }

        self.removeFocusOnKeydownHandler = function($element, shift) {
            if (!$element || !$element.length) return;
            $element.off(shift ? TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT : SHIFT_TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT);
        }

        function keydownHandler(e) {
            // Skip to the last tabbable in restricted container on Shift + Tab.
            var code = (e.keyCode ? e.keyCode : e.which);
            var $restrictContainer =
                restrictFocusStack[restrictFocusStack.length - 1] &&
                restrictFocusStack[restrictFocusStack.length - 1].$container;
            if (code === $.ui.keyCode.TAB && e.shiftKey === true && $restrictContainer) {
                e.preventDefault();
                getLastTabbableElement($restrictContainer).focus();
            }
        }

        function restrictFocusHandler(e) {
            if (restrictFocusStack.length === 0) {
                return;
            }

            var flyout = restrictFocusStack[restrictFocusStack.length - 1];

            var $target = $(e.target);
            if (isValidFocusableElement($target, flyout.$container, flyout.isModal)) {
                currentFocusedElement = $target;
                return;
            }

            e.stopPropagation();

            var $firstTabbableInContainer = getFirstTabbableElement(flyout.$container);
            var isInsideFlyout = flyout.$container.find(currentFocusedElement).length !== 0;

            if (flyout.isModal || !isInsideFlyout) {
                $firstTabbableInContainer.focus();
            }

            if (flyout.onOutsideElementFocused) {
                flyout.onOutsideElementFocused();
            }
        }

        function isValidFocusableElement($target, $topmostContainer, ignoreSpecialClass) {
            var isInContainer = $.contains($topmostContainer[0], $target[0]);
            var hasSpecialClass = $target.hasClass(NO_RESTRICT_CLASS);
            var isRootElement = $target.is('html') || $target.parent().length === 0; // Preventing focus trap in browser controls
            return isInContainer || (!ignoreSpecialClass && hasSpecialClass) || isRootElement;
        }

        function getFirstTabbableElement($container) {
            if (!$container || $container.length === 0) {
                return null;
            }

            return $container.find(":tabbable").first();
        }

        function getLastTabbableElement($container) {
            if (!$container || $container.length === 0) {
                return null;
            }

            var $lastTabbableElement = $container.find('.' + self.LAST_TABBABLE_ELEMENT_CLASS);
            if ($lastTabbableElement.length) {
                return $lastTabbableElement;
            }

            return $container.find(":tabbable").last();
        }
    };

    namespace('gJobs').focusService = new FocusService();

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

    function ArrowsNavigationService() {
        var self = this;

        self.addArrowsNavigation = function ($elements) {
            $(document).on('keydown', { $elements: $elements }, keydownHandler);
        }

        self.removeArrowsNavigation = function () {
            $(document).off('keydown', keydownHandler);
        }
        
        self.addArrowsNavigationOnElements = function ($elements) {
            $elements.on('keydown', { $elements: $elements }, keydownHandler);
        }

        self.removeArrowsNavigationOnElements = function ($elements) {
            $elements.off('keydown', keydownHandler);
        }
        
        function keydownHandler (e) {
            var isUpKey = e.keyCode === $.ui.keyCode.UP || e.keyCode === $.ui.keyCode.PAGE_UP;
            var isDownKey = e.keyCode === $.ui.keyCode.DOWN || e.keyCode === $.ui.keyCode.PAGE_DOWN;
            if ((!isUpKey && !isDownKey) || e.shiftKey) {
                return;
            }

            var $elements = e.data.$elements;
            var currentIndex = $elements.index($(e.target));

            if (isUpKey && currentIndex > 0 && currentIndex < $elements.length) {
                e.preventDefault();
                $elements.eq(currentIndex - 1).focus();
            } else if (isDownKey && currentIndex >= 0 && currentIndex < ($elements.length - 1)) {
                e.preventDefault();
                $elements.eq(currentIndex + 1).focus();
            }
            e.stopPropagation();
        }
    };

    namespace('gJobs').arrowsNavigationService = new ArrowsNavigationService();

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

    function AbstractPageScrollService() {
        var self = this;

        self.getFlyoutScrollContainer = function () {
            return $();
        };

        /*
        metrics = {
            offset,
            position,
            padding,
            containerScroll
        };
        */
        self.scrollToView = function (metrics) {
        };
    }

    namespace('gJobs').AbstractPageScrollService = AbstractPageScrollService;
})(window);;
(function (window, undefined) {
    'use strict';

    function AgencyPageScrollService() {

        var self = gJobs.AbstractPageScrollService.call(this) || this;

        self.getFlyoutScrollContainer = function () {
            return $('.flyout-scroll-view').first();
        };

        self.scrollToView = function (metrics) {
            var $flyout = $('.flyout.active, .flyout .active');

            if ($flyout.length == 0) {
                var headerElementHeight = $('.floating-header').height();
                if (headerElementHeight == null)
                    headerElementHeight = 0;

                if ($('html').hasClass('device-phone') || $('html').hasClass('device-tablet')) {

                    var $scrollElement = $('.edit-dialog');
                    if ($scrollElement.length == 0) {
                        $('html, body').animate({
                            scrollTop: metrics.offset.top - metrics.padding - headerElementHeight
                        }, "fast");
                    } else {
                        var offTop = $scrollElement.scrollTop() + metrics.offset.top - $(window).scrollTop();
                        $scrollElement.animate({
                            scrollTop: offTop - metrics.padding - headerElementHeight
                        }, "fast");
                    }
                } else {
                    if (metrics.offset)
                        $('html, body').animate({ scrollTop: metrics.offset.top - headerElementHeight - metrics.padding }, "fast");
                    else
                        $('html, body').animate({ scrollTop: 0}, "fast");
                }
            } else {
                var $container = $flyout.find('.flyout-scroll-view').eq(0);

                if ($('html').hasClass('device-phone')) {
                    $container.animate({
                        scrollTop:  metrics.position.top - metrics.padding
                    }, "fast");
                } else {
                    var topPositionInScrollingViewport = metrics.offset.top - $container.offset().top;
                    $container.animate({
                        scrollTop: metrics.containerScroll + topPositionInScrollingViewport - metrics.padding
                    }, "fast");
                }
            }
        };
    }

    namespace('gJobs').pageScrollService = new AgencyPageScrollService();
})(window);;
(function (window, undefined) {
    'use strict';

    function AbstractAreaInfoService() {
        var self = this;

        self.areaNames = {
            GJobs: 'GJobs',
            Career: 'Career Pages',
            Agency: 'Agency Pages'
        };

        self.namespaceNames = {
            GJobs: 'gJobs',
            CareerPages: 'AgencyPages'
        }

        self.getCurrentArea = function () {
        };

        self.getCurrentNamespace = function () {            
        };
    }

    namespace('gJobs').AbstractAreaInfoService = AbstractAreaInfoService;
})(window);;
(function (window, undefined) {
    'use strict';

    function CareerAreaInfoService() {
        var self = gJobs.AbstractAreaInfoService.call(this) || this;

        var currentArea = self.areaNames.Career;
        var currentNamespace = self.namespaceNames.CareerPages;

        self.getCurrentArea = function () {
            return currentArea;
        };

        self.getCurrentNamespace = function () {
            return currentNamespace;
        }
    }

    namespace('gJobs').areaInfoService = new CareerAreaInfoService();

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

    function PageTabNavigationService() {
        var self = this;

        self.enableScrollForElements = function ($container, tabbableElementSelector, tabbableElementContainer) {
            if (!$container || $container.length === 0) {
                return;
            }

            $container
                .on('mousedown', tabbableElementSelector, function () {
                    $(this).data('isClicking', true);
                })
                .on('focus', tabbableElementSelector, function () {
                    var $this = $(this);

                    if ($this.data('isClicking')) {
                        $this.data('isClicking', false);
                        return;
                    }

                    var $tabbableElementContainer = $this.closest(tabbableElementContainer);

                    if ($tabbableElementContainer.length !== 0) {
                        $tabbableElementContainer[0].scrollIntoView(false);
                    }
                });
        };

        self.adjustNavigationForFixedHeader = function ($container, tabbableElementSelector, tabbableElementContainer) {
            var $fixedHeader = $('.navbar-fixed-top, .navbar'); // revampedDesign. The first header selector is related to old design.
            var $manageBar = $('#manage-bar');
            if (!$fixedHeader.length) {
                $fixedHeader = $('.user-navigation');
            }
            $container.on('focus', tabbableElementSelector || '*', function (event) {
                var $target = $(event.target);

                // In IE click focuses DIV even if div is not focusable (doesn't have tabindex attribute)
                if ($target.is('div') && !$target.attr('tabindex')) {
                    return;
                }

                if ($target.closest($manageBar).length ||
                    $target.closest($fixedHeader).length ||
                    $target.closest('.disable-adjusting-navigation').length ||
                    $target.css('position') === 'fixed') {
                    return;
                }
                var headerHeight = $fixedHeader.height();

                var isManageBarFixed = $manageBar.length &&
                    ($manageBar.closest('.content-container.fixed.search-field-fixed').length ||
                    $(window).scrollTop() > $manageBar.offset().top); // When it is appearing just after flyout is closed

                if (isManageBarFixed) {
                    headerHeight += $manageBar.height();
                }

                var $targetContainer = $target.closest(tabbableElementContainer);
                $targetContainer = $targetContainer.length ? $targetContainer : $target;

                if ($targetContainer.get(0).getBoundingClientRect().top < headerHeight) {
                    var $scrollParent = $targetContainer.scrollParent();
                    if ($scrollParent.is('body')) {
                        $scrollParent = $(window); // Firefox can't scroll body
                    }

                    $scrollParent.scrollTop($targetContainer.offset().top - headerHeight);
                }
                if (!tabbableElementSelector) {
                    event.stopPropagation();
                }
            });
        };
    }

    namespace('gJobs').pageTabNavigationService = new PageTabNavigationService();

})(window);
;
(function () {
    var NOTIFICATION_CLASS = 'screenreader-notification';
    var ARIA_LIVE_NOTIFICATION_CONTAINER = "#aria-live-message-container";
    var ARIA_LIVE_PAGE_LOAD_MESSAGE_NOTIFICATION_CONTAINER = "#aria-live-page-load-message-container";
    var PAGE_LOAD_MESSAGES_SELECTOR = '.page-load-message';

    function ScreenReadersService() {
        var self = this;

        self.setNotification = function ($element, text, suffix, setFocus, rememberPreviousElement, shouldShow, noDelay) {
            if ($element) {
                var notification = text || '';
                if (suffix) {
                    notification += ' ' + suffix;
                }
                var $commonNotification = $element.find('.common-notification');
                if ($commonNotification.length) {
                    $commonNotification.text(notification);
                    $commonNotification.attr('aria-label', notification);
                } else {
                    $element.text(notification);
                }
                $element.attr('aria-label', notification);
                if (shouldShow) {
                    $element.attr('aria-hidden', 'false');
                    $element.attr('tabindex', '-1');
                }
                if (setFocus) {
                    if (gJobs && gJobs.focusService && gJobs.focusService.setFocus && rememberPreviousElement) {
                        gJobs.focusService.setFocus($element);
                    } else {
                        if (noDelay) {
                            $element.focus();
                        } else {
                            setTimeout(() => $element.focus(), 200);
                        }
                    }
                }
            }
        }

        self.setNotificationWithDelay = function ($element, text, suffix, setFocus, rememberPreviousElement, delay) {
            setTimeout(function () {
                self.setNotification($element, text, suffix, setFocus, rememberPreviousElement);
            }, delay);
        }

        self.onceNotification = function (options) {
            var $element = options.$element;
            var ariaLabelText = $element.attr('aria-label') || $element.text() || $element.attr('placeholder');
            var newAriaLabelText = options.message + ariaLabelText;
            $element.attr('aria-label', newAriaLabelText);
            $element.one('blur', function () {
                $element.attr('aria-label', ariaLabelText);
            });
        }

        self.onceAriaLabelledByNotification = function (options) {
            var $element = options.$element;
            var ariaLabelledBy = $element.attr('aria-labelledby') || '';

            var containerIds = options.notificationContainerIds.split(',');
            var newAriaLabelledBy = containerIds.join(' ') + ' ' + ariaLabelledBy;

            var setAriaHiddenAttr = function (containerIds, ariaHiddenAttr) {
                var idsSelector = '#' + containerIds.join(', #');
                $(idsSelector).attr('aria-hidden', ariaHiddenAttr);
            }

            setAriaHiddenAttr(containerIds, false);

            $element.attr('aria-labelledby', newAriaLabelledBy);
            $element.one('blur', function () {
                setAriaHiddenAttr(containerIds, true);

                $element.attr('aria-labelledby', ariaLabelledBy);
            });
        }

        self.setNotificationWithFocusSaving = function (options) {
            var $target = (options.$element && options.$element.length) ? options.$element : $(document.activeElement);
            var $notification = $('<span>');

            $notification.attr('aria-label', options.text);
            $notification.text(options.text);

            $notification.addClass(NOTIFICATION_CLASS);
            $notification.attr('tabindex', '-1');
            copyElementMetrics($notification, $target, options.dontConsiderParentScroll);

            options.moveFocusToNextElement ? $target.after($notification) : $target.before($notification);
            $notification.focus();

            $notification.one('keydown', function (e) {
                var keyCode = e.keyCode || e.which;
                if (keyCode === $.ui.keyCode.TAB) {
                    $notification.remove();
                }
            });

            if (options.returnFocusBack) {
                $notification.one('keydown', function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode === $.ui.keyCode.TAB) {
                        if (options.shouldForceDropdownOpening) {
                            $target.trigger('liszt:open');
                        } else {
                            $target.focus();
                        }
                        return false;
                    }
                });
            }
        }

        self.setNotificationOnElement = function (options) {

            function removeNotificationFromElement() {
                if (savedDropdownlabelledBy !== null) {
                    $target.attr('aria-labelledby', savedDropdownlabelledBy);
                    $dropdownNotification.remove();
                }

                if (savedAriaLabel !== null) {
                    var ariaLabel = savedAriaLabel ? savedAriaLabel : '';
                    $target.attr('aria-label', ariaLabel);
                }

                if (savedLabelHtml !== null) {
                    $label.html(savedLabelHtml);
                }
            }

            var $target = (options.$element && options.$element.length) ? options.$element : $(document.activeElement);

            var isDropdown = $target.hasClass('chzn-container');
            var $label = $('label[for="' + $target[0].id + '"]');
            var elementAriaLabel = $target.attr('aria-label');

            var savedAriaLabel = null;
            var savedLabelHtml = null;

            var savedDropdownlabelledBy = null;
            var $dropdownNotification = null;

            if (isDropdown) {
                var dropdownNotificationId = $target.attr('id') + '-notification';
                $dropdownNotification = $('<span>')
                    .attr({ 'id': dropdownNotificationId, 'class': 'sr-only' })
                    .text(options.text)
                    .appendTo($target);
                savedDropdownlabelledBy = $target.attr('aria-labelledby') || '';
                $target.attr('aria-labelledby', dropdownNotificationId + ' ' + savedDropdownlabelledBy);
            } else if ($label.length) {
                var savedLabelHtml = $label.html();
                $label.html('<span class="sr-only">' + options.text + '</span>' + savedLabelHtml);
            } else {
                savedAriaLabel = elementAriaLabel;
                var ariaLabelText = savedAriaLabel ? options.text + ' ' + savedAriaLabel : options.text;
                $target.attr('aria-label', ariaLabelText);
            }

            var isFormElement = $target.is('input,textarea,select');
            if (isFormElement) {
                OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
            } else {
                $target.focus();
            }

            $target.one('keydown', removeNotificationFromElement);

            // remove notification only on user-initiated click events
            setTimeout(function () {
                $(document).one('click', removeNotificationFromElement);
            });
        }

        self.clearNotificationsOnBlur = function (shouldHide, primaryNotification, secondaryNotification) {
            $(primaryNotification).one('blur', function () {
                self.clearNotification(primaryNotification, shouldHide);
                if (secondaryNotification) {
                    self.clearNotification(secondaryNotification, shouldHide);
                }
            });

        }

        self.clearNotification = function ($element, shouldHide) {
            $element.text('');
            $element.attr('aria-label', '');
            if (shouldHide) {
                $element.removeAttr('tabindex');
                $element.attr('aria-hidden', shouldHide);
            }
        }

        self.setSignInNotification = function ($signInFormNotification, focusRestoreCallback) {
            if (!$signInFormNotification.length) {
                return;
            }

            var notificationText = 'Sign in form is opened';
            if (OnlineApp.ViewModels.applicationViewModel &&
                OnlineApp.ViewModels.applicationViewModel.loginViewModel &&
                OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.isActive()) {
                notificationText = 'Create a new account form is opened.';
            }

            gJobs.screenReadersService.setNotification($signInFormNotification, notificationText, null, true);
            $(document).one(OnlineApp.Events.CommonEventsNames.Login, function () {
                $signInFormNotification.remove();
            });

            if (typeof (focusRestoreCallback) == 'function') {
                $signInFormNotification.one('keydown', function (e) {
                    if (e.keyCode !== $.ui.keyCode.TAB) {
                        return;
                    }
                    e.stopPropagation();
                    e.preventDefault();
                    focusRestoreCallback();
                });
            }
        }

        self.setLogInNotification = function (notificationText) {
            var $loginNotification = $('#sign-in-reader-notification');

            gJobs.screenReadersService.setNotification($loginNotification, notificationText, null, true);

            $loginNotification.one('focusout', function () {
                $loginNotification.text(' ');
            });
        }

        self.silenceScreenreader = function () {
            var $emptySpan = $('<span class="hide-notification no-restrict-focus" tabindex="-1">&nbsp;</span>');
            $('body').prepend($emptySpan);
            $emptySpan.focus();
            $emptySpan.one('focusout', function () {
                $emptySpan.remove();
            });
        }

        self.silenceScreenreaderForBanner = function (notification) {
            var $emptySpan = $('<span class="hide-notification no-restrict-focus" tabindex="-1">' + notification + '</span>');
            $('body').prepend($emptySpan);
            $emptySpan.focus();
            $emptySpan.one('focusout', function () {
                $emptySpan.remove();
            });
        }

        // Adding invisible spaces to force NVDA to read the whole phrase.
        self.applyNvdaAriaLiveFix = function ($element, newText) {
            var invisibleSpace = '<span class="hide-notification">&nbsp;</span>';
            var isFixApplied = !!$element.data('aria-live-fixed');
            var output = isFixApplied ? newText : invisibleSpace + newText + invisibleSpace;

            $element.html(output);
            $element.data('aria-live-fixed', !isFixApplied);
        }

        // Make fake element having the same size and position,
        // so ZoomText border will be the same too.
        function copyElementMetrics($target, $source, dontConsiderParentScroll) {
            $target.height($source.outerHeight());
            $target.width($source.outerWidth());
            var sourcePosition = $source.position();
            var topPostion = sourcePosition.top;

            if (!dontConsiderParentScroll) {
                topPostion += $source.scrollParent().scrollTop();
            }

            $target.css({
                position: 'absolute',
                // Copying margins instead of calling outerHeight(true),
                // because ZoomText border relies on margins too.
                // We can't copy the whole 'margin' property in FF.
                marginTop: $source.css('marginTop'),
                marginRight: $source.css('marginRight'),
                marginBottom: $source.css('marginBottom'),
                marginLeft: $source.css('marginLeft'),
                top: topPostion,
                left: sourcePosition.left
            });
        }

        self.stopNotification = function (selector) {
            var $container = $(selector);
            var $emptyNotification = $('#empty-notification');
            if ($emptyNotification.length) {
                $emptyNotification.remove();
            }
            $emptyNotification = $("<span id='empty-notification' class='common-notification' tabindex='-1'> </span>");
            $container.before($emptyNotification);
            $emptyNotification.focus();
        }

        self.setAriaLiveNotification = function (notification, selector, addAlertAttribute, elementToFocus = null) {
            if (!selector) {
                selector = ARIA_LIVE_NOTIFICATION_CONTAINER;
            }

            $(selector).text('').text(notification);

            if (addAlertAttribute) {
                $(selector).attr('role', 'alert');
            }

            if (!elementToFocus) $(selector).focus();
            else elementToFocus.focus();
        }

        self.setAriaLiveNotificationWithTimeout = function (notification, selector, addAlertAttribute, elementToFocus = null) {
            if (!selector) {
                selector = ARIA_LIVE_NOTIFICATION_CONTAINER;
            }

            $(selector).text('');

            setTimeout(function () { $(selector).text(notification); }, 100);

            if (addAlertAttribute) {
                $(selector).attr('role', 'alert');
            }

            if (!elementToFocus) $(selector).focus();
            else elementToFocus.focus();
        }

        self.setAriaLiveNotificationWithoutRepeat = function (notification, selector) {
            if (!selector) {
                selector = ARIA_LIVE_NOTIFICATION_CONTAINER;
            }
            var $notificationContainer = $(selector);

            if ($notificationContainer.text() !== notification) {
                $notificationContainer.text('').text(notification);
            }
        }

        self.readPageTitle = function ($element, notificationText) {
            var readingPageTitleHelperContainer = "#reading-page-title-helper";
            $(readingPageTitleHelperContainer).attr("tabindex", 0);
            if (!!notificationText) {
                $(readingPageTitleHelperContainer).text(notificationText);
            }
            $(readingPageTitleHelperContainer).focus();
            setTimeout(function () {
                $element.focus();
                $(readingPageTitleHelperContainer).attr("tabindex", -1);
                $(readingPageTitleHelperContainer).text("");
            }, 300);
        }

        self.notificationOnLoad = function () {
            var getPageLoadedMessage = function () {
                var message = $(PAGE_LOAD_MESSAGES_SELECTOR).map(function (index, element) {
                    return $(element).text();
                }).toArray().join(', ');
                return message;
            }

            self.setAriaLiveNotification(
                getPageLoadedMessage,
                ARIA_LIVE_PAGE_LOAD_MESSAGE_NOTIFICATION_CONTAINER
            );
        }
    }

    namespace('gJobs').screenReadersService = new ScreenReadersService();
})();;
(function () {
    var FOCUSABLE_SELECTOR = 'a, area[href], input:not([disabled]):not([type="hidden"]),'
                              + 'select:not([disabled]), textarea:not([disabled]),'
                              + 'button:not([disabled]), iframe, object, embed, [tabindex]';                         

    function AriaSelectors() {
        var self = this;

        self.getFocusableSelector = function () {
            return FOCUSABLE_SELECTOR;
        }
    }

    namespace('gJobs').ariaSelectors = new AriaSelectors();
})();
;
(function () {
    var focusableSelector = gJobs.ariaSelectors.getFocusableSelector();     
    var ARIA_SELECTOR = 'h1, h2, h3, h4, h5, h6, ' + focusableSelector; 
    var ARIA_HIDDEN_DATA_NAME = "ariahidden";

    function getOptions (options) {
        options = options || {};

        if (!options.selector) {
            options.selector = ARIA_SELECTOR;
        }

        return options;
    }

    function getElementsBySelector (selector, modalId) {
        var $elements;

        if (modalId) {
            var $modal = $('#' + modalId);
            $elements = $(selector).not($modal.find("*"));
        } else {
            $elements = $(selector);
        }

        return $elements;
    }

    function disableRestoreAriaHidden ($elementsForShowHide, shouldDisable) {
        var isAttributeHasValue = function (attrValue) {
            if (attrValue !== null && attrValue !== undefined) {
                return true;
            } else {
                return false;
            }
        }

        $elementsForShowHide.each(function() {
            var $element = $(this);
            var ariaHidden;

            if (shouldDisable) {
                ariaHidden = $element.attr("aria-hidden");

                if (isAttributeHasValue(ariaHidden)) {
                    $element.data(ARIA_HIDDEN_DATA_NAME, ariaHidden);
                }

                $element.attr("aria-hidden", "true");
            } else {
                $element.removeAttr("aria-hidden");
                ariaHidden = $element.data(ARIA_HIDDEN_DATA_NAME);

                if (isAttributeHasValue(ariaHidden)) {
                    $element.attr("aria-hidden", ariaHidden);
                    $element.removeData(ARIA_HIDDEN_DATA_NAME);
                }
            }
        });
    }

    function DialogHelper() {
        var self = this;

        self.showHideElementsOnDialog = function (options) {
            var options = getOptions(options);

            var $elementsForShowHide = getElementsBySelector(options.selector, options.modalId);  

            if (options.hide) {
                if (options.shouldDisableRestoreTabIndex === true) {
                    OnlineApp.Services.tabIndexService.disableTabIndex({ hideSkipButton: true });
                }

                disableRestoreAriaHidden($elementsForShowHide, true);

            } else {
                if (options.shouldDisableRestoreTabIndex === true) {
                    OnlineApp.Services.tabIndexService.restoreTabIndex({ hideSkipButton: true });
                }

                disableRestoreAriaHidden($elementsForShowHide, false);
            }
        }

        self.disableTabIndexOnParentView = function (options) {
            var options = getOptions(options);
            OnlineApp.Services.tabIndexService.disableTabIndex({ hideSkipButton: true });
        }

        self.setTabIndexOnJobAlertsPopup = function(jobAlertDialogId) {
            const focusableElements =
                'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
            const modal = document.querySelector(jobAlertDialogId); // select the modal by it's id
            if (!modal) return;
            const firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal
            const focusableContent = modal.querySelectorAll(focusableElements);
            const lastFocusableElement = jobAlertDialogId == "#jobAlertAuthorizationPopup" ? focusableContent[focusableContent.length - 2] : focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal
            document.addEventListener('keydown', function (e) {
                let isTabPressed = e.key === 'Tab' || e.keyCode === 9;
                if (!isTabPressed) {
                    return;
                }
                if (e.shiftKey) { // if shift key pressed for shift + tab combination
                    if (document.activeElement === firstFocusableElement) {
                        lastFocusableElement.focus(); // add focus for the last focusable element
                        e.preventDefault();
                    }
                } else { // if tab key is pressed
                    if (document.activeElement === lastFocusableElement) { // if focused has reached to last focusable element then focus first focusable element after pressing tab
                        firstFocusableElement.focus(); // add focus for the first focusable element
                        e.preventDefault();
                    }
                }
            });
            firstFocusableElement.focus();
        }
    }

    namespace('gJobs').dialogHelper = new DialogHelper();
})();
;
(function () {
    var PDF_READER_LINK = namespace('Resources').PdfReader.downloadLink;
    var PDF_READER_TITLE = namespace('Resources').PdfReader.downloadTitle;

    function AccessibilityHtmlTransformer() {
        var self = this;

        self.makeElementContentAccessible = function($element) {
            self.addPdfDownloadLinks($element);
            self.addMissingImageDescriptions($element);
            self.fixEmbeddedVideoTabIndex($element);
        };

        self.addPdfDownloadLinks = function($element) {
            var pdfLinks = $element.find('a[href$=".pdf"]:not(.print-button)');
            var readerDownloadLink = $('<a>')
                .text('(' + PDF_READER_TITLE + ')')
                .attr({
                    href: PDF_READER_LINK,
                    target: '_blank'
                });

            pdfLinks.after(readerDownloadLink);
            pdfLinks.after(' ');
        };

        self.addMissingImageDescriptions = function($element) {
            var imagesWithoutDescription = $element
                .find('img')
                .filter(function (index, img) {
                    return !$(img).attr('alt');
                });

            var defaultAltText;
            var jobName = $('.job-header-title, .summary .title').filter(':visible').text();
            if (jobName) {
                defaultAltText = jobName + ' description image';
            } else {
                defaultAltText = 'An image without description';
            }

            imagesWithoutDescription.attr('alt', defaultAltText);
        };

        self.fixEmbeddedVideoTabIndex = function ($element) {
            $element
                .find('div[data-oembed-url]')
                .find('iframe[tabindex="-1"]')
                .removeAttr('tabindex');
        };

        self.initPagerSkipButtons = function (container) {
            function initPaginationItem($container, options) {
                $container.find(options.selector).addClass(options.className).find('a').attr('title', options.title).attr('aria-label', options.title);
            }

            var $container = $(container);
            initPaginationItem($container, { selector: '.PagedList-skipToFirst', className: 'first-page-link', title: 'Skip to the first page' });
            initPaginationItem($container, { selector: '.PagedList-skipToPrevious', className: 'previous-page-link', title: 'Skip to the previous page' });
            initPaginationItem($container, { selector: '.PagedList-skipToNext', className: 'next-page-link', title: 'Skip to the next page' });
            initPaginationItem($container, { selector: '.PagedList-skipToLast', className: 'last-page-link', title: 'Skip to the last page' });
        }

        // Create a MutationObserver instance
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(function (node) {
                        if (node.nodeName === 'IFRAME') {
                            var target = $(node);
                            var targetSrc = target.attr('src');
                            if (!target.length || !targetSrc) {
                                return;
                            }
                            if (targetSrc.indexOf('recruitics') >= 0) {
                                target.attr('title', 'Recruitics frame');
                                target.attr('aria-hidden', 'true');
                                observer.disconnect();
                            }
                        }
                    });
                }
            });
        });

        // Configuration of the observer:
        var config = { childList: true, subtree: true };

        // Pass in the target node (body in this case), as well as the observer options
        observer.observe(document.body, config);
    }

    namespace('gJobs').accessibilityHtmlTransformer = new AccessibilityHtmlTransformer();
})();
;
(function (window, undefined) {
    'use strict';

    var aria = gJobs.ariaAttributes;

    // Initialize autocomplete
    $(function () {
        $.fn.tab.Constructor.prototype.activate = window.utils.wrapFunction($.fn.tab.Constructor.prototype.activate,
            function (element, container) {
                if (!container.is('ul')) {
                    return;
                }
                var $selectedTab = element.children().first('a');

                container.find('a[role="tab"]').setAttributes([
                    [ aria.selected, false ]
                ]);

                $selectedTab.setAttributes([
                    [ aria.selected, true ]
                ]);

                $selectedTab.focus();
            });

        $(document).on('keydown', 'a[role="tab"]', function (e) {
            var keyCode = e.keyCode || e.which;
            if (keyCode === $.ui.keyCode.SPACE) {
                var $link = $(e.target || e.srcElement);
                $link.click();
                e.preventDefault();
            }
        });
    });

})(window);;
(function (window, $, undefined) {

    var NAVIGATION_HELPER_TEXT_COLLAPSED = 'List is collapsed. Press Enter to open list. Use up and down arrow keys to navigate.';
    var NAVIGATION_HELPER_TEXT_EXPANDED = 'List is expanded. Use up and down arrow keys to navigate.';
    var SELECTED_OPTIONS_POSTFIX = '-selected-option-names-container';

    var isEnterPressed = false;

    var aria = gJobs.ariaAttributes;

    if (typeof $.fn.chosen === 'function') {

        var Chosen = $.fn.chosen;

        $.fn.chosen = function (options) {
            var $dropdowns = Chosen.apply(this, options);

            return $dropdowns.each(function () {

                var $this = $(this);
                var elementId = $this.attr('id');
                var chosen = $this.data('chosen');

                var navigationHelperId = elementId + '-navigation-helper-label';
                var $navigationHelper = createHelper(navigationHelperId, NAVIGATION_HELPER_TEXT_COLLAPSED);
                $this.after($navigationHelper);
                options.describedBy = options.describedBy 
                    ? options.describedBy + ' ' + navigationHelperId
                    : navigationHelperId;

                if (chosen) {
                    var labels = $this.attr(aria.notification);
                    if (labels) {
                        options.labelledby = options.labelledby
                            ? options.labelledby + ' ' + labels
                            : labels;
                    }

                    initElements(chosen, options);

                    var chosenPrototype = chosen.constructor.prototype;
                    if (!chosenPrototype.accessibility) {
                        //There is no direct access to the prototype. It should be extended only once at the first call.
                        extendPrototype(chosenPrototype);
                    }
                }
            });
        };
    }

    function getChosenSelection(chosen) {
        return chosen.selected_item || chosen.search_choices;
    }

    //Sets initial values of WAI ARIA attributes on the Chosen dropdown elements.
    function initElements(chosen, options) {
        var $select = chosen.selected_item;

        if ($select) {
            initSingleDropdown(chosen, $select, options);
        }

        $select = chosen.search_choices;
        if ($select) {
            initNotification(chosen, $select, options);
            initMultipleDropdown(chosen, $select, options);
        }
    }

    function initNotification(chosen, $select, options) {
        if ($select && options && options.labelledby) {
            var notification = getTextByIDs(options.labelledby);
            if (notification) {
                $select.setAttributes([
                    [aria.notification, notification]
                ]);
            }
        }
    }

    function initSingleDropdown(chosen, $select, options) {

        var $input = $select.find('input');
        var $list = chosen.dropdown.find('ul');
        var $container = $(chosen.container);

        $select.off('focus');

        var labelId = options.labelledby;
        var chosenId = $(chosen.form_field).attr('id');
        var listId = chosenId + '_dropdown';
        var inputId = chosenId + '_input';

        var selectedItemSpanId = chosenId + '-selected-item';
        var selectedItemSpan = $select.children('span');
        selectedItemSpan.attr('id', selectedItemSpanId);

        var containerLabel = labelId + ' ' + selectedItemSpanId;

        $input.setAttributes([
            [aria.autocomplete, 'inline'],          
            ['id', inputId],
            [aria.role, 'textbox']
        ]);

        $input.addClass('ignore-tabindex-update');

        $container.setAttributes([
            [aria.role, 'textbox'],
            [aria.labelledBy, containerLabel],
            [aria.required, options.required],
            [aria.describedBy, options.describedBy],
            ['tabindex', '0'],
        ]);

        var commonAttributes = [
            ['tabindex', '-1'],
            ['data-toggle', 'popover'],
            ['data-container', 'body'],
            ['data-trigger', 'hover'],
            ['data-placement', 'bottom']
        ]        

        if (!options.isDropdownTrigger) {            
            commonAttributes.push([aria.role, 'textbox']);
        }        

        if (options.placeholderTextSingle) {
            commonAttributes.push(['aria-label', options.placeholderTextSingle]);
            $list.attr('aria-label', options.placeholderTextSingle);
        }    
        $select.setAttributes(commonAttributes);

        $select.popover({
            template: '<div class="popover job-details-popover disable-popover-smallscreen" role="tooltip"><div class="arrow">' +
                '</div><h3 class="popover-title"></h3><div class="popover-content"></div></div>',
            animation: false,
            content: function() {
                return $('#' + selectedItemSpanId).text();
            }
        });

        $list.setAttributes([
            ['id', listId],
            ['tabindex', '-1'],
        ]);

        $list.find('li').setAttributes([
            ['tabindex', '-1'],
            [aria.role, 'option']
        ]);

        $select.addClass('ignore-tabindex-update');

        $input.on('keydown', function (e) {
            if (e.which === $.ui.keyCode.ENTER) {
                isEnterPressed ^= true;
                return;
            }
        });

        $input.onFirst('keyup', function (e) {
            if (e.which === $.ui.keyCode.ENTER && !isEnterPressed) {
                // Enter key was pressed down before chosen initialization.
                // It shouldn't be closed immediately, so we're suppressing keyup event.
                e.stopImmediatePropagation();
            }
        });

        $container.keydown(function(evt) {
            if (evt.keyCode === $.ui.keyCode.ENTER || (evt.altKey && evt.keyCode === $.ui.keyCode.DOWN)) {
                chosen.activate_action(evt);
                chosen.selected_item_focus(evt);
            } 
        }); 

        waveFix($input, $select.attr(aria.notification));
    }

    function initMultipleDropdown(chosen, $select, options) {
        var $input = $select.find('input');
        var $list = chosen.dropdown.find('ul');
        var $container = $(chosen.container);

        var chosenId = $(chosen.form_field).attr('id');
        var labelId = options.labelledby;
        var inputId = chosenId + '_input';
        var listId = chosenId + '_dropdown';

        var $selectedOptions = createSelectedOptionNamesContainer(chosen.container_id + SELECTED_OPTIONS_POSTFIX);

        $container.append($selectedOptions);

        $container.setAttributes([
            [aria.role, 'listbox'],
            [aria.labelledBy, labelId + ' ' + chosen.container_id + SELECTED_OPTIONS_POSTFIX],
            [aria.describedBy, options.describedBy],
            [aria.required, options.required],
            ['tabindex', '0']
        ]);

        $input.setAttributes([
            ['id', inputId],
            [aria.role, 'listbox'],
            [aria.owns, listId],
            [aria.required, options.required],
            ['tabindex', '-1']
        ]);

        $input.addClass('ignore-tabindex-update');

        $select.setAttributes([
            [aria.labelledBy, labelId]
        ]);

        $list.setAttributes([
            ['id', listId],
            [aria.role, 'listbox'],
            [aria.labelledBy, labelId]
        ]);

        $list.find('li').setAttributes([
            ['tabindex', '-1'],
            [aria.role, 'option']
        ]);

        $container.on('keydown.chosen.accessibility.multiselect', multiselectKeydownHandler);
        $container.on('keyup.chosen.accessibility.multiselect', multiselectKeyupHandler(chosen));
    }

    //Adds hooks around the Chosen methods to set proper WAI ARIA attribute values in response to user interaction.
    function extendPrototype(chosenPrototype) {

        chosenPrototype.accessibility = {};

        chosenPrototype.getElements = function () {
            return {
                $input: getChosenSelection(this).find('input'),
                $select: getChosenSelection(this),
                $list: this.dropdown.find('ul')
            };
        };

        chosenPrototype.isSingleSelect = function() {
            return this.selected_item !== undefined;
        };

        chosenPrototype.results_build = window.utils.wrapFunction(chosenPrototype.results_build, function () {
            var el = this.getElements();
            //the initial selection is set inside the results_build method
            var initialSelectionId = el.$list.find('.result-selected').attr('id');

            if (!this.isSingleSelect()) {
                var $selectedOptions = el.$select.find('.search-choice');
                var labelId = 'label-' + this.form_field_jq.attr('id');
                $.each($selectedOptions, function (i, val) {
                    var $el = $(val);
                    $removeElement = $el.find('.search-choice-close');
                    $removeElement.setAttributes([
                        [aria.label, 'Remove ' + $el.text()]                        
                    ]);
                });
                var selectedOptionsNames = $.map($selectedOptions, function(selectedOption) {
                    return $(selectedOption).text();
                }).join(', ');
                $('#' + this.container_id + SELECTED_OPTIONS_POSTFIX).text(this.choices_count() ? selectedOptionsNames : '');
            }

            el.$input.attr(aria.activeDescendant, initialSelectionId);
        }, true);

        chosenPrototype.set_tab_index_initial = function(el) {
            var ti;
            if (this.form_field_jq.attr("tabindex")) {
                ti = this.form_field_jq.attr("tabindex");
                this.form_field_jq.attr("tabindex", -1);
                return this.container.attr("tabindex", ti);
            }
        };

        chosenPrototype.set_tab_index_on_show = function(el) {
            var ti = this.container.attr("tabindex");

            if (ti !== '-1') {
                this.container.attr('tabindex', -1);
                
                if (this.is_multiple) {
                    this.container.off('keydown.chosen.accessibility.multiselect');
                    this.container.off('keyup.chosen.accessibility.multiselect');
                }

                return this.search_field.attr('tabindex', ti);
            }
        };
      
        chosenPrototype.set_tab_index_on_hide = function(el) {
            var ti = this.search_field.attr('tabindex');

            if (ti !== '-1') {
                this.container.attr('tabindex', ti);
                this.search_field.attr('tabindex', -1);

                if (this.is_multiple) {
                    this.container.on('keydown.chosen.accessibility.multiselect', multiselectKeydownHandler);
                    this.container.on('keyup.chosen.accessibility.multiselect', multiselectKeyupHandler(this));
                }

                return this.container.focus();
            }
        };

        chosenPrototype.results_show = window.utils.wrapFunction(chosenPrototype.results_show, function () {
            var el = this.getElements();
            gJobs.screenReadersService.setAriaLiveNotificationWithoutRepeat(NAVIGATION_HELPER_TEXT_EXPANDED);
            //The list of items is regenerated each time user opens the dropdown, so the roles must be set too.
            var $listParent = el.$list.parent();
            el.$list.detach();
            el.$list.find('li').setAttributes([
                ['tabindex', '-1'],
                [aria.role, 'option']
            ]);

            $listParent.append(el.$list);
        });

        chosenPrototype.winnow_results = window.utils.wrapFunction(chosenPrototype.winnow_results, function () {
            var el = this.getElements();
            var noResult = el.$list.children('.no-results');
            if (noResult.length) {
                var noResultId = this.container_id + 'no-results';
                noResult.attr('id', noResultId);
                noResult.attr('tabindex', -1);
                el.$input.attr(aria.activeDescendant, noResultId);
            }

        }, true);

        chosenPrototype.close_field = window.utils.wrapFunction(chosenPrototype.close_field, function () {
            if (this.$activatedOption) {
                this.$activatedOption = null;
            }
            this.isActivated = false;
            // Removing role attribute to prevent JAWS Forms Mode from displaying them.
            var el = this.getElements();
            var $listParent = el.$list.parent();
            el.$list.detach();

            $listParent.append(el.$list);
        }, true);

        chosenPrototype.results_hide = window.utils.wrapFunction(chosenPrototype.results_hide, function () {
            setTimeout(function() { // Waiting for 'ko if' binding applying
                if (isEnterPressed) {
                    isEnterPressed ^= true;
                }
            });

            gJobs.screenReadersService.setAriaLiveNotification('');
        });

        chosenPrototype.result_do_highlight = window.utils.wrapFunction(chosenPrototype.result_do_highlight, function ($activeElement) {
            var activeOptionId = $activeElement.attr('id');
            var el = this.getElements();
            if (this.isSingleSelect()) {
                el.$list.find('li').attr(aria.selected, "false");
                $activeElement.attr(aria.selected, "true");
            }

            el.$input.attr(aria.activeDescendant, activeOptionId);
        });

        chosenPrototype.keydown_arrow = window.utils.wrapFunction(chosenPrototype.keydown_arrow, function () {
            var el = this.getElements();
            var $activeElement = el.$list.find('.highlighted');

            el.$input.val($activeElement.text());
        }, true);

        chosenPrototype.keyup_arrow = window.utils.wrapFunction(chosenPrototype.keyup_arrow, function () {
            var el = this.getElements();
            if (this.result_highlight && this.result_highlight.prevAll("li.active-result").length === 0) {
                this.selected_option_count = 0;
                var $defaultItemText = $(this.search_results.children(':visible')[0]).text();
                el.$input.val($defaultItemText);
            } else if (!this.result_highlight) {
                this.result_do_highlight($(this.search_results.children(':visible')[0]));
            } else {
                var $activeElement = el.$list.find('.highlighted');

                el.$input.val($activeElement.text());
            }
        }, true);

        chosenPrototype.result_select = (function(base) {
            return function () {
                if (this.result_highlight && this.result_highlight.length) {
                    var el = this.getElements();
                    var activeOptionId = this.result_highlight.attr('id');

                    el.$input.attr(aria.activeDescendant, activeOptionId);
                }

                base.apply(this, arguments);

                return this.container.focus();
            }
        })(chosenPrototype.result_select);

        chosenPrototype.keydown_checker = window.utils.wrapFunction(chosenPrototype.keydown_checker, function(event) {
            event.stopPropagation();
        }, true);

        chosenPrototype.choice_build = window.utils.wrapFunction(chosenPrototype.choice_build, function(item) {
            var chosen = this;

            var itemCloseLink = getChosenSelection(this).find('.search-choice-close[rel=' + item.array_index + ']');

            itemCloseLink.on("keydown", function(evt) {
                if (event.keyCode === $.ui.keyCode.ENTER) {
                    evt.preventDefault();
                    evt.stopImmediatePropagation();
                    return false;
                }
            });

            itemCloseLink.on("keyup", function(evt) {
                if (event.keyCode === $.ui.keyCode.ENTER) {
                    chosen.choice_destroy_link_click(evt);
                    return false;
                }
            });

        }, true);

        chosenPrototype.results_hide = window.utils.wrapFunction(chosenPrototype.results_hide, function() {
            if (!this.is_multiple) {
                this.getElements().$input.val('');
            }
        }, true);

        chosenPrototype.choice_destroy_link_click = (function(func) {
            return function(event) {
                var $focusTarget;
                var $link = $(event.target);
                var $removingItem = $link.parents('li');
                var $prevItem = $removingItem.prev();
                var $nextItem = $removingItem.next();
                var el = this.getElements();
                var relIndex;
                gJobs.screenReadersService.setAriaLiveNotification($removingItem.text() + ' removed.');

                if ($prevItem.length) {
                    $focusTarget = $prevItem;
                } else {
                    $focusTarget = $nextItem;
                }

                // After removing an element all the others are reattached to DOM,
                // so old links are not working anymore.
                relIndex = $focusTarget.find('a').attr('rel');

                func.call(this, event);

                if (relIndex !== undefined) {
                    $focusTarget = el.$select.find('.search-choice-close[rel="' + relIndex + '"]');
                } else {
                    $focusTarget = this.container;
                }

                $focusTarget.focus();
            };
        })(chosenPrototype.choice_destroy_link_click);
    }

    function createHelper(helperId, helperText) {
        var $helper = $('<span class="ui-helper-hidden-accessible"></span>');
        $helper.text(helperText);
        $helper.attr('id', helperId);
        return $helper;
    }

    function createSelectedOptionNamesContainer(containerId) {
        var $selectedOptions = $('<span class="ui-helper-hidden-accessible"></span>');
        $selectedOptions.attr('id', containerId);
        return $selectedOptions;
    }

    function getTextByIDs(id) {
        var selectors = id.replace(/[ ,]+/gi, ' ').trim().split(' ');
        var text = selectors.map(function (selector) {
            if (!selector.length) {
                return '';
            }
            if (selector[0] !== '#') {
                selector = '#' + selector;
            }
            return $(selector).text().trim() + '.';
        });
        var result = text.join(' ').replace(/[*]+/gi, ' ');
        return result;
    }
    function setNotification($element, notification) {
        var text = $element.text();
        var $notificationContainer = $("<span />");
        $notificationContainer.addClass('hide-notification');
        $notificationContainer.text(notification);
        $notificationContainer.prependTo($element);
        $element.attr(aria.label, notification + ' ' + text);
    }
    function clearNotification($element) {
        $element.find('.hide-notification').remove();
        $element.attr(aria.label, $element.text().trim());
    }
    function waveFix($element, text) {
        var label = $('<label />');
        label.attr('for', $element.attr('id'));
        label.css('display', 'none');
        label.text(text);
        label.appendTo($element.parent());
    }

    function multiselectKeydownHandler(evt) {
        if (evt.keyCode === $.ui.keyCode.ENTER || (evt.altKey && evt.keyCode === $.ui.keyCode.DOWN)) {
            evt.stopImmediatePropagation();
            evt.preventDefault();
            return false;
        }
    }

    function multiselectKeyupHandler(chosen) {
        return function(evt) {
            if (evt.keyCode === $.ui.keyCode.ENTER || (evt.altKey && evt.keyCode === $.ui.keyCode.DOWN)) {
                evt.stopImmediatePropagation();
                evt.preventDefault();
                chosen.input_focus();
                return false;
            }
        }
    }

})(window, jQuery);;
(function ($, window, document, undefined) {

    var pluginName = "keySelection",

        keyEventName = "keydown",

        firstItemIndex = 0,

        actions = {
            up: "up",
            down: "down"
        },

        defaults = {

            selectionItemSelector: ".selection-item",

            isCircling: false,

            keyActions: [
                {
                    keyCode: $.ui.keyCode.UP,
                    action: actions.up
                },
                {
                    keyCode: $.ui.keyCode.PAGE_UP,
                    action: actions.up
                },
                {
                    keyCode: $.ui.keyCode.LEFT,
                    action: actions.up
                },
                {
                    keyCode: $.ui.keyCode.DOWN,
                    action: actions.down
                },
                {
                    keyCode: $.ui.keyCode.PAGE_DOWN,
                    action: actions.down
                },
                {
                    keyCode: $.ui.keyCode.RIGHT,
                    action: actions.down
                }
            ]
        };

    function Plugin(container, options) {

        var self = this;

        this.name = pluginName;
        this.defaults = defaults;
        this.options = $.extend({}, defaults, options);

        this.$container = $(container);
        this.$items = this.$container.find(this.options.selectionItemSelector);
        this.$currentItem = null;

        this.init = init;
        this.up = up;
        this.down = down;
        this.destroy = destroy;

        this.init();

        function init() {
            self.$items.on(keyEventName, keydownHandler);
        }
        function up() {
            moveSelection(function (length, index) {
                if (index > firstItemIndex) {
                    return index - 1;
                } else if (self.options.isCircling && index === firstItemIndex) {
                    return length - 1;
                }
                return undefined;
            });
        }
        function down() {
            moveSelection(function (length, index) {
                if (index < (length - 1)) {
                    return index + 1;
                } else if (self.options.isCircling && (index === (length - 1))) {
                    return firstItemIndex;
                }
                return undefined;
            });
        }
        function destroy() {
            self.$items.off(keyEventName, keydownHandler);
        }

        function keydownHandler(e) {
            var keyCode = e.keyCode || e.which;
            self.$currentItem = $(e.target || e.srcElement);
            $.each(self.options.keyActions, function (i, keyAction) {
                if (keyAction.keyCode === keyCode) {
                    e.preventDefault();
                    switch (keyAction.action) {
                        case actions.up:
                            self.up();
                            break;
                        case actions.down:
                            self.down();
                            break;
                    }
                }
            });
        }
        function moveSelection(actionHandler) {
            if (self.$currentItem) {
                var index = self.$items.index(self.$currentItem);
                var nextIndex = actionHandler(self.$items.length, index);
                if (nextIndex !== undefined) {
                    var nextitem = self.$items.get(nextIndex);
                    self.$currentItem = $(nextitem);
                    self.$currentItem.focus();
                }
            }
        }
    }

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
            if ((typeof options === "string" || options instanceof String) && (/up|down|destroy/).test(options)) {
                var plugin = $.data(this, "plugin_" + pluginName);
                plugin[options].call(plugin);
            }
        });
    };

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

    var CONSENT_COOKIE_NAME = 'CookieConsent';
    var cookieConsent = '#cookie-consent';
    var acceptButton = '#cookie-consent .accept-use-of-cookies';

    if ($.cookie(CONSENT_COOKIE_NAME) !== 'true') {
        $(acceptButton).on('click', setCookieConsent);
        $(cookieConsent).removeClass('hidden');

        $(document).ready(function() {
            $(cookieConsent).focus();
        });
    }

    function setCookieConsent() {
        $(cookieConsent).addClass('hidden');
        $.cookie(CONSENT_COOKIE_NAME, 'true', {expires: 365, path: '/'});
    }
})();;
(function (window, undefined) {
    'use strict';
    $(function () {
        // focus next element after dropdown is closed
        function focusNextElement (event) {
            var $target = $(event.target);
            
            if (!$target.hasClass('dropdown-toggle') && event.keyCode === $.ui.keyCode.ENTER) {
                setTimeout(function() {
                    $target.closest('.dropdown-nav').parent().find('.tab-content').find(':focusable').first().focus();
                });
            }
        }

        // close dropdown when tabbing out of it
        function closeDropdown (event) {
            var focusableElements = $('#navigation-dropdown').find('a[href]');

            var $target = $(event.target)[0];

            if ($target === focusableElements.last()[0] && event.keyCode === $.ui.keyCode.TAB && !event.shiftKey) {
                $('#navigation-dropdown').removeClass('open');
            };

            if ($target === focusableElements.first()[0] && event.keyCode === $.ui.keyCode.TAB && event.shiftKey) {
                $('#navigation-dropdown').removeClass('open');
            };
        };

        function dropdownHandler(e) {
            closeDropdown(e);
            focusNextElement(e);
        }

        $(document).on('keydown.dropdown.data-api', '#navigation-dropdown',  dropdownHandler);
    });

})(window);;
(function(window) {

    $(document).ready(function() {

        var $confirmDialog = $('#confirm-dialog'),
            $body = $('body'),
            disableScrollClasses = 'scroll-disable inner-scrollbar',
            initialBodyClasses = '',
            confirmDialogHeaderSelector = '#dialog-header',
            confirmDialogSubHeaderSelector = '#dialog-subheader',
            confirmDialogCancelButtonSelector = '.cancel-button',
            lastFocusedElement;

        function ConfirmDialogViewModel() {
            var self = this;

            var closeDialog = function () {
                $("#aria-live-message-container").text('');
                self.visible(false);
                setTimeout(function () {                    
                    gJobs.screenReadersService.setAriaLiveNotification("The modal dialog has been closed.");                    
                });
            }

            var defaultViewData = {
                header: 'Proceed with an action',                
                cancelButtonText: 'Cancel',
                confirmButtonText: 'Confirm',
                additionalCssClassName: '',
                innerHtml: null,
                confirmClick: closeDialog,
                cancelClick: closeDialog,
                ariaLabel:'Confirm Dialog'
            };

            self.visible = ko.observable(false);
    
            self.additionalCssClassName = ko.observable(defaultViewData.additionalCssClassName);

            self.innerHtml = ko.observable(null);

            self.confirmDialogStateClassName = ko.observable('');

            self.confirmDialogClasses = ko.computed(function () {
                var confirmDialogStateClassName = self.confirmDialogStateClassName();
                var additionalCssClassName = self.additionalCssClassName();

                var classes = [];
                if (confirmDialogStateClassName) {
                    classes.push(confirmDialogStateClassName);
                }
                if (additionalCssClassName) {
                    classes.push(additionalCssClassName);
                }

                return classes.join(' ');
            });

            self.confirmClick = ko.observable(defaultViewData.confirmClick);
            self.cancelClick = ko.observable(defaultViewData.cancelClick);

            self.header = ko.observable(defaultViewData.header);

            self.subHeader = ko.observable(defaultViewData.subHeader);

            self.confirmButtonText = ko.observable(defaultViewData.confirmButtonText);
            self.cancelButtonText = ko.observable(defaultViewData.cancelButtonText);
            self.ariaLabel = ko.observable(defaultViewData.ariaLabel);

            self.show = function (viewData) {
                self.confirmClick(function() {
                    defaultViewData.confirmClick();
                    if (viewData.confirmClick || viewData.confirmClick === "function") {
                        viewData.confirmClick();
                    }
                });
                self.cancelClick(function() {
                    defaultViewData.cancelClick();
                    if (viewData.cancelClick && typeof viewData.cancelClick === "function") {
                        viewData.cancelClick();
                    }
                });

                self.header(viewData.header || defaultViewData.header);
                self.subHeader(viewData.subHeader || defaultViewData.subHeader);
    
                if (viewData.hideSubHeader) {
                    self.subHeader('');
                }

                self.confirmButtonText(viewData.confirmButtonText || defaultViewData.confirmButtonText);
                self.cancelButtonText(viewData.cancelButtonText || defaultViewData.cancelButtonText);
                self.ariaLabel(viewData.ariaLabel || defaultViewData.ariaLabel);

                self.additionalCssClassName(viewData.additionalCssClassName || defaultViewData.additionalCssClassName);

                self.innerHtml(viewData.innerHtml || defaultViewData.innerHtml);

                self.visible(true);                
                self.announceConfirmDialogContent();
            };

            self.visible.subscribe(function (newValue) {
                self.confirmDialogStateClassName(newValue ? 'active' : 'inactive');

                if (newValue) {
                    $(document).on('touchmove', disableTouchMove);
    
                    var buttonSelector = $confirmDialog.find('button');
                    var firstButton = buttonSelector.eq(0); // Close button icon (X)
                    if (!firstButton.length || firstButton.css('display') === 'none') {
                        firstButton = buttonSelector.eq(1); // Cancel button
                    }

                    // Delay the focusing because of IE11
                    setTimeout(function() {
                        firstButton.focus();
                    });

                    showHideElementsOnPopup(true);
                } else {
                    $(document).off('touchmove', disableTouchMove);
                    
                    showHideElementsOnPopup(false);

                    $body.attr('class', initialBodyClasses);
                    lastFocusedElement.focus();
                    ko.cleanNode($confirmDialog[0]);
                }
            });

            self.announceConfirmDialogContent = function() {
                if (!$confirmDialog.length) return;
              

            

                var dialogSubHeaderMessage = $confirmDialog.find(confirmDialogSubHeaderSelector).text();
                var message = dialogSubHeaderMessage;
                var headerMessage = $confirmDialog.find(confirmDialogHeaderSelector).text();

                var confirmDialogCancelButton = $confirmDialog.find(confirmDialogCancelButtonSelector);

                var options = {
                    message: message,
                    $element: confirmDialogCancelButton
                }; 
                
                setTimeout(function(){
                    gJobs.screenReadersService.setAriaLiveNotification(headerMessage +"   "+ message); 
                }, 200);
               
            };
    
            function showHideElementsOnPopup(hide) {
                var selector = '#body-container, #main-container, #footer, ' 
                                + '.new-job-flyout, #skip-to-content-button, '
                                + '#last-focusable-element, #cookie-consent';

                if (window.revampedDesign) {
                    selector += ", #footer-new"
                }

                gJobs.dialogHelper.showHideElementsOnDialog(
                    {
                        selector: selector,
                        shouldDisableRestoreTabIndex: true,
                        hide: hide 
                    }
                );
            }

            function disableTouchMove(e) {
                e.preventDefault();
            }
    
            $(window).on('statechange', function () {
                if (self.visible()) {
                    self.visible(false);
                }
            });

            $(document).on('keydown', function(e) {
                if (e.keyCode === $.ui.keyCode.ESCAPE && self.visible()) {
                    self.cancelClick()();
                }
            });
        }

        $(document).on(Events.CommonEventsNames.ShowConfirmDialog, function (e, data) {
            if (!$('html').hasClass('error-page')) {
                $element = $confirmDialog[0];
                lastFocusedElement = $(document.activeElement);
                if (!ko.dataFor($element)) {
                    var viewModel = new ConfirmDialogViewModel();
                    ko.applyBindings(viewModel, $element);
                    viewModel.show(data);
                }

                initialBodyClasses = $body.attr('class') || '';
                $body.addClass(disableScrollClasses);
            }
        });
    })
})(window);
(function (window) {

    $(document).ready(function () {
        if (!window.enableChatbase) return;

        var $chatbotOpenButton = $("#chatbase-bubble-button"), $chatBubbleWindow = $("#chatbase-bubble-window"), $chatMessageBubbleWindow = $("#chatbase-message-bubbles"),
            isChatBotOpened = false;
        var loginFailedCounter = 0;
        var isOpenedFromHelpAndSupport = false;
        var isloginFailed = false;
        var isChatWindowShownAutomaticallyInHelpAndSupport = false;
        var link = window.location.href;
        var isSchoolJobs = link.toLowerCase().indexOf("schooljobs") !== -1 ? true : false;


        if ($chatbotOpenButton) {
            $chatbotOpenButton.attr("tabindex", "0");
            $chatbotOpenButton.css("z-index", "999999");
            $chatbotOpenButton.css("height", "80px");
            $chatbotOpenButton.css("width", "80px");
            $chatbotOpenButton.css("border-radius", "50px");
            $chatbotOpenButton.css("bottom", "50px");
            $chatbotOpenButton.attr("role", "button");
        }
        $chatMessageBubbleWindow.css("z-index", "0");
        $chatMessageBubbleWindow.css("display", "none");
        if ($chatBubbleWindow) {
            $chatBubbleWindow.attr("tabindex", "0");
            $chatBubbleWindow.css("max-height", "600px");
            $chatBubbleWindow.css("max-width", "350px");
            $chatBubbleWindow.css("bottom", "1rem");
            $chatBubbleWindow.css("right", "5rem");
            $chatBubbleWindow.attr("role", "dialog");

        }

        if ($chatMessageBubbleWindow) {
            $chatMessageBubbleWindow.hide();
        }

        function showChatbotOpenButton() {
            $chatbotOpenButton.show();
            $chatbotOpenButton.focus();
        }

        function hideChatbotOpenButton() {
            setTimeout(function () {
                $chatBubbleWindow.css("display", "none");
                $chatbotOpenButton.hide();
                $chatBubbleWindow.hide();
            }, 100);
        }

        function openChatBot(isClicked) {
            if (isSchoolJobs) {
                gJobs.screenReadersService.setAriaLiveNotification(
                    "The Schooljobs.com's virtual agent has been opened."
                );
            }
            else {
                gJobs.screenReadersService.setAriaLiveNotification(
                    "The Governmentjobs.com's virtual agent has been opened."
                );
            }
            $chatbotOpenButton.show();
            setTimeout(function () {
                $chatBubbleWindow.focus();
                isChatBotOpened = true;
            }, 100);


        }

        function minimizeChatBot() {
            if (isSchoolJobs) {
                gJobs.screenReadersService.setAriaLiveNotification(
                    "The Schooljobs.com's virtual agent has been closed."
                );
            }
            else {
                gJobs.screenReadersService.setAriaLiveNotification(
                    "The Governmentjobs.com's virtual agent has been closed."
                );
            }
            setTimeout(function () {

                $chatbotOpenButton.focus();
                isChatBotOpened = false;
            }, 100);
        }

        function setWithExpiry(key, value, ms) {
            const now = new Date();

            const item = {
                value: value,
                expiry: now.getTime() + ms
            }

            localStorage.setItem(key, JSON.stringify(item));
        }

        function getWithExpiry(key) {
            const itemFromStorage = localStorage.getItem(key);

            if (!itemFromStorage) {
                return null;
            }

            const item = JSON.parse(itemFromStorage);
            const now = new Date();

            if (now.getTime() > item.expiry) {
                localStorage.removeItem("showChatBotIcon");
                return null;
            }

            return item.value;
        }

        function attachChatbotEventHandlers() {
            document.addEventListener('keydown', function (event) {
                if (event.key === 'Escape') {
                    let chatwindow = document.getElementById('chatbase-bubble-window');
                    if (chatwindow) {
                        chatwindow.style.display = "none";
                        window.localStorage.removeItem("showChatBotIcon");
                        hideChatbotOpenButton();
                        isloginFailed = false;
                        isChatBotOpened = false;
                        let element = document.getElementById('chatbase-bubble-button');
                        if (element) {
                            element.style.display = "none";
                        }
                        if (isSchoolJobs) {
                            gJobs.screenReadersService.setAriaLiveNotification(
                                "The Schooljobs.com's virtual agent has been closed."
                            );
                        }
                        else {
                            gJobs.screenReadersService.setAriaLiveNotification(
                                "The Governmentjobs.com's virtual agent has been closed."
                            );
                        }
                    }
                }

            });

            $(document).on(Events.CommonEventsNames.LoginFailed, function (event) {

                loginFailedCounter++;
                if (loginFailedCounter > 1) {
                    var element = document.getElementById('chatbase-bubble-button');
                    if (element) {
                        element.style.display = "block";
                        setTimeout(function () {
                            element.addEventListener('click', function () {

                                var element1 = document.getElementById('chatbase-bubble-window');
                                var computedStyle = window.getComputedStyle(element1);
                                var displayValue = computedStyle.display;
                                if (displayValue == 'flex') {
                                    if (isSchoolJobs) {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Schooljobs.com's virtual agent has been opened."
                                        );
                                    }
                                    else {

                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Governmentjobs.com's virtual agent has been opened."
                                        );
                                    }
                                }
                                else {
                                    if (isSchoolJobs) {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Schooljobs.com's virtual agent has been closed."
                                        );
                                    }
                                    else {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Governmentjobs.com's virtual agent has been closed."
                                        );
                                    }
                                }
                            });
                        }, 1000);
                    }
                    isloginFailed = false;

                    $chatbotOpenButton.click();
                    let chatwindow = document.getElementById('chatbase-bubble-window');
                    let iframe = chatwindow.querySelector('iframe');
                    if (chatwindow) {
                        iframe.src = "https://" + window.chatBaseDomain + "/chatbot-iframe/" + window.chatbaseId;
                        chatwindow.style.display = "block";
                    }
                    setWithExpiry("showChatBotIcon", true, 15 * 60 * 1000);
                    if (isSchoolJobs) {
                        gJobs.screenReadersService.setAriaLiveNotification(
                            "The Schooljobs.com's virtual agent has been opened."
                        );
                    }
                    else {
                        gJobs.screenReadersService.setAriaLiveNotification(
                            "The Governmentjobs.com's virtual agent has been opened."
                        );
                    }

                }
            });

            // Create a MutationObserver instance
            var observer = new MutationObserver(function () {

                var chatbaseButton = document.getElementById('chatbase-bubble-button');
                if (chatbaseButton) {
                    var computedStyle = window.getComputedStyle(chatbaseButton);
                    var displayValue = computedStyle.display;
                    if (displayValue == 'block') {
                        $('#closeIcon').remove();
                        var imgExists = $('#chatbase-bubble-button div img').length > 0;
                        if (!imgExists) {
                            // Create and append the image if it doesn't already exist
                            const imgElement = $('<img>', {
                                src: 'https://backend.chatbase.co/storage/v1/object/public/chat-icons/a2bd3986-9c2f-4a6c-b27d-02d8bc317b36/2oTr2r01dzmQIaqiyt65W.jpg',
                                alt: 'Virtual Agent',
                                css: {
                                    width: '55px',
                                    height: '55px',
                                    'border-radius': '50%'
                                }
                            });
                            $('#chatbase-bubble-button div').append(imgElement);
                        }
                    }
                }

                if (!isOpenedFromHelpAndSupport) {
                    setTimeout(function () {
                        var isKeyAvailable = getWithExpiry("showChatBotIcon");
                        if (!isKeyAvailable) {
                            var element = document.getElementById('chatbase-bubble-button');
                            if (element) {
                                element.hidden = true;
                                $chatbotOpenButton.hide();
                                element.style.display = "none";

                                var chatbaseButton = document.getElementById('chatbase-bubble-button');
                                var computedStyle = window.getComputedStyle(chatbaseButton);
                                var displayValue = computedStyle.display;
                                if (displayValue == 'block') {
                                    if (isSchoolJobs) {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Schooljobs.com's virtual agent has been closed."
                                        );
                                    }
                                    else {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Governmentjobs.com's virtual agent has been closed."
                                        );
                                    }

                                }
                            }
                        }
                        else {
                            var element = document.getElementById('chatbase-bubble-button');
                            if (element) {
                                element.hidden = false;
                                element.style.display = "block";
                                $chatbotOpenButton.show();
                                if (isChatBotOpened == false && isloginFailed) {
                                    $chatbotOpenButton.click();
                                }
                            }
                        }
                    }, 1000);
                }
                else {
                    if (isChatWindowShownAutomaticallyInHelpAndSupport == false) {
                        var isLocalStorage = getWithExpiry("showChatBotIcon");
                        if (!isLocalStorage) {
                            $chatbotOpenButton.hide();
                            var element = document.getElementById('chatbase-bubble-button');
                            if (element) {
                                element.style.display = "none";
                            }
                        }
                    }
                    setTimeout(function () {
                        var element = document.getElementById('chatbase-bubble-button');
                        if (element) {
                            element.hidden = false;
                            element.style.display = "block";
                            $chatbotOpenButton.show();

                        }
                        if (isChatBotOpened == false && isChatWindowShownAutomaticallyInHelpAndSupport == false) {
                            isChatWindowShownAutomaticallyInHelpAndSupport = true;
                            setTimeout(function () {
                                element.addEventListener('click', function () {
                                    var chatbaseWindow = document.getElementById('chatbase-bubble-window');
                                    var computedStyle = window.getComputedStyle(chatbaseWindow);
                                    var displayValue = computedStyle.display;
                                    if (displayValue == 'flex') {
                                        if (isSchoolJobs) {
                                            gJobs.screenReadersService.setAriaLiveNotification(
                                                "The Schooljobs.com's virtual agent has been opened."
                                            );
                                        }
                                        else {
                                            gJobs.screenReadersService.setAriaLiveNotification(
                                                "The Governmentjobs.com's virtual agent has been opened."
                                            );
                                        }

                                    }
                                    else {
                                        if (isSchoolJobs) {
                                            gJobs.screenReadersService.setAriaLiveNotification(
                                                "The Schooljobs.com's virtual agent has been closed."
                                            );
                                        }
                                        else {
                                            gJobs.screenReadersService.setAriaLiveNotification(
                                                "The Governmentjobs.com's virtual agent has been closed."
                                            );
                                        }

                                    }
                                });

                            }, 1000);
                        }
                    }, 3000)
                }
            });

            // Configuration of the observer:
            var config = { attributes: true, childList: true, subtree: true };

            // Pass in the target node (body in this case), as well as the observer options
            observer.observe(document.body, config);

            $(document).on(Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register, function (event) {

                if (isChatBotOpened == true) {
                    minimizeChatBot();
                }
                window.localStorage.removeItem("showChatBotIcon");
                hideChatbotOpenButton();
                isloginFailed = false;
                isChatBotOpened = false;
                let element = document.getElementById('chatbase-bubble-button');
                if (element) {
                    element.style.display = "none";
                }
                let chatWindow = document.getElementById('chatbase-bubble-window');
                if (chatWindow) {
                    chatWindow.style.display = "none";
                }

            });



            $(document).on(Events.CommonEventsNames.HelpAndSupportPageOpened, function (event) {
                isOpenedFromHelpAndSupport = true;

                //setWithExpiry("showChatBotIcon");
                var isLocalStorage = getWithExpiry("showChatBotIcon");
                if (!isLocalStorage) {
                    $chatbotOpenButton.hide();
                }
            });
        }

        (function initChatbot() {
            isOpenedFromHelpAndSupport = false;
            isloginFailed = false;
            isChatWindowShownAutomaticallyInHelpAndSupport = false;
            var areaInfoService = gJobs.areaInfoService;
            var isCareerPages = areaInfoService.getCurrentArea() === areaInfoService.areaNames.Career;


            attachChatbotEventHandlers();
            setTimeout(function () {
                var showChatBotIcon = getWithExpiry("showChatBotIcon");

                if (!showChatBotIcon) {
                    $chatbotOpenButton.hide();
                }
                else {
                    $chatbotOpenButton.show();
                    var element = document.getElementById('chatbase-bubble-button');
                    if (element) {
                        element.style.display = "block";
                        setTimeout(function () {
                            element.addEventListener('click', function () {

                                var element1 = document.getElementById('chatbase-bubble-window');
                                var computedStyle = window.getComputedStyle(element1);
                                var displayValue = computedStyle.display;
                                if (displayValue == 'flex') {
                                    if (isSchoolJobs) {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Schooljobs.com's virtual agent has been opened."
                                        );
                                    }
                                    else {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Governmentjobs.com's virtual agent has been opened."
                                        );
                                    }

                                }
                                else {
                                    if (isSchoolJobs) {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Schooljobs.com's virtual agent has been closed."
                                        );
                                    }
                                    else {
                                        gJobs.screenReadersService.setAriaLiveNotification(
                                            "The Governmentjobs.com's virtual agent has been closed."
                                        );
                                    }
                                }
                            });
                        }, 1000);
                    }
                }

                $chatMessageBubbleWindow.hide();
            }, 3000);
        })();

        $chatbotOpenButton.click(function (event) {


            isChatBotOpened ? minimizeChatBot() : openChatBot(isChatBotOpened);


        });
        $chatbotOpenButton.on('keydown', function (event) {
            if (event.keyCode === $.ui.keyCode.ENTER) {
                $chatbotOpenButton.click();
            }
        });

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

    var PAGE_TITLE_MAX_LINES = 3;

    $(document).ready(function () {
        var pageTitle = $('.job-search-header-title > h1').get(0);

        var adjustPageTitle = function () {
            clamp(pageTitle, PAGE_TITLE_MAX_LINES);
        };

        $(window).on('resize', adjustPageTitle);

        adjustPageTitle();
    });
})(window);;
(function (window, undefined) {
    'use strict';

    var DEFAULT_DELAY = 500;
    var DEFAULT_REFRESH = 700;

    var lastPopoverShow = 0,
        mouseEnterTime = 0,
        mouseLeaveTime = 0;
    

    $.fn.delayedPopover = function (popoverOptions, delayTime, refreshTime, isResponsiveOnly) {

        var self = this;

        var popoverDelay = delayTime || DEFAULT_DELAY;
        var popoverRefresh = refreshTime || DEFAULT_REFRESH;

        var options;
        if (popoverOptions && !popoverOptions.trigger || !popoverOptions) {
            options = $.extend(popoverOptions, {
                trigger: 'manual',
                animation: false,
                html: true
            });
        } else {
            options = popoverOptions;
        }

        self.popover(options);

        var isElementShown = false;

        var getTimeInMsec = function () {
            return (new Date()).getTime();
        };

        var showPopover = function ($element) {
            $element.popover('show');
            if ($element.hasClass('hide-aria-label'))
                $element.removeAttr('aria-describedby');
            isElementShown = true;
            $('a#gmapLink').css('color', 'white');
            $('#gmapLink').focus();
            $('.popover-content').css("pointer-events", "auto")
        };

        var hidePopover = function ($element) {
            if (iselementshown) {
                $element.popover('hide');
                lastpopovershow = gettimeinmsec();
                iselementshown = false;
            }
        };
        var closeLocationPopover = function () {
            $("#redirectLink").popover('hide');
            $('.click-popover').removeClass('visible-desktop');
            $('.click-popover').hide();
        };

        self
            .on('click', function () {
                var $this = $(this);
                if ($this[0].id == "redirectLink") {
                    showPopover($this);
                    $('.popover-content').css("pointer-events", "auto")
                }
            })
            .on('keydown', function (e) {
                if (e.keyCode == 13) {
                    var $this = $(this);
                    if ($this[0].id == "redirectLink") {
                        showPopover($this);

                        $('.popover-content').css("pointer-events", "auto")
                    }
                }

            })
            .on('focus mouseenter', function () {
                if (isResponsiveOnly && $('html').hasClass('device-phone') || !isResponsiveOnly) {
                    var $this = $(this);
                    mouseEnterTime = getTimeInMsec();
                    if ($this[0].id != "redirectLink") {
                        if (mouseEnterTime >= lastPopoverShow + popoverRefresh) {
                            setTimeout(function () {
                                var currenTime = getTimeInMsec();
                                if (currenTime >= mouseLeaveTime + popoverDelay) {
                                    showPopover($this);
                                    closeLocationPopover();
                                }
                            }, popoverDelay);
                        } else {
                            showPopover($this);
                            closeLocationPopover();
                        }
                    }
                }
            });
            

        return self;
    };

    
    $('body').on('click', function (e) {
        if ($('#applications').length == 0) {//Part of fix for ONLINE-13390, eventhandler added for maps and not required for application submission page
            var isPopoverVisible = $('.popover-content').length > 0;
            if (e.target.id == 'redirectLink') {

                if (isPopoverVisible) {
                    gJobs.screenReadersService.setNotification($("#aria-live-message-container"), 'Popover opened', '', true);
                }
            }
            if (e.target.id != 'redirectLink' && isPopoverVisible) {
                $('.popover').popover('hide');
                $('[data-toggle=popover]').each(function () {
                    // hide any open popovers when the anywhere else in the body is clicked
                    if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                        $(this).popover('hide');
                        var elementsToExclude = getListOfElmentsToBeExcluded();
                        if (e.target && e.classList && e.target.id && e.target.id != "" && elementsToExclude.indexOf(e.target.id) == -1 && !e.classList.contains('selectable-item-container')) {
                            gJobs.screenReadersService.setNotification($("#aria-live-message-container"), 'Popover closed', '', true);
                        }
                    }
                });
            }
        }
    });

    $('body').on('keydown', function (e) {
        var isPopoverVisible = $('.popover-content').length > 0;
        if (e.keyCode == 27 && isPopoverVisible) {
            $('.popover').popover('hide');
            $("#redirectLink").popover('hide');
            $('.click-popover').removeClass('visible-desktop');
            $('.click-popover').hide();
            if (e.target.id == 'gmapLink')
                $("#redirectLink").focus();
            var elementsToExclude = getListOfElmentsToBeExcluded();
            if (e.target && e.classList && e.target.id && e.target.id != "" && elementsToExclude.indexOf(e.target.id) == -1 && !e.classList.contains('selectable-item-container')) {
                gJobs.screenReadersService.setNotification($("#aria-live-message-container"), 'Popover closed', '', true);
            }
        }
    });

    $(document).ready(function () {
        var delayedPopoverSelector = $('.delayed-popover');
        var delayedResponsivePopoverSelector = $('.responsive-delayed-popover');
        $("[data-toggle=popover]").not(".donot-register-delayed-popover")
            .popover({ html: true })
        // Initialize non-responsive delayed popovers
        if (delayedPopoverSelector.length > 0) {
            delayedPopoverSelector.popover().click(function () {
                $(this).popover('hide');
            });
        }

        // Initialize responsive delayed popovers
        if (delayedResponsivePopoverSelector.length > 0) {
            delayedResponsivePopoverSelector.delayedPopover(null, null, null, true).click(function () {
                $(this).popover('hide');
            });
        }
        $('#redirectLink').on('click', function () {
            $(this).popover({
                template: '<div class="popover click-popover" role="tooltip"><h3 class="popover-title"></h3><div class="popover-content"></div></div>',
                animation: false,
                html: true,
                trigger: 'manual'
            });

            $(this).popover('show');
            $('a#gmapLink').css('color', 'white');
            $('#gmapLink').focus();
            $('.popover-content').css("pointer-events", "auto")
        })



        $('#redirectLink').on('keydown', function (e) {
            if (e.keyCode == 13) {
                $(this).popover({
                    template: '<div class="popover click-popover" role="tooltip"><h3 class="popover-title"></h3><div class="popover-content"></div></div>',
                    animation: false,
                    html: true,
                    trigger: 'manual'
                });

                $(this).popover('show');
                $('a#gmapLink').css('color', 'white');
                $('#gmapLink').focus();
                $('.popover-content').css("pointer-events", "auto")
            }
        })

    });
})(window);;
(function (window, $, undefined) {
    'use strict';

    var pageTypes = {
        promotionalJobs: { type: 'promotionalJobs', urlPart: 'promotionaljobs' },
        transferJobs: { type: 'transferJobs', urlPart: 'transferjobs' },
        jobOpportunitiesJobs: { type: 'jobOpportunitiesJobs', urlPart: '' },
        classSpecifications: { type: 'classSpecifications', urlPart: 'classspecs' },
        categories: {type: 'categories', urlPart: 'categories'},
        accountSettings: { type: 'accountSettings', urlPart: 'accountsettings' },
        profileSettings: { type: 'profileSettings', urlPart: 'profilesettings' },
        applications: { type: 'applications', urlPart: 'applications' },
        manageJobInterestCard: { type: 'manage', urlPart: 'manage'},
        inbox: { type: 'inbox', urlPart: 'inbox' }
    };

    var virtualPageTypes = [
        {
            tabName: 'resume',
            page: 'resume-upload',
            title: ' | Resume'
        },
        {
            tabName: 'general',
            page: 'info',
            title: ' | Info'
        },
        {
            tabName: 'work',
            page: 'work-expirience',
            title: ' | Work Experience'
        },
        {
            tabName: 'education',
            page: 'education',
            title: ' | Education'
        },
        {
            tabName: 'additional',
            page: 'additional-information',
            title: ' | Additional Information'
        },
        {
            tabName: 'attachments',
            page: 'attachment',
            title: ' | Attachments'
        },
        {
            tabName: 'questions',
            page: 'questions',
            title: ' | Questions'
        },
        {
            tabName: 'review',
            page: 'review',
            title: ' | Review'
        },
        {
            tabName: 'submit',
            page: 'submit',
            title: ' | Certify'
        }
    ]

    function PageInfoService() {
        var currentPageType;
        var currentUrlParts;
        var currentDepartmentFolderName = null;

        var self = this;

        self.virtualPageTypes = virtualPageTypes;

        self.getCurrentVirtualPageProperties = function (tabName) {
            var currentVirtualPage = null;
            self.virtualPageTypes.some(function(element) {
                return element.tabName == tabName ?
                    ((currentVirtualPage = element), true) :
                    false;
            });
            return currentVirtualPage;
        } 

        function setCurrentDepartmentFolder() {
            var urlParams = self.getCurrentUrlParts();
            currentDepartmentFolderName = urlParams[3];

            if (window.enableTwoFactorAuthentication) {
                var currentDepartmentLower = currentDepartmentFolderName.toLowerCase();

                if (currentDepartmentLower === "verifyidentity" || currentDepartmentLower === "verifyaccount") currentDepartmentFolderName = null;
            }

            if (currentPageType.urlPart !== '') {
                currentPageType.urlPart = urlParams[3] + '/' + currentPageType.urlPart;
            } else {
                currentPageType.urlPart = urlParams[3];
            }
        }

        self.getCurrentUrlParts = function () {
            if (!currentUrlParts) {
                var currentRoutePath = window.location.pathname;
                if (currentRoutePath !== undefined) {
                    var routeTokens = /^\/([^/]*)(?:\/([^/]*))?(?:\/([^/]*))?(?:\/([^/]*))?(?:\/([^/]*))?/i.exec(currentRoutePath);

                    currentUrlParts = routeTokens;
                } else {
                    currentUrlParts = [];
                }
            }

            return currentUrlParts;
        };

        self.parseQuery = function () {
            var queryString = window.location.search;
            var query = {};
            var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
            for (var i = 0; i < pairs.length; i++) {
                var pair = pairs[i].split('=');
                query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
            }
            return query;
        }

        self.getCurrentPageType = function () {
            if (!currentPageType) {
                var routeTokens = self.getCurrentUrlParts();

                if (routeTokens != undefined && routeTokens.length > 3 && routeTokens[3] !== undefined) {
                    if (routeTokens[5]) {
                        if (routeTokens[4].toLowerCase() == 'applications') {
                            if (routeTokens[5].toLowerCase() == 'accountsettings') {
                                currentPageType = pageTypes.accountSettings;
                            } else {
                                currentPageType = pageTypes.applications;
                            }
                            setCurrentDepartmentFolder();
                        } else if (routeTokens[3].toLowerCase() == 'applications') {
                            if (routeTokens[4].toLowerCase() == 'accountsettings') {
                                currentPageType = pageTypes.accountSettings;
                            } else {
                                currentPageType = pageTypes.applications;
                            }
                        }
                        else if (routeTokens[3].toLowerCase() === 'inbox') {
                            currentPageType = pageTypes.inbox;
                        }
                         else if (routeTokens[4].toLowerCase() == 'manage') {
                            currentPageType = pageTypes.manageJobInterestCard;
                        }
                    } else if (routeTokens[4]) {
                        if (routeTokens[4] && routeTokens[4].toLowerCase() == 'transferjobs') {
                            currentPageType = pageTypes.transferJobs;
                            setCurrentDepartmentFolder();
                        } else if (routeTokens[4] && routeTokens[4].toLowerCase() == 'promotionaljobs') {
                            currentPageType = pageTypes.promotionalJobs;
                            setCurrentDepartmentFolder();
                        } else if (routeTokens[4] && routeTokens[4].toLowerCase() == 'classspecs') {
                            currentPageType = pageTypes.classSpecifications;
                            setCurrentDepartmentFolder();
                        } else if (routeTokens[4].toLowerCase() == 'profilesettings') {
                            currentPageType = pageTypes.profileSettings;
                        } else if (routeTokens[3].toLowerCase() == 'applications') {
                            if (routeTokens[4].toLowerCase() == 'accountsettings') {
                                currentPageType = pageTypes.accountSettings;
                            } else {
                                currentPageType = pageTypes.applications;
                            }
                        } else if (routeTokens[4].toLowerCase() == 'categories') {
                            currentPageType = pageTypes.categories;
                        } else if (routeTokens[3].toLowerCase() === 'canvass') {
                            currentPageType = pageTypes.jobOpportunitiesJobs;
                        }
                    } else {
                        if (routeTokens[3].toLowerCase() == 'transferjobs') {
                            currentPageType = pageTypes.transferJobs;
                        } else if (routeTokens[3].toLowerCase() == 'promotionaljobs') {
                            currentPageType = pageTypes.promotionalJobs;
                        } else if (routeTokens[3].toLowerCase() == 'classspecs') {
                            currentPageType = pageTypes.classSpecifications;
                        } else if (routeTokens[3].toLowerCase() == 'profilesettings') {
                            currentPageType = pageTypes.profileSettings;
                        } else if (routeTokens[3].toLowerCase() === 'inbox') {
                            currentPageType = pageTypes.inbox;
                        } else {
                            currentPageType = pageTypes.jobOpportunitiesJobs;
                            setCurrentDepartmentFolder();
                        }
                    }
                } else {
                    currentPageType = pageTypes.jobOpportunitiesJobs;
                }
            }

            return currentPageType;
        };

        self.isJobDetailsPage = function () {
            var currentUrlParts = self.getCurrentUrlParts();
            var query = self.parseQuery();
            return (currentUrlParts[3] && currentUrlParts[3] == 'jobs') ||
                (query.jobId || query.jobName);
        };

        self.getCurrentAgencyFolderName = function () {
            var agencyFolderName = $('html').data('agency-folder-name');
            
            if (agencyFolderName) {
                return agencyFolderName;
            } else {
                return self.getCurrentUrlParts()[2];
            }
        };

        self.getCurrentDepartmentFolderName = function () {
            return currentDepartmentFolderName || $('html').data('department-folder-name');
        };

        self.isDepartmentPage = function () {
            return !!self.getCurrentDepartmentFolderName();
        };

        self.getCurrentInitialUrl = function(customPrefixForUrlPart) {
            var currentPage = self.getCurrentPageType();

            if (!currentPage) return currentPage;

            var urlPart = currentPage.urlPart === '' ? '' : '/' + currentPage.urlPart;

            if (customPrefixForUrlPart) {
                urlPart = customPrefixForUrlPart + urlPart;
            }

            var initialUrl = AgencyPages.routePrefix + '/' + self.getCurrentAgencyFolderName() + urlPart;

            return initialUrl;
        };

        self.getCurrentAgencyHomePath = function () {
            var routeTokens = self.getCurrentUrlParts();

            if (routeTokens != undefined && routeTokens.length > 2 && routeTokens[2] !== undefined && namespace('AgencyPages').router != undefined) {
                var homePagePath = namespace('AgencyPages').router.routePrefix + '/' + routeTokens[2];

                if (self.isDepartmentPage()) {
                    homePagePath += '/' + self.getCurrentDepartmentFolderName();
                }

                return homePagePath;
            }

            return window.location.href;
        }

        self.getCurrentAgencyHomePageUrl = function () {
            var routeTokens = self.getCurrentUrlParts();

            if (routeTokens != undefined && routeTokens.length > 2 && routeTokens[2] !== undefined) {
                if (!window.location.origin) { //ie<11 doesn't support location.origin
                    window.location.origin = window.location.protocol +
                        "//" + window.location.hostname +
                        (window.location.port ? ':' + window.location.port : '');
                }

                var homeUrl = window.location.origin + self.getCurrentAgencyHomePath();

                return homeUrl;
            }

            return window.location.href;
        };

        self.getPageTypes = function() {
            return pageTypes;
        };

        self.isOnApplyPage = function() {
            return window.location.href.toLowerCase().indexOf('/apply') > -1;
        };

        self.isOnPreferencesSectionPage = function() {
            return self.getCurrentPageType().type === pageTypes.accountSettings.type
                && window.location.hash.toLowerCase().indexOf('#preferences') > -1;
        };
    }

    namespace('AgencyPages').pageInfoService = new PageInfoService();
})(window, jQuery);
;
(function(window, undefined) {
    'use strict';

    var agencyUserSettingsName = 'agencyUserSettings';

    function UserSettingsService() {
        var self = this;

        self.getSettings = function() {
            if (typeof (Storage) !== 'undefined') {
                //check for stored settings
                var settingsString = localStorage.getItem(agencyUserSettingsName);

                if (settingsString) {
                    return JSON.parse(settingsString);
                }
            }

            return {};
        };

        self.setSettings = function(settings) {
            //check for local storage support
            if (typeof (Storage) !== 'undefined') {
                localStorage.setItem(agencyUserSettingsName, JSON.stringify(settings));
            }
        };

        self.getSettingsTargetPage = function (targetPageName) {
            var settings = self.getSettings();

            if (settings) {
                return settings[targetPageName];
            }

            return undefined;
        };

        self.setSettingsTargetPage = function(targetPageName, targetPageSettings) {
            //check for local storage support
            if (typeof (Storage) !== 'undefined') {
                //check for stored settings
                var settingsString = localStorage.getItem(agencyUserSettingsName);

                var settings;

                if (!settingsString) {
                    settings = {};
                } else {
                    settings = JSON.parse(settingsString);
                }

                if (!settings[targetPageName]) {
                    settings[targetPageName] = {};
                }

                settings[targetPageName] = targetPageSettings;

                self.setSettings(settings);
            }
        };
    }

    namespace('AgencyPages').userSettingsService = new UserSettingsService();
})(window);;
(function () {
    'use strict';

    var DISABLE_SCROLL_CLASS = 'fixfixed';

    function BodyScrollingAdjustmentService() {
        var self = this;

        var $html = $('html'),
            scrollTop = 0;

        self.disableBodyScrolling = function () {
            scrollTop = $(document).scrollTop();
            $html.addClass(DISABLE_SCROLL_CLASS);
            $html.css('margin-top', -scrollTop);
        };

        self.enableBodyScrolling = function () {
            $html.removeClass(DISABLE_SCROLL_CLASS);
            $html.css('margin-top', 0);

            var currentScrollTop = $(document).scrollTop();
            if (currentScrollTop !== scrollTop) {
                $(document).scrollTop(scrollTop);
            }
        };
    }

    namespace('AgencyPages').bodyScrollingAdjustmentService = new BodyScrollingAdjustmentService();
})();
(function () {
    var matches = navigator.userAgent.match(/(iPad|iPhone|iPod touch);.*CPU.*OS 7_\d.*(CriOS|Version)\/[.0-9]*\sMobile/i);

    //check for iOS 7 and for safari mobile
    if (matches && matches[2] !== 'CriOS') {
        //add a css class so we can use css for styles specific for ios7
        $('html').addClass('ios7-device');

        //ios bars state: true - shown, false - hidden
        var ios7bars = null,
            //function to force iOS 7 Safari page rerender
            refresh = function () {
                window.scrollTo(document.body.scrollLeft, document.body.scrollTop);
                window.dispatchEvent(new Event('resize'));
            };

        //check for changes of the viewport size and detect ios 7 bars every .5s
        setInterval(function() {
            var landscape = window.orientation == 90 || window.orientation == -90,
                viewportHeight = window.innerHeight,

                //available screen height in current device orientation
                testHeight = (landscape ? screen.availWidth : screen.availHeight) * 0.85;

            if ((ios7bars == null || ios7bars == false) && (viewportHeight < testHeight)) {
                ios7bars = true;
                refresh();
            } else if ((ios7bars == null || ios7bars == true) && (viewportHeight > testHeight)) {
                ios7bars = false;
                refresh();
            }
        }, 500);
    }
})();;
(function (window, undefined) {
    function Ios8Detector() {
        var self = this;

        self.IsIos8 = function() {
            var deviceAgent = window.navigator.userAgent.toLowerCase();
            return /(iphone|ipod|ipad).* os 8_/.test(deviceAgent);
        }
    }

    namespace('AgencyPages').Ios8Detector = new Ios8Detector();
})(window);;
(function(window, undefined) {
    $(window).on("load", function() {
        $('img').filter(function() {
            var img = this;

            if (!img.complete) {
                return true;
            }

            if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
                return true;
            }

            return false;
        }).addClass('missing-image')
            .parent('a')
            .addClass('missing-image-link');
    });
})(window);
(function(window, undefined) {
    function ScrollableContainerAdjuster() {
        var self = this;

        var shadowContainerClass = 'header-shadow';
        var shadowContainerSelector = '.' + shadowContainerClass;

        self.addHeaderShadowOnScrolling = function(scrollableContainer) {
            if (!scrollableContainer || !scrollableContainer.length) {
                return;
            }

            var $scrollableContainer = $(scrollableContainer);

            $scrollableContainer.scroll(function () {
                var scroll = $scrollableContainer.scrollTop();

                if (scroll !== 0) {
                    if (!$scrollableContainer.siblings(shadowContainerSelector).length) {
                        //Applying shadow to the element itself causes shadow to be below contents
                        //(noticeable on images), thus a separate shadow element is needed.
                        $('<div>').attr('class', shadowContainerClass).insertAfter($scrollableContainer);
                    }
                } else {
                    $scrollableContainer.siblings(shadowContainerSelector).remove();
                }
            });
        };
    }
    
    namespace('AgencyPages').scrollableContainerAdjuster = new ScrollableContainerAdjuster();
})(window);
(function(window, undefined) {
    'use strict';

    function ClassSpecificationsFilterCategoryViewModel() {
        var self = this,
            classSpecificationsSearchFieldSelector = '#class-specifications-search-field',
            classSpecificationsSearchComponentSelector = '.class-specs-search-with-autocomplete-labels-component',
            classSpecificationsAutocompleteMenuClassName = 'class-specifications-autocomplete-menu',
            classSpecSearchFieldFocusNotification = 'Search for class specifications. When autocomplete results are available use up and down arrows to select an item.',
            applyClassSpecificationsFilterCategoryButtonSelector = '.apply-class-specifications-filter-category-button';

        self.classSpecificationsSearchString = ko.observable('').extend({ required: {} });

        self.selectedClassSpecifications = ko.observableArray([]);

        self.selectedClassSpecificationsCache = ko.observableArray([]);

        self.initSearchFieldWithAutocomplete = function(searchFieldSelector, initOptions) {
            var autocompleteMenuSelector = '.' + initOptions.autocompleteMenuClassName;

            var options = {
                searchFieldSelectors: [searchFieldSelector],
                additionalCssClassNames: initOptions.autocompleteMenuClassName,
                responseCallback: initOptions.searchCallback
            };

            $(document).trigger(OnlineApp.Events.CommonEventsNames.InitSearchFieldsWithAutocomplete, options);

            $(document).on(OnlineApp.Events.CommonEventsNames.AutocompleteMenuItemSelect, autocompleteMenuSelector, function(event, ui) {
                var $searchField = $(searchFieldSelector);

                if ($searchField && $searchField.length) {
                    $searchField.val('');
                }

                initOptions.searchItemSelectCallback(event, ui);
            });

            $(searchFieldSelector).removeAttr('aria-expanded');
            $(searchFieldSelector).attr('role', 'textbox');
        };

        self.addSelectedSearchItem = function(
            item,
            selectedItemsCollection,
            selectedItemsSearchComponentSelector,
            name,
            fieldSelector,
            selectedItemsCollectionCache) {
            var itemWasAdded = selectedItemsCollection().some(function(selectedItem) {
                return item.text.trim() === selectedItem.text.trim();
            });

            if (itemWasAdded) return;

            var removeSelectedAutocompleteLabelCallback = function() {
                var removeNotification = 'The selected class specification ' + item.text + ' has been removed. ';

                $(classSpecificationsSearchFieldSelector).attr('aria-label', removeNotification + classSpecSearchFieldFocusNotification);

                selectedItemsCollection.remove(item);

                $(classSpecificationsSearchFieldSelector).focus();

                $(classSpecificationsSearchFieldSelector).one('blur', function() {
                    $(classSpecificationsSearchFieldSelector).attr('aria-label', classSpecSearchFieldFocusNotification);
                });
            };

            OnlineApp.Helpers.textSearchWithAutocompleteLabelsComponentHelper
                .addSelectedAutocompleteLabelToSearchComponent(
                    item.text, 
                    selectedItemsSearchComponentSelector,
                    removeSelectedAutocompleteLabelCallback,
                    name,
                    fieldSelector);

            selectedItemsCollection().push(item);

            selectedItemsCollectionCache().push(item);

            selectedItemsCollection.valueHasMutated();

            selectedItemsCollectionCache().valueHasMutated();
        };

        self.getSelectedSearchItemFromUi = function(ui) {
            let itemText = $(ui.item).data().uiAutocompleteItem.label;
            let itemSqlId = $(ui.item).data().uiAutocompleteItem.itemId;
            let itemCode = $(ui.item).data().uiAutocompleteItem.classCode;

            let selectedSearchItem = { text: itemText, sqlId: itemSqlId, code:itemCode };

            return selectedSearchItem;
        };

        self.getSelectedClassSpecificationsCodes = function() {
            var selectedClassSpecificationsCodes = self.selectedClassSpecifications().map(function (selectedItem) {
                return selectedItem.code;
            });

            return selectedClassSpecificationsCodes;
        };

        self.addSelectedClassSpecification = function(event, ui) {
            var selectedClassSpecification = self.getSelectedSearchItemFromUi(ui);

            self.addSelectedSearchItem(
                selectedClassSpecification,
                self.selectedClassSpecifications,
                classSpecificationsSearchComponentSelector,
                'Class Specification',
                classSpecificationsSearchFieldSelector,
                self.selectedClassSpecificationsCache);
        };

        self.getClassSpecificationsCodesFromQueryString = function() {
            var urlSearchParams = new URLSearchParams(window.location.search.replace(/(\[\d+\])+/g, ''));

            var classSpecificationsCodes = urlSearchParams.getAll('classspecificationscodes');

            return classSpecificationsCodes;
        }

        self.updateFieldErrorState = function(field, hasError, errorMessage) {
            field.hasError(hasError);
            field.isValidationMessageVisible(hasError);

            if (hasError && errorMessage) {
                field.validationMessage(errorMessage);
            }
        };

        self.handleSearchFieldChange = function(event) {
            self.updateFieldErrorState(
                self.classSpecificationsSearchString,
                false);
        };

        self.classSpecificationsSearchFieldAfterRender = function() {
            var initOptions = {
                searchCallback: self.clearSearchResultsFromSelectedClassSpecifications,
                searchItemSelectCallback: self.addSelectedClassSpecification,
                autocompleteMenuClassName: classSpecificationsAutocompleteMenuClassName
            };

            self.initSearchFieldWithAutocomplete(classSpecificationsSearchFieldSelector, initOptions);

            OnlineApp.Helpers.textSearchWithAutocompleteLabelsComponentHelper
                .initScrollHandlersForSearchField(classSpecificationsSearchComponentSelector);
            $(classSpecificationsSearchFieldSelector).removeAttr('aria-expanded');

            $(classSpecificationsSearchFieldSelector).keydown(function(event) {
                self.handleSearchFieldChange();

                if (event.keyCode === $.ui.keyCode.ENTER) {
                    $(applyClassSpecificationsFilterCategoryButtonSelector).focus();
                }
            });
        };

        self.clearSelectedLabels = function(selectedLabelsSelector) {
            var $selectedLabels = $(selectedLabelsSelector);

            if ($selectedLabels && $selectedLabels.length) $selectedLabels.remove();
        };

        self.clearSearchResultsFromSelectedItems = function(uiContent, selectedItemsCollection) {
            var uiContentIndexDifference = 0;

            $(uiContent).each(function(index, searchResult) {
                var searchResultWasSelected = selectedItemsCollection().some(function (selectedItem) {
                    return searchResult.itemId === selectedItem.sqlId;
                });

                if (searchResultWasSelected) {
                    uiContent.splice(index - uiContentIndexDifference, 1);

                    uiContentIndexDifference++;
                }
            });
        };

        self.clearSearchResultsFromSelectedClassSpecifications = function(event, ui) {
            self.clearSearchResultsFromSelectedItems(ui.content, self.selectedClassSpecifications);
        };

        self.addAutocompleteLabelsToSearchComponentForSelectedClassSpecifications = function() {
            self.selectedClassSpecifications().forEach(function(selectedItem) {
                var removeSelectedAutocompleteLabelCallback = function() {
                    self.selectedClassSpecifications.remove(selectedItem);
                };

                OnlineApp.Helpers.textSearchWithAutocompleteLabelsComponentHelper
                    .addSelectedAutocompleteLabelToSearchComponent(
                        selectedItem.text,
                        classSpecificationsSearchComponentSelector,
                        removeSelectedAutocompleteLabelCallback,
                        'Class Specification',
                        classSpecificationsSearchFieldSelector);
            });
        };

        self.validate = function() {
            var isValid = self.selectedClassSpecifications().length;

            if (!isValid) {
                var appliedClassSpecificationsCodes = self.getClassSpecificationsCodesFromQueryString();

                if (appliedClassSpecificationsCodes && appliedClassSpecificationsCodes.length) {
                    isValid = true;

                    self.updateFieldErrorState(
                        self.classSpecificationsSearchString,
                        false);
                } else {
                    self.updateFieldErrorState(
                        self.classSpecificationsSearchString,
                        true,
                        OnlineApp.Validation.validationMessages.invalidClassSpecificationsSearchString + $("#filter-title").text());
                }
            } else {
                self.updateFieldErrorState(
                    self.classSpecificationsSearchString,
                    false);
            }

            return isValid;
        };
    }

    namespace('AgencyPages').classSpecificationsFilterCategoryViewModel = new ClassSpecificationsFilterCategoryViewModel();
})(window);
;
(function (window, undefined) {

    var TRANSITION_END_EVENT_NAMES = 'webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd';

    var isTransitionEventSupported = gJobs.isTransitionEventSupported && gJobs.isTransitionEventSupported();

    var $body = $('body');

    var defaults = {
        showOverlay: true,
        disableBodyScroll: true,
        content: $('<div/>'),
        container: $body,
        wrapperClass: '',
        pageContentSelector: '#sizer',
        closeButton: false
    };

    var ACTIVE_CLASS = 'active',
        FIXED_CLASS = 'fixed',
        HIDE_CLASS = 'hide';

    var flyoutTransitionClasses = [HIDE_CLASS, { name: ACTIVE_CLASS, causingTransition: true }];

    var setBodyScrollable = function (scrollable) {
        $body.toggleClass('inner-scrollbar', !scrollable);

        var getScrollbarWidth = function () {
            var parent, child, width;

            parent = $('<div style="width:50px; height:50px; overflow:auto"><div/></div>').appendTo($body);
            child = parent.children();
            width = child.innerWidth() - child.height(99).innerWidth();
            parent.remove();

            return width;
        };

        // Add padding right to handle contents to stay at its original place
        // in Windows and Firefox in Mac when hiding the scrollbar.
        //But fixed elements are not affected by this padding, so apply padding to them explicitly
        var fixedElementsSelector = '.search-field-fixed #manage-bar';
        if (scrollable) {
            $body.add(fixedElementsSelector).css('padding-right', 0);
        } else {
            $body.add(fixedElementsSelector).css('padding-right', getScrollbarWidth());
        }
    };

    function FlyoutSizeService(flyout, pageContentSelector) {
        var self = this;

        var maximizeClass = 'maximized';

        self.maximize = function () {
            flyout.$wrapper.addClass(maximizeClass);
        };

        self.restoreDown = function () {
            flyout.$wrapper.removeClass(maximizeClass);
        };

        self.isMaximized = function () {
            return flyout.$wrapper.hasClass(maximizeClass);
        };
    };

    var flyoutConstructor = function (options) {

        var self = this;
        var $mainContainer = $('[role="main"]');

        options = $.extend({}, defaults, options);

        var flyoutWrapperClasses = 'flyout ' + HIDE_CLASS;
        var $flyoutWrapper = $('<div/>').addClass(flyoutWrapperClasses);
        if (options.wrapperClass) {
            $flyoutWrapper.addClass(options.wrapperClass);
        }
        if (options.role) {
            $flyoutWrapper.attr('role', options.role);
        }
        options.content.appendTo($flyoutWrapper);
        var flyoutSizeService = new FlyoutSizeService(self, options.pageContentSelector);

        $flyoutWrapper.appendTo(options.container);

        if (options.disableBodyScroll) {
            $flyoutWrapper.addClass(FIXED_CLASS);
        }

        if (options.showOverlay) {
            var $flyoutOverlayClasses = 'flyout-overlay';
            let $wrapperClassSpecificOverLay = '';
            if (options.wrapperClass) {
                $wrapperClassSpecificOverLay = options.wrapperClass + '-overlay';
            }
            var $flyoutOverlay = $('<div/>').addClass($flyoutOverlayClasses).addClass($wrapperClassSpecificOverLay);
            $body.append($flyoutOverlay);
            self.$overlay = $flyoutOverlay;
        }

        if (options.closeButton) {

            var closeButtonAriaLabel = options.closeButtonAriaLabel
                ? options.closeButtonAriaLabel
                : 'Close';

            var $closeButton = $('<button type="button" class="close-button ss-delete" aria-label="' +
                closeButtonAriaLabel + '">' +
                '<span class="hide symbol-label">' +
                'Close' +
                '</span>' +
                '</button>');

            $flyoutWrapper.find('[class*="flyout-header"]').first().append($closeButton);
            self.$closeButton = $closeButton;
        }

        var isOpen = false;

        self.isOpen = function () {
            return isOpen;
        };

        self.open = function ($focusTarget) {
            if (isOpen) {
                return;
            }

            OnlineApp.Services.tabIndexService.disableTabIndex();

            if (options.disableBodyScroll) {
                setBodyScrollable(false);
            }

            $flyoutWrapper.toggleClassSequence(flyoutTransitionClasses);

            if (options.showOverlay) {
                $flyoutOverlay.toggleClass(ACTIVE_CLASS, true);
            }

            $body.addClass('scroll-disable');

            isOpen = true;

            //disable body scrolling
            AgencyPages && AgencyPages.bodyScrollingAdjustmentService &&
                AgencyPages.bodyScrollingAdjustmentService.disableBodyScrolling();

            gJobs.focusService.enableFocusForBrowserControls();

            if ($focusTarget) {
                gJobs.focusService.setFocus($focusTarget);
            }

            $('#main-container').children().each(function () {
                $(this).attr('aria-hidden', 'true');
            });
            $('.search-results-grid-container').attr('aria-hidden', 'true');
            $('.search-results-grid-container').attr('tabindex', '-1');
            $('.search-results-grid-container').children().each(function () {
                $(this).attr('aria-hidden', 'true');
                $(this).attr('tabindex', '-1');
            });

            $('.cookie-link, .accept-use-of-cookies').attr('aria-hidden', true);

            $mainContainer.removeAttr('role');
            self.$wrapper.attr('role', 'main');

            $(document).trigger(Events.CommonEventsNames.ShowFlyout, Areas.AreaNames.careerPages);
        };

        self.maximize = function () {
            flyoutSizeService.maximize();
        };

        self.restoreDown = function () {
            flyoutSizeService.restoreDown();
        };

        self.close = function (closeOptions) {
            if (!isOpen) {
                return;
            }
            if ($("#header-menu-action") && $("#header-menu-action").length > 0) {
                $("#header-menu-action").attr("aria-hidden", "true");
            }
            $('#main-container').children().each(function () {
                $(this).attr('aria-hidden', 'false');
            });

            $('.search-results-grid-container').attr('aria-hidden', 'false');
            $('.search-results-grid-container').attr('tabindex', '0');
            $('.search-results-grid-container').children().each(function () {
                $(this).attr('aria-hidden', 'false');
                $(this).attr('tabindex', '0');
            });

            if (!closeOptions || !closeOptions.preventTriggerCloseEvent) {
                $(document).trigger(Events.CommonEventsNames.FlyoutClosing);
            }

            if (flyoutSizeService.isMaximized()) {
                flyoutSizeService.restoreDown();
            }

            $flyoutWrapper.toggleClassSequence(flyoutTransitionClasses, true);

            OnlineApp.Services.tabIndexService.restoreTabIndex();

            if (options.showOverlay) {
                $flyoutOverlay.toggleClass(ACTIVE_CLASS, false);
            }
            if (options.disableBodyScroll) {
                setBodyScrollable(true);
            }

            $body.removeClass('scroll-disable');

            isOpen = false;

            $('.cookie-link, .accept-use-of-cookies').attr('aria-hidden', false);

            self.$wrapper.removeAttr('role');   
            $mainContainer.attr('role', 'main');

            //enable body scrolling
            AgencyPages && AgencyPages.bodyScrollingAdjustmentService &&
                AgencyPages.bodyScrollingAdjustmentService.enableBodyScrolling();

            gJobs.focusService.restoreBrowserControlsFocusBehavior();
            gJobs.focusService.restoreFocus({
                focusRestoringCallback: function ($restoringElement) {
                    var activePageMessage = $('#page-title').text() + ' page is active.';
                    var flyoutCloseMessage = 'Flyout has been closed. ' + activePageMessage;
                    gJobs.screenReadersService.onceNotification({
                        $element: $restoringElement,
                        message: flyoutCloseMessage
                    });
                }
            });

            if (options && $.isFunction(options.closeFlyoutCallback)) {
                options.closeFlyoutCallback();
            }
        };

        self.showClassSpec = function (id) {

            if (arguments.length == 1) { //arguments may be passed also as a single object
                var argumentsObject = arguments[0];
                id = argumentsObject.id;
            }

            self.open(this.$wrapper.find(".opened-notification"));
            gJobs.skipToContentService.showOnNextTab();
        }

        if (options.showOverlay) {
            $flyoutOverlay.click(self.close);
        }
        if (options.closeButton) {
            self.$closeButton.on('touchstart click', self.close);
        }

        self.$wrapper = $flyoutWrapper;

    };

    namespace('AgencyPages').Flyout = flyoutConstructor;
    window.Flyout = flyoutConstructor; //for compatibility only, todo: check usages and remove it completely

})(window);;
(function (window, AgencyPages, undefined) {

    var JOB_DETAILS_TAB = 1;
    var APPLY_TAB = 2;
    var KeyboardCodes = {
        ENTER: 13,
        ESCAPE: 27,
        PAGEUP: 33,
        PAGEDOWN: 34
    };
    var JOBSOURCE_JOBBOARD = 1; // JobSource enum value for JobBoard, used in job hits counter service

    var $body = $('body');

    //todo: declare all selectors as constants

    var CachedJobInfoSource = function () {
        var jobInfoEndpoint = '/careers/jobInfo/agencyJobDetails/';
        var self = this;

        var cache = {};

        self.isCached = function(id) {
            return !!cache[id];
        };

        self.get = function (id, departmentFolderName) {
            if (cache[id]) {
                return (new $.Deferred()).resolve(cache[id]).promise();
            } else {
                var departmentQuery = departmentFolderName ? '?departmentFolder=' + departmentFolderName : '';
                var isSubmittedApplicationPageQuery = departmentFolderName ? '&isSubmittedApplicationPage=false' : '?isSubmittedApplicationPage=false';
                return $.ajax({
                    url: jobInfoEndpoint + id + departmentQuery + isSubmittedApplicationPageQuery,
                    type: 'GET',
                    cache: false
                }).done(function (data) {
                    cache[id] = data;
                });
            }
        };
    };

    var AgencyPagesRouterHelper = function () {
        var self = this;

        var pageInfoService = namespace('AgencyPages').pageInfoService;
        var pageTypes = pageInfoService.getPageTypes();
        var currentPageType = pageInfoService.getCurrentPageType();
        var initialUrl = pageInfoService.getCurrentInitialUrl();
        initialUrl = currentPageType.type === pageTypes.applications.type ? initialUrl + '/incomplete' : initialUrl;

        var jobUrl = '';

        function getInitialUrl() {
            var fullUrl = namespace('AgencyPages').router.addQueryString(initialUrl);
            fullUrl = namespace('AgencyPages').router.removePageTypeFromQuery(fullUrl);
            return fullUrl;
        }

        self.setJobUrl = function(url) {
            jobUrl = url.replace(/\/apply(.+)?$/, '');
        }

        self.getJobUrl = function () {
            return jobUrl;
        };

        self.getApplyUrl = function () {
            return self.getJobUrl() + '/apply';
        };

        self.closeFlyout = function () {
            namespace('AgencyPages').router.navigate(getInitialUrl(), true, false, null, null);
        };

        self.navigateToJob = function (title, id, tab) {
            var url = tab === JOB_DETAILS_TAB ? self.getJobUrl() : self.getApplyUrl();

            namespace('AgencyPages').router.navigate(url, true, false, null, {
                title: title,
                id: id,
                tab: tab
            }, true);
        };
    };

    function setGoogleAnalyticsJobInfo(jobTitle) {
        if (AgencyPages && AgencyPages.pageInfoService) {
            var applicationsPageType = AgencyPages.pageInfoService.getPageTypes().applications;
            var currentPageType = AgencyPages.pageInfoService.getCurrentPageType();
            if (currentPageType && currentPageType.type === applicationsPageType.type) {
                var onlineApplicationLink = $('#online-application-link');
                var jobDepartment = onlineApplicationLink.data('job-department');
                if (jobDepartment && jobTitle) {
                    gJobs.common.analytics.setProperties({
                        properties: {
                            dimension8: jobTitle,
                            dimension9: jobDepartment
                        },
                        sendToAllTrackers: true
                    });
                }
            }
        }
    }

    var jobFlyoutConstructor = function (options) {

        //todo: a more generic approach will be used
        var content = options.content || $('#job-flyout-content');

        var self = window.Flyout.call(this, {
            showOverlay: true,
            disableBodyScroll: true,
            container: $body,
            content: content,
            closeButton: true,
            disableDefaultEscapeHandler: true,
            //todo: rename to job-flyout, also in agency specific razor-generated css
            wrapperClass: 'new-job-flyout flyout-window', //flyout-window class is required for OnlineApp to know that it is loaded inside a flyout
        }) || this;

        var $mainContainer;
        var jobListAdapter = options.jobListAdapter; //if null, navigation through jobs will be disabled
        self.jobInfoSource = new CachedJobInfoSource(); //may be taken from options if needed for customization
        var routerHelper = options.routerHelper || new AgencyPagesRouterHelper();

        //try close online app correctly (with confirmation popup) and execute callback if user confirms close
        var tryCloseOnlineAppAndDo = function (callback) {

            if (self.isOnlineAppLoaded() && self.isAppLoaded) {
                //OnlineApp first listens to TryCloseFlyout event to show the confirmation, and when the user confirms, CloseFlyout is fired

                var tryCloseEvent = $.Event(Events.CommonEventsNames.TryCloseFlyout);
                tryCloseEvent.canRaiseEvent = true;
                tryCloseEvent.callbackEventName = Events.CommonEventsNames.CloseFlyout;

                //to be sure that online app is open
                routerHelper.navigateToJob(self.activeJobTitle, self.activeJobId, APPLY_TAB);

                $(document).trigger(tryCloseEvent);

                if (tryCloseEvent.canRaiseEvent) {
                    callback();
                } else {
                    $(document).one(Events.CommonEventsNames.CloseFlyout, function () {
                        self.activeOnlineAppId = null; //mark Online App as unloaded
                        callback();
                    });
                }
            } else {
                callback();
            }
        };

        var navigateToPreviousJob = function () {
            if (jobListAdapter && jobListAdapter.hasPreviousJob(self.activeJobId)) {
                tryCloseOnlineAppAndDo(function () {
                    jobListAdapter.getPreviousJob(self.activeJobId);
                    gJobs.skipToContentService.showOnNextTab();
                    routerHelper.setJobUrl(location.pathname);
                });
            }
        };

        var navigateToNextJob = function () {
            if (jobListAdapter && jobListAdapter.hasNextJob(self.activeJobId)) {
                tryCloseOnlineAppAndDo(function () {
                    jobListAdapter.getNextJob(self.activeJobId);
                    gJobs.skipToContentService.showOnNextTab();
                    routerHelper.setJobUrl(location.pathname);
                });
            }
        };

        var keyUpHandler = function (event) {
            if (self.activeTab !== APPLY_TAB) {
                if (event.keyCode === KeyboardCodes.PAGEUP) {
                    navigateToPreviousJob();
                } else if (event.keyCode === KeyboardCodes.PAGEDOWN) {
                    navigateToNextJob();
                }
            }
        };

        var loadOnlineApp = function () {
            var applicationLoader = AgencyPages.applicationLoader;

            applicationLoader.getListOfOnlineApplicationScriptsAsync()
                .then(applicationLoader.loadScriptsFromListAsync)
                .then(applicationLoader.initOnlineApplication);

            self.isAppLoaded = true;
        };

        self.activeJobId = null;
        self.activeJobTitle = null;
        self.activeTab = null;
        self.activeOnlineAppId = null;
        self.isAppLoaded = false;

        var baseOpen = self.open;
        self.open = function ($focusTarget) {
            if (self.isOpen()) {
                return;
            }

            $mainContainer = $('[role="main"]').not(self.$wrapper);
            $mainContainer.removeAttr('role');            

            routerHelper.setJobUrl(location.pathname);
            baseOpen($focusTarget);
            $(document).on('keyup', keyUpHandler);
            self.$wrapper.on(Events.CommonEventsNames.FlyoutClosing, reinitializeKeyUpHandler);
        };

        var baseClose = self.close;
        self.close = function () {
            if (!self.isOpen()) {
                return;
            }

            self.$wrapper.removeAttr('role');
            $mainContainer.attr('role', 'main');

            baseClose();
            $(document).trigger(Events.CommonEventsNames.CloseFlyout);
            $(document).off('keyup', keyUpHandler);
            self.$wrapper.off(Events.CommonEventsNames.FlyoutClosing, reinitializeKeyUpHandler);
            self.activeTab = null;

            if ($openedNotification) {
                gJobs.screenReadersService.clearNotification($openedNotification);
            }
            if ($loadedNotification) {
                gJobs.screenReadersService.clearNotification($loadedNotification);
            }
        };

        self.isOnlineAppLoaded = function () {
            return self.activeJobId !== null && self.activeJobId === self.activeOnlineAppId;
        };

        var $applyButton = self.$wrapper.find('.flyout-switch-button');
        var $jobApplyTabHeader = self.$wrapper.find('.job-apply-tab .job-flyout-header');
        var $jobApplyTabHeaderUserInfoContainer = $jobApplyTabHeader.find('.user-info-container');
        var $onlineAppJobDetailsButton = $jobApplyTabHeader.find('.job-details-link-container');
        var $jobFlyoutFooter = self.$wrapper.find('.job-flyout-footer');

        $jobApplyTabHeader
            .find('.close-button')
            .add(self.$closeButton)
            .off('touchstart click')
            .click(function () {
                tryCloseOnlineAppAndDo(self.close);
            });

        self.$overlay.off('click').click(function () {
            tryCloseOnlineAppAndDo(self.close);
        });

        $applyButton.click(function (event) {
            routerHelper.navigateToJob(self.activeJobTitle, self.activeJobId, APPLY_TAB);
            event.preventDefault();
        });

        $onlineAppJobDetailsButton.click(function () {
            OnlineApp &&
                OnlineApp.ViewModels &&
                OnlineApp.ViewModels.applicationViewModel &&
                OnlineApp.ViewModels.applicationViewModel.showJobDetails &&
                OnlineApp.ViewModels.applicationViewModel.showJobDetails();

            $(document).off('keyup', keyUpHandler);
            applyTabSettings();
        });

        $onlineAppJobDetailsButton.keypress(function (event) {
            if (event.keyCode === KeyboardCodes.ENTER) {
                $onlineAppJobDetailsButton.click();
                applyTabSettings();
                event.preventDefault();
            }
        });

        function applyTabSettings() {
            let tablists = document.querySelectorAll('[role=tablist]');
            for (let i = 0; i < tablists.length; i++) {
                new TabsManual(tablists[i]);
            }
            let desc_li = $('.description');
            let questions_li = $('.questions');
            let benefits_li = $('.benefits');
            let descButton = $('#description');
            let benefitsButton = $('#benefits');
            let questionsButton = $('#questions');
            if (desc_li) {
                let isDescActive = desc_li.hasClass('active');
                if (isDescActive == true) {
                    descButton.attr('tabindex', '0');
                    questionsButton.attr('tabindex', '-1');
                    benefitsButton.attr('tabindex', '-1');
                }
            }
            if (benefits_li) {
                let isBenefitsActive = benefits_li.hasClass('active');
                if (isBenefitsActive == true) {
                    descButton.attr('tabindex', '-1');
                    questionsButton.attr('tabindex', '-1');
                    benefitsButton.attr('tabindex', '0');
                }
            }
            if (questions_li) {
                let isQuestionsActive = questions_li.hasClass('active');
                if (isQuestionsActive == true) {
                    descButton.attr('tabindex', '-1');
                    questionsButton.attr('tabindex', '0');
                    benefitsButton.attr('tabindex', '-1');
                }
            }
        }

        function reinitializeKeyUpHandler(e) {
            e.stopPropagation();
            $(document)
            .off('keyup', keyUpHandler)
            .on('keyup', keyUpHandler);
        }

        self.$wrapper.on('click', '.prev-posting', navigateToPreviousJob);

        self.$wrapper.on('click', '.next-posting', navigateToNextJob);

        $(document).on(Events.CommonEventsNames.CloseFlyout, function () {
            routerHelper.closeFlyout();
            self.activeOnlineAppId = null;
        });

        var $addthisToolbox = self.$wrapper.find('.addthis_toolbox'),
            $flyoutHeader = self.$wrapper.find('.flyout-header'),
            $openedNotification = self.$wrapper.find('.opened-notification'),
            $loadedNotification = self.$wrapper.find('.loaded-notification'),
            $spinner = self.$wrapper.find('.flyout-spinner');

        var $scrollableContainer = self.$wrapper.find('.entity-info');

        AgencyPages.scrollableContainerAdjuster.addHeaderShadowOnScrolling($scrollableContainer);

        var $jobDetailsTab = self.$wrapper.find('.entity-details-tab');
        var $jobApplyTab = self.$wrapper.find('.job-apply-tab');

        self.showJob = function (title, id, tab) {
            if (arguments.length == 1) { //arguments may be passed also as a single object
                var argumentsObject = arguments[0];
                title = argumentsObject.title;
                id = argumentsObject.id;
                tab = argumentsObject.tab;
            }

            if (id == undefined && self.activeJobId !== null) {
                id = self.activeJobId;
            }
            if (title == undefined && self.activeJobTitle !== null) {
                title = self.activeJobTitle;
            }
            if (tab === undefined) {
                tab = JOB_DETAILS_TAB;
            }

            if (id === self.activeJobId && tab === self.activeTab) {
                //nothing changed
                return;
            }

            $flyoutHeader.removeClass('highlight-bottom');

            self.activeJobId = id;
            self.activeTab = tab;
            self.activeJobTitle = title;

            self.open();

            if (tab === JOB_DETAILS_TAB) {
                var $jobInfoContainer = self.$wrapper.find('.entity-info').empty();
                $spinner.removeClass('hide');

                $jobDetailsTab.addClass('active');
                $jobApplyTab.removeClass('active');

                //hide/show posting navigation buttons if a list adapter was passed in constructor
                if (jobListAdapter) {
                    if (jobListAdapter.hasPreviousJob(id)) {
                        self.$wrapper.find('.prev-posting')
                            .removeClass('disable')
                            .removeAttr('tabindex aria-disabled');
                    } else {
                        self.$wrapper.find('.prev-posting')
                            .addClass('disable')
                            .attr({'tabindex': '-1', 'aria-disabled': 'true'});
                    }

                    if (jobListAdapter.hasNextJob(id)) {
                        self.$wrapper.find('.next-posting')
                            .removeClass('disable')
                            .removeAttr('tabindex aria-disabled');
                    } else {
                        self.$wrapper.find('.next-posting')
                            .addClass('disable')
                            .attr({'tabindex': '-1', 'aria-disabled': 'true'});
                    }
                }

                gJobs.screenReadersService.setNotification($openedNotification, title, ' is loading', true, true);

                //init header popovers
                if (!window.enableShareThis) {
                    $flyoutHeader.find('a[data-toggle="popover"]').popover({ html: true });
                } else {
                    $flyoutHeader.find('button[data-toggle="popover"]').popover({ html: true });
                }

                var departmentFolderName = namespace('AgencyPages').pageInfoService.getCurrentDepartmentFolderName();
                self.jobInfoSource.get(id, departmentFolderName).done(function (data) {
                    $jobInfoContainer.html(data);
                    $spinner.addClass('hide');

                    // Add job title and navigation status to notification message for screen readers.
                    gJobs.screenReadersService.setNotification($loadedNotification, title, ' flyout has been opened', true);
                    jobListAdapter.resetJobNavigationStatus();
                    self.$wrapper.find('.entity-info').find('a').attr('tabindex','0');
                    //initialize salary and location popovers
                    $jobInfoContainer.find('span[data-toggle="popover"]').popover({ html: true });
                    $jobInfoContainer.find('a[data-toggle="popover"]').popover({ html: true });
                    //set print button href
                    var printingUrl = $jobInfoContainer.find('.summary').data('printing-url');
                    self.$wrapper.find('a.print-button').attr('href', printingUrl);

                    //try to call job hits counter service
                    let jobId = $jobInfoContainer.find('.summary').data('job-id');
                    let jobSource = $jobInfoContainer.find('.summary').data('job-source');

                    if (jobId && jobSource == JOBSOURCE_JOBBOARD) {                        
                            $.ajax({
                                type: 'GET',
                                url: '/jobInfo/IncreaseHitsJobCount/' + jobId,
                                async: true
                            });                        
                    }

                    //initialize social buttons
                    var jobLocation = $jobInfoContainer.find('.summary').data('location');
                    var jobUrl = namespace('AgencyPages').router.cutQueryString(History.getState().url);
                    if ($addthisToolbox)
                        gJobs.common.social.init($addthisToolbox, title, jobUrl, jobLocation);

                    //ONLINE-1356: Firefox restores scroll position of the flyout which is not desired behavior
                    $scrollableContainer.scrollTop(0);

                    gJobs.accessibilityHtmlTransformer.makeElementContentAccessible($('.entity-details-content'));

                    //clear job detais tab to prevent id duplications with online app job details flyout
                    self.$wrapper.find('.job-apply-tab .entity-info').empty();
                    applyTabSettings();
                   
                });

                if (!self.isOnlineAppLoaded() && id) {
                    self.isAppLoaded = false;

                    $applyButton.addClass('hidden');
                    $jobFlyoutFooter.addClass('hidden');

                    var $onlineapp = self.$wrapper.find('.onlineapp').empty();

                    var parameters = self.jobInfoSource.isCached(id)
                        ? '?registerHit=true'
                        : '';

                    $.ajax({
                        url: AgencyPages.router.routePrefix + '/jobInfo/agencyApply/' + id + '/' + parameters,
                        type: 'GET',
                        cache: false,
                        success: function (data) {
                            if (data) {
                                $onlineapp.html(data);
                                const jobDetails = document.querySelector("#online-application-link");
                                var isApplyVisible = jobDetails.dataset.isapplyvisible;
                                if (isApplyVisible === "True") {
                                    $applyButton.removeClass('hidden');
                                }
                                $jobFlyoutFooter.removeClass('hidden');
                            }
                        }
                    });

                    self.activeOnlineAppId = id;
                }

                if (id) {
                    var $freeSubscriptionApply = self.$wrapper
                        .find('.free-subscription-apply')
                        .addClass('hidden');

                    $.ajax({
                        url: AgencyPages.router.routePrefix + '/jobInfo/liteAgencyApply/' + id,
                        type: 'GET',
                        cache: false,
                        success: function (data) {
                            if (data) {
                                $freeSubscriptionApply
                                    .html(data)
                                    .removeClass('hidden');
                            }
                        }
                    });
                }

            } else if (tab === APPLY_TAB) {
                $jobDetailsTab.removeClass('active');
                $jobApplyTab.addClass('active');
                self.maximize();

                $(document).trigger(OnlineApp.Events.CommonEventsNames.ApplyTabOpened);

                $jobApplyTabHeader.find('.entity-title').text(title);
                $jobApplyTabHeader.find('.entity-title').prop('title', title);

                var $jobApplyTabHeaderUserInfo = $jobApplyTabHeaderUserInfoContainer
                    .find('.applying-username-verbiage, .username, .delimiter');

                var applyNotification = $('#job-flyout-content .job-apply-tab, #incomplete-application-flyout-content .job-apply-tab').data('selected-notification');
                var signinFormNotification = ' Sign in form is opened';

                $jobApplyTabHeaderUserInfo.addClass('hide');
                OnlineApp.Services.authenticationService.isLoggedIn().done(function (data) {
                    if (data) {
                        $jobApplyTabHeaderUserInfo.removeClass('hide');
                    } else {
                        $(document).one(OnlineApp.Events.CommonEventsNames.Login, function () {
                            $jobApplyTabHeaderUserInfo.removeClass('hide');
                        });
                        applyNotification += signinFormNotification;

                        gJobs.common.analytics.trackVirtualPageView({
                            page: 'login',
                            title: 'Job Opportunities | ' + self.activeJobTitle + '| LogIn',
                            sendToAllTrackers: true
                        });

                        $(document).one(OnlineApp.Events.CommonEventsNames.RegisterAccountLinkClicked, function () {
                            gJobs.common.analytics.trackVirtualPageView({
                                page: 'create-account',
                                title: 'Job Opportunities | ' + self.activeJobTitle + '| Create Account',
                                sendToAllTrackers: true
                            });
                        });
                    }
                    gJobs.screenReadersService.setAriaLiveNotification(applyNotification);
                });

                if (!self.isOnlineAppLoaded() && id) {
                    self.isAppLoaded = false;
                    self.$wrapper.find('.onlineapp').empty().load(
                        AgencyPages.router.routePrefix + '/jobInfo/agencyApply/' + id, function () {
                            loadOnlineApp();
                            setGoogleAnalyticsJobInfo(title);
                        });
                    self.activeOnlineAppId = id;
                } else if (self.isOnlineAppLoaded() && !self.isAppLoaded) {
                    loadOnlineApp();
                    setGoogleAnalyticsJobInfo(title);
                }

                //clear job detais tab to prevent id duplications with online app job details flyout
                self.$wrapper.find('.entity-info').empty();
            }
        };
    };

    namespace('AgencyPages').JobFlyout = jobFlyoutConstructor;
    //todo: remove export to the global object after checking dependencies across the project
    window.JobFlyout = jobFlyoutConstructor;

})(window, AgencyPages);;
(function (window, undefined) {

    var pageInfoService = namespace('AgencyPages').pageInfoService;
    var customLabels = namespace('AgencyPages').customLabels;
    var customLabelService = namespace('gJobs').customLabelService;

    var classSpecificationsFilterCategoryTitle = 'CLASS SPECIFICATIONS',
        classSpecificationsFilterCategoryViewModel = null,
        classSpecificationsFilterCategoryContainerSelector = '#class-specifications-filters-category',
        applyClassSpecificationsFilterCategoryButtonSelector = '.apply-class-specifications-filter-category-button',
        classSpecificationsSearchComponentSelector = '.class-specs-search-with-autocomplete-labels-component',
        selectedSearchLabelSelector = '.selected-search-label-container',
        getClassSpecificationsDetailsByCodesUrl = AgencyPages.routePrefix + '/ClassSpecifications/GetClassSpecsDetailsByIds',
        mobileApplyFilterButtonSelector = '.device-phone .flyout.new-filter-flyout .filter-flyout-container .apply-button';

    var SortByPanel = {
        KEY: 1,
        OPTIONS: {
            TITLE: 'Sort by',
            ICON_CLASS: 'icon icon-xs icon-sort-amount-desc',
            DESCRIPTION: 'Please select one of the following'
        }
    };

    var FilterPanel = {
        KEY: 2,
        OPTIONS: {
            TITLE: 'Filter',
            ICON_CLASS: 'icon icon-xs icon-filter',
            DESCRIPTION: ''
        }
    };

    var FilterCategory = {
        KEY: 3,
        OPTIONS: {
            LOCATION: {
                TITLE: 'Location',
                FILTER: 'location',
                TYPE: 'lowercaseLocation',
                SUPPORTS_MULTI_CHOICE: true,
                DESCRIPTION: ''
            },
            DEPARTMENT: {
                TITLE: (customLabels.Department && customLabels.Department.SingularLabel) || 'Department',
                FILTER: 'department',
                TYPE: 'department',
                SUPPORTS_MULTI_CHOICE: true,
                DESCRIPTION: ''
            },
            'JOB CATEGORY': {
                TITLE: 'Job Category',
                FILTER: 'category',
                TYPE: 'category',
                SUPPORTS_MULTI_CHOICE: true,
                DESCRIPTION: ''
            },
            'JOB TYPE': {
                TITLE: 'Job Type',
                FILTER: 'jobType',
                TYPE: 'jobType',
                SUPPORTS_MULTI_CHOICE: true,
                DESCRIPTION: ''
            },
            SALARY: {
                TITLE: 'Estimated Annual Salary',
                MOBILE_TITLE: 'Est. Annual Salary',
                FILTER: 'salary',
                TYPE: 'salary',
                DESCRIPTION: 'Please select one of the following'
            },
            'EXAM TYPE': {
                TITLE: 'Exam Type',
                FILTER: 'examType',
                TYPE: 'examType',
                SUPPORTS_MULTI_CHOICE: true,
                DESCRIPTION: ''
            },
            'REMOTE': {
                TITLE: 'Remote',
                FILTER: 'remoteworkoptionids',
                TYPE: 'remote',
                DESCRIPTION: '',
                SUPPORTS_MULTI_CHOICE: true
            },
            'CLASS SPECIFICATIONS': {
                TITLE: (customLabels.ClassSpecification && customLabels.ClassSpecification.SingularLabel) || 'Class Specifications',
                FILTER: 'classspecificationscodes',
                TYPE: 'classspecifications',
                DESCRIPTION: '',
                SUPPORTS_MULTI_CHOICE: true
            }
        }
    };

    var Pages = {
        JOB_OPPORTUNITIES: {
            SORT_PANEL_SOURCE: '/Areas/AgencyPages/Views/Templates/FilterOptions/JobOpportunities/SortByPanel.html',
            FILTER_PANEL_SOURCE: AgencyPages.routePrefix + '/FilterFlyout/GetFiltersPanel',
            FILTER_CATEGORY_ENDPOINT: AgencyPages.routePrefix + '/FilterFlyout/GetFiltersCategories',
            TRIGGERED_EVENT_PREFIX: 'SearchPage',
            shouldPassQueryStringToRetrieveFilterPanel: true
        },

        CLASS_SPECIFICATION: {
            SORT_PANEL_SOURCE: '/Areas/AgencyPages/Views/Templates/FilterOptions/ClassSpecifications/SortByPanel.html',
            FILTER_PANEL_SOURCE: '/Areas/AgencyPages/Views/Templates/FilterOptions/ClassSpecifications/FilterPanel.html',
            FILTER_CATEGORY_ENDPOINT: AgencyPages.routePrefix + '/ClassSpecifications/GetFiltersCategories',
            TRIGGERED_EVENT_PREFIX: 'ClassSpecificationsPage'
        },

        APPLICATIONS: {
            SORT_PANEL_SOURCE: '/Areas/AgencyPages/Views/Templates/FilterOptions/Applications/SortByPanel.html',
            TRIGGERED_EVENT_PREFIX: 'ApplicationsPage'
        }

    };

    var currentConfig;

    var $body = $('body'),
        $flyoutOverlay = $('.filter-flyout-overlay');

    var filters = {
        location: [],
        department: [],
        category: [],
        salary: null,
        examType: [],
        jobType: [],
        remoteworkoptionids: [],
        classspecificationscodes: [],
    }

    var filterKeyword = null;

    var sortBy = null;

    var previousFilterValue = null;

    var filtersCategoriesData = null;

    var lastAppliedFilter = null;

    var FilterCategorySource = function () {
        var self = this;

        self.getData = function (currentFacetFilterFieldType) {
            var $def = $.Deferred();

            var params = '';
            var agencyFolderName = pageInfoService.getCurrentAgencyFolderName();
            var departmentFolderName = pageInfoService.getCurrentDepartmentFolderName();
            var filterCategoryUrl = currentConfig.FILTER_CATEGORY_ENDPOINT;

            if (agencyFolderName) {
                var filterOptions = FilterCategory.OPTIONS;
                params += '?agency=' + encodeURIComponent(agencyFolderName);

                if (filterKeyword) {
                    params += '&keyword=' + encodeURIComponent(filterKeyword);
                }

                if (departmentFolderName) {
                    params += '&departmentFolder=' + encodeURIComponent(departmentFolderName);
                }

                var i;

                if (filters.location.length) {
                    for (i = 0; i < filters.location.length; i++) {
                        params += '&facetlocation=' + encodeURIComponent(filters.location[i]);
                    }
                }

                if (filters.department.length) {
                    for (i = 0; i < filters.department.length; i++) {
                        params += '&department=' + encodeURIComponent(filters.department[i]);
                    }
                }

                if (filters.category.length) {
                    for (i = 0; i < filters.category.length; i++) {
                        params += '&category=' + encodeURIComponent(filters.category[i]);
                    }
                }

                if (filters.jobType.length) {
                    for (i = 0; i < filters.jobType.length; i++) {
                        params += '&jobType=' + encodeURIComponent(filters.jobType[i]);
                    }
                }


                if (filters.salary !== null && FilterCategory.OPTIONS.SALARY.TYPE != currentFacetFilterFieldType) {
                    params += '&salary=' + encodeURIComponent(filters.salary);
                }

                if (filters.remoteworkoptionid !== null && FilterCategory.OPTIONS.REMOTE.TYPE != currentFacetFilterFieldType) {
                    params += '&remoteworkoptionid=' + encodeURIComponent(filters.remoteworkoptionid);
                }

                if (filters.remoteworkoptionids && filters.remoteworkoptionids.length) {
                    for (i = 0; i < filters.remoteworkoptionids.length; i++) {
                        if (params != '?') {
                            params += '&';
                        }

                        params += 'remoteworkoptionids=' + encodeURIComponent(filters.remoteworkoptionids[i]);
                    }
                }

                if (filters.classspecificationscodes && filters.classspecificationscodes.length) {
                    for (i = 0; i < filters.classspecificationscodes.length; i++) {
                        if (params != '?') {
                            params += '&';
                        }

                        params += 'classspecificationscodes=' + encodeURIComponent(filters.classspecificationscodes[i]);
                    }
                }

                if (filters.examType.length) {
                    for (i = 0; i < filters.examType.length; i++) {
                        params += '&examType=' + encodeURIComponent(filters.examType[i]);
                    }
                }

                if (currentFacetFilterFieldType) {
                    params += '&currentFacetFilterFieldType=' + encodeURIComponent(currentFacetFilterFieldType);
                }

                if (isPromotionalJobs()) {
                    params += '&ispromotional=true';
                }

                if (isTransferJobs()) {
                    params += '&istransfer=true';
                }

                filterCategoryUrl += params;
                $flyoutOverlay.show();

                $.ajax({
                    url: filterCategoryUrl,
                    type: 'GET',
                    cache: false,
                }).done(function (data) {
                    filtersCategoriesData = data;
                    $flyoutOverlay.hide();
                    $def.resolve();
                });
            }

            return $def.promise();
        };
    };

    var FiltersPanelSource = function () {
        var self = this;

        var cache = {};

        self.getMarkup = function (panelType) {
            if (cache[panelType]) {
                return (new $.Deferred()).resolve(cache[panelType]).promise();
            } else {
                var getFiltersPanelUrl = panelType === FilterPanel.KEY ? currentConfig.FILTER_PANEL_SOURCE : currentConfig.SORT_PANEL_SOURCE;

                if (currentConfig.shouldPassQueryStringToRetrieveFilterPanel) {
                    var agencyFolderName = pageInfoService.getCurrentAgencyFolderName();
                    var departmentFolderName = pageInfoService.getCurrentDepartmentFolderName();
                    getFiltersPanelUrl += '?agency=' + encodeURIComponent(agencyFolderName);
                    if (departmentFolderName) {
                        getFiltersPanelUrl += '&departmentFolder=' + encodeURIComponent(departmentFolderName);
                    }

                    if (isPromotionalJobs()) {
                        getFiltersPanelUrl += '&ispromotional=true';
                    }

                    if (isTransferJobs()) {
                        getFiltersPanelUrl += '&istransfer=true';
                    }
                }

                return $.get(getFiltersPanelUrl, function (data) {
                    cache[panelType] = data;
                });
            }
        };
    };

    function mapRemoteFilterValueToRemoteOptionText(remoteFilterValue) {
        var remoteFilterMapper = {
            1: "Remote Only",
            2: "Remote Optional",
            3: "Flexible/Hybrid"
        };

        return remoteFilterMapper[remoteFilterValue];
    }

    var filterFlyoutConstructor = function (page) {
        var self = window.Flyout.call(this, {
            showOverlay: true,
            disableBodyScroll: true,
            container: $body,
            content: $('#filter-flyout-content'),
            wrapperClass: 'new-filter-flyout'
        }) || this;

        var $wrapper = self.$wrapper,
            $resetButton = $wrapper.find('.reset-button'),
            $closeButton = $wrapper.find('.close-button'),
            $applyButton = $wrapper.find('.filter-flyout-container .apply-button'),
            $headerTitle = $wrapper.find('.filter-title'),
            $mobileHeaderTitle = $wrapper.find('.filter-mobile-title'),
            $backButton = $wrapper.find('.back-button'),
            $icon = $wrapper.find('span.icon'),
            $headerDescription = $wrapper.find('.filter-description');

        var filterCategorySource = new FilterCategorySource(),
            filtersPanelSource = new FiltersPanelSource();

        var router = AgencyPages.router;

        var initialUrl = pageInfoService.getCurrentInitialUrl();

        var releaseFocus;

        currentConfig = Pages[page];


        $closeButton.click(function () {
            if ($backButton.is(":visible")) {
                $backButton.hide();
                $resetButton.show();

                self.updateHeader(FilterPanel.TITLE, FilterPanel.MOBILE_TITLE);
                self.showFilterPanel(FilterPanel.KEY);
                var closedMessage = filterCategoryTitle + ' filter category tab is closed. Filters flyout is active.';
                gJobs.screenReadersService.setNotification($notificationContainer, closedMessage, null, true, false);

                event.preventDefault();
            }
            else {
                var $skipToContentButton = $('#skip-to-content-button');
                $skipToContentButton.attr("tabindex", "0");
                self.close();
            }
        });
        $applyButton.click(function () {
            self.close();
        });

        $(document).on(Events.CommonEventsNames.JobsListLoaded + " " + Events.CommonEventsNames.ClassSpecsListLoaded, function (event, jobsCount) {
            if (!lastAppliedFilter) return;

            var filterValue = lastAppliedFilter.filterValue;
            if (lastAppliedFilter.filterType.toLowerCase() === FilterCategory.OPTIONS.REMOTE.TITLE.toLowerCase())
                filterValue = mapRemoteFilterValueToRemoteOptionText(filterValue);

            var filterStatus = lastAppliedFilter.isFilterValueAdded ? 'applied' : 'removed';
            var notificationText = filterValue + ' ' + lastAppliedFilter.filterType + ' filter is ' + filterStatus + '. ';
            notificationText += jobsCount + ' jobs loaded';
            gJobs.screenReadersService.readPageTitle($('[data-filter-value="' + lastAppliedFilter.filterValue + '"]').closest('.selectable-item-container'), notificationText);
        });

        function getChangedFiltersCount() {
            var changedFiltersCount = 0;

            for (var propertyName in filters) {
                for (var categoryPropertyName in FilterCategory.OPTIONS) {
                    if (FilterCategory.OPTIONS[categoryPropertyName].FILTER === propertyName) {
                        if (!!FilterCategory.OPTIONS[categoryPropertyName].SUPPORTS_MULTI_CHOICE) {
                            changedFiltersCount += filters[propertyName].length;
                        } else {
                            if (filters[propertyName] !== null) {
                                changedFiltersCount++;
                            }
                        }
                    }
                }
            }

            return changedFiltersCount;
        }

        function applyClassSpecificationsFilter() {
            if (classSpecificationsFilterCategoryViewModel) {
                if (!classSpecificationsFilterCategoryViewModel.validate()) return;

                var filterQueryParamName = FilterCategory.OPTIONS[classSpecificationsFilterCategoryTitle].FILTER;

                var selectedClassSpecificationsCodes = classSpecificationsFilterCategoryViewModel.getSelectedClassSpecificationsCodes();

                filters[filterQueryParamName] = selectedClassSpecificationsCodes;

                lastAppliedFilter = {
                    filterType: FilterCategory.OPTIONS[classSpecificationsFilterCategoryTitle].TITLE
                };

                if (selectedClassSpecificationsCodes && selectedClassSpecificationsCodes.length) {
                    var selectedClassSpecificationsTitles = classSpecificationsFilterCategoryViewModel
                        .selectedClassSpecifications().map(function (selectedItem) {
                            return selectedItem.text;
                        })
                        .join();

                    lastAppliedFilter.filterValue = selectedClassSpecificationsTitles;
                    lastAppliedFilter.isFilterValueAdded = true;
                } else {
                    lastAppliedFilter.filterValue = 'All class specifications of ';
                    lastAppliedFilter.isFilterValueAdded = false;
                }

                var changedFiltersCount = getChangedFiltersCount();

                self.updateQueryParameters();

                self.triggerFiltersChange(changedFiltersCount, true);
            }
        }

        function initClassSpecificationsFilter() {
            var isClassSpecificationsFilterViewModelExists =
                classSpecificationsFilterCategoryViewModel && $(classSpecificationsFilterCategoryContainerSelector).length;

            if (!isClassSpecificationsFilterViewModelExists) {
                classSpecificationsFilterCategoryViewModel =
                    namespace('AgencyPages').classSpecificationsFilterCategoryViewModel;
            }

            ko.applyBindings(
                classSpecificationsFilterCategoryViewModel,
                $(classSpecificationsFilterCategoryContainerSelector).get(0));

            $(applyClassSpecificationsFilterCategoryButtonSelector).click(applyClassSpecificationsFilter);

            $(applyClassSpecificationsFilterCategoryButtonSelector).focus(function () {
                classSpecificationsFilterCategoryViewModel.validate();
            });

            var appliedClassSpecificationsCodes = classSpecificationsFilterCategoryViewModel
                .getClassSpecificationsCodesFromQueryString();

            if (isClassSpecificationsFilterViewModelExists) {
                if (appliedClassSpecificationsCodes && appliedClassSpecificationsCodes.length) {
                    var selectedAndAppliedClassSpecifications = classSpecificationsFilterCategoryViewModel
                        .selectedClassSpecifications()
                        .filter(item => appliedClassSpecificationsCodes.some((id) => id === item.code.toString()));
                    selectedAndAppliedClassSpecifications = [...selectedAndAppliedClassSpecifications.reduce((map, obj) => map.set(obj.code, obj), new Map()).values()];
                    var deletedNotConfirmedClassSpecificationCodes = appliedClassSpecificationsCodes
                        .filter(id => !classSpecificationsFilterCategoryViewModel
                            .selectedClassSpecifications()
                            .some((item) => item.code.toString() === id));

                    if (deletedNotConfirmedClassSpecificationCodes && deletedNotConfirmedClassSpecificationCodes.length) {
                        var deletedNotConfirmedClassSpecifications = classSpecificationsFilterCategoryViewModel
                            .selectedClassSpecificationsCache()
                            .filter(item => deletedNotConfirmedClassSpecificationCodes.some((id) => id === item.code.toString()));
                        deletedNotConfirmedClassSpecifications = [...deletedNotConfirmedClassSpecifications.reduce((map, obj) => map.set(obj.code, obj), new Map()).values()];
                        if (deletedNotConfirmedClassSpecifications && deletedNotConfirmedClassSpecifications.length) {
                            selectedAndAppliedClassSpecifications = selectedAndAppliedClassSpecifications
                                .concat(deletedNotConfirmedClassSpecifications);
                        }
                    }

                    classSpecificationsFilterCategoryViewModel
                        .selectedClassSpecifications = ko.observableArray(selectedAndAppliedClassSpecifications);

                    classSpecificationsFilterCategoryViewModel
                        .addAutocompleteLabelsToSearchComponentForSelectedClassSpecifications();
                } else {
                    classSpecificationsFilterCategoryViewModel
                        .clearSelectedLabels(classSpecificationsSearchComponentSelector + ' ' + selectedSearchLabelSelector);

                    classSpecificationsFilterCategoryViewModel
                        .selectedClassSpecifications = ko.observableArray([]);
                }
            } else {
                if (appliedClassSpecificationsCodes && appliedClassSpecificationsCodes.length) {
                    var queryParams = '?agency=' + encodeURIComponent(pageInfoService.getCurrentAgencyFolderName());

                    for (var index = 0; index < appliedClassSpecificationsCodes.length; index++) {
                        queryParams += '&codes[' + index + ']=' + encodeURIComponent(appliedClassSpecificationsCodes[index]);
                    }

                    $.ajax({
                        url: getClassSpecificationsDetailsByCodesUrl + queryParams,
                        type: 'GET',
                        cache: false
                    }).done(function (data) {
                        var classSpecsDetails = data && data.length ? data : [];

                        classSpecificationsFilterCategoryViewModel
                            .selectedClassSpecifications = ko.observableArray(classSpecsDetails.map(function (item) {
                                return {
                                    text: item.title,
                                    code: item.code
                                };
                            }));

                        classSpecificationsFilterCategoryViewModel
                            .addAutocompleteLabelsToSearchComponentForSelectedClassSpecifications();
                    });
                }
            }

            $(mobileApplyFilterButtonSelector).hide();
        }

        self.updateFilterPanel = function (panelType, markup, shouldAnnounceOpening) {
            var $filterContentContainer = self.$wrapper.find('.filter-flyout-container .filter-flyout-content-container');

            gJobs.arrowsNavigationService.removeArrowsNavigation();

            $filterContentContainer.html(markup);

            var $flyoutSelectableList = $filterContentContainer.find('ul li div input');
            var $notificationContainer = $('#screen-reader-message');

            var panelTitle = panelType === FilterPanel.KEY
                ? FilterPanel.OPTIONS.TITLE
                : SortByPanel.OPTIONS.TITLE;

            var $selectableItemContainer = $filterContentContainer.find('.selectable-item-container');
            gJobs.arrowsNavigationService.addArrowsNavigation($selectableItemContainer);

            customLabelService.updateCustomLabels($filterContentContainer, customLabels);

            $selectableItemContainer
                .off('keydown')
                .on('keydown', function (e) {                   
                    var $this = $(this),
                        $selectableElement = $this.is('input') ? $this : $this.find('input'),
                        filterType = $filterContentContainer.children().data('filter-category');

                    if (e.keyCode === $.ui.keyCode.ENTER || e.keyCode === $.ui.keyCode.SPACE) {                        
                        e.preventDefault();
                        $selectableElement.trigger('click');
                        if (filterType && FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE) {
                            $selectableElement.attr("aria-checked", $selectableElement.prop("checked"));
                        } else {
                            $selectableItemContainer.each(function (index, item) {
                                updateSelectedLabel(item);
                            });
                        }
                    }
                });

            $selectableItemContainer.off('click').on('click',
                function (e) {
                    var $this = $(this),
                        $selectableElement = $this.is('input') ? $this : $this.find('input'),
                        filterType = $filterContentContainer.children().data('filter-category');

                    if (e.target === this) {
                        $selectableElement.trigger('click');
                    }
                    if (filterType && FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE) {
                        $selectableElement.attr("aria-checked", $selectableElement.prop("checked"));
                    } else {
                        $selectableItemContainer.each(function (index, item) {
                            updateSelectedLabel(item);
                        });
                    }
                });

            if (panelType === SortByPanel.KEY) {

                if (shouldAnnounceOpening) {
                    gJobs.screenReadersService.setNotification($notificationContainer, panelTitle, ' flyout is opened. Press tab to move to the flyout', true, true);
                    var $skipToContentButton = $('#skip-to-content-button');
                    $skipToContentButton.attr("tabindex", "-1");
                }

                if (filterKeyword) {
                    self.showSortByRelevanceChoice();
                } else {
                    self.hideSortByRelevanceChoice();
                }

                self.updateHeader(SortByPanel.OPTIONS.TITLE, SortByPanel.OPTIONS.MOBILE_TITLE, SortByPanel.OPTIONS.ICON_CLASS, SortByPanel.OPTIONS.DESCRIPTION);

                $backButton.hide();
                $resetButton.hide();


                var flyoutSelectableListCheckedItem =
                    $flyoutSelectableList.closest("[data-sort-type='" + sortBy + "']");
                flyoutSelectableListCheckedItem.prop('checked', true);
                flyoutSelectableListCheckedItem.attr('aria-checked', true);
                updateSelectedLabel(flyoutSelectableListCheckedItem.closest('.selectable-item-container'));

                $flyoutSelectableList.off('click');
                $flyoutSelectableList.click(function (event) {                    
                    var $selectableElement = $(this),
                        sortType = $selectableElement.data('sort-type');

                    if (sortType !== sortBy) {
                        var currentFilters = getCurrentFilters();
                        $.extend(currentFilters, { sort: sortType });
                        if (filterKeyword) {
                            $.extend(currentFilters, { keywords: filterKeyword });
                        }

                        var query = url.buildget(currentFilters);
                        router.navigate(initialUrl + '?' + query, false);

                        self.changeSort(sortType);

                        var notificationText = 'Flyout is closed ' + $selectableElement
                            .siblings('.selectable-item-label').text() + ' sort is applied';
                        gJobs.screenReadersService.setNotificationWithFocusSaving({
                            text: notificationText,
                            $element: $('#action-sort-by'),
                            returnFocusBack: true
                        });

                    }
                });

            } else if (panelType === FilterPanel.KEY) {
                self.updateHeader(FilterPanel.OPTIONS.TITLE, FilterPanel.OPTIONS.MOBILE_TITLE, FilterPanel.OPTIONS.ICON_CLASS, FilterPanel.OPTIONS.DESCRIPTION);
                $backButton.hide();
                $resetButton.show();


                if (isDepartmentPage()) {
                    $('a[data-filter-category="DEPARTMENT"]').hide();
                }

                var notificationText = self.highlightChangedCategories(true);

                if (shouldAnnounceOpening) {
                    if (notificationText) {
                        gJobs.screenReadersService.setNotification($notificationContainer, panelTitle + ' flyout is opened. Press tab to move to the flyout' + notificationText, '', true, true);
                    }
                    else {
                        gJobs.screenReadersService.setNotification($notificationContainer, panelTitle, 'flyout is opened. Press tab to move to the flyout', true, true);
                    }
                    var $skipToContentButton = $('#skip-to-content-button');
                    $skipToContentButton.attr("tabindex", "-1");
                }
                else if (notificationText) {
                    gJobs.screenReadersService.setNotification($notificationContainer, notificationText, '', true);
                }


                var $categoriesList = $filterContentContainer.find('.filter-panel ul li a');
                $categoriesList.off('click');
                $categoriesList.click(function (event) {                   
                    var filterCategoryKey = $(this).data('filter-category'),
                        filterCategory = FilterCategory.OPTIONS[filterCategoryKey];

                    filterCategorySource.getData(filterCategory.TYPE).done(function () {
                        self.showFilterCategory(filterCategoryKey);
                        $('.filter-flyout-content-container').find('[data-toggle="popover"]').popover();
                        if (filterCategoryKey === classSpecificationsFilterCategoryTitle) {
                            initClassSpecificationsFilter();
                        }

                    });
                    event.preventDefault();                  
                    
                });

                $resetButton.off('click');
                $resetButton.click(function (event) {
                    lastAppliedFilter = null;
                    self.resetFilters();

                    $(document).one(Events.CommonEventsNames.JobsListLoaded + " " + Events.CommonEventsNames.ClassSpecsListLoaded, function () {
                        gJobs.screenReadersService.readPageTitle($resetButton, "All filters are removed");
                    });
                });
            } else if (panelType === FilterCategory.KEY) {
                var filterType = $filterContentContainer.children().data('filter-category'),
                    filterValue = self.getFilterValue(filterType);

                $backButton.show();


                previousFilterValue = filterValue;

                if (filterValue !== null) {
                    if (!!FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE) {
                        for (var multiFilterValueIndex = 0; multiFilterValueIndex < filterValue.length; multiFilterValueIndex++) {
                            var flyoutSelectableListCheckedItem = $flyoutSelectableList.closest("[data-filter-value='" +
                                filterValue[multiFilterValueIndex] +
                                "']");
                            flyoutSelectableListCheckedItem.prop('checked', true);
                            flyoutSelectableListCheckedItem.attr('aria-checked', true);
                            flyoutSelectableListCheckedItem.closest('.selectable-item-container').attr("aria-checked", true);
                        }
                    } else {
                        var flyoutSelectableListCheckedItem =
                            $flyoutSelectableList.closest("[data-filter-value='" + filterValue + "']");
                        flyoutSelectableListCheckedItem.prop('checked', true);
                        flyoutSelectableListCheckedItem.attr('aria-checked', true);
                        updateSelectedLabel(flyoutSelectableListCheckedItem.closest('.selectable-item-container'));
                    }
                }

                var filterCategoryTitle = FilterCategory.OPTIONS[filterType].TITLE;

                var notificationMessage = filterCategoryTitle + ' filter flyout is opened. ';

                if (filterValue !== null && filterValue.length) {
                    var appliedFiltersNotification = (filterValue instanceof Array)
                        ? filterValue.join(', ')
                        : filterValue;
                    appliedFiltersNotification += ' ' + filterCategoryTitle;
                    appliedFiltersNotification += filterValue.length === 1 ? ' filter is ' : ' filters are ';
                    appliedFiltersNotification += 'already applied';
                    notificationMessage += appliedFiltersNotification;
                }

                gJobs.screenReadersService.setNotification(
                    $notificationContainer, notificationMessage, null, true, false);

                $flyoutSelectableList.off('click');
               

                $flyoutSelectableList.click(function (event) {                    
                    var $selectableElement = $(this),
                        filterValue = $selectableElement.data('filter-value').toString();

                    var changeFiltersResult = self.changeFilters(filterValue, filterType);

                    if (filterType && FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE) {
                        $selectableElement.attr("aria-checked", $selectableElement.prop("checked"));
                    }
                    if (!FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE && !changeFiltersResult.isFilterValueAdded) {
                        $selectableElement.prop('checked', false);
                        $selectableElement.attr('aria-checked', false);
                        if (!event.originalEvent) {
                            event.preventDefault();
                        }
                    }

                    self.updateQueryParameters();

                    self.triggerFiltersChange(changeFiltersResult.changedFiltersCount, true);
                    $('.filter-flyout-content-container').find('[data-toggle="popover"]').popover();
                });
                $flyoutSelectableList.focus(function () {
                    $(this).addClass('focused');
                    $(this).closest('.selectable-item-container').addClass('focused');
                    $('.filter-flyout-content-container').find('[data-toggle="popover"]').popover();
                });
                $flyoutSelectableList.blur(function () {
                    $(this).removeClass('focused');
                    $(this).closest('.selectable-item-container').removeClass('focused');
                });

                $backButton.off('click');
                $backButton.click(function (event) {
                    $backButton.hide();
                    $resetButton.show();

                    self.updateHeader(FilterPanel.TITLE, FilterPanel.MOBILE_TITLE);
                    self.showFilterPanel(FilterPanel.KEY);
                    var closedMessage = filterCategoryTitle + ' filter category tab is closed. Filters flyout is active.';
                    gJobs.screenReadersService.setNotification($notificationContainer, closedMessage, null, true, false);

                    event.preventDefault();
                });
            }
        };

        self.updateQueryParameters = function () {
            var currentFilters = getCurrentFilters();

            $.extend(currentFilters, { sort: sortBy });
            if (filterKeyword) {
                $.extend(currentFilters, { keywords: filterKeyword });
            }

            var query = url.buildget(currentFilters);
            router.navigate(initialUrl + '?' + query, false);
        }

        self.showFilterCategory = function (filterCategoryKey) {
            var filterCategory = FilterCategory.OPTIONS[filterCategoryKey];

            $resetButton.hide();

            self.updateHeader(filterCategory.TITLE, filterCategory.MOBILE_TITLE, filterCategory.ICON_CLASS, filterCategory.DESCRIPTION);
            var data = self.getFiltersCategories(filterCategoryKey);
            self.updateFilterPanel(FilterCategory.KEY, data);
        };

        self.updateHeader = function (title, mobileTitle, iconClass, description) {
            $headerTitle.text(title);

            mobileTitle = mobileTitle || title;
            $mobileHeaderTitle.text(mobileTitle);

            if (iconClass) {
                $icon.attr('class', iconClass).show();
            } else {
                $icon.hide();
            }

            if (description) {
                $headerDescription.text(description).show();
            } else {
                $headerDescription.hide();
            }
        };

        self.getFiltersCategories = function (category) {
            return $(filtersCategoriesData).find("[data-filter-category='" + category + "']");
        };

        self.applyFilters = function (currentFilters) {
            self.setFilters(currentFilters);

            var changedFiltersCount = self.getFiltersCount();

            if (changedFiltersCount === 0) {
                router.navigate(initialUrl, false);
            }

            self.triggerFiltersChange(changedFiltersCount);
        }

        self.getLastAppliedFilter = function () {
            return lastAppliedFilter;
        }

        self.changeFilters = function (filterValue, filterType) {
            var item = FilterCategory.OPTIONS[filterType].FILTER,
                //shows whether new filter value is added to filters
                isFilterValueAdded = true;

            if (filterValue === previousFilterValue
                || ((!!FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE) && (filters[item].indexOf(filterValue) > -1))) {
                previousFilterValue = null;

                if (!!FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE) {
                    filters[item].splice(filters[item].indexOf(filterValue), 1);
                } else {
                    filters[item] = null;
                }

                isFilterValueAdded = false;
            } else {
                previousFilterValue = filterValue;

                if (!!FilterCategory.OPTIONS[filterType].SUPPORTS_MULTI_CHOICE) {
                    if (filters[item].indexOf(filterValue) === -1) {
                        filters[item].push(filterValue);
                    }
                } else {
                    filters[item] = filterValue;
                }
            }

            lastAppliedFilter = {
                filterValue: filterValue,
                filterType: filterType,
                isFilterValueAdded: isFilterValueAdded
            };

            var changedFiltersCount = getChangedFiltersCount();

            return {
                isFilterValueAdded: isFilterValueAdded,
                changedFiltersCount: changedFiltersCount
            };
        };

        self.resetFilters = function () {
            var isFiltersEmpty = false;

            for (var propertyName in filters) {
                for (var categoryPropertyName in FilterCategory.OPTIONS) {
                    if (FilterCategory.OPTIONS[categoryPropertyName].FILTER === propertyName) {
                        if (!!FilterCategory.OPTIONS[categoryPropertyName].SUPPORTS_MULTI_CHOICE) {
                            if (!!filters[propertyName].length) {
                                filters[propertyName] = [];
                                isFiltersEmpty = true;
                            }
                        } else {
                            if (filters[propertyName] !== null) {
                                filters[propertyName] = null;
                                isFiltersEmpty = true;
                            }
                        }
                    }
                }
            }

            if (isFiltersEmpty) {
                self.highlightChangedCategories(false);
                filterCategorySource.getData();

                self.triggerFiltersChange(0, true);

                self.updateQueryParameters();
            }
        };

        self.setFilters = function (currentFilters) {
            for (var filter in currentFilters) {
                for (var categoryPropertyName in FilterCategory.OPTIONS) {
                    if (FilterCategory.OPTIONS[categoryPropertyName].FILTER === filter) {
                        if (!!FilterCategory.OPTIONS[categoryPropertyName].SUPPORTS_MULTI_CHOICE) {
                            var filterCategory = currentFilters[filter];

                            if (filterCategory.length !== 0) {
                                filters[filter] = filterCategory;
                            }
                        } else {
                            var value = currentFilters[filter];

                            if (value) {
                                filters[filter] = value;
                            }
                        }
                    }
                }
            }
        }

        self.getFiltersCount = function () {
            var filtersCount = 0;

            $.each(filters, function (index, value) {
                if (Array.isArray(value) && value.length > 0) {
                    filtersCount += value.length;
                }

                if (!Array.isArray(value) && value) {
                    filtersCount++;
                }
            });

            return filtersCount;
        }

        self.changeSort = function (sortType, silent) {
            if (!silent) {
                sortBy = sortType;
                lastAppliedFilter = null;
                $(document).trigger(currentConfig.TRIGGERED_EVENT_PREFIX + ':sort', sortBy);
                self.close();
            }
        };

        self.getFilterValue = function (filterType) {
            var item = FilterCategory.OPTIONS[filterType].FILTER;

            return filters[item];
        };

        self.highlightChangedCategories = function (isHighlight) {
            var changedCategoriesTitles = [];
            for (var filterPropertyName in filters) {
                for (var categoryPropertyName in FilterCategory.OPTIONS) {
                    if (FilterCategory.OPTIONS[categoryPropertyName].FILTER === filterPropertyName) {
                        var changedFiltersCount;

                        if (FilterCategory.OPTIONS[categoryPropertyName].SUPPORTS_MULTI_CHOICE) {
                            changedFiltersCount = filters[filterPropertyName].length;
                        } else {
                            changedFiltersCount = filters[filterPropertyName] ? 1 : 0;
                        }

                        var $filterLink = self.$wrapper.find('ul li')
                            .find("[data-filter-category='" + categoryPropertyName + "']");

                        if (isHighlight && changedFiltersCount) {
                            changedCategoriesTitles.push(FilterCategory.OPTIONS[categoryPropertyName].TITLE);

                            $filterLink.find(".badge").text(changedFiltersCount);
                            $filterLink.attr('aria-label', 'Filter by ' + FilterCategory.OPTIONS[categoryPropertyName].TITLE + ', ' + changedFiltersCount + ' Filter applied');
                        } else {
                            $filterLink.find(".badge").text('');
                            $filterLink.attr('aria-label', 'Filter by ' + FilterCategory.OPTIONS[categoryPropertyName].TITLE);
                        }
                    }
                }
            }

            if (changedCategoriesTitles.length) {
                return 'Search results are based on ' + changedCategoriesTitles.join(', ') + ' filters.';
            }
        };

        self.showFilterPanel = function (panelType, keyword, shouldAnnounceOpening) {
            if (keyword != undefined && keyword != filterKeyword) {
                filterKeyword = keyword;
            }

            if (shouldAnnounceOpening) {
                self.open();
            }

            filtersPanelSource.getMarkup(panelType).done(function (data) {
                self.updateFilterPanel(panelType, data, shouldAnnounceOpening);
            });
        };

        self.hideSortByRelevanceChoice = function () {
            var $relevanceElement = self.getRelevanceElement();
            $relevanceElement.hide();
        };

        self.showSortByRelevanceChoice = function () {
            var $relevanceElement = self.getRelevanceElement();
            $relevanceElement.show();
        };

        self.getRelevanceElement = function () {
            return self.$wrapper.find('.sort-panel input[data-sort-type="null"]').closest('li');
        };

        self.triggerFiltersChange = function (changedFiltersCount, isChangeFromFlyout) {
            $(document).trigger('Header:filtersCountChanged', changedFiltersCount);
            data = {
                newfilters: getCurrentFilters(),
                isChangeFromFlyout: isChangeFromFlyout
            };
            $(document).trigger(currentConfig.TRIGGERED_EVENT_PREFIX + ':filtersChanged', data);
        }

        $(document).on('FilterFlyout:sortByChanged', function (e, sortType) {
            sortBy = !sortType ? null : sortType;
        });

        $(document).on(Events.CommonEventsNames.FlyoutClosing, function () {
            gJobs.arrowsNavigationService.removeArrowsNavigation();
            if (releaseFocus) {
                releaseFocus();
                releaseFocus = undefined;
            }
        });
    };

    function updateSelectedLabel(el) {
        $(el).find('.selection-label').text($(el).find('input').prop('checked') ? ' Selected' : '');
    }

    function isTransferJobs() {
        return pageInfoService.getCurrentPageType().type == pageInfoService.getPageTypes().transferJobs.type;
    }

    function isPromotionalJobs() {
        return pageInfoService.getCurrentPageType().type == pageInfoService.getPageTypes().promotionalJobs.type;
    }

    function isDepartmentPage() {
        return pageInfoService.isDepartmentPage();
    }

    function getCurrentFilters() {
        var currentFilters = {}
        $.each(filters, function (index, value) {
            if (value && value.length !== 0) {
                currentFilters[index] = value;
            }
        });

        return currentFilters;
    }

    window.FilterFlyout = filterFlyoutConstructor;
})(window);;
(function (window, undefined) {
    'use strict';

    $(document).ready(function () {
        var $html = $('html'),
            $body = $('body'),
            $header = $('#header'),

            $headerMenuAction = $('#header-menu-action'),
            $menuContainer = $('#menu-container'),
            $menuItems = $menuContainer.find('a[role="menuitem"]'),
            $closeMenuButton = $menuContainer.find('#close-menu-button'),

            $headerSigninAction = $('#header-signin-action'),
            $headerSigninForm = $('#header-sign-in-form'),
            $headerSigninOverlay = $headerSigninForm.find('.sign-in-overlay'),

            $headerUserNameContainer = $header.find('.floating-header .user-name-container'),
            $headerUserMenuPopupContainer = $header.find('.floating-header .user-name-container + .header-user-menu-popup-container'),
            $menuAccessibilityHelper = $header.find('.application-menu-link .ui-helper-hidden-accessible'),
            $userMenuPopup = $headerUserMenuPopupContainer.find('.user-menu-popup'),
            $userMenuPopupLinks = $userMenuPopup.find('.application-menu-items a'),
            $userMenuPopupOverlay = $headerUserMenuPopupContainer.find('.user-menu-popup-overlay'),
            $headerSigninBlock = $headerSigninForm.find('#sign-in-block'),
            $tabbableApplicationMenuElements = $headerUserNameContainer.add($userMenuPopupLinks),
            $flyoutMenuOverlay = $menuContainer.find('.menu-overlay'),
            $changedFiltersCountBadgeContainer = $('.changed-filters-count-badge-container'),
            $changedFiltersCountBadge = $changedFiltersCountBadgeContainer.find('.changed-filters-count-badge'),
            $managePanel = $('#manage-bar'),
            $contentContainer = $('#main-container > .content-container');

        var menu = {
            $items: $menuItems,
            direction: {
                next: 'next',
                prev: 'prev'
            }
        }

        //avoid JAWS reading menu items twice in IE
        if (gJobs.browserDetector.isIE()) {
            $userMenuPopupLinks.attr('aria-label', ' ');
            $.each($userMenuPopupLinks, function () {
                var $this = $(this);
                var userMenuPopupLinkTitle = $.trim($this.text().replace(/\s+/g, ' '));
                $this.attr('title', userMenuPopupLinkTitle);
            });
        }

        var loginAndRegisterEvents = Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;

        var menuTransitionClasses = ['hide', { name: 'active', causingTransition: true }];

        var maxMobileScreenWidth = 767,
            floatingHeaderHeight = 60;

        $(document).on(OnlineApp.Events.CommonEventsNames.ApplyTabOpened, function () {
            $header.css('visibility', 'hidden');
        });
        $(document).on(Events.CommonEventsNames.CloseFlyout, function () {
            $header.css('visibility', 'visible');
        });

        function addMenuHandlers() {
            $headerMenuAction.click(function (e) {
                $menuContainer.toggleClassSequence(menuTransitionClasses);

                var notificationText = "Menu flyout is open.";
                gJobs.screenReadersService.setNotificationWithFocusSaving({
                    text: notificationText,
                    $element: $closeMenuButton,
                    returnFocusBack: true
                });

                OnlineApp.Services.tabIndexService.disableTabIndex({
                    hideSkipButton: true
                });
                disableBodyScrolling();

                $('#main-container').attr('aria-hidden', 'true');


            });

            //initialize menu flyout popovers for external and social links
            $menuItems.popover();

            //initialize header sign in popover
            $headerSigninAction.click(function (e) {
                $headerSigninBlock.addClass('active');
                $headerSigninForm.addClass('active');
                $headerSigninOverlay.removeClass('hide');

                if ($html.hasClass('device-phone')) {
                    disableBodyScrolling();
                }

                gJobs.focusService.setFocus($headerSigninBlock);

                $html.one('click', closePopup);

                e.stopPropagation();
            });

            $headerSigninOverlay.click(function () {
                $headerSigninBlock.removeClass('active');
                $headerSigninForm.removeClass('active');
                $headerSigninOverlay.addClass('hide');

                gJobs.focusService.setFocus($headerSigninAction);

                enableBodyScrolling();
            });

            $headerUserNameContainer.click(function (e) {
                toggleUserMenu();

                e.stopPropagation();
                e.preventDefault();
            });
            $closeMenuButton.click(function () {
                $('#header-menu-action').focus();
            })

            $userMenuPopup.find('a').click(function () {
                $userMenuPopup.trigger('click');
            });

            $userMenuPopup.on('keydown', ':tabbable:last', function (e) {
                if (e.keyCode === $.ui.keyCode.TAB && !e.shiftKey) {
                    toggleUserMenu();
                }
            });

            $headerSigninBlock.on('keydown', ':tabbable:last', function (e) {
                if (e.keyCode === $.ui.keyCode.TAB && !e.shiftKey) {
                    closePopup();
                }
            });

            $headerSigninBlock.on('keydown', function (e) {
                if (e.keyCode === $.ui.keyCode.ESCAPE) {
                    if ($('#' + $(e.target).attr('aria-describedby')).is('.popover.fade.in[role="tooltip"]:visible')) {
                        $(e.target).popover('hide');
                        e.preventDefault();
                        e.stopPropagation();
                    } else {
                        // Only close popup if not on a popover
                        if (typeof closePopup === "function") {
                            closePopup();
                        }
                    }
                }
            });
            
            function toggleUserMenu() {
                $userMenuPopup.toggleClass('hide');
                $userMenuPopupOverlay.toggleClass('hide');

                if (!$userMenuPopup.hasClass('hide')) {
                    $menuAccessibilityHelper.text('Menu expanded');
                    $headerUserNameContainer.attr('aria-pressed', true);
                    if ($html.hasClass('device-phone')) {
                        disableBodyScrolling();
                    }

                    var $menuItem = $userMenuPopup.find('.job-applications-link:first');
                    var $menuNotification = $('<span class="hide-notification" tabindex="-1">User Menu with ' + $userMenuPopupLinks.length + ' options was opened.</span>');
                    $menuItem.prepend($menuNotification);
                    $menuItem.one('focusout', function () {
                        $menuNotification.remove();
                    });
                    gJobs.focusService.setFocus($menuItem);
                    gJobs.arrowsNavigationService.addArrowsNavigationOnElements($tabbableApplicationMenuElements);

                    $html.one('click', function () {
                        if (!$userMenuPopup.hasClass('hide')) {
                            $headerUserNameContainer.trigger('click');
                        }
                    });
                } else {
                    $menuAccessibilityHelper.text('Menu collapsed');
                    $headerUserNameContainer.attr('aria-pressed', false);
                    enableBodyScrolling();
                    gJobs.focusService.restoreFocus();
                    gJobs.arrowsNavigationService.addArrowsNavigationOnElements($tabbableApplicationMenuElements);
                }
            }

            function closePopup() {
                if ($headerSigninBlock.hasClass('active')) {
                    $headerSigninBlock.removeClass('active');
                    $headerSigninOverlay.addClass('hide');
                    $headerSigninForm.removeClass('active');

                    OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.isEmailTooltipFocusable(true);

                    enableBodyScrolling();
                    $("#aria-live-message-container").text('');
                    if ($(".login-container") && $(".login-container").length > 0) {
                        setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Sign in form is closed.', $("#aria-live-message-container"), false); }, 300);
                    }
                    else if ($(".register-container") && $(".register-container").length > 0) {                   
                        setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Create account form is closed.', $("#aria-live-message-container"), false); }, 300);
                    }
                    gJobs.focusService.restoreFocus();
                }
            }

            $(document).on(loginAndRegisterEvents, closePopup);

            $userMenuPopup.on('click', function (e) {
                e.stopPropagation();
            });

            $headerSigninBlock.on('click', function (e) {
                e.stopPropagation();
                OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.isEmailTooltipFocusable(false);
            });

            $headerSigninBlock.on('keydown', '.toggle-link', function (e) {
                if (e.keyCode === $.ui.keyCode.ENTER) {
                    e.preventDefault();
                    gJobs.signInForm.toggleLogInAndRegister(e);
                }
            });

            $(window).on('resize', function () {
                if (!$userMenuPopup.hasClass('hide')
                    || $headerSigninBlock.hasClass('active')) {

                    if ($html.hasClass('device-phone')) {
                        if (!$body.hasClass('scroll-disable')) {
                            disableBodyScrolling();
                        }
                    } else {
                        if ($body.hasClass('scroll-disable')) {
                            enableBodyScrolling();
                        }
                    }
                }
            });

            $menuContainer.find('.close-button').click(function (e) {
                $('#main-container').attr('aria-hidden', 'false');

                $menuContainer.toggleClassSequence(menuTransitionClasses, true);


                var flyoutCloseMessage = 'Menu flyout has been closed';

                // announce active page only when menu flyout closed by a user
                if (e.originalEvent) {
                    var activePageMessage = $('#page-title').text() + ' page is active. ';
                    flyoutCloseMessage += activePageMessage;
                }
                gJobs.screenReadersService.onceNotification({
                    $element: $headerMenuAction,
                    message: flyoutCloseMessage
                });

                OnlineApp.Services.tabIndexService.restoreTabIndex();

                enableBodyScrolling();
            });

            $menuContainer.find('.custom-links a').click(function () {
                $menuContainer.find('.close-button').trigger('click');
            });

            $flyoutMenuOverlay.click(function () {
                $menuContainer.toggleClassSequence(menuTransitionClasses, true);

                OnlineApp.Services.tabIndexService.restoreTabIndex();

                enableBodyScrolling();
            });

            $(document).on('Header:filtersCountChanged', function (e, newValue) {
                if (newValue) {
                    $changedFiltersCountBadgeContainer.show();
                } else {
                    $changedFiltersCountBadgeContainer.hide();
                }

                $changedFiltersCountBadge.text(newValue);
                var $filterContainer = $changedFiltersCountBadgeContainer.parent();
                $filterContainer.attr('aria-label', 'Filter, ' + newValue + ' Filters applied');
            });

            $(document).on('keyup', function (e) {
                if ($menuContainer.hasClass('active')) {
                    if (e.keyCode === $.ui.keyCode.ESCAPE) { 
                        const elementsWithPopover = $menuContainer.find('[aria-describedby]').length > 0;
                        if (!elementsWithPopover) {
                            $menuContainer.find('.close-button').trigger('click');
                        }
                    } else if (e.keyCode === $.ui.keyCode.UP) {
                        switchMenuItem(menu.direction.prev);
                    } else if (e.keyCode === $.ui.keyCode.DOWN) {
                        switchMenuItem(menu.direction.next);
                    } else if (e.keyCode === $.ui.keyCode.ENTER) {
                        var $activeItem = $(document.activeElement);
                        if ($activeItem.attr('role') == 'menuitem') {
                            $activeItem.find('a')[0].click();
                        }
                    }
                }

                if (!$userMenuPopup.hasClass('hide')) {
                    if (e.keyCode === $.ui.keyCode.ESCAPE) {
                        $headerUserNameContainer.trigger('click');
                    }
                }
                
            });
        }

        function switchMenuItem(direction) {
            var $activeItem = $(document.activeElement);
            var menuIndex = menu.$items.index($activeItem);
            if (direction === menu.direction.next) {
                if (menuIndex > -1 && menu.$items[menuIndex + 1]) {
                    menu.$items[menuIndex + 1].focus();
                } else {
                    menu.$items.first().focus();
                }
            } else if (direction === menu.direction.prev) {
                if (menuIndex > -1 && menu.$items[menuIndex - 1]) {
                    menu.$items[menuIndex - 1].focus();
                } else {
                    menu.$items.last().focus();
                }
            }
        }

        function disableBodyScrolling() {
            if ($html.get(0).scrollHeight > $html.get(0).clientHeight) {
                $html.addClass('scroll-visible');
            }

            $body.addClass('scroll-disable');

            //disable body scrolling
            AgencyPages && AgencyPages.bodyScrollingAdjustmentService &&
                AgencyPages.bodyScrollingAdjustmentService.disableBodyScrolling();
        }

        function enableBodyScrolling() {
            if ($html.hasClass('scroll-visible')) {
                $html.removeClass('scroll-visible');
            }

            $body.removeClass('scroll-disable');

            //enable body scrolling
            AgencyPages && AgencyPages.bodyScrollingAdjustmentService &&
                AgencyPages.bodyScrollingAdjustmentService.enableBodyScrolling();
        }

        addMenuHandlers();

        AgencyPatternLibrary.FixedHeader.init({
            $header: $header,
            $contentContainer: $contentContainer,
            maxMobileScreenWidth: maxMobileScreenWidth,
            floatingHeaderHeight: floatingHeaderHeight
        });

        AgencyPatternLibrary.FloatingManagePanel.init({
            $managePanel: $managePanel,
            $contentContainer: $contentContainer,
            $header: $header,
            $headerImage: $header.find('.agency-logo-small'),
            maxMobileScreenWidth: maxMobileScreenWidth,
            floatingHeaderHeight: floatingHeaderHeight,
            fixedSearchFieldClass: 'search-field-fixed'
        });

    });
})(window);
(function (window, undefined) {
    'use strict';

    var $header,
        $footer,
        $contentContainer;

    function adjustContentMinHeight() {
        var minContentHeight = $(window).height() - ($header.outerHeight(true) + $footer.outerHeight(true));
        $contentContainer.css({ 'min-height': minContentHeight });
    }

    $(document).ready(function () {
        $header = $('header');
        $footer = $('footer');
        $contentContainer = $('#main-container > .content-container');

        $(window).resize(adjustContentMinHeight);

        adjustContentMinHeight();
    });
})(window);;
(function (window, undefined) {
    'use strict';

    var TRANSITION_END_EVENT_NAMES = 'webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd';

    //minimal time period of inactivity to show splash screen in ms (10 minutes)
    var minInactivityPeriodTime = 10*60*1000;
    //delay in ms untill splash screen autohide (3 seconds)
    var splashScreenHideDelay = 3*1000;

    var $splashScreen = $('#splash-screen-container .splash-screen');

    var updateLastActivityTimeStamp = function () {
        var currentUserSettings = userSettingsService.getSettings();
        currentUserSettings.lastActivityTimeStamp = Date.now();
        userSettingsService.setSettings(currentUserSettings);
    };

    var activateSplashScreen = function () {
        $splashScreen.off(TRANSITION_END_EVENT_NAMES);
        $splashScreen.removeClass('hidden');
        $splashScreen.width($splashScreen.width());
        $splashScreen.removeClass('inactive');
    };

    var deactivateSplashScreen = function () {
        $splashScreen.one(TRANSITION_END_EVENT_NAMES, function () {
            $splashScreen.addClass('hidden');
        });
        $splashScreen.addClass('hidden');

        updateLastActivityTimeStamp();
    };

    var forceDeactivateSplashScreen = function() {
        $splashScreen.addClass('hidden');
       

        updateLastActivityTimeStamp();
    };

    $splashScreen.on('touchend', function() {
        deactivateSplashScreen();
    });

    //check for user settings
    var userSettingsService = AgencyPages && AgencyPages.userSettingsService;
    //check if there are any problems with local storage
    if (!userSettingsService) {
        forceDeactivateSplashScreen();
        return;
    }

    //enable Date.now support in ie8 and older browsers
    if (!Date.now) {
        Date.now = function() { return new Date().getTime(); };
    }

    var userSettings = userSettingsService.getSettings();
    var currentTimestamp = Date.now();
    if (!userSettings.lastActivityTimeStamp || ((currentTimestamp - userSettings.lastActivityTimeStamp) >= minInactivityPeriodTime)) {
        setTimeout(function() {
            deactivateSplashScreen();
        }, splashScreenHideDelay);
    } else {
        forceDeactivateSplashScreen();
    }

    $(window).on('touchend', function() {
        updateLastActivityTimeStamp();
    });
})(window);
(function (window, undefined) {
    'use strict';

    namespace('AgencyPages').getUrlParams = function (url, paramsToExclude) {
        var params = [],
            hashes = url.slice(url.indexOf('?') + 1).split('&'),
            hash,
            i;

        for (i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');

            if ((!paramsToExclude || $.inArray(hash[0], paramsToExclude) == -1) && hash[1]) {
                params.push(hash[0]);
                params[hash[0]] = hash[1];
            }
        }

        return params;
    };

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

    namespace('AgencyPages').isElementInViewport = function (el) {
        if (el instanceof jQuery) {
            el = el[0];
        }

        var rect = el.getBoundingClientRect();

        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.left <= (window.innerWidth || document.documentElement.clientWidth)
        );
    };
})(window);;
(function (window, undefined) {
    'use strict';

    function ApplicationLoader() {
        var self = this;

        self.getOnlineApplicationScriptsUrl = function () {
            return $('#online-application-link').attr('href');
        };

        self.getCurrentJobId = function () {
            var jobAttribute = $('#online-application-link').attr('job');
            var jobId = parseInt(jobAttribute);

            return jobId;
        };

        self.getScriptTagsFromText = function (text) {
            var elements = $.parseHTML(text, document, true);
            var $scriptElements = $(elements).filter('script');

            return $scriptElements;
        };

        self.loadScriptsFromListAsync = function ($scriptElements) {
            var chain = $LAB.sandbox();
            var deferred = $.Deferred();

            $scriptElements.each(function () {
                var $scriptElement = $(this);
                var scriptUrl = $scriptElement.attr('src');
                var scriptContent = $scriptElement.text();

                if (scriptUrl) {
                    chain = chain.script(scriptUrl).wait();
                }
                else {
                    var inlineScript = new Function(scriptContent);

                    chain.wait(inlineScript);
                }
            });

            chain.wait(function () {
                deferred.resolve();
            });


            return deferred.promise();
        };

        self.getListOfOnlineApplicationScriptsAsync = function () {
            var onlineApplicationScriptsUrl = self.getOnlineApplicationScriptsUrl();

            var promise = gJobs.ajax
                .ajaxGet(onlineApplicationScriptsUrl)
                .then(function (text) {
                    return self.getScriptTagsFromText(text);
                });

            return promise;
        };

        self.initOnlineApplication = function () {
            var $apply = $('#online-application-block');
            var $onlineAppWrapper = $apply.closest('.application-container');
            var $onlineApp = $onlineAppWrapper.find('.onlineapp');

            //OnlineApp is aligned to center, thus if a scrollbar appears/disappears, everything shifts, which is undesirable.
            $onlineAppWrapper.on('shown', 'a[data-toggle="tab"]', function () {
                var scrollbarWidth = $onlineAppWrapper.get(0).offsetWidth - $onlineAppWrapper.get(0).clientWidth;
                var onlineAppWidth = $onlineApp.width();
                $onlineApp.css('margin-left', (-onlineAppWidth / 2 + scrollbarWidth/2) + 'px');
            });

            $apply.data('onlineApplicationLoaded', true);

            if ($apply.length !== 0) {
                var viewModel = OnlineApp.ViewModels.applicationViewModel;
                var element = $apply.get(0);

                //ko.cleanNode(element);
                ko.applyBindings(viewModel, element);
            }

            var currentJobId = self.getCurrentJobId();

            OnlineApp.ViewModels.applicationViewModel.jobId(currentJobId);
        };
    }

    namespace('AgencyPages').applicationLoader = new ApplicationLoader();
})();;
(function (window, undefined) {
    var TRANSITION_END_EVENT_NAMES = 'webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd';

    var isTransitionEventSupported = gJobs.isTransitionEventSupported && gJobs.isTransitionEventSupported();

    var layoutHelper = OnlineApp.Helpers.layoutHelper;

    function OnlineAppJobDetaisFlyout() {
        var self = this;

        var flyoutContainer = '#onlineapp-job-details-flyout-container',
            flyoutOverlay = '#onlineapp-job-details-flyout-overlay',
            flyout = '#onlineapp-job-details-flyout',
            closeButton = '.close-button',
            loadingSpinner = '.loading-spinner',
            onlineAppContainerSelector = '#incomplete-application-flyout-content .application-container, #job-flyout-content .application-container',
            jobFlyoutHeaderSelector = '#incomplete-application-flyout-content .job-flyout-header, #job-flyout-content .job-flyout-header';

        var showLoadingSpinner = function() {
            $(loadingSpinner).removeClass('hide');
        };

        var hideLoadingSpinner = function() {
            $(loadingSpinner).addClass('hide');
        };
        
        var navigateBack = function() {
            AgencyPages.router.back();
        }

        function getFlyout() {
            //gets the flyout depending on which page we are
            return AgencyPages.jobFlyout || AgencyPages.incompleteAppFlyout || AgencyPages.standaloneJob;
        }

        var loadJobDetails = function (jobId) {
            var departmentFolderName = namespace('AgencyPages').pageInfoService.getCurrentDepartmentFolderName();

            getFlyout().jobInfoSource.get(jobId, departmentFolderName)
                .done(jobId, function (data) {

                    var $flyout = $(flyout);
                    var $notificationContainer = $('#screen-reader-message');

                    $flyout.find('.flyout-content').html(data);
                    initializeHandlers();
                    hideLoadingSpinner();

                    gJobs.accessibilityHtmlTransformer.makeElementContentAccessible($('.entity-details-content'));
                    $flyout.find('.flyout-content').scrollTop(0);

                    gJobs.screenReadersService.setNotification($notificationContainer, $flyout.find('.title').text(), ' flyout has been opened', true, true);
                })
                .fail(function () {
                    toastr && toastr.warning("Sorry.. We've encountered a problem during job details loading");
                    self.closeFlyout();
                });
        };

        var initializeHandlers = function() {
            $(flyout).find('.flyout-content').find('.popover-trigger').popover();

            var $scrollableContainer = $(flyout).find('.entity-info');

            //add header shadow to flyout-header when scrolling
            AgencyPages.scrollableContainerAdjuster.addHeaderShadowOnScrolling($scrollableContainer);
        };

        self.isFlyoutOpened = function() {
            return $(flyout).hasClass('active');
        };

        var releaseFocus;

        self.openFlyout = function () {
            document.title = document.title.replace('Apply tab', 'Job Details tab');
            var $flyout = $(flyout);
            var $closeButton = $flyout.find(closeButton);

            if (isTransitionEventSupported) {
                $flyout.off(TRANSITION_END_EVENT_NAMES);
            }

            $flyout.removeClass('hidden');
            $flyout.width($flyout.width());
            $flyout.addClass('active');

            $(jobFlyoutHeaderSelector).add(onlineAppContainerSelector).attr('aria-hidden', 'true');

            if (gJobs.browserDetector.isFirefox()) {
                $(onlineAppContainerSelector).attr('tabindex', '-1');
            }
            
            OnlineApp.Services.tabIndexService.disableTabIndex({
                containerSelector: onlineAppContainerSelector + ',' + jobFlyoutHeaderSelector
            });

            releaseFocus = gJobs.focusService.restrictFocus($flyout);
            gJobs.skipToContentService.showOnNextTab();

            $(flyoutContainer).find(flyoutOverlay).addClass('active');

            $(flyoutContainer).find(flyoutOverlay).one('click', navigateBack);

            $flyout.find($closeButton).one('touchstart click', navigateBack);
        };

        self.openFlyoutForJobWithId = function (jobId) {
            if (jobId) {
                self.openFlyout();
                showLoadingSpinner();
                loadJobDetails(jobId);

                if (layoutHelper) {
                    var flyoutContainer = $("#onlineapp-job-details-flyout");
                    layoutHelper.tabbing.updateIndices(flyoutContainer);
                }
            } else {
                //close flyout if no job id is passed
                AgencyPages.router && AgencyPages.router.back && AgencyPages.router.back();
            }
        };

        self.closeFlyout = function () {
            var hideFlyout = function () {
                $(flyout).addClass('hidden');
                $(flyoutContainer).find(flyoutOverlay).removeClass('active');
                $(flyout).find('.flyout-content').empty();
                $(jobFlyoutHeaderSelector).add(onlineAppContainerSelector).attr('aria-hidden', 'false');
            };

            if (isTransitionEventSupported) {
                $(flyout).one(TRANSITION_END_EVENT_NAMES, hideFlyout);
            } else {
                hideFlyout();
            }

            OnlineApp.Services.tabIndexService.restoreTabIndex({
                containerSelector: onlineAppContainerSelector + ',' + jobFlyoutHeaderSelector
            });

            $(flyout).removeClass('active');
            if (releaseFocus) {
                releaseFocus();
                releaseFocus = undefined;
            }

            gJobs.focusService.restoreFocus({
                focusRestoringCallback: function ($restoringElement) {
                    gJobs.screenReadersService.onceNotification({
                        $element: $restoringElement,
                        message: 'Flyout has been closed. '
                    });
                }
            });
        };
    };

    namespace('AgencyPages').onlineAppJobDetailsFlyout = new OnlineAppJobDetaisFlyout();
})(window);;
(function (window, undefined) {
    'use strict';

    function AgencyPagesPageContextService() {
        var self = this;

        self.isInsideFlyout = function () {
            //In Agency Pages context, both job flyout and stand-alone job details page open the OnlineApp in a flyout
            return true;
        };

        self.getOnlineAppFlyoutContainer = function () {
            return $('#online-application-block').parent();
        };

        self.getApplicationsPageUrl = function () {
            return AgencyPages.pageInfoService.getCurrentAgencyHomePageUrl() + '/Applications/Index';
        };

        self.getHomePageUrl = function () {
            return AgencyPages.pageInfoService.getCurrentAgencyHomePageUrl();
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.Services', {
        pageContextService: new AgencyPagesPageContextService()
    });

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

    if (AgencyPages && AgencyPages.Ios8Detector && AgencyPages.Ios8Detector.IsIos8()) {
        var $viewport = $('meta[name="viewport"]');
        var content = $viewport.attr('content');
        content = content.replace(new RegExp('height\\D*\\d*,'), '');
        $viewport.attr('content', content);
    }
})();
;
(function($, undefined) {
/*
    TrafficCop
    Author: Jim Cowart
    License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
    Version 0.3.0
*/

var inProgress = {};

$.trafficCop = function(url, options) {
    var reqOptions = url, key;
    if(arguments.length === 2) {
        reqOptions = $.extend(true, options, { url: url });
    }
    key = JSON.stringify(reqOptions);
    if (key in inProgress) {
        for (i in {done: 1, fail: 1, always: 1}) {
            inProgress[key][i](reqOptions[i]);
        }
    } else {
        // notify on any load start
        $(document).trigger("koTemplateLoadStart");

        inProgress[key] = $.ajax(reqOptions)
            .done(reqOptions.done)
            .fail(reqOptions.fail)
            .always(function() {
                delete inProgress[key];

                // trigger allTemplatesLoaded event when inProgress collection is empty
                // todo: investigate why "always" callback fires not directly after ajax but rather after ajax and cached templates were apllied
                if ($.isEmptyObject(inProgress)) {
                    $(document).trigger("koTemplatesLoaded");
                }
            });
    }
    return inProgress[key];
};

})(jQuery);

(function($, global, undefined) {
/*
    infuser.js
    Author: Jim Cowart
    License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
    Version 0.2.0
*/
var hashStorage = {
    templates: {},

    storeTemplate: function(templateId, templateContent) {
        this.templates[templateId] = templateContent;
    },

    getTemplate: function(templateId) {
        return this.templates[templateId];
    },

    purge: function() {
        this.templates = {};
    }
};
var scriptStorage = {
    templateIds: [],
    storeTemplate: function(templateId, templateContent) {
        var node = document.getElementById(templateId);
        if(node === null) {
            this.templateIds.push(templateId);
            node = document.createElement("script");
            node.type = "text/html";
            node.id = templateId;
            document.body.appendChild(node);
        }
        node.text = templateContent;
    },

    getTemplate: function(templateId) {
        return document.getElementById(templateId);
    },

    purge: function() {
        for(var i = 0; i < this.templateIds.length; i++) {
            document.body.removeChild(document.getElementById(this.templateIds[i]));
        }
        this.templateIds = [];
    }
};
var errorHtml = "<div class='infuser-error'>The template <a href='{TEMPLATEURL}'>{TEMPLATEID}</a> could not be loaded. {STATUS}</div>",
    returnErrorTemplate = function(status, templateId, templatePath) {
        return errorHtml.replace('{STATUS}', status).replace('{TEMPLATEID}', templateId).replace('{TEMPLATEURL}', templatePath);
    },
    errors = [];
var helpers = {
    getTemplatePath: function (templateOptions) {
        var templateFile = templateOptions.templatePrefix + templateOptions.templateId + templateOptions.templateSuffix;
        var templateUrl = templateOptions.templateUrl === undefined || templateOptions.templateUrl === ""
            ? templateFile
            : templateOptions.templateUrl + "/" + templateFile;

        return window.templateVersion
            ? templateUrl + '?v=' + window.templateVersion
            : templateUrl;
    },
    templateGetSuccess: function(templateId, callback) {
        return function(response) {
            infuser.store.storeTemplate(templateId, response);
            callback(infuser.store.getTemplate(templateId));
        };
    },
    templateGetError: function(templateId, templatePath, callback) {
        return function(exception) {
            if($.inArray(templateId, errors) === -1) {
                errors.push(templateId);
            }
            var templateHtml = returnErrorTemplate("HTTP Status code: " + exception.status, templateId, templatePath);
            infuser.store.storeTemplate(templateId, templateHtml);
            callback(infuser.store.getTemplate(templateId));
        };
    },
    getAjaxOptions: function(templateOptions) {

    }
},
infuserOptions = ['target','loadingTemplate','postRender','preRender','render','bindingInstruction','useLoadingTemplate','model','templateUrl','templateSuffix','templatePrefix',''];
var infuser = {
    storageOptions: {
        hash: hashStorage,
        script: scriptStorage
    },

    store: hashStorage,

    defaults: {
        // Template name conventions
        templateUrl: "",
        templateSuffix: ".html",
        templatePrefix: "",
        // AJAX Options
        ajax: {
            "async": true,
            "dataType": "html",
            "type": "GET"
        },
        // infuse() specific options - NOT used for "get" or "getSync"
        target:  function(templateId) { return "#" + templateId }, // DEFAULT MAPPING
        loadingTemplate:    {
            content: '<p></p>', // empty content while loading, use a spinner overlapping the whole onlineapp area
                                transitionIn:   function(target, content) {
                                                    var tgt = $(target);
                                                    //tgt.hide();
                                                    tgt.html(content);
                                                    //tgt.fadeIn();
                                                },
                                transitionOut: function (target) {
                                                    $(target).html("");
                                                }
                            },
        postRender:         function(targetElement) { }, // NO_OP effectively by default
        preRender:          function(targetElement, template) { }, // NO_OP effectively by default
        render:             function(target, template) {
                                var tgt = $(target);
                                if(tgt.children().length === 0) {
                                    tgt.append($(template));
                                }
                                else {
                                    tgt.children().replaceWith($(template));
                                }
                            },
        bindingInstruction:  function(template, model) { return template; }, // NO_OP effectively by default
        useLoadingTemplate: true // true/false
    },

    get: function (options, callback) {
        var templateOptions = $.extend({}, infuser.defaults, (typeof options === "object" ? options : { templateId: options })),
            template;
        templateOptions.ajax.url = helpers.getTemplatePath(templateOptions);
        template = infuser.store.getTemplate(templateOptions.ajax.url);
        if(!template || $.inArray(templateOptions.ajax.url, errors) !== -1) {
            templateOptions.ajax.done = helpers.templateGetSuccess(templateOptions.ajax.url, callback);
            templateOptions.ajax.fail = helpers.templateGetError(templateOptions.templateId, templateOptions.ajax.url, callback);
            $.trafficCop(templateOptions.ajax);
        }
        else {
            callback(template);
        }
    },

    getSync: function(options) {
        var templateOptions = $.extend({}, infuser.defaults, (typeof options === "object" ? options : { templateId: options }), { ajax: { async: false } }),
            template,
            templateHtml;
        templateOptions.ajax.url = helpers.getTemplatePath(templateOptions);
        template = infuser.store.getTemplate(templateOptions.ajax.url);
        if(!template || $.inArray(templateOptions.ajax.url, errors) !== -1) {
            templateHtml = null;
            templateOptions.ajax.done = function(response) { templateHtml = response; };
            templateOptions.ajax.fail = function(exception) {
                if($.inArray(templateOptions.ajax.url) === -1) {
                    errors.push(templateOptions.ajax.url);
                }
                templateHtml = returnErrorTemplate("HTTP Status code: exception.status", templateOptions.templateId, templateOptions.ajax.url);
            };
            $.ajax(templateOptions.ajax);
            if(templateHtml === null) {
                templateHtml = returnErrorTemplate("An unknown error occurred.", templateOptions.templateId, templateOptions.ajax.url);
            }
            else {
                infuser.store.storeTemplate(templateOptions.ajax.url, templateHtml);
                template = infuser.store.getTemplate(templateOptions.ajax.url);
            }
        }
        return template;
    },

    infuse: function(templateId, renderOptions) {
        var templateOptions = $.extend({}, infuser.defaults, (typeof templateId === "object" ? templateId : renderOptions), (typeof templateId === "string" ? { templateId: templateId } : undefined )),
            targetElement = typeof templateOptions.target === 'function' ? templateOptions.target(templateId) : templateOptions.target;
        if(templateOptions.useLoadingTemplate) {
            templateOptions.loadingTemplate.transitionIn(targetElement, templateOptions.loadingTemplate.content);
        }
        infuser.get(templateOptions, function(template) {
            var _template = template;
            templateOptions.preRender(targetElement, _template);
            _template = templateOptions.bindingInstruction(_template, templateOptions.model);
            if(templateOptions.useLoadingTemplate) {
                templateOptions.loadingTemplate.transitionOut(targetElement);
            }
            templateOptions.render(targetElement, _template);
            templateOptions.postRender(targetElement);
        });
    }
};
global.infuser = infuser; })(jQuery, window);


// Knockout External Template Engine
// Author: Jim Cowart
// License: MIT (http://www.opensource.org/licenses/mit-license)
// Version 2.0.4


(function ( global, ko, jQuery, infuser, undefined ) {

	var ExternalTemplateSource = function(templateId, options) {
	    var self = this, origAfterRender;
	    self.templateId = templateId;
	    self.loaded = false;
	    self.template = ko.observable(infuser.defaults.useLoadingTemplate ? infuser.defaults.loadingTemplate.content : undefined);
	    self.template.data = {};
	    self.options = ko.utils.extend({},options);
	    self.options.templateId = templateId;
	    if(self.options && self.options.afterRender) {
	        origAfterRender = self.options.afterRender;
	        // todo: investigate - afterRender fires twice when using self.options
	        // first time it fires for "Loading..." div element
	        // link https://github.com/fazzamar/Knockout.js-External-Template-Engine/commit/5b053acd0465cd5c98b947d97cbd4d2e675c9f52
	        options.afterRender = function() {
	            if (self.loaded) {
	                origAfterRender.apply(self.options, arguments);
	            }
	        };
	    }
	};
	
	ko.utils.extend(ExternalTemplateSource.prototype, {
	    data: function(key, value) {
	        if (arguments.length === 1) {
	            if(key === "precompiled") {
	                this.template();
	            }
	            return this.template.data[key];
	        }
	        this.template.data[key] = value;
	    },
	
	    text: function(value) {
	        if (!this.loaded) {
	           this.getTemplate();
	        }
	
	        if (arguments.length === 0) {
	            return this.template();
	        } else {
	           this.template(arguments[0]);
	        }
	    },
	
	    getTemplate: function() {
	        var self = this;
	        infuser.get(self.options, function(tmpl) {
	            self.data("precompiled",null);
	            self.template(tmpl);
	            self.loaded = true;
	        });
	    }
	});
	var KoExternalTemplateEngine = function(koEngineType) {
	    var engine = koEngineType ? new koEngineType() : new ko.nativeTemplateEngine();
	    engine.templates = {};
	    engine.makeTemplateSource = function(template, bindingContext, options) {
	        // Named template
	        if (typeof template == "string") {
	            var elem = document.getElementById(template);
	            if (elem)
	                return new ko.templateSources.domElement(elem);
	            else {
	                if(!engine.templates[template]) {
	                    engine.templates[template] = new ExternalTemplateSource(template, options);
	                }
	                return engine.templates[template];
	            }
	        }
	        else if ((template.nodeType == 1) || (template.nodeType == 8)) {
	            // Anonymous template
	            return new ko.templateSources.anonymousTemplate(template);
	        }
	        
	    };
	
	    engine.renderTemplate = function (template, bindingContext, options) {
	        var templateSource = engine.makeTemplateSource(template, bindingContext, options);
	        return engine.renderTemplateSource(templateSource, bindingContext, options);
	    };
	
	    return engine;
	};
	
	ko.KoExternalTemplateEngine = KoExternalTemplateEngine;
	
	if (jQuery['tmpl'] && jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
	    ko.setTemplateEngine(new KoExternalTemplateEngine(ko.jqueryTmplTemplateEngine));
	}
	else {
	    ko.setTemplateEngine(new KoExternalTemplateEngine());
	}

})( window, ko, jQuery, infuser );;
(function (window, undefined) {
    'use strict';

    var fail = function () {

        gJobs.screenReadersService.setAriaLiveNotification("Login was failed");

        toastr.warning(Resources.NotificationMessages.ServiceUnavailable);
        OnlineApp.Helpers.layoutHelper.hideOnlineAppInnerSpinner();
        OnlineApp.Helpers.layoutHelper.hideOnlineAppSpinner();
    };

    var jawsReaderIEFormFix = function () {
        // Focus on an empty span to prevent JAWS from reading the whole SignIn form in IE.
        if (gJobs.browserDetector.isIE()) {
            gJobs.screenReadersService.silenceScreenreader();
        }
    };

    function hideStickyHeader() {
        $('#sticky-header').hide();
        $('#content').removeClass('respect-sticky-header');
    }

    function SignInViewModel() {
        var self = this;
        self.firstFieldHasFocus = ko.observable(false);
        var ShowAccessMembershipDialog = false;    
        var CAPTCHA_USER_ANSWER_INPUT_ID_FOR_LOGIN = "captcha-user-answer-for-login";
        var CAPTCHA_INVALID_MESSAGE = "Captcha is invalid";
        self.textCaptchaViewModel = new OnlineApp.ViewModels.TextCaptchaViewModel("Login");
        self.textCaptchaViewModel.setCustomUserAnswerInputId(CAPTCHA_USER_ANSWER_INPUT_ID_FOR_LOGIN);
        self.needsCaptcha = ko.observable(false);
        OnlineApp.Services.captchaService.isCaptchaRequiredForLogin()
            .done(function (isCaptchaRequired) {
                if (isCaptchaRequired) {
                    self.textCaptchaViewModel.getTextCaptchaQuestion();
                    self.needsCaptcha(isCaptchaRequired);
                }
            });
            
        var success = function (data) {
            if (data.isCaptchaRequired) {
                if (data.errorMessage == CAPTCHA_INVALID_MESSAGE) {
                    self.textCaptchaViewModel.refreshCaptchaAndSetFocusonUserAns(true, CAPTCHA_INVALID_MESSAGE);
                }
                else {
                    self.textCaptchaViewModel.refreshCaptchaAndSetFocusonUserAns();
                }
                self.needsCaptcha(true);
            }          
            if (data.forceRedirectUrl) {
                sessionStorage.setItem(OnlineApp.SessionKeys.PostBackUrl, window.location.href);
                if (self.showJobAlert()) {
                    sessionStorage.setItem(OnlineApp.LocalStorageKeys.RedirectToShowJobAlertPopup, "true");
                }
                window.location = data.forceRedirectUrl;
                return;
            }       
            OnlineApp.Helpers.layoutHelper.hideOnlineAppInnerSpinner();
            if (data.jobSeeker) {
                var savingProgress = "Saving... ";
                gJobs.screenReadersService.setAriaLiveNotification(savingProgress);
                setTimeout(function () {
                    gJobs.screenReadersService.setAriaLiveNotification("You are now logged in.");
                }, 300);
                OnlineApp.Helpers.layoutHelper.showOnlineAppSpinner();

                var applicationViewModel = OnlineApp.ViewModels.applicationViewModel;
                applicationViewModel.load();
                applicationViewModel.isAuthorized(true);

                //Audit successfull login action

                if (!applicationViewModel.definitionsViewModel) {
                    applicationViewModel.definitionsViewModel = new OnlineApp.ViewModels.DefinitionsViewModel();
                }

                var menuStep = applicationViewModel.definitionsViewModel.menuStep.findItemByField('text', 'LoginSuccess');
                /* 
                    Alexei Skachykhin: In a context of Government Jobs, jobId may not even exists.
                                       Direct attempt to dereference missing observable causes TypeError.
                */
                var jobId = ko.utils.unwrapObservable(applicationViewModel.jobId);
                OnlineApp.Services.auditService.setAction(jobId, menuStep.id);

                var isInJobContext = !!jobId;

                $(document).trigger(OnlineApp.Events.CommonEventsNames.Login, {
                    identity: {
                        userName: self.username()
                    },
                    isInJobContext: isInJobContext
                });

                // trigger native Event
                document.dispatchEvent(new CustomEvent(Events.CommonEventsNames.Angular.Login));

                gJobs.common.analytics.trackLoginEvent('Online Account');               


                OnlineApp.Services.jobAlertService.isJobAlertsEnabled()
                    .done(function (response) {
                        if (response.isJobAlertsEnabled) {
                            var currentArea = gJobs.areaInfoService.getCurrentArea();
                            var isAgencyPages = currentArea === gJobs.areaInfoService.areaNames.Career;
                            if (!isAgencyPages) {
                                OnlineApp.Services.jobAlertService.isJobAlertCanBeCreated(OnlineApp.Helpers.Url.getJsonFromUrl(location.search))
                                    .done(function (response) {
                                        if (response !== "") {
                                            hideStickyHeader();
                                            gJobs.dialogHelper.disableTabIndexOnParentView();
                                            $('#job-alert-out-container').html(response);
                                        }

                                        if (self.showJobAlert()) {
                                            hideStickyHeader();
                                            if (!ShowAccessMembershipDialog) {
                                                if ($('#job-alert-access-membership-popup')[0]) {
                                                    OnlineApp.Services.jobAlertService.isAccessMembershipEnabled()
                                                        .done((isAccessMembershipEnabled) => {
                                                            if (!isAccessMembershipEnabled) {
                                                                $('#job-alert-access-membership-popup').removeClass('hidden');
                                                                gJobs.screenReadersService.setAriaLiveNotification("Enroll in Free Access Membership modal is opened.");
                                                                gJobs.dialogHelper.setTabIndexOnJobAlertsPopup('#job-alert-access-membership-popup');
                                                            }
                                                            else {
                                                                displayJobAlert();
                                                            }
                                                        });
                                                }
                                                else {
                                                    displayJobAlert();
                                                }
                                            }

                                            function displayJobAlert() {
                                                $('#job-alert-out-container').removeClass('hidden');
                                                gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
                                            }
                                        }
                                    });
                            }
                        }
                    })

            } else {
                // TODO: replace with redirect to invalid login/password page 
                $(".standalone-validation-error").attr("aria-hidden", false);
                $(".form-signin").find("button[type=submit]").attr("aria-hidden", false);
                if (data.errorMessage != CAPTCHA_INVALID_MESSAGE) {
                    self.loginErrorMessage("");
                    self.loginErrorMessage(data.errorMessage);

                    $(".standalone-validation-error").focus();
                    $(document).trigger(Events.CommonEventsNames.LoginFailed);
                    $(".standalone-validation-error").attr("aria-hidden", true);
                    setTimeout(function () {
                        gJobs.screenReadersService.setAriaLiveNotification(data.errorMessage);
                        $(".form-signin").find("button[type=submit]").focus();
                    }, 300);                    
                }
            }
        };

        var currentUserNameFromUrlParam = window.utils.getUrlParameter('onLoadShowLoginWithUserName');
        if (!currentUserNameFromUrlParam) {
            currentUserNameFromUrlParam = '';
        }

        //Username or email for login.
        self.username = ko.observable().extend({
            required: {},
            composite: {
                validators: {
                    alphaNumericWithUnderscore: {},
                    email: {}
                },
                validationMessage: 'Invalid username or email.'
            },
        });

        self.password = ko.observable('').extend({ required: {} });
        self.showJobAlert = ko.observable(false);
        self.loginErrorMessage = ko.observable('');

        self.signInFormHeadingText = ko.observable('Sign in to apply');

        self.validate = function () {

            var isValid = true;

            self.username.validate();
            if (self.username.hasError()) {
                isValid = false;
            }

            self.password.validate();
            if (self.password.hasError()) {
                isValid = false;
            }

            self.textCaptchaViewModel.validate();
            if (self.needsCaptcha() && self.textCaptchaViewModel.userAnswer.hasError()) {
                isValid = false;
            }

            return isValid;
        };

        self.login = function () {
            if (self.validate()) {

                OnlineApp.Helpers.layoutHelper.showOnlineAppInnerSpinner();

                var promise;
                self.isBusy(true);
                if (self.needsCaptcha()) {
                    promise = OnlineApp.Services.authenticationService
                        .login(self.username(), self.password(), self.textCaptchaViewModel.userAnswer())
                        .always(function () {
                            self.isBusy(false);
                        })
                        .fail(fail)
                        .done(success);
                } else {
                    promise = OnlineApp.Services.authenticationService
                        .login(self.username(), self.password(), undefined)
                        .always(function () {
                            self.isBusy(false);
                        })
                        .fail(fail)
                        .done(success);
                }

                jawsReaderIEFormFix();

                return promise;
            } else {
                var savingProgress = "Saving... ";
                OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement(undefined, function ($firstTabbingElement) {
                    gJobs.screenReadersService.onceNotification({
                        $element: $firstTabbingElement,
                        message: savingProgress + 'Entered form is invalid. Please fix the errors. '
                    });
                });
            }

            // TODO: replace call to jQuery
            return $.when();
        };

        self.isActive = ko.observable(true);

        self.isBusy = ko.observable(false);

        self.clearFields = function () {
            self.username('');
            self.username.hasError(false);

            self.password('');
            self.password.hasError(false);
        };
        $(document).on(Events.CommonEventsNames.OpenAccessMembershipDialog, function () {
            ShowAccessMembershipDialog = true;
        });
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        SignInViewModel: SignInViewModel,
    });

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

    var fail = function () {
        toastr.warning(Resources.NotificationMessages.ServiceUnavailable);
        OnlineApp.Helpers.layoutHelper.hideOnlineAppInnerSpinner();
        OnlineApp.Helpers.layoutHelper.hideOnlineAppSpinner();
    };

    var jawsReaderIEFormFix = function () {
        // Focus on an empty span to prevent JAWS from reading the whole SignIn form in IE.
        if (gJobs.browserDetector.isIE()) {
            gJobs.screenReadersService.silenceScreenreader();
        }
    };

    var captchaHelper = OnlineApp.Helpers.loginCaptchaHelper;

    // TODO: think about separating email/confirmEmail, username and password to separate entities inside of VM
    function RegisterViewModel() {
        var self = this;
        self.firstFieldHasFocus = ko.observable(false);
        self.isSubmitted = ko.observable(false);
        self.showJobAlert = ko.observable(false);

        self.textCaptchaViewModel = new OnlineApp.ViewModels.TextCaptchaViewModel();
        OnlineApp.Services.captchaService.isCaptchaRequiredForRegister()
            .done(function(isCaptchaRequired) {
                if (isCaptchaRequired) {
                    self.textCaptchaViewModel.getTextCaptchaQuestion();
                    self.needsCaptcha(true);
                }
            });

        var success = function (data) {

            //captchaHelper.resetCaptcha();

            OnlineApp.Helpers.layoutHelper.hideOnlineAppInnerSpinner();
            if (data.success) {
                if (data.forceRedirectUrl) {
                    window.location = data.forceRedirectUrl;
                    return;
                }

                var applicationViewModel = OnlineApp.ViewModels.applicationViewModel;

                applicationViewModel.load();
                applicationViewModel.isAuthorized(true);

                //Audit successfull register action

                if (!applicationViewModel.definitionsViewModel) {
                    applicationViewModel.definitionsViewModel = new OnlineApp.ViewModels.DefinitionsViewModel();
                }

                gJobs.screenReadersService.setAriaLiveNotification('Account created. You are now logged in.');

                var menuStep = applicationViewModel.definitionsViewModel.menuStep.findItemByField('text', 'Register');
                /* 
                    Alexei Skachykhin: In a context of Government Jobs, jobId may not even exists.
                                       Direct attempt to dereference missing observable causes TypeError.
                */
                var jobId = ko.utils.unwrapObservable(applicationViewModel.jobId);
                OnlineApp.Services.auditService.setAction(jobId, menuStep.id);

                var isInJobContext = !!jobId;

                $(document).trigger(OnlineApp.Events.CommonEventsNames.Register, {
                    identity: {
                        userName: self.username(),
                        email: self.email()
                    },
                    isInJobContext: isInJobContext
                });

                // trigger native Event
                document.dispatchEvent(new CustomEvent(Events.CommonEventsNames.Angular.Register));
                self.isUserRegisteredInCurrentSession(true);

                OnlineApp.Services.jobAlertService.isJobAlertsEnabled()
                    .done(function (isJobAlertsEnabled) {
                        if (isJobAlertsEnabled) {
                            var currentArea = gJobs.areaInfoService.getCurrentArea();
                            var isAgencyPages = currentArea === gJobs.areaInfoService.areaNames.Career;
                            if (!isAgencyPages) {
                                OnlineApp.Services.jobAlertService.isJobAlertCanBeCreated(OnlineApp.Helpers.Url.getJsonFromUrl(location.search))
                                    .done(function () {
                                        if (self.showJobAlert()) {
                                            $(document).on(Events.CommonEventsNames.CloseAccessMembershipDialog, function (event) {
                                                $('#job-alert-out-container').removeClass('hidden');
                                            });
                                        }
                                    });
                            }
                        }
                    })
            } else {
                var promise;

                if (data.isCaptchaRequired) {
                    promise = self.textCaptchaViewModel.resetCaptcha()
                        .then(function() {
                            self.needsCaptcha(true);
                        });
                } else {
                    promise = $.when(function() { return true; });
                }

                promise.then(function() {
                    self.registerErrorMessage("");
                    self.email.validationMessage("");
                    switch (data.errorPropertyName) {
                        case 'Email':
                            self.email.hasError(true);
                            self.email.validationMessage(data.errorMessage);
                            self.email.isValidationMessageVisible(true);
                            self.hasEmailChangedAfterError(false);
                            self.externalEmailError(data.errorMessage);
                            OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                            break;
                        case 'Username':
                            self.username.hasError(true);
                            self.username.validationMessage(data.errorMessage);
                            self.username.isValidationMessageVisible(true);
                            self.hasUsernameChangedAfterError(false);
                            self.externalUsernameError(data.errorMessage);
                            OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                            break;
                        case 'Password':
                            self.password.hasError(true);
                            self.password.validationMessage(data.errorMessage);
                            self.password.isValidationMessageVisible(true);
                            self.hasPasswordChangedAfterError(false);
                            OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                            break;
                        case 'Captcha':
                            self.textCaptchaViewModel.userAnswer.hasError(true);
                            self.textCaptchaViewModel.userAnswer.validationMessage(data.errorMessage);
                            self.textCaptchaViewModel.userAnswer.isValidationMessageVisible(true);
                            OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                            break;
                        default:
                            self.registerErrorMessage(data.errorMessage);
                            $('.form-validation-error:visible').first().focus();
                            $('.form-validation-error:visible').first().on("blur",
                                function() {
                                    OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                                    $(this).off("blur");
                                });
                            break;
                    }
                });

                return promise;
            }
        };

        self.createAccountFormHeadingText = ko.observable('Create a new account');

        self.needsCaptcha = ko.observable(false);

        self.username = ko.observable('').extend({
            required: {},
            alphaNumericWithUnderscore: {
                validationMessage: 'Username may contain only alphanumerics and underscore.',
                showValidationMessage: true
            }
        });
        self.isUsernameSelected = ko.observable(false);
        self.isUsernameAvailable = ko.computed(function () {
            return self.username() && !self.username.hasError();
        });
        self.isUsernameNotAvailable = ko.observable(false);
        self.hasUsernameChangedAfterError = ko.observable(true);
        self.externalUsernameError = ko.observable('');
        self.username.subscribe(function (value) {
            if (value) {
                self.checkUsername();
            } else {
                self.isUsernameNotAvailable(false);
            }

            self.hasUsernameChangedAfterError(true);
            self.externalUsernameError('')
        });
        self.isUsernameNotValid = ko.computed(function() {
            return self.isUsernameNotAvailable() || self.username.hasError();
        });

        self.email = ko.observable('').extend({ required: {}, email: {} });

        /* TODO - make refactoring of the code below - remove redundant variables */
        self.isEmailSelected = ko.observable(false);
        self.isEmailAllowed = ko.observable(false);
        self.isEmailAvailable = ko.computed(function () {
            return self.email() && !self.email.hasError();
        });
        self.isEmailNotAvailable = ko.observable(false);
        self.isEmailTooltipFocusable = ko.observable(true);
        self.hasEmailChangedAfterError = ko.observable(true);
        self.externalEmailError = ko.observable('');
        self.email.subscribe(function (value) {
            if (value) {
                self.checkEmail();
            } else {
                self.isEmailNotAvailable(false);
            }

            self.hasEmailChangedAfterError(true);
            self.externalEmailError('');
        });
        self.isEmailNotValid = ko.computed(function () {
            return self.isEmailNotAvailable() || self.email.hasError();
        });

        self.password = OnlineApp.ViewModels.Common.PasswordExtender({ required: {}, password: {} });
        self.passwordStrength = ko.observable('');
        self.isPasswordSelected = ko.observable(false);

        self.isInPasswordBlock = ko.observable(false);
        self.passwordRequirements = Resources.AdditionalInfoMessages.passwordRequirements;
        self.hasPasswordChangedAfterError = ko.observable(true);
        self.password.subscribe(function(value) {
            self.hasPasswordChangedAfterError(true);
        });
        self.inPasswordBlock = function () {
            self.isInPasswordBlock(true);
        };
        self.outOfPasswordBlock = function () {
            if (self.hasPasswordChangedAfterError()) {
                if (self.isInPasswordBlock() && !self.isPasswordSelected() && !self.password.isConfirmPasswordSelected()) {
                    self.isInPasswordBlock(false);

                    self.password.validate();
                    if (self.password.hasError()) {
                        gJobs.screenReadersService.setAriaLiveNotification("Password " + self.password.validationMessage());
                    }
                }
            }
        };

        self.outOfEmailBlock = function (model, event) {
            if (self.hasEmailChangedAfterError()) {
                // set handling to the end of event queue
                self.email.validate();
                if (self.email.hasError()) {
                    var sourceElement = event.target;
                    var sourceElementType = sourceElement.tagName.toLowerCase();
                    if (sourceElementType === 'span') {
                        gJobs.screenReadersService.setAriaLiveNotification("Email " + self.email.validationMessage());
                    }
                }
            }
        };

        self.outOfUsernameBlock = function () {
            if (self.hasUsernameChangedAfterError()) {
                // set handling to the end of event queue
                self.username.validate();
                if (self.username.hasError()) {
                    gJobs.screenReadersService.setAriaLiveNotification("Username " + self.username.validationMessage());
                }
            }
        };

        self.showPasswordConfirmation = ko.computed(function() {
            return self.isInPasswordBlock() || !self.password.isPasswordConfirmed();
        });

        self.isPasswordAllowed = ko.computed(function() {
            return !self.password.hasError() && self.password.isPasswordConfirmed() && self.password();
        });

        self.registerErrorMessage = ko.observable('');

        self.validate = function () {
            var isValid = true;

            self.email.validate();
            if (self.email.hasError() || !self.hasEmailChangedAfterError()) {
                isValid = false;
            }

            self.username.validate();
            if (self.username.hasError() || !self.hasUsernameChangedAfterError()) {
                isValid = false;
            }

            self.password.validate();
            if (self.password.hasError() || !self.password.isPasswordConfirmed()
                || !self.hasPasswordChangedAfterError()) {
                isValid = false;
            }

            self.textCaptchaViewModel.validate();
            if (self.needsCaptcha() && self.textCaptchaViewModel.userAnswer.hasError()) {
                isValid = false;
            }

            return isValid;
        };

        self.checkUsername = function () {
            self.username.validate();
        };

        self.checkEmail = function () {
            self.email.validate();
            
        };

        self.emailIsValidNotificationMessage = ko.computed(function () {
            if (!self.isSubmitted()) {
                return '';
            }
            return !self.email() || self.email.hasError() ? 'email is not valid' : 'email is valid';
        });

        self.passwordsAreValidNotificationMessage = ko.computed(function () {
            return self.password() && self.password.isPasswordConfirmed() ? 'passwords match' : '';
        });

        self.register = function () {
            if (self.validate()) {
                var savingProgress = "Saving... ";
                gJobs.screenReadersService.setAriaLiveNotification(savingProgress);

                OnlineApp.Helpers.layoutHelper.showOnlineAppInnerSpinner();

                self.isBusy(true);

                if (self.needsCaptcha()) {

                    OnlineApp.Services.authenticationService
                    .register(self.username(),
                        self.password(),
                        self.email(),
                        self.textCaptchaViewModel.userAnswer())
                    .always(function () {
                        self.isBusy(false);
                    })
                    .fail(function (data) {
                        //fail with providedAnswer==false means that user closed the captcha modal without answering
                        if (!(data && data.providedAnswer === false)) {
                            fail();
                        }
                    })
                    .done(success);

                    var message = gJobs.common.analytics.messages.captchaMessage;
                    gJobs.common.analytics.trackLoginEvent(message + ' (CreateAccount)');
                } else {

                    OnlineApp.Services.authenticationService
                        .register(self.username(), self.password(), self.email())
                        .always(function () {
                            self.isBusy(false);
                        })
                        .done(success)
                        .fail(fail);
                }
                jawsReaderIEFormFix();
                self.isSubmitted(true);
            } else {
                self.isSubmitted(true);

                if (!self.hasEmailChangedAfterError() && !self.textCaptchaViewModel.hasError()) {
                    self.email.hasError(true);
                    self.email.validationMessage(self.externalEmailError());
                    self.email.isValidationMessageVisible(true);
                }

                if (!self.hasUsernameChangedAfterError() && !self.textCaptchaViewModel.hasError()) {
                    self.username.hasError(true);
                    self.username.validationMessage(self.externalUsernameError());
                    self.username.isValidationMessageVisible(true);
                }

                var $firstInvalidField = OnlineApp.Helpers.layoutHelper.tabbing.getFirstElement();

                var notificationContainerId = 'register-error-notification';
                var savingProgressContainerId = 'saving-progress-notification';

                gJobs.screenReadersService.onceAriaLabelledByNotification({
                    notificationContainerIds: savingProgressContainerId + ',' + notificationContainerId,
                    $element: $firstInvalidField
                });

                $firstInvalidField.focus();
            }
        };

        self.isActive = ko.observable(false);

        self.isUserRegisteredInCurrentSession = ko.observable(false);

        self.isBusy = ko.observable(false);

        self.clearFields = function () {
            self.username('');
            self.username.hasError(false);

            self.email('');
            self.email.hasError(false);

            self.password.clearFields();
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        RegisterViewModel: RegisterViewModel,
    });

})(window);
;
(function (window, undefined) {
    'use strict';

    var captchaHelper = OnlineApp.Helpers.loginCaptchaHelper;

    function LoginViewModel() {
        var self = this;
        self.schoolJobsConstant = window.SchoolJobSiteConstant;
        self.isGjobs = window.IsGjobs;
        self.signInViewModel = new OnlineApp.ViewModels.SignInViewModel();
        self.registerViewModel = new OnlineApp.ViewModels.RegisterViewModel();
        self.enableGoogleSSO = window.enableGoogleSSO;

        const googleButtonConfig = {
            type: "standard",
            size: "medium",
            height: "45",
            width: "280",
            theme: "outline",
            shape: "rectangular",
            text: "sign_in_with",
            logo_alignment: "center"
        };

        self.loginFacebook = function (data, event) {
            var $externalSignInForm = $(event.target).closest('.form-external-signin');
            var showJobAlert = data.signInViewModel.showJobAlert();
            FB.login(function (loginResponse) {
                if (loginResponse.authResponse) {
                    $('<input>').attr({
                        type: 'hidden',
                        name: 'accessToken',
                        value: loginResponse.authResponse.accessToken
                    }).appendTo($externalSignInForm);

                    $('<input>').attr({
                        type: 'hidden',
                        name: 'provider',
                        value: 'Facebook'
                    }).appendTo($externalSignInForm);

                    if (window.enableTwoFactorAuthentication) {
                        sessionStorage.setItem(OnlineApp.SessionKeys.PostBackUrl, window.location.href);
                    }

                    if (showJobAlert) {
                        sessionStorage.setItem(OnlineApp.LocalStorageKeys.ShowJobAlertPopup, "true");
                    }

                    $externalSignInForm.trigger('submit');
                }
            }, { auth_type: 'reauthenticate', scope: 'email,public_profile' });
        }

        self.signInUrl = getSignInUrl();
        self.toggleModels = function (viewModel, e) {
            var isSignInActive = self.signInViewModel.isActive();
            var $container;
            var isStandaloneBlock = false;
            var isHeaderBlock = false;

            if (e) {
                if (e.currentTarget.id == 'login-button' || e.currentTarget.id == 'signup-button') {
                    isHeaderBlock = true;
                }

                $container = $(e.target).parents(".sign-in-sign-up-container");
                isStandaloneBlock = $container.parents("#standalone-sign-in-block").length > 0;
            }

            if (isSignInActive && e) {
                $(document).trigger(OnlineApp.Events.CommonEventsNames.RegisterAccountLinkClicked, e);
            }

            if (isSignInActive) {
                self.signInViewModel.clearFields();
            }
            else {
                self.registerViewModel.clearFields();
            }

            self.signInViewModel.isActive(!isSignInActive);
            self.registerViewModel.isActive(isSignInActive);

            if (self.registerViewModel.isActive() && self.registerViewModel.needsCaptcha())
                captchaHelper.renderCaptcha();

            $(document).trigger('layoutUpdated');

            self.registerViewModel.firstFieldHasFocus(isStandaloneBlock ? isSignInActive : false);
            self.signInViewModel.firstFieldHasFocus(isStandaloneBlock ? !isSignInActive : false);

            if (e && !isHeaderBlock) {
                if (isSignInActive) {
                    $(document).trigger(OnlineApp.Events.CommonEventsNames.RegisterAccountFormOpened, $container);
                } else {
                    $(document).trigger(OnlineApp.Events.CommonEventsNames.LoginFormOpened, $container);
                }
            }
        };

        self.onSignInLinkClick = function (e) {

            if (self.signInViewModel.isActive()) {
                self.signInViewModel.clearFields();
            } else {
                self.registerViewModel.clearFields();
            }

            if (gJobs && gJobs.signInForm && gJobs.signInForm.show && !gJobs.signInForm.isOpen()) {
                gJobs.signInForm.show();
            }
            setTimeout(function () {
                gJobs.signInForm.focusFirstTabbableElement();

                if (self.signInViewModel.isActive()) {
                    $(document).trigger(OnlineApp.Events.CommonEventsNames.LoginFormOpened);
                } else {
                    $(document).trigger(OnlineApp.Events.CommonEventsNames.RegisterAccountFormOpened);
                }
            });


        };

        self.onEmployerKeydown = function (el, e) {
            if (e.keyCode === $.ui.keyCode.SPACE) {
                window.location.href = $(e.target).attr("href");
            }
            return true;
        };       

        function handleCredentialResponse(response) {
            // Decode the JWT token
            if (response && response.credential) {
                let $externalSignInForm = $('#external-login-form');
                let showJobAlert = self.signInViewModel.showJobAlert();
                const idToken = response.credential;                
                const payload = JSON.parse(atob(idToken.split('.')[1]));
                const payload2 = JSON.parse(atob(idToken.split('.')[0]));                
                $('<input>').attr({
                    type: 'hidden',
                    name: 'accessToken',
                    value: idToken
                }).appendTo($externalSignInForm);

                $('<input>').attr({
                    type: 'hidden',
                    name: 'provider',
                    value: 'Google'
                }).appendTo($externalSignInForm);

                if (window.enableTwoFactorAuthentication) {
                    sessionStorage.setItem(OnlineApp.SessionKeys.PostBackUrl, window.location.href);
                }

                if (showJobAlert) {
                    sessionStorage.setItem(OnlineApp.LocalStorageKeys.ShowJobAlertPopup, "true");
                }

                $externalSignInForm.trigger('submit');
            }            
        }

        function getSignInUrl() {
            var queryString = '/Oauth/Login?ReturnUrl=';

            if (window.location.hash && window.location.hash == '#_=_') {
                window.location.hash = '';
            }

            var currentUrl = encodeURIComponent(window.location.href);
            queryString += currentUrl;

            return queryString;
        };

        function renderGoogleButton(element) {
            if (element) {
                google.accounts.id.renderButton(element, googleButtonConfig);
            }
        }

        function tryRenderGoogleButtons() {
            var googleButtonElement = $("#content-container-redesign").find("#google-sign-in");
            var googleButtonElementSjobs = $(".sjobs-flyout-window-body").find("#google-sign-in");
            if (document.getElementById("google-sign-in")) {
                renderGoogleButton(document.getElementById("google-sign-in"));
            }
            if (document.getElementById("popup-google-sign-in")) {
                renderGoogleButton(document.getElementById("popup-google-sign-in"));
            }
            if (googleButtonElement && googleButtonElement.length > 0) {
                renderGoogleButton(googleButtonElement[0]);
            }
            if (googleButtonElementSjobs && googleButtonElementSjobs.length > 0) {
                renderGoogleButton(googleButtonElementSjobs[0]);
            }
        }

        $(document).ready(function () {
            $('body').scrollTop(0);
            if (window.enableGoogleSSO) {
                google.accounts.id.initialize({
                    client_id: window.googleClientID,
                    callback: handleCredentialResponse
                });
                // Run once at start
                tryRenderGoogleButtons();
                // Observe DOM changes
                var observer = new MutationObserver(function (mutations, obs) {
                    // Only run if a new button is added (not already present)
                    var found = false;
                    mutations.forEach(function (mutation) {
                        if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                            $(mutation.addedNodes).each(function () {
                                if (
                                    this.id === "google-sign-in" ||
                                    this.id === "popup-google-sign-in" ||
                                    $(this).find("#google-sign-in").length > 0 ||
                                    $(this).find("#popup-google-sign-in").length > 0
                                ) {
                                    found = true;
                                }
                            });
                        }
                    });
                    if (found) {
                        tryRenderGoogleButtons();
                        obs.disconnect(); // Stop observing after rendering
                    }
                });
                observer.observe(document.body, { childList: true, subtree: true });
                // Fallback: disconnect after 10 seconds to avoid leaks if buttons never appear
                setTimeout(function () {
                    observer.disconnect();
                }, 5000);
            }
        });
    }




    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        LoginViewModel: LoginViewModel
    });

})(window);;
(function(window, undefined) {
    'use strict';

    function TextCaptchaViewModel(keyForTextCaptchaAnswer) {
        var self = this;
        var isRefreshClicked = false;
        var setFocusonUserAnsInput = false;
        var keyForAnswer = keyForTextCaptchaAnswer ? keyForTextCaptchaAnswer : "";

        self.question = ko.observable();
        self.userAnswer = ko.observable('').extend({ required: {}});
        self.isBusy = ko.observable(false);
        self.customLabelHtmlContent = ko.observable("");
        self.customUserAnswerInputId = ko.observable("");

        self.getTextCaptchaQuestion = function () {
            self.isBusy(true);

            return OnlineApp.Services.captchaService.getCaptcha(keyForAnswer).done(function (question) {
                if (question) {
                    self.question(question);
                    gJobs.screenReadersService.setAriaLiveNotification('New captcha question is loaded', '.text-captcha-container .loaded-notification:visible');
                }                
                else if (setFocusonUserAnsInput) {
                    $('#' + self.getCustomIdForUserAnswerCaptcha()).focus();    
                    $('#popup-' + self.getCustomIdForUserAnswerCaptcha()).focus(); 
                }
                else {
                    $('#skip-to-content-button').focus();
                }
            }).then(function () {
                self.isBusy(false);
                if (isRefreshClicked) {
                    $('#' + self.getCustomIdForUserAnswerCaptcha()).focus(); 
                    $('#popup-' + self.getCustomIdForUserAnswerCaptcha()).focus(); 
                    isRefreshClicked = false;
                }
                else if (setFocusonUserAnsInput) {
                    $('#' + self.getCustomIdForUserAnswerCaptcha()).focus();  
                    $('#popup-' + self.getCustomIdForUserAnswerCaptcha()).focus(); 
                    setFocusonUserAnsInput = false;
                }
                else {
                    $('#skip-to-content-button').focus();
                }
            });
        }

        self.validate = function() {
            return self.userAnswer.validate();
        }

        self.hasError = function() {
            return self.userAnswer.hasError();
        }

        self.refreshCaptcha = function () {
            isRefreshClicked = true;
            self.resetCaptcha();
        }

        self.refreshCaptchaAndSetFocusonUserAns = function (hasError, errorMessage) {
            setFocusonUserAnsInput = true;
            self.resetCaptcha(hasError, errorMessage);
        }

        self.resetCaptcha = function (hasError, errorMessage, customUserAnswerInputId, updatedCaptchaQuestion) {
            self.userAnswer('');
            setFocusonUserAnsInput = true;
            self.userAnswer.hasError(hasError);
            self.userAnswer.validationMessage(errorMessage);
            self.userAnswer.isValidationMessageVisible(hasError);

            if (updatedCaptchaQuestion) {
                self.question(updatedCaptchaQuestion);
                setTimeout(function() {
                    gJobs.screenReadersService.setAriaLiveNotification('New captcha question is loaded', '.text-captcha-container .loaded-notification:visible');
                }, 400);
                if (setFocusonUserAnsInput) {
                    setTimeout(function() {
                        $('#' + self.getCustomIdForUserAnswerCaptcha()).focus();
                    }, 400);
                }
                else {
                    $('#skip-to-content-button').focus();
                }
            } else {
                self.getTextCaptchaQuestion();
            }
        }
        
        self.setCustomLabelHtmlContent = function (htmlContent) {
            if (self.customLabelHtmlContent() !== htmlContent) {
                self.customLabelHtmlContent(htmlContent);
            }
        }

        self.setCustomUserAnswerInputId = function (customUserAnswerInputId) {
            if (self.customUserAnswerInputId() !== customUserAnswerInputId) {
                self.customUserAnswerInputId(customUserAnswerInputId);
            }
        }

        self.getCaptchaLabelHtmlContent = function () {
            var customLabelHtmlContent = self.customLabelHtmlContent();

            if (customLabelHtmlContent) {
                return customLabelHtmlContent;
            } else {
                return "Please verify that you are not a robot<span class='sr-only'>.</span>";
            }
        }

        self.getCustomIdForUserAnswerCaptcha = function () {
            var customUserAnswerInputId = self.customUserAnswerInputId();
            if (customUserAnswerInputId) {
                return customUserAnswerInputId;
            } else {
                return 'text-captcha-user-answer';
            }
        }
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        TextCaptchaViewModel: TextCaptchaViewModel,
    });

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

    function ApplicationSignInViewModel() {

        var self = this;

        /*
            Define child view-models
        */
        (function () {
            var vm = OnlineApp.ViewModels;

            if (vm.LoginViewModel) {
                self.loginViewModel = new vm.LoginViewModel();
            }
        })();

        /*
            Public members.
        */
        self.isAuthorized = ko.observable(false);

        self.load = function() {
            // do nothing here
        };

        self.loginLoaded = function () {
            $(document).trigger('ApplicationSignInViewModel:ViewLoaded');
        };
        
        self.FocusinValidationVisibleChange = function (event, field) {
            if (event.type == 'focusin') {
                field.isValidationMessageVisible(false);
            } else if (event.type == 'focusout') {
                if (field.hasError()) {
                    field.isValidationMessageVisible(true);
                }
            }
        };

        self.checkIfShouldCreateNewAccount = function() {
            if (sessionStorage.getItem('shouldCreateNewAccount')) {
                sessionStorage.removeItem('shouldCreateNewAccount');

                self.loginViewModel.toggleModels(null, null);
            }
        };

        $(document).on("toggleLogInAndRegister", function (e, sourceEvent) {
            self.loginViewModel.toggleModels(null, sourceEvent);
        });
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        applicationViewModel: new ApplicationSignInViewModel()
    });

    $(document).ready(function () {
        OnlineApp.Services.authenticationService
            .isLoggedIn()
            .fail(function () {
                toastr.warning(Resources.NotificationMessages.ServerConnectionFailed);
            })
            .done(function (data) {
                if (data) {
                    OnlineApp.ViewModels.applicationViewModel.isAuthorized(true);
                } else {
                    OnlineApp.ViewModels.applicationViewModel.isAuthorized(false);
                }
            });
    });

})(window);
;
