/* Minification failed. Returning unminified contents.
(15488,6716-6721): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,8761-8766): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,9743-9748): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,14778-14783): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,17832-17837): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,40582-40587): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,68720-68725): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,80158-80163): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,81256-81261): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,86115-86120): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,93645-93652): run-time error JS1137: 'default' is a new reserved word and should not be used as an identifier: default
(15488,94666-94671): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,101682-101687): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,113181-113186): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,113329-113336): run-time error JS1137: 'finally' is a new reserved word and should not be used as an identifier: finally
(15488,119303-119308): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,123665-123670): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,124275-124280): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,180996-181001): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,182290-182295): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,182708-182713): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,185930-185935): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,186033-186038): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,186227-186232): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,187487-187492): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,195840-195845): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,196221-196226): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,285129-285134): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,287049-287054): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,299447-299452): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,299901-299906): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,300168-300173): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,302649-302654): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,302163-302168): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,302350-302355): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,303300-303305): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,308220-308225): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,312903-312908): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,318759-318764): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,319132-319137): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,322949-322954): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,322503-322508): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
(15488,322809-322814): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
 */
/*! jQuery v3.2.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.2.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c<b?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:h,sort:c.sort,splice:c.splice},r.extend=r.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||r.isFunction(g)||(g={}),h===i&&(g=this,h--);h<i;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(r.isPlainObject(d)||(e=Array.isArray(d)))?(e?(e=!1,f=c&&Array.isArray(c)?c:[]):f=c&&r.isPlainObject(c)?c:{},g[b]=r.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},r.extend({expando:"jQuery"+(q+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===r.type(a)},isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=r.type(a);return("number"===b||"string"===b)&&!isNaN(a-parseFloat(a))},isPlainObject:function(a){var b,c;return!(!a||"[object Object]"!==k.call(a))&&(!(b=e(a))||(c=l.call(b,"constructor")&&b.constructor,"function"==typeof c&&m.call(c)===n))},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?j[k.call(a)]||"object":typeof a},globalEval:function(a){p(a)},camelCase:function(a){return a.replace(t,"ms-").replace(u,v)},each:function(a,b){var c,d=0;if(w(a)){for(c=a.length;d<c;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(s,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(w(Object(a))?r.merge(c,"string"==typeof a?[a]:a):h.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:i.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;d<c;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;f<g;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,f=0,h=[];if(w(a))for(d=a.length;f<d;f++)e=b(a[f],f,c),null!=e&&h.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&h.push(e);return g.apply([],h)},guid:1,proxy:function(a,b){var c,d,e;if("string"==typeof b&&(c=a[b],b=a,a=c),r.isFunction(a))return d=f.call(arguments,2),e=function(){return a.apply(b||this,d.concat(f.call(arguments)))},e.guid=a.guid=a.guid||r.guid++,e},now:Date.now,support:o}),"function"==typeof Symbol&&(r.fn[Symbol.iterator]=c[Symbol.iterator]),r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){j["[object "+b+"]"]=b.toLowerCase()});function w(a){var b=!!a&&"length"in a&&a.length,c=r.type(a);return"function"!==c&&!r.isWindow(a)&&("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",M="\\["+K+"*("+L+")(?:"+K+"*([*^$|!~]?=)"+K+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+L+"))|)"+K+"*\\]",N=":("+L+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(K+"+","g"),P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c<b;c+=2)a.push(c);return a}),odd:pa(function(a,b){for(var c=1;c<b;c+=2)a.push(c);return a}),lt:pa(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function ra(){}ra.prototype=d.filters=d.pseudos,d.setFilters=new ra,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=Q.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function sa(a){for(var b=0,c=a.length,d="";b<c;b++)d+=a[b].value;return d}function ta(a,b,c){var d=b.dir,e=b.next,f=e||d,g=c&&"parentNode"===f,h=x++;return b.first?function(b,c,e){while(b=b[d])if(1===b.nodeType||g)return a(b,c,e);return!1}:function(b,c,i){var j,k,l,m=[w,h];if(i){while(b=b[d])if((1===b.nodeType||g)&&a(b,c,i))return!0}else while(b=b[d])if(1===b.nodeType||g)if(l=b[u]||(b[u]={}),k=l[b.uniqueID]||(l[b.uniqueID]={}),e&&e===b.nodeName.toLowerCase())b=b[d]||b;else{if((j=k[f])&&j[0]===w&&j[1]===h)return m[2]=j[2];if(k[f]=m,m[2]=a(b,c,i))return!0}return!1}}function ua(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d<e;d++)ga(a,b[d],c);return c}function wa(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;h<i;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function xa(a,b,c,d,e,f){return d&&!d[u]&&(d=xa(d)),e&&!e[u]&&(e=xa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||va(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:wa(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=wa(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i<f;i++)if(c=d.relative[a[i].type])m=[ta(ua(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;e<f;e++)if(d.relative[a[e].type])break;return xa(i>1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i<e&&ya(a.slice(i,e)),e<f&&ya(a=a.slice(e)),e<f&&sa(a))}m.push(c)}return ua(m)}function za(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext;function B(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()}var C=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,D=/^.[^:#\[\.,]*$/;function E(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):D.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b<d;b++)if(r.contains(e[b],this))return!0}));for(c=this.pushStack([]),b=0;b<d;b++)r.find(a,e[b],c);return d>1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(E(this,a||[],!1))},not:function(a){return this.pushStack(E(this,a||[],!0))},is:function(a){return!!E(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var F,G=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,H=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||F,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:G.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),C.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};H.prototype=r.fn,F=r(d);var I=/^(?:parents|prev(?:Until|All))/,J={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a<c;a++)if(r.contains(this,b[a]))return!0})},closest:function(a,b){var c,d=0,e=this.length,f=[],g="string"!=typeof a&&r(a);if(!A.test(a))for(;d<e;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function K(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return K(a,"nextSibling")},prev:function(a){return K(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return B(a,"iframe")?a.contentDocument:(B(a,"template")&&(a=a.content||a),r.merge([],a.childNodes))}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(J[a]||r.uniqueSort(e),I.test(a)&&e.reverse()),this.pushStack(e)}});var L=/[^\x20\t\r\n\f]+/g;function M(a){var b={};return r.each(a.match(L)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?M(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=e||a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){r.each(b,function(b,c){r.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==r.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return r.each(arguments,function(a,b){var c;while((c=r.inArray(b,f,c))>-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function N(a){return a}function O(a){throw a}function P(a,b,c,d){var e;try{a&&r.isFunction(e=a.promise)?e.call(a).done(b).fail(c):a&&r.isFunction(e=a.then)?e.call(a,b,c):b.apply(void 0,[a].slice(d))}catch(a){c.apply(void 0,[a])}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b<f)){if(a=d.apply(h,i),a===c.promise())throw new TypeError("Thenable self-resolution");j=a&&("object"==typeof a||"function"==typeof a)&&a.then,r.isFunction(j)?e?j.call(a,g(f,c,N,e),g(f,c,O,e)):(f++,j.call(a,g(f,c,N,e),g(f,c,O,e),g(f,c,N,c.notifyWith))):(d!==N&&(h=void 0,i=[a]),(e||c.resolveWith)(h,i))}},k=e?j:function(){try{j()}catch(a){r.Deferred.exceptionHook&&r.Deferred.exceptionHook(a,k.stackTrace),b+1>=f&&(d!==O&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:N,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:N)),c[2][3].add(g(0,a,r.isFunction(d)?d:O))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(P(a,g.done(h(c)).resolve,g.reject,!b),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)P(e[c],h(c),g.reject);return g.promise()}});var Q=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&Q.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var R=r.Deferred();r.fn.ready=function(a){return R.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||R.resolveWith(d,[r]))}}),r.ready.then=R.then;function S(){d.removeEventListener("DOMContentLoaded",S),
a.removeEventListener("load",S),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",S),a.addEventListener("load",S));var T=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)T(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h<i;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},U=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function V(){this.expando=r.expando+V.uid++}V.uid=1,V.prototype={cache:function(a){var b=a[this.expando];return b||(b={},U(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[r.camelCase(b)]=c;else for(d in b)e[r.camelCase(d)]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][r.camelCase(b)]},access:function(a,b,c){return void 0===b||b&&"string"==typeof b&&void 0===c?this.get(a,b):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d=a[this.expando];if(void 0!==d){if(void 0!==b){Array.isArray(b)?b=b.map(r.camelCase):(b=r.camelCase(b),b=b in d?[b]:b.match(L)||[]),c=b.length;while(c--)delete d[b[c]]}(void 0===b||r.isEmptyObject(d))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!r.isEmptyObject(b)}};var W=new V,X=new V,Y=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Z=/[A-Z]/g;function $(a){return"true"===a||"false"!==a&&("null"===a?null:a===+a+""?+a:Y.test(a)?JSON.parse(a):a)}function _(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Z,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c=$(c)}catch(e){}X.set(a,b,c)}else c=void 0;return c}r.extend({hasData:function(a){return X.hasData(a)||W.hasData(a)},data:function(a,b,c){return X.access(a,b,c)},removeData:function(a,b){X.remove(a,b)},_data:function(a,b,c){return W.access(a,b,c)},_removeData:function(a,b){W.remove(a,b)}}),r.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=X.get(f),1===f.nodeType&&!W.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=r.camelCase(d.slice(5)),_(f,d,e[d])));W.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){X.set(this,a)}):T(this,function(b){var c;if(f&&void 0===b){if(c=X.get(f,a),void 0!==c)return c;if(c=_(f,a),void 0!==c)return c}else this.each(function(){X.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){X.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=W.get(a,b),c&&(!d||Array.isArray(c)?d=W.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return W.get(a,c)||W.access(a,c,{empty:r.Callbacks("once memory").add(function(){W.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?r.queue(this[0],a):void 0===b?this:this.each(function(){var c=r.queue(this,a,b);r._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&r.dequeue(this,a)})},dequeue:function(a){return this.each(function(){r.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=r.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=W.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var aa=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ba=new RegExp("^(?:([+-])=|)("+aa+")([a-z%]*)$","i"),ca=["Top","Right","Bottom","Left"],da=function(a,b){return a=b||a,"none"===a.style.display||""===a.style.display&&r.contains(a.ownerDocument,a)&&"none"===r.css(a,"display")},ea=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};function fa(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return r.css(a,b,"")},i=h(),j=c&&c[3]||(r.cssNumber[b]?"":"px"),k=(r.cssNumber[b]||"px"!==j&&+i)&&ba.exec(r.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,r.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var ga={};function ha(a){var b,c=a.ownerDocument,d=a.nodeName,e=ga[d];return e?e:(b=c.body.appendChild(c.createElement(d)),e=r.css(b,"display"),b.parentNode.removeChild(b),"none"===e&&(e="block"),ga[d]=e,e)}function ia(a,b){for(var c,d,e=[],f=0,g=a.length;f<g;f++)d=a[f],d.style&&(c=d.style.display,b?("none"===c&&(e[f]=W.get(d,"display")||null,e[f]||(d.style.display="")),""===d.style.display&&da(d)&&(e[f]=ha(d))):"none"!==c&&(e[f]="none",W.set(d,"display",c)));for(f=0;f<g;f++)null!=e[f]&&(a[f].style.display=e[f]);return a}r.fn.extend({show:function(){return ia(this,!0)},hide:function(){return ia(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){da(this)?r(this).show():r(this).hide()})}});var ja=/^(?:checkbox|radio)$/i,ka=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,la=/^$|\/(?:java|ecma)script/i,ma={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ma.optgroup=ma.option,ma.tbody=ma.tfoot=ma.colgroup=ma.caption=ma.thead,ma.th=ma.td;function na(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&B(a,b)?r.merge([a],c):c}function oa(a,b){for(var c=0,d=a.length;c<d;c++)W.set(a[c],"globalEval",!b||W.get(b[c],"globalEval"))}var pa=/<|&#?\w+;/;function qa(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],n=0,o=a.length;n<o;n++)if(f=a[n],f||0===f)if("object"===r.type(f))r.merge(m,f.nodeType?[f]:f);else if(pa.test(f)){g=g||l.appendChild(b.createElement("div")),h=(ka.exec(f)||["",""])[1].toLowerCase(),i=ma[h]||ma._default,g.innerHTML=i[1]+r.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;r.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",n=0;while(f=m[n++])if(d&&r.inArray(f,d)>-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=na(l.appendChild(f),"script"),j&&oa(g),c){k=0;while(f=g[k++])la.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var ra=d.documentElement,sa=/^key/,ta=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ua=/^([^.]*)(?:\.(.+)|)/;function va(){return!0}function wa(){return!1}function xa(){try{return d.activeElement}catch(a){}}function ya(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ya(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=wa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(ra,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(L)||[""],j=b.length;while(j--)h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.hasData(a)&&W.get(a);if(q&&(i=q.events)){b=(b||"").match(L)||[""],j=b.length;while(j--)if(h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&W.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(W.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c<arguments.length;c++)i[c]=arguments[c];if(b.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,b)!==!1){h=r.event.handlers.call(this,b,j),c=0;while((f=h[c++])&&!b.isPropagationStopped()){b.currentTarget=f.elem,d=0;while((g=f.handlers[d++])&&!b.isImmediatePropagationStopped())b.rnamespace&&!b.rnamespace.test(g.namespace)||(b.handleObj=g,b.data=g.data,e=((r.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(b.result=e)===!1&&(b.preventDefault(),b.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,b),b.result}},handlers:function(a,b){var c,d,e,f,g,h=[],i=b.delegateCount,j=a.target;if(i&&j.nodeType&&!("click"===a.type&&a.button>=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c<i;c++)d=b[c],e=d.selector+" ",void 0===g[e]&&(g[e]=d.needsContext?r(e,this).index(j)>-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i<b.length&&h.push({elem:j,handlers:b.slice(i)}),h},addProp:function(a,b){Object.defineProperty(r.Event.prototype,a,{enumerable:!0,configurable:!0,get:r.isFunction(b)?function(){if(this.originalEvent)return b(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[a]},set:function(b){Object.defineProperty(this,a,{enumerable:!0,configurable:!0,writable:!0,value:b})}})},fix:function(a){return a[r.expando]?a:new r.Event(a)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==xa()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===xa()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&B(this,"input"))return this.click(),!1},_default:function(a){return B(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},r.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},r.Event=function(a,b){return this instanceof r.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?va:wa,this.target=a.target&&3===a.target.nodeType?a.target.parentNode:a.target,this.currentTarget=a.currentTarget,this.relatedTarget=a.relatedTarget):this.type=a,b&&r.extend(this,b),this.timeStamp=a&&a.timeStamp||r.now(),void(this[r.expando]=!0)):new r.Event(a,b)},r.Event.prototype={constructor:r.Event,isDefaultPrevented:wa,isPropagationStopped:wa,isImmediatePropagationStopped:wa,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=va,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=va,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=va,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},r.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(a){var b=a.button;return null==a.which&&sa.test(a.type)?null!=a.charCode?a.charCode:a.keyCode:!a.which&&void 0!==b&&ta.test(a.type)?1&b?1:2&b?3:4&b?2:0:a.which}},r.event.addProp),r.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){r.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||r.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),r.fn.extend({on:function(a,b,c,d){return ya(this,a,b,c,d)},one:function(a,b,c,d){return ya(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,r(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=wa),this.each(function(){r.event.remove(this,a,c,b)})}});var za=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,Aa=/<script|<style|<link/i,Ba=/checked\s*(?:[^=]|=\s*.checked.)/i,Ca=/^true\/(.*)/,Da=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Ea(a,b){return B(a,"table")&&B(11!==b.nodeType?b:b.firstChild,"tr")?r(">tbody",a)[0]||a:a}function Fa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ga(a){var b=Ca.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ha(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(W.hasData(a)&&(f=W.access(a),g=W.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c<d;c++)r.event.add(b,e,j[e][c])}X.hasData(a)&&(h=X.access(a),i=r.extend({},h),X.set(b,i))}}function Ia(a,b){var c=b.nodeName.toLowerCase();"input"===c&&ja.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function Ja(a,b,c,d){b=g.apply([],b);var e,f,h,i,j,k,l=0,m=a.length,n=m-1,q=b[0],s=r.isFunction(q);if(s||m>1&&"string"==typeof q&&!o.checkClone&&Ba.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ja(f,b,c,d)});if(m&&(e=qa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(na(e,"script"),Fa),i=h.length;l<m;l++)j=e,l!==n&&(j=r.clone(j,!0,!0),i&&r.merge(h,na(j,"script"))),c.call(a[l],j,l);if(i)for(k=h[h.length-1].ownerDocument,r.map(h,Ga),l=0;l<i;l++)j=h[l],la.test(j.type||"")&&!W.access(j,"globalEval")&&r.contains(k,j)&&(j.src?r._evalUrl&&r._evalUrl(j.src):p(j.textContent.replace(Da,""),k))}return a}function Ka(a,b,c){for(var d,e=b?r.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||r.cleanData(na(d)),d.parentNode&&(c&&r.contains(d.ownerDocument,d)&&oa(na(d,"script")),d.parentNode.removeChild(d));return a}r.extend({htmlPrefilter:function(a){return a.replace(za,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=na(h),f=na(a),d=0,e=f.length;d<e;d++)Ia(f[d],g[d]);if(b)if(c)for(f=f||na(a),g=g||na(h),d=0,e=f.length;d<e;d++)Ha(f[d],g[d]);else Ha(a,h);return g=na(h,"script"),g.length>0&&oa(g,!i&&na(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(U(c)){if(b=c[W.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[W.expando]=void 0}c[X.expando]&&(c[X.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ka(this,a,!0)},remove:function(a){return Ka(this,a)},text:function(a){return T(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.appendChild(a)}})},prepend:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(na(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return T(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!Aa.test(a)&&!ma[(ka.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c<d;c++)b=this[c]||{},1===b.nodeType&&(r.cleanData(na(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ja(this,arguments,function(b){var c=this.parentNode;r.inArray(this,a)<0&&(r.cleanData(na(this)),c&&c.replaceChild(b,this))},a)}}),r.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){r.fn[a]=function(a){for(var c,d=[],e=r(a),f=e.length-1,g=0;g<=f;g++)c=g===f?this:this.clone(!0),r(e[g])[b](c),h.apply(d,c.get());return this.pushStack(d)}});var La=/^margin/,Ma=new RegExp("^("+aa+")(?!px)[a-z%]+$","i"),Na=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)};!function(){function b(){if(i){i.style.cssText="box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",i.innerHTML="",ra.appendChild(h);var b=a.getComputedStyle(i);c="1%"!==b.top,g="2px"===b.marginLeft,e="4px"===b.width,i.style.marginRight="50%",f="4px"===b.marginRight,ra.removeChild(h),i=null}}var c,e,f,g,h=d.createElement("div"),i=d.createElement("div");i.style&&(i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",o.clearCloneStyle="content-box"===i.style.backgroundClip,h.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",h.appendChild(i),r.extend(o,{pixelPosition:function(){return b(),c},boxSizingReliable:function(){return b(),e},pixelMarginRight:function(){return b(),f},reliableMarginLeft:function(){return b(),g}}))}();function Oa(a,b,c){var d,e,f,g,h=a.style;return c=c||Na(a),c&&(g=c.getPropertyValue(b)||c[b],""!==g||r.contains(a.ownerDocument,a)||(g=r.style(a,b)),!o.pixelMarginRight()&&Ma.test(g)&&La.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function Pa(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Qa=/^(none|table(?!-c[ea]).+)/,Ra=/^--/,Sa={position:"absolute",visibility:"hidden",display:"block"},Ta={letterSpacing:"0",fontWeight:"400"},Ua=["Webkit","Moz","ms"],Va=d.createElement("div").style;function Wa(a){if(a in Va)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ua.length;while(c--)if(a=Ua[c]+b,a in Va)return a}function Xa(a){var b=r.cssProps[a];return b||(b=r.cssProps[a]=Wa(a)||a),b}function Ya(a,b,c){var d=ba.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Za(a,b,c,d,e){var f,g=0;for(f=c===(d?"border":"content")?4:"width"===b?1:0;f<4;f+=2)"margin"===c&&(g+=r.css(a,c+ca[f],!0,e)),d?("content"===c&&(g-=r.css(a,"padding"+ca[f],!0,e)),"margin"!==c&&(g-=r.css(a,"border"+ca[f]+"Width",!0,e))):(g+=r.css(a,"padding"+ca[f],!0,e),"padding"!==c&&(g+=r.css(a,"border"+ca[f]+"Width",!0,e)));return g}function $a(a,b,c){var d,e=Na(a),f=Oa(a,b,e),g="border-box"===r.css(a,"boxSizing",!1,e);return Ma.test(f)?f:(d=g&&(o.boxSizingReliable()||f===a.style[b]),"auto"===f&&(f=a["offset"+b[0].toUpperCase()+b.slice(1)]),f=parseFloat(f)||0,f+Za(a,b,c||(g?"border":"content"),d,e)+"px")}r.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Oa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=r.camelCase(b),i=Ra.test(b),j=a.style;return i||(b=Xa(h)),g=r.cssHooks[b]||r.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:j[b]:(f=typeof c,"string"===f&&(e=ba.exec(c))&&e[1]&&(c=fa(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(r.cssNumber[h]?"":"px")),o.clearCloneStyle||""!==c||0!==b.indexOf("background")||(j[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i?j.setProperty(b,c):j[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=r.camelCase(b),i=Ra.test(b);return i||(b=Xa(h)),g=r.cssHooks[b]||r.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Oa(a,b,d)),"normal"===e&&b in Ta&&(e=Ta[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),r.each(["height","width"],function(a,b){r.cssHooks[b]={get:function(a,c,d){if(c)return!Qa.test(r.css(a,"display"))||a.getClientRects().length&&a.getBoundingClientRect().width?$a(a,b,d):ea(a,Sa,function(){return $a(a,b,d)})},set:function(a,c,d){var e,f=d&&Na(a),g=d&&Za(a,b,d,"border-box"===r.css(a,"boxSizing",!1,f),f);return g&&(e=ba.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=r.css(a,b)),Ya(a,c,g)}}}),r.cssHooks.marginLeft=Pa(o.reliableMarginLeft,function(a,b){if(b)return(parseFloat(Oa(a,"marginLeft"))||a.getBoundingClientRect().left-ea(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px"}),r.each({margin:"",padding:"",border:"Width"},function(a,b){r.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];d<4;d++)e[a+ca[d]+b]=f[d]||f[d-2]||f[0];return e}},La.test(a)||(r.cssHooks[a+b].set=Ya)}),r.fn.extend({css:function(a,b){return T(this,function(a,b,c){var d,e,f={},g=0;if(Array.isArray(b)){for(d=Na(a),e=b.length;g<e;g++)f[b[g]]=r.css(a,b[g],!1,d);return f}return void 0!==c?r.style(a,b,c):r.css(a,b)},a,b,arguments.length>1)}});function _a(a,b,c,d,e){return new _a.prototype.init(a,b,c,d,e)}r.Tween=_a,_a.prototype={constructor:_a,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=_a.propHooks[this.prop];return a&&a.get?a.get(this):_a.propHooks._default.get(this)},run:function(a){var b,c=_a.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):_a.propHooks._default.set(this),this}},_a.prototype.init.prototype=_a.prototype,_a.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},_a.propHooks.scrollTop=_a.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=_a.prototype.init,r.fx.step={};var ab,bb,cb=/^(?:toggle|show|hide)$/,db=/queueHooks$/;function eb(){bb&&(d.hidden===!1&&a.requestAnimationFrame?a.requestAnimationFrame(eb):a.setTimeout(eb,r.fx.interval),r.fx.tick())}function fb(){return a.setTimeout(function(){ab=void 0}),ab=r.now()}function gb(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ca[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function hb(a,b,c){for(var d,e=(kb.tweeners[b]||[]).concat(kb.tweeners["*"]),f=0,g=e.length;f<g;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,k,l="width"in b||"height"in b,m=this,n={},o=a.style,p=a.nodeType&&da(a),q=W.get(a,"fxshow");c.queue||(g=r._queueHooks(a,"fx"),null==g.unqueued&&(g.unqueued=0,h=g.empty.fire,g.empty.fire=function(){g.unqueued||h()}),g.unqueued++,m.always(function(){m.always(function(){g.unqueued--,r.queue(a,"fx").length||g.empty.fire()})}));for(d in b)if(e=b[d],cb.test(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||r.style(a,d)}if(i=!r.isEmptyObject(b),i||!r.isEmptyObject(n)){l&&1===a.nodeType&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=q&&q.display,null==j&&(j=W.get(a,"display")),k=r.css(a,"display"),"none"===k&&(j?k=j:(ia([a],!0),j=a.style.display||j,k=r.css(a,"display"),ia([a]))),("inline"===k||"inline-block"===k&&null!=j)&&"none"===r.css(a,"float")&&(i||(m.done(function(){o.display=j}),null==j&&(k=o.display,j="none"===k?"":k)),o.display="inline-block")),c.overflow&&(o.overflow="hidden",m.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]})),i=!1;for(d in n)i||(q?"hidden"in q&&(p=q.hidden):q=W.access(a,"fxshow",{display:j}),f&&(q.hidden=!p),p&&ia([a],!0),m.done(function(){p||ia([a]),W.remove(a,"fxshow");for(d in n)r.style(a,d,n[d])})),i=hb(p?q[d]:0,d,m),d in q||(q[d]=i.start,p&&(i.end=i.start,i.start=0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=r.camelCase(c),e=b[d],f=a[c],Array.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=r.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=kb.prefilters.length,h=r.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=ab||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;g<i;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),f<1&&i?c:(i||h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:r.extend({},b),opts:r.extend(!0,{specialEasing:{},easing:r.easing._default},c),originalProperties:b,originalOptions:c,startTime:ab||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=r.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;c<d;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);f<g;f++)if(d=kb.prefilters[f].call(j,a,k,j.opts))return r.isFunction(d.stop)&&(r._queueHooks(j.elem,j.opts.queue).stop=r.proxy(d.stop,d)),d;return r.map(k,hb,j),r.isFunction(j.opts.start)&&j.opts.start.call(a,j),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always),r.fx.timer(r.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j}r.Animation=r.extend(kb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return fa(c.elem,a,ba.exec(b),c),c}]},tweener:function(a,b){r.isFunction(a)?(b=a,a=["*"]):a=a.match(L);for(var c,d=0,e=a.length;d<e;d++)c=a[d],kb.tweeners[c]=kb.tweeners[c]||[],kb.tweeners[c].unshift(b)},prefilters:[ib],prefilter:function(a,b){b?kb.prefilters.unshift(a):kb.prefilters.push(a)}}),r.speed=function(a,b,c){var d=a&&"object"==typeof a?r.extend({},a):{complete:c||!c&&b||r.isFunction(a)&&a,duration:a,easing:c&&b||b&&!r.isFunction(b)&&b};return r.fx.off?d.duration=0:"number"!=typeof d.duration&&(d.duration in r.fx.speeds?d.duration=r.fx.speeds[d.duration]:d.duration=r.fx.speeds._default),null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){r.isFunction(d.old)&&d.old.call(this),d.queue&&r.dequeue(this,d.queue)},d},r.fn.extend({fadeTo:function(a,b,c,d){return this.filter(da).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=r.isEmptyObject(a),f=r.speed(b,c,d),g=function(){var b=kb(this,r.extend({},a),f);(e||W.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=r.timers,g=W.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&db.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||r.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=W.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=r.timers,g=d?d.length:0;for(c.finish=!0,r.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;b<g;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),r.each(["toggle","show","hide"],function(a,b){var c=r.fn[b];r.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),r.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){r.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),r.timers=[],r.fx.tick=function(){var a,b=0,c=r.timers;for(ab=r.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||r.fx.stop(),ab=void 0},r.fx.timer=function(a){r.timers.push(a),r.fx.start()},r.fx.interval=13,r.fx.start=function(){bb||(bb=!0,eb())},r.fx.stop=function(){bb=null},r.fx.speeds={slow:600,fast:200,_default:400},r.fn.delay=function(b,c){return b=r.fx?r.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",o.checkOn=""!==a.value,o.optSelected=c.selected,a=d.createElement("input"),a.value="t",a.type="radio",o.radioValue="t"===a.value}();var lb,mb=r.expr.attrHandle;r.fn.extend({attr:function(a,b){return T(this,r.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?lb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),
null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&B(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(L);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),lb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=mb[b]||r.find.attr;mb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=mb[g],mb[g]=e,e=null!=c(a,b,d)?g:null,mb[g]=f),e}});var nb=/^(?:input|select|textarea|button)$/i,ob=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return T(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):nb.test(a.nodeName)||ob.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function pb(a){var b=a.match(L)||[];return b.join(" ")}function qb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,qb(this)))});if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,qb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,qb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(L)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=qb(this),b&&W.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":W.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+pb(qb(c))+" ").indexOf(b)>-1)return!0;return!1}});var rb=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":Array.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:pb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d<i;d++)if(c=e[d],(c.selected||d===f)&&!c.disabled&&(!c.parentNode.disabled||!B(c.parentNode,"optgroup"))){if(b=r(c).val(),g)return b;h.push(b)}return h},set:function(a,b){var c,d,e=a.options,f=r.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=r.inArray(r.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(Array.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var sb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!sb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,sb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(W.get(h,"events")||{})[b.type]&&W.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&U(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!U(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=W.access(d,b);e||d.addEventListener(a,c,!0),W.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=W.access(d,b)-1;e?W.access(d,b,e):(d.removeEventListener(a,c,!0),W.remove(d,b))}}});var tb=a.location,ub=r.now(),vb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(Array.isArray(b))r.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(Array.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!ja.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:Array.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}});var Bb=/%20/g,Cb=/#.*$/,Db=/([?&])_=[^&]*/,Eb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Fb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Gb=/^(?:GET|HEAD)$/,Hb=/^\/\//,Ib={},Jb={},Kb="*/".concat("*"),Lb=d.createElement("a");Lb.href=tb.href;function Mb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(L)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nb(a,b,c,d){var e={},f=a===Jb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Ob(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Pb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Qb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:tb.href,type:"GET",isLocal:Fb.test(tb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Ob(Ob(a,r.ajaxSettings),b):Ob(r.ajaxSettings,a)},ajaxPrefilter:Mb(Ib),ajaxTransport:Mb(Jb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Eb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||tb.href)+"").replace(Hb,tb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(L)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Lb.protocol+"//"+Lb.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Nb(Ib,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Gb.test(o.type),f=o.url.replace(Cb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(Bb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(vb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Db,"$1"),n=(vb.test(f)?"&":"?")+"_="+ub++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Kb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Nb(Jb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Pb(o,y,d)),v=Qb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Rb={0:200,1223:204},Sb=r.ajaxSettings.xhr();o.cors=!!Sb&&"withCredentials"in Sb,o.ajax=Sb=!!Sb,r.ajaxTransport(function(b){var c,d;if(o.cors||Sb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Rb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Tb=[],Ub=/(=)\?(?=&|$)|\?\?/;r.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Tb.pop()||r.expando+"_"+ub++;return this[a]=!0,a}}),r.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Ub.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ub.test(b.data)&&"data");if(h||"jsonp"===b.dataTypes[0])return e=b.jsonpCallback=r.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Ub,"$1"+e):b.jsonp!==!1&&(b.url+=(vb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||r.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?r(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Tb.push(e)),g&&r.isFunction(f)&&f(g[0]),g=f=void 0}),"script"}),o.createHTMLDocument=function(){var a=d.implementation.createHTMLDocument("").body;return a.innerHTML="<form></form><form></form>",2===a.childNodes.length}(),r.parseHTML=function(a,b,c){if("string"!=typeof a)return[];"boolean"==typeof b&&(c=b,b=!1);var e,f,g;return b||(o.createHTMLDocument?(b=d.implementation.createHTMLDocument(""),e=b.createElement("base"),e.href=d.location.href,b.head.appendChild(e)):b=d),f=C.exec(a),g=!c&&[],f?[b.createElement(f[1])]:(f=qa([a],b,g),g&&g.length&&r(g).remove(),r.merge([],f.childNodes))},r.fn.load=function(a,b,c){var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=pb(a.slice(h)),a=a.slice(0,h)),r.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&r.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?r("<div>").append(r.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},r.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){r.fn[b]=function(a){return this.on(b,a)}}),r.expr.pseudos.animated=function(a){return r.grep(r.timers,function(b){return a===b.elem}).length},r.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=r.css(a,"position"),l=r(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=r.css(a,"top"),i=r.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),r.isFunction(b)&&(b=b.call(a,c,r.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},r.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){r.offset.setOffset(this,a,b)});var b,c,d,e,f=this[0];if(f)return f.getClientRects().length?(d=f.getBoundingClientRect(),b=f.ownerDocument,c=b.documentElement,e=b.defaultView,{top:d.top+e.pageYOffset-c.clientTop,left:d.left+e.pageXOffset-c.clientLeft}):{top:0,left:0}},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===r.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),B(a[0],"html")||(d=a.offset()),d={top:d.top+r.css(a[0],"borderTopWidth",!0),left:d.left+r.css(a[0],"borderLeftWidth",!0)}),{top:b.top-d.top-r.css(c,"marginTop",!0),left:b.left-d.left-r.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===r.css(a,"position"))a=a.offsetParent;return a||ra})}}),r.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;r.fn[a]=function(d){return T(this,function(a,d,e){var f;return r.isWindow(a)?f=a:9===a.nodeType&&(f=a.defaultView),void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),r.each(["top","left"],function(a,b){r.cssHooks[b]=Pa(o.pixelPosition,function(a,c){if(c)return c=Oa(a,b),Ma.test(c)?r(a).position()[b]+"px":c})}),r.each({Height:"height",Width:"width"},function(a,b){r.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){r.fn[d]=function(e,f){var g=arguments.length&&(c||"boolean"!=typeof e),h=c||(e===!0||f===!0?"margin":"border");return T(this,function(b,c,e){var f;return r.isWindow(b)?0===d.indexOf("outer")?b["inner"+a]:b.document.documentElement["client"+a]:9===b.nodeType?(f=b.documentElement,Math.max(b.body["scroll"+a],f["scroll"+a],b.body["offset"+a],f["offset"+a],f["client"+a])):void 0===e?r.css(b,c,h):r.style(b,c,e,h)},b,g?e:void 0,g)}})}),r.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),r.holdReady=function(a){a?r.readyWait++:r.ready(!0)},r.isArray=Array.isArray,r.parseJSON=JSON.parse,r.nodeName=B,"function"==typeof define&&define.amd&&define("jquery",[],function(){return r});var Vb=a.jQuery,Wb=a.$;return r.noConflict=function(b){return a.$===r&&(a.$=Wb),b&&a.jQuery===r&&(a.jQuery=Vb),r},b||(a.jQuery=a.$=r),r});
;
/*! jQuery UI - v1.12.1 - 2016-09-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-1-7.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){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,o)}function o(){t.datepicker._isDisabledDatepicker(m.inline?m.dpDiv.parent()[0]:m.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function a(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;a>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(e[i]=t.isPlainObject(s)?t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var o="string"==typeof n,a=l.call(arguments,1),r=this;return o?this.length||"instance"!==n?this.each(function(){var i,o=t.data(this,s);return"instance"===n?(r=o,!1):o?t.isFunction(o[n])&&"_"!==n.charAt(0)?(i=o[n].apply(o,a),i!==o&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+n+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+n+"'")}):r=void 0:(a.length&&(n=t.widget.extend.apply(null,[n].concat(a))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(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(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,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(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_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){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+o.eventNamespace,c=h[2];c?n.on(l,c,r):i.on(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){function e(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(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,o=Math.max,a=Math.abs,r=/left|center|right/,h=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,o="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:o?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType,o=!s&&!n;return{element:i,isWindow:s,isDocument:n,offset:o?t(e).offset():{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:i.outerWidth(),height:i.outerHeight()}}},t.fn.position=function(n){if(!n||!n.of)return d.apply(this,arguments);n=t.extend({},n);var u,p,f,g,m,_,v=t(n.of),b=t.position.getWithinInfo(n.within),y=t.position.getScrollInfo(b),w=(n.collision||"flip").split(" "),k={};return _=s(v),v[0].preventDefault&&(n.at="left top"),p=_.width,f=_.height,g=_.offset,m=t.extend({},g),t.each(["my","at"],function(){var t,e,i=(n[this]||"").split(" ");1===i.length&&(i=r.test(i[0])?i.concat(["center"]):h.test(i[0])?["center"].concat(i):["center","center"]),i[0]=r.test(i[0])?i[0]:"center",i[1]=h.test(i[1])?i[1]:"center",t=l.exec(i[0]),e=l.exec(i[1]),k[this]=[t?t[0]:0,e?e[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===n.at[0]?m.left+=p:"center"===n.at[0]&&(m.left+=p/2),"bottom"===n.at[1]?m.top+=f:"center"===n.at[1]&&(m.top+=f/2),u=e(k.at,p,f),m.left+=u[0],m.top+=u[1],this.each(function(){var s,r,h=t(this),l=h.outerWidth(),c=h.outerHeight(),d=i(this,"marginLeft"),_=i(this,"marginTop"),x=l+d+i(this,"marginRight")+y.width,C=c+_+i(this,"marginBottom")+y.height,D=t.extend({},m),I=e(k.my,h.outerWidth(),h.outerHeight());"right"===n.my[0]?D.left-=l:"center"===n.my[0]&&(D.left-=l/2),"bottom"===n.my[1]?D.top-=c:"center"===n.my[1]&&(D.top-=c/2),D.left+=I[0],D.top+=I[1],s={marginLeft:d,marginTop:_},t.each(["left","top"],function(e,i){t.ui.position[w[e]]&&t.ui.position[w[e]][i](D,{targetWidth:p,targetHeight:f,elemWidth:l,elemHeight:c,collisionPosition:s,collisionWidth:x,collisionHeight:C,offset:[u[0]+I[0],u[1]+I[1]],my:n.my,at:n.at,within:b,elem:h})}),n.using&&(r=function(t){var e=g.left-D.left,i=e+p-l,s=g.top-D.top,r=s+f-c,u={target:{element:v,left:g.left,top:g.top,width:p,height:f},element:{element:h,left:D.left,top:D.top,width:l,height:c},horizontal:0>i?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};l>p&&p>a(e+i)&&(u.horizontal="center"),c>f&&f>a(s+r)&&(u.vertical="middle"),u.important=o(a(e),a(i))>o(a(s),a(r))?"horizontal":"vertical",n.using.call(this,t,u)}),h.offset(t.extend(D,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-a-n;e.collisionWidth>a?h>0&&0>=l?(i=t.left+h+e.collisionWidth-a-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+a-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-a-n;e.collisionHeight>a?h>0&&0>=l?(i=t.top+h+e.collisionHeight-a-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+a-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,r=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-r-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-r-o,(0>i||a(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>a(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,r=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-r-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-r-o,(0>s||a(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,(i>0||u>a(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}});var c="ui-effects-",u="ui-effects-style",d="ui-effects-animated",p=t;t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[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:0>t?0:t>s.max?s.max:t)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(t,o){var a,r=o.re.exec(i),h=r&&o.parse(r),l=o.space||"rgba";return h?(a=s[l](h),s[c[l].cache]=a[c[l].cache],n=s._rgba=a._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,o.transparent),s):o[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var o,a="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(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})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([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)]}},{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]]}}],l=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={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"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=l.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),l.fn=t.extend(l.prototype,{parse:function(n,a,r,h){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(a),a=e);var u=this,d=t.type(n),p=this._rgba=[];return a!==e&&(n=[n,a,r,h],d="array"),"string"===d?this.parse(s(n)||o._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof l?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var o=s.cache;f(s.props,function(t,e){if(!u[o]&&s.to){if("alpha"===t||null==n[t])return;u[o]=s.to(u._rgba)}u[o][e.idx]=i(n[t],e,!0)}),u[o]&&0>t.inArray(null,u[o].slice(0,3))&&(u[o][3]=1,s.from&&(u._rgba=s.from(u[o])))}),this):e},is:function(t){var i=l(t),s=!0,n=this;return f(c,function(t,o){var a,r=i[o.cache];return r&&(a=n[o.cache]||o.to&&o.to(n._rgba)||[],f(o.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===a[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=l(t),n=s._space(),o=c[n],a=0===this.alpha()?l("transparent"):this,r=a[o.cache]||o.to(a._rgba),h=r.slice();return s=s[o.cache],f(o.props,function(t,n){var o=n.idx,a=r[o],l=s[o],c=u[n.type]||{};null!==l&&(null===a?h[o]=l:(c.mod&&(l-a>c.mod/2?a+=c.mod:a-l>c.mod/2&&(a-=c.mod)),h[o]=i((l-a)*e+a,n)))}),this[n](h)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(e)._rgba;return l(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,o=t[2]/255,a=t[3],r=Math.max(s,n,o),h=Math.min(s,n,o),l=r-h,c=r+h,u=.5*c;return e=h===r?0:s===r?60*(n-o)/l+360:n===r?60*(o-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=u?l/c:l/(2-c),[Math.round(e)%360,i,u,null==a?1:a]},c.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],o=t[3],a=.5>=s?s*(1+i):s+i-s*i,r=2*s-a;return[Math.round(255*n(r,a,e+1/3)),Math.round(255*n(r,a,e)),Math.round(255*n(r,a,e-1/3)),o]},f(c,function(s,n){var o=n.props,a=n.cache,h=n.to,c=n.from;l.fn[s]=function(s){if(h&&!this[a]&&(this[a]=h(this._rgba)),s===e)return this[a].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[a].slice();return f(o,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=l(c(d)),n[a]=d,n):l(d)},f(o,function(e,i){l.fn[e]||(l.fn[e]=function(n){var o,a=t.type(n),h="alpha"===e?this._hsla?"hsla":"rgba":s,l=this[h](),c=l[i.idx];return"undefined"===a?c:("function"===a&&(n=n.call(this,c),a=t.type(n)),null==n&&i.empty?this:("string"===a&&(o=r.exec(n),o&&(n=c+parseFloat(o[2])*("+"===o[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var o,a,r="";if("transparent"!==n&&("string"!==t.type(n)||(o=s(n)))){if(n=l(o||n),!d.rgba&&1!==n._rgba[3]){for(a="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&a&&a.style;)try{r=t.css(a,"backgroundColor"),a=a.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(h){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=l(e.elem,i),e.end=l(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},l.hook(a),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},o=t.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"}}(p),function(){function e(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,o={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(o[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(o[i]=n[i]);return o}function i(e,i){var s,o,a={};for(s in i)o=i[s],e[s]!==o&&(n[s]||(t.fx.step[s]||!isNaN(parseFloat(o)))&&(a[s]=o));return a}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(p.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(n,o,a,r){var h=t.speed(o,a,r);return this.queue(function(){var o,a=t(this),r=a.attr("class")||"",l=h.children?a.find("*").addBack():a;l=l.map(function(){var i=t(this);return{el:i,start:e(this)}}),o=function(){t.each(s,function(t,e){n[e]&&a[e+"Class"](n[e])})},o(),l=l.map(function(){return this.end=e(this.el[0]),this.diff=i(this.start,this.end),this}),a.attr("class",r),l=l.map(function(){var e=this,i=t.Deferred(),s=t.extend({},h,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,l.get()).done(function(){o(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),h.complete.call(a[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,o):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(e){return function(i,s,n,o,a){return"boolean"==typeof s||void 0===s?n?t.effects.animateClass.call(this,s?{add:i}:{remove:i},n,o,a):e.apply(this,arguments):t.effects.animateClass.call(this,{toggle:i},s,n,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){function e(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function i(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}function s(t,e){var i=e.outerWidth(),s=e.outerHeight(),n=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,o=n.exec(t)||["",0,i,s,0];return{top:parseFloat(o[1])||0,right:"auto"===o[2]?i:parseFloat(o[2]),bottom:"auto"===o[3]?s:parseFloat(o[3]),left:parseFloat(o[4])||0}}t.expr&&t.expr.filters&&t.expr.filters.animated&&(t.expr.filters.animated=function(e){return function(i){return!!t(i).data(d)||e(i)}}(t.expr.filters.animated)),t.uiBackCompat!==!1&&t.extend(t.effects,{save:function(t,e){for(var i=0,s=e.length;s>i;i++)null!==e[i]&&t.data(c+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;n>s;s++)null!==e[s]&&(i=t.data(c+e[s]),t.css(e[s],i))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(a){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).trigger("focus"),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).trigger("focus")),e}}),t.extend(t.effects,{version:"1.12.1",define:function(e,i,s){return s||(s=i,i="effect"),t.effects.effect[e]=s,t.effects.effect[e].mode=i,s},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,n="vertical"!==i?(e||100)/100:1;return{height:t.height()*n,width:t.width()*s,outerHeight:t.outerHeight()*n,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();e>1&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(u,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(u)||"",t.removeData(u)},mode:function(t,e){var i=t.is(":hidden");return"toggle"===e&&(e=i?"show":"hide"),(i?"hide"===e:"show"===e)&&(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(e){var i,s=e.css("position"),n=e.position();return e.css({marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()),/^(static|relative)/.test(s)&&(s="absolute",i=t("<"+e[0].nodeName+">").insertAfter(e).css({display:/^(inline|ruby)/.test(e.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight"),"float":e.css("float")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).addClass("ui-effects-placeholder"),e.data(c+"placeholder",i)),e.css({position:s,left:n.left,top:n.top}),i},removePlaceholder:function(t){var e=c+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(e){t.effects.restoreStyle(e),t.effects.removePlaceholder(e)},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){function i(e){function i(){r.removeData(d),t.effects.cleanUp(r),"hide"===s.mode&&r.hide(),a()}function a(){t.isFunction(h)&&h.call(r[0]),t.isFunction(e)&&e()}var r=t(this);s.mode=c.shift(),t.uiBackCompat===!1||o?"none"===s.mode?(r[l](),a()):n.call(r[0],s,i):(r.is(":hidden")?"hide"===l:"show"===l)?(r[l](),a()):n.call(r[0],s,a)}var s=e.apply(this,arguments),n=t.effects.effect[s.effect],o=n.mode,a=s.queue,r=a||"fx",h=s.complete,l=s.mode,c=[],u=function(e){var i=t(this),s=t.effects.mode(i,l)||o;i.data(d,!0),c.push(s),o&&("show"===s||s===o&&"hide"===s)&&i.show(),o&&"none"===s||t.effects.saveStyle(i),t.isFunction(e)&&e()};return t.fx.off||!n?l?this[l](s.duration,h):this.each(function(){h&&h.call(this)}):a===!1?this.each(u).each(i):this.queue(r,u).queue(r,i)},show:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="show",this.effect.call(this,n)
}}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(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)"):s(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),t.isFunction(i)&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=s(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{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;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}();var f=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},h=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),h&&h.css(t.effects.clipToBox(r)),r.clip=a),h&&h.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,h="hide"===r,l="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(l||h?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),l&&(n={opacity:1},n[m]=o,a.css("opacity",0).css(m,_?2*-u:2*u).animate(n,f,g)),h&&(u/=Math.pow(2,d-1)),n={},n[m]=o;d>v;v++)s={},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=h?2*u:u/2;h&&(s={opacity:0},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,h=r||"horizontal"===a,l=r||"vertical"===a;s=o.cssClip(),n.clip={top:l?(s.bottom-s.top)/2:s.top,right:h?(s.right-s.left)/2:s.right,bottom:l?(s.bottom-s.top)/2:s.bottom,left:h?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a="show"===o,r=e.direction||"left",h="up"===r||"down"===r?"top":"left",l="up"===r||"left"===r?"-=":"+=",c="+="===l?"-=":"+=",u={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,u[h]=l+s,a&&(n.css(u),u[h]=c+s,u.opacity=1),n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=e.mode,g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacity:g?1:0},e.duration||500,e.easing,s)}),t.effects.define("fade","toggle",function(e,i){var s="show"===e.mode;t(this).css("opacity",s?0:1).animate({opacity:s?1:0},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("fold","hide",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=e.size||15,h=/([0-9]+)%/.exec(r),l=!!e.horizFirst,c=l?["right","bottom"]:["bottom","right"],u=e.duration/2,d=t.effects.createPlaceholder(s),p=s.cssClip(),f={clip:t.extend({},p)},g={clip:t.extend({},p)},m=[p[c[0]],p[c[1]]],_=s.queue().length;h&&(r=parseInt(h[1],10)/100*m[a?0:1]),f.clip[c[0]]=r,g.clip[c[0]]=r,g.clip[c[1]]=0,o&&(s.cssClip(g.clip),d&&d.css(t.effects.clipToBox(g)),g.clip=p),s.queue(function(i){d&&d.animate(t.effects.clipToBox(f),u,e.easing).animate(t.effects.clipToBox(g),u,e.easing),i()}).animate(f,u,e.easing).animate(g,u,e.easing).queue(i),t.effects.unshift(s,_,4)}),t.effects.define("highlight","show",function(e,i){var s=t(this),n={backgroundColor:s.css("backgroundColor")};"hide"===e.mode&&(n.opacity=0),t.effects.saveStyle(s),s.css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("size",function(e,i){var s,n,o,a=t(this),r=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],l=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],c=e.mode,u="effect"!==c,d=e.scale||"both",p=e.origin||["middle","center"],f=a.css("position"),g=a.position(),m=t.effects.scaledDimensions(a),_=e.from||m,v=e.to||t.effects.scaledDimensions(a,0);t.effects.createPlaceholder(a),"show"===c&&(o=_,_=v,v=o),n={from:{y:_.height/m.height,x:_.width/m.width},to:{y:v.height/m.height,x:v.width/m.width}},("box"===d||"both"===d)&&(n.from.y!==n.to.y&&(_=t.effects.setTransition(a,h,n.from.y,_),v=t.effects.setTransition(a,h,n.to.y,v)),n.from.x!==n.to.x&&(_=t.effects.setTransition(a,l,n.from.x,_),v=t.effects.setTransition(a,l,n.to.x,v))),("content"===d||"both"===d)&&n.from.y!==n.to.y&&(_=t.effects.setTransition(a,r,n.from.y,_),v=t.effects.setTransition(a,r,n.to.y,v)),p&&(s=t.effects.getBaseline(p,m),_.top=(m.outerHeight-_.outerHeight)*s.y+g.top,_.left=(m.outerWidth-_.outerWidth)*s.x+g.left,v.top=(m.outerHeight-v.outerHeight)*s.y+g.top,v.left=(m.outerWidth-v.outerWidth)*s.x+g.left),a.css(_),("content"===d||"both"===d)&&(h=h.concat(["marginTop","marginBottom"]).concat(r),l=l.concat(["marginLeft","marginRight"]),a.find("*[width]").each(function(){var i=t(this),s=t.effects.scaledDimensions(i),o={height:s.height*n.from.y,width:s.width*n.from.x,outerHeight:s.outerHeight*n.from.y,outerWidth:s.outerWidth*n.from.x},a={height:s.height*n.to.y,width:s.width*n.to.x,outerHeight:s.height*n.to.y,outerWidth:s.width*n.to.x};n.from.y!==n.to.y&&(o=t.effects.setTransition(i,h,n.from.y,o),a=t.effects.setTransition(i,h,n.to.y,a)),n.from.x!==n.to.x&&(o=t.effects.setTransition(i,l,n.from.x,o),a=t.effects.setTransition(i,l,n.to.x,a)),u&&t.effects.saveStyle(i),i.css(o),i.animate(a,e.duration,e.easing,function(){u&&t.effects.restoreStyle(i)})})),a.animate(v,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){var e=a.offset();0===v.opacity&&a.css("opacity",_.opacity),u||(a.css("position","static"===f?"relative":f).offset(e),t.effects.saveStyle(a)),i()}})}),t.effects.define("scale",function(e,i){var s=t(this),n=e.mode,o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"effect"!==n?0:100),a=t.extend(!0,{from:t.effects.scaledDimensions(s),to:t.effects.scaledDimensions(s,o,e.direction||"both"),origin:e.origin||["middle","center"]},e);e.fade&&(a.from.opacity=1,a.to.opacity=0),t.effects.effect.size.call(this,a,i)}),t.effects.define("puff","hide",function(e,i){var s=t.extend(!0,{},e,{fade:!0,percent:parseInt(e.percent,10)||150});t.effects.effect.scale.call(this,s,i)}),t.effects.define("pulsate","show",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=o||a,h=2*(e.times||5)+(r?1:0),l=e.duration/h,c=0,u=1,d=s.queue().length;for((o||!s.is(":visible"))&&(s.css("opacity",0).show(),c=1);h>u;u++)s.animate({opacity:c},l,e.easing),c=1-c;s.animate({opacity:c},l,e.easing),s.queue(i),t.effects.unshift(s,d,h+1)}),t.effects.define("shake",function(e,i){var s=1,n=t(this),o=e.direction||"left",a=e.distance||20,r=e.times||3,h=2*r+1,l=Math.round(e.duration/h),c="up"===o||"down"===o?"top":"left",u="up"===o||"left"===o,d={},p={},f={},g=n.queue().length;for(t.effects.createPlaceholder(n),d[c]=(u?"-=":"+=")+a,p[c]=(u?"+=":"-=")+2*a,f[c]=(u?"-=":"+=")+2*a,n.animate(d,l,e.easing);r>s;s++)n.animate(p,l,e.easing).animate(f,l,e.easing);n.animate(p,l,e.easing).animate(d,l/2,e.easing).queue(i),t.effects.unshift(n,g,h+1)}),t.effects.define("slide","show",function(e,i){var s,n,o=t(this),a={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},r=e.mode,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h,u=e.distance||o["top"===l?"outerHeight":"outerWidth"](!0),d={};t.effects.createPlaceholder(o),s=o.cssClip(),n=o.position()[l],d[l]=(c?-1:1)*u+n,d.clip=o.cssClip(),d.clip[a[h][1]]=d.clip[a[h][0]],"show"===r&&(o.cssClip(d.clip),o.css(l,d[l]),d.clip=s,d[l]=n),o.animate(d,{queue:!1,duration:e.duration,easing:e.easing,complete:i})});var f;t.uiBackCompat!==!1&&(f=t.effects.define("transfer",function(e,i){t(this).transfer(e,i)})),t.ui.focusable=function(i,s){var n,o,a,r,h,l=i.nodeName.toLowerCase();return"area"===l?(n=i.parentNode,o=n.name,i.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap='#"+o+"']"),a.length>0&&a.is(":visible")):!1):(/^(input|select|textarea|button|object)$/.test(l)?(r=!i.disabled,r&&(h=t(i).closest("fieldset")[0],h&&(r=!h.disabled))):r="a"===l?i.href||s:s,r&&t(i).is(":visible")&&e(t(i)))},t.extend(t.expr[":"],{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.fn.form=function(){return"string"==typeof this[0].form?this.closest("form"):t(this[0].form)},t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=this.element.form(),this.form.length){var t=this.form.data("ui-form-reset-instances")||[];t.length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},"1.7"===t.fn.jquery.substring(0,3)&&(t.each(["Width","Height"],function(e,i){function s(e,i,s,o){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),o&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],o=i.toLowerCase(),a={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?a["inner"+i].call(this):this.each(function(){t(this).css(o,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?a["outer"+i].call(this,e):this.each(function(){t(this).css(o,s(this,e,!0,n)+"px")})}}),t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.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},t.ui.escapeSelector=function(){var t=/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;return function(e){return e.replace(t,"\\$1")}}(),t.fn.labels=function(){var e,i,s,n,o;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(n=this.eq(0).parents("label"),s=this.attr("id"),s&&(e=this.eq(0).parents().last(),o=e.add(e.length?e.siblings():this.siblings()),i="label[for='"+t.ui.escapeSelector(s)+"']",n=n.add(o.find(i).addBack(i))),this.pushStack(n))},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.extend(t.expr[":"],{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.widget("ui.accordion",{version:"1.12.1",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:"> li > :first-child, > :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e,i,s=this.options.icons;s&&(e=t("<span>"),this._addClass(e,"ui-accordion-header-icon","ui-icon "+s.header),e.prependTo(this.headers),i=this.active.children(".ui-accordion-header-icon"),this._removeClass(i,s.header)._addClass(i,null,s.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){return"active"===t?(this._activate(e),void 0):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),void 0)},_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(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),t(o).trigger("focus"),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().trigger("focus")},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;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 e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.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 e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){var i=t(this).is(":visible");i||t(this).show(),e=Math.max(e,t(this).css("height","").height()),i||t(this).hide()}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.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(e){var i,s,n=this.options,o=this.active,a=t(e.currentTarget),r=a[0]===o[0],h=r&&n.collapsible,l=h?t():a.next(),c=o.next(),u={oldHeader:o,oldPanel:c,newHeader:h?t():a,newPanel:l};e.preventDefault(),r&&!n.collapsible||this._trigger("beforeActivate",e,u)===!1||(n.active=h?!1:this.headers.index(a),this.active=r?t():a,this._toggle(u),this._removeClass(o,"ui-accordion-header-active","ui-state-active"),n.icons&&(i=o.children(".ui-accordion-header-icon"),this._removeClass(i,null,n.icons.activeHeader)._addClass(i,null,n.icons.header)),r||(this._removeClass(a,"ui-accordion-header-collapsed")._addClass(a,"ui-accordion-header-active","ui-state-active"),n.icons&&(s=a.children(".ui-accordion-header-icon"),this._removeClass(s,null,n.icons.header)._addClass(s,null,n.icons.activeHeader)),this._addClass(a.next(),"ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,o,a=this,r=0,h=t.css("box-sizing"),l=t.length&&(!e.length||t.index()<e.index()),c=this.options.animate||{},u=l&&c.down||c,d=function(){a._toggleComplete(i)};return"number"==typeof u&&(o=u),"string"==typeof u&&(n=u),n=n||u.easing||c.easing,o=o||u.duration||c.duration,e.length?t.length?(s=t.show().outerHeight(),e.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(this.showProps,{duration:o,easing:n,complete:d,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?"content-box"===h&&(r+=i.now):"content"!==a.options.heightStyle&&(i.now=Math.round(s-e.outerHeight()-r),r=0)}}),void 0):e.animate(this.hideProps,o,n,d):t.animate(this.showProps,o,n,d)},_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)}}),t.ui.safeActiveElement=function(t){var e;try{e=t.activeElement}catch(i){e=t.body}return e||(e=t.body),e.nodeName||(e=t.body),e},t.widget("ui.menu",{version:"1.12.1",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target),s=t(t.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);i[0]===s[0]&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){var i=!t.contains(this.element[0],t.ui.safeActiveElement(this.document[0]));i&&this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),i=e.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(),i.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",o=!1,n=e.keyCode>=96&&105>=e.keyCode?""+(e.keyCode-96):String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.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 e,i,s,n,o,a=this,r=this.options.icons.submenu,h=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),s=h.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("<span>").data("ui-menu-submenu-caret",!0);a._addClass(s,"ui-menu-icon","ui-icon "+r),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(s,"ui-menu","ui-widget ui-widget-content ui-front"),e=h.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);a._isDivider(e)&&a._addClass(e,"ui-menu-divider","ui-widget-content")}),n=i.not(".ui-menu-item, .ui-menu-divider"),o=n.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(n,"ui-menu-item")._addClass(o,"ui-menu-item-wrapper"),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){if("icons"===t){var 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",t+""),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},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(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.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.active.children(".ui-menu ").find(this.options.items).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},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(t.trim(t(this).children(".ui-menu-item-wrapper").text()))})}}),t.widget("ui.autocomplete",{version:"1.12.1",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n;
this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,this.element[0]!==t.ui.safeActiveElement(this.document[0])&&this.element.trigger("focus")})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,i){var s=i.item.data("ui-autocomplete-item"),n=this.previous;this.element[0]!==t.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=n,this._delay(function(){this.previous=n,this.selectedItem=s})),!1!==this._trigger("select",e,{item:s})&&this._value(s.value),this.term=this._value(),this.close(e),this.selectedItem=s}}),this.liveRegion=t("<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(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},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):this._trigger("search",e)!==!1?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 t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")},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._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(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({},e,{label:e.label||e.value,value:e.value||e.label})})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.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(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").append(t("<div>").text(i.label)).appendTo(e)},_move:function(t,e){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[t](e),void 0):(this.search(null,e),void 0)},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}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.children().hide(),t("<div>").text(i).appendTo(this.liveRegion))}}),t.ui.autocomplete;var g=/ui-corner-([a-z]){2,6}/g;t.widget("ui.controlgroup",{version:"1.12.1",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 e=this,i=[];t.each(this.options.items,function(s,n){var o,a={};return n?"controlgroupLabel"===s?(o=e.element.find(n),o.each(function(){var e=t(this);e.children(".ui-controlgroup-label-contents").length||e.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),e._addClass(o,null,"ui-widget ui-widget-content ui-state-default"),i=i.concat(o.get()),void 0):(t.fn[s]&&(a=e["_"+s+"Options"]?e["_"+s+"Options"]("middle"):{classes:{}},e.element.find(n).each(function(){var n=t(this),o=n[s]("instance"),r=t.widget.extend({},a);if("button"!==s||!n.parent(".ui-spinner").length){o||(o=n[s]()[s]("instance")),o&&(r.classes=e._resolveClassesValues(r.classes,o)),n[s](r);var h=n[s]("widget");t.data(h[0],"ui-controlgroup-data",o?o:n[s]("instance")),i.push(h[0])}})),void 0):void 0}),this.childWidgets=t(t.unique(i)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var i=t(this),s=i.data("ui-controlgroup-data");s&&s[e]&&s[e]()})},_updateCornerClass:function(t,e){var i="ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all",s=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,i),this._addClass(t,null,s)},_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){var e=this._buildSimpleOptions(t,"ui-spinner");return e.classes["ui-spinner-up"]="",e.classes["ui-spinner-down"]="",e},_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":!1,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(e,i){var s={};return t.each(e,function(n){var o=i.options.classes[n]||"";o=t.trim(o.replace(g,"")),s[n]=(o+" "+e[n]).replace(/\s+/g," ")}),s},_setOption:function(t,e){return"direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"===t?(this._callChildMethod(e?"disable":"enable"),void 0):(this.refresh(),void 0)},refresh:function(){var e,i=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),e=this.childWidgets,this.options.onlyVisible&&(e=e.filter(":visible")),e.length&&(t.each(["first","last"],function(t,s){var n=e[s]().data("ui-controlgroup-data");if(n&&i["_"+n.widgetName+"Options"]){var o=i["_"+n.widgetName+"Options"](1===e.length?"only":s);o.classes=i._resolveClassesValues(o.classes,n),n.element[n.widgetName](o)}else i._updateCornerClass(e[s](),s)}),this._callChildMethod("refresh"))}}),t.widget("ui.checkboxradio",[t.ui.formResetMixin,{version:"1.12.1",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var e,i,s=this,n=this._super()||{};return this._readType(),i=this.element.labels(),this.label=t(i[i.length-1]),this.label.length||t.error("No label found for checkboxradio widget"),this.originalLabel="",this.label.contents().not(this.element[0]).each(function(){s.originalLabel+=3===this.nodeType?t(this).text():this.outerHTML}),this.originalLabel&&(n.label=this.originalLabel),e=this.element[0].disabled,null!=e&&(n.disabled=e),n},_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.icon&&this._addClass(this.icon,null,"ui-state-hover")),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 e=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===e&&/radio|checkbox/.test(this.type)||t.error("Can't create checkboxradio on element.nodeName="+e+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var e,i=this.element[0].name,s="input[name='"+t.ui.escapeSelector(i)+"']";return i?(e=this.form.length?t(this.form[0].elements).filter(s):t(s).filter(function(){return 0===t(this).form().length}),e.not(this.element)):t([])},_toggleClasses:function(){var e=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",e),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",e)._toggleClass(this.icon,null,"ui-icon-blank",!e),"radio"===this.type&&this._getRadioGroup().each(function(){var e=t(this).checkboxradio("instance");e&&e._removeClass(e.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){return"label"!==t||e?(this._super(t,e),"disabled"===t?(this._toggleClass(this.label,null,"ui-state-disabled",e),this.element[0].disabled=e,void 0):(this.refresh(),void 0)):void 0},_updateIcon:function(e){var i="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=t("<span>"),this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(i+=e?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,e?"ui-icon-blank":"ui-icon-check")):i+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",i),e||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])),this.iconSpace&&(t=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})}}]),t.ui.checkboxradio,t.widget("ui.button",{version:"1.12.1",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"),t=this.element[0].disabled,null!=t&&(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(e){e.keyCode===t.ui.keyCode.SPACE&&(e.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(e,i){var s="iconPosition"!==e,n=s?this.options.iconPosition:i,o="top"===n||"bottom"===n;this.icon?s&&this._removeClass(this.icon,null,this.options.icon):(this.icon=t("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),s&&this._addClass(this.icon,null,i),this._attachIcon(n),o?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconSpace||(this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(n))},_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.showLabel:t.showLabel,i=void 0===t.icon?this.options.icon: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,e&&this.element.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()}}),t.uiBackCompat!==!1&&(t.widget("ui.button",t.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){return"text"===t?(this._super("showLabel",e),void 0):("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),void 0)}}),t.fn.button=function(e){return function(){return!this.length||this.length&&"INPUT"!==this[0].tagName||this.length&&"INPUT"===this[0].tagName&&"checkbox"!==this.attr("type")&&"radio"!==this.attr("type")?e.apply(this,arguments):(t.ui.checkboxradio||t.error("Checkboxradio widget missing"),0===arguments.length?this.checkboxradio({icon:!1}):this.checkboxradio.apply(this,arguments))}}(t.fn.button),t.fn.buttonset=function(){return t.ui.controlgroup||t.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))}),t.ui.button,t.extend(t.ui,{datepicker:{version:"1.12.1"}});var m;t.extend(s.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return a(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,o;s=e.nodeName.toLowerCase(),n="div"===s||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),o=this._newInst(t(e),n),o.settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,o):n&&this._inlineDatepicker(e,o)},_newInst:function(e,i){var s=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?n(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(i),t.data(e,"datepicker",i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,o,a=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),a&&(i.append=t("<span class='"+this._appendClass+"'>"+a+"</span>"),e[r?"before":"after"](i.append)),e.off("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&e.on("focus",this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),o=this._get(i,"buttonImage"),i.trigger=t(this._get(i,"buttonImageOnly")?t("<img/>").addClass(this._triggerClass).attr({src:o,alt:n,title:n}):t("<button type='button'></button>").addClass(this._triggerClass).html(o?t("<img/>").attr({src:o,alt:n,title:n}):n)),e[r?"before":"after"](i.trigger),i.trigger.on("click",function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]?(t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])):t.datepicker._showDatepicker(e[0]),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,o=new Date(2009,11,20),a=this._get(t,"dateFormat");a.match(/[DM]/)&&(e=function(t){for(i=0,s=0,n=0;t.length>n;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(e,i){var s=t(e);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,n,o){var r,h,l,c,u,d=this._dialogInst;return d||(this.uuid+=1,r="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+r+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.on("keydown",this._doKeyDown),t("body").append(this._dialogInput),d=this._dialogInst=this._newInst(this._dialogInput,!1),d.settings={},t.data(this._dialogInput[0],"datepicker",d)),a(d.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(d,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,c=document.documentElement.scrollLeft||document.body.scrollLeft,u=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+c,l/2-150+u]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),d.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],"datepicker",d),this},_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,"datepicker");s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),m===n&&(m=null))},_enableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.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;this._disabledInputs.length>e;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,i,s){var n,o,r,h,l=this._getInst(e);return 2===arguments.length&&"string"==typeof i?"defaults"===i?t.extend({},t.datepicker._defaults):l?"all"===i?t.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),o=this._getDateDatepicker(e,!0),r=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),a(l.settings,n),null!==r&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,r)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(t(e),l),this._autoSize(l),this._setDate(l,o),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,o=t.datepicker._getInst(e.target),a=!0,r=o.dpDiv.is(".ui-datepicker-rtl");if(o._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),a=!1;break;case 13:return n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",o.dpDiv),n[0]&&t.datepicker._selectDay(e.target,o.selectedMonth,o.selectedYear,n[0]),i=t.datepicker._get(o,"onSelect"),i?(s=t.datepicker._formatDate(o),i.apply(o.input?o.input[0]:null,[s,o])):t.datepicker._hideDatepicker(),!1;case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),a=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),a=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),a=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),a=e.ctrlKey||e.metaKey;break;default:a=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):a=!1;a&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var i,s,n=t.datepicker._getInst(e.target);return t.datepicker._get(n,"constrainInput")?(i=t.datepicker._possibleChars(t.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(e){var i,s=t.datepicker._getInst(e.target);if(s.input.val()!==s.lastVal)try{i=t.datepicker.parseDate(t.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,t.datepicker._getFormatConfig(s)),i&&(t.datepicker._setDateFromField(s),t.datepicker._updateAlternate(s),t.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(e){if(e=e.target||e,"input"!==e.nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e){var s,n,o,r,h,l,c;s=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==s&&(t.datepicker._curInst.dpDiv.stop(!0,!0),s&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),n=t.datepicker._get(s,"beforeShow"),o=n?n.apply(e,[e,s]):{},o!==!1&&(a(s.settings,o),s.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(s),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),r=!1,t(e).parents().each(function(){return r|="fixed"===t(this).css("position"),!r}),h={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,s.dpDiv.empty(),s.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(s),h=t.datepicker._checkOffset(s,h,r),s.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":r?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),s.inline||(l=t.datepicker._get(s,"showAnim"),c=t.datepicker._get(s,"duration"),s.dpDiv.css("z-index",i(t(e))+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[l]?s.dpDiv.show(l,t.datepicker._get(s,"showOptions"),c):s.dpDiv[l||"show"](l?c:null),t.datepicker._shouldFocusInput(s)&&s.input.trigger("focus"),t.datepicker._curInst=s))
}},_updateDatepicker:function(e){this.maxRows=4,m=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],a=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;!a||e&&a!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&(t.effects.effect[i]||t.effects[i])?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(a,"onClose"),o&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(e,i,s){if(null==e||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,o,a,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,c="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),u=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,d=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,g=-1,m=-1,_=-1,v=-1,b=!1,y=function(t){var i=e.length>n+1&&e.charAt(n+1)===t;return i&&n++,i},w=function(t){var e=y(t),s="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n="y"===t?s:1,o=RegExp("^\\d{"+n+","+s+"}"),a=i.substring(h).match(o);if(!a)throw"Missing number at position "+h;return h+=a[0].length,parseInt(a[0],10)},k=function(e,s,n){var o=-1,a=t.map(y(e)?n:s,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(a,function(t,e){var s=e[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(o=e[0],h+=s.length,!1):void 0}),-1!==o)return o+1;throw"Unknown name at position "+h},x=function(){if(i.charAt(h)!==e.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;e.length>n;n++)if(b)"'"!==e.charAt(n)||y("'")?x():b=!1;else switch(e.charAt(n)){case"d":_=w("d");break;case"D":k("D",u,d);break;case"o":v=w("o");break;case"m":m=w("m");break;case"M":m=k("M",p,f);break;case"y":g=w("y");break;case"@":r=new Date(w("@")),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"!":r=new Date((w("!")-this._ticksTo1970)/1e4),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"'":y("'")?x():b=!0;break;default:x()}if(i.length>h&&(a=i.substr(h),!/^\s+/.test(a)))throw"Extra/unparsed characters found in date: "+a;if(-1===g?g=(new Date).getFullYear():100>g&&(g+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c>=g?0:-100)),v>-1)for(m=1,_=v;;){if(o=this._getDaysInMonth(g,m-1),o>=_)break;m++,_-=o}if(r=this._daylightSavingAdjust(new Date(g,m-1,_)),r.getFullYear()!==g||r.getMonth()+1!==m||r.getDate()!==_)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,o=(i?i.dayNames:null)||this._defaults.dayNames,a=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(e){var i=t.length>s+1&&t.charAt(s+1)===e;return i&&s++,i},l=function(t,e,i){var s=""+e;if(h(t))for(;i>s.length;)s="0"+s;return s},c=function(t,e,i,s){return h(t)?s[e]:i[e]},u="",d=!1;if(e)for(s=0;t.length>s;s++)if(d)"'"!==t.charAt(s)||h("'")?u+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":u+=l("d",e.getDate(),2);break;case"D":u+=c("D",e.getDay(),n,o);break;case"o":u+=l("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=l("m",e.getMonth()+1,2);break;case"M":u+=c("M",e.getMonth(),a,r);break;case"y":u+=h("y")?e.getFullYear():(10>e.getFullYear()%100?"0":"")+e.getFullYear()%100;break;case"@":u+=e.getTime();break;case"!":u+=1e4*e.getTime()+this._ticksTo1970;break;case"'":h("'")?u+="'":d=!0;break;default:u+=t.charAt(s)}return u},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=t.length>e+1&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;t.length>e;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,e){return void 0!==t.settings[e]?t.settings[e]: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(r){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(e,i,s){var n=function(t){var e=new Date;return e.setDate(e.getDate()+t),e},o=function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,o=n.getFullYear(),a=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":a+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a));break;case"y":case"Y":o+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a))}l=h.exec(i)}return new Date(o,a,r)},a=null==i||""===i?s:"string"==typeof i?o(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return a=a&&"Invalid Date"==""+a?s:a,a&&(a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)),this._daylightSavingAdjust(a)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,a=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=a.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=a.getMonth(),t.drawYear=t.selectedYear=t.currentYear=a.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){var e=!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return e},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}};t(this).on(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,h,l,c,u,d,p,f,g,m,_,v,b,y,w,k,x,C,D,I,T,P,M,S,H,z,O,A,N,W,E,F,L,R=new Date,B=this._daylightSavingAdjust(new Date(R.getFullYear(),R.getMonth(),R.getDate())),Y=this._get(t,"isRTL"),j=this._get(t,"showButtonPanel"),q=this._get(t,"hideIfNoPrevNext"),K=this._get(t,"navigationAsDateFormat"),U=this._getNumberOfMonths(t),V=this._get(t,"showCurrentAtPos"),$=this._get(t,"stepMonths"),X=1!==U[0]||1!==U[1],G=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),Q=this._getMinMaxDate(t,"min"),J=this._getMinMaxDate(t,"max"),Z=t.drawMonth-V,te=t.drawYear;if(0>Z&&(Z+=12,te--),J)for(e=this._daylightSavingAdjust(new Date(J.getFullYear(),J.getMonth()-U[0]*U[1]+1,J.getDate())),e=Q&&Q>e?Q:e;this._daylightSavingAdjust(new Date(te,Z,1))>e;)Z--,0>Z&&(Z=11,te--);for(t.drawMonth=Z,t.drawYear=te,i=this._get(t,"prevText"),i=K?this.formatDate(i,this._daylightSavingAdjust(new Date(te,Z-$,1)),this._getFormatConfig(t)):i,s=this._canAdjustMonth(t,-1,te,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>":q?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>",n=this._get(t,"nextText"),n=K?this.formatDate(n,this._daylightSavingAdjust(new Date(te,Z+$,1)),this._getFormatConfig(t)):n,o=this._canAdjustMonth(t,1,te,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>":q?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>",a=this._get(t,"currentText"),r=this._get(t,"gotoCurrent")&&t.currentDay?G:B,a=K?this.formatDate(a,r,this._getFormatConfig(t)):a,h=t.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(t,"closeText")+"</button>",l=j?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(Y?h:"")+(this._isInRange(t,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+a+"</button>":"")+(Y?"":h)+"</div>":"",c=parseInt(this._get(t,"firstDay"),10),c=isNaN(c)?0:c,u=this._get(t,"showWeek"),d=this._get(t,"dayNames"),p=this._get(t,"dayNamesMin"),f=this._get(t,"monthNames"),g=this._get(t,"monthNamesShort"),m=this._get(t,"beforeShowDay"),_=this._get(t,"showOtherMonths"),v=this._get(t,"selectOtherMonths"),b=this._getDefaultDate(t),y="",k=0;U[0]>k;k++){for(x="",this.maxRows=4,C=0;U[1]>C;C++){if(D=this._daylightSavingAdjust(new Date(te,Z,t.selectedDay)),I=" ui-corner-all",T="",X){if(T+="<div class='ui-datepicker-group",U[1]>1)switch(C){case 0:T+=" ui-datepicker-group-first",I=" ui-corner-"+(Y?"right":"left");break;case U[1]-1:T+=" ui-datepicker-group-last",I=" ui-corner-"+(Y?"left":"right");break;default:T+=" ui-datepicker-group-middle",I=""}T+="'>"}for(T+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+I+"'>"+(/all|left/.test(I)&&0===k?Y?o:s:"")+(/all|right/.test(I)&&0===k?Y?s:o:"")+this._generateMonthYearHeader(t,Z,te,Q,J,k>0||C>0,f,g)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",P=u?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",w=0;7>w;w++)M=(w+c)%7,P+="<th scope='col'"+((w+c+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[M]+"'>"+p[M]+"</span></th>";for(T+=P+"</tr></thead><tbody>",S=this._getDaysInMonth(te,Z),te===t.selectedYear&&Z===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,S)),H=(this._getFirstDayOfMonth(te,Z)-c+7)%7,z=Math.ceil((H+S)/7),O=X?this.maxRows>z?this.maxRows:z:z,this.maxRows=O,A=this._daylightSavingAdjust(new Date(te,Z,1-H)),N=0;O>N;N++){for(T+="<tr>",W=u?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(A)+"</td>":"",w=0;7>w;w++)E=m?m.apply(t.input?t.input[0]:null,[A]):[!0,""],F=A.getMonth()!==Z,L=F&&!v||!E[0]||Q&&Q>A||J&&A>J,W+="<td class='"+((w+c+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(A.getTime()===D.getTime()&&Z===t.selectedMonth&&t._keyEvent||b.getTime()===A.getTime()&&b.getTime()===D.getTime()?" "+this._dayOverClass:"")+(L?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!_?"":" "+E[1]+(A.getTime()===G.getTime()?" "+this._currentClass:"")+(A.getTime()===B.getTime()?" ui-datepicker-today":""))+"'"+(F&&!_||!E[2]?"":" title='"+E[2].replace(/'/g,"&#39;")+"'")+(L?"":" data-handler='selectDay' data-event='click' data-month='"+A.getMonth()+"' data-year='"+A.getFullYear()+"'")+">"+(F&&!_?"&#xa0;":L?"<span class='ui-state-default'>"+A.getDate()+"</span>":"<a class='ui-state-default"+(A.getTime()===B.getTime()?" ui-state-highlight":"")+(A.getTime()===G.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+A.getDate()+"</a>")+"</td>",A.setDate(A.getDate()+1),A=this._daylightSavingAdjust(A);T+=W+"</tr>"}Z++,Z>11&&(Z=0,te++),T+="</tbody></table>"+(X?"</div>"+(U[0]>0&&C===U[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=T}y+=x}return y+=l,t._keyEvent=!1,y},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var h,l,c,u,d,p,f,g,m=this._get(t,"changeMonth"),_=this._get(t,"changeYear"),v=this._get(t,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",y="";if(o||!m)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",c=0;12>c;c++)(!h||c>=s.getMonth())&&(!l||n.getMonth()>=c)&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(v||(b+=y+(!o&&m&&_?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!_)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(u=this._get(t,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e},f=p(u[0]),g=Math.max(f,p(u[1]||"")),f=s?Math.max(f,s.getFullYear()):f,g=n?Math.min(g,n.getFullYear()):g,t.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";g>=f;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),v&&(b+=(!o&&m&&_?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),o=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),a=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,o)));t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&i>e?i:e;return s&&n>s?s:n},_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){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_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),o=this._daylightSavingAdjust(new Date(i,s+(0>e?e:n[0]*n[1]),1));return 0>e&&o.setDate(this._getDaysInMonth(o.getFullYear(),o.getMonth())),this._isInRange(t,o)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),o=this._getMinMaxDate(t,"max"),a=null,r=null,h=this._get(t,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),a=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(a+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!o||e.getTime()<=o.getTime())&&(!a||e.getFullYear()>=a)&&(!r||r>=e.getFullYear())},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),{shortYearCutoff:e,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);var n=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"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).on("mousedown",t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)}):t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i))},t.datepicker=new s,t.datepicker.initialized=!1,t.datepicker.uuid=(new Date).getTime(),t.datepicker.version="1.12.1",t.datepicker,t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var _=!1;t(document).on("mouseup",function(){_=!1}),t.widget("ui.mouse",{version:"1.12.1",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(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),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(e){if(!_){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,s=1===e.which,n="string"==typeof this.options.cancel&&e.target.nodeName?t(e.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(e)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(e)!==!1,!this._mouseStarted)?(e.preventDefault(),!0):(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),_=!0,!0)):!0}},_mouseMove:function(e){if(this._mouseMoved){if(t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button)return this._mouseUp(e);if(!e.which)if(e.originalEvent.altKey||e.originalEvent.ctrlKey||e.originalEvent.metaKey||e.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,_=!1,e.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}}),t.ui.plugin={add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])},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;o.length>n;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},t.ui.safeBlur=function(e){e&&"body"!==e.nodeName.toLowerCase()&&t(e).trigger("blur")},t.widget("ui.draggable",t.ui.mouse,{version:"1.12.1",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(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(this._blurActiveElement(e),this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("<div>").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=t.ui.safeActiveElement(this.document[0]),s=t(e.target);s.closest(i).length||t.ui.safeBlur(i)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!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(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp(new t.Event("mouseup",e)),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.trigger("focus"),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new t.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper),n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.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 e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=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:s?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:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(h=this.originalPageX),"x"===a.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._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(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){var t=this;t.isOver?(t.isOver=0,s.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,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,o=this;o.positionAbs=s.positionAbs,o.helperProportions=s.helperProportions,o.offset.click=s.offset.click,o._intersectsWith(o.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==o&&this._intersectsWith(this.containerCache)&&t.contains(o.element[0],this.element[0])&&(n=!1),n})),n?(o.isOver||(o.isOver=1,s._parent=i.helper.parent(),o.currentItem=i.helper.appendTo(o.element).data("ui-sortable-item",!0),o.options._helper=o.options.helper,o.options.helper=function(){return i.helper[0]},e.target=o.currentItem[0],o._mouseCapture(e,!0),o._mouseStart(e,!0,!0),o.offset.click.top=s.offset.click.top,o.offset.click.left=s.offset.click.left,o.offset.parent.left-=s.offset.parent.left-o.offset.parent.left,o.offset.parent.top-=s.offset.parent.top-o.offset.parent.top,s._trigger("toSortable",e),s.dropped=o.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,o.fromOutside=s),o.currentItem&&(o._mouseDrag(e),i.position=o.position)):o.isOver&&(o.isOver=0,o.cancelHelperRemoval=!0,o.options._revert=o.options.revert,o.options.revert=!1,o._trigger("out",e,o._uiHash(o)),o._mouseStop(e,!0),o.options.revert=o.options._revert,o.options.helper=o.options._helper,o.placeholder&&o.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),o=s.options;n.css("cursor")&&(o._cursor=n.css("cursor")),n.css("cursor",o.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("opacity")&&(o._opacity=n.css("opacity")),n.css("opacity",o.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.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(e,i,s){var n=s.options,o=!1,a=s.scrollParentNotHidden[0],r=s.document[0];a!==r&&"HTML"!==a.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+a.offsetHeight-e.pageY<n.scrollSensitivity?a.scrollTop=o=a.scrollTop+n.scrollSpeed:e.pageY-s.overflowOffset.top<n.scrollSensitivity&&(a.scrollTop=o=a.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+a.offsetWidth-e.pageX<n.scrollSensitivity?a.scrollLeft=o=a.scrollLeft+n.scrollSpeed:e.pageX-s.overflowOffset.left<n.scrollSensitivity&&(a.scrollLeft=o=a.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(e.pageY-t(r).scrollTop()<n.scrollSensitivity?o=t(r).scrollTop(t(r).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(r).scrollTop())<n.scrollSensitivity&&(o=t(r).scrollTop(t(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(e.pageX-t(r).scrollLeft()<n.scrollSensitivity?o=t(r).scrollLeft(t(r).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(r).scrollLeft())<n.scrollSensitivity&&(o=t(r).scrollLeft(t(r).scrollLeft()+n.scrollSpeed)))),o!==!1&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(s,e)}}),t.ui.plugin.add("draggable","snap",{start:function(e,i,s){var n=s.options;s.snapElements=[],t(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var e=t(this),i=e.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:e.outerWidth(),height:e.outerHeight(),top:i.top,left:i.left})})},drag:function(e,i,s){var n,o,a,r,h,l,c,u,d,p,f=s.options,g=f.snapTolerance,m=i.offset.left,_=m+s.helperProportions.width,v=i.offset.top,b=v+s.helperProportions.height;for(d=s.snapElements.length-1;d>=0;d--)h=s.snapElements[d].left-s.margins.left,l=h+s.snapElements[d].width,c=s.snapElements[d].top-s.margins.top,u=c+s.snapElements[d].height,h-g>_||m>l+g||c-g>b||v>u+g||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)?(s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(n=g>=Math.abs(c-b),o=g>=Math.abs(u-v),a=g>=Math.abs(h-_),r=g>=Math.abs(l-m),n&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||o||a||r,"outer"!==f.snapMode&&(n=g>=Math.abs(c-v),o=g>=Math.abs(u-b),a=g>=Math.abs(h-m),r=g>=Math.abs(l-_),n&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||o||a||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||o||a||r||p)}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,o=s.options,a=t.makeArray(t(o.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});a.length&&(n=parseInt(t(a[0]).css("zIndex"),10)||0,t(a).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+a.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("zIndex")&&(o._zIndex=n.css("zIndex")),n.css("zIndex",o.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.resizable",t.ui.mouse,{version:"1.12.1",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(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)},_create:function(){var e,i=this.options,s=this;this._addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!i.aspectRatio,aspectRatio:i.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:i.helper||i.ghost||i.animate?i.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,e={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(e),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(e),this._proportionallyResize()),this._setupHandles(),i.autoHide&&t(this.element).on("mouseenter",function(){i.disabled||(s._removeClass("ui-resizable-autohide"),s._handles.show())}).on("mouseleave",function(){i.disabled||s.resizing||(s._addClass("ui-resizable-autohide"),s._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(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),i(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;default:}},_setupHandles:function(){var e,i,s,n,o,a=this.options,r=this;if(this.handles=a.handles||(t(".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=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),s=this.handles.split(","),this.handles={},i=0;s.length>i;i++)e=t.trim(s[i]),n="ui-resizable-"+e,o=t("<div>"),this._addClass(o,"ui-resizable-handle "+n),o.css({zIndex:a.zIndex}),this.handles[e]=".ui-resizable-"+e,this.element.append(o);this._renderAxis=function(e){var i,s,n,o;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(o=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=o&&o[1]?o[1]:"se")}),a.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,o=this.options,a=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),o.containment&&(i+=t(o.containment).scrollLeft()||0,s+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),this._addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,o=this.axis,a=e.pageX-n.left||0,r=e.pageY-n.top||0,h=this._change[o];return this._updatePrevProperties(),h?(i=h.apply(this,[e,a,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:c.sizeDiff.height,o=s?0:c.sizeDiff.width,a={width:c.helper.width()-o,height:c.helper.height()-n},r=parseFloat(c.element.css("left"))+(c.position.left-c.originalPosition.left)||null,h=parseFloat(c.element.css("top"))+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(a,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",e),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,n,o,a=this.options;o={minWidth:this._isNumber(a.minWidth)?a.minWidth:0,maxWidth:this._isNumber(a.maxWidth)?a.maxWidth:1/0,minHeight:this._isNumber(a.minHeight)?a.minHeight:0,maxHeight:this._isNumber(a.maxHeight)?a.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,s=o.minWidth/this.aspectRatio,i=o.maxHeight*this.aspectRatio,n=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),s>o.minHeight&&(o.minHeight=s),o.maxWidth>i&&(o.maxWidth=i),o.maxHeight>n&&(o.maxHeight=n)),this._vBoundaries=o},_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,h=this.originalPosition.top+this.originalSize.height,l=/sw|nw|w/.test(i),c=/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&&l&&(t.left=r-e.minWidth),s&&l&&(t.left=r-e.maxWidth),a&&c&&(t.top=h-e.minHeight),n&&c&&(t.top=h-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")];4>e;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;this._proportionallyResizeElements.length>e;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 e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),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:++i.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,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-a},l=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,c=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,o,a,r,h=t(this).resizable("instance"),l=h.options,c=h.element,u=l.containment,d=u instanceof t?u.get(0):/parent/.test(u)?c.parent().get(0):u;d&&(h.containerElement=t(d),/document/.test(u)||u===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=h._num(e.css("padding"+s))}),h.containerOffset=e.offset(),h.containerPosition=e.position(),h.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,o=h.containerSize.width,a=h._hasScroll(d,"left")?d.scrollWidth:o,r=h._hasScroll(d)?d.scrollHeight:n,h.parentData={element:d,left:s.left,top:s.top,width:a,height:r}))},resize:function(e){var i,s,n,o,a=t(this).resizable("instance"),r=a.options,h=a.containerOffset,l=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(a._helper?h.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-h.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio,p=!1),a.position.left=r.helper?h.left:0),l.top<(a._helper?h.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-h.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio,p=!1),a.position.top=a._helper?h.top:0),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o?(a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top):(a.offset.left=a.element.offset().left,a.offset.top=a.element.offset().top),i=Math.abs(a.sizeDiff.width+(a._helper?a.offset.left-u.left:a.offset.left-h.left)),s=Math.abs(a.sizeDiff.height+(a._helper?a.offset.top-u.top:a.offset.top-h.top)),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio,p=!1)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio,p=!1)),p||(a.position.left=a.prevPosition.left,a.position.top=a.prevPosition.top,a.size.width=a.prevSize.width,a.size.height=a.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),h=a.outerWidth()-e.sizeDiff.width,l=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance"),i=e.options;t(i.alsoResize).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseFloat(e.width()),height:parseFloat(e.height()),left:parseFloat(e.css("left")),top:parseFloat(e.css("top"))})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left:s.position.left-a.left||0};t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},o=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("ui-resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:i.height,width:i.width,margin:0,left:0,top:0}),e._addClass(e.ghost,"ui-resizable-ghost"),t.uiBackCompat!==!1&&"string"==typeof e.options.ghost&&e.ghost.addClass(this.options.ghost),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,o=i.originalSize,a=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,c=h[1]||1,u=Math.round((n.width-o.width)/l)*l,d=Math.round((n.height-o.height)/c)*c,p=o.width+u,f=o.height+d,g=s.maxWidth&&p>s.maxWidth,m=s.maxHeight&&f>s.maxHeight,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=h,_&&(p+=l),v&&(f+=c),g&&(p-=l),m&&(f-=c),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=a.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=a.left-u):((0>=f-c||0>=p-l)&&(e=i._getPaddingPlusBorderDimensions(this)),f-c>0?(i.size.height=f,i.position.top=a.top-d):(f=c-e.height,i.size.height=f,i.position.top=a.top+o.height-f),p-l>0?(i.size.width=p,i.position.left=a.left-u):(p=l-e.width,i.size.width=p,i.position.left=a.left+o.width-p))}}),t.ui.resizable,t.widget("ui.dialog",{version:"1.12.1",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(e){var i=t(this).css(e).offset().top;0>i&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),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&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"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),t.length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog
},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t.ui.safeBlur(t.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(t.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(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_keepFocus:function(e){function i(){var e=t.ui.safeActiveElement(this.document[0]),i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<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(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.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 e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<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)}}),e=t("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this._removeClass(this.uiDialog,"ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,o={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(o).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){i._addClass(t(this),"ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,e(n))},drag:function(t,s){i._trigger("drag",t,e(s))},stop:function(n,o){var a=o.offset.left-i.document.scrollLeft(),r=o.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(a>=0?"+":"")+a+" "+"top"+(r>=0?"+":"")+r,of:i.window},i._removeClass(t(this),"ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,e(o))}})},_makeResizable:function(){function e(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}var i=this,s=this.options,n=s.resizable,o=this.uiDialog.css("position"),a="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:a,start:function(s,n){i._addClass(t(this),"ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,e(n))},resize:function(t,s){i._trigger("resize",t,e(s))},stop:function(n,o){var a=i.uiDialog.offset(),r=a.left-i.document.scrollLeft(),h=a.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},i._removeClass(t(this),"ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,e(o))}}).css("position",o)},_trackFocus:function(){this._on(this.widget(),{focusin:function(e){this._makeFocusTarget(),this._focusedElement=t(e.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var e=this._trackingInstances(),i=t.inArray(this,e);-1!==i&&e.splice(i,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||(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(e){var i=this,s=!1,n={};t.each(e,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(e,i){var s,n,o=this.uiDialog;"disabled"!==e&&(this._super(e,i),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:t("<a>").text(""+this.options.closeText).html()}),"draggable"===e&&(s=o.is(":data(ui-draggable)"),s&&!i&&o.draggable("destroy"),!s&&i&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(n=o.is(":data(ui-resizable)"),n&&!i&&o.resizable("destroy"),n&&"string"==typeof i&&o.resizable("option","handles",i),n||i===!1||this._makeResizable()),"title"===e&&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 e=t(this);return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return t(e.target).closest(".ui-dialog").length?!0:!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=!0;this._delay(function(){e=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(t){e||this._allowInteraction(t)||(t.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=t("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var t=this.document.data("ui-dialog-overlays")-1;t?this.document.data("ui-dialog-overlays",t):(this._off(this.document,"focusin"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null}}}),t.uiBackCompat!==!1&&t.widget("ui.dialog",t.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)}}),t.ui.dialog,t.widget("ui.droppable",{version:"1.12.1",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 e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],void 0):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this._addClass("ui-droppable")},_addToManager:function(e){t.ui.ddmanager.droppables[e]=t.ui.ddmanager.droppables[e]||[],t.ui.ddmanager.droppables[e].push(this)},_splice:function(t){for(var e=0;t.length>e;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var e=t.ui.ddmanager.droppables[this.options.scope];this._splice(e)},_setOption:function(e,i){if("accept"===e)this.accept=t.isFunction(i)?i:function(t){return t.is(i)};else if("scope"===e){var s=t.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(e,i)},_activate:function(e){var i=t.ui.ddmanager.current;this._addActiveClass(),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this._removeActiveClass(),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._addHoverClass(),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeHoverClass(),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=t(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&v(s,t.extend(i,{offset:i.element.offset()}),i.options.tolerance,e)?(n=!0,!1):void 0}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},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")}});var v=t.ui.intersect=function(){function t(t,e,i){return t>=e&&e+i>t}return function(e,i,s,n){if(!i.offset)return!1;var o=(e.positionAbs||e.position.absolute).left+e.margins.left,a=(e.positionAbs||e.position.absolute).top+e.margins.top,r=o+e.helperProportions.width,h=a+e.helperProportions.height,l=i.offset.left,c=i.offset.top,u=l+i.proportions().width,d=c+i.proportions().height;switch(s){case"fit":return o>=l&&u>=r&&a>=c&&d>=h;case"intersect":return o+e.helperProportions.width/2>l&&u>r-e.helperProportions.width/2&&a+e.helperProportions.height/2>c&&d>h-e.helperProportions.height/2;case"pointer":return t(n.pageY,c,i.proportions().height)&&t(n.pageX,l,i.proportions().width);case"touch":return(a>=c&&d>=a||h>=c&&d>=h||c>a&&h>d)&&(o>=l&&u>=o||r>=l&&u>=r||l>o&&r>u);default:return!1}}}();t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,o=t.ui.ddmanager.droppables[e.options.scope]||[],a=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;o.length>s;s++)if(!(o[s].options.disabled||e&&!o[s].accept.call(o[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===o[s].element[0]){o[s].proportions().height=0;continue t}o[s].visible="none"!==o[s].element.css("display"),o[s].visible&&("mousedown"===a&&o[s]._activate.call(o[s],i),o[s].offset=o[s].element.offset(),o[s].proportions({width:o[s].element[0].offsetWidth,height:o[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&v(e,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").on("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,o,a=v(e,this,this.options.tolerance,i),r=!a&&this.isover?"isout":a&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,o=this.element.parents(":data(ui-droppable)").filter(function(){return t(this).droppable("instance").options.scope===n}),o.length&&(s=t(o[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").off("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}},t.uiBackCompat!==!1&&t.widget("ui.droppable",t.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)}}),t.ui.droppable,t.widget("ui.progressbar",{version:"1.12.1",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=t("<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){return void 0===t?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),void 0)},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1: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 e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).width(i.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,e===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}}),t.widget("ui.selectable",t.ui.mouse,{version:"1.12.1",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 e=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e.elementPos=t(e.element[0]).offset(),e.selectees=t(e.options.filter,e.element[0]),e._addClass(e.selectees,"ui-selectee"),e.selectees.each(function(){var i=t(this),s=i.offset(),n={left:s.left-e.elementPos.left,top:s.top-e.elementPos.top};t.data(this,"selectable-item",{element:this,$element:i,left:n.left,top:n.top,right:n.left+i.outerWidth(),bottom:n.top+i.outerHeight(),startselected:!1,selected:i.hasClass("ui-selected"),selecting:i.hasClass("ui-selecting"),unselecting:i.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=t("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.elementPos=t(this.element[0]).offset(),this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(i._removeClass(s.$element,"ui-selected"),s.selected=!1,i._addClass(s.$element,"ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),i._removeClass(n.$element,s?"ui-unselecting":"ui-selected")._addClass(n.$element,s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,o=this.opos[0],a=this.opos[1],r=e.pageX,h=e.pageY;return o>r&&(i=r,r=o,o=i),a>h&&(i=h,h=a,a=i),this.helper.css({left:o,top:a,width:r-o,height:h-a}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),l=!1,c={};i&&i.element!==s.element[0]&&(c.left=i.left+s.elementPos.left,c.right=i.right+s.elementPos.left,c.top=i.top+s.elementPos.top,c.bottom=i.bottom+s.elementPos.top,"touch"===n.tolerance?l=!(c.left>r||o>c.right||c.top>h||a>c.bottom):"fit"===n.tolerance&&(l=c.left>o&&r>c.right&&c.top>a&&h>c.bottom),l?(i.selected&&(s._removeClass(i.$element,"ui-selected"),i.selected=!1),i.unselecting&&(s._removeClass(i.$element,"ui-unselecting"),i.unselecting=!1),i.selecting||(s._addClass(i.$element,"ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,s._addClass(i.$element,"ui-selected"),i.selected=!0):(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,i.startselected&&(s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(s._removeClass(i.$element,"ui-selected"),i.selected=!1,s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-selecting")._addClass(s.$element,"ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),t.widget("ui.selectmenu",[t.ui.formResetMixin,{version:"1.12.1",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 e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=t()},_drawButton:function(){var e,i=this,s=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.focus(),t.preventDefault()}}),this.element.hide(),this.button=t("<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"),e=t("<span>").appendTo(this.button),this._addClass(e,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(s).appendTo(this.button),this.options.width!==!1&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){i._rendered||i._refreshMenu()})},_drawMenu:function(){var e=this;this.menu=t("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=t("<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,i){t.preventDefault(),e._setSelection(),e._select(i.item.data("ui-selectmenu-item"),t)},focus:function(t,i){var s=i.item.data("ui-selectmenu-item");null!=e.focusIndex&&s.index!==e.focusIndex&&(e._trigger("focus",t,{item:s}),e.isOpen||e._select(s,t)),e.focusIndex=s.index,e.button.attr("aria-activedescendant",e.menuItems.eq(s.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,e=this.element.find("option");this.menu.empty(),this._parseOptions(e),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,e.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(t.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(e){var i=t("<span>");return this._setText(i,e.label),this._addClass(i,"ui-selectmenu-text"),i},_renderMenu:function(e,i){var s=this,n="";t.each(i,function(i,o){var a;o.optgroup!==n&&(a=t("<li>",{text:o.optgroup}),s._addClass(a,"ui-selectmenu-optgroup","ui-menu-divider"+(o.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),a.appendTo(e),n=o.optgroup),s._renderItemData(e,o)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(e,i){var s=t("<li>"),n=t("<div>",{title:i.element.attr("title")});return i.disabled&&this._addClass(s,null,"ui-state-disabled"),this._setText(n,i.label),s.append(n).appendTo(e)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),n+=":not(.ui-state-disabled)"),s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](n).eq(-1):i[t+"All"](n).eq(0),s.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(),t.removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(e){this.isOpen&&(t(e.target).closest(".ui-selectmenu-menu, #"+t.ui.escapeSelector(this.ids.button)).length||this.close(e))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection(),t.rangeCount&&(this.range=t.getRangeAt(0))):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(e){var i=!0;switch(e.keyCode){case t.ui.keyCode.TAB:case t.ui.keyCode.ESCAPE:this.close(e),i=!1;break;case t.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(e);break;case t.ui.keyCode.UP:e.altKey?this._toggle(e):this._move("prev",e);break;case t.ui.keyCode.DOWN:e.altKey?this._toggle(e):this._move("next",e);break;case t.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(e):this._toggle(e);break;case t.ui.keyCode.LEFT:this._move("prev",e);break;case t.ui.keyCode.RIGHT:this._move("next",e);break;case t.ui.keyCode.HOME:case t.ui.keyCode.PAGE_UP:this._move("first",e);break;case t.ui.keyCode.END:case t.ui.keyCode.PAGE_DOWN:this._move("last",e);break;default:this.menu.trigger(e),i=!1}i&&e.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){var e=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":e,"aria-activedescendant":e}),this.menu.attr("aria-activedescendant",e)},_setOption:function(t,e){if("icons"===t){var 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 e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_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;return t===!1?(this.button.css("width",""),void 0):(null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t),void 0)},_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(e){var i=this,s=[];e.each(function(e,n){s.push(i._parseOption(t(n),e))}),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)}}]),t.widget("ui.slider",t.ui.mouse,{version:"1.12.1",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 e,i,s=this.options,n=this.element.find(".ui-slider-handle"),o="<span tabindex='0'></span>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.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=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.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(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,this._addClass(o,null,"ui-state-active"),o.trigger("focus"),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!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,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_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,o=this.value(),a=this.values();this._hasMultipleValues()&&(n=this.values(e?0:1),o=this.values(e),2===this.options.values.length&&this.options.range===!0&&(i=0===e?Math.min(n,i):Math.max(n,i)),a[e]=i),i!==o&&(s=this._trigger("slide",t,this._uiHash(e,i,a)),s!==!1&&(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(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this._hasMultipleValues()?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),this._super(e,i),e){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(i),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=n-1;s>=0;s--)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_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,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this._hasMultipleValues()){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step,s=Math.round((t-e)/i)*i;t=s+e,t>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-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,s,n,o,a=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,c={};this._hasMultipleValues()?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),c["horizontal"===h.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[l?"animate":"css"](c,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),o=this._valueMax(),i=o!==n?100*((s-n)/(o-n)):0,c["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](c,r.animate),"min"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:100-i+"%"},r.animate),"min"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:100-i+"%"},r.animate))},_handleEvents:{keydown:function(e){var i,s,n,o,a=t(e.target).data("ui-slider-handle-index");switch(e.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(e.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(t(e.target),null,"ui-state-active"),i=this._start(e,a),i===!1))return}switch(o=this.options.step,s=n=this._hasMultipleValues()?this.values(a):this.value(),e.keyCode){case t.ui.keyCode.HOME:n=this._valueMin();break;case t.ui.keyCode.END:n=this._valueMax();break;case t.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+o);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-o)}this._slide(e,a,n)},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),this._removeClass(t(e.target),null,"ui-state-active"))}}}),t.widget("ui.sortable",t.ui.mouse,{version:"1.12.1",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 t>=e&&e+i>t},_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 e=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),t.each(this.items,function(){e._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;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):void 0}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-this.document.scrollTop()<a.scrollSensitivity?r=this.document.scrollTop(this.document.scrollTop()-a.scrollSpeed):this.window.height()-(e.pageY-this.document.scrollTop())<a.scrollSensitivity&&(r=this.document.scrollTop(this.document.scrollTop()+a.scrollSpeed)),e.pageX-this.document.scrollLeft()<a.scrollSensitivity?r=this.document.scrollLeft(this.document.scrollLeft()-a.scrollSpeed):this.window.width()-(e.pageX-this.document.scrollLeft())<a.scrollSensitivity&&(r=this.document.scrollLeft(this.document.scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp(new t.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 e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].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(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_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,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var e,i,s="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),n="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),o=s&&n;return o?(e=this._getDragVerticalDirection(),i=this._getDragHorizontalDirection(),this.floating?"right"===i||"down"===e?2:1:e&&("down"===e?2:1)):!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._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"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(e){function i(){r.push(this)}var s,n,o,a,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(o=t(l[s],this.document[0]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&h.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i],this.document[0]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]);return e._addClass(n,"ui-sortable-placeholder",i||e.currentItem[0].className)._removeClass(n,"ui-sortable-helper"),"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("<tr>",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t("<td>&#160;</td>",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,o,a,r,h,l,c,u,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0);if(d)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,o=null,c=d.floating||this._isFloating(this.currentItem),a=c?"left":"top",r=c?"width":"height",u=c?"pageX":"pageY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[a],l=!1,e[u]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(e[u]-h)&&(n=Math.abs(e[u]-h),o=this.items[s],this.direction=l?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;o?this._rearrange(e,o,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){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()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.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(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.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){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.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||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,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(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.spinner",{version:"1.12.1",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 e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?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(e){function i(){var e=this.element[0]===t.ui.safeActiveElement(this.document[0]);e||(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===t.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"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())&&this.uiSpinner.height()>0&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_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&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.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,s,n;return"culture"===t||"numberFormat"===t?(i=this._parse(this.element.val()),this.options[t]=e,this.element.val(this._format(i)),void 0):(("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(s=this.buttons.first().find(".ui-icon"),this._removeClass(s,null,this.options.icons.up),this._addClass(s,null,e.up),n=this.buttons.last().find(".ui-icon"),this._removeClass(n,null,this.options.icons.down),this._addClass(n,null,e.down)),this._super(t,e),void 0)},_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:r(function(t){this._super(t)}),_parse:function(t){return"string"==typeof t&&""!==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?!1:t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(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:r(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:r(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:r(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:r(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(r(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),t.uiBackCompat!==!1&&t.widget("ui.spinner",t.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>"}}),t.ui.spinner,t.widget("ui.tabs",{version:"1.12.1",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:function(){var t=/#.*$/;return function(e){var i,s;i=e.href.replace(t,""),s=location.href.replace(t,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return e.hash.length>1&&i===s}}(),_create:function(){var e=this,i=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,i.collapsible),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var e=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===e&&(s&&this.tabs.each(function(i,n){return t(n).attr("aria-controls")===s?(e=i,!1):void 0}),null===e&&(e=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===e||-1===e)&&(e=this.tabs.length?0:!1)),e!==!1&&(e=this.tabs.index(this.tabs.eq(e)),-1===e&&(e=i?!1:0)),!i&&e===!1&&this.anchors.length&&(e=0),e},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(e){var i=t(t.ui.safeActiveElement(this.document[0])).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(e)){switch(e.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:s++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:n=!1,s--;break;case t.ui.keyCode.END:s=this.anchors.length-1;break;case t.ui.keyCode.HOME:s=0;break;case t.ui.keyCode.SPACE:return e.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case t.ui.keyCode.ENTER:return e.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}e.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),e.ctrlKey||e.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(e){return e.altKey&&e.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):e.altKey&&e.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):(this._super(t,e),"collapsible"===t&&(this._toggleClass("ui-tabs-collapsible",null,e),e||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e),void 0)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),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 e=this,i=this.tabs,s=this.anchors,n=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(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){t(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 t("a",this)[0]}).attr({role:"presentation",tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=t(),this.anchors.each(function(i,s){var n,o,a,r=t(s).uniqueId().attr("id"),h=t(s).closest("li"),l=h.attr("aria-controls");e._isLocal(s)?(n=s.hash,a=n.substring(1),o=e.element.find(e._sanitizeSelector(n))):(a=h.attr("aria-controls")||t({}).uniqueId()[0].id,n="#"+a,o=e.element.find(n),o.length||(o=e._createPanel(a),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":a,"aria-labelledby":r}),o.attr("aria-labelledby",r)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(e){var i,s,n;for(t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1),n=0;s=this.tabs[n];n++)i=t(s),e===!0||-1!==t.inArray(n,e)?(i.attr("aria-disabled","true"),this._addClass(i,null,"ui-state-disabled")):(i.removeAttr("aria-disabled"),this._removeClass(i,null,"ui-state-disabled"));this.options.disabled=e,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,e===!0)},_setupEvents:function(e){var i={};e&&t.each(e.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(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n.closest("li"),a=o[0]===s[0],r=a&&i.collapsible,h=r?t():this._getPanelForTab(o),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():o,newPanel:h};e.preventDefault(),o.hasClass("ui-state-disabled")||o.hasClass("ui-tabs-loading")||this.running||a&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(o),this.active=a?t():o,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(o),e),this._toggle(e,c))},_toggle:function(e,i){function s(){o.running=!1,o._trigger("activate",e,i)}function n(){o._addClass(i.newTab.closest("li"),"ui-tabs-active","ui-state-active"),a.length&&o.options.show?o._show(a,o.options.show,s):(a.show(),s())}var o=this,a=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){o._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),n()}):(this._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),a.length&&r.length?i.oldTab.attr("tabIndex",-1):a.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),a.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+t.ui.escapeSelector(e)+"']"))),e},_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(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(e){var i=this.options.disabled;i!==!1&&(void 0===e?i=!1:(e=this._getIndex(e),i=t.isArray(i)?t.map(i,function(t){return t!==e?t:null}):t.map(this.tabs,function(t,i){return i!==e?i:null})),this._setOptionDisabled(i))},disable:function(e){var i=this.options.disabled;if(i!==!0){if(void 0===e)i=!0;else{if(e=this._getIndex(e),-1!==t.inArray(e,i))return;i=t.isArray(i)?t.merge([e],i).sort():[e]}this._setOptionDisabled(i)}},load:function(e,i){e=this._getIndex(e);var s=this,n=this.tabs.eq(e),o=n.find(".ui-tabs-anchor"),a=this._getPanelForTab(n),r={tab:n,panel:a},h=function(t,e){"abort"===e&&s.panels.stop(!1,!0),s._removeClass(n,"ui-tabs-loading"),a.removeAttr("aria-busy"),t===s.xhr&&delete s.xhr};this._isLocal(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(this._addClass(n,"ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,n){setTimeout(function(){a.html(t),s._trigger("load",i,r),h(n,e)},1)}).fail(function(t,e){setTimeout(function(){h(t,e)},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href").replace(/#.*$/,""),beforeSend:function(e,o){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:o},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}}),t.uiBackCompat!==!1&&t.widget("ui.tabs",t.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}}),t.ui.tabs,t.widget("ui.tooltip",{version:"1.12.1",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).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(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))},_removeDescribedBy:function(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=t("<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=t([])},_setOption:function(e,i){var s=this;this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s.element[0],e.close(n,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var e=t(this);return e.is("[title]")?e.data("ui-tooltip-title",e.attr("title")).removeAttr("title"):void 0}))},_enable:function(){this.disabledTitles.each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))}),this.disabledTitles=t([])},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._registerCloseHandlers(e,s),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;return"string"==typeof s||s.nodeType||s.jquery?this._open(e,t,s):(i=s.call(t[0],function(i){n._delay(function(){t.data("ui-tooltip-open")&&(e&&(e.type=o),this._open(e,t,i))})}),i&&this._open(e,t,i),void 0)},_open:function(e,i,s){function n(t){l.of=t,a.is(":hidden")||a.position(l)}var o,a,r,h,l=t.extend({},this.options.position);if(s){if(o=this._find(i))return o.tooltip.find(".ui-tooltip-content").html(s),void 0;i.is("[title]")&&(e&&"mouseover"===e.type?i.attr("title",""):i.removeAttr("title")),o=this._tooltip(i),a=o.tooltip,this._addDescribedBy(i,a.attr("id")),a.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),h=t("<div>").html(a.find(".ui-tooltip-content").html()),h.removeAttr("name").find("[name]").removeAttr("name"),h.removeAttr("id").find("[id]").removeAttr("id"),h.appendTo(this.liveRegion),this.options.track&&e&&/^mouse/.test(e.type)?(this._on(this.document,{mousemove:n}),n(e)):a.position(t.extend({of:i},this.options.position)),a.hide(),this._show(a,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(r=this.delayedShow=setInterval(function(){a.is(":visible")&&(n(l.of),clearInterval(r))},t.fx.interval)),this._trigger("open",e,{tooltip:a})}},_registerCloseHandlers:function(e,i){var s={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var s=t.Event(e);s.currentTarget=i[0],this.close(s,!0)}}};i[0]!==this.element[0]&&(s.remove=function(){this._removeTooltip(this._find(i).tooltip)}),e&&"mouseover"!==e.type||(s.mouseleave="close"),e&&"focusin"!==e.type||(s.focusout="close"),this._on(!0,i,s)},close:function(e){var i,s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);return o?(i=o.tooltip,o.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),o.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),o.closing=!0,this._trigger("close",e,{tooltip:i}),o.hiding||(o.closing=!1)),void 0):(n.removeData("ui-tooltip-open"),void 0)},_tooltip:function(e){var i=t("<div>").attr("role","tooltip"),s=t("<div>").appendTo(i),n=i.uniqueId().attr("id");return this._addClass(s,"ui-tooltip-content"),this._addClass(i,"ui-tooltip","ui-widget ui-widget-content"),i.appendTo(this._appendTo(e)),this.tooltips[n]={element:e,tooltip:i}},_find:function(t){var e=t.data("ui-tooltip-id");return e?this.tooltips[e]:null},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){var e=t.closest(".ui-front, dialog");return e.length||(e=this.document[0].body),e},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur"),o=s.element;n.target=n.currentTarget=o[0],e.close(n,!0),t("#"+i).remove(),o.data("ui-tooltip-title")&&(o.attr("title")||o.attr("title",o.data("ui-tooltip-title")),o.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),t.uiBackCompat!==!1&&t.widget("ui.tooltip",t.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}}),t.ui.tooltip});;
// http://plugins.jquery.com/project/URLEncode
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});


;
/*!
 * Globalize
 *
 * http://github.com/jquery/globalize
 *
 * Copyright Software Freedom Conservancy, Inc.
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */

(function (window, undefined) {

    var Globalize,
        // private variables
        regexHex,
        regexInfinity,
        regexParseFloat,
        regexTrim,
        // private JavaScript utility functions
        arrayIndexOf,
        endsWith,
        extend,
        isArray,
        isFunction,
        isObject,
        startsWith,
        trim,
        truncate,
        zeroPad,
        // private Globalization utility functions
        appendPreOrPostMatch,
        expandFormat,
        formatDate,
        formatNumber,
        getTokenRegExp,
        getEra,
        getEraYear,
        parseExact,
        parseNegativePattern;

    // Global variable (Globalize) or CommonJS module (globalize)
    Globalize = function (cultureSelector) {
        return new Globalize.prototype.init(cultureSelector);
    };

    if (typeof require !== "undefined" &&
        typeof exports !== "undefined" &&
        typeof module !== "undefined") {
        // Assume CommonJS
        module.exports = Globalize;
    } else {
        // Export as global variable
        window.Globalize = Globalize;
    }

    Globalize.cultures = {};

    Globalize.prototype = {
        constructor: Globalize,
        init: function (cultureSelector) {
            this.cultures = Globalize.cultures;
            this.cultureSelector = cultureSelector;

            return this;
        }
    };
    Globalize.prototype.init.prototype = Globalize.prototype;

    // 1. When defining a culture, all fields are required except the ones stated as optional.
    // 2. Each culture should have a ".calendars" object with at least one calendar named "standard"
    //    which serves as the default calendar in use by that culture.
    // 3. Each culture should have a ".calendar" object which is the current calendar being used,
    //    it may be dynamically changed at any time to one of the calendars in ".calendars".
    Globalize.cultures["default"] = {
        // A unique name for the culture in the form <language code>-<country/region code>
        name: "en",
        // the name of the culture in the english language
        englishName: "English",
        // the name of the culture in its own language
        nativeName: "English",
        // whether the culture uses right-to-left text
        isRTL: false,
        // "language" is used for so-called "specific" cultures.
        // For example, the culture "es-CL" means "Spanish, in Chili".
        // It represents the Spanish-speaking culture as it is in Chili,
        // which might have different formatting rules or even translations
        // than Spanish in Spain. A "neutral" culture is one that is not
        // specific to a region. For example, the culture "es" is the generic
        // Spanish culture, which may be a more generalized version of the language
        // that may or may not be what a specific culture expects.
        // For a specific culture like "es-CL", the "language" field refers to the
        // neutral, generic culture information for the language it is using.
        // This is not always a simple matter of the string before the dash.
        // For example, the "zh-Hans" culture is netural (Simplified Chinese).
        // And the "zh-SG" culture is Simplified Chinese in Singapore, whose lanugage
        // field is "zh-CHS", not "zh".
        // This field should be used to navigate from a specific culture to it's
        // more general, neutral culture. If a culture is already as general as it
        // can get, the language may refer to itself.
        language: "en",
        // numberFormat defines general number formatting rules, like the digits in
        // each grouping, the group separator, and how negative numbers are displayed.
        numberFormat: {
            // [negativePattern]
            // Note, numberFormat.pattern has no "positivePattern" unlike percent and currency,
            // but is still defined as an array for consistency with them.
            //   negativePattern: one of "(n)|-n|- n|n-|n -"
            pattern: ["-n"],
            // number of decimal places normally shown
            decimals: 2,
            // string that separates number groups, as in 1,000,000
            ",": ",",
            // string that separates a number from the fractional portion, as in 1.99
            ".": ".",
            // array of numbers indicating the size of each number group.
            // TODO: more detailed description and example
            groupSizes: [3],
            // symbol used for positive numbers
            "+": "+",
            // symbol used for negative numbers
            "-": "-",
            // symbol used for NaN (Not-A-Number)
            "NaN": "NaN",
            // symbol used for Negative Infinity
            negativeInfinity: "-Infinity",
            // symbol used for Positive Infinity
            positiveInfinity: "Infinity",
            percent: {
                // [negativePattern, positivePattern]
                //   negativePattern: one of "-n %|-n%|-%n|%-n|%n-|n-%|n%-|-% n|n %-|% n-|% -n|n- %"
                //   positivePattern: one of "n %|n%|%n|% n"
                pattern: ["-n %", "n %"],
                // number of decimal places normally shown
                decimals: 2,
                // array of numbers indicating the size of each number group.
                // TODO: more detailed description and example
                groupSizes: [3],
                // string that separates number groups, as in 1,000,000
                ",": ",",
                // string that separates a number from the fractional portion, as in 1.99
                ".": ".",
                // symbol used to represent a percentage
                symbol: "%"
            },
            currency: {
                // [negativePattern, positivePattern]
                //   negativePattern: one of "($n)|-$n|$-n|$n-|(n$)|-n$|n-$|n$-|-n $|-$ n|n $-|$ n-|$ -n|n- $|($ n)|(n $)"
                //   positivePattern: one of "$n|n$|$ n|n $"
                pattern: ["($n)", "$n"],
                // number of decimal places normally shown
                decimals: 2,
                // array of numbers indicating the size of each number group.
                // TODO: more detailed description and example
                groupSizes: [3],
                // string that separates number groups, as in 1,000,000
                ",": ",",
                // string that separates a number from the fractional portion, as in 1.99
                ".": ".",
                // symbol used to represent currency
                symbol: "$"
            }
        },
        // calendars defines all the possible calendars used by this culture.
        // There should be at least one defined with name "standard", and is the default
        // calendar used by the culture.
        // A calendar contains information about how dates are formatted, information about
        // the calendar's eras, a standard set of the date formats,
        // translations for day and month names, and if the calendar is not based on the Gregorian
        // calendar, conversion functions to and from the Gregorian calendar.
        calendars: {
            standard: {
                // name that identifies the type of calendar this is
                name: "Gregorian_USEnglish",
                // separator of parts of a date (e.g. "/" in 11/05/1955)
                "/": "/",
                // separator of parts of a time (e.g. ":" in 05:44 PM)
                ":": ":",
                // the first day of the week (0 = Sunday, 1 = Monday, etc)
                firstDay: 0,
                days: {
                    // full day names
                    names: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
                    // abbreviated day names
                    namesAbbr: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
                    // shortest day names
                    namesShort: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
                },
                months: {
                    // full month names (13 months for lunar calendards -- 13th month should be "" if not lunar)
                    names: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ""],
                    // abbreviated month names
                    namesAbbr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""]
                },
                // AM and PM designators in one of these forms:
                // The usual view, and the upper and lower case versions
                //   [ standard, lowercase, uppercase ]
                // The culture does not use AM or PM (likely all standard date formats use 24 hour time)
                //   null
                AM: ["AM", "am", "AM"],
                PM: ["PM", "pm", "PM"],
                eras: [
                    // eras in reverse chronological order.
                    // name: the name of the era in this culture (e.g. A.D., C.E.)
                    // start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era.
                    // offset: offset in years from gregorian calendar
                    {
                        "name": "A.D.",
                        "start": null,
                        "offset": 0
                    }
                ],
                // when a two digit year is given, it will never be parsed as a four digit
                // year greater than this year (in the appropriate era for the culture)
                // Set it as a full year (e.g. 2029) or use an offset format starting from
                // the current year: "+19" would correspond to 2029 if the current year 2010.
                twoDigitYearMax: 2029,
                // set of predefined date and time patterns used by the culture
                // these represent the format someone in this culture would expect
                // to see given the portions of the date that are shown.
                patterns: {
                    // short date pattern
                    d: "M/d/yyyy",
                    // long date pattern
                    D: "dddd, MMMM dd, yyyy",
                    // short time pattern
                    t: "h:mm tt",
                    // long time pattern
                    T: "h:mm:ss tt",
                    // long date, short time pattern
                    f: "dddd, MMMM dd, yyyy h:mm tt",
                    // long date, long time pattern
                    F: "dddd, MMMM dd, yyyy h:mm:ss tt",
                    // month/day pattern
                    M: "MMMM dd",
                    // month/year pattern
                    Y: "yyyy MMMM",
                    // S is a sortable format that does not vary by culture
                    S: "yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss"
                }
                // optional fields for each calendar:
                /*
                monthsGenitive:
                    Same as months but used when the day preceeds the month.
                    Omit if the culture has no genitive distinction in month names.
                    For an explaination of genitive months, see http://blogs.msdn.com/michkap/archive/2004/12/25/332259.aspx
                convert:
                    Allows for the support of non-gregorian based calendars. This convert object is used to
                    to convert a date to and from a gregorian calendar date to handle parsing and formatting.
                    The two functions:
                        fromGregorian( date )
                            Given the date as a parameter, return an array with parts [ year, month, day ]
                            corresponding to the non-gregorian based year, month, and day for the calendar.
                        toGregorian( year, month, day )
                            Given the non-gregorian year, month, and day, return a new Date() object
                            set to the corresponding date in the gregorian calendar.
                */
            }
        },
        // For localized strings
        messages: {}
    };

    Globalize.cultures["default"].calendar = Globalize.cultures["default"].calendars.standard;

    Globalize.cultures.en = Globalize.cultures["default"];

    Globalize.cultureSelector = "en";

    //
    // private variables
    //

    regexHex = /^0x[a-f0-9]+$/i;
    regexInfinity = /^[+\-]?infinity$/i;
    regexParseFloat = /^[+\-]?\d*\.?\d*(e[+\-]?\d+)?$/;
    regexTrim = /^\s+|\s+$/g;

    //
    // private JavaScript utility functions
    //

    arrayIndexOf = function (array, item) {
        if (array.indexOf) {
            return array.indexOf(item);
        }
        for (var i = 0, length = array.length; i < length; i++) {
            if (array[i] === item) {
                return i;
            }
        }
        return -1;
    };

    endsWith = function (value, pattern) {
        return value.substr(value.length - pattern.length) === pattern;
    };

    extend = function () {
        var options, name, src, copy, copyIsArray, clone,
            target = arguments[0] || {},
            i = 1,
            length = arguments.length,
            deep = false;

        // Handle a deep copy situation
        if (typeof target === "boolean") {
            deep = target;
            target = arguments[1] || {};
            // skip the boolean and the target
            i = 2;
        }

        // Handle case when target is a string or something (possible in deep copy)
        if (typeof target !== "object" && !isFunction(target)) {
            target = {};
        }

        for (; i < length; i++) {
            // Only deal with non-null/undefined values
            if ((options = arguments[i]) != null) {
                // Extend the base object
                for (name in options) {
                    src = target[name];
                    copy = options[name];

                    // Prevent never-ending loop
                    if (target === copy) {
                        continue;
                    }

                    // Recurse if we're merging plain objects or arrays
                    if (deep && copy && (isObject(copy) || (copyIsArray = isArray(copy)))) {
                        if (copyIsArray) {
                            copyIsArray = false;
                            clone = src && isArray(src) ? src : [];

                        } else {
                            clone = src && isObject(src) ? src : {};
                        }

                        // Never move original objects, clone them
                        target[name] = extend(deep, clone, copy);

                        // Don't bring in undefined values
                    } else if (copy !== undefined) {
                        target[name] = copy;
                    }
                }
            }
        }

        // Return the modified object
        return target;
    };

    isArray = Array.isArray || function (obj) {
        return Object.prototype.toString.call(obj) === "[object Array]";
    };

    isFunction = function (obj) {
        return Object.prototype.toString.call(obj) === "[object Function]";
    };

    isObject = function (obj) {
        return Object.prototype.toString.call(obj) === "[object Object]";
    };

    startsWith = function (value, pattern) {
        return value.indexOf(pattern) === 0;
    };

    trim = function (value) {
        return (value + "").replace(regexTrim, "");
    };

    truncate = function (value) {
        if (isNaN(value)) {
            return NaN;
        }
        return Math[value < 0 ? "ceil" : "floor"](value);
    };

    zeroPad = function (str, count, left) {
        var l;
        for (l = str.length; l < count; l += 1) {
            str = (left ? ("0" + str) : (str + "0"));
        }
        return str;
    };

    //
    // private Globalization utility functions
    //

    appendPreOrPostMatch = function (preMatch, strings) {
        // appends pre- and post- token match strings while removing escaped characters.
        // Returns a single quote count which is used to determine if the token occurs
        // in a string literal.
        var quoteCount = 0,
            escaped = false;
        for (var i = 0, il = preMatch.length; i < il; i++) {
            var c = preMatch.charAt(i);
            switch (c) {
                case "\'":
                    if (escaped) {
                        strings.push("\'");
                    }
                    else {
                        quoteCount++;
                    }
                    escaped = false;
                    break;
                case "\\":
                    if (escaped) {
                        strings.push("\\");
                    }
                    escaped = !escaped;
                    break;
                default:
                    strings.push(c);
                    escaped = false;
                    break;
            }
        }
        return quoteCount;
    };

    expandFormat = function (cal, format) {
        // expands unspecified or single character date formats into the full pattern.
        format = format || "F";
        var pattern,
            patterns = cal.patterns,
            len = format.length;
        if (len === 1) {
            pattern = patterns[format];
            if (!pattern) {
                throw "Invalid date format string \'" + format + "\'.";
            }
            format = pattern;
        }
        else if (len === 2 && format.charAt(0) === "%") {
            // %X escape format -- intended as a custom format string that is only one character, not a built-in format.
            format = format.charAt(1);
        }
        return format;
    };

    formatDate = function (value, format, culture) {
        var cal = culture.calendar,
            convert = cal.convert,
            ret;

        if (!format || !format.length || format === "i") {
            if (culture && culture.name.length) {
                if (convert) {
                    // non-gregorian calendar, so we cannot use built-in toLocaleString()
                    ret = formatDate(value, cal.patterns.F, culture);
                }
                else {
                    var eraDate = new Date(value.getTime()),
                        era = getEra(value, cal.eras);
                    eraDate.setFullYear(getEraYear(value, cal, era));
                    ret = eraDate.toLocaleString();
                }
            }
            else {
                ret = value.toString();
            }
            return ret;
        }

        var eras = cal.eras,
            sortable = format === "s";
        format = expandFormat(cal, format);

        // Start with an empty string
        ret = [];
        var hour,
            zeros = ["0", "00", "000"],
            foundDay,
            checkedDay,
            dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g,
            quoteCount = 0,
            tokenRegExp = getTokenRegExp(),
            converted;

        function padZeros(num, c) {
            var r, s = num + "";
            if (c > 1 && s.length < c) {
                r = (zeros[c - 2] + s);
                return r.substr(r.length - c, c);
            }
            else {
                r = s;
            }
            return r;
        }

        function hasDay() {
            if (foundDay || checkedDay) {
                return foundDay;
            }
            foundDay = dayPartRegExp.test(format);
            checkedDay = true;
            return foundDay;
        }

        function getPart(date, part) {
            if (converted) {
                return converted[part];
            }
            switch (part) {
                case 0:
                    return date.getFullYear();
                case 1:
                    return date.getMonth();
                case 2:
                    return date.getDate();
                default:
                    throw "Invalid part value " + part;
            }
        }

        if (!sortable && convert) {
            converted = convert.fromGregorian(value);
        }

        for (; ;) {
            // Save the current index
            var index = tokenRegExp.lastIndex,
                // Look for the next pattern
                ar = tokenRegExp.exec(format);

            // Append the text before the pattern (or the end of the string if not found)
            var preMatch = format.slice(index, ar ? ar.index : format.length);
            quoteCount += appendPreOrPostMatch(preMatch, ret);

            if (!ar) {
                break;
            }

            // do not replace any matches that occur inside a string literal.
            if (quoteCount % 2) {
                ret.push(ar[0]);
                continue;
            }

            var current = ar[0],
                clength = current.length;

            switch (current) {
                case "ddd":
                    //Day of the week, as a three-letter abbreviation
                case "dddd":
                    // Day of the week, using the full name
                    var names = (clength === 3) ? cal.days.namesAbbr : cal.days.names;
                    ret.push(names[value.getDay()]);
                    break;
                case "d":
                    // Day of month, without leading zero for single-digit days
                case "dd":
                    // Day of month, with leading zero for single-digit days
                    foundDay = true;
                    ret.push(
                        padZeros(getPart(value, 2), clength)
                    );
                    break;
                case "MMM":
                    // Month, as a three-letter abbreviation
                case "MMMM":
                    // Month, using the full name
                    var part = getPart(value, 1);
                    ret.push(
                        (cal.monthsGenitive && hasDay()) ?
                        (cal.monthsGenitive[clength === 3 ? "namesAbbr" : "names"][part]) :
                        (cal.months[clength === 3 ? "namesAbbr" : "names"][part])
                    );
                    break;
                case "M":
                    // Month, as digits, with no leading zero for single-digit months
                case "MM":
                    // Month, as digits, with leading zero for single-digit months
                    ret.push(
                        padZeros(getPart(value, 1) + 1, clength)
                    );
                    break;
                case "y":
                    // Year, as two digits, but with no leading zero for years less than 10
                case "yy":
                    // Year, as two digits, with leading zero for years less than 10
                case "yyyy":
                    // Year represented by four full digits
                    part = converted ? converted[0] : getEraYear(value, cal, getEra(value, eras), sortable);
                    if (clength < 4) {
                        part = part % 100;
                    }
                    ret.push(
                        padZeros(part, clength)
                    );
                    break;
                case "h":
                    // Hours with no leading zero for single-digit hours, using 12-hour clock
                case "hh":
                    // Hours with leading zero for single-digit hours, using 12-hour clock
                    hour = value.getHours() % 12;
                    if (hour === 0) hour = 12;
                    ret.push(
                        padZeros(hour, clength)
                    );
                    break;
                case "H":
                    // Hours with no leading zero for single-digit hours, using 24-hour clock
                case "HH":
                    // Hours with leading zero for single-digit hours, using 24-hour clock
                    ret.push(
                        padZeros(value.getHours(), clength)
                    );
                    break;
                case "m":
                    // Minutes with no leading zero for single-digit minutes
                case "mm":
                    // Minutes with leading zero for single-digit minutes
                    ret.push(
                        padZeros(value.getMinutes(), clength)
                    );
                    break;
                case "s":
                    // Seconds with no leading zero for single-digit seconds
                case "ss":
                    // Seconds with leading zero for single-digit seconds
                    ret.push(
                        padZeros(value.getSeconds(), clength)
                    );
                    break;
                case "t":
                    // One character am/pm indicator ("a" or "p")
                case "tt":
                    // Multicharacter am/pm indicator
                    part = value.getHours() < 12 ? (cal.AM ? cal.AM[0] : " ") : (cal.PM ? cal.PM[0] : " ");
                    ret.push(clength === 1 ? part.charAt(0) : part);
                    break;
                case "f":
                    // Deciseconds
                case "ff":
                    // Centiseconds
                case "fff":
                    // Milliseconds
                    ret.push(
                        padZeros(value.getMilliseconds(), 3).substr(0, clength)
                    );
                    break;
                case "z":
                    // Time zone offset, no leading zero
                case "zz":
                    // Time zone offset with leading zero
                    hour = value.getTimezoneOffset() / 60;
                    ret.push(
                        (hour <= 0 ? "+" : "-") + padZeros(Math.floor(Math.abs(hour)), clength)
                    );
                    break;
                case "zzz":
                    // Time zone offset with leading zero
                    hour = value.getTimezoneOffset() / 60;
                    ret.push(
                        (hour <= 0 ? "+" : "-") + padZeros(Math.floor(Math.abs(hour)), 2) +
                        // Hard coded ":" separator, rather than using cal.TimeSeparator
                        // Repeated here for consistency, plus ":" was already assumed in date parsing.
                        ":" + padZeros(Math.abs(value.getTimezoneOffset() % 60), 2)
                    );
                    break;
                case "g":
                case "gg":
                    if (cal.eras) {
                        ret.push(
                            cal.eras[getEra(value, eras)].name
                        );
                    }
                    break;
                case "/":
                    ret.push(cal["/"]);
                    break;
                default:
                    throw "Invalid date format pattern \'" + current + "\'.";
            }
        }
        return ret.join("");
    };

    // formatNumber
    (function () {
        var expandNumber;

        expandNumber = function (number, precision, formatInfo) {
            var groupSizes = formatInfo.groupSizes,
                curSize = groupSizes[0],
                curGroupIndex = 1,
                factor = Math.pow(10, precision),
                rounded = Math.round(number * factor) / factor;

            if (!isFinite(rounded)) {
                rounded = number;
            }
            number = rounded;

            var numberString = number + "",
                right = "",
                split = numberString.split(/e/i),
                exponent = split.length > 1 ? parseInt(split[1], 10) : 0;
            numberString = split[0];
            split = numberString.split(".");
            numberString = split[0];
            right = split.length > 1 ? split[1] : "";

            if (exponent > 0) {
                right = zeroPad(right, exponent, false);
                numberString += right.slice(0, exponent);
                right = right.substr(exponent);
            }
            else if (exponent < 0) {
                exponent = -exponent;
                numberString = zeroPad(numberString, exponent + 1, true);
                right = numberString.slice(-exponent, numberString.length) + right;
                numberString = numberString.slice(0, -exponent);
            }

            if (precision > 0) {
                right = formatInfo["."] +
                    ((right.length > precision) ? right.slice(0, precision) : zeroPad(right, precision));
            }
            else {
                right = "";
            }

            var stringIndex = numberString.length - 1,
                sep = formatInfo[","],
                ret = "";

            while (stringIndex >= 0) {
                if (curSize === 0 || curSize > stringIndex) {
                    return numberString.slice(0, stringIndex + 1) + (ret.length ? (sep + ret + right) : right);
                }
                ret = numberString.slice(stringIndex - curSize + 1, stringIndex + 1) + (ret.length ? (sep + ret) : "");

                stringIndex -= curSize;

                if (curGroupIndex < groupSizes.length) {
                    curSize = groupSizes[curGroupIndex];
                    curGroupIndex++;
                }
            }

            return numberString.slice(0, stringIndex + 1) + sep + ret + right;
        };

        formatNumber = function (value, format, culture) {
            if (!isFinite(value)) {
                if (value === Infinity) {
                    return culture.numberFormat.positiveInfinity;
                }
                if (value === -Infinity) {
                    return culture.numberFormat.negativeInfinity;
                }
                return culture.numberFormat.NaN;
            }
            if (!format || format === "i") {
                return culture.name.length ? value.toLocaleString() : value.toString();
            }
            format = format || "D";

            var nf = culture.numberFormat,
                number = Math.abs(value),
                precision = -1,
                pattern;
            if (format.length > 1) precision = parseInt(format.slice(1), 10);

            var current = format.charAt(0).toUpperCase(),
                formatInfo;

            switch (current) {
                case "D":
                    pattern = "n";
                    number = truncate(number);
                    if (precision !== -1) {
                        number = zeroPad("" + number, precision, true);
                    }
                    if (value < 0) number = "-" + number;
                    break;
                case "N":
                    formatInfo = nf;
                    /* falls through */
                case "C":
                    formatInfo = formatInfo || nf.currency;
                    /* falls through */
                case "P":
                    formatInfo = formatInfo || nf.percent;
                    pattern = value < 0 ? formatInfo.pattern[0] : (formatInfo.pattern[1] || "n");
                    if (precision === -1) precision = formatInfo.decimals;
                    number = expandNumber(number * (current === "P" ? 100 : 1), precision, formatInfo);
                    break;
                default:
                    throw "Bad number format specifier: " + current;
            }

            var patternParts = /n|\$|-|%/g,
                ret = "";
            for (; ;) {
                var index = patternParts.lastIndex,
                    ar = patternParts.exec(pattern);

                ret += pattern.slice(index, ar ? ar.index : pattern.length);

                if (!ar) {
                    break;
                }

                switch (ar[0]) {
                    case "n":
                        ret += number;
                        break;
                    case "$":
                        ret += nf.currency.symbol;
                        break;
                    case "-":
                        // don't make 0 negative
                        if (/[1-9]/.test(number)) {
                            ret += nf["-"];
                        }
                        break;
                    case "%":
                        ret += nf.percent.symbol;
                        break;
                }
            }

            return ret;
        };

    }());

    getTokenRegExp = function () {
        // regular expression for matching date and time tokens in format strings.
        return (/\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g);
    };

    getEra = function (date, eras) {
        if (!eras) return 0;
        var start, ticks = date.getTime();
        for (var i = 0, l = eras.length; i < l; i++) {
            start = eras[i].start;
            if (start === null || ticks >= start) {
                return i;
            }
        }
        return 0;
    };

    getEraYear = function (date, cal, era, sortable) {
        var year = date.getFullYear();
        if (!sortable && cal.eras) {
            // convert normal gregorian year to era-shifted gregorian
            // year by subtracting the era offset
            year -= cal.eras[era].offset;
        }
        return year;
    };

    // parseExact
    (function () {
        var expandYear,
            getDayIndex,
            getMonthIndex,
            getParseRegExp,
            outOfRange,
            toUpper,
            toUpperArray;

        expandYear = function (cal, year) {
            // expands 2-digit year into 4 digits.
            if (year < 100) {
                var now = new Date(),
                    era = getEra(now),
                    curr = getEraYear(now, cal, era),
                    twoDigitYearMax = cal.twoDigitYearMax;
                twoDigitYearMax = typeof twoDigitYearMax === "string" ? new Date().getFullYear() % 100 + parseInt(twoDigitYearMax, 10) : twoDigitYearMax;
                year += curr - (curr % 100);
                if (year > twoDigitYearMax) {
                    year -= 100;
                }
            }
            return year;
        };

        getDayIndex = function (cal, value, abbr) {
            var ret,
                days = cal.days,
                upperDays = cal._upperDays;
            if (!upperDays) {
                cal._upperDays = upperDays = [
                    toUpperArray(days.names),
                    toUpperArray(days.namesAbbr),
                    toUpperArray(days.namesShort)
                ];
            }
            value = toUpper(value);
            if (abbr) {
                ret = arrayIndexOf(upperDays[1], value);
                if (ret === -1) {
                    ret = arrayIndexOf(upperDays[2], value);
                }
            }
            else {
                ret = arrayIndexOf(upperDays[0], value);
            }
            return ret;
        };

        getMonthIndex = function (cal, value, abbr) {
            var months = cal.months,
                monthsGen = cal.monthsGenitive || cal.months,
                upperMonths = cal._upperMonths,
                upperMonthsGen = cal._upperMonthsGen;
            if (!upperMonths) {
                cal._upperMonths = upperMonths = [
                    toUpperArray(months.names),
                    toUpperArray(months.namesAbbr)
                ];
                cal._upperMonthsGen = upperMonthsGen = [
                    toUpperArray(monthsGen.names),
                    toUpperArray(monthsGen.namesAbbr)
                ];
            }
            value = toUpper(value);
            var i = arrayIndexOf(abbr ? upperMonths[1] : upperMonths[0], value);
            if (i < 0) {
                i = arrayIndexOf(abbr ? upperMonthsGen[1] : upperMonthsGen[0], value);
            }
            return i;
        };

        getParseRegExp = function (cal, format) {
            // converts a format string into a regular expression with groups that
            // can be used to extract date fields from a date string.
            // check for a cached parse regex.
            var re = cal._parseRegExp;
            if (!re) {
                cal._parseRegExp = re = {};
            }
            else {
                var reFormat = re[format];
                if (reFormat) {
                    return reFormat;
                }
            }

            // expand single digit formats, then escape regular expression characters.
            var expFormat = expandFormat(cal, format).replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1"),
                regexp = ["^"],
                groups = [],
                index = 0,
                quoteCount = 0,
                tokenRegExp = getTokenRegExp(),
                match;

            // iterate through each date token found.
            while ((match = tokenRegExp.exec(expFormat)) !== null) {
                var preMatch = expFormat.slice(index, match.index);
                index = tokenRegExp.lastIndex;

                // don't replace any matches that occur inside a string literal.
                quoteCount += appendPreOrPostMatch(preMatch, regexp);
                if (quoteCount % 2) {
                    regexp.push(match[0]);
                    continue;
                }

                // add a regex group for the token.
                var m = match[0],
                    len = m.length,
                    add;
                switch (m) {
                    case "dddd": case "ddd":
                    case "MMMM": case "MMM":
                    case "gg": case "g":
                        add = "(\\D+)";
                        break;
                    case "tt": case "t":
                        add = "(\\D*)";
                        break;
                    case "yyyy":
                    case "fff":
                    case "ff":
                    case "f":
                        add = "(\\d{" + len + "})";
                        break;
                    case "dd": case "d":
                    case "MM": case "M":
                    case "yy": case "y":
                    case "HH": case "H":
                    case "hh": case "h":
                    case "mm": case "m":
                    case "ss": case "s":
                        add = "(\\d\\d?)";
                        break;
                    case "zzz":
                        add = "([+-]?\\d\\d?:\\d{2})";
                        break;
                    case "zz": case "z":
                        add = "([+-]?\\d\\d?)";
                        break;
                    case "/":
                        add = "(\\/)";
                        break;
                    default:
                        throw "Invalid date format pattern \'" + m + "\'.";
                }
                if (add) {
                    regexp.push(add);
                }
                groups.push(match[0]);
            }
            appendPreOrPostMatch(expFormat.slice(index), regexp);
            regexp.push("$");

            // allow whitespace to differ when matching formats.
            var regexpStr = regexp.join("").replace(/\s+/g, "\\s+"),
                parseRegExp = { "regExp": regexpStr, "groups": groups };

            // cache the regex for this format.
            return re[format] = parseRegExp;
        };

        outOfRange = function (value, low, high) {
            return value < low || value > high;
        };

        toUpper = function (value) {
            // "he-IL" has non-breaking space in weekday names.
            return value.split("\u00A0").join(" ").toUpperCase();
        };

        toUpperArray = function (arr) {
            var results = [];
            for (var i = 0, l = arr.length; i < l; i++) {
                results[i] = toUpper(arr[i]);
            }
            return results;
        };

        parseExact = function (value, format, culture) {
            // try to parse the date string by matching against the format string
            // while using the specified culture for date field names.
            value = trim(value);
            var cal = culture.calendar,
                // convert date formats into regular expressions with groupings.
                // use the regexp to determine the input format and extract the date fields.
                parseInfo = getParseRegExp(cal, format),
                match = new RegExp(parseInfo.regExp).exec(value);
            if (match === null) {
                return null;
            }
            // found a date format that matches the input.
            var groups = parseInfo.groups,
                era = null, year = null, month = null, date = null, weekDay = null,
                hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null,
                pmHour = false;
            // iterate the format groups to extract and set the date fields.
            for (var j = 0, jl = groups.length; j < jl; j++) {
                var matchGroup = match[j + 1];
                if (matchGroup) {
                    var current = groups[j],
                        clength = current.length,
                        matchInt = parseInt(matchGroup, 10);
                    switch (current) {
                        case "dd": case "d":
                            // Day of month.
                            date = matchInt;
                            // check that date is generally in valid range, also checking overflow below.
                            if (outOfRange(date, 1, 31)) return null;
                            break;
                        case "MMM": case "MMMM":
                            month = getMonthIndex(cal, matchGroup, clength === 3);
                            if (outOfRange(month, 0, 11)) return null;
                            break;
                        case "M": case "MM":
                            // Month.
                            month = matchInt - 1;
                            if (outOfRange(month, 0, 11)) return null;
                            break;
                        case "y": case "yy":
                        case "yyyy":
                            year = clength < 4 ? expandYear(cal, matchInt) : matchInt;
                            if (outOfRange(year, 0, 9999)) return null;
                            break;
                        case "h": case "hh":
                            // Hours (12-hour clock).
                            hour = matchInt;
                            if (hour === 12) hour = 0;
                            if (outOfRange(hour, 0, 11)) return null;
                            break;
                        case "H": case "HH":
                            // Hours (24-hour clock).
                            hour = matchInt;
                            if (outOfRange(hour, 0, 23)) return null;
                            break;
                        case "m": case "mm":
                            // Minutes.
                            min = matchInt;
                            if (outOfRange(min, 0, 59)) return null;
                            break;
                        case "s": case "ss":
                            // Seconds.
                            sec = matchInt;
                            if (outOfRange(sec, 0, 59)) return null;
                            break;
                        case "tt": case "t":
                            // AM/PM designator.
                            // see if it is standard, upper, or lower case PM. If not, ensure it is at least one of
                            // the AM tokens. If not, fail the parse for this format.
                            pmHour = cal.PM && (matchGroup === cal.PM[0] || matchGroup === cal.PM[1] || matchGroup === cal.PM[2]);
                            if (
                                !pmHour && (
                                    !cal.AM || (matchGroup !== cal.AM[0] && matchGroup !== cal.AM[1] && matchGroup !== cal.AM[2])
                                )
                            ) return null;
                            break;
                        case "f":
                            // Deciseconds.
                        case "ff":
                            // Centiseconds.
                        case "fff":
                            // Milliseconds.
                            msec = matchInt * Math.pow(10, 3 - clength);
                            if (outOfRange(msec, 0, 999)) return null;
                            break;
                        case "ddd":
                            // Day of week.
                        case "dddd":
                            // Day of week.
                            weekDay = getDayIndex(cal, matchGroup, clength === 3);
                            if (outOfRange(weekDay, 0, 6)) return null;
                            break;
                        case "zzz":
                            // Time zone offset in +/- hours:min.
                            var offsets = matchGroup.split(/:/);
                            if (offsets.length !== 2) return null;
                            hourOffset = parseInt(offsets[0], 10);
                            if (outOfRange(hourOffset, -12, 13)) return null;
                            var minOffset = parseInt(offsets[1], 10);
                            if (outOfRange(minOffset, 0, 59)) return null;
                            tzMinOffset = (hourOffset * 60) + (startsWith(matchGroup, "-") ? -minOffset : minOffset);
                            break;
                        case "z": case "zz":
                            // Time zone offset in +/- hours.
                            hourOffset = matchInt;
                            if (outOfRange(hourOffset, -12, 13)) return null;
                            tzMinOffset = hourOffset * 60;
                            break;
                        case "g": case "gg":
                            var eraName = matchGroup;
                            if (!eraName || !cal.eras) return null;
                            eraName = trim(eraName.toLowerCase());
                            for (var i = 0, l = cal.eras.length; i < l; i++) {
                                if (eraName === cal.eras[i].name.toLowerCase()) {
                                    era = i;
                                    break;
                                }
                            }
                            // could not find an era with that name
                            if (era === null) return null;
                            break;
                    }
                }
            }
            var result = new Date(), defaultYear, convert = cal.convert;
            defaultYear = convert ? convert.fromGregorian(result)[0] : result.getFullYear();
            if (year === null) {
                year = defaultYear;
            }
            else if (cal.eras) {
                // year must be shifted to normal gregorian year
                // but not if year was not specified, its already normal gregorian
                // per the main if clause above.
                year += cal.eras[(era || 0)].offset;
            }
            // set default day and month to 1 and January, so if unspecified, these are the defaults
            // instead of the current day/month.
            if (month === null) {
                month = 0;
            }
            if (date === null) {
                date = 1;
            }
            // now have year, month, and date, but in the culture's calendar.
            // convert to gregorian if necessary
            if (convert) {
                result = convert.toGregorian(year, month, date);
                // conversion failed, must be an invalid match
                if (result === null) return null;
            }
            else {
                // have to set year, month and date together to avoid overflow based on current date.
                result.setFullYear(year, month, date);
                // check to see if date overflowed for specified month (only checked 1-31 above).
                if (result.getDate() !== date) return null;
                // invalid day of week.
                if (weekDay !== null && result.getDay() !== weekDay) {
                    return null;
                }
            }
            // if pm designator token was found make sure the hours fit the 24-hour clock.
            if (pmHour && hour < 12) {
                hour += 12;
            }
            result.setHours(hour, min, sec, msec);
            if (tzMinOffset !== null) {
                // adjust timezone to utc before applying local offset.
                var adjustedMin = result.getMinutes() - (tzMinOffset + result.getTimezoneOffset());
                // Safari limits hours and minutes to the range of -127 to 127.  We need to use setHours
                // to ensure both these fields will not exceed this range.	adjustedMin will range
                // somewhere between -1440 and 1500, so we only need to split this into hours.
                result.setHours(result.getHours() + parseInt(adjustedMin / 60, 10), adjustedMin % 60);
            }
            return result;
        };
    }());

    parseNegativePattern = function (value, nf, negativePattern) {
        var neg = nf["-"],
            pos = nf["+"],
            ret;
        switch (negativePattern) {
            case "n -":
                neg = " " + neg;
                pos = " " + pos;
                /* falls through */
            case "n-":
                if (endsWith(value, neg)) {
                    ret = ["-", value.substr(0, value.length - neg.length)];
                }
                else if (endsWith(value, pos)) {
                    ret = ["+", value.substr(0, value.length - pos.length)];
                }
                break;
            case "- n":
                neg += " ";
                pos += " ";
                /* falls through */
            case "-n":
                if (startsWith(value, neg)) {
                    ret = ["-", value.substr(neg.length)];
                }
                else if (startsWith(value, pos)) {
                    ret = ["+", value.substr(pos.length)];
                }
                break;
            case "(n)":
                if (startsWith(value, "(") && endsWith(value, ")")) {
                    ret = ["-", value.substr(1, value.length - 2)];
                }
                break;
        }
        return ret || ["", value];
    };

    //
    // public instance functions
    //

    Globalize.prototype.findClosestCulture = function (cultureSelector) {
        return Globalize.findClosestCulture.call(this, cultureSelector);
    };

    Globalize.prototype.format = function (value, format, cultureSelector) {
        return Globalize.format.call(this, value, format, cultureSelector);
    };

    Globalize.prototype.localize = function (key, cultureSelector) {
        return Globalize.localize.call(this, key, cultureSelector);
    };

    Globalize.prototype.parseInt = function (value, radix, cultureSelector) {
        return Globalize.parseInt.call(this, value, radix, cultureSelector);
    };

    Globalize.prototype.parseFloat = function (value, radix, cultureSelector) {
        return Globalize.parseFloat.call(this, value, radix, cultureSelector);
    };

    Globalize.prototype.culture = function (cultureSelector) {
        return Globalize.culture.call(this, cultureSelector);
    };

    //
    // public singleton functions
    //

    Globalize.addCultureInfo = function (cultureName, baseCultureName, info) {

        var base = {},
            isNew = false;

        if (typeof cultureName !== "string") {
            // cultureName argument is optional string. If not specified, assume info is first
            // and only argument. Specified info deep-extends current culture.
            info = cultureName;
            cultureName = this.culture().name;
            base = this.cultures[cultureName];
        } else if (typeof baseCultureName !== "string") {
            // baseCultureName argument is optional string. If not specified, assume info is second
            // argument. Specified info deep-extends specified culture.
            // If specified culture does not exist, create by deep-extending default
            info = baseCultureName;
            isNew = (this.cultures[cultureName] == null);
            base = this.cultures[cultureName] || this.cultures["default"];
        } else {
            // cultureName and baseCultureName specified. Assume a new culture is being created
            // by deep-extending an specified base culture
            isNew = true;
            base = this.cultures[baseCultureName];
        }

        this.cultures[cultureName] = extend(true, {},
            base,
            info
        );
        // Make the standard calendar the current culture if it's a new culture
        if (isNew) {
            this.cultures[cultureName].calendar = this.cultures[cultureName].calendars.standard;
        }
    };

    Globalize.findClosestCulture = function (name) {
        var match;
        if (!name) {
            return this.findClosestCulture(this.cultureSelector) || this.cultures["default"];
        }
        if (typeof name === "string") {
            name = name.split(",");
        }
        if (isArray(name)) {
            var lang,
                cultures = this.cultures,
                list = name,
                i, l = list.length,
                prioritized = [];
            for (i = 0; i < l; i++) {
                name = trim(list[i]);
                var pri, parts = name.split(";");
                lang = trim(parts[0]);
                if (parts.length === 1) {
                    pri = 1;
                }
                else {
                    name = trim(parts[1]);
                    if (name.indexOf("q=") === 0) {
                        name = name.substr(2);
                        pri = parseFloat(name);
                        pri = isNaN(pri) ? 0 : pri;
                    }
                    else {
                        pri = 1;
                    }
                }
                prioritized.push({ lang: lang, pri: pri });
            }
            prioritized.sort(function (a, b) {
                if (a.pri < b.pri) {
                    return 1;
                } else if (a.pri > b.pri) {
                    return -1;
                }
                return 0;
            });
            // exact match
            for (i = 0; i < l; i++) {
                lang = prioritized[i].lang;
                match = cultures[lang];
                if (match) {
                    return match;
                }
            }

            // neutral language match
            for (i = 0; i < l; i++) {
                lang = prioritized[i].lang;
                do {
                    var index = lang.lastIndexOf("-");
                    if (index === -1) {
                        break;
                    }
                    // strip off the last part. e.g. en-US => en
                    lang = lang.substr(0, index);
                    match = cultures[lang];
                    if (match) {
                        return match;
                    }
                }
                while (1);
            }

            // last resort: match first culture using that language
            for (i = 0; i < l; i++) {
                lang = prioritized[i].lang;
                for (var cultureKey in cultures) {
                    var culture = cultures[cultureKey];
                    if (culture.language === lang) {
                        return culture;
                    }
                }
            }
        }
        else if (typeof name === "object") {
            return name;
        }
        return match || null;
    };

    Globalize.format = function (value, format, cultureSelector) {
        var culture = this.findClosestCulture(cultureSelector);
        if (value instanceof Date) {
            value = formatDate(value, format, culture);
        }
        else if (typeof value === "number") {
            value = formatNumber(value, format, culture);
        }
        return value;
    };

    Globalize.localize = function (key, cultureSelector) {
        return this.findClosestCulture(cultureSelector).messages[key] ||
            this.cultures["default"].messages[key];
    };

    Globalize.parseDate = function (value, formats, culture) {
        culture = this.findClosestCulture(culture);

        var date, prop, patterns;
        if (formats) {
            if (typeof formats === "string") {
                formats = [formats];
            }
            if (formats.length) {
                for (var i = 0, l = formats.length; i < l; i++) {
                    var format = formats[i];
                    if (format) {
                        date = parseExact(value, format, culture);
                        if (date) {
                            break;
                        }
                    }
                }
            }
        } else {
            patterns = culture.calendar.patterns;
            for (prop in patterns) {
                date = parseExact(value, patterns[prop], culture);
                if (date) {
                    break;
                }
            }
        }

        return date || null;
    };

    Globalize.parseInt = function (value, radix, cultureSelector) {
        return truncate(Globalize.parseFloat(value, radix, cultureSelector));
    };

    Globalize.parseFloat = function (value, radix, cultureSelector) {
        // radix argument is optional
        if (typeof radix !== "number") {
            cultureSelector = radix;
            radix = 10;
        }

        var culture = this.findClosestCulture(cultureSelector);
        var ret = NaN,
            nf = culture.numberFormat;

        if (value.indexOf(culture.numberFormat.currency.symbol) > -1) {
            // remove currency symbol
            value = value.replace(culture.numberFormat.currency.symbol, "");
            // replace decimal seperator
            value = value.replace(culture.numberFormat.currency["."], culture.numberFormat["."]);
        }

        //Remove percentage character from number string before parsing
        if (value.indexOf(culture.numberFormat.percent.symbol) > -1) {
            value = value.replace(culture.numberFormat.percent.symbol, "");
        }

        // remove spaces: leading, trailing and between - and number. Used for negative currency pt-BR
        value = value.replace(/ /g, "");

        // allow infinity or hexidecimal
        if (regexInfinity.test(value)) {
            ret = parseFloat(value);
        }
        else if (!radix && regexHex.test(value)) {
            ret = parseInt(value, 16);
        }
        else {

            // determine sign and number
            var signInfo = parseNegativePattern(value, nf, nf.pattern[0]),
                sign = signInfo[0],
                num = signInfo[1];

            // #44 - try parsing as "(n)"
            if (sign === "" && nf.pattern[0] !== "(n)") {
                signInfo = parseNegativePattern(value, nf, "(n)");
                sign = signInfo[0];
                num = signInfo[1];
            }

            // try parsing as "-n"
            if (sign === "" && nf.pattern[0] !== "-n") {
                signInfo = parseNegativePattern(value, nf, "-n");
                sign = signInfo[0];
                num = signInfo[1];
            }

            sign = sign || "+";

            // determine exponent and number
            var exponent,
                intAndFraction,
                exponentPos = num.indexOf("e");
            if (exponentPos < 0) exponentPos = num.indexOf("E");
            if (exponentPos < 0) {
                intAndFraction = num;
                exponent = null;
            }
            else {
                intAndFraction = num.substr(0, exponentPos);
                exponent = num.substr(exponentPos + 1);
            }
            // determine decimal position
            var integer,
                fraction,
                decSep = nf["."],
                decimalPos = intAndFraction.indexOf(decSep);
            if (decimalPos < 0) {
                integer = intAndFraction;
                fraction = null;
            }
            else {
                integer = intAndFraction.substr(0, decimalPos);
                fraction = intAndFraction.substr(decimalPos + decSep.length);
            }
            // handle groups (e.g. 1,000,000)
            var groupSep = nf[","];
            integer = integer.split(groupSep).join("");
            var altGroupSep = groupSep.replace(/\u00A0/g, " ");
            if (groupSep !== altGroupSep) {
                integer = integer.split(altGroupSep).join("");
            }
            // build a natively parsable number string
            var p = sign + integer;
            if (fraction !== null) {
                p += "." + fraction;
            }
            if (exponent !== null) {
                // exponent itself may have a number patternd
                var expSignInfo = parseNegativePattern(exponent, nf, "-n");
                p += "e" + (expSignInfo[0] || "+") + expSignInfo[1];
            }
            if (regexParseFloat.test(p)) {
                ret = parseFloat(p);
            }
        }
        return ret;
    };

    Globalize.culture = function (cultureSelector) {
        // setter
        if (typeof cultureSelector !== "undefined") {
            this.cultureSelector = cultureSelector;
        }
        // getter
        return this.findClosestCulture(cultureSelector) || this.cultures["default"];
    };

}(this));;
(function ($) {
	var 
	// Will speed up references to undefined, and allows munging its name.
        underfined;

	function addOption(select, text, value, selected) {
		/// Internal helper method for adding options to select elements
		selected = selected || false;
		var option = new Option(text, value, selected, selected);
		if ($.browser.msie) {
			select.add(option)
		} else {
			select.add(option, null);
		}
	}

	function addOption(select, text, value, selected, disabled) {
		/// Internal helper method for adding options to select elements
		selected = selected || false;
		disabled = disabled || false;
		var option = new Option(text, value, selected, selected);
		if (disabled)
			option.disabled = 'disabled';
		if ($.browser.msie) {
			select.add(option)
		} else {
			select.add(option, null);
		}
	}

	$.fn.addOption = function (text, value, selected) {
		///	<summary>
		///		Add an element to a select list.
		///	</summary>
		///	<returns type="jQuery" />
		///	<param name="text" type="String">
		///		Text to assign to new option.
		///	</param>  
		///	<param name="value" type="Object">
		///		Value to assign to new option.
		///	</param>
		///	<param name="selected" type="Boolean">
		///		Specifies that the element is selected.
		///	</param>
		return this.each(function () {
			if (this.tagName == 'SELECT') {
				addOption(this, text, value, selected);
			}
		});
	}


	$.fn.emptySelect = function () {
		///	<summary>
		///		Empties a select element of all options.
		///	</summary>
		///	<returns type="jQuery" />
		return this.each(function () {
			if (this.tagName == 'SELECT') {
				this.options.length = 0;
			}
		});
	}

	$.fn.loadSelect = function (object, empty) {
		///	<summary>
		///		Loads a select element with data.
		///	</summary>
		///	<returns type="jQuery" />
		///	<param name="object" type="Object|List">
		///		1: object - An object (Dictionary) object to retrieve key/value pairs.
		///		2: list - List of values
		///	</param>
		///	<param name="empty" type="Boolean">
		///		Empty the specified control prior to adding items.
		///	</param>
		empty = (empty == null) ? true : empty;
		return this.each(function () {
			if (this.tagName == 'SELECT') {
				if (empty) $(this).emptySelect();
				var name, i = 0, length = object.length;
				// Determine if we have a list or an object
				if (length === undefined) {
					// Iterate over object
					for (name in object) {
						addOption(this, name, object[name]);
					}
				} else {
					// Iterate over list
					for (var item = object[0]; i < length; item = object[++i]) {
					    if (item.Text || item.Value) {
					        addOption(this, item.Text, item.Value, null, item.Disabled);
					    }
					    else {
					        addOption(this, item, item);
					    }
					}
				}
			}
		});
	}

	$.fn.disable = function (state) {
		///	<summary>
		///		Disables form elements.
		///	</summary>
		///	<returns type="jQuery" />
		///	<param name="state" type="boolean">
		///		If true element will be disabled; default is true.
		///	</param>
		state = (state == null) ? true : state;
		return this.each(function () {
			if ($.inArray(this.tagName, ['INPUT', 'SELECT', 'TEXTAREA', 'BUTTON']) >= 0) {
				if (state) {
					$(this).attr({ 'disabled': 'disabled' });
				} else {
					$(this).removeAttr("disabled");
				}
			}
		});
	}

	$.fn.changeLoad = function (sourceUrl, targetElement, callback) {
		///	<summary>
		///		Adds an event to populate a different select element when this element changes.
		///	</summary>
		///	<returns type="jQuery" />
		///	<param name="sourceUrl" type="String">
		///		URI to fetch data about change from.
		///	</param>  
		///	<param name="targetElement" type="String|Element|jQueryResult">
		///		Element to populate when the change event is raised.
		///	</param>
		///	<param name="callback" type="Function">
		///		Function that returns data to be passed as part of the server callback.
		///	</param>
		return this.change(function () {
			var target = $(targetElement).disable();
			var nullText = target.attr("data-selectextras-nulltext");
			if (!nullText)
				nullText = "Select...";
			if ($(this).val() === "") {
				target.emptySelect().addOption(nullText, "")
                    .triggerHandler("change");
			} else {
				target.emptySelect().addOption("Loading...", "");

				$.post(sourceUrl, callback.apply(this), function (data) {
					target.emptySelect()
                        .addOption(nullText, "")
                        .loadSelect(data.d, false)
                        .disable(false)
                        .triggerHandler("change");
				}, "json");
			}
		});
	}

    /* $.fn.loadSelectSimple = function (object, empty) {
    ///	<summary>
    ///		Loads a select element with data.
    ///	</summary>
    ///	<returns type="jQuery" />
    ///	<param name="object" type="Object|List">
    ///		1: object - An object (Dictionary) object to retrieve key/value pairs.
    ///		2: list - List of values
    ///	</param>
    ///	<param name="empty" type="Boolean">
    ///		Empty the specified control prior to adding items.
    ///	</param>
    empty = (empty == null) ? true : empty;
    return this.each(function () {
    if (this.tagName == 'SELECT') {
    if (empty) $(this).emptySelect();
    var name, i = 0, length = object.length;
    // Determine if we have a list or an object
    if (length === undefined) {
    // Iterate over object
    for (name in object) {
    addOption(this, name, object[name]);
    }
    } else {
    // Iterate over list
    for (var item = object[0]; i < length; item = object[++i]) {
    addOption(this, item, item);
    }
    }
    }
    });
    }*/


    $.fn.changeLoadGet = function (sourceUrl, targetElement, jsonP, callback) {
        /// <summary>
        ///     Adds an event to populate a different select element when this element changes using HTTP get. Supports JSONP.
        /// </summary>
        ///	<returns type="jQuery" />
        ///	<param name="sourceUrl" type="String">
        ///		URI to fetch data about change from.
        ///	</param>  
        ///	<param name="targetElement" type="String|Element|jQueryResult">
        ///		Element to populate when the change event is raised.
        ///	</param>
        ///	<param name="callback" type="Function">
        ///		Function that returns data to be passed as part of the server callback.
        ///	</param>
        /// <param name="jsonP" type="String">
        ///     parameter used to trigger a JSONP exchange.
        /// </param>
        return this.change(function () {
            var target = $(targetElement).disable();
            if ($(this).val() === "") {
                target.emptySelect().addOption("Select...", "")
                target.triggerHandler("change");
            } else {
                target.emptySelect().addOption("Loading...", "");

                var jsonPParameter = jsonP ? jsonP + "=?" : "";

                var data = callback.apply(this);
                var params;

                if (data == null)
                    params = "";
                else
                    params = $.param(data);

                if (data.length == 0) {
                    params = jsonPParameter;
                }
                else if (jsonPParameter.length > 0) {
                    params = params + "&" + jsonPParameter;
                }
                var xhr = $.getJSON(sourceUrl + "?" + params, null, function (data) {
                    target.emptySelect().addOption("Select...", "")
                        .loadSelect(data, false)
                        .disable(false)
                        .triggerHandler("change");
                });
            }
        });
    }

})(jQuery);
;

// Modification from: http://code.google.com/p/sroucheray-js/wiki/JqueryIframeResizer

jQuery.fn.iframeResize = function (options) {

    var settings = jQuery.extend({
        width: null,
        height: null,
        timeout: 500
    }, options),
        loadedKey = "loaded",
        timeoutKey = "iframeResize_timeout";

    function resizeIframe() {
        var frame = jQuery(this),
            body = jQuery(this).contents().find("html");
        var agt = navigator.userAgent.toLowerCase();
        if (agt.indexOf("msie") != -1) {
            body = jQuery(this).contents().find("body");
        }

        if (settings.width) {
            frame.css("width", (settings.width === "fill") ? "100%" : parseInt(settings.width, 10));
        }
        if (settings.height) {
            frame.css("height", settings.height === "auto" ? body.height() : parseInt(settings.height, 10));
        }
        if (frame.data(timeoutKey)) {
            window.clearTimeout(frame.data(timeoutKey));
            frame.removeData(timeoutKey);
        }
    }

    function onEachIframe() {
        var frame = jQuery(this);
        // set a timeout on the max case... in case we missed the load event
        frame.data(timeoutKey, window.setTimeout(function () { if (!frame.data(loadedKey)) { resizeIframe.call(frame); } }, settings.timeout));
        // attach to the load event
        frame.bind("load", function () { frame.data(loadedKey, true); resizeIframe.call(frame); });
    }

    jQuery(this).each(onEachIframe);
};
;
/*
 * Date prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
 * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
 * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
 *
 * Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 *
 * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
 * I've added my name to these methods so you know who to blame if they are broken!
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * An Array of day names starting with Sunday.
 * 
 * @example dayNames[0]
 * @result 'Sunday'
 *
 * @name dayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

/**
 * An Array of abbreviated day names starting with Sun.
 * 
 * @example abbrDayNames[0]
 * @result 'Sun'
 *
 * @name abbrDayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

/**
 * An Array of month names starting with Janurary.
 * 
 * @example monthNames[0]
 * @result 'January'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

/**
 * An Array of abbreviated month names starting with Jan.
 * 
 * @example abbrMonthNames[0]
 * @result 'Jan'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/**
 * The first day of the week for this locale.
 *
 * @name firstDayOfWeek
 * @type Number
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.firstDayOfWeek = 1;

/**
 * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';

/**
 * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
 * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.fullYearStart = '20';

(function() {

	/**
	 * Adds a given method under the given name 
	 * to the Date prototype if it doesn't
	 * currently exist.
	 *
	 * @private
	 */
	function add(name, method) {
		if( !Date.prototype[name] ) {
			Date.prototype[name] = method;
		}
	};
	
	/**
	 * Checks if the year is a leap year.
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isLeapYear();
	 * @result true
	 *
	 * @name isLeapYear
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isLeapYear", function() {
		var y = this.getFullYear();
		return (y%4==0 && y%100!=0) || y%400==0;
	});
	
	/**
	 * Checks if the day is a weekend day (Sat or Sun).
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekend();
	 * @result false
	 *
	 * @name isWeekend
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekend", function() {
		return this.getDay()==0 || this.getDay()==6;
	});
	
	/**
	 * Check if the day is a day of the week (Mon-Fri)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekDay();
	 * @result false
	 * 
	 * @name isWeekDay
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekDay", function() {
		return !this.isWeekend();
	});
	
	/**
	 * Gets the number of days in the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDaysInMonth();
	 * @result 31
	 * 
	 * @name getDaysInMonth
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDaysInMonth", function() {
		return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
	});
	
	/**
	 * Gets the name of the day.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName();
	 * @result 'Saturday'
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName(true);
	 * @result 'Sat'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getDayName", function(abbreviated) {
		return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
	});

	/**
	 * Gets the name of the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName();
	 * @result 'Janurary'
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName(true);
	 * @result 'Jan'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getMonthName", function(abbreviated) {
		return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
	});

	/**
	 * Get the number of the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayOfYear();
	 * @result 11
	 * 
	 * @name getDayOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDayOfYear", function() {
		var tmpdtm = new Date("1/1/" + this.getFullYear());
		return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
	});
	
	/**
	 * Get the number of the week of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getWeekOfYear();
	 * @result 2
	 * 
	 * @name getWeekOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getWeekOfYear", function() {
		return Math.ceil(this.getDayOfYear() / 7);
	});

	/**
	 * Set the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.setDayOfYear(1);
	 * dtm.toString();
	 * @result 'Tue Jan 01 2008 00:00:00'
	 * 
	 * @name setDayOfYear
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("setDayOfYear", function(day) {
		this.setMonth(0);
		this.setDate(day);
		return this;
	});
	
	/**
	 * Add a number of years to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addYears(1);
	 * dtm.toString();
	 * @result 'Mon Jan 12 2009 00:00:00'
	 * 
	 * @name addYears
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addYears", function(num) {
		this.setFullYear(this.getFullYear() + num);
		return this;
	});
	
	/**
	 * Add a number of months to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMonths(1);
	 * dtm.toString();
	 * @result 'Tue Feb 12 2008 00:00:00'
	 * 
	 * @name addMonths
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMonths", function(num) {
		var tmpdtm = this.getDate();
		
		this.setMonth(this.getMonth() + num);
		
		if (tmpdtm > this.getDate())
			this.addDays(-this.getDate());
		
		return this;
	});
	
	/**
	 * Add a number of days to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addDays(1);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addDays
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addDays", function(num) {
		//this.setDate(this.getDate() + num);
		this.setTime(this.getTime() + (num*86400000) );
		return this;
	});
	
	/**
	 * Add a number of hours to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addHours(24);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addHours
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addHours", function(num) {
		this.setHours(this.getHours() + num);
		return this;
	});

	/**
	 * Add a number of minutes to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMinutes(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 01:00:00'
	 * 
	 * @name addMinutes
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMinutes", function(num) {
		this.setMinutes(this.getMinutes() + num);
		return this;
	});
	
	/**
	 * Add a number of seconds to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addSeconds(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name addSeconds
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addSeconds", function(num) {
		this.setSeconds(this.getSeconds() + num);
		return this;
	});
	
	/**
	 * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
	 * 
	 * @example var dtm = new Date();
	 * dtm.zeroTime();
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name zeroTime
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("zeroTime", function() {
		this.setMilliseconds(0);
		this.setSeconds(0);
		this.setMinutes(0);
		this.setHours(0);
		return this;
	});
	
	/**
	 * Returns a string representation of the date object according to Date.format.
	 * (Date.toString may be used in other places so I purposefully didn't overwrite it)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.asString();
	 * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name asString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("asString", function(format) {
		var r = format || Date.format;
		if (r.split('mm').length>1) { // ugly workaround to make sure we don't replace the m's in e.g. noveMber
			r = r.split('mmmm').join(this.getMonthName(false))
				.split('mmm').join(this.getMonthName(true))
				.split('mm').join(_zeroPad(this.getMonth()+1))
		} else {
			r = r.split('m').join(this.getMonth()+1);
		}
		r = r.split('yyyy').join(this.getFullYear())
			.split('yy').join((this.getFullYear() + '').substring(2))
			.split('dd').join(_zeroPad(this.getDate()))
			.split('d').join(this.getDate());
		return r;
	});
	
	/**
	 * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
	 * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
	 *
	 * @example var dtm = Date.fromString("12/01/2008");
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name fromString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	Date.fromString = function(s)
	{
		var f = Date.format;
		
		var d = new Date('01/01/1970');
		
		if (s == undefined || s == '') return d;

		s = s.toLowerCase();
		var matcher = '';
		var order = [];
		var r = /(dd?d?|mm?m?|yy?yy?)+([^(m|d|y)])?/g;
		var results;
		while ((results = r.exec(f)) != null)
		{
			switch (results[1]) {
				case 'd':
				case 'dd':
				case 'm':
				case 'mm':
				case 'yy':
				case 'yyyy':
					matcher += '(\\d+\\d?\\d?\\d?)+';
					order.push(results[1].substr(0, 1));
					break;
				case 'mmm':
					matcher += '([a-z]{3})';
					order.push('M');
					break;
			}
			if (results[2]) {
				matcher += results[2];
			}
			
		}
		var dm = new RegExp(matcher);
		var result = s.match(dm);
		for (var i=0; i<order.length; i++) {
			var res = result[i+1];
			switch(order[i]) {
				case 'd':
					d.setDate(res);
					break;
				case 'm':
					d.setMonth(Number(res)-1);
					break;
				case 'M':
					for (var j=0; j<Date.abbrMonthNames.length; j++) {
						if (Date.abbrMonthNames[j].toLowerCase() == res) break;
					}
					d.setMonth(j);
					break;
				case 'y':
					d.setYear(res);
					break;
			}
		}

		return d;
	};
	
	// utility method
	var _zeroPad = function(num) {
		var s = '0'+num;
		return s.substring(s.length-2)
		//return ('0'+num).substring(-2); // doesn't work on IE :(
	};
	
})();;
/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var b="unobtrusiveAjaxClick",d="unobtrusiveAjaxClickTarget",h="unobtrusiveValidation";function c(d,b){var a=window,c=(d||"").split(".");while(a&&c.length)a=a[c.shift()];if(typeof a==="function")return a;b.push(d);return Function.constructor.apply(null,b)}function e(a){return a==="GET"||a==="POST"}function g(b,a){!e(a)&&b.setRequestHeader("X-HTTP-Method-Override",a)}function i(c,b,e){var d;if(e.indexOf("application/x-javascript")!==-1)return;d=(c.getAttribute("data-ajax-mode")||"").toUpperCase();a(c.getAttribute("data-ajax-update")).each(function(f,c){var e;switch(d){case"BEFORE":e=c.firstChild;a("<div />").html(b).contents().each(function(){c.insertBefore(this,e)});break;case"AFTER":a("<div />").html(b).contents().each(function(){c.appendChild(this)});break;case"REPLACE-WITH":a(c).replaceWith(b);break;default:a(c).html(b)}})}function f(b,d){var j,k,f,h;j=b.getAttribute("data-ajax-confirm");if(j&&!window.confirm(j))return;k=a(b.getAttribute("data-ajax-loading"));h=parseInt(b.getAttribute("data-ajax-loading-duration"),10)||0;a.extend(d,{type:b.getAttribute("data-ajax-method")||undefined,url:b.getAttribute("data-ajax-url")||undefined,cache:!!b.getAttribute("data-ajax-cache"),beforeSend:function(d){var a;g(d,f);a=c(b.getAttribute("data-ajax-begin"),["xhr"]).apply(b,arguments);a!==false&&k.show(h);return a},complete:function(){k.hide(h);c(b.getAttribute("data-ajax-complete"),["xhr","status"]).apply(b,arguments)},success:function(a,e,d){i(b,a,d.getResponseHeader("Content-Type")||"text/html");c(b.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(b,arguments)},error:function(){c(b.getAttribute("data-ajax-failure"),["xhr","status","error"]).apply(b,arguments)}});d.data.push({name:"X-Requested-With",value:"XMLHttpRequest"});f=d.type.toUpperCase();if(!e(f)){d.type="POST";d.data.push({name:"X-HTTP-Method-Override",value:f})}a.ajax(d)}function j(c){var b=a(c).data(h);return!b||!b.validate||b.validate()}a(document).on("click","a[data-ajax=true]",function(a){a.preventDefault();f(this,{url:this.href,type:"GET",data:[]})});a(document).on("click","form[data-ajax=true] input[type=image]",function(c){var g=c.target.name,e=a(c.target),f=a(e.parents("form")[0]),d=e.offset();f.data(b,[{name:g+".x",value:Math.round(c.pageX-d.left)},{name:g+".y",value:Math.round(c.pageY-d.top)}]);setTimeout(function(){f.removeData(b)},0)});a(document).on("click","form[data-ajax=true] :submit",function(e){var g=e.currentTarget.name,f=a(e.target),c=a(f.parents("form")[0]);c.data(b,g?[{name:g,value:e.currentTarget.value}]:[]);c.data(d,f);setTimeout(function(){c.removeData(b);c.removeData(d)},0)});a(document).on("submit","form[data-ajax=true]",function(h){var e=a(this).data(b)||[],c=a(this).data(d),g=c&&c.hasClass("cancel");h.preventDefault();if(!g&&!j(this))return;f(this,{url:this.action,type:this.method||"GET",data:e.concat(a(this).serializeArray())})})})(jQuery);;
/*! jQuery Validation Plugin - v1.16.0 - 12/2/2016
 * http://jqueryvalidation.org/
 * Copyright (c) 2016 Jörn Zaefferer; Licensed MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){a.extend(a.fn,{validate:function(b){if(!this.length)return void(b&&b.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.on("click.validate",":submit",function(b){c.settings.submitHandler&&(c.submitButton=b.target),a(this).hasClass("cancel")&&(c.cancelSubmit=!0),void 0!==a(this).attr("formnovalidate")&&(c.cancelSubmit=!0)}),this.on("submit.validate",function(b){function d(){var d,e;return!c.settings.submitHandler||(c.submitButton&&(d=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),e=c.settings.submitHandler.call(c,c.currentForm,b),c.submitButton&&d.remove(),void 0!==e&&e)}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c,d;return a(this[0]).is("form")?b=this.validate().form():(d=[],b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b,b||(d=d.concat(c.errorList))}),c.errorList=d),b},rules:function(b,c){var d,e,f,g,h,i,j=this[0];if(null!=j&&null!=j.form){if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(b,c){i[c]=f[c],delete f[c],"required"===c&&a(j).removeAttr("aria-required")}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g),a(j).attr("aria-required","true")),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}}),a.extend(a.expr.pseudos||a.expr[":"],{blank:function(b){return!a.trim(""+a(b).val())},filled:function(b){var c=a(b).val();return null!==c&&!!a.trim(""+c)},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:void 0===c?b:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",pendingClass:"pending",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(b,c){var d=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===c.which&&""===this.elementValue(b)||a.inArray(c.keyCode,d)!==-1||(b.name in this.submitted||b.name in this.invalid)&&this.element(b)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}."),step:a.validator.format("Please enter a multiple of {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){!this.form&&this.hasAttribute("contenteditable")&&(this.form=a(this).closest("form")[0]);var c=a.data(this.form,"validator"),d="on"+b.type.replace(/^validate/,""),e=c.settings;e[d]&&!a(this).is(e.ignore)&&e[d].call(c,this,b)}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){d[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox'], [contenteditable], [type='button']",b).on("click.validate","select, option, [type='radio'], [type='checkbox']",b),this.settings.invalidHandler&&a(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler),a(this.currentForm).find("[required], [data-rule-required], .required").attr("aria-required","true")},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c,d,e=this.clean(b),f=this.validationTargetFor(e),g=this,h=!0;return void 0===f?delete this.invalid[e.name]:(this.prepareElement(f),this.currentElements=a(f),d=this.groups[f.name],d&&a.each(this.groups,function(a,b){b===d&&a!==f.name&&(e=g.validationTargetFor(g.clean(g.findByName(a))),e&&e.name in g.invalid&&(g.currentElements.push(e),h=g.check(e)&&h))}),c=this.check(f)!==!1,h=h&&c,c?this.invalid[f.name]=!1:this.invalid[f.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),a(b).attr("aria-invalid",!c)),h},showErrors:function(b){if(b){var c=this;a.extend(this.errorMap,b),this.errorList=a.map(this.errorMap,function(a,b){return{message:a,element:c.findByName(b)[0]}}),this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.invalid={},this.submitted={},this.prepareForm(),this.hideErrors();var b=this.elements().removeData("previousValue").removeAttr("aria-invalid");this.resetElements(b)},resetElements:function(a){var b;if(this.settings.unhighlight)for(b=0;a[b];b++)this.settings.unhighlight.call(this,a[b],this.settings.errorClass,""),this.findByName(a[b].name).removeClass(this.settings.validClass);else a.removeClass(this.settings.errorClass).removeClass(this.settings.validClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)a[b]&&c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){var d=this.name||a(this).attr("name");return!d&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.hasAttribute("contenteditable")&&(this.form=a(this).closest("form")[0]),!(d in c||!b.objectLength(a(this).rules()))&&(c[d]=!0,!0)})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},resetInternals:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([])},reset:function(){this.resetInternals(),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d,e=a(b),f=b.type;return"radio"===f||"checkbox"===f?this.findByName(b.name).filter(":checked").val():"number"===f&&"undefined"!=typeof b.validity?b.validity.badInput?"NaN":e.val():(c=b.hasAttribute("contenteditable")?e.text():e.val(),"file"===f?"C:\\fakepath\\"===c.substr(0,12)?c.substr(12):(d=c.lastIndexOf("/"),d>=0?c.substr(d+1):(d=c.lastIndexOf("\\"),d>=0?c.substr(d+1):c)):"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f=a(b).rules(),g=a.map(f,function(a,b){return b}).length,h=!1,i=this.elementValue(b);if("function"==typeof f.normalizer){if(i=f.normalizer.call(b,i),"string"!=typeof i)throw new TypeError("The normalizer should return a string value.");delete f.normalizer}for(d in f){e={method:d,parameters:f[d]};try{if(c=a.validator.methods[d].call(this,i,b,e.parameters),"dependency-mismatch"===c&&1===g){h=!0;continue}if(h=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(j){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",j),j instanceof TypeError&&(j.message+=".  Exception occurred when checking element "+b.id+", check the '"+e.method+"' method."),j}}if(!h)return this.objectLength(f)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(void 0!==arguments[a])return arguments[a]},defaultMessage:function(b,c){"string"==typeof c&&(c={method:c});var d=this.findDefined(this.customMessage(b.name,c.method),this.customDataMessage(b,c.method),!this.settings.ignoreTitle&&b.title||void 0,a.validator.messages[c.method],"<strong>Warning: No message defined for "+b.name+"</strong>"),e=/\$?\{(\d+)\}/g;return"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),d},formatAndAdd:function(a,b){var c=this.defaultMessage(a,b);this.errorList.push({message:c,element:a,method:b.method}),this.errorMap[a.name]=c,this.submitted[a.name]=c},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g,h=this.errorsFor(b),i=this.idOrName(b),j=a(b).attr("aria-describedby");h.length?(h.removeClass(this.settings.validClass).addClass(this.settings.errorClass),h.html(c)):(h=a("<"+this.settings.errorElement+">").attr("id",i+"-error").addClass(this.settings.errorClass).html(c||""),d=h,this.settings.wrapper&&(d=h.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement.call(this,d,a(b)):d.insertAfter(b),h.is("label")?h.attr("for",i):0===h.parents("label[for='"+this.escapeCssMeta(i)+"']").length&&(f=h.attr("id"),j?j.match(new RegExp("\\b"+this.escapeCssMeta(f)+"\\b"))||(j+=" "+f):j=f,a(b).attr("aria-describedby",j),e=this.groups[b.name],e&&(g=this,a.each(g.groups,function(b,c){c===e&&a("[name='"+g.escapeCssMeta(b)+"']",g.currentForm).attr("aria-describedby",h.attr("id"))})))),!c&&this.settings.success&&(h.text(""),"string"==typeof this.settings.success?h.addClass(this.settings.success):this.settings.success(h,b)),this.toShow=this.toShow.add(h)},errorsFor:function(b){var c=this.escapeCssMeta(this.idOrName(b)),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+this.escapeCssMeta(d).replace(/\s+/g,", #")),this.errors().filter(e)},escapeCssMeta:function(a){return a.replace(/([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g,"\\$1")},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+this.escapeCssMeta(b)+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return!this.dependTypes[typeof a]||this.dependTypes[typeof a](a,b)},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(b){this.pending[b.name]||(this.pendingRequest++,a(b).addClass(this.settings.pendingClass),this.pending[b.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],a(b).removeClass(this.settings.pendingClass),c&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b,c){return c="string"==typeof c&&c||"remote",a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,{method:c})})},destroy:function(){this.resetForm(),a(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},normalizeAttributeRule:function(a,b,c,d){/min|max|step/.test(c)&&(null===b||/number|range|text/.test(b))&&(d=Number(d),isNaN(d)&&(d=void 0)),d||0===d?a[c]=d:b===c&&"range"!==b&&(a[c]=!0)},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),this.normalizeAttributeRule(e,g,c,d);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),this.normalizeAttributeRule(e,g,c,d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0===e.param||e.param:(a.data(c.form,"validator").resetElements(a(c)),delete b[d])}}),a.each(b,function(d,e){b[d]=a.isFunction(e)&&"normalizer"!==d?e(c):e}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var c;b[this]&&(a.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(c=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(c[0]),Number(c[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:b.length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(a)},date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a).toString())},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e<=d},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||a<=c},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},step:function(b,c,d){var e,f=a(c).attr("type"),g="Step attribute on input type "+f+" is not supported.",h=["text","number","range"],i=new RegExp("\\b"+f+"\\b"),j=f&&!i.test(h.join()),k=function(a){var b=(""+a).match(/(?:\.(\d+))?$/);return b&&b[1]?b[1].length:0},l=function(a){return Math.round(a*Math.pow(10,e))},m=!0;if(j)throw new Error(g);return e=k(d),(k(b)>e||l(b)%l(d)!==0)&&(m=!1),this.optional(c)||m},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.not(".validate-equalTo-blur").length&&e.addClass("validate-equalTo-blur").on("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d,e){if(this.optional(c))return"dependency-mismatch";e="string"==typeof e&&e||"remote";var f,g,h,i=this.previousValue(c,e);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),i.originalMessage=i.originalMessage||this.settings.messages[c.name][e],this.settings.messages[c.name][e]=i.message,d="string"==typeof d&&{url:d}||d,h=a.param(a.extend({data:b},d.data)),i.old===h?i.valid:(i.old=h,f=this,this.startRequest(c),g={},g[c.name]=b,a.ajax(a.extend(!0,{mode:"abort",port:"validate"+c.name,dataType:"json",data:g,context:f.currentForm,success:function(a){var d,g,h,j=a===!0||"true"===a;f.settings.messages[c.name][e]=i.originalMessage,j?(h=f.formSubmitted,f.resetInternals(),f.toHide=f.errorsFor(c),f.formSubmitted=h,f.successList.push(c),f.invalid[c.name]=!1,f.showErrors()):(d={},g=a||f.defaultMessage(c,{method:e,parameters:b}),d[c.name]=i.message=g,f.invalid[c.name]=!0,f.showErrors(d)),i.valid=j,f.stopRequest(c,j)}},d)),"pending")}}});var b,c={};return a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,d){var e=a.port;"abort"===a.mode&&(c[e]&&c[e].abort(),c[e]=d)}):(b=a.ajax,a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return"abort"===e?(c[f]&&c[f].abort(),c[f]=b.apply(this,arguments),c[f]):b.apply(this,arguments)}),a});;
/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,e){var b=a(this).find("[data-valmsg-for='"+f(e[0].name)+"']"),d=b.attr("data-valmsg-replace"),g=d?JSON.parse(d)!==false:null;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(g){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("<li />").html(this.message).appendTo(b)})}}function k(d){var b=d.data("unobtrusiveContainer"),c=b.attr("data-valmsg-replace"),e=c?JSON.parse(c):null;if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");d.removeData("unobtrusiveContainer");e&&b.empty()}}function n(){var b=a(this),c="__jquery_unobtrusive_validation_form_reset";if(b.data(c))return;b.data(c,true);try{b.data("validator").resetForm()}finally{b.removeData(c)}b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(b){var c=a(b),f=c.data(e),i=a.proxy(n,b),g=d.unobtrusive.options||{},h=function(e,d){var c=g[e];c&&a.isFunction(c)&&c.apply(b,d)};if(!f){f={options:{errorClass:g.errorClass||"input-validation-error",errorElement:g.errorElement||"span",errorPlacement:function(){m.apply(b,arguments);h("errorPlacement",arguments)},invalidHandler:function(){l.apply(b,arguments);h("invalidHandler",arguments)},messages:{},rules:{},success:function(){k.apply(b,arguments);h("success",arguments)}},attachValidation:function(){c.off("reset."+e,i).on("reset."+e,i).validate(this.options)},validate:function(){c.validate();return c.valid()}};c.data(e,f)}return f}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(c){var b=a(c),e=b.parents().addBack().filter("form").add(b.find("form")).has("[data-val=true]");b.find("[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});e.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});if(d.methods.extension){b.addSingleVal("accept","mimtype");b.addSingleVal("extension","extension")}else b.addSingleVal("extension","extension","accept");b.addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input").filter("[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){var d=a(b.form).find(":input").filter("[name='"+f(c)+"']");return d.is(":checkbox")?d.filter(":checked").val()||d.filter(":hidden").val()||"":d.is(":radio")?d.filter(":checked").val()||"":d.val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery);;
/*!
 * jQuery blockUI plugin
 * Version 2.70.0-2014.11.23
 * Requires jQuery v1.7 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2013 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function() {
/*jshint eqeqeq:false curly:false latedef:false */
"use strict";

	function setup($) {
		$.fn._fadeIn = $.fn.fadeIn;

		var noOp = $.noop || function() {};

		// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
		// confusing userAgent strings on Vista)
		var msie = /MSIE/.test(navigator.userAgent);
		var ie6  = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
		var mode = document.documentMode || 0;
		var setExpr = $.isFunction( document.createElement('div').style.setExpression );

		// global $ methods for blocking/unblocking the entire page
		$.blockUI   = function(opts) { install(window, opts); };
		$.unblockUI = function(opts) { remove(window, opts); };

		// convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
		$.growlUI = function(title, message, timeout, onClose) {
			var $m = $('<div class="growlUI"></div>');
			if (title) $m.append('<h1>'+title+'</h1>');
			if (message) $m.append('<h2>'+message+'</h2>');
			if (timeout === undefined) timeout = 3000;

			// Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications
			var callBlock = function(opts) {
				opts = opts || {};

				$.blockUI({
					message: $m,
					fadeIn : typeof opts.fadeIn  !== 'undefined' ? opts.fadeIn  : 700,
					fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000,
					timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout,
					centerY: false,
					showOverlay: false,
					onUnblock: onClose,
					css: $.blockUI.defaults.growlCSS
				});
			};

			callBlock();
			var nonmousedOpacity = $m.css('opacity');
			$m.mouseover(function() {
				callBlock({
					fadeIn: 0,
					timeout: 30000
				});

				var displayBlock = $('.blockMsg');
				displayBlock.stop(); // cancel fadeout if it has started
				displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency
			}).mouseout(function() {
				$('.blockMsg').fadeOut(1000);
			});
			// End konapun additions
		};

		// plugin method for blocking element content
		$.fn.block = function(opts) {
			if ( this[0] === window ) {
				$.blockUI( opts );
				return this;
			}
			var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
			this.each(function() {
				var $el = $(this);
				if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
					return;
				$el.unblock({ fadeOut: 0 });
			});

			return this.each(function() {
				if ($.css(this,'position') == 'static') {
					this.style.position = 'relative';
					$(this).data('blockUI.static', true);
				}
				this.style.zoom = 1; // force 'hasLayout' in ie
				install(this, opts);
			});
		};

		// plugin method for unblocking element content
		$.fn.unblock = function(opts) {
			if ( this[0] === window ) {
				$.unblockUI( opts );
				return this;
			}
			return this.each(function() {
				remove(this, opts);
			});
		};

		$.blockUI.version = 2.70; // 2nd generation blocking at no extra cost!

		// override these in your code to change the default behavior and style
		$.blockUI.defaults = {
			// message displayed when blocking (use null for no message)
			message:  '<h1>Please wait...</h1>',

			title: null,		// title string; only used when theme == true
			draggable: true,	// only used when theme == true (requires jquery-ui.js to be loaded)

			theme: false, // set to true to use with jQuery UI themes

			// styles for the message when blocking; if you wish to disable
			// these and use an external stylesheet then do this in your code:
			// $.blockUI.defaults.css = {};
			css: {
				padding:	0,
				margin:		0,
				width:		'30%',
				top:		'40%',
				left:		'35%',
				textAlign:	'center',
				color:		'#000',
				border:		'3px solid #aaa',
				backgroundColor:'#fff',
				cursor:		'wait'
			},

			// minimal style set used when themes are used
			themedCSS: {
				width:	'30%',
				top:	'40%',
				left:	'35%'
			},

			// styles for the overlay
			overlayCSS:  {
				backgroundColor:	'#000',
				opacity:			0.6,
				cursor:				'wait'
			},

			// style to replace wait cursor before unblocking to correct issue
			// of lingering wait cursor
			cursorReset: 'default',

			// styles applied when using $.growlUI
			growlCSS: {
				width:		'350px',
				top:		'10px',
				left:		'',
				right:		'10px',
				border:		'none',
				padding:	'5px',
				opacity:	0.6,
				cursor:		'default',
				color:		'#fff',
				backgroundColor: '#000',
				'-webkit-border-radius':'10px',
				'-moz-border-radius':	'10px',
				'border-radius':		'10px'
			},

			// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
			// (hat tip to Jorge H. N. de Vasconcelos)
			/*jshint scripturl:true */
			iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',

			// force usage of iframe in non-IE browsers (handy for blocking applets)
			forceIframe: false,

			// z-index for the blocking overlay
			baseZ: 1000,

			// set these to true to have the message automatically centered
			centerX: true, // <-- only effects element blocking (page block controlled via css above)
			centerY: true,

			// allow body element to be stetched in ie6; this makes blocking look better
			// on "short" pages.  disable if you wish to prevent changes to the body height
			allowBodyStretch: true,

			// enable if you want key and mouse events to be disabled for content that is blocked
			bindEvents: true,

			// be default blockUI will supress tab navigation from leaving blocking content
			// (if bindEvents is true)
			constrainTabKey: true,

			// fadeIn time in millis; set to 0 to disable fadeIn on block
			fadeIn:  200,

			// fadeOut time in millis; set to 0 to disable fadeOut on unblock
			fadeOut:  400,

			// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
			timeout: 0,

			// disable if you don't want to show the overlay
			showOverlay: true,

			// if true, focus will be placed in the first available input field when
			// page blocking
			focusInput: true,

            // elements that can receive focus
            focusableElements: ':input:enabled:visible',

			// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
			// no longer needed in 2012
			// applyPlatformOpacityRules: true,

			// callback method invoked when fadeIn has completed and blocking message is visible
			onBlock: null,

			// callback method invoked when unblocking has completed; the callback is
			// passed the element that has been unblocked (which is the window object for page
			// blocks) and the options that were passed to the unblock call:
			//	onUnblock(element, options)
			onUnblock: null,

			// callback method invoked when the overlay area is clicked.
			// setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used.
			onOverlayClick: null,

			// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
			quirksmodeOffsetHack: 4,

			// class name of the message block
			blockMsgClass: 'blockMsg',

			// if it is already blocked, then ignore it (don't unblock and reblock)
			ignoreIfBlocked: false
		};

		// private data and functions follow...

		var pageBlock = null;
		var pageBlockEls = [];

		function install(el, opts) {
			var css, themedCSS;
			var full = (el == window);
			var msg = (opts && opts.message !== undefined ? opts.message : undefined);
			opts = $.extend({}, $.blockUI.defaults, opts || {});

			if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
				return;

			opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
			css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
			if (opts.onOverlayClick)
				opts.overlayCSS.cursor = 'pointer';

			themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
			msg = msg === undefined ? opts.message : msg;

			// remove the current block (if there is one)
			if (full && pageBlock)
				remove(window, {fadeOut:0});

			// if an existing element is being used as the blocking content then we capture
			// its current place in the DOM (and current display style) so we can restore
			// it when we unblock
			if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
				var node = msg.jquery ? msg[0] : msg;
				var data = {};
				$(el).data('blockUI.history', data);
				data.el = node;
				data.parent = node.parentNode;
				data.display = node.style.display;
				data.position = node.style.position;
				if (data.parent)
					data.parent.removeChild(node);
			}

			$(el).data('blockUI.onUnblock', opts.onUnblock);
			var z = opts.baseZ;

			// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
			// layer1 is the iframe layer which is used to supress bleed through of underlying content
			// layer2 is the overlay layer which has opacity and a wait cursor (by default)
			// layer3 is the message content that is displayed while blocking
			var lyr1, lyr2, lyr3, s;
			if (msie || opts.forceIframe)
				lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>');
			else
				lyr1 = $('<div class="blockUI" style="display:none"></div>');

			if (opts.theme)
				lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>');
			else
				lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');

			if (opts.theme && full) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">';
				if ( opts.title ) {
					s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
				}
				s += '<div class="ui-widget-content ui-dialog-content"></div>';
				s += '</div>';
			}
			else if (opts.theme) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">';
				if ( opts.title ) {
					s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
				}
				s += '<div class="ui-widget-content ui-dialog-content"></div>';
				s += '</div>';
			}
			else if (full) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
			}
			else {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
			}
			lyr3 = $(s);

			// if we have a message, style it
			if (msg) {
				if (opts.theme) {
					lyr3.css(themedCSS);
					lyr3.addClass('ui-widget-content');
				}
				else
					lyr3.css(css);
			}

			// style the overlay
			if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
				lyr2.css(opts.overlayCSS);
			lyr2.css('position', full ? 'fixed' : 'absolute');

			// make iframe layer transparent in IE
			if (msie || opts.forceIframe)
				lyr1.css('opacity',0.0);

			//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
			var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
			$.each(layers, function() {
				this.appendTo($par);
			});

			if (opts.theme && opts.draggable && $.fn.draggable) {
				lyr3.draggable({
					handle: '.ui-dialog-titlebar',
					cancel: 'li'
				});
			}

			// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
			var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
			if (ie6 || expr) {
				// give body 100% height
				if (full && opts.allowBodyStretch && $.support.boxModel)
					$('html,body').css('height','100%');

				// fix ie6 issue when blocked element has a border width
				if ((ie6 || !$.support.boxModel) && !full) {
					var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
					var fixT = t ? '(0 - '+t+')' : 0;
					var fixL = l ? '(0 - '+l+')' : 0;
				}

				// simulate fixed position
				$.each(layers, function(i,o) {
					var s = o[0].style;
					s.position = 'absolute';
					if (i < 2) {
						if (full)
							s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
						else
							s.setExpression('height','this.parentNode.offsetHeight + "px"');
						if (full)
							s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
						else
							s.setExpression('width','this.parentNode.offsetWidth + "px"');
						if (fixL) s.setExpression('left', fixL);
						if (fixT) s.setExpression('top', fixT);
					}
					else if (opts.centerY) {
						if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
						s.marginTop = 0;
					}
					else if (!opts.centerY && full) {
						var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
						var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
						s.setExpression('top',expression);
					}
				});
			}

			// show the message
			if (msg) {
				if (opts.theme)
					lyr3.find('.ui-widget-content').append(msg);
				else
					lyr3.append(msg);
				if (msg.jquery || msg.nodeType)
					$(msg).show();
			}

			if ((msie || opts.forceIframe) && opts.showOverlay)
				lyr1.show(); // opacity is zero
			if (opts.fadeIn) {
				var cb = opts.onBlock ? opts.onBlock : noOp;
				var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
				var cb2 = msg ? cb : noOp;
				if (opts.showOverlay)
					lyr2._fadeIn(opts.fadeIn, cb1);
				if (msg)
					lyr3._fadeIn(opts.fadeIn, cb2);
			}
			else {
				if (opts.showOverlay)
					lyr2.show();
				if (msg)
					lyr3.show();
				if (opts.onBlock)
					opts.onBlock.bind(lyr3)();
			}

			// bind key and mouse events
			bind(1, el, opts);

			if (full) {
				pageBlock = lyr3[0];
				pageBlockEls = $(opts.focusableElements,pageBlock);
				if (opts.focusInput)
					setTimeout(focus, 20);
			}
			else
				center(lyr3[0], opts.centerX, opts.centerY);

			if (opts.timeout) {
				// auto-unblock
				var to = setTimeout(function() {
					if (full)
						$.unblockUI(opts);
					else
						$(el).unblock(opts);
				}, opts.timeout);
				$(el).data('blockUI.timeout', to);
			}
		}

		// remove the block
		function remove(el, opts) {
			var count;
			var full = (el == window);
			var $el = $(el);
			var data = $el.data('blockUI.history');
			var to = $el.data('blockUI.timeout');
			if (to) {
				clearTimeout(to);
				$el.removeData('blockUI.timeout');
			}
			opts = $.extend({}, $.blockUI.defaults, opts || {});
			bind(0, el, opts); // unbind events

			if (opts.onUnblock === null) {
				opts.onUnblock = $el.data('blockUI.onUnblock');
				$el.removeData('blockUI.onUnblock');
			}

			var els;
			if (full) // crazy selector to handle odd field errors in ie6/7
				els = $('body').children().filter('.blockUI').add('body > .blockUI');
			else
				els = $el.find('>.blockUI');

			// fix cursor issue
			if ( opts.cursorReset ) {
				if ( els.length > 1 )
					els[1].style.cursor = opts.cursorReset;
				if ( els.length > 2 )
					els[2].style.cursor = opts.cursorReset;
			}

			if (full)
				pageBlock = pageBlockEls = null;

			if (opts.fadeOut) {
				count = els.length;
				els.stop().fadeOut(opts.fadeOut, function() {
					if ( --count === 0)
						reset(els,data,opts,el);
				});
			}
			else
				reset(els, data, opts, el);
		}

		// move blocking element back into the DOM where it started
		function reset(els,data,opts,el) {
			var $el = $(el);
			if ( $el.data('blockUI.isBlocked') )
				return;

			els.each(function(i,o) {
				// remove via DOM calls so we don't lose event handlers
				if (this.parentNode)
					this.parentNode.removeChild(this);
			});

			if (data && data.el) {
				data.el.style.display = data.display;
				data.el.style.position = data.position;
				data.el.style.cursor = 'default'; // #59
				if (data.parent)
					data.parent.appendChild(data.el);
				$el.removeData('blockUI.history');
			}

			if ($el.data('blockUI.static')) {
				$el.css('position', 'static'); // #22
			}

			if (typeof opts.onUnblock == 'function')
				opts.onUnblock(el,opts);

			// fix issue in Safari 6 where block artifacts remain until reflow
			var body = $(document.body), w = body.width(), cssW = body[0].style.width;
			body.width(w-1).width(w);
			body[0].style.width = cssW;
		}

		// bind/unbind the handler
		function bind(b, el, opts) {
			var full = el == window, $el = $(el);

			// don't bother unbinding if there is nothing to unbind
			if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
				return;

			$el.data('blockUI.isBlocked', b);

			// don't bind events when overlay is not in use or if bindEvents is false
			if (!full || !opts.bindEvents || (b && !opts.showOverlay))
				return;

			// bind anchors and inputs for mouse and key events
			var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
			if (b)
				$(document).bind(events, opts, handler);
			else
				$(document).unbind(events, handler);

		// former impl...
		//		var $e = $('a,:input');
		//		b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
		}

		// event handler to suppress keyboard/mouse events when blocking
		function handler(e) {
			// allow tab navigation (conditionally)
			if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) {
				if (pageBlock && e.data.constrainTabKey) {
					var els = pageBlockEls;
					var fwd = !e.shiftKey && e.target === els[els.length-1];
					var back = e.shiftKey && e.target === els[0];
					if (fwd || back) {
						setTimeout(function(){focus(back);},10);
						return false;
					}
				}
			}
			var opts = e.data;
			var target = $(e.target);
			if (target.hasClass('blockOverlay') && opts.onOverlayClick)
				opts.onOverlayClick(e);

			// allow events within the message content
			if (target.parents('div.' + opts.blockMsgClass).length > 0)
				return true;

			// allow events for content that is not being blocked
			return target.parents().children().filter('div.blockUI').length === 0;
		}

		function focus(back) {
			if (!pageBlockEls)
				return;
			var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
			if (e)
				e.focus();
		}

		function center(el, x, y) {
			var p = el.parentNode, s = el.style;
			var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
			var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
			if (x) s.left = l > 0 ? (l+'px') : '0';
			if (y) s.top  = t > 0 ? (t+'px') : '0';
		}

		function sz(el, p) {
			return parseInt($.css(el,p),10)||0;
		}

	}


	/*global define:true */
	if (typeof define === 'function' && define.amd && define.amd.jQuery) {
		define(['jquery'], setup);
	} else {
		setup(jQuery);
	}

})();
;
/* jSticky Plugin - customised with jQuery lockfixed plugin. Fixed position alternative works on older IOS and Android
 * =============
 * Author: Andrew Henderson (@AndrewHenderson)
 * Date: 9/7/2012
 * Update: 11/4/2012
 * Website: http://github.com/andrewhenderson/jsticky/
 * Description: A jQuery plugin that keeps select DOM element(s)
 * in view while scrolling the page.  */
/*!
 * jQuery lockfixed plugin
 * http://www.directlyrics.com/code/lockfixed/
 * Copyright 2012 Yvo Schaap
 * Released under the MIT license
 * http://www.directlyrics.com/code/lockfixed/license.txt
 * Date: Sun Jan 27 2013 12:00:00 GMT
 */
; (function ($) {

    $.fn.stickyScroller = function (options) {

        var defaults = {
            forcemargin: false,
            topspacing: 0, // No spacing by default
            stopper: 0 // stopper class, also accepts number value
        },
          settings = $.extend({}, defaults, options); // Accepts custom stopper id or class

        // Checks if a stopper exists in the DOM or number defined
        function checkStopper() {

            if (0 < $(settings.stopper).length || typeof settings.stopper === 'number') {
                return true;
            } else {
                return false;
            }
        }
        var hasStopper = checkStopper(); // True or false

        return this.each(function () {

            var el = $(this),
            el_top = el.offset().top,
            el_left = el.offset().left,
            el_height = el.outerHeight(true),
            el_width = el.outerWidth(),
            el_position = el.css("position"),
            el_position_top = el.css("top"),
            el_margin_top = parseInt(el.css("marginTop"), 10),
            topspacing = settings.topspacing,
            stopper = settings.stopper,
            placeholder = $('<div></div>').width(el_width).height(el_height).addClass('sticky-placeholder'), // Cache a clone sticky element
            top = 0,
            pos_not_fixed = false;

            // Calculate intial stop point height
            if (hasStopper && typeof stopper === 'string') {
                var stopPoint = parseInt($(stopper).outerHeight(), 10);
            } else if (hasStopper && typeof stopper === 'number') {
                var stopPoint = parseInt(stopper, 10);
            }
            var max_height = $(document).height() - stopPoint;

            /* we prefer feature testing, too much hassle for the upside */
            /* while prettier to use position: fixed (less jitter when scrolling) */
            /* iOS 5+ + Andriud has fixed support, but issue with toggeling between fixed and not and zoomed view, is iOs only calls after scroll is done, so we ignore iOS 5 for now */
            if (settings.forcemargin === true || navigator.userAgent.match(/\bMSIE (4|5|6)\./) || navigator.userAgent.match(/\bOS (3|4|5|6)_/) || navigator.userAgent.match(/\bAndroid (1|2|3|4)\./i)) {
                pos_not_fixed = true;
            }

            function stickyScroll() {
                var el_height = el.outerHeight(),
                    scroll_top = $(window).scrollTop(); // Check window's scroll position

                //if we have a input focus don't change this (for ios zoom and stuff)
                if (pos_not_fixed && document.activeElement && document.activeElement.nodeName === "INPUT") {
                    return;
                }

                // Push point reached
                if (scroll_top >= (el_top - (el_margin_top ? el_margin_top : 0) - topspacing)) {

                    if (max_height < (scroll_top + el_height + el_margin_top + topspacing)) {
                        top = (scroll_top + el_height + el_margin_top + topspacing) - max_height;
                    } else {
                        top = 0;
                    }

                    if (pos_not_fixed) {		// Calulate margin top value - static positioning
                        el.css({ 'marginTop': parseInt(((el_margin_top ? el_margin_top : 0) + (scroll_top - el_top - top) + 2 * topspacing), 10) + 'px' });
                    } else if (hasStopper) {	// Calulate top value - fixed positioning
                        if (hasStopper && typeof stopper === 'string') {	//Recalculate the stop point based on the offset
                            var stopperTop = $(stopper).offset().top,
                                stopPoint = (stopperTop - el_height) - topspacing;
                        }

                        el.after(placeholder).css({ position: 'fixed', top: topspacing });

                        if (stopPoint < scroll_top) {	// Stop point
                            var diff = (stopPoint - scroll_top) + topspacing;
                            el.css({ 'position': 'fixed', 'top': diff + 'px', 'width': el_width + "px" });
                        }
                    }
                }
                    // Reset
                else {
                    el.css({ 'position': el_position, 'top': el_position_top, 'width': el_width + "px", 'marginTop': (el_margin_top ? el_margin_top : 0) + "px" });
                    placeholder.remove();
                }
            }

            $(window).on('scroll resize orientationchange load', stickyScroll);
        });
    };
})(jQuery);;
/*
 * jQuery Templates Plugin 1.0.0pre
 * http://github.com/jquery/jquery-tmpl
 * Requires jQuery 1.4.2
 *
 * Copyright 2011, Software Freedom Conservancy, Inc.
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */
(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},i=0,c=0,l=[];function g(g,d,h,e){var c={data:e||(e===0||e===false)?e:d?d.data:{},_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};g&&a.extend(c,g,{nodes:[],parent:d});if(h){c.tmpl=h;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++i;(l.length?f:b)[i]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a(i[h])[d](k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,m,k){if(d[0]&&a.isArray(d[0])){var g=a.makeArray(arguments),h=d[0],j=h.length,i=0,f;while(i<j&&!(f=a.data(h[i++],"tmplItem")));if(f&&c)g[2]=function(b){a.tmpl.afterManip(this,b,k)};r.apply(this,g)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var i,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(j(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);i=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(j(c,null,i)):i},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){__=__.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(__,$1,$2);__=[];",close:"call=$item.calls();__=call._.concat($item.wrap(call,__));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){__.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){__.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function j(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:j(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=k(c).concat(b);if(d)b=b.concat(k(d))});return b?b:k(c)}function k(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,__=[],$data=$item.data;with($data){__.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,k,g,b,c,d){var j=a.tmpl.tag[k],i,e,f;if(!j)throw"Unknown template tag: "+k;i=j._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=h(b);d=d?","+h(d)+")":c?")":"";e=c?b.indexOf(".")>-1?b+h(c):"("+b+").call($item"+d:b;f=c?e:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else f=e=i.$1||"null";g=h(g);return"');"+j[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(f).split("$1").join(e).split("$2").join(g||i.$2||"")+"__.push('"})+"');}return __;")}function n(c,b){c._wrap=j(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function h(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,h;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(h=j.length-1;h>=0;h--)m(j[h]);m(k)}function m(j){var p,h=j,k,e,m;if(m=j.getAttribute(d)){while(h.parentNode&&(h=h.parentNode).nodeType===1&&!(p=h.getAttribute(d)));if(p!==m){h=h.parentNode?h.nodeType===11?0:h.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[h]||f[h]);e.key=++i;b[i]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;h=a.data(j.parentNode,"tmplItem");h=h?h.key:0}if(e){k=e;while(k&&k.key!=h){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);;
/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version 3.0.1
 *
 * Requires jQuery >= 1.2.6
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if ( typeof exports === 'object' ) {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    $.fn.bgiframe = function(s) {
        s = $.extend({
            top         : 'auto', // auto == borderTopWidth
            left        : 'auto', // auto == borderLeftWidth
            width       : 'auto', // auto == offsetWidth
            height      : 'auto', // auto == offsetHeight
            opacity     : true,
            src         : 'javascript:false;',
            conditional : /MSIE 6\.0/.test(navigator.userAgent) // expression or function. return false to prevent iframe insertion
        }, s);

        // wrap conditional in a function if it isn't already
        if ( !$.isFunction(s.conditional) ) {
            var condition = s.conditional;
            s.conditional = function() { return condition; };
        }

        var $iframe = $('<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
                           'style="display:block;position:absolute;z-index:-1;"/>');

        return this.each(function() {
            var $this = $(this);
            if ( s.conditional(this) === false ) { return; }
            var existing = $this.children('iframe.bgiframe');
            var $el = existing.length === 0 ? $iframe.clone() : existing;
            $el.css({
                'top': s.top == 'auto' ?
                    ((parseInt($this.css('borderTopWidth'),10)||0)*-1)+'px' : prop(s.top),
                'left': s.left == 'auto' ?
                    ((parseInt($this.css('borderLeftWidth'),10)||0)*-1)+'px' : prop(s.left),
                'width': s.width == 'auto' ? (this.offsetWidth + 'px') : prop(s.width),
                'height': s.height == 'auto' ? (this.offsetHeight + 'px') : prop(s.height),
                'opacity': s.opacity === true ? 0 : undefined
            });

            if ( existing.length === 0 ) {
                $this.prepend($el);
            }
        });
    };

    // old alias
    $.fn.bgIframe = $.fn.bgiframe;

    function prop(n) {
        return n && n.constructor === Number ? n + 'px' : n;
    }

}));
;
/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

/*global window, jQuery */
(function($) {
    // Default configuration properties.
    var defaults = {
        vertical: false,
        rtl: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        setupCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        animationStepCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null,
        itemFallbackDimension: null
    }, windowLoaded = false;

    $(window).on('load.jcarousel', function() { windowLoaded = true; });

    /**
     * The jCarousel object.
     *
     * @constructor
     * @class jcarousel
     * @param e {HTMLElement} The element to create the carousel for.
     * @param o {Object} A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked          = false;
        this.autoStopped     = false;

        this.container       = null;
        this.clip            = null;
        this.list            = null;
        this.buttonNext      = null;
        this.buttonPrev      = null;
        this.buttonNextState = null;
        this.buttonPrevState = null;

        // Only set if not explicitly passed as option
        if (!o || o.rtl === undefined) {
            this.options.rtl = ($(e).attr('dir') || $('html').attr('dir') || '').toLowerCase() == 'rtl';
        }

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? (this.options.rtl ? 'right' : 'left') : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                skin = split[i];
                break;
            }
        }

        if (e.nodeName.toUpperCase() == 'UL' || e.nodeName.toUpperCase() == 'OL') {
            this.list      = $(e);
            this.clip      = this.list.parents('.jcarousel-clip');
            this.container = this.list.parents('.jcarousel-container');
        } else {
            this.container = $(e);
            this.list      = this.container.find('ul,ol').eq(0);
            this.clip      = this.container.find('.jcarousel-clip');
        }

        if (this.clip.length === 0) {
            this.clip = this.list.wrap('<div></div>').parent();
        }

        if (this.container.length === 0) {
            this.container = this.clip.wrap('<div></div>').parent();
        }

        if (skin !== '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1) {
            this.container.wrap('<div class=" '+ skin + '"></div>');
        }

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.length === 0 && this.options.buttonPrevHTML !== null) {
            this.buttonPrev = $(this.options.buttonPrevHTML).appendTo(this.container);
        }

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.length === 0 && this.options.buttonNextHTML !== null) {
            this.buttonNext = $(this.options.buttonNextHTML).appendTo(this.container);
        }

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip')).css({
            position: 'relative'
        });

        this.list.addClass(this.className('jcarousel-list')).css({
            overflow: 'hidden',
            position: 'relative',
            top: 0,
            margin: 0,
            padding: 0
        }).css((this.options.rtl ? 'right' : 'left'), 0);

        this.container.addClass(this.className('jcarousel-container')).css({
            position: 'relative'
        });

        if (!this.options.vertical && this.options.rtl) {
            this.container.addClass('jcarousel-direction-rtl').attr('dir', 'rtl');
        }

        var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.length > 0) {
            var wh = 0, j = this.options.offset;
            li.each(function() {
                self.format(this, j++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, (wh + 100) + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined) {
                this.options.size = li.length;
            }
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); return false; };
        this.funcPrev   = function() { self.prev(); return false; };
        this.funcResize = function() {
            if (self.resizeTimer) {
                clearTimeout(self.resizeTimer);
            }

            self.resizeTimer = setTimeout(function() {
                self.reload();
            }, 100);
        };

        if (this.options.initCallback !== null) {
            this.options.initCallback(this, 'init');
        }

        if (!windowLoaded && $jc.isSafari()) {
            this.buttons(false, false);
            $(window).on('load.jcarousel', function() { self.setup(); });
        } else {
            this.setup();
        }
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.9'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @method setup
         * @return undefined
         */
        setup: function() {
            this.first       = null;
            this.last        = null;
            this.prevFirst   = null;
            this.prevLast    = null;
            this.animating   = false;
            this.timer       = null;
            this.resizeTimer = null;
            this.tail        = null;
            this.inTail      = false;

            if (this.locked) {
                return;
            }

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start, true);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).off('resize.jcarousel', this.funcResize).on('resize.jcarousel', this.funcResize);

            if (this.options.setupCallback !== null) {
                this.options.setupCallback(this);
            }
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @method reset
         * @return undefined
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback !== null) {
                this.options.initCallback(this, 'reset');
            }

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @method reload
         * @return undefined
         */
        reload: function() {
            if (this.tail !== null && this.inTail) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);
            }

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback !== null) {
                this.options.reloadCallback(this);
            }

            if (this.options.visible !== null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                this.list.children('li').each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first) {
                        lt = wh;
                    }
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @method lock
         * @return undefined
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @method unlock
         * @return undefined
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @method size
         * @return undefined
         * @param s {Number} The size of the carousel.
         */
        size: function(s) {
            if (s !== undefined) {
                this.options.size = s;
                if (!this.locked) {
                    this.buttons();
                }
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @method get
         * @return bool
         * @param i {Number} The index of the (first) element.
         * @param i2 {Number} The index of the last element.
         */
        has: function(i, i2) {
            if (i2 === undefined || !i2) {
                i2 = i;
            }

            if (this.options.size !== null && i2 > this.options.size) {
                i2 = this.options.size;
            }

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder')) {
                    return false;
                }
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @method get
         * @return jQuery
         * @param i {Number} The index of the element.
         */
        get: function(i) {
            return $('>.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @method add
         * @return jQuery
         * @param i {Number} The index of the element.
         * @param s {String} The innerHTML of the element.
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, n = $(s);

            if (e.length === 0) {
                var c, j = $jc.intval(i);
                e = this.create(i);
                while (true) {
                    c = this.get(--j);
                    if (j <= 0 || c.length) {
                        if (j <= 0) {
                            this.list.prepend(e);
                        } else {
                            c.after(e);
                        }
                        break;
                    }
                }
            } else {
                old = this.dimension(e);
            }

            if (n.get(0).nodeName.toUpperCase() == 'LI') {
                e.replaceWith(n);
                e = n;
            } else {
                e.empty().append(s);
            }

            this.format(e.removeClass(this.className('jcarousel-item-placeholder')), i);

            var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');
            }

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @method remove
         * @return undefined
         * @param i {Number} The index of the element.
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last)) {
                return;
            }

            var d = this.dimension(e);

            if (i < this.first) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');
            }

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @method next
         * @return undefined
         */
        next: function() {
            if (this.tail !== null && !this.inTail) {
                this.scrollTail(false);
            } else {
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size !== null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
            }
        },

        /**
         * Moves the carousel backwards.
         *
         * @method prev
         * @return undefined
         */
        prev: function() {
            if (this.tail !== null && this.inTail) {
                this.scrollTail(true);
            } else {
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size !== null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
            }
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @method scrollTail
         * @return undefined
         * @param b {Boolean} Whether scroll the tail back or forward.
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail) {
                return;
            }

            this.pauseAuto();

            var pos  = $jc.intval(this.list.css(this.lt));

            pos = !b ? pos - this.tail : pos + this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @method scroll
         * @return undefined
         * @param i {Number} The index of the element to scoll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        scroll: function(i, a) {
            if (this.locked || this.animating) {
                return;
            }

            this.pauseAuto();
            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @method pos
         * @return {Number}
         * @param i {Number} The index of the element to scoll to.
         * @param fv {Boolean} Whether to force last item to be visible.
         */
        pos: function(i, fv) {
            var pos  = $jc.intval(this.list.css(this.lt));

            if (this.locked || this.animating) {
                return pos;
            }

            if (this.options.wrap != 'circular') {
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);
            }

            var back = this.first > i;

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0, g;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length === 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);

                    if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length) {
                            e = this.add(j, g.clone(true));
                        }
                    }
                }

                c = e;
                d = this.dimension(e);

                if (p) {
                    l += d;
                }

                if (this.first !== null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size === null || j <= this.options.size)))) {
                    pos = back ? pos + d : pos - d;
                }
            }

            // Calculate visible items
            var clipping = this.clipping(), cache = [], visible = 0, v = 0;
            c = this.get(i - 1);
            j = i;

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length === 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    if (c.length === 0) {
                        this.list.prepend(e);
                    } else {
                        c[back ? 'before' : 'after' ](e);
                    }

                    if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length) {
                            e = this.add(j, g.clone(true));
                        }
                    }
                }

                c = e;
                d = this.dimension(e);
                if (d === 0) {
                    throw new Error('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size) {
                    cache.push(e);
                } else if (p) {
                    l += d;
                }

                v += d;

                if (v >= clipping) {
                    break;
                }

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++) {
                cache[x].remove();
            }

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size) {
                last = this.options.size;
            }

            if (j > last) {
                visible = 0;
                j = last;
                v = 0;
                while (++visible) {
                    e = this.get(j--);
                    if (!e.length) {
                        break;
                    }
                    v += this.dimension(e);
                    if (v >= clipping) {
                        break;
                    }
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1) {
                first = 1;
            }

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.intval(this.get(last).css(!this.options.vertical ? 'marginRight' : 'marginBottom'));
                if ((v - m) > clipping) {
                    this.tail = v - clipping - m;
                }
            }

            if (fv && i === this.options.size && this.tail) {
                pos -= this.tail;
                this.inTail = true;
            }

            // Adjust position
            while (i-- > first) {
                pos += this.dimension(this.get(i));
            }

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @method animate
         * @return undefined
         * @param p {Number} Position to scroll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        animate: function(p, a) {
            if (this.locked || this.animating) {
                return;
            }

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p === 0) {
                    self.list.css(self.lt,  0);
                }

                if (!self.autoStopped && (self.options.wrap == 'circular' || self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size === null || self.last < self.options.size || (self.last == self.options.size && self.tail !== null && !self.inTail))) {
                    self.startAuto();
                }

                self.buttons();
                self.notify('onAfterAnimation');

                // This function removes items which are appended automatically for circulation.
                // This prevents the list from growing infinitely.
                if (self.options.wrap == 'circular' && self.options.size !== null) {
                    for (var i = self.prevFirst; i <= self.prevLast; i++) {
                        if (i !== null && !(i >= self.first && i <= self.last) && (i < 1 || i > self.options.size)) {
                            self.remove(i);
                        }
                    }
                }
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a === false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? (this.options.rtl ? {'right': p} : {'left': p}) : {'top': p};
                // Define animation settings.
                var settings = {
                    duration: this.options.animation,
                    easing:   this.options.easing,
                    complete: scrolled
                };
                // If we have a step callback, specify it as well.
                if ($.isFunction(this.options.animationStepCallback)) {
                    settings.step = this.options.animationStepCallback;
                }
                // Start the animation.
                this.list.animate(o, settings);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @method auto
         * @return undefined
         * @param s {Number} Seconds to periodically autoscroll the content.
         */
        startAuto: function(s) {
            if (s !== undefined) {
                this.options.auto = s;
            }

            if (this.options.auto === 0) {
                return this.stopAuto();
            }

            if (this.timer !== null) {
                return;
            }

            this.autoStopped = false;

            var self = this;
            this.timer = window.setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @method stopAuto
         * @return undefined
         */
        stopAuto: function() {
            this.pauseAuto();
            this.autoStopped = true;
        },

        /**
         * Pauses autoscrolling.
         *
         * @method pauseAuto
         * @return undefined
         */
        pauseAuto: function() {
            if (this.timer === null) {
                return;
            }

            window.clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @method buttons
         * @return undefined
         */
        buttons: function(n, p) {
            if (n == null) {
                n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size === null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size !== null && this.last >= this.options.size) {
                    n = this.tail !== null && !this.inTail;
                }
            }

            if (p == null) {
                p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size !== null && this.first == 1) {
                    p = this.tail !== null && this.inTail;
                }
            }

            var self = this;

            if (this.buttonNext.length > 0) {
                this.buttonNext.off(this.options.buttonNextEvent + '.jcarousel', this.funcNext);

                if (n) {
                    this.buttonNext.on(this.options.buttonNextEvent + '.jcarousel', this.funcNext);
                }

                this.buttonNext[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);

                if (this.options.buttonNextCallback !== null && this.buttonNext.data('jcarouselstate') != n) {
                    this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); }).data('jcarouselstate', n);
                }
            } else {
                if (this.options.buttonNextCallback !== null && this.buttonNextState != n) {
                    this.options.buttonNextCallback(self, null, n);
                }
            }

            if (this.buttonPrev.length > 0) {
                this.buttonPrev.off(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);

                if (p) {
                    this.buttonPrev.on(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);
                }

                this.buttonPrev[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

                if (this.options.buttonPrevCallback !== null && this.buttonPrev.data('jcarouselstate') != p) {
                    this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); }).data('jcarouselstate', p);
                }
            } else {
                if (this.options.buttonPrevCallback !== null && this.buttonPrevState != p) {
                    this.options.buttonPrevCallback(self, null, p);
                }
            }

            this.buttonNextState = n;
            this.buttonPrevState = p;
        },

        /**
         * Notify callback of a specified event.
         *
         * @method notify
         * @return undefined
         * @param evt {String} The event name
         */
        notify: function(evt) {
            var state = this.prevFirst === null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == null || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation')) {
                return;
            }

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback)) {
                return;
            }

            var self = this;

            if (i1 === undefined) {
                callback(self, state, evt);
            } else if (i2 === undefined) {
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            } else {
                var call = function(i) {
                    self.get(i).each(function() { callback(self, this, i, state, evt); });
                };
                for (var i = i1; i <= i2; i++) {
                    if (i !== null && !(i >= i3 && i <= i4)) {
                        call(i);
                    }
                }
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            e = $(e);
            var split = e.get(0).className.split(' ');
            for (var j = 0; j < split.length; j++) {
                if (split[j].indexOf('jcarousel-') != -1) {
                    e.removeClass(split[j]);
                }
            }
            e.addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i)).css({
                'float': (this.options.rtl ? 'right' : 'left'),
                'list-style': 'none'
            }).attr('jcarouselindex', i);
            return e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = $(e);

            if (d == null) {
                return !this.options.vertical ?
                    ((el.innerWidth() +
                        $jc.intval(el.css('margin-left')) +
                        $jc.intval(el.css('margin-right')) +
                        $jc.intval(el.css('border-left-width')) +
                        $jc.intval(el.css('border-right-width'))) || $jc.intval(this.options.itemFallbackDimension)) :
                    ((el.innerHeight() +
                        $jc.intval(el.css('margin-top')) +
                        $jc.intval(el.css('margin-bottom')) +
                        $jc.intval(el.css('border-top-width')) +
                        $jc.intval(el.css('border-bottom-width'))) || $jc.intval(this.options.itemFallbackDimension));
            } else {
                var w = !this.options.vertical ?
                    d - $jc.intval(el.css('marginLeft')) - $jc.intval(el.css('marginRight')) :
                    d - $jc.intval(el.css('marginTop')) - $jc.intval(el.css('marginBottom'));

                $(el).css(this.wh, w + 'px');

                return this.dimension(el);
            }
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == null) {
                s = this.options.size;
            }

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @method defaults
         * @return {Object}
         * @param d {Object} A set of key/value pairs to set as configuration properties.
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        intval: function(v) {
            v = parseInt(v, 10);
            return isNaN(v) ? 0 : v;
        },

        windowLoaded: function() {
            windowLoaded = true;
        },

        isSafari: function() {
            var ua = navigator.userAgent.toLowerCase(),
                match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || [],
                browser = match[1] || "";

            return browser === 'webkit';
        }
    });

    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *   </div>
     * </div>
     *
     * @method jcarousel
     * @return jQuery
     * @param o {Hash|String} A set of key/value pairs to set as configuration properties or a method name to call on a formerly created instance.
     */
    $.fn.jcarousel = function(o) {
        if (typeof o == 'string') {
            var instance = $(this).data('jcarousel'), args = Array.prototype.slice.call(arguments, 1);
            return instance[o].apply(instance, args);
        } else {
            return this.each(function() {
                var instance = $(this).data('jcarousel');
                if (instance) {
                    if (o) {
                        $.extend(instance.options, o);
                    }
                    instance.reload();
                } else {
                    $(this).data('jcarousel', new $jc(this, o));
                }
            });
        }
    };

})(jQuery);
;
/*
* jquery.spellchecker.js - a simple jQuery Spell Checker
* Copyright (c) 2009 Richard Willis
* MIT license  : http://www.opensource.org/licenses/mit-license.php
* Project      : http://jquery-spellchecker.googlecode.com
* Contact      : willis.rh@gmail.com
*/

(function ($) {

    $.fn.extend({

        spellchecker: function (options, callback) {
            return this.each(function () {
                var obj = $(this).data('spellchecker');
                if (obj && String === options.constructor && obj[options]) {
                    obj[options](callback);
                } else if (obj) {
                    obj.init();
                } else {
                    $(this).data('spellchecker', new SpellChecker(this, (Object === options.constructor ? options : null)));
                    (String === options.constructor) && $(this).data('spellchecker')[options](callback);
                }
            });
        }
    });

    var SpellChecker = function (domObj, options) {
        this.options = $.extend({
            url: '/Scripts/netspell/netspell.ashx', // default spellcheck url
            lang: 'en', 		// default language 
            engine: 'pspell', 	// pspell or google
            addToDictionary: false, 	// display option to add word to dictionary (pspell only)
            wordlist: {
                action: 'after', // which jquery dom insert action
                element: domObj		// which object to apply above method
            },
            suggestBoxPosition: 'below', // position of suggest box; above or below the highlighted word
            innerDocument: true		// if you want the badwords highlighted in the html then set to true
        }, options || {});
        this.$domObj = $(domObj);
        this.elements = {};
        this.init();
    };

    SpellChecker.prototype = {

        init: function () {
            var self = this;
            this.createElements();
            this.$domObj.addClass('spellcheck-container');
            // hide the suggest box on document click
            $(document).bind('click', function (e) {
                (!$(e.target).hasClass('spellcheck-word-highlight') &&
				!$(e.target).parents().filter('.spellcheck-suggestbox').length) &&
				self.hideBox();
            });
        },

        // checks a chunk of text for bad words, then either shows the words below the original element (if texarea) or highlights the bad words
        check: function (callback) {

            var self = this, node = this.$domObj.get(0).nodeName,
			tagExp = '<[^>]+>',
			puncExp = '^[^a-zA-Z\\u00A1-\\uFFFF]|[^a-zA-Z\\u00A1-\\uFFFF]+[^a-zA-Z\\u00A1-\\uFFFF]|[^a-zA-Z\\u00A1-\\uFFFF]$|\\n|\\t|\\s{2,}';

            if (node == 'TEXTAREA' || node == 'INPUT') {
                this.type = 'textarea';
                var text = $.trim(
					this.$domObj.val()
					.replace(new RegExp(tagExp, 'g'), '')	// strip html tags
					.replace(new RegExp(puncExp, 'g'), ' ') // strip punctuation
				);
            } else {
                this.type = 'html';
                var text = $.trim(
					this.$domObj.text()
					.replace(new RegExp(puncExp, 'g'), " ") // strip punctuation
				);
            }
            this.postJson(this.options.url, {
                text: encodeURIComponent(text).replace(/%20/g, '+')
            }, function (json) {
                self.type == 'html' && self.options.innerDocument ?
				self.highlightWords(json, callback) :
				self.buildBadwordsBox(json, callback);
            });
        },

        highlightWords: function (json, callback) {
            if (!json.length) { callback.call(this.$domObj, true); return; }

            var self = this, html = this.$domObj.html();

            $.each(json, function (key, replaceWord) {
                html = html.replace(
					new RegExp('([^a-zA-Z\\u00A1-\\uFFFF])(' + replaceWord + ')([^a-zA-Z\\u00A1-\\uFFFF])', 'g'),
					'$1<span class="spellcheck-word-highlight">$2</span>$3'
				);
            });
            this.$domObj.html(html).find('.spellcheck-word-highlight').each(function () {
                self.elements.highlightWords.push(
					$(this).click(function () {
					    self.suggest(this);
					})
				);
            });
            (callback) && callback();
        },

        buildBadwordsBox: function (json, callback) {
            if (!json.length) { callback.call(this.$domObj, true); return; }

            var self = this, words = [];

            // insert badwords list into dom
            $(this.options.wordlist.element)[this.options.wordlist.action](this.elements.$badwords);

            // empty the badwords container
            this.elements.$badwords.empty()

            // append incorrectly spelt words
            $.each(json, function (key, badword) {
                if ($.inArray(badword, words) === -1) {
                    self.elements.highlightWords.push(
						$('<span class="spellcheck-word-highlight">' + badword + '</span>')
						.click(function () { self.suggest(this); })
						.appendTo(self.elements.$badwords)
						.after('<span class="spellcheck-sep">,</span> ')
					);
                    words.push(badword);
                }
            });
            $('.spellcheck-sep:last', self.elements.$badwords).addClass('spellcheck-sep-last');
            (callback) && callback();
        },

        // gets a list of suggested words, appends to the suggestbox and shows the suggestbox
        suggest: function (word) {

            var self = this, $word = $(word), offset = $word.offset();
            this.$curWord = $word;

            if (this.options.innerDocument) {
                this.elements.$suggestBox = this.elements.$body.find('.spellcheck-suggestbox');
                this.elements.$suggestWords = this.elements.$body.find('.spellcheck-suggestbox-words');
                this.elements.$suggestFoot = this.elements.$body.find('.spellcheck-suggestbox-foot');
            }

            this.elements.$suggestFoot.hide();
            this.elements.$suggestBox
			.stop().hide()
			.css({
			    opacity: 1,
			    width: "auto",
			    left: offset.left + "px",
			    top:
					(this.options.suggestBoxPosition == "above" ?
					(offset.top - ($word.outerHeight() + 10)) + "px" :
					(offset.top + $word.outerHeight()) + "px")
			}).fadeIn(200);

            this.elements.$suggestWords.html('<em>Loading..</em>');

            this.postJson(this.options.url, {
                suggest: encodeURIComponent($.trim($word.text()))
            }, function (json) {
                self.buildSuggestBox(json, offset);
            });
        },

        buildSuggestBox: function (json, offset) {

            var self = this, $word = this.$curWord;

            this.elements.$suggestWords.empty();

            // build suggest word list
            for (var i = 0; i < (json.length < 5 ? json.length : 5); i++) {
                this.elements.$suggestWords.append(
					$('<a href="#">' + json[i] + '</a>')
					.addClass((!i ? 'first' : ''))
					.click(function () { return false; })
					.mousedown(function (e) {
					    e.preventDefault();
					    self.replace(this.innerHTML);
					    self.hideBox();
					})
				);
            }

            // no word suggestions
            (!i) && this.elements.$suggestWords.append('<em>(no suggestions)</em>');

            // get browser viewport height
            var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();

            this.elements.$suggestFoot.show();

            // position the suggest box
            self.elements.$suggestBox
			.css({
			    top: (this.options.suggestBoxPosition == 'above') ||
					(offset.top + $word.outerHeight() + this.elements.$suggestBox.outerHeight() > viewportHeight + 10) ?
					(offset.top - (this.elements.$suggestBox.height() + 5)) + "px" :
					(offset.top + $word.outerHeight() + "px"),
			    width: 'auto',
			    left: (this.elements.$suggestBox.outerWidth() + offset.left > $('body').width() ?
					(offset.left - this.elements.$suggestBox.width()) + $word.outerWidth() + 'px' :
					offset.left + 'px')
			});

        },

        // hides the suggest box	
        hideBox: function (callback) {
            this.elements.$suggestBox.fadeOut(250, function () {
                (callback) && callback();
            });
        },

        // replace incorrectly spelt word with suggestion
        replace: function (replace) {
            switch (this.type) {
                case 'textarea': this.replaceTextbox(replace); break;
                case 'html': this.replaceHtml(replace); break;
            }
        },

        // replaces a word string in a chunk of text
        replaceWord: function (text, replace) {
            return text
				.replace(
					new RegExp("([^a-zA-Z\\u00A1-\\uFFFF]?)(" + this.$curWord.text() + ")([^a-zA-Z\\u00A1-\\uFFFF]?)", "g"),
					'$1' + replace + '$3'
				)
				.replace(
					new RegExp("^(" + this.$curWord.text() + ")([^a-zA-Z\\u00A1-\\uFFFF])", "g"),
					replace + '$2'
				)
				.replace(
					new RegExp("([^a-zA-Z\\u00A1-\\uFFFF])(" + this.$curWord.text() + ")$", "g"),
					'$1' + replace
				);
        },

        // replace word in a textarea
        replaceTextbox: function (replace) {
            this.removeBadword(this.$curWord);
            this.$domObj.val(
				this.replaceWord(this.$domObj.val(), replace)
			);
        },

        // replace word in an HTML container
        replaceHtml: function (replace) {
            var words = this.$domObj.find('.spellcheck-word-highlight:contains(' + this.$curWord.text() + ')')
            if (words.length) {
                words.after(replace).remove();
            } else {
                $(this.$domObj).html(
					this.replaceWord($(this.$domObj).html(), replace)
				);
                this.removeBadword(this.$curWord);
            }
        },

        // remove spelling formatting from word to ignore in original element
        ignore: function () {
            if (this.type == 'textarea') {
                this.removeBadword(this.$curWord);
            } else {
                this.$curWord.after(this.$curWord.html()).remove();
            }
        },

        // remove spelling formatting from all words to ignore in original element
        ignoreAll: function () {
            var self = this;
            if (this.type == 'textarea') {
                this.removeBadword(this.$curWord);
            } else {
                //to-do: disable 
                if (typeof self.$curWord != 'undefined') {
                    $('.spellcheck-word-highlight', this.$domObj).each(function () {
                        (new RegExp(self.$curWord.text(), 'i').test(this.innerHTML)) &&
					$(this).after(this.innerHTML).remove(); // remove anchor
                    });
                }
            }
        },

        removeBadword: function ($domObj) {
            ($domObj.next().hasClass('spellcheck-sep')) && $domObj.next().remove();
            $domObj.remove();
            if (!$('.spellcheck-sep', this.elements.$badwords).length) {
                this.elements.$badwords.remove();
            } else {
                $('.spellcheck-sep:last', this.elements.$badwords).addClass('spellcheck-sep-last');
            }
        },

        // add word to personal dictionary (pspell only)
        addToDictionary: function () {
            var self = this;
            this.hideBox(function () {
                confirm('Are you sure you want to add the word "' + self.$curWord.text() + '" to the dictionary?') &&
				self.postJson(self.options.url, { addtodictionary: self.$curWord.text() }, function () {
				    self.ignoreAll();
				    self.check();
				});
            });
        },

        // remove spell check formatting
        remove: function (destroy) {
            destroy = destroy || true;
            $.each(this.elements.highlightWords, function (val) {
                this.after(this.innerHTML).remove()
            });
            this.elements.$badwords.remove();
            this.elements.$suggestBox.remove();
            $(this.domObj).removeClass('spellcheck-container');
            (destroy) && $(this.domObj).data('spellchecker', null);
        },

        // sends post request, return JSON object
        postJson: function (url, data, callback) {
            var xhr = $.ajax({
                type: 'POST',
                url: url,
                data: $.extend(data, {
                    engine: this.options.engine,
                    lang: this.options.lang
                }),
                dataType: 'json',
                cache: false,
                error: function (XHR, status, error) {
                    alert('Sorry, there was an error processing the request.');
                },
                success: function (json) {
                    (callback) && callback(json);
                }
            });
            return xhr;
        },

        // create the spellchecker elements, prepend to body
        createElements: function () {
            var self = this;

            this.elements.$body = this.options.innerDocument ? this.$domObj.parents().filter('html:first').find("body") : $('body');
            this.elements.highlightWords = [];
            this.elements.$suggestWords = this.elements.$suggestWords ||
				$('<div></div>').addClass('spellcheck-suggestbox-words');
            this.elements.$ignoreWord = this.elements.$ignoreWord ||
				$('<a href="#">Ignore Word</a>')
				.click(function (e) {
				    e.preventDefault();
				    self.ignore();
				    self.hideBox();
				});
            this.elements.$ignoreAllWords = this.elements.$ignoreAllWords ||
				$('<a href="#">Ignore all</a>')
				.click(function (e) {
				    e.preventDefault();
				    self.ignoreAll();
				    self.hideBox();
				});
            this.elements.$ignoreWordsForever = this.elements.$ignoreWordsForever ||
				$('<a href="#" title="ignore word forever (add to dictionary)">Ignore forever</a>')
				.click(function (e) {
				    e.preventDefault();
				    self.addToDictionary();
				    self.hideBox();
				});
            this.elements.$suggestFoot = this.elements.$suggestFoot ||
				$('<div></div>').addClass('spellcheck-suggestbox-foot')
				.append(this.elements.$ignoreWord)
				.append(this.elements.$ignoreAllWords)
				.append(this.options.engine == "pspell" && self.options.addToDictionary ? this.elements.$ignoreWordsForever : false);
            this.elements.$badwords = this.elements.$badwords ||
				$('<div></div>').addClass('spellcheck-badwords');
            this.elements.$suggestBox = this.elements.$suggestBox ||
				$('<div></div>').addClass('spellcheck-suggestbox')
				.append(this.elements.$suggestWords)
				.append(this.elements.$suggestFoot)
				.prependTo(this.elements.$body);
        }
    };

})(jQuery);
;
/* jQuery jqEasyCharCounter plugin
 * Examples and documentation at: http://www.jqeasy.com/
 * Version: 1.0 (05/07/2010)
 * No license. Use it however you want. Just keep this notice included.
 * Requires: jQuery v1.3+
 *
 * 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 ($) {

    $.fn.extend({
        jqEasyCounter: function (givenOptions) {
            return this.each(function () {
                var $this = $(this),
                options = $.extend({
                    maxChars: 0,
                    //                    maxCharsWarning: 80,
                    //                    msgFontSize: '12px',
                    //                    msgFontColor: '#000000',
                    //                    msgFontFamily: 'Arial',
                    //                    msgTextAlign: 'right',
                    //                    msgWarningColor: '#F00',
                    msgAppendMethod: 'insertAfter'
                }, givenOptions);

                // try getting the length from the input itself
                if (options.maxChars <= 0) {
                    if ($this.data('val-length-max'))
                        options.maxChars = $this.data('val-length-max');
                    else if ($this.attr('maxlength'))
                        options.maxChars = $this.attr('maxlength');
                }

                if (options.maxChars <= 0) return;

                // create counter element
                var jqEasyCounterMsg = $("<span class=\"hint\">&nbsp;</span>");
                var jqEasyCounterMsgStyle = {
                    'font-size': options.msgFontSize,
                    'font-family': options.msgFontFamily,
                    'color': options.msgFontColor,
                    'text-align': options.msgTextAlign,
                    //                    'width': $this.width(),
                    'opacity': 0
                };
                jqEasyCounterMsg.css(jqEasyCounterMsgStyle);
                // append counter element to DOM
                jqEasyCounterMsg[options.msgAppendMethod]($this);

                // bind events to this element
                $this
				.bind('keydown keyup keypress', doCount)
				.bind('focus paste', function () { setTimeout(doCount, 10); })
                .bind('blur', function () { jqEasyCounterMsg.stop().fadeTo('fast', 0); return false; });

                function doCount() {
                    var val = $this.val(),
					length = val.length

                    if (length >= options.maxChars) {
                        val = val.substring(0, options.maxChars);
                    };

                    if (length > options.maxChars) {
                        // keep scroll bar position
                        var originalScrollTopPosition = $this.scrollTop();
                        $this.val(val.substring(0, options.maxChars));
                        $this.scrollTop(originalScrollTopPosition);
                    };

                    if (length >= options.maxCharsWarning) {
                        jqEasyCounterMsg.css({ "color": options.msgWarningColor });
                    } else {
                        jqEasyCounterMsg.css({ "color": options.msgFontColor });
                    };

                    var charsRemaining = (options.maxChars - $this.val().length);
                    if (charsRemaining > 1)
                        jqEasyCounterMsg.html(options.maxChars - $this.val().length + " characters remaining");
                    else if (charsRemaining < 1)
                        jqEasyCounterMsg.html("0 characters remaining"); // cater for negative case
                    else
                        jqEasyCounterMsg.html("1 character remaining");
                    jqEasyCounterMsg.stop().fadeTo('fast', 1);
                };
            });
        }
    });

})(jQuery);;
(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function o(e){e.minTime&&(e.minTime=S(e.minTime)),e.maxTime&&(e.maxTime=S(e.maxTime)),e.durationTime&&typeof e.durationTime!="function"&&(e.durationTime=S(e.durationTime));if(e.disableTimeRanges.length>0){for(var t in e.disableTimeRanges)e.disableTimeRanges[t]=[S(e.disableTimeRanges[t][0]),S(e.disableTimeRanges[t][1])];e.disableTimeRanges=e.disableTimeRanges.sort(function(e,t){return e[0]-t[0]})}return e}function u(t){var r=t.data("timepicker-settings"),i=t.data("timepicker-list");i&&i.length&&(i.remove(),t.data("timepicker-list",!1)),i=e("<ul />",{"class":"ui-timepicker-list"});var o=e("<div />",{"class":"ui-timepicker-wrapper",tabindex:-1});o.css({display:"none",position:"absolute"}).append(i),r.className&&o.addClass(r.className),(r.minTime!==null||r.durationTime!==null)&&r.showDuration&&o.addClass("ui-timepicker-with-duration");var u=r.minTime;typeof r.durationTime=="function"?u=S(r.durationTime()):r.durationTime!==null&&(u=r.durationTime);var a=r.minTime!==null?r.minTime:0,f=r.maxTime!==null?r.maxTime:a+n-1;f<=a&&(f+=n);var l=r.disableTimeRanges,c=0,p=l.length;for(var d=a;d<=f;d+=r.step*60){var v=d%n,m=e("<li />");m.data("time",v),m.text(E(v,r.timeFormat));if((r.minTime!==null||r.durationTime!==null)&&r.showDuration){var g=e("<span />");g.addClass("ui-timepicker-duration"),g.text(" ("+w(d-u)+")"),m.append(g)}c<p&&(v>=l[c][0]&&v<l[c][1]?m.addClass("ui-timepicker-disabled"):v>=l[c][1]&&(c+=1)),i.append(m)}o.data("timepicker-input",t),t.data("timepicker-list",o);var y=r.appendTo;typeof y=="string"?y=e(y):typeof y=="function"&&(y=y(t)),y.append(o),h(t,i),i.on("click","li",function(n){t.off("focus.timepicker"),t.on("focus.timepicker-ie-hack",function(){t.off("focus.timepicker-ie-hack"),t.on("focus.timepicker",s.show)}),t[0].focus(),i.find("li").removeClass("ui-timepicker-selected"),e(this).addClass("ui-timepicker-selected"),b(t)&&o.hide()})}function a(){return new Date(1970,1,1,0,0,0)}function f(t){"ontouchstart"in document?e("body").on("touchstart.ui-timepicker",l):(e("body").on("mousedown.ui-timepicker",l),t.closeOnWindowScroll&&e(window).on("scroll.ui-timepicker",l))}function l(t){var n=e(t.target),r=n.closest(".ui-timepicker-input");r.length===0&&n.closest(".ui-timepicker-wrapper").length===0&&(s.hide(),e("body").unbind(".ui-timepicker"),e(window).unbind(".ui-timepicker"))}function c(t,n,r){if(!r&&r!==0)return!1;var i=t.data("timepicker-settings"),s=!1,o=i.step*30;return n.find("li").each(function(t,n){var i=e(n),u=i.data("time")-r;if(Math.abs(u)<o||u==o)return s=i,!1}),s}function h(e,t){t.find("li").removeClass("ui-timepicker-selected");var n=S(d(e));if(!n)return;var r=c(e,t,n);if(r){var i=r.offset().top-t.offset().top;(i+r.outerHeight()>t.outerHeight()||i<0)&&t.scrollTop(t.scrollTop()+r.position().top-r.outerHeight()),r.addClass("ui-timepicker-selected")}}function p(){if(this.value==="")return;var t=e(this),n=S(this.value);if(n===null){t.trigger("timeFormatError");return}var r=t.data("timepicker-settings");r.minTime!==null&&n<r.minTime?t.trigger("timeRangeError"):r.maxTime!==null&&n>r.maxTime&&t.trigger("timeRangeError"),e.each(r.disableTimeRanges,function(){if(n>=this[0]&&n<this[1])return t.trigger("timeRangeError"),!1});if(r.forceRoundTime){var i=n%(r.step*60);i>=r.step*30?n+=r.step*60-i:n-=i}var s=E(n,r.timeFormat);v(t,s)}function d(e){return e.is("input")?e.val():e.data("ui-timepicker-value")}function v(e,t){e.is("input")?e.val(t):e.data("ui-timepicker-value",t)}function m(t){var n=e(this),r=n.data("timepicker-list");if(!r||!r.is(":visible")){if(t.keyCode!=40)return g(t,n);n.focus()}switch(t.keyCode){case 13:return b(n)&&s.hide.apply(this),t.preventDefault(),!1;case 38:var i=r.find(".ui-timepicker-selected");return i.length?i.is(":first-child")||(i.removeClass("ui-timepicker-selected"),i.prev().addClass("ui-timepicker-selected"),i.prev().position().top<i.outerHeight()&&r.scrollTop(r.scrollTop()-i.outerHeight())):(r.find("li").each(function(t,n){if(e(n).position().top>0)return i=e(n),!1}),i.addClass("ui-timepicker-selected")),!1;case 40:return i=r.find(".ui-timepicker-selected"),i.length===0?(r.find("li").each(function(t,n){if(e(n).position().top>0)return i=e(n),!1}),i.addClass("ui-timepicker-selected")):i.is(":last-child")||(i.removeClass("ui-timepicker-selected"),i.next().addClass("ui-timepicker-selected"),i.next().position().top+2*i.outerHeight()>r.outerHeight()&&r.scrollTop(r.scrollTop()+i.outerHeight())),!1;case 27:r.find("li").removeClass("ui-timepicker-selected"),r.hide();break;case 9:s.hide();break;default:return g(t,n)}}function g(e,t){return!t.data("timepicker-settings").disableTextInput||e.ctrlKey||e.altKey||e.metaKey||e.keyCode!=2&&(e.keyCode<46||e.keyCode>90)}function y(t){var n=e(this),r=n.data("timepicker-list");if(!r||!r.is(":visible"))return!0;switch(t.keyCode){case 96:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 65:case 77:case 80:case 186:case 8:case 46:h(n,r);break;default:return}}function b(e){var t=e.data("timepicker-settings"),n=e.data("timepicker-list"),r=null,i=n.find(".ui-timepicker-selected");if(i.hasClass("ui-timepicker-disabled"))return!1;i.length?r=i.data("time"):d(e)&&(r=S(d(e)),h(e,n));if(r!==null){var s=E(r,t.timeFormat);v(e,s)}return e.trigger("change").trigger("changeTime"),!0}function w(e){var t=Math.round(e/60),n;if(Math.abs(t)<60)n=[t,i.mins];else if(t==60)n=["1",i.hr];else{var r=(t/60).toFixed(1);i.decimal!="."&&(r=r.replace(".",i.decimal)),n=[r,i.hrs]}return n.join(" ")}function E(e,n){if(e===null)return;var r=new Date(t.valueOf()+e*1e3),i="",s,o;for(var u=0;u<n.length;u++){o=n.charAt(u);switch(o){case"a":i+=r.getHours()>11?"pm":"am";break;case"A":i+=r.getHours()>11?"PM":"AM";break;case"g":s=r.getHours()%12,i+=s===0?"12":s;break;case"G":i+=r.getHours();break;case"h":s=r.getHours()%12,s!==0&&s<10&&(s="0"+s),i+=s===0?"12":s;break;case"H":s=r.getHours(),i+=s>9?s:"0"+s;break;case"i":var a=r.getMinutes();i+=a>9?a:"0"+a;break;case"s":e=r.getSeconds(),i+=e>9?e:"0"+e;break;default:i+=o}}return i}function S(e){if(e==="")return null;if(!e||e+0==e)return e;typeof e=="object"&&(e=e.getHours()+":"+x(e.getMinutes())+":"+x(e.getSeconds())),e=e.toLowerCase();var t=new Date(0),n;e.indexOf(":")===-1?(n=e.match(/^([0-9]):?([0-5][0-9])?:?([0-5][0-9])?\s*([pa]?)m?$/),n||(n=e.match(/^([0-2][0-9]):?([0-5][0-9])?:?([0-5][0-9])?\s*([pa]?)m?$/))):n=e.match(/^(\d{1,2})(?::([0-5][0-9]))?(?::([0-5][0-9]))?\s*([pa]?)m?$/);if(!n)return null;var r=parseInt(n[1]*1,10),i;n[4]?r==12?i=n[4]=="p"?12:0:i=r+(n[4]=="p"?12:0):i=r;var s=n[2]*1||0,o=n[3]*1||0;return i*3600+s*60+o}function x(e){return("0"+e).slice(-2)}var t=a(),n=86400,r={className:null,minTime:null,maxTime:null,durationTime:null,step:30,showDuration:!1,timeFormat:"g:ia",scrollDefaultNow:!1,scrollDefaultTime:!1,selectOnBlur:!1,disableTouchKeyboard:!0,forceRoundTime:!1,appendTo:"body",disableTimeRanges:[],closeOnWindowScroll:!1,disableTextInput:!1},i={decimal:".",mins:"mins",hr:"hr",hrs:"hrs"},s={init:function(t){return this.each(function(){var n=e(this);if(n[0].tagName=="SELECT"){var u={type:"text",value:n.val()},a=n[0].attributes;for(var f=0;f<a.length;f++)u[a[f].nodeName]=a[f].nodeValue;var l=e("<input />",u);n.replaceWith(l),n=l}var c=e.extend({},r);t&&(c=e.extend(c,t)),c.lang&&(i=e.extend(i,c.lang)),c=o(c),n.data("timepicker-settings",c),n.prop("autocomplete","off"),n.on("click.timepicker focus.timepicker",s.show),n.on("blur.timepicker",p),n.on("keydown.timepicker",m),n.on("keyup.timepicker",y),n.addClass("ui-timepicker-input"),p.call(n.get(0))})},show:function(t){var n=e(this),r=n.data("timepicker-settings");"ontouchstart"in document&&r.disableTouchKeyboard&&n.blur();var i=n.data("timepicker-list");if(n.prop("readonly"))return;if(!i||i.length===0||typeof r.durationTime=="function")u(n),i=n.data("timepicker-list");if(i.is(":visible"))return;s.hide(),i.show(),n.offset().top+n.outerHeight(!0)+i.outerHeight()>e(window).height()+e(window).scrollTop()?i.offset({left:n.offset().left+parseInt(i.css("marginLeft").replace("px",""),10),top:n.offset().top-i.outerHeight()+parseInt(i.css("marginTop").replace("px",""),10)}):i.offset({left:n.offset().left+parseInt(i.css("marginLeft").replace("px",""),10),top:n.offset().top+n.outerHeight()+parseInt(i.css("marginTop").replace("px",""),10)});var o=i.find(".ui-timepicker-selected");o.length||(d(n)?o=c(n,i,S(d(n))):r.scrollDefaultNow?o=c(n,i,S(new Date)):r.scrollDefaultTime!==!1&&(o=c(n,i,S(r.scrollDefaultTime))));if(o&&o.length){var a=i.scrollTop()+o.position().top-o.outerHeight();i.scrollTop(a)}else i.scrollTop(0);f(r),n.trigger("showTimepicker")},hide:function(t){e(".ui-timepicker-wrapper:visible").each(function(){var t=e(this),n=t.data("timepicker-input"),r=n.data("timepicker-settings");r&&r.selectOnBlur&&b(n),t.hide(),n.trigger("hideTimepicker")})},option:function(t,n){var r=this,i=r.data("timepicker-settings"),s=r.data("timepicker-list");if(typeof t=="object")i=e.extend(i,t);else if(typeof t=="string"&&typeof n!="undefined")i[t]=n;else if(typeof t=="string")return i[t];return i=o(i),r.data("timepicker-settings",i),s&&(s.remove(),r.data("timepicker-list",!1)),r},getSecondsFromMidnight:function(){return S(d(this))},getTime:function(){var e=this,t=new Date;return t.setHours(0,0,0,0),new Date(t.valueOf()+S(d(e))*1e3)},setTime:function(e){var t=this,n=E(S(e),t.data("timepicker-settings").timeFormat);v(t,n)},remove:function(){var e=this;if(!e.hasClass("ui-timepicker-input"))return;e.removeAttr("autocomplete","off"),e.removeClass("ui-timepicker-input"),e.removeData("timepicker-settings"),e.off(".timepicker"),e.data("timepicker-list")&&e.data("timepicker-list").remove(),e.removeData("timepicker-list")}};e.fn.timepicker=function(t){if(s[t])return s[t].apply(this,Array.prototype.slice.call(arguments,1));if(typeof t=="object"||!t)return s.init.apply(this,arguments);e.error("Method "+t+" does not exist on jQuery.timepicker")}});;
!function(e){e(["jquery"],function(e){return function(){function t(e,t,n){return f({type:O.error,iconClass:g().iconClasses.error,message:e,optionsOverride:n,title:t})}function n(t,n){return t||(t=g()),v=e("#"+t.containerId),v.length?v:(n&&(v=c(t)),v)}function i(e,t,n){return f({type:O.info,iconClass:g().iconClasses.info,message:e,optionsOverride:n,title:t})}function o(e){w=e}function s(e,t,n){return f({type:O.success,iconClass:g().iconClasses.success,message:e,optionsOverride:n,title:t})}function a(e,t,n){return f({type:O.warning,iconClass:g().iconClasses.warning,message:e,optionsOverride:n,title:t})}function r(e){var t=g();v||n(t),l(e,t)||u(t)}function d(t){var i=g();return v||n(i),t&&0===e(":focus",t).length?void h(t):void(v.children().length&&v.remove())}function u(t){for(var n=v.children(),i=n.length-1;i>=0;i--)l(e(n[i]),t)}function l(t,n){return t&&0===e(":focus",t).length?(t[n.hideMethod]({duration:n.hideDuration,easing:n.hideEasing,complete:function(){h(t)}}),!0):!1}function c(t){return v=e("<div/>").attr("id",t.containerId).addClass(t.positionClass).attr("aria-live","polite").attr("role","alert"),v.appendTo(e(t.target)),v}function p(){return{tapToDismiss:!0,toastClass:"toast",containerId:"toast-container",debug:!1,showMethod:"fadeIn",showDuration:300,showEasing:"swing",onShown:void 0,hideMethod:"fadeOut",hideDuration:1e3,hideEasing:"swing",onHidden:void 0,extendedTimeOut:1e3,iconClasses:{error:"toast-error",info:"toast-info",success:"toast-success",warning:"toast-warning"},iconClass:"toast-info",positionClass:"toast-top-right",timeOut:5e3,titleClass:"toast-title",messageClass:"toast-message",target:"body",closeHtml:'<button type="button">&times;</button>',newestOnTop:!0,preventDuplicates:!1,progressBar:!1}}function m(e){w&&w(e)}function f(t){function i(t){return!e(":focus",l).length||t?(clearTimeout(O.intervalId),l[r.hideMethod]({duration:r.hideDuration,easing:r.hideEasing,complete:function(){h(l),r.onHidden&&"hidden"!==b.state&&r.onHidden(),b.state="hidden",b.endTime=new Date,m(b)}})):void 0}function o(){(r.timeOut>0||r.extendedTimeOut>0)&&(u=setTimeout(i,r.extendedTimeOut),O.maxHideTime=parseFloat(r.extendedTimeOut),O.hideEta=(new Date).getTime()+O.maxHideTime)}function s(){clearTimeout(u),O.hideEta=0,l.stop(!0,!0)[r.showMethod]({duration:r.showDuration,easing:r.showEasing})}function a(){var e=(O.hideEta-(new Date).getTime())/O.maxHideTime*100;f.width(e+"%")}var r=g(),d=t.iconClass||r.iconClass;if("undefined"!=typeof t.optionsOverride&&(r=e.extend(r,t.optionsOverride),d=t.optionsOverride.iconClass||d),r.preventDuplicates){if(t.message===C)return;C=t.message}T++,v=n(r,!0);var u=null,l=e("<div/>"),c=e("<div/>"),p=e("<div/>"),f=e("<div/>"),w=e(r.closeHtml),O={intervalId:null,hideEta:null,maxHideTime:null},b={toastId:T,state:"visible",startTime:new Date,options:r,map:t};return t.iconClass&&l.addClass(r.toastClass).addClass(d),t.title&&(c.append(t.title).addClass(r.titleClass),l.append(c)),t.message&&(p.append(t.message).addClass(r.messageClass),l.append(p)),r.closeButton&&(w.addClass("toast-close-button").attr("role","button"),l.prepend(w)),r.progressBar&&(f.addClass("toast-progress"),l.prepend(f)),l.hide(),r.newestOnTop?v.prepend(l):v.append(l),l[r.showMethod]({duration:r.showDuration,easing:r.showEasing,complete:r.onShown}),r.timeOut>0&&(u=setTimeout(i,r.timeOut),O.maxHideTime=parseFloat(r.timeOut),O.hideEta=(new Date).getTime()+O.maxHideTime,r.progressBar&&(O.intervalId=setInterval(a,10))),l.hover(s,o),!r.onclick&&r.tapToDismiss&&l.click(i),r.closeButton&&w&&w.click(function(e){e.stopPropagation?e.stopPropagation():void 0!==e.cancelBubble&&e.cancelBubble!==!0&&(e.cancelBubble=!0),i(!0)}),r.onclick&&l.click(function(){r.onclick(),i()}),m(b),r.debug&&console&&console.log(b),l}function g(){return e.extend({},p(),b.options)}function h(e){v||(v=n()),e.is(":visible")||(e.remove(),e=null,0===v.children().length&&(v.remove(),C=void 0))}var v,w,C,T=0,O={error:"error",info:"info",success:"success",warning:"warning"},b={clear:r,remove:d,error:t,getContainer:n,info:i,options:{},subscribe:o,success:s,version:"2.1.0",warning:a};return b}()})}("function"==typeof define&&define.amd?define:function(e,t){"undefined"!=typeof module&&module.exports?module.exports=t(require("jquery")):window.toastr=t(window.jQuery)});
//# sourceMappingURL=toastr.js.map
;
// Knockout JavaScript library v2.2.0
// (c) Steven Sanderson - http://knockoutjs.com/
// License: MIT (http://www.opensource.org/licenses/mit-license.php)

(function() {function i(v){throw v;}var l=!0,n=null,q=!1;function t(v){return function(){return v}};var w=window,x=document,fa=navigator,E=window.jQuery,H=void 0;
function K(v){function ga(a,d,c,e,f){var g=[],a=b.j(function(){var a=d(c,f)||[];0<g.length&&(b.a.Xa(L(g),a),e&&b.r.K(e,n,[c,a,f]));g.splice(0,g.length);b.a.P(g,a)},n,{W:a,Ja:function(){return 0==g.length||!b.a.X(g[0])}});return{M:g,j:a.oa()?a:H}}function L(a){for(;a.length&&!b.a.X(a[0]);)a.splice(0,1);if(1<a.length){for(var d=a[0],c=a[a.length-1],e=[d];d!==c;){d=d.nextSibling;if(!d)return;e.push(d)}Array.prototype.splice.apply(a,[0,a.length].concat(e))}return a}function R(a,b,c,e,f){var g=Math.min,
h=Math.max,j=[],k,m=a.length,p,r=b.length,u=r-m||1,F=m+r+1,I,z,y;for(k=0;k<=m;k++){z=I;j.push(I=[]);y=g(r,k+u);for(p=h(0,k-1);p<=y;p++)I[p]=p?k?a[k-1]===b[p-1]?z[p-1]:g(z[p]||F,I[p-1]||F)+1:p+1:k+1}g=[];h=[];u=[];k=m;for(p=r;k||p;)r=j[k][p]-1,p&&r===j[k][p-1]?h.push(g[g.length]={status:c,value:b[--p],index:p}):k&&r===j[k-1][p]?u.push(g[g.length]={status:e,value:a[--k],index:k}):(g.push({status:"retained",value:b[--p]}),--k);if(h.length&&u.length)for(var a=10*m,s,b=c=0;(f||b<a)&&(s=h[c]);c++){for(e=
0;j=u[e];e++)if(s.value===j.value){s.moved=j.index;j.moved=s.index;u.splice(e,1);b=e=0;break}b+=e}return g.reverse()}function S(a,d,c,e,f){var f=f||{},g=a&&M(a),g=g&&g.ownerDocument,h=f.templateEngine||N;b.ya.ub(c,h,g);c=h.renderTemplate(c,e,f,g);("number"!=typeof c.length||0<c.length&&"number"!=typeof c[0].nodeType)&&i(Error("Template engine must return an array of DOM nodes"));g=q;switch(d){case "replaceChildren":b.e.N(a,c);g=l;break;case "replaceNode":b.a.Xa(a,c);g=l;break;case "ignoreTargetNode":break;
default:i(Error("Unknown renderMode: "+d))}g&&(T(c,e),f.afterRender&&b.r.K(f.afterRender,n,[c,e.$data]));return c}function M(a){return a.nodeType?a:0<a.length?a[0]:n}function T(a,d){if(a.length){var c=a[0],e=a[a.length-1];U(c,e,function(a){b.Ca(d,a)});U(c,e,function(a){b.s.hb(a,[d])})}}function U(a,d,c){for(var e,d=b.e.nextSibling(d);a&&(e=a)!==d;)a=b.e.nextSibling(e),(1===e.nodeType||8===e.nodeType)&&c(e)}function V(a,d,c){for(var a=b.g.aa(a),e=b.g.Q,f=0;f<a.length;f++){var g=a[f].key;if(e.hasOwnProperty(g)){var h=
e[g];"function"===typeof h?(g=h(a[f].value))&&i(Error(g)):h||i(Error("This template engine does not support the '"+g+"' binding within its templates"))}}a="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+b.g.ba(a)+" } })()})";return c.createJavaScriptEvaluatorBlock(a)+d}function W(a,d,c,e){function f(a){return function(){return j[a]}}function g(){return j}var h=0,j,k;b.j(function(){var m=c&&c instanceof b.z?c:new b.z(b.a.d(c)),p=m.$data;e&&b.cb(a,m);if(j=("function"==typeof d?
d(m,a):d)||b.J.instance.getBindings(a,m)){if(0===h){h=1;for(var r in j){var u=b.c[r];u&&8===a.nodeType&&!b.e.I[r]&&i(Error("The binding '"+r+"' cannot be used with virtual elements"));if(u&&"function"==typeof u.init&&(u=(0,u.init)(a,f(r),g,p,m))&&u.controlsDescendantBindings)k!==H&&i(Error("Multiple bindings ("+k+" and "+r+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.")),k=r}h=2}if(2===h)for(r in j)(u=b.c[r])&&"function"==
typeof u.update&&(0,u.update)(a,f(r),g,p,m)}},n,{W:a});return{Mb:k===H}}function X(a,d,c){var e=l,f=1===d.nodeType;f&&b.e.Sa(d);if(f&&c||b.J.instance.nodeHasBindings(d))e=W(d,n,a,c).Mb;e&&Y(a,d,!f)}function Y(a,d,c){for(var e=b.e.firstChild(d);d=e;)e=b.e.nextSibling(d),X(a,d,c)}function Z(a,b){var c=$(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:n}function $(a,b){for(var c=a,e=1,f=[];c=c.nextSibling;){if(G(c)&&(e--,0===e))return f;f.push(c);A(c)&&e++}b||i(Error("Cannot find closing comment tag to match: "+
a.nodeValue));return n}function G(a){return 8==a.nodeType&&(J?a.text:a.nodeValue).match(ha)}function A(a){return 8==a.nodeType&&(J?a.text:a.nodeValue).match(ia)}function O(a,b){for(var c=n;a!=c;)c=a,a=a.replace(ja,function(a,c){return b[c]});return a}function ka(){var a=[],d=[];this.save=function(c,e){var f=b.a.i(a,c);0<=f?d[f]=e:(a.push(c),d.push(e))};this.get=function(c){c=b.a.i(a,c);return 0<=c?d[c]:H}}function aa(a,b,c){function e(e){var g=b(a[e]);switch(typeof g){case "boolean":case "number":case "string":case "function":f[e]=
g;break;case "object":case "undefined":var h=c.get(g);f[e]=h!==H?h:aa(g,b,c)}}c=c||new ka;a=b(a);if(!("object"==typeof a&&a!==n&&a!==H&&!(a instanceof Date)))return a;var f=a instanceof Array?[]:{};c.save(a,f);var g=a;if(g instanceof Array){for(var h=0;h<g.length;h++)e(h);"function"==typeof g.toJSON&&e("toJSON")}else for(h in g)e(h);return f}function ba(a,d){if(a)if(8==a.nodeType){var c=b.s.Ta(a.nodeValue);c!=n&&d.push({rb:a,Eb:c})}else if(1==a.nodeType)for(var c=0,e=a.childNodes,f=e.length;c<f;c++)ba(e[c],
d)}function P(a,d,c,e){b.c[a]={init:function(a){b.a.f.set(a,ca,{});return{controlsDescendantBindings:l}},update:function(a,g,h,j,k){var h=b.a.f.get(a,ca),g=b.a.d(g()),j=!c!==!g,m=!h.Ya;if(m||d||j!==h.pb)m&&(h.Ya=b.a.Ha(b.e.childNodes(a),l)),j?(m||b.e.N(a,b.a.Ha(h.Ya)),b.Da(e?e(k,g):k,a)):b.e.Y(a),h.pb=j}};b.g.Q[a]=q;b.e.I[a]=l}function da(a,d,c){c&&d!==b.k.q(a)&&b.k.T(a,d);d!==b.k.q(a)&&b.r.K(b.a.Aa,n,[a,"change"])}var b="undefined"!==typeof v?v:{};b.b=function(a,d){for(var c=a.split("."),e=b,f=0;f<
c.length-1;f++)e=e[c[f]];e[c[c.length-1]]=d};b.p=function(a,b,c){a[b]=c};b.version="2.2.0";b.b("version",b.version);b.a=new function(){function a(a,d){if("input"!==b.a.u(a)||!a.type||"click"!=d.toLowerCase())return q;var c=a.type;return"checkbox"==c||"radio"==c}var d=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,c={},e={};c[/Firefox\/2/i.test(fa.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];c.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");
for(var f in c){var g=c[f];if(g.length)for(var h=0,j=g.length;h<j;h++)e[g[h]]=f}var k={propertychange:l},m,c=3;f=x.createElement("div");for(g=f.getElementsByTagName("i");f.innerHTML="<\!--[if gt IE "+ ++c+"]><i></i><![endif]--\>",g[0];);m=4<c?c:H;return{Ma:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],o:function(a,b){for(var d=0,c=a.length;d<c;d++)b(a[d])},i:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var d=0,c=a.length;d<
c;d++)if(a[d]===b)return d;return-1},kb:function(a,b,d){for(var c=0,e=a.length;c<e;c++)if(b.call(d,a[c]))return a[c];return n},ga:function(a,d){var c=b.a.i(a,d);0<=c&&a.splice(c,1)},Fa:function(a){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)0>b.a.i(d,a[c])&&d.push(a[c]);return d},V:function(a,b){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)d.push(b(a[c]));return d},fa:function(a,b){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)b(a[c])&&d.push(a[c]);return d},P:function(a,b){if(b instanceof Array)a.push.apply(a,
b);else for(var d=0,c=b.length;d<c;d++)a.push(b[d]);return a},extend:function(a,b){if(b)for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);return a},ka:function(a){for(;a.firstChild;)b.removeNode(a.firstChild)},Gb:function(a){for(var a=b.a.L(a),d=x.createElement("div"),c=0,e=a.length;c<e;c++)d.appendChild(b.A(a[c]));return d},Ha:function(a,d){for(var c=0,e=a.length,g=[];c<e;c++){var f=a[c].cloneNode(l);g.push(d?b.A(f):f)}return g},N:function(a,d){b.a.ka(a);if(d)for(var c=0,e=d.length;c<e;c++)a.appendChild(d[c])},
Xa:function(a,d){var c=a.nodeType?[a]:a;if(0<c.length){for(var e=c[0],g=e.parentNode,f=0,h=d.length;f<h;f++)g.insertBefore(d[f],e);f=0;for(h=c.length;f<h;f++)b.removeNode(c[f])}},ab:function(a,b){7>m?a.setAttribute("selected",b):a.selected=b},D:function(a){return(a||"").replace(d,"")},Qb:function(a,d){for(var c=[],e=(a||"").split(d),f=0,g=e.length;f<g;f++){var h=b.a.D(e[f]);""!==h&&c.push(h)}return c},Nb:function(a,b){a=a||"";return b.length>a.length?q:a.substring(0,b.length)===b},sb:function(a,b){if(b.compareDocumentPosition)return 16==
(b.compareDocumentPosition(a)&16);for(;a!=n;){if(a==b)return l;a=a.parentNode}return q},X:function(a){return b.a.sb(a,a.ownerDocument)},u:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},n:function(b,d,c){var e=m&&k[d];if(!e&&"undefined"!=typeof E){if(a(b,d))var f=c,c=function(a,b){var d=this.checked;b&&(this.checked=b.mb!==l);f.call(this,a);this.checked=d};E(b).on(d,c)}else!e&&"function"==typeof b.addEventListener?b.addEventListener(d,c,q):"undefined"!=typeof b.attachEvent?b.attachEvent("on"+
d,function(a){c.call(b,a)}):i(Error("Browser doesn't support addEventListener or attachEvent"))},Aa:function(b,d){(!b||!b.nodeType)&&i(Error("element must be a DOM node when calling triggerEvent"));if("undefined"!=typeof E){var c=[];a(b,d)&&c.push({mb:b.checked});E(b).trigger(d,c)}else"function"==typeof x.createEvent?"function"==typeof b.dispatchEvent?(c=x.createEvent(e[d]||"HTMLEvents"),c.initEvent(d,l,l,w,0,0,0,0,0,q,q,q,q,0,b),b.dispatchEvent(c)):i(Error("The supplied element doesn't support dispatchEvent")):
"undefined"!=typeof b.fireEvent?(a(b,d)&&(b.checked=b.checked!==l),b.fireEvent("on"+d)):i(Error("Browser doesn't support triggering events"))},d:function(a){return b.$(a)?a():a},ta:function(a){return b.$(a)?a.t():a},da:function(a,d,c){if(d){var e=/[\w-]+/g,f=a.className.match(e)||[];b.a.o(d.match(e),function(a){var d=b.a.i(f,a);0<=d?c||f.splice(d,1):c&&f.push(a)});a.className=f.join(" ")}},bb:function(a,d){var c=b.a.d(d);if(c===n||c===H)c="";if(3===a.nodeType)a.data=c;else{var e=b.e.firstChild(a);
!e||3!=e.nodeType||b.e.nextSibling(e)?b.e.N(a,[x.createTextNode(c)]):e.data=c;b.a.vb(a)}},$a:function(a,b){a.name=b;if(7>=m)try{a.mergeAttributes(x.createElement("<input name='"+a.name+"'/>"),q)}catch(d){}},vb:function(a){9<=m&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},tb:function(a){if(9<=m){var b=a.style.width;a.style.width=0;a.style.width=b}},Kb:function(a,d){for(var a=b.a.d(a),d=b.a.d(d),c=[],e=a;e<=d;e++)c.push(e);return c},L:function(a){for(var b=[],d=0,c=a.length;d<
c;d++)b.push(a[d]);return b},Ob:6===m,Pb:7===m,Z:m,Na:function(a,d){for(var c=b.a.L(a.getElementsByTagName("input")).concat(b.a.L(a.getElementsByTagName("textarea"))),e="string"==typeof d?function(a){return a.name===d}:function(a){return d.test(a.name)},f=[],g=c.length-1;0<=g;g--)e(c[g])&&f.push(c[g]);return f},Hb:function(a){return"string"==typeof a&&(a=b.a.D(a))?w.JSON&&w.JSON.parse?w.JSON.parse(a):(new Function("return "+a))():n},wa:function(a,d,c){("undefined"==typeof JSON||"undefined"==typeof JSON.stringify)&&
i(Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js"));return JSON.stringify(b.a.d(a),d,c)},Ib:function(a,d,c){var c=c||{},e=c.params||{},f=c.includeFields||this.Ma,g=a;if("object"==typeof a&&"form"===b.a.u(a))for(var g=a.action,h=f.length-1;0<=h;h--)for(var j=b.a.Na(a,f[h]),k=j.length-1;0<=k;k--)e[j[k].name]=j[k].value;var d=b.a.d(d),m=x.createElement("form");
m.style.display="none";m.action=g;m.method="post";for(var v in d)a=x.createElement("input"),a.name=v,a.value=b.a.wa(b.a.d(d[v])),m.appendChild(a);for(v in e)a=x.createElement("input"),a.name=v,a.value=e[v],m.appendChild(a);x.body.appendChild(m);c.submitter?c.submitter(m):m.submit();setTimeout(function(){m.parentNode.removeChild(m)},0)}}};b.b("utils",b.a);b.b("utils.arrayForEach",b.a.o);b.b("utils.arrayFirst",b.a.kb);b.b("utils.arrayFilter",b.a.fa);b.b("utils.arrayGetDistinctValues",b.a.Fa);b.b("utils.arrayIndexOf",
b.a.i);b.b("utils.arrayMap",b.a.V);b.b("utils.arrayPushAll",b.a.P);b.b("utils.arrayRemoveItem",b.a.ga);b.b("utils.extend",b.a.extend);b.b("utils.fieldsIncludedWithJsonPost",b.a.Ma);b.b("utils.getFormFields",b.a.Na);b.b("utils.peekObservable",b.a.ta);b.b("utils.postJson",b.a.Ib);b.b("utils.parseJson",b.a.Hb);b.b("utils.registerEventHandler",b.a.n);b.b("utils.stringifyJson",b.a.wa);b.b("utils.range",b.a.Kb);b.b("utils.toggleDomNodeCssClass",b.a.da);b.b("utils.triggerEvent",b.a.Aa);b.b("utils.unwrapObservable",
b.a.d);Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Array.prototype.slice.call(arguments),a=c.shift();return function(){return b.apply(a,c.concat(Array.prototype.slice.call(arguments)))}});b.a.f=new function(){var a=0,d="__ko__"+(new Date).getTime(),c={};return{get:function(a,d){var c=b.a.f.getAll(a,q);return c===H?H:c[d]},set:function(a,d,c){c===H&&b.a.f.getAll(a,q)===H||(b.a.f.getAll(a,l)[d]=c)},getAll:function(b,f){var g=b[d];if(!g||!("null"!==g&&c[g])){if(!f)return H;
g=b[d]="ko"+a++;c[g]={}}return c[g]},clear:function(a){var b=a[d];return b?(delete c[b],a[d]=n,l):q}}};b.b("utils.domData",b.a.f);b.b("utils.domData.clear",b.a.f.clear);b.a.F=new function(){function a(a,d){var e=b.a.f.get(a,c);e===H&&d&&(e=[],b.a.f.set(a,c,e));return e}function d(c){var e=a(c,q);if(e)for(var e=e.slice(0),j=0;j<e.length;j++)e[j](c);b.a.f.clear(c);"function"==typeof E&&"function"==typeof E.cleanData&&E.cleanData([c]);if(f[c.nodeType])for(e=c.firstChild;c=e;)e=c.nextSibling,8===c.nodeType&&
d(c)}var c="__ko_domNodeDisposal__"+(new Date).getTime(),e={1:l,8:l,9:l},f={1:l,9:l};return{Ba:function(b,d){"function"!=typeof d&&i(Error("Callback must be a function"));a(b,l).push(d)},Wa:function(d,e){var f=a(d,q);f&&(b.a.ga(f,e),0==f.length&&b.a.f.set(d,c,H))},A:function(a){if(e[a.nodeType]&&(d(a),f[a.nodeType])){var c=[];b.a.P(c,a.getElementsByTagName("*"));for(var j=0,k=c.length;j<k;j++)d(c[j])}return a},removeNode:function(a){b.A(a);a.parentNode&&a.parentNode.removeChild(a)}}};b.A=b.a.F.A;
b.removeNode=b.a.F.removeNode;b.b("cleanNode",b.A);b.b("removeNode",b.removeNode);b.b("utils.domNodeDisposal",b.a.F);b.b("utils.domNodeDisposal.addDisposeCallback",b.a.F.Ba);b.b("utils.domNodeDisposal.removeDisposeCallback",b.a.F.Wa);b.a.sa=function(a){var d;if("undefined"!=typeof E){if((d=E.clean([a]))&&d[0]){for(a=d[0];a.parentNode&&11!==a.parentNode.nodeType;)a=a.parentNode;a.parentNode&&a.parentNode.removeChild(a)}}else{var c=b.a.D(a).toLowerCase();d=x.createElement("div");c=c.match(/^<(thead|tbody|tfoot)/)&&
[1,"<table>","</table>"]||!c.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!c.indexOf("<td")||!c.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||[0,"",""];a="ignored<div>"+c[1]+a+c[2]+"</div>";for("function"==typeof w.innerShiv?d.appendChild(w.innerShiv(a)):d.innerHTML=a;c[0]--;)d=d.lastChild;d=b.a.L(d.lastChild.childNodes)}return d};b.a.ca=function(a,d){b.a.ka(a);d=b.a.d(d);if(d!==n&&d!==H)if("string"!=typeof d&&(d=d.toString()),"undefined"!=typeof E)E(a).html(d);else for(var c=
b.a.sa(d),e=0;e<c.length;e++)a.appendChild(c[e])};b.b("utils.parseHtmlFragment",b.a.sa);b.b("utils.setHtml",b.a.ca);var Q={};b.s={qa:function(a){"function"!=typeof a&&i(Error("You can only pass a function to ko.memoization.memoize()"));var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);Q[b]=a;return"<\!--[ko_memo:"+b+"]--\>"},gb:function(a,b){var c=Q[a];c===H&&i(Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized."));
try{return c.apply(n,b||[]),l}finally{delete Q[a]}},hb:function(a,d){var c=[];ba(a,c);for(var e=0,f=c.length;e<f;e++){var g=c[e].rb,h=[g];d&&b.a.P(h,d);b.s.gb(c[e].Eb,h);g.nodeValue="";g.parentNode&&g.parentNode.removeChild(g)}},Ta:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:n}};b.b("memoization",b.s);b.b("memoization.memoize",b.s.qa);b.b("memoization.unmemoize",b.s.gb);b.b("memoization.parseMemoText",b.s.Ta);b.b("memoization.unmemoizeDomNodeAndDescendants",b.s.hb);b.La={throttle:function(a,
d){a.throttleEvaluation=d;var c=n;return b.j({read:a,write:function(b){clearTimeout(c);c=setTimeout(function(){a(b)},d)}})},notify:function(a,d){a.equalityComparer="always"==d?t(q):b.m.fn.equalityComparer;return a}};b.b("extenders",b.La);b.eb=function(a,d,c){this.target=a;this.ha=d;this.qb=c;b.p(this,"dispose",this.B)};b.eb.prototype.B=function(){this.Bb=l;this.qb()};b.S=function(){this.w={};b.a.extend(this,b.S.fn);b.p(this,"subscribe",this.xa);b.p(this,"extend",this.extend);b.p(this,"getSubscriptionsCount",
this.xb)};b.S.fn={xa:function(a,d,c){var c=c||"change",a=d?a.bind(d):a,e=new b.eb(this,a,function(){b.a.ga(this.w[c],e)}.bind(this));this.w[c]||(this.w[c]=[]);this.w[c].push(e);return e},notifySubscribers:function(a,d){d=d||"change";this.w[d]&&b.r.K(function(){b.a.o(this.w[d].slice(0),function(b){b&&b.Bb!==l&&b.ha(a)})},this)},xb:function(){var a=0,b;for(b in this.w)this.w.hasOwnProperty(b)&&(a+=this.w[b].length);return a},extend:function(a){var d=this;if(a)for(var c in a){var e=b.La[c];"function"==
typeof e&&(d=e(d,a[c]))}return d}};b.Pa=function(a){return"function"==typeof a.xa&&"function"==typeof a.notifySubscribers};b.b("subscribable",b.S);b.b("isSubscribable",b.Pa);var B=[];b.r={lb:function(a){B.push({ha:a,Ka:[]})},end:function(){B.pop()},Va:function(a){b.Pa(a)||i(Error("Only subscribable things can act as dependencies"));if(0<B.length){var d=B[B.length-1];d&&!(0<=b.a.i(d.Ka,a))&&(d.Ka.push(a),d.ha(a))}},K:function(a,b,c){try{return B.push(n),a.apply(b,c||[])}finally{B.pop()}}};var la={undefined:l,
"boolean":l,number:l,string:l};b.m=function(a){function d(){if(0<arguments.length){if(!d.equalityComparer||!d.equalityComparer(c,arguments[0]))d.H(),c=arguments[0],d.G();return this}b.r.Va(d);return c}var c=a;b.S.call(d);d.t=function(){return c};d.G=function(){d.notifySubscribers(c)};d.H=function(){d.notifySubscribers(c,"beforeChange")};b.a.extend(d,b.m.fn);b.p(d,"peek",d.t);b.p(d,"valueHasMutated",d.G);b.p(d,"valueWillMutate",d.H);return d};b.m.fn={equalityComparer:function(a,b){return a===n||typeof a in
la?a===b:q}};var D=b.m.Jb="__ko_proto__";b.m.fn[D]=b.m;b.la=function(a,d){return a===n||a===H||a[D]===H?q:a[D]===d?l:b.la(a[D],d)};b.$=function(a){return b.la(a,b.m)};b.Qa=function(a){return"function"==typeof a&&a[D]===b.m||"function"==typeof a&&a[D]===b.j&&a.yb?l:q};b.b("observable",b.m);b.b("isObservable",b.$);b.b("isWriteableObservable",b.Qa);b.R=function(a){0==arguments.length&&(a=[]);a!==n&&(a!==H&&!("length"in a))&&i(Error("The argument passed when initializing an observable array must be an array, or null, or undefined."));
var d=b.m(a);b.a.extend(d,b.R.fn);return d};b.R.fn={remove:function(a){for(var b=this.t(),c=[],e="function"==typeof a?a:function(b){return b===a},f=0;f<b.length;f++){var g=b[f];e(g)&&(0===c.length&&this.H(),c.push(g),b.splice(f,1),f--)}c.length&&this.G();return c},removeAll:function(a){if(a===H){var d=this.t(),c=d.slice(0);this.H();d.splice(0,d.length);this.G();return c}return!a?[]:this.remove(function(d){return 0<=b.a.i(a,d)})},destroy:function(a){var b=this.t(),c="function"==typeof a?a:function(b){return b===
a};this.H();for(var e=b.length-1;0<=e;e--)c(b[e])&&(b[e]._destroy=l);this.G()},destroyAll:function(a){return a===H?this.destroy(t(l)):!a?[]:this.destroy(function(d){return 0<=b.a.i(a,d)})},indexOf:function(a){var d=this();return b.a.i(d,a)},replace:function(a,b){var c=this.indexOf(a);0<=c&&(this.H(),this.t()[c]=b,this.G())}};b.a.o("pop push reverse shift sort splice unshift".split(" "),function(a){b.R.fn[a]=function(){var b=this.t();this.H();b=b[a].apply(b,arguments);this.G();return b}});b.a.o(["slice"],
function(a){b.R.fn[a]=function(){var b=this();return b[a].apply(b,arguments)}});b.b("observableArray",b.R);b.j=function(a,d,c){function e(){b.a.o(y,function(a){a.B()});y=[]}function f(){var a=h.throttleEvaluation;a&&0<=a?(clearTimeout(s),s=setTimeout(g,a)):g()}function g(){if(!p)if(m&&v())z();else{p=l;try{var a=b.a.V(y,function(a){return a.target});b.r.lb(function(c){var d;0<=(d=b.a.i(a,c))?a[d]=H:y.push(c.xa(f))});for(var c=r.call(d),e=a.length-1;0<=e;e--)a[e]&&y.splice(e,1)[0].B();m=l;h.notifySubscribers(k,
"beforeChange");k=c}finally{b.r.end()}h.notifySubscribers(k);p=q;y.length||z()}}function h(){if(0<arguments.length)return"function"===typeof u?u.apply(d,arguments):i(Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.")),this;m||g();b.r.Va(h);return k}function j(){return!m||0<y.length}var k,m=q,p=q,r=a;r&&"object"==typeof r?(c=r,r=c.read):(c=c||{},r||(r=c.read));"function"!=typeof r&&i(Error("Pass a function that returns the value of the ko.computed"));
var u=c.write,F=c.disposeWhenNodeIsRemoved||c.W||n,v=c.disposeWhen||c.Ja||t(q),z=e,y=[],s=n;d||(d=c.owner);h.t=function(){m||g();return k};h.wb=function(){return y.length};h.yb="function"===typeof c.write;h.B=function(){z()};h.oa=j;b.S.call(h);b.a.extend(h,b.j.fn);b.p(h,"peek",h.t);b.p(h,"dispose",h.B);b.p(h,"isActive",h.oa);b.p(h,"getDependenciesCount",h.wb);c.deferEvaluation!==l&&g();if(F&&j()){z=function(){b.a.F.Wa(F,arguments.callee);e()};b.a.F.Ba(F,z);var C=v,v=function(){return!b.a.X(F)||C()}}return h};
b.Ab=function(a){return b.la(a,b.j)};v=b.m.Jb;b.j[v]=b.m;b.j.fn={};b.j.fn[v]=b.j;b.b("dependentObservable",b.j);b.b("computed",b.j);b.b("isComputed",b.Ab);b.fb=function(a){0==arguments.length&&i(Error("When calling ko.toJS, pass the object you want to convert."));return aa(a,function(a){for(var c=0;b.$(a)&&10>c;c++)a=a();return a})};b.toJSON=function(a,d,c){a=b.fb(a);return b.a.wa(a,d,c)};b.b("toJS",b.fb);b.b("toJSON",b.toJSON);b.k={q:function(a){switch(b.a.u(a)){case "option":return a.__ko__hasDomDataOptionValue__===
l?b.a.f.get(a,b.c.options.ra):7>=b.a.Z?a.getAttributeNode("value").specified?a.value:a.text:a.value;case "select":return 0<=a.selectedIndex?b.k.q(a.options[a.selectedIndex]):H;default:return a.value}},T:function(a,d){switch(b.a.u(a)){case "option":switch(typeof d){case "string":b.a.f.set(a,b.c.options.ra,H);"__ko__hasDomDataOptionValue__"in a&&delete a.__ko__hasDomDataOptionValue__;a.value=d;break;default:b.a.f.set(a,b.c.options.ra,d),a.__ko__hasDomDataOptionValue__=l,a.value="number"===typeof d?
d:""}break;case "select":for(var c=a.options.length-1;0<=c;c--)if(b.k.q(a.options[c])==d){a.selectedIndex=c;break}break;default:if(d===n||d===H)d="";a.value=d}}};b.b("selectExtensions",b.k);b.b("selectExtensions.readValue",b.k.q);b.b("selectExtensions.writeValue",b.k.T);var ja=/\@ko_token_(\d+)\@/g,ma=["true","false"],na=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;b.g={Q:[],aa:function(a){var d=b.a.D(a);if(3>d.length)return[];"{"===d.charAt(0)&&(d=d.substring(1,d.length-1));for(var a=[],
c=n,e,f=0;f<d.length;f++){var g=d.charAt(f);if(c===n)switch(g){case '"':case "'":case "/":c=f,e=g}else if(g==e&&"\\"!==d.charAt(f-1)){g=d.substring(c,f+1);a.push(g);var h="@ko_token_"+(a.length-1)+"@",d=d.substring(0,c)+h+d.substring(f+1),f=f-(g.length-h.length),c=n}}e=c=n;for(var j=0,k=n,f=0;f<d.length;f++){g=d.charAt(f);if(c===n)switch(g){case "{":c=f;k=g;e="}";break;case "(":c=f;k=g;e=")";break;case "[":c=f,k=g,e="]"}g===k?j++:g===e&&(j--,0===j&&(g=d.substring(c,f+1),a.push(g),h="@ko_token_"+(a.length-
1)+"@",d=d.substring(0,c)+h+d.substring(f+1),f-=g.length-h.length,c=n))}e=[];d=d.split(",");c=0;for(f=d.length;c<f;c++)j=d[c],k=j.indexOf(":"),0<k&&k<j.length-1?(g=j.substring(k+1),e.push({key:O(j.substring(0,k),a),value:O(g,a)})):e.push({unknown:O(j,a)});return e},ba:function(a){for(var d="string"===typeof a?b.g.aa(a):a,c=[],a=[],e,f=0;e=d[f];f++)if(0<c.length&&c.push(","),e.key){var g;a:{g=e.key;var h=b.a.D(g);switch(h.length&&h.charAt(0)){case "'":case '"':break a;default:g="'"+h+"'"}}e=e.value;
c.push(g);c.push(":");c.push(e);e=b.a.D(e);0<=b.a.i(ma,b.a.D(e).toLowerCase())?e=q:(h=e.match(na),e=h===n?q:h[1]?"Object("+h[1]+")"+h[2]:e);e&&(0<a.length&&a.push(", "),a.push(g+" : function(__ko_value) { "+e+" = __ko_value; }"))}else e.unknown&&c.push(e.unknown);d=c.join("");0<a.length&&(d=d+", '_ko_property_writers' : { "+a.join("")+" } ");return d},Db:function(a,d){for(var c=0;c<a.length;c++)if(b.a.D(a[c].key)==d)return l;return q},ea:function(a,d,c,e,f){if(!a||!b.Qa(a)){if((a=d()._ko_property_writers)&&
a[c])a[c](e)}else(!f||a.t()!==e)&&a(e)}};b.b("expressionRewriting",b.g);b.b("expressionRewriting.bindingRewriteValidators",b.g.Q);b.b("expressionRewriting.parseObjectLiteral",b.g.aa);b.b("expressionRewriting.preProcessBindings",b.g.ba);b.b("jsonExpressionRewriting",b.g);b.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",b.g.ba);var J="<\!--test--\>"===x.createComment("test").text,ia=J?/^<\!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*--\>$/:/^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/,ha=J?/^<\!--\s*\/ko\s*--\>$/:
/^\s*\/ko\s*$/,oa={ul:l,ol:l};b.e={I:{},childNodes:function(a){return A(a)?$(a):a.childNodes},Y:function(a){if(A(a))for(var a=b.e.childNodes(a),d=0,c=a.length;d<c;d++)b.removeNode(a[d]);else b.a.ka(a)},N:function(a,d){if(A(a)){b.e.Y(a);for(var c=a.nextSibling,e=0,f=d.length;e<f;e++)c.parentNode.insertBefore(d[e],c)}else b.a.N(a,d)},Ua:function(a,b){A(a)?a.parentNode.insertBefore(b,a.nextSibling):a.firstChild?a.insertBefore(b,a.firstChild):a.appendChild(b)},Oa:function(a,d,c){c?A(a)?a.parentNode.insertBefore(d,
c.nextSibling):c.nextSibling?a.insertBefore(d,c.nextSibling):a.appendChild(d):b.e.Ua(a,d)},firstChild:function(a){return!A(a)?a.firstChild:!a.nextSibling||G(a.nextSibling)?n:a.nextSibling},nextSibling:function(a){A(a)&&(a=Z(a));return a.nextSibling&&G(a.nextSibling)?n:a.nextSibling},ib:function(a){return(a=A(a))?a[1]:n},Sa:function(a){if(oa[b.a.u(a)]){var d=a.firstChild;if(d){do if(1===d.nodeType){var c;c=d.firstChild;var e=n;if(c){do if(e)e.push(c);else if(A(c)){var f=Z(c,l);f?c=f:e=[c]}else G(c)&&
(e=[c]);while(c=c.nextSibling)}if(c=e){e=d.nextSibling;for(f=0;f<c.length;f++)e?a.insertBefore(c[f],e):a.appendChild(c[f])}}while(d=d.nextSibling)}}}};b.b("virtualElements",b.e);b.b("virtualElements.allowedBindings",b.e.I);b.b("virtualElements.emptyNode",b.e.Y);b.b("virtualElements.insertAfter",b.e.Oa);b.b("virtualElements.prepend",b.e.Ua);b.b("virtualElements.setDomNodeChildren",b.e.N);b.J=function(){this.Ga={}};b.a.extend(b.J.prototype,{nodeHasBindings:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind")!=
n;case 8:return b.e.ib(a)!=n;default:return q}},getBindings:function(a,b){var c=this.getBindingsString(a,b);return c?this.parseBindingsString(c,b,a):n},getBindingsString:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind");case 8:return b.e.ib(a);default:return n}},parseBindingsString:function(a,d,c){try{var e;if(!(e=this.Ga[a])){var f=this.Ga,g="with($context){with($data||{}){return{"+b.g.ba(a)+"}}}";e=f[a]=new Function("$context","$element",g)}return e(d,c)}catch(h){i(Error("Unable to parse bindings.\nMessage: "+
h+";\nBindings value: "+a))}}});b.J.instance=new b.J;b.b("bindingProvider",b.J);b.c={};b.z=function(a,d,c){d?(b.a.extend(this,d),this.$parentContext=d,this.$parent=d.$data,this.$parents=(d.$parents||[]).slice(0),this.$parents.unshift(this.$parent)):(this.$parents=[],this.$root=a,this.ko=b);this.$data=a;c&&(this[c]=a)};b.z.prototype.createChildContext=function(a,d){return new b.z(a,this,d)};b.z.prototype.extend=function(a){var d=b.a.extend(new b.z,this);return b.a.extend(d,a)};b.cb=function(a,d){if(2==
arguments.length)b.a.f.set(a,"__ko_bindingContext__",d);else return b.a.f.get(a,"__ko_bindingContext__")};b.Ea=function(a,d,c){1===a.nodeType&&b.e.Sa(a);return W(a,d,c,l)};b.Da=function(a,b){(1===b.nodeType||8===b.nodeType)&&Y(a,b,l)};b.Ca=function(a,b){b&&(1!==b.nodeType&&8!==b.nodeType)&&i(Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"));b=b||w.document.body;X(a,b,l)};b.ja=function(a){switch(a.nodeType){case 1:case 8:var d=b.cb(a);if(d)return d;
if(a.parentNode)return b.ja(a.parentNode)}return H};b.ob=function(a){return(a=b.ja(a))?a.$data:H};b.b("bindingHandlers",b.c);b.b("applyBindings",b.Ca);b.b("applyBindingsToDescendants",b.Da);b.b("applyBindingsToNode",b.Ea);b.b("contextFor",b.ja);b.b("dataFor",b.ob);var ea={"class":"className","for":"htmlFor"};b.c.attr={update:function(a,d){var c=b.a.d(d())||{},e;for(e in c)if("string"==typeof e){var f=b.a.d(c[e]),g=f===q||f===n||f===H;g&&a.removeAttribute(e);8>=b.a.Z&&e in ea?(e=ea[e],g?a.removeAttribute(e):
a[e]=f):g||a.setAttribute(e,f.toString());"name"===e&&b.a.$a(a,g?"":f.toString())}}};b.c.checked={init:function(a,d,c){b.a.n(a,"click",function(){var e;if("checkbox"==a.type)e=a.checked;else if("radio"==a.type&&a.checked)e=a.value;else return;var f=d(),g=b.a.d(f);"checkbox"==a.type&&g instanceof Array?(e=b.a.i(g,a.value),a.checked&&0>e?f.push(a.value):!a.checked&&0<=e&&f.splice(e,1)):b.g.ea(f,c,"checked",e,l)});"radio"==a.type&&!a.name&&b.c.uniqueName.init(a,t(l))},update:function(a,d){var c=b.a.d(d());
"checkbox"==a.type?a.checked=c instanceof Array?0<=b.a.i(c,a.value):c:"radio"==a.type&&(a.checked=a.value==c)}};b.c.css={update:function(a,d){var c=b.a.d(d());if("object"==typeof c)for(var e in c){var f=b.a.d(c[e]);b.a.da(a,e,f)}else c=String(c||""),b.a.da(a,a.__ko__cssValue,q),a.__ko__cssValue=c,b.a.da(a,c,l)}};b.c.enable={update:function(a,d){var c=b.a.d(d());c&&a.disabled?a.removeAttribute("disabled"):!c&&!a.disabled&&(a.disabled=l)}};b.c.disable={update:function(a,d){b.c.enable.update(a,function(){return!b.a.d(d())})}};
b.c.event={init:function(a,d,c,e){var f=d()||{},g;for(g in f)(function(){var f=g;"string"==typeof f&&b.a.n(a,f,function(a){var g,m=d()[f];if(m){var p=c();try{var r=b.a.L(arguments);r.unshift(e);g=m.apply(e,r)}finally{g!==l&&(a.preventDefault?a.preventDefault():a.returnValue=q)}p[f+"Bubble"]===q&&(a.cancelBubble=l,a.stopPropagation&&a.stopPropagation())}})})()}};b.c.foreach={Ra:function(a){return function(){var d=a(),c=b.a.ta(d);if(!c||"number"==typeof c.length)return{foreach:d,templateEngine:b.C.na};
b.a.d(d);return{foreach:c.data,as:c.as,includeDestroyed:c.includeDestroyed,afterAdd:c.afterAdd,beforeRemove:c.beforeRemove,afterRender:c.afterRender,beforeMove:c.beforeMove,afterMove:c.afterMove,templateEngine:b.C.na}}},init:function(a,d){return b.c.template.init(a,b.c.foreach.Ra(d))},update:function(a,d,c,e,f){return b.c.template.update(a,b.c.foreach.Ra(d),c,e,f)}};b.g.Q.foreach=q;b.e.I.foreach=l;b.c.hasfocus={init:function(a,d,c){function e(e){a.__ko_hasfocusUpdating=l;var f=a.ownerDocument;"activeElement"in
f&&(e=f.activeElement===a);f=d();b.g.ea(f,c,"hasfocus",e,l);a.__ko_hasfocusUpdating=q}var f=e.bind(n,l),g=e.bind(n,q);b.a.n(a,"focus",f);b.a.n(a,"focusin",f);b.a.n(a,"blur",g);b.a.n(a,"focusout",g)},update:function(a,d){var c=b.a.d(d());a.__ko_hasfocusUpdating||(c?a.focus():a.blur(),b.r.K(b.a.Aa,n,[a,c?"focusin":"focusout"]))}};b.c.html={init:function(){return{controlsDescendantBindings:l}},update:function(a,d){b.a.ca(a,d())}};var ca="__ko_withIfBindingData";P("if");P("ifnot",q,l);P("with",l,q,function(a,
b){return a.createChildContext(b)});b.c.options={update:function(a,d,c){"select"!==b.a.u(a)&&i(Error("options binding applies only to SELECT elements"));for(var e=0==a.length,f=b.a.V(b.a.fa(a.childNodes,function(a){return a.tagName&&"option"===b.a.u(a)&&a.selected}),function(a){return b.k.q(a)||a.innerText||a.textContent}),g=a.scrollTop,h=b.a.d(d());0<a.length;)b.A(a.options[0]),a.remove(0);if(h){var c=c(),j=c.optionsIncludeDestroyed;"number"!=typeof h.length&&(h=[h]);if(c.optionsCaption){var k=x.createElement("option");
b.a.ca(k,c.optionsCaption);b.k.T(k,H);a.appendChild(k)}for(var d=0,m=h.length;d<m;d++){var p=h[d];if(!p||!p._destroy||j){var k=x.createElement("option"),r=function(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c},u=r(p,c.optionsValue,p);b.k.T(k,b.a.d(u));p=r(p,c.optionsText,u);b.a.bb(k,p);a.appendChild(k)}}h=a.getElementsByTagName("option");d=j=0;for(m=h.length;d<m;d++)0<=b.a.i(f,b.k.q(h[d]))&&(b.a.ab(h[d],l),j++);a.scrollTop=g;e&&"value"in c&&da(a,b.a.ta(c.value),l);b.a.tb(a)}}};
b.c.options.ra="__ko.optionValueDomData__";b.c.selectedOptions={init:function(a,d,c){b.a.n(a,"change",function(){var e=d(),f=[];b.a.o(a.getElementsByTagName("option"),function(a){a.selected&&f.push(b.k.q(a))});b.g.ea(e,c,"value",f)})},update:function(a,d){"select"!=b.a.u(a)&&i(Error("values binding applies only to SELECT elements"));var c=b.a.d(d());c&&"number"==typeof c.length&&b.a.o(a.getElementsByTagName("option"),function(a){var d=0<=b.a.i(c,b.k.q(a));b.a.ab(a,d)})}};b.c.style={update:function(a,
d){var c=b.a.d(d()||{}),e;for(e in c)if("string"==typeof e){var f=b.a.d(c[e]);a.style[e]=f||""}}};b.c.submit={init:function(a,d,c,e){"function"!=typeof d()&&i(Error("The value for a submit binding must be a function"));b.a.n(a,"submit",function(b){var c,h=d();try{c=h.call(e,a)}finally{c!==l&&(b.preventDefault?b.preventDefault():b.returnValue=q)}})}};b.c.text={update:function(a,d){b.a.bb(a,d())}};b.e.I.text=l;b.c.uniqueName={init:function(a,d){if(d()){var c="ko_unique_"+ ++b.c.uniqueName.nb;b.a.$a(a,
c)}}};b.c.uniqueName.nb=0;b.c.value={init:function(a,d,c){function e(){h=q;var e=d(),f=b.k.q(a);b.g.ea(e,c,"value",f)}var f=["change"],g=c().valueUpdate,h=q;g&&("string"==typeof g&&(g=[g]),b.a.P(f,g),f=b.a.Fa(f));if(b.a.Z&&("input"==a.tagName.toLowerCase()&&"text"==a.type&&"off"!=a.autocomplete&&(!a.form||"off"!=a.form.autocomplete))&&-1==b.a.i(f,"propertychange"))b.a.n(a,"propertychange",function(){h=l}),b.a.n(a,"blur",function(){h&&e()});b.a.o(f,function(c){var d=e;b.a.Nb(c,"after")&&(d=function(){setTimeout(e,
0)},c=c.substring(5));b.a.n(a,c,d)})},update:function(a,d){var c="select"===b.a.u(a),e=b.a.d(d()),f=b.k.q(a),g=e!=f;0===e&&(0!==f&&"0"!==f)&&(g=l);g&&(f=function(){b.k.T(a,e)},f(),c&&setTimeout(f,0));c&&0<a.length&&da(a,e,q)}};b.c.visible={update:function(a,d){var c=b.a.d(d()),e="none"!=a.style.display;c&&!e?a.style.display="":!c&&e&&(a.style.display="none")}};b.c.click={init:function(a,d,c,e){return b.c.event.init.call(this,a,function(){var a={};a.click=d();return a},c,e)}};b.v=function(){};b.v.prototype.renderTemplateSource=
function(){i(Error("Override renderTemplateSource"))};b.v.prototype.createJavaScriptEvaluatorBlock=function(){i(Error("Override createJavaScriptEvaluatorBlock"))};b.v.prototype.makeTemplateSource=function(a,d){if("string"==typeof a){var d=d||x,c=d.getElementById(a);c||i(Error("Cannot find template with ID "+a));return new b.l.h(c)}if(1==a.nodeType||8==a.nodeType)return new b.l.O(a);i(Error("Unknown template type: "+a))};b.v.prototype.renderTemplate=function(a,b,c,e){a=this.makeTemplateSource(a,e);
return this.renderTemplateSource(a,b,c)};b.v.prototype.isTemplateRewritten=function(a,b){return this.allowTemplateRewriting===q?l:this.makeTemplateSource(a,b).data("isRewritten")};b.v.prototype.rewriteTemplate=function(a,b,c){a=this.makeTemplateSource(a,c);b=b(a.text());a.text(b);a.data("isRewritten",l)};b.b("templateEngine",b.v);var pa=/(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi,qa=/<\!--\s*ko\b\s*([\s\S]*?)\s*--\>/g;b.ya={ub:function(a,
d,c){d.isTemplateRewritten(a,c)||d.rewriteTemplate(a,function(a){return b.ya.Fb(a,d)},c)},Fb:function(a,b){return a.replace(pa,function(a,e,f,g,h,j,k){return V(k,e,b)}).replace(qa,function(a,e){return V(e,"<\!-- ko --\>",b)})},jb:function(a){return b.s.qa(function(d,c){d.nextSibling&&b.Ea(d.nextSibling,a,c)})}};b.b("__tr_ambtns",b.ya.jb);b.l={};b.l.h=function(a){this.h=a};b.l.h.prototype.text=function(){var a=b.a.u(this.h),a="script"===a?"text":"textarea"===a?"value":"innerHTML";if(0==arguments.length)return this.h[a];
var d=arguments[0];"innerHTML"===a?b.a.ca(this.h,d):this.h[a]=d};b.l.h.prototype.data=function(a){if(1===arguments.length)return b.a.f.get(this.h,"templateSourceData_"+a);b.a.f.set(this.h,"templateSourceData_"+a,arguments[1])};b.l.O=function(a){this.h=a};b.l.O.prototype=new b.l.h;b.l.O.prototype.text=function(){if(0==arguments.length){var a=b.a.f.get(this.h,"__ko_anon_template__")||{};a.za===H&&a.ia&&(a.za=a.ia.innerHTML);return a.za}b.a.f.set(this.h,"__ko_anon_template__",{za:arguments[0]})};b.l.h.prototype.nodes=
function(){if(0==arguments.length)return(b.a.f.get(this.h,"__ko_anon_template__")||{}).ia;b.a.f.set(this.h,"__ko_anon_template__",{ia:arguments[0]})};b.b("templateSources",b.l);b.b("templateSources.domElement",b.l.h);b.b("templateSources.anonymousTemplate",b.l.O);var N;b.va=function(a){a!=H&&!(a instanceof b.v)&&i(Error("templateEngine must inherit from ko.templateEngine"));N=a};b.ua=function(a,d,c,e,f){c=c||{};(c.templateEngine||N)==H&&i(Error("Set a template engine before calling renderTemplate"));
f=f||"replaceChildren";if(e){var g=M(e);return b.j(function(){var h=d&&d instanceof b.z?d:new b.z(b.a.d(d)),j="function"==typeof a?a(h.$data,h):a,h=S(e,f,j,h,c);"replaceNode"==f&&(e=h,g=M(e))},n,{Ja:function(){return!g||!b.a.X(g)},W:g&&"replaceNode"==f?g.parentNode:g})}return b.s.qa(function(e){b.ua(a,d,c,e,"replaceNode")})};b.Lb=function(a,d,c,e,f){function g(a,b){T(b,j);c.afterRender&&c.afterRender(b,a)}function h(d,e){j=f.createChildContext(b.a.d(d),c.as);j.$index=e;var g="function"==typeof a?
a(d,j):a;return S(n,"ignoreTargetNode",g,j,c)}var j;return b.j(function(){var a=b.a.d(d)||[];"undefined"==typeof a.length&&(a=[a]);a=b.a.fa(a,function(a){return c.includeDestroyed||a===H||a===n||!b.a.d(a._destroy)});b.r.K(b.a.Za,n,[e,a,h,c,g])},n,{W:e})};b.c.template={init:function(a,d){var c=b.a.d(d());if("string"!=typeof c&&!c.name&&(1==a.nodeType||8==a.nodeType))c=1==a.nodeType?a.childNodes:b.e.childNodes(a),c=b.a.Gb(c),(new b.l.O(a)).nodes(c);return{controlsDescendantBindings:l}},update:function(a,
d,c,e,f){var d=b.a.d(d()),c={},e=l,g,h=n;"string"!=typeof d&&(c=d,d=c.name,"if"in c&&(e=b.a.d(c["if"])),e&&"ifnot"in c&&(e=!b.a.d(c.ifnot)),g=b.a.d(c.data));"foreach"in c?h=b.Lb(d||a,e&&c.foreach||[],c,a,f):e?(f="data"in c?f.createChildContext(g,c.as):f,h=b.ua(d||a,f,c,a)):b.e.Y(a);f=h;(g=b.a.f.get(a,"__ko__templateComputedDomDataKey__"))&&"function"==typeof g.B&&g.B();b.a.f.set(a,"__ko__templateComputedDomDataKey__",f&&f.oa()?f:H)}};b.g.Q.template=function(a){a=b.g.aa(a);return 1==a.length&&a[0].unknown||
b.g.Db(a,"name")?n:"This template engine does not support anonymous templates nested within its templates"};b.e.I.template=l;b.b("setTemplateEngine",b.va);b.b("renderTemplate",b.ua);b.a.Ia=function(a,b,c){a=a||[];b=b||[];return a.length<=b.length?R(a,b,"added","deleted",c):R(b,a,"deleted","added",c)};b.b("utils.compareArrays",b.a.Ia);b.a.Za=function(a,d,c,e,f){function g(a,b){s=k[b];v!==b&&(y[a]=s);s.ma(v++);L(s.M);r.push(s);z.push(s)}function h(a,c){if(a)for(var d=0,e=c.length;d<e;d++)c[d]&&b.a.o(c[d].M,
function(b){a(b,d,c[d].U)})}for(var d=d||[],e=e||{},j=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")===H,k=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")||[],m=b.a.V(k,function(a){return a.U}),p=b.a.Ia(m,d),r=[],u=0,v=0,A=[],z=[],d=[],y=[],m=[],s,C=0,B,D;B=p[C];C++)switch(D=B.moved,B.status){case "deleted":D===H&&(s=k[u],s.j&&s.j.B(),A.push.apply(A,L(s.M)),e.beforeRemove&&(d[C]=s,z.push(s)));u++;break;case "retained":g(C,u++);break;case "added":D!==H?g(C,
D):(s={U:B.value,ma:b.m(v++)},r.push(s),z.push(s),j||(m[C]=s))}h(e.beforeMove,y);b.a.o(A,e.beforeRemove?b.A:b.removeNode);for(var C=0,j=b.e.firstChild(a),G;s=z[C];C++){s.M||b.a.extend(s,ga(a,c,s.U,f,s.ma));for(u=0;p=s.M[u];j=p.nextSibling,G=p,u++)p!==j&&b.e.Oa(a,p,G);!s.zb&&f&&(f(s.U,s.M,s.ma),s.zb=l)}h(e.beforeRemove,d);h(e.afterMove,y);h(e.afterAdd,m);b.a.f.set(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult",r)};b.b("utils.setDomNodeChildrenFromArrayMapping",b.a.Za);b.C=function(){this.allowTemplateRewriting=
q};b.C.prototype=new b.v;b.C.prototype.renderTemplateSource=function(a){var d=!(9>b.a.Z)&&a.nodes?a.nodes():n;if(d)return b.a.L(d.cloneNode(l).childNodes);a=a.text();return b.a.sa(a)};b.C.na=new b.C;b.va(b.C.na);b.b("nativeTemplateEngine",b.C);b.pa=function(){var a=this.Cb=function(){if("undefined"==typeof E||!E.tmpl)return 0;try{if(0<=E.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,c,e){e=e||{};2>a&&i(Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later."));
var f=b.data("precompiled");f||(f=b.text()||"",f=E.template(n,"{{ko_with $item.koBindingContext}}"+f+"{{/ko_with}}"),b.data("precompiled",f));b=[c.$data];c=E.extend({koBindingContext:c},e.templateOptions);c=E.tmpl(f,b,c);c.appendTo(x.createElement("div"));E.fragments={};return c};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){x.write("<script type='text/html' id='"+a+"'>"+b+"<\/script>")};0<a&&(E.tmpl.tag.ko_code=
{open:"__.push($1 || '');"},E.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};b.pa.prototype=new b.v;v=new b.pa;0<v.Cb&&b.va(v);b.b("jqueryTmplTemplateEngine",b.pa)}"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?K(module.exports||exports):"function"===typeof define&&define.amd?define(["exports"],K):K(w.ko={});l;
})();
;
/*
See: http://stackoverflow.com/questions/9703647/knockout-custom-binding-for-jquery-ui-sortable-strange-behavior

*/
ko.bindingHandlers.uiSortableList = {
    init: function (element, valueAccessor, allBindingsAccesor, context) {
        var $element = $(element),
                list = valueAccessor(),
                allBindings = allBindingsAccesor();

        $element.sortable({
            tolerance: 'pointer',
            placeholder: 'placeholder',
            items: 'li:not(.placeholder-cue)',
            update: function (event, ui) {
                var item = ko.dataFor(ui.item[0]),
                        newIndex = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]);
                if (newIndex >= list().length) newIndex = list().length - 1;
                if (newIndex < 0) newIndex = 0;
                ui.item.remove();

                // HACK: For photo uploader, the list is bound to a composite object. This accesses the actual object.
                // Use it like this: data-bind="foreach: itemsToShowInList, uiSortableList: selectedImages, sortableProperty: 'item'"
                var sortableProperty = allBindings.sortableProperty || '';
                if (sortableProperty != '') {
                    item = eval('item.' + sortableProperty);
                }
                
                list.remove(item);
                list.splice(newIndex, 0, item);
            }
        });
    }
};
ko.virtualElements.allowedBindings.uiSortableList = true;
;
/// Knockout Mapping plugin v2.4.1
/// (c) 2013 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/
/// License: MIT (http://www.opensource.org/licenses/mit-license.php)
(function(e){"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?e(require("knockout"),exports):"function"===typeof define&&define.amd?define(["knockout","exports"],e):e(ko,ko.mapping={})})(function(e,f){function y(b,c){var a,d;for(d in c)if(c.hasOwnProperty(d)&&c[d])if(a=f.getType(b[d]),d&&b[d]&&"array"!==a&&"string"!==a)y(b[d],c[d]);else if("array"===f.getType(b[d])&&"array"===f.getType(c[d])){a=b;for(var e=d,l=b[d],n=c[d],t={},g=l.length-1;0<=g;--g)t[l[g]]=l[g];for(g=
n.length-1;0<=g;--g)t[n[g]]=n[g];l=[];n=void 0;for(n in t)l.push(t[n]);a[e]=l}else b[d]=c[d]}function E(b,c){var a={};y(a,b);y(a,c);return a}function z(b,c){for(var a=E({},b),e=L.length-1;0<=e;e--){var f=L[e];a[f]&&(a[""]instanceof Object||(a[""]={}),a[""][f]=a[f],delete a[f])}c&&(a.ignore=h(c.ignore,a.ignore),a.include=h(c.include,a.include),a.copy=h(c.copy,a.copy),a.observe=h(c.observe,a.observe));a.ignore=h(a.ignore,j.ignore);a.include=h(a.include,j.include);a.copy=h(a.copy,j.copy);a.observe=h(a.observe,
j.observe);a.mappedProperties=a.mappedProperties||{};a.copiedProperties=a.copiedProperties||{};return a}function h(b,c){"array"!==f.getType(b)&&(b="undefined"===f.getType(b)?[]:[b]);"array"!==f.getType(c)&&(c="undefined"===f.getType(c)?[]:[c]);return e.utils.arrayGetDistinctValues(b.concat(c))}function F(b,c,a,d,k,l,n){var t="array"===f.getType(e.utils.unwrapObservable(c));l=l||"";if(f.isMapped(b)){var g=e.utils.unwrapObservable(b)[p];a=E(g,a)}var j=n||k,h=function(){return a[d]&&a[d].create instanceof
Function},x=function(b){var f=G,g=e.dependentObservable;e.dependentObservable=function(a,b,c){c=c||{};a&&"object"==typeof a&&(c=a);var d=c.deferEvaluation,M=!1;c.deferEvaluation=!0;a=new H(a,b,c);if(!d){var g=a,d=e.dependentObservable;e.dependentObservable=H;a=e.isWriteableObservable(g);e.dependentObservable=d;d=H({read:function(){M||(e.utils.arrayRemoveItem(f,g),M=!0);return g.apply(g,arguments)},write:a&&function(a){return g(a)},deferEvaluation:!0});d.__DO=g;a=d;f.push(a)}return a};e.dependentObservable.fn=
H.fn;e.computed=e.dependentObservable;b=e.utils.unwrapObservable(k)instanceof Array?a[d].create({data:b||c,parent:j,skip:N}):a[d].create({data:b||c,parent:j});e.dependentObservable=g;e.computed=e.dependentObservable;return b},u=function(){return a[d]&&a[d].update instanceof Function},v=function(b,f){var g={data:f||c,parent:j,target:e.utils.unwrapObservable(b)};e.isWriteableObservable(b)&&(g.observable=b);return a[d].update(g)};if(n=I.get(c))return n;d=d||"";if(t){var t=[],s=!1,m=function(a){return a};
a[d]&&a[d].key&&(m=a[d].key,s=!0);e.isObservable(b)||(b=e.observableArray([]),b.mappedRemove=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.remove(function(a){return c(m(a))})},b.mappedRemoveAll=function(a){var c=C(a,m);return b.remove(function(a){return-1!=e.utils.arrayIndexOf(c,m(a))})},b.mappedDestroy=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.destroy(function(a){return c(m(a))})},b.mappedDestroyAll=function(a){var c=C(a,m);return b.destroy(function(a){return-1!=
e.utils.arrayIndexOf(c,m(a))})},b.mappedIndexOf=function(a){var c=C(b(),m);a=m(a);return e.utils.arrayIndexOf(c,a)},b.mappedGet=function(a){return b()[b.mappedIndexOf(a)]},b.mappedCreate=function(a){if(-1!==b.mappedIndexOf(a))throw Error("There already is an object with the key that you specified.");var c=h()?x(a):a;u()&&(a=v(c,a),e.isWriteableObservable(c)?c(a):c=a);b.push(c);return c});n=C(e.utils.unwrapObservable(b),m).sort();g=C(c,m);s&&g.sort();s=e.utils.compareArrays(n,g);n={};var J,A=e.utils.unwrapObservable(c),
y={},z=!0,g=0;for(J=A.length;g<J;g++){var r=m(A[g]);if(void 0===r||r instanceof Object){z=!1;break}y[r]=A[g]}var A=[],B=0,g=0;for(J=s.length;g<J;g++){var r=s[g],q,w=l+"["+g+"]";switch(r.status){case "added":var D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=F(void 0,D,a,d,b,w,k);h()||(q=e.utils.unwrapObservable(q));w=O(e.utils.unwrapObservable(c),D,n);q===N?B++:A[w-B]=q;n[w]=!0;break;case "retained":D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=K(b,r.value,m);F(q,D,a,d,b,w,
k);w=O(e.utils.unwrapObservable(c),D,n);A[w]=q;n[w]=!0;break;case "deleted":q=K(b,r.value,m)}t.push({event:r.status,item:q})}b(A);a[d]&&a[d].arrayChanged&&e.utils.arrayForEach(t,function(b){a[d].arrayChanged(b.event,b.item)})}else if(P(c)){b=e.utils.unwrapObservable(b);if(!b){if(h())return s=x(),u()&&(s=v(s)),s;if(u())return v(s);b={}}u()&&(b=v(b));I.save(c,b);if(u())return b;Q(c,function(d){var f=l.length?l+"."+d:d;if(-1==e.utils.arrayIndexOf(a.ignore,f))if(-1!=e.utils.arrayIndexOf(a.copy,f))b[d]=
c[d];else if("object"!=typeof c[d]&&"array"!=typeof c[d]&&0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=c[d],a.copiedProperties[f]=!0;else{var g=I.get(c[d]),k=F(b[d],c[d],a,d,b,f,b),g=g||k;if(0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=g(),a.copiedProperties[f]=!0;else{if(e.isWriteableObservable(b[d])){if(g=e.utils.unwrapObservable(g),b[d]()!==g)b[d](g)}else g=void 0===b[d]?g:e.utils.unwrapObservable(g),b[d]=g;a.mappedProperties[f]=!0}}})}else switch(f.getType(c)){case "function":u()?
e.isWriteableObservable(c)?(c(v(c)),b=c):b=v(c):b=c;break;default:if(e.isWriteableObservable(b))return q=u()?v(b):e.utils.unwrapObservable(c),b(q),q;h()||u();b=h()?x():e.observable(e.utils.unwrapObservable(c));u()&&b(v(b))}return b}function O(b,c,a){for(var d=0,e=b.length;d<e;d++)if(!0!==a[d]&&b[d]===c)return d;return null}function R(b,c){var a;c&&(a=c(b));"undefined"===f.getType(a)&&(a=b);return e.utils.unwrapObservable(a)}function K(b,c,a){b=e.utils.unwrapObservable(b);for(var d=0,f=b.length;d<
f;d++){var l=b[d];if(R(l,a)===c)return l}throw Error("When calling ko.update*, the key '"+c+"' was not found!");}function C(b,c){return e.utils.arrayMap(e.utils.unwrapObservable(b),function(a){return c?R(a,c):a})}function Q(b,c){if("array"===f.getType(b))for(var a=0;a<b.length;a++)c(a);else for(a in b)c(a)}function P(b){var c=f.getType(b);return("object"===c||"array"===c)&&null!==b}function T(){var b=[],c=[];this.save=function(a,d){var f=e.utils.arrayIndexOf(b,a);0<=f?c[f]=d:(b.push(a),c.push(d))};
this.get=function(a){a=e.utils.arrayIndexOf(b,a);return 0<=a?c[a]:void 0}}function S(){var b={},c=function(a){var c;try{c=a}catch(e){c="$$$"}a=b[c];void 0===a&&(a=new T,b[c]=a);return a};this.save=function(a,b){c(a).save(a,b)};this.get=function(a){return c(a).get(a)}}var p="__ko_mapping__",H=e.dependentObservable,B=0,G,I,L=["create","update","key","arrayChanged"],N={},x={include:["_destroy"],ignore:[],copy:[],observe:[]},j=x;f.isMapped=function(b){return(b=e.utils.unwrapObservable(b))&&b[p]};f.fromJS=
function(b){if(0==arguments.length)throw Error("When calling ko.fromJS, pass the object you want to convert.");try{B++||(G=[],I=new S);var c,a;2==arguments.length&&(arguments[1][p]?a=arguments[1]:c=arguments[1]);3==arguments.length&&(c=arguments[1],a=arguments[2]);a&&(c=E(c,a[p]));c=z(c);var d=F(a,b,c);a&&(d=a);if(!--B)for(;G.length;){var e=G.pop();e&&(e(),e.__DO.throttleEvaluation=e.throttleEvaluation)}d[p]=E(d[p],c);return d}catch(f){throw B=0,f;}};f.fromJSON=function(b){var c=e.utils.parseJson(b);
arguments[0]=c;return f.fromJS.apply(this,arguments)};f.updateFromJS=function(){throw Error("ko.mapping.updateFromJS, use ko.mapping.fromJS instead. Please note that the order of parameters is different!");};f.updateFromJSON=function(){throw Error("ko.mapping.updateFromJSON, use ko.mapping.fromJSON instead. Please note that the order of parameters is different!");};f.toJS=function(b,c){j||f.resetDefaultOptions();if(0==arguments.length)throw Error("When calling ko.mapping.toJS, pass the object you want to convert.");
if("array"!==f.getType(j.ignore))throw Error("ko.mapping.defaultOptions().ignore should be an array.");if("array"!==f.getType(j.include))throw Error("ko.mapping.defaultOptions().include should be an array.");if("array"!==f.getType(j.copy))throw Error("ko.mapping.defaultOptions().copy should be an array.");c=z(c,b[p]);return f.visitModel(b,function(a){return e.utils.unwrapObservable(a)},c)};f.toJSON=function(b,c){var a=f.toJS(b,c);return e.utils.stringifyJson(a)};f.defaultOptions=function(){if(0<arguments.length)j=
arguments[0];else return j};f.resetDefaultOptions=function(){j={include:x.include.slice(0),ignore:x.ignore.slice(0),copy:x.copy.slice(0)}};f.getType=function(b){if(b&&"object"===typeof b){if(b.constructor===Date)return"date";if(b.constructor===Array)return"array"}return typeof b};f.visitModel=function(b,c,a){a=a||{};a.visitedObjects=a.visitedObjects||new S;var d,k=e.utils.unwrapObservable(b);if(P(k))a=z(a,k[p]),c(b,a.parentName),d="array"===f.getType(k)?[]:{};else return c(b,a.parentName);a.visitedObjects.save(b,
d);var l=a.parentName;Q(k,function(b){if(!(a.ignore&&-1!=e.utils.arrayIndexOf(a.ignore,b))){var j=k[b],g=a,h=l||"";"array"===f.getType(k)?l&&(h+="["+b+"]"):(l&&(h+="."),h+=b);g.parentName=h;if(!(-1===e.utils.arrayIndexOf(a.copy,b)&&-1===e.utils.arrayIndexOf(a.include,b)&&k[p]&&k[p].mappedProperties&&!k[p].mappedProperties[b]&&k[p].copiedProperties&&!k[p].copiedProperties[b]&&"array"!==f.getType(k)))switch(f.getType(e.utils.unwrapObservable(j))){case "object":case "array":case "undefined":g=a.visitedObjects.get(j);
d[b]="undefined"!==f.getType(g)?g:f.visitModel(j,c,a);break;default:d[b]=c(j,a.parentName)}}});return d}});
;
/*
 * jQuery File Upload Plugin
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 */

/* jshint nomen:false */
/* global define, require, window, document, location, Blob, FormData */

;(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'jquery-ui/ui/widget'
        ], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS:
        factory(
            require('jquery'),
            require('./vendor/jquery.ui.widget')
        );
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Detect file input support, based on
    // http://viljamis.com/blog/2012/file-upload-support-on-mobile/
    $.support.fileInput = !(new RegExp(
        // Handle devices which give false positives for the feature detection:
        '(Android (1\\.[0156]|2\\.[01]))' +
            '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' +
            '|(w(eb)?OSBrowser)|(webOS)' +
            '|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
    ).test(window.navigator.userAgent) ||
        // Feature detection for all other devices:
        $('<input type="file">').prop('disabled'));

    // The FileReader API is not actually used, but works as feature detection,
    // as some Safari versions (5?) support XHR file uploads via the FormData API,
    // but not non-multipart XHR file uploads.
    // window.XMLHttpRequestUpload is not available on IE10, so we check for
    // window.ProgressEvent instead to detect XHR2 file upload capability:
    $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader);
    $.support.xhrFormDataFileUpload = !!window.FormData;

    // Detect support for Blob slicing (required for chunked uploads):
    $.support.blobSlice = window.Blob && (Blob.prototype.slice ||
        Blob.prototype.webkitSlice || Blob.prototype.mozSlice);

    // Helper function to create drag handlers for dragover/dragenter/dragleave:
    function getDragHandler(type) {
        var isDragOver = type === 'dragover';
        return function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var dataTransfer = e.dataTransfer;
            if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 &&
                    this._trigger(
                        type,
                        $.Event(type, {delegatedEvent: e})
                    ) !== false) {
                e.preventDefault();
                if (isDragOver) {
                    dataTransfer.dropEffect = 'copy';
                }
            }
        };
    }

    // 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 undefined.
            // Set to a DOM node or jQuery object to enable file pasting:
            pasteZone: undefined,
            // 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,
            // The following option limits the number of files uploaded with one
            // XHR request to keep the request size under or equal to the defined
            // limit in bytes:
            limitMultiFileUploadSize: undefined,
            // Multipart file uploads add a number of bytes to each uploaded file,
            // therefore the following option adds an overhead for each file used
            // in the limitMultiFileUploadSize configuration:
            limitMultiFileUploadSizeOverhead: 512,
            // 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,

            // Error and info messages:
            messages: {
                uploadedBytes: 'Uploaded bytes exceed file size'
            },

            // Translation function, gets the message key to be translated
            // and an object with context specific data as arguments:
            i18n: function (message, context) {
                message = this.messages[message] || message.toString();
                if (context) {
                    $.each(context, function (key, value) {
                        message = message.replace('{' + key + '}', value);
                    });
                }
                return message;
            },

            // 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 uploads, 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 you 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 (e.isDefaultPrevented()) {
                    return false;
                }
                if (data.autoUpload || (data.autoUpload !== false &&
                        $(this).fileupload('option', 'autoUpload'))) {
                    data.process().done(function () {
                        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,
            timeout: 0
        },

        // A list of options that require reinitializing event listeners and/or
        // special initialization code:
        _specialOptions: [
            'fileInput',
            'dropZone',
            'pasteZone',
            'multipart',
            'forceIframeTransport'
        ],

        _blobSlice: $.support.blobSlice && function () {
            var slice = this.slice || this.webkitSlice || this.mozSlice;
            return slice.apply(this, arguments);
        },

        _BitrateTimer: function () {
            this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
            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 ($.type(options.formData) === 'function') {
                return options.formData(options.form);
            }
            if ($.isArray(options.formData)) {
                return options.formData;
            }
            if ($.type(options.formData) === 'object') {
                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) {
            var progress = {
                loaded: 0,
                total: 0,
                bitrate: 0
            };
            if (obj._progress) {
                $.extend(obj._progress, progress);
            } else {
                obj._progress = progress;
            }
        },

        _initResponseObject: function (obj) {
            var prop;
            if (obj._response) {
                for (prop in obj._response) {
                    if (obj._response.hasOwnProperty(prop)) {
                        delete obj._response[prop];
                    }
                }
            } else {
                obj._response = {};
            }
        },

        _onProgress: function (e, data) {
            if (e.lengthComputable) {
                var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
                    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',
                    $.Event('progress', {delegatedEvent: e}),
                    data
                );
                // Trigger a global progress event for all current file uploads,
                // including ajax calls queued for sequential file uploads:
                this._trigger(
                    'progressall',
                    $.Event('progressall', {delegatedEvent: 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).on('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;
                };
            }
        },

        _isInstanceOf: function (type, obj) {
            // Cross-frame instanceof check
            return Object.prototype.toString.call(obj) === '[object ' + type + ']';
        },

        _initXHRData: function (options) {
            var that = this,
                formData,
                file = options.files[0],
                // Ignore non-multipart setting if not supported:
                multipart = options.multipart || !$.support.xhrFileUpload,
                paramName = $.type(options.paramName) === 'array' ?
                    options.paramName[0] : options.paramName;
            options.headers = $.extend({}, options.headers);
            if (options.contentRange) {
                options.headers['Content-Range'] = options.contentRange;
            }
            if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
                options.headers['Content-Disposition'] = 'attachment; filename="' +
                    encodeURI(file.uploadName || file.name) + '"';
            }
            if (!multipart) {
                options.contentType = file.type || 'application/octet-stream';
                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: ($.type(options.paramName) === 'array' &&
                                    options.paramName[index]) || paramName,
                                value: file
                            });
                        });
                    }
                } else {
                    if (that._isInstanceOf('FormData', options.formData)) {
                        formData = options.formData;
                    } else {
                        formData = new FormData();
                        $.each(this._getFormData(options), function (index, field) {
                            formData.append(field.name, field.value);
                        });
                    }
                    if (options.blob) {
                        formData.append(
                            paramName,
                            options.blob,
                            file.uploadName || file.name
                        );
                    } else {
                        $.each(options.files, function (index, file) {
                            // This check allows the tests to run with
                            // dummy objects:
                            if (that._isInstanceOf('File', file) ||
                                    that._isInstanceOf('Blob', file)) {
                                formData.append(
                                    ($.type(options.paramName) === 'array' &&
                                        options.paramName[index]) || paramName,
                                    file,
                                    file.uploadName || file.name
                                );
                            }
                        });
                    }
                }
                options.data = formData;
            }
            // Blob reference is not needed anymore, free memory:
            options.blob = null;
        },

        _initIframeSettings: function (options) {
            var targetHost = $('<a></a>').prop('href', options.url).prop('host');
            // 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 && targetHost && targetHost !== 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);
            }
        },

        _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 ||
                ($.type(options.form.prop('method')) === 'string' &&
                    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 data callback argument:
        _addConvenienceMethods: function (e, data) {
            var that = this,
                getPromise = function (args) {
                    return $.Deferred().resolveWith(that, args).promise();
                };
            data.process = function (resolveFunc, rejectFunc) {
                if (resolveFunc || rejectFunc) {
                    data._processQueue = this._processQueue =
                        (this._processQueue || getPromise([this])).then(
                            function () {
                                if (data.errorThrown) {
                                    return $.Deferred()
                                        .rejectWith(that, [data]).promise();
                                }
                                return getPromise(arguments);
                            }
                        ).then(resolveFunc, rejectFunc);
                }
                return this._processQueue || getPromise([this]);
            };
            data.submit = function () {
                if (this.state() !== 'pending') {
                    data.jqXHR = this.jqXHR =
                        (that._trigger(
                            'submit',
                            $.Event('submit', {delegatedEvent: e}),
                            this
                        ) !== false) && that._onSend(e, this);
                }
                return this.jqXHR || that._getXHRPromise();
            };
            data.abort = function () {
                if (this.jqXHR) {
                    return this.jqXHR.abort();
                }
                this.errorThrown = 'abort';
                that._trigger('fail', null, this);
                return that._getXHRPromise(false);
            };
            data.state = function () {
                if (this.jqXHR) {
                    return that._getDeferredState(this.jqXHR);
                }
                if (this._processQueue) {
                    return that._getDeferredState(this._processQueue);
                }
            };
            data.processing = function () {
                return !this.jqXHR && this._processQueue && that
                    ._getDeferredState(this._processQueue) === 'pending';
            };
            data.progress = function () {
                return this._progress;
            };
            data.response = function () {
                return this._response;
            };
        },

        // 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) {
            options.uploadedBytes = options.uploadedBytes || 0;
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes,
                mcs = options.maxChunkSize || fs,
                slice = this._blobSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || ($.type(mcs) === 'function' ? mcs(options) : mcs) < fs)) ||
                    options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = options.i18n('uploadedBytes');
                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 + ($.type(mcs) === 'function' ? mcs(o) : 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 (currentLoaded + o.chunkSize - o._progress.loaded) {
                            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;
            }
            // Make sure the container objects for the .response() and
            // .progress() methods on the data object are available
            // and reset to their initial state:
            this._initResponseObject(data);
            this._initProgressObject(data);
            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,
                response = options._response;
            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);
            }
            response.result = options.result = result;
            response.textStatus = options.textStatus = textStatus;
            response.jqXHR = options.jqXHR = jqXHR;
            this._trigger('done', null, options);
        },

        _onFail: function (jqXHR, textStatus, errorThrown, options) {
            var response = options._response;
            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;
            }
            response.jqXHR = options.jqXHR = jqXHR;
            response.textStatus = options.textStatus = textStatus;
            response.errorThrown = options.errorThrown = errorThrown;
            this._trigger('fail', null, options);
        },

        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
            // jqXHRorResult, textStatus and jqXHRorError are added to the
            // options object via done and fail callbacks
            this._trigger('always', null, options);
        },

        _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',
                            $.Event('send', {delegatedEvent: 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._onAlways(
                            jqXHRorResult,
                            textStatus,
                            jqXHRorError,
                            options
                        );
                        that._sending -= 1;
                        that._active -= 1;
                        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();
                            }
                        }
                        if (that._active === 0) {
                            // The stop callback is triggered when all uploads have
                            // been completed, equivalent to the global ajaxStop event:
                            that._trigger('stop');
                        }
                    });
                    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.then(send);
                } else {
                    this._sequence = this._sequence.then(send, send);
                    pipe = this._sequence;
                }
                // 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),
                files = data.files,
                filesLength = files.length,
                limit = options.limitMultiFileUploads,
                limitSize = options.limitMultiFileUploadSize,
                overhead = options.limitMultiFileUploadSizeOverhead,
                batchSize = 0,
                paramName = this._getParamName(options),
                paramNameSet,
                paramNameSlice,
                fileSet,
                i,
                j = 0;
            if (!filesLength) {
                return false;
            }
            if (limitSize && files[0].size === undefined) {
                limitSize = undefined;
            }
            if (!(options.singleFileUploads || limit || limitSize) ||
                    !this._isXHRUpload(options)) {
                fileSet = [files];
                paramNameSet = [paramName];
            } else if (!(options.singleFileUploads || limitSize) && limit) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < filesLength; i += limit) {
                    fileSet.push(files.slice(i, i + limit));
                    paramNameSlice = paramName.slice(i, i + limit);
                    if (!paramNameSlice.length) {
                        paramNameSlice = paramName;
                    }
                    paramNameSet.push(paramNameSlice);
                }
            } else if (!options.singleFileUploads && limitSize) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < filesLength; i = i + 1) {
                    batchSize += files[i].size + overhead;
                    if (i + 1 === filesLength ||
                            ((batchSize + files[i + 1].size + overhead) > limitSize) ||
                            (limit && i + 1 - j >= limit)) {
                        fileSet.push(files.slice(j, i + 1));
                        paramNameSlice = paramName.slice(j, i + 1);
                        if (!paramNameSlice.length) {
                            paramNameSlice = paramName;
                        }
                        paramNameSet.push(paramNameSlice);
                        j = i + 1;
                        batchSize = 0;
                    }
                }
            } else {
                paramNameSet = paramName;
            }
            data.originalFiles = files;
            $.each(fileSet || files, function (index, element) {
                var newData = $.extend({}, data);
                newData.files = fileSet ? element : [element];
                newData.paramName = paramNameSet[index];
                that._initResponseObject(newData);
                that._initProgressObject(newData);
                that._addConvenienceMethods(e, newData);
                result = that._trigger(
                    'add',
                    $.Event('add', {delegatedEvent: e}),
                    newData
                );
                return result;
            });
            return result;
        },

        _replaceFileInput: function (data) {
            var input = data.fileInput,
                inputClone = input.clone(true),
                restoreFocus = input.is(document.activeElement);
            // Add a reference for the new cloned file input to the data argument:
            data.fileInputClone = inputClone;
            $('<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();
            // If the fileInput had focus before it was detached,
            // restore focus to the inputClone.
            if (restoreFocus) {
                inputClone.focus();
            }
            // Avoid memory leaks with the detached file input:
            $.cleanData(input.off('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(),
                entries = [],
                dirReader,
                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]);
                },
                successHandler = function (entries) {
                    that._handleFileTreeEntries(
                        entries,
                        path + entry.name + '/'
                    ).done(function (files) {
                        dfd.resolve(files);
                    }).fail(errorHandler);
                },
                readEntries = function () {
                    dirReader.readEntries(function (results) {
                        if (!results.length) {
                            successHandler(entries);
                        } else {
                            entries = entries.concat(results);
                            readEntries();
                        }
                    }, errorHandler);
                };
            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();
                readEntries();
            } 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);
                })
            ).then(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)
            ).then(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);
                }
                if (that._trigger(
                        'change',
                        $.Event('change', {delegatedEvent: e}),
                        data
                    ) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onPaste: function (e) {
            var items = e.originalEvent && e.originalEvent.clipboardData &&
                    e.originalEvent.clipboardData.items,
                data = {files: []};
            if (items && items.length) {
                $.each(items, function (index, item) {
                    var file = item.getAsFile && item.getAsFile();
                    if (file) {
                        data.files.push(file);
                    }
                });
                if (this._trigger(
                        'paste',
                        $.Event('paste', {delegatedEvent: e}),
                        data
                    ) !== false) {
                    this._onAdd(e, data);
                }
            }
        },

        _onDrop: function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var that = this,
                dataTransfer = e.dataTransfer,
                data = {};
            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
                e.preventDefault();
                this._getDroppedFiles(dataTransfer).always(function (files) {
                    data.files = files;
                    if (that._trigger(
                            'drop',
                            $.Event('drop', {delegatedEvent: e}),
                            data
                        ) !== false) {
                        that._onAdd(e, data);
                    }
                });
            }
        },

        _onDragOver: getDragHandler('dragover'),

        _onDragEnter: getDragHandler('dragenter'),

        _onDragLeave: getDragHandler('dragleave'),

        _initEventHandlers: function () {
            if (this._isXHRUpload(this.options)) {
                this._on(this.options.dropZone, {
                    dragover: this._onDragOver,
                    drop: this._onDrop,
                    // event.preventDefault() on dragenter is required for IE10+:
                    dragenter: this._onDragEnter,
                    // dragleave is not required, but added for completeness:
                    dragleave: this._onDragLeave
                });
                this._on(this.options.pasteZone, {
                    paste: this._onPaste
                });
            }
            if ($.support.fileInput) {
                this._on(this.options.fileInput, {
                    change: this._onChange
                });
            }
        },

        _destroyEventHandlers: function () {
            this._off(this.options.dropZone, 'dragenter dragleave dragover drop');
            this._off(this.options.pasteZone, 'paste');
            this._off(this.options.fileInput, 'change');
        },

        _destroy: function () {
            this._destroyEventHandlers();
        },

        _setOption: function (key, value) {
            var reinit = $.inArray(key, this._specialOptions) !== -1;
            if (reinit) {
                this._destroyEventHandlers();
            }
            this._super(key, value);
            if (reinit) {
                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);
            }
        },

        _getRegExp: function (str) {
            var parts = str.split('/'),
                modifiers = parts.pop();
            parts.shift();
            return new RegExp(parts.join('/'), modifiers);
        },

        _isRegExpOption: function (key, value) {
            return key !== 'url' && $.type(value) === 'string' &&
                /^\/.*\/[igm]{0,3}$/.test(value);
        },

        _initDataAttributes: function () {
            var that = this,
                options = this.options,
                data = this.element.data();
            // Initialize options set via HTML5 data-attributes:
            $.each(
                this.element[0].attributes,
                function (index, attr) {
                    var key = attr.name.toLowerCase(),
                        value;
                    if (/^data-/.test(key)) {
                        // Convert hyphen-ated key to camelCase:
                        key = key.slice(5).replace(/-[a-z]/g, function (str) {
                            return str.charAt(1).toUpperCase();
                        });
                        value = data[key];
                        if (that._isRegExpOption(key, value)) {
                            value = that._getRegExp(value);
                        }
                        options[key] = value;
                    }
                }
            );
        },

        _create: function () {
            this._initDataAttributes();
            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 number of active uploads:
        active: function () {
            return this._active;
        },

        // 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;
                            }
                            if (!files.length) {
                                dfd.reject();
                                return;
                            }
                            data.files = files;
                            jqXHR = that._onSend(null, data);
                            jqXHR.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
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 */

/* global define, require, window, document, JSON */

;(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS:
        factory(require('jquery'));
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Helper variable to create unique names for the transport iframes:
    var counter = 0,
        jsonAPI = $,
        jsonParse = 'parseJSON';

    if ('JSON' in window && 'parse' in JSON) {
      jsonAPI = JSON;
      jsonParse = 'parse';
    }

    // The iframe transport accepts four 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}]
    // options.initialIframeSrc: the URL of the initial iframe src,
    //  by default set to "javascript:false;"
    $.ajaxTransport('iframe', function (options) {
        if (options.async) {
            // javascript:false as initial iframe src
            // prevents warning popups on HTTPS in IE6:
            /*jshint scripturl: true */
            var initialIframeSrc = options.initialIframeSrc || 'javascript:false;',
            /*jshint scripturl: false */
                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';
                    }
                    // 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:
                    counter += 1;
                    iframe = $(
                        '<iframe src="' + initialIframeSrc +
                            '" name="iframe-transport-' + counter + '"></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="' + initialIframeSrc + '"></iframe>')
                                    .appendTo(form);
                                window.setTimeout(function () {
                                    // Removing the form in a setTimeout call
                                    // allows Chrome's developer tools to display
                                    // the response result
                                    form.remove();
                                }, 0);
                            });
                        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');
                            // Remove the HTML5 form attribute from the input(s):
                            options.fileInput.removeAttr('form');
                        }
                        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]);
                                // Restore the original name and form properties:
                                $(input)
                                    .prop('name', clone.prop('name'))
                                    .attr('form', clone.attr('form'));
                                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', initialIframeSrc);
                    }
                    if (form) {
                        form.remove();
                    }
                }
            };
        }
    });

    // The iframe transport returns the iframe content document as response.
    // The following adds converters from iframe to text, json, html, xml
    // and script.
    // Please note that the Content-Type for JSON responses has to be text/plain
    // or text/html, if the browser doesn't include application/json in the
    // Accept header, else IE will show a download dialog.
    // The Content-Type for XML responses on the other hand has to be always
    // application/xml or text/xml, so IE properly parses the XML response.
    // See also
    // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
    $.ajaxSetup({
        converters: {
            'iframe text': function (iframe) {
                return iframe && $(iframe[0].body).text();
            },
            'iframe json': function (iframe) {
                return iframe && jsonAPI[jsonParse]($(iframe[0].body).text());
            },
            'iframe html': function (iframe) {
                return iframe && $(iframe[0].body).html();
            },
            'iframe xml': function (iframe) {
                var xmlDoc = iframe && iframe[0];
                return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
                        $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
                            $(xmlDoc.body).html());
            },
            'iframe script': function (iframe) {
                return iframe && $.globalEval($(iframe[0].body).text());
            }
        }
    });

}));
;
/**
* @license Core Fairfax Digital JavaScript library.
* Copyright 2010 Fairfax Digital.
*/
"use strict";

/*global FD:true, window:false */

// Create FD namespace
if (typeof FD === "undefined" || !FD) {
    /// <summary>The FD global namespace object.</summary>
    var FD = {};
}

/// <summary>Returns the namespace specified and creates it if it doesn't exist.</summary>
/// <returns>Reference to the last namespace object created.</returns>
FD.namespace = function () {
    var a = arguments, o = null, i, ilen, j, jlen, ns;

    // Loop through each argument (namespace).
    for (i = 0, ilen = a.length; i < ilen; i = i + 1) {
        ns = ("" + a[i]).split(".");
        o = FD;

        // FD is implied so it is ignored if included
        for (j = (ns[0] === "FD") ? 1 : 0, jlen = ns.length; j < jlen; j = j + 1) {
            o[ns[j]] = o[ns[j]] || {};
            o = o[ns[j]];
        }
    }

    return o;
};

/// <summary>Iterate through items in an array or object.</summary>
/// <param name="o" type="object|array">Array or Object to iterate over.</param>
/// <param name="c" type="function">Callback function.</param>
/// <returns>Supplied object.</returns>
FD.each = function (o, c) {
    var n, v, i = 0, iLen = o.length, isObj = o.length === undefined;

    if (isObj) {
        for (n in o) {
            if (o.hasOwnProperty(n)) {
                var v = o[n];
                if (c.call(v, n, v) === false) {
                    break;
                }
            }
        }
    } else if (iLen > 0) {
        for (v = o[0]; i < iLen && c.call(v, i, v) !== false; v = o[++i]) { }
    }

    return o;
};

/// <summary>Log object configured by what logging modules are available.</summary>
(FD.log = function () {
    var h = [], c = window.console;

    return function () {
        h.push(arguments);
        //c && c.log[c.firebug ? 'apply' : 'call'](c, Array.prototype.slice.call(arguments));
        if (c) {
            if (c.log.apply) {
                c.log.apply(c, Array.prototype.slice.call(arguments));
            }
            else if (c.log.call) {
                c.log.call(c, Array.prototype.slice.call(arguments));
            }
            else {
                c.log(c, Array.prototype.slice.call(arguments));
            }
        }
    };
} ());


/// <summary>Base class to enable custom objects to raise events.</summary>
FD.eventEnabledObject = function () {
    //this.events = {};
    return {

        events: {},

        /// <summary>Dispatches the specified event name and it's arguments to all listeners.</summary>
        /// <param name="name" type="string">Event name to fire.</param>
        trigger: function (name) {
            var list = this.events[name.toLowerCase()], i, args;

            // console.log(name, arguments);

            if (list) {
                // Replace name with sender in args
                args = Array.prototype.slice.call(arguments);
                args[0] = this;

                // Dispatch event to all listeners
                for (i = 0; i < list.length; i++) {
                    // Fire event, break chain if false is returned
                    if (list[i].func.apply(list[i].scope, args) === false) {
                        return false;
                    }
                }
            }

            return true;
        },

        /// <summary>Adds an event listener by name.</summary>
        /// <param name="name" type="string">Event name to subscribe to.</param>
        /// <param name="func" type="function">Callback function.</param>
        /// <param name="scope" type="object">Optional scope to execute the specified function in.</param>
        /// <returns>Supplied object.</returns>
        bind: function (name, func, scope) {
            var list;

            name = name.toLowerCase();
            list = this.events[name] || [];
            list.push({ func: func, scope: scope || this });
            this.events[name] = list;
        },

        /// <summary>Removes the specified event listener.</summary>
        /// <param name="name" type="string">Name of event to remove.</param>
        /// <param name="func" type="function">Function to remove from listener.</param>
        unbind: function (name, func) {
            var list = this.events[name.toLowerCase()], i;

            if (list) {
                for (i = list.length - 1; i >= 0; i--) {
                    if (list[i].func === func) {
                        list.splice(i, 1);
                    }
                }
            }
        }
    };
}

/// <summary>Returns a new object based upon the supplied object (prototype inheritance).</summary>
/// <param name="o" type="object">The supplier object</param>
/// <returns>New object.</returns>
/// <remarks>
///     <para>
///         See http://javascript.crockford.com/prototypal.html and http://www.yuiblog.com/blog/2010/01/06/inheritance-patterns-in-yui-3/
///     </para>
/// </remarks>
FD.Object = function (o) {
    var F = function () { };
    F.prototype = o;
    return new F();
};

/* Enhance the built in date.parse function to support "basic" ISO-8601
 * only supports UTC datetimes.
 */
(function () {
    Date.prototype.toISOString = function() {
        var pad = function(n) {
                return n<10 ? '0'+n : n
            };

        return this.getUTCFullYear()      + '-'
            + pad(this.getUTCMonth() + 1) + '-'
            + pad(this.getUTCDate())      + 'T'
            + pad(this.getUTCHours())     + ':'
            + pad(this.getUTCMinutes())   + ':'
            + pad(this.getUTCSeconds())   + 'Z';
    };


    // Add the class to the body that scripting is possible
    // Note: moved from being an inline script so that ad blockers will trigger "scriptable" to not be added.
    $("body").addClass("scriptable");

}());



;
/**
* @license Core Fairfax Digital JavaScript library.
* Copyright 2010 Fairfax Digital.
*/
"use strict";

/*global FD:true, window:false */

/*
 * Extensions to fd.core.js reliant on jQuery
 */

FD.namespace("FD.Convert");
(function ($) {

    FD.Convert.toText = function (htmlString) {
        var div = $("<div/>");
        div.html(htmlString);
        return div.text();
    };

} (jQuery));;
$(function () {

    /* Equal heights */
    $(".feature-wrap.col-2 .panel").equalHeights();
    $(".feature-wrap.col-3 .panel").equalHeights();
    $(".static .first.col-3 .panel").equalHeights();
    $(".static .last.col-3 .panel").equalHeights();
    $(".ffx-radio-buttons.offer-choice li.selector").equalHeights()

	/* [Basic Behaviour]
	-------------------------------------------------------*/
	if ($(".asideFixPos").length != 0) {
		var top = $('.aside').offset().top - parseFloat($('.aside').css('marginTop').replace(/auto/, 0));
		$(window).scroll(function (event) {
			// what the y position of the scroll is
			var y = $(this).scrollTop();

			// whether that's below the form
			if (y >= top) {
				// if so, ad the fixed class
				$('.aside').addClass('fixed');
			} else {
				// otherwise remove it
				$('.aside').removeClass('fixed');
			}
		});
	}

    /* Toggle content - trigger injected (toggle-content) */
    $(".offer-choice .toggle-content").toggleCAP({
        trigger: {
            expand: "View publications",
            collapse: "Hide publications"
        }
    });
    $(".myads .toggle-content").toggleCAP({
        trigger: {
            expand: "View publications",
            collapse: "Hide publications"
        }
    });

    $("body").on("click", ".toggle-trigger", function (evt) {
        evt.preventDefault();
        return false;
    });

	/* Collapsible [cN-login] */
	if ($(".cN-login").parent(".aside").length == 0) {
		$(".cN-login h3").after('<a class="button login" href="javascript:void(0);">Log in to place your ad</a>');
		$(".cN-login a.login, .cN-signup-email a.login").click(function () {
			// apply this action to 'Log in' links elsewhere on the page as well
			$(".cN-login").addClass("expanded");
		});
	}

	/* iFrame auto height */
	$("iframe.autoHeight").iframeResize({ "height": "auto" });

	/* [Call Functions]
	-----------------------------------------------------------------------------*/
	$(".jsToggler").toggler();

	/* Popup hint */
	$("div.hint").each(function () { if($(this).prev('a.hint').length== 0) $(this).popupHint(); });

	/* Sticky panel */
	$(".stickyPos").stickyPanel();

	/* Modal - Async HTML fragments loaded into jQuery UI Dialog */
	$(".dialog-trigger").modal();

	/* Shopping cart toggle */
	$(".cN-cartSummary .cartToggle").cartToggle();

	/* Open popup window */
	$(".popupWindowTrigger").popupWindow();

	/* Print Dialog */
	$("a[rel*='print']").printDialog();

	$(".productPricing.col2 .panelInner").equalHeights();

	$(".productPricing.col3 .panelInner").equalHeights();

	$(".z-position").zPosition(1000);
	$(".cN-dialog .z-position").zPosition(2000);

	//    /* [jQuery UI]
	//    -----------------------------------------------------------------------------*/
	//    /* Datepicker */
	//    $(".datepickerTrigger").each(function () {
	//        $(this).datepicker({
	//            showOn: 'both',
	//            dateFormat: 'dd/mm/yy',
	//            buttonImage: "",
	//            buttonImageOnly: false,
	//            buttonText: 'Choose a date'
	//        });
	//    });

});

/* Height and vertical alignment adjustment for [cT-formFields]
...................................................................................... */
$(".cT-formFields > ul > li > label").each(function () {
	var label = $(this);
	// check if the label (incl. padding-top) is taller than the li containing it
	if (label.innerHeight() > label.parent().height()) {
		// if yes, add the class "tall" to the li
		label.parent().addClass("tall");
	}
});



/* --------------------------------------------------------------------------------------
@Functions
-------------------------------------------------------------------------------------- */

$.fn.fixSearchPreview = function () {
    var wrap = $(this).contents().find('div.wrap');
    wrap.css('width', 'auto');
    wrap.css('padding-top', '0px');
    $(this).iframeResize({ "height": "auto" });
}

/* fix z-index */
$.fn.zPosition = function (zIndexNumber) {
    return this.each(function () {
        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });
}

//Toggle an attribute on an element
$.fn.toggleAttr = function (attribute, on, off, check) {
	return this.each(function () {
		var $this = $(this);
		if (check)
			$this.attr(attribute, ($this.filter(":visible").length === 0 ? off : on));
		else
			$this.attr(attribute, ($this.attr(attribute) == on ? off : on));
	});
};

$.fn.cartToggle = function () {
	return this.each(function () {
		var cartToggle = $(this);
		var id = cartToggle.attr("id");
		var row = cartToggle.closest("tr");
		var breakdownClass = ".breakdown-" + id;
		var toggleRow = row.siblings(breakdownClass);
		toggleRow.attr("aria-labelledby", id);

		//Add aria-expanded and make element focusable
		cartToggle.attr({ "aria-expanded": "false", "tabindex": "0", "aria-controls": id });
		cartToggle.off("click keydown"); // ensure the click is only handled once
		cartToggle.on("click keydown", function (e) {
			if (e.keyCode == 13 || e.type == "click") {
			    //Toggle aria-expanded attribute value
				cartToggle.toggleAttr("aria-expanded", "true", "false", false).toggleClass("expanded");
				row.children(".price").toggleClass("collapsed");
				toggleRow.toggleClass("collapsed");
			}
		});

	});
}

/* Pop-up hints for [cT-formFields] and [cS-signup-email] */
$.fn.popupHint = function () {
    var hints = this;

	function toggleHint(container) {


		hintContainer = container.parent();

		// ensure only one hint is shown at a time
		if (!hintContainer.hasClass("hint-visible")) {
			/* check if the current item has the "hint-visible" class
			if not, it is currently hidden and is about to be shown, so hide every existing hint */
			hints.parent().removeClass("hint-visible");
		}
		// show/hide this hint
		hintContainer.toggleClass("hint-visible");
	}
 
	return this.each(function () {
		var container = $(this);
	    // insert link to show hint div (using title text of div if specified, otherwise use "Help"
		var hintButton = $('<a class="hint" title="Help" href="javascript:void(0);"><span>' + (this.title /*? this.title : "Help"*/) + '</span></a>');
		container.before(
		// <span> is needed to position text off screen. It's a fix that's needed for IE6. 
                hintButton.click(function () {
                    // get the position of the link so we can position the hint container relative to the link
                    var hintPos = $(this).position();

                    // get the left margin of the hint link. Need to convert it from string to integer.
                    var hintMarginL = parseInt($(this).css("margin-left").replace("px", "").replace("em", ""));
                    var hintPosLeft = Math.round(hintPos.left) + hintMarginL - 1; //-1 to align the popup hint with link outline

                    // get top coordinate and add a bit of spacing between link and hint container
                    var hintPosTop = Math.round(hintPos.top) + 20;

                    // position the hint container
                    if (container.hasClass("right")) {
                        container.css({ 'left': 'auto', 'right': '-8px', 'top': hintPosTop });
                    } else {
                        container.css({ 'left': hintPosLeft, 'top': hintPosTop });
                    }
                    toggleHint(container);
                })
        );

		if (container.hasClass('privacyToolTip')) {
		    hintButton.before($('<span class="tooltipTitle">' + (this.title) + '</span>').click(function () { hintButton.click();}));
		    $('.tooltipTitle').css({ 'border-bottom': '1px dashed', 'cursor': 'pointer' });
		}

		// add close link within hint div
		container.append(
            $('<a class="close" href="javascript:void(0);">Close</a>')
                .click(function () { toggleHint(container); })
        );
	});
};


/* [Toggle] - New function injects trigger (CAP version)
------------------------------------------------------*/
$.fn.toggleCAP = function (options) {
    var defaults = {
        mode: '', // 'alt'
        trigger: {
            expand: "Show", // "More"
            collapse: "Hide", // "Less"
            position: 'top' // 'bottom'
        }
    },
		settings = $.extend(true, defaults, options);

    var $elements = $(this);

    return $elements.each(function () {
        var $element = $(this),
			$trigger = $("<button></button>"),
			$group = $element.add($trigger);

        $trigger.addClass('toggle-trigger');
        $trigger.attr('tabindex', 0);

        $group.attr('aria-expanded', 'false');

        if (settings.mode == 'alt') {
            $group.addClass('alt');
        }

        $element.addClass('collapsed');

        $trigger.addClass('expand');
        $trigger.html(settings.trigger.expand);

        switch (settings.trigger.position) {
            case 'top':
                $element.before($trigger);
                break;
            case 'bottom':
                $element.after($trigger);
        }

        $trigger.on('click', function () {
            $group.toggleAttr('aria-expanded', 'true', 'false', false);

            $element.toggleClass('expanded collapsed');

            $trigger.toggleClass('expand collapse');
            $trigger.html(($element.hasClass('collapsed')) ? settings.trigger.expand : settings.trigger.collapse);
        });
    });
};


/* ======================================================================================
FUNCTIONS
====================================================================================== */

/* [Modal] - Async HTML injected into jQuery UI Dialog
-------------------------------------------------------*/
$.fn.modal = function (options) {
    var defaults = {
        modal: true,
        draggable: false,
        resizable: false,
        classes: {
            "ui-dialog" : "custom-dialog"
        },
        minWidth: false,
        minHeight: false,
        width: function () {
            return $(this).find(".dialog-wrap").width();
        },
        height: 'auto',
        appendTo: $("body")
    },
        settings = $.extend(true, defaults, options);

    $(this).on('click', function (event) {
        var $modal = $("<div></div>");
        $modal.load(
            this.href,
            null,
            function (responseText, textStatus, XMLHttpRequest) {
                $modal.dialog(settings);

                $modal.find(":focus").blur(); // clear initial focus

                $modal.find("iframe.autoHeight").iframeResize({ height: 'auto' }); // Resize iframed contents

                $modal.on('click', ".ui-dialog-titlebar-close, .dialog-close", function (event) {
                    $modal.trigger('dialogclose');
                });

                $modal.on('dialogclose dialogdestroy', function (event) {
                    $modal.dialog('destroy').remove();
                });
            }
        );

        event.preventDefault();
        event.stopPropagation();
    });

    return this;
};


/* Toggle function */
$.fn.toggler = function () {

	return this.each(function () {

		// enable tab access for toggler
		$(this).attr('tabindex', 0);

		// use .live() in case toggle elements are injected using JS
		$(this).on('click keypress', function (event) {
			// Click or Enter / Return key
			if (event.type == 'click' || (event.type == 'keypress' && event.which == 13)) {
				toggleAction(this);
				toggleHTML(this);
			}
			return false;
		});


		function toggleAction(thisElement) {
			if ($(thisElement).hasClass("jsToggleOpen")) {
				$(thisElement).removeClass("jsToggleOpen").addClass("jsToggleHide");
			}
			else if ($(thisElement).hasClass("jsToggleHide")) {
				$(thisElement).removeClass("jsToggleHide").addClass("jsToggleOpen");
			}

			//Get the next element .jsToggleElement
			var toggleElement = $(thisElement).next(".jsToggleElement");

			//if toggle element is hidden by default
			if ($(toggleElement).hasClass("jsToggleHidden")) {
				$(toggleElement).removeClass("jsToggleHidden").addClass("jsToggleOpen");
			}
			//if toggle element is shown by default
			else if ($(toggleElement).hasClass("jsToggleOpen")) {
				$(toggleElement).removeClass("jsToggleOpen").addClass("jsToggleHidden");
			}
		}

		function toggleHTML(thisElement) {
			var html = $(thisElement).text();

			if (html.indexOf("More") != -1) {
				thisElement.innerHTML = html.replace("More", "Less");
				return;
			}
			if (html.indexOf("Less") != -1) {
				thisElement.innerHTML = html.replace("Less", "More");
				return;
			}

			if (html.indexOf("more") != -1) {
				thisElement.innerHTML = html.replace("more", "less");
				return;
			}
			if (html.indexOf("less") != -1) {
				thisElement.innerHTML = html.replace("less", "more");
				return;
			}

			if (html.indexOf("Set") != -1) {
				thisElement.innerHTML = html.replace("Set", "Close");
				return;
			}
			if (html.indexOf("Close") != -1) {
				thisElement.innerHTML = html.replace("Close", "Set");
				return;
			}

			if (html.indexOf("Show") != -1) {
				thisElement.innerHTML = html.replace("Show", "Hide");
				return;
			}
			if (html.indexOf("Hide") != -1) {
				thisElement.innerHTML = html.replace("Hide", "Show");
				return;
			}
		}
	})
}



$(function () {
    $(".toggleAll .expand").click(function () {
        $(".toggleTrigger").children().removeClass("expand").addClass("collapse");
        $(".toggleContent").show();
    })

    $(".toggleAll .collapse").click(function () {
        $(".toggleTrigger").children().removeClass("collapse").addClass("expand");
        $(".toggleContent").hide();
    })
})


/* sticky panel */
$.fn.stickyPanel = function () {
	thisElement = $(this);
	thisElement.each(function () {
		var top = thisElement.offset().top;
		$(window).scroll(function (event) {
			// what the y position of the scroll is
			var y = $(this).scrollTop();

			if (y >= top) {
				// if scroller position passes the sticky element, add the fixed class
				thisElement.addClass('sticky');
			} else {
				// otherwise remove it
				thisElement.removeClass('sticky');
			}
		});
	})
}

/* Opens popup window - http://swip.codylindley.com/popupWindowDemo.html */
$.fn.popupWindow = function (instanceSettings) {

	return this.each(function () {

		$(this).click(function () {

			$.fn.popupWindow.defaultSettings = {
				centerBrowser: 0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
				centerScreen: 0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
				height: 700, // sets the height in pixels of the window.
				left: 0, // left position when the window appears.
				location: 0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
				menubar: 0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
				resizable: 0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
				scrollbars: 1, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
				status: 0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
				width: 800, // sets the width in pixels of the window.
				windowName: null, // name of window set from the name attribute of the element that invokes the click
				windowURL: null, // url used for the popup
				top: 0, // top position when the window appears.
				toolbar: 0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
			};

			settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});

			var windowFeatures = 'height=' + settings.height +
                            ',width=' + settings.width +
                            ',toolbar=' + settings.toolbar +
                            ',scrollbars=' + settings.scrollbars +
                            ',status=' + settings.status +
                            ',resizable=' + settings.resizable +
                            ',location=' + settings.location +
                            ',menuBar=' + settings.menubar;

			settings.windowName = this.name || settings.windowName;
			settings.windowURL = this.href || settings.windowURL;
			var centeredY, centeredX;

			if (settings.centerBrowser) {

				centeredY = window.screenY + (((window.outerHeight / 2) - (settings.height / 2)));
				centeredX = window.screenX + (((window.outerWidth / 2) - (settings.width / 2)));

				window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY).focus();
			} else if (settings.centerScreen) {
				centeredY = (screen.height - settings.height) / 2;
				centeredX = (screen.width - settings.width) / 2;
				window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY).focus();
			} else {
				window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + settings.left + ',top=' + settings.top).focus();
			}

			return false;
		});

	});
}

/* Print Dialog */
$.fn.printDialog = function () {
	var thisPrintLink = $(this);
	$.each(thisPrintLink, function () {
		$(this).click(function () {
			window.print();
			return false;
		});
	});
}

/*
* (modified) Equal Heights Plugin (http://www.cssnewbie.com/equalheights-jquery-plugin/)
* Equalize the heights of elements. Great for columns or any elements
* that need to be the same size (floats, etc).
* 
* Version 1.0
* Updated 12/10/2008
*
* Copyright (c) 2008 Rob Glazebrook (cssnewbie.com) 
*
* Usage: $(object).equalHeights([minHeight], [maxHeight]);
* 
* Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
* Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
* Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
* than 300 pixels tall. Elements with too much content will gain a scrollbar.
* 
*/
$.fn.equalHeights = function (minHeight, maxHeight) {
	tallest = (minHeight) ? minHeight : 0;
	this.each(function () {
		if ($(this).height() > tallest) {
			tallest = $(this).height();
		}
	});
	if ((maxHeight) && tallest > maxHeight) tallest = maxHeight;
	return this.each(function () {
		$(this).height(tallest); //.css("overflow","auto")
	});
}



/* whitestrip */

/* - split list of links so that links marked with the class "more" appear in a 'More' drop-down 
- enable keyboard operation by listening for keyboard tabbing to the 'More' link */
function listDropdownSplit(list) {
	// we need a controller list item, which contains a 'More' link and an empty (nested) list to hold the contents of the dropdown 
	var controller = $('<li class="controller last"><a href="javascript:void(0);">More</a><ul></ul></li>'),
	// also need a reference to the document object 
    doc = $(document);
	// append the new controller to the end of the original list 
	list.append(controller);
	// then append to the nested list within the controller all the items with the class "more" 
	controller.children("ul").append(list.find(".more"));
	// define function to hide dropdown (once shown by keyboard operation) 
	function closeDropdown() {
		controller.removeClass("focus");
		// once executed, unbind this handler from the window, as it is no longer required 
		doc.unbind("click", closeDropdown);
	}
	// enable keyboard operability by adding class "focus" to show dropdown when keyboard tabs to the 'More' link 
	controller.children("a").focus(function () {
		// check if the class "focus" already exists before running this function, because the user may have tabbed into the dropdown and then back to the controller link (in which case the dropdown will still be active) 
		if (controller.hasClass("focus")) return;
		controller.addClass("focus");
		// then bind handler to watch for click event to close dropdown 
		doc.click(closeDropdown);
		// also listen for keyboard tabbing beyond the last list item 
		controller.find("li:last-child a").blur(closeDropdown);
		// as well as keyboard tabbing back beyond the controller to the previous item 
		controller.prev().find("a").focus(closeDropdown);
	});
	// attach class to indicate script has executed 
	list.addClass("scripted");
}

// run the above function listDropdownSplit on elements that require it 
$(function () { listDropdownSplit($(".nN-whiteStrip .hasDropdownSplit")) });


// Modification from: http://code.google.com/p/sroucheray-js/wiki/JqueryIframeResizer

jQuery.fn.iframeResize = function (options) {

	var settings = jQuery.extend({
		width: null,
		height: null,
		timeout: 500
	}, options),
        loadedKey = "loaded",
        timeoutKey = "iframeResize_timeout";

	function resizeIframe() {
		var frame = jQuery(this),
            body = jQuery(this).contents().find("body");
		if (settings.width) {
			frame.css("width", (settings.width === "fill") ? "100%" : parseInt(settings.width, 10));
		}
		if (settings.height) {
			frame.css("height", settings.height === "auto" ? (body.outerHeight(true) + 5) : parseInt(settings.height, 10));
		}
		if (frame.data(timeoutKey)) {
			window.clearTimeout(frame.data(timeoutKey));
			frame.removeData(timeoutKey);
		}
	}

	function onEachIframe() {
		var frame = jQuery(this);
		// set a timeout on the max case... in case we missed the load event
		frame.data(timeoutKey, window.setTimeout(function () { if (!frame.data(loadedKey)) { resizeIframe.call(frame); } }, settings.timeout));
		// attach to the load event
		frame.on("load", function () { frame.data(loadedKey, true); resizeIframe.call(frame); });
	}

	jQuery(this).each(onEachIframe);
};

;
(function () {
    Date.prototype.setUTCKind = function () {
        if (this === null) {
            return null;
        }
        var buffer = new Date(
            Date.UTC(
                this.getFullYear(),
                this.getMonth(),
                this.getDate(),
                this.getHours(),
                this.getMinutes(),
                this.getSeconds(),
                this.getMilliseconds())
        );
        return buffer;
    };

    Date.prototype.setLocalKind = function () {
        if (this === null) {
            return null;
        }
        var buffer = new Date(
                this.getUTCFullYear(),
                this.getUTCMonth(),
                this.getUTCDate(),
                this.getUTCHours(),
                this.getUTCMinutes(),
                this.getUTCSeconds(),
                this.getUTCMilliseconds()
        );
        return buffer;
    };

    var __dateTest = new Date();
    if (typeof (__dateTest.toJSON) === "undefined") {
        // Sniff for toJSON function... and define if not present.
        // Only be the case for IE6 & 7
        Date.prototype.toJSON = function () {
            if (this === null) {
                return null;
            }
            var year = this.getUTCFullYear();
            var month = this.getUTCMonth();
            var date = this.getUTCDate();
            var hours = this.getUTCHours();
            var minutes = this.getUTCMinutes();
            var seconds = this.getUTCSeconds();
            var milliseconds = this.getUTCMilliseconds();
            return ""
                + ((year < 10) ? "0" : "")
                + ((year < 100) ? "0" : "")
                + year
                + "-"
                + ((month < 10) ? "0" : "")
                + month
                + "-"
                + ((date < 10) ? "0" : "")
                + date
                + "T"
                + ((hours < 10) ? "0" : "")
                + hours
                + ":"
                + ((minutes < 10) ? "0" : "")
                + minutes
                + ":"
                + ((seconds < 10) ? "0" : "")
                + seconds
                + "."
                + milliseconds
                + "Z";
        }
    }
}());;
(function ($) {
    var methods = {
        init: function (options, site) {
            var settings = {
                'minchars': 3,
                'sourceUrl': "/api/Location/GetSuburbSuggestion"
            };
            return this.each(function (index, Element) {
                $(function () {
                    // If options exist, lets merge them
                    // with our default settings
                    if (options) {
                        $.extend(settings, options);
                    }
                    if (site) {
                        settings.sourceUrl = settings.sourceUrl + "?site=" + site;
                    }

                    var 
                containerObj = $(Element),
                locationInputObj = containerObj.find(":input[type='text']"),
                locationInputId = "#" + locationInputObj.attr("id"),
                loadingObj = containerObj.find(".ui-loading"),
                locationDisplayObj = containerObj.find("p.text-value"),
                changeLinkObj = locationDisplayObj.find("a"),
                postcodeObj = containerObj.find(".location-postcode"),
                suburbObj = containerObj.find(".location-suburb"),
                stateObj = containerObj.find(".location-state"),

                showDescription = function (locationInputObj, locationDisplayObj, postcode, suburb, state) {
                    locationInputObj
                        .val("")
                        .autocomplete("close").addClass("hide");
                    locationDisplayObj
                        .removeClass("hide")
                        .find("span")
                        .html("<strong>" + suburb + "</strong> " + state + " " + postcode);
                    locationInputObj.trigger("change");
                };

                    locationInputObj.autocomplete({
                        minLength: settings.minchars,
                        select: function (event, ui) {

                            postcodeObj.val(ui.item.payload.Postcode);
                            suburbObj.val(ui.item.payload.Suburb);
                            stateObj.val(ui.item.payload.State);

                            showDescription(
                        locationInputObj, locationDisplayObj,
                        ui.item.payload.Postcode, ui.item.payload.Suburb, ui.item.payload.State);

                            $('form').validate().element(locationInputObj);

                            // Success
                            if (settings && settings.success) {
                                settings.success();
                            }
                            var data = $(containerObj).data('location');
                            if (data && data.success) {
                                data.success();
                            }
                        },
                        source: function (request, response) {
                            var cacheData = $(document.body).data('location');
                            if (cacheData && cacheData.cache) {
                                if (request.term in cacheData.cache) {
                                    response(cacheData.cache[request.term]);
                                    return;
                                }
                            }

                            loadingObj.show();
                            $.ajax({
                                url: settings.sourceUrl,
                                dataType: "json",
                                data: { keyword: request.term },
                                error: function () {
                                    loadingObj.hide();
                                },
                                success: function (data) {
                                    var
                                term = locationInputObj.val(),
                                highlightedData = {};

                                    loadingObj.hide();
                                    // if there is only one entry in the data then use it
                                    if (data.length === 1) {
                                        stateObj.val(data[0].State);
                                        suburbObj.val(data[0].Suburb);
                                        postcodeObj.val(data[0].Postcode);
                                        showDescription(locationInputObj, locationDisplayObj, data[0].Postcode, data[0].Suburb, data[0].State);
                                        $('field-validation-valid').addClass('hide');
                                        
                                    } else {
                                        // Highlight keywords
                                        highlightedData = $.map(data, function (item) {
                                            var
                                    findExpr = new RegExp("(" + term + ")", "gi"),
                                    highlightedItem = {
                                        Postcode: (item.Postcode != null)?item.Postcode.replace(findExpr, "$1"):"",
                                        Suburb: (item.Suburb != null) ? item.Suburb.replace(findExpr, "$1") : "",
                                        State: (item.State != null) ? item.State.replace(findExpr, "$1>") : ""
                                    };

                                            return {
                                                value: item.Suburb + " " + item.State + " " + item.Postcode,
                                                label: highlightedItem.Suburb + ", " + highlightedItem.State + " " + highlightedItem.Postcode,
                                                payload: item
                                            };
                                        });
                                        var data = $(document.body).data('location');
                                        if (!data) {
                                            data = {};
                                        }
                                        if (!data.cache) {
                                            data['cache'] = {};
                                        }
                                        data.cache[request.term] = highlightedData;
                                        $(document.body).data('location', data);
                                        response(highlightedData);
                                    }
                                }
                            });
                        }
                    });

                    // Hookup the change link to toggle back the search box
                    changeLinkObj.click(function (e) {
                        e.preventDefault();

                        locationDisplayObj.addClass("hide");
                        stateObj.val("");
                        suburbObj.val("");
                        postcodeObj.val("");
                        loadingObj.hide();
                        locationInputObj.val("").removeClass("hide").focus();
                    });

                    // Pre-populate the display text if data is available
                    var postcode = postcodeObj.val(),
                suburb = suburbObj.val(),
                state = stateObj.val();

                    if ((postcode && postcode.length > 0) &&
                (suburb && suburb.length > 0) &&
                (state && state.length > 0)) {
                        showDescription(
                    locationInputObj, locationDisplayObj,
                    postcode, suburb, state);
                    }

                    locationInputObj.focusout(function () {
                        $(this).attr('data-val-locationdata-enabledvalid', true);
                    });

                    locationInputObj.focus(function () {
                        $(this).attr('data-val-locationdata-enabledvalid', false);
                    });
                });


            });
        },
        success: function (successfunction) {
            return this.each(function (index, Element) {
                var data = $(Element).data('location');
                if (!data) {
                    data = {
                        'success': successfunction
                    };
                }
                data.success = successfunction;
                $(Element).data('location', data);
            });


        },
        changing: function (changingfunction) {
            return this.each(function (index, Element) {
                var data = $(Element).data('location');
                if (!data) {
                    data = {
                        'changing': changingfunction
                    };
                }
                data.changing = changingfunction;
                $(Element).data('location', data);
            });

        },
        destroy: function () {
            return this.each(function () {
                $(window).unbind('.location');
            });

        },
        lostfocus: function () {

            alert('Lost Focus');

        }
    };

	$.fn.location = function (method) {

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.location');
		}

	};

	$("[data-val-locationdata]").keyup(function () { return false });

    $.validator.addMethod(
        "locationdata",
        function (value, element, params) {
            var containerObj = $("#" + params.clientid);
            var url = 'VerifyLocation';

            var customUrl = containerObj.data("val-locationdata-url");
            if (customUrl != null && customUrl.length > 0)
                url = customUrl;

            var IsAddressValid = false;

            if (params.isonelinetext === "False") {
                //particular used for domain
                //location does not appear in one line text, find current fieldset children relevant element
                var postcodeVal = containerObj.closest("fieldset").find('.postcode').val(),
                    suburbVal = containerObj.closest("fieldset").find('.suburb').val(),
                    stateVal = containerObj.closest("fieldset").find('.state').val();

                if (params.isrequired === "False" && (postcodeVal.length == 0 || suburbVal.length == 0 || stateVal.length == 0))
                    return true;

                $.ajax({
                    cache: false,
                    success: function (data) {
                        if (data === 'True') IsAddressValid = true;
                    },
                    error: function (request, status, error) {
                        return false;
                    },
                    url: url + '?postcode=' + postcodeVal + '&state=' + stateVal + '&suburb=' + suburbVal,
                    type: 'GET',
                    async: false
                });
                

                if (IsAddressValid === true) return true;
                if (IsAddressValid === false) return false;
            }
            else {
                var locationTextobj = $("#" + params.clientid + '_LocationText');
                if (locationTextobj != 'undefined' || locationTextobj != null) {
                    if ((params.isrequired != "True" && locationTextobj.val() != null && locationTextobj.val().length == 0) || locationTextobj.attr('data-val-locationdata-enabledvalid') == 'false') {
                        return true;
                    }
                }

                var postcodeVal = containerObj.find("input[name$='" + params.clientname + "." + params.postcodepropname + "']").val(),
                    suburbVal = containerObj.find("input[name$='" + params.clientname + "." + params.suburbpropname + "']").val(),
                    stateVal = containerObj.find("input[name$='" + params.clientname + "." + params.statepropname + "']").val();

                if (stateVal == null) {
                    stateVal = containerObj.find("select[name$='" + params.clientname + "." + params.statepropname + "']").val();
                }

                if (!containerObj || containerObj.length == 0 || !stateVal || !postcodeVal || !suburbVal) {
                    // try to obtain the postcode, suburb, state values straight using the property names as ID.
                    postcodeVal = $("#" + params.clientid + "_" + params.postcodepropname).val();
                    suburbVal = $("#" + params.clientid + "_" + params.suburbpropname).val();
                    stateVal = $("#" + params.clientid + "_" + params.statepropname).val();
                }

                if ((postcodeVal && postcodeVal.length > 0) &&
                        (stateVal && stateVal.length > 0)) {
                    var ddlStates = containerObj.find("select[name$='" + params.clientname + "." + params.statepropname + "']").length;

                    if (ddlStates == 0) return true;

                    if ($("#" + params.clientid + '_LocationText').length == 0) {
                        //other location text
                        //validate if state and postcode combination is correct

                        var isPaymentAddress = containerObj.data("ispayment");

                        if (isPaymentAddress === true) {

                            $.ajax({
                                cache: false,
                                async: false,
                                success: function (data) {
                                    if (data) {
                                        IsAddressValid = true;
                                    }
                                },
                                error: function (request, status, error) {
                                    return false;
                                },
                                url: '/api/Location/GetLocation?postcode=' + postcodeVal + '&state=' + stateVal + '&suburb=' + suburbVal,
                                type: 'GET',
                                async: false
                            });
                        } else {

                            $.ajax({
                                cache: false,
                                async: false,
                                success: function (data) {
                                    IsAddressValid = data;
                                },
                                error: function (request, status, error) {
                                    return false;
                                },
                                url: url + '?postcode=' + postcodeVal + '&state=' + stateVal + '&suburb=' + suburbVal,
                                type: 'GET',
                                async: false
                            });
                        }

                        if (IsAddressValid === true) return true;
                    } else if (suburbVal && suburbVal.length > 0)
                        //autocomplete location text
                        return true;
                }
                return false;
            }
        }, "Fail");


    $.validator.unobtrusive.adapters.add('locationdata', ['clientid', 'clientname', 'postcodepropname', 'statepropname', 'suburbpropname', 'isonelinetext', 'isrequired'],
            function (options) { options.rules['locationdata'] = options.params; options.messages['locationdata'] = options.message;});

})(jQuery);

;
/**
* @license Core Fairfax Digital JavaScript library.
* Copyright 2010 Fairfax Digital.
*/
"use strict";

// Global Declarations for JSLint
/*global FD:true, window:true, jQuery:false */

/// <reference path="fd.core.js" />

FD.namespace("FD.Classifieds.CasualAds.YearMonthPicker");

(function ($) {
    FD.Classifieds.CasualAds.YearMonthPicker.setup = function (monthClientId, yearClientId, targetInputClientId) {
        var monthClient = $(monthClientId),
            yearClient = $(yearClientId),
            targetInputClient = $(targetInputClientId),
            updateDateFn = function () {
                var monthVal = monthClient.val(),
                    yearVal = yearClient.val()

                if (monthVal && yearVal)
                {
                    var dateString = '1 ' + monthVal + ' ' + yearVal;
                    targetInputClient.val(dateString);
                }
                else
                {
                    targetInputClient.val('');
                }
            };

        $([monthClient, yearClient]).each(function (index) {
                this.change(function () {
                    updateDateFn();
                });
            });
    };
}(jQuery));;
(function ($) {
    $.ajaxSetup({
        statusCode: {
            401: function () {
                alert("Sorry, your session has timed out. The screen will now be reloaded.");
                document.location = document.location.href;
            },
            415: function () {
                // error is on fail event
            },
            500: function () {
                // error is on fail event                
            }
        }
    });


    FD.namespace("FD.Images");
    FD.Images.Uploader = function (targetElement) {
        this.targetElement = targetElement;

        // Attach the KO stuff...
        this.model = new ImageLibraryViewModel();
        this.model.webApiUrl(targetElement.data("webapiurl")); // "/api/imagelibrary/"
        this.model.standardFileCount(targetElement.data("standardfilecount"));
        this.model.upsellFileCount(targetElement.data("upsellfilecount"));
        this.model.upsellActive(targetElement.data("upsellactive"));
        this.model.fieldPrefix(targetElement.data("fieldprefix"));
        this.model.selectedImages(targetElement.data("initial"));

        var erroMsg = targetElement.data("exceedlimitmsg");
        if (erroMsg != undefined && erroMsg != "")
            alert(erroMsg)

        this.model.hasPrimaryImage(targetElement.data("hasprimaryimage"));
        this.model.labelText(targetElement.data("labeltext"));

        this.model.uploader = this;

        ko.applyBindings(this.model, targetElement.parents(".ad-photos").get(0));
    };

    FD.Images.Uploader.prototype.init = function (webApiUrl)
    {
        var self = this;
        self.fileupload = this.targetElement.fileupload({
            dataType: 'json',
            dropZone: $("#drop_zone"),
            url: webApiUrl,
            progressInterval: 10,
            singleFileUploads: true, // post multiple files in one request
            done: function (e, data) {
                $.each(data.result, function (index, file) {
                    self.model.inProgressImages.pop();
                    if (file.Message != null && file.Message.length > 0) {
                        alert(file.Message);
                    } else {
                        self.model.selectedImages.push(file);
                    }
                });
            },
            add: function (e, data) {
                var shouldCancel = false;
                $.each(data.files, function (index, file) {
                    if (file.size > self.model.maxFileSize()) {
                        //exceed the max file size
                        shouldCancel = true;
                        alert("The image to be uploaded should not exceed 10 MB");
                        return false;
                    }

                    if (self.model.placeholdersToShow().length == 0) { // placeholderstoshow becomes a pseudonym for how many photos they can upload now. 
                        // If they can't upload any more, then remove the existing selection (the button they clicked is "change")
                        self.model.selectedImages.pop();
                    }
                    self.model.inProgressImages.push("");
                });

                if (!shouldCancel)
                    data.submit();
            },
            progress: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
            },
            start: function (e) {
                /*didError = false;
                statusBar.css("width", fullBar * 0.1 + "px");
                theForm.dialog("close");
                theStatusContainer.dialog('open');*/
            },
            stop: function (e) {
                /*statusBar.css("width", fullBar + "px");
                //theInputContainer.show();
                theStatusContainer.dialog('close');
                if (didError) {
                theForm.dialog("open");
                }*/
            },
            fail: function (e, data) {
                //didError = true;
                self.model.inProgressImages.pop();
                if (data.jqXHR != null) {
                    var file = $.parseJSON(data.jqXHR.responseText);
                    if (data.jqXHR.status == 415) {
                        if (file != null && file.length > 0) {
                            alert("Sorry, unable to upload file " + file[0].Filename + ". " + file[0].Message);
                        }
                        else {
                            alert("Sorry, unable to upload file. No further information is available. Please check that the file does not exceed file size limits.");
                        }
                    }
                    else if (data.jqXHR.status == 500) {
                        if (file != null && file.length > 0) {
                            alert("Sorry, unable to upload file " + file[0].Filename + ". " + file[0].Message);
                        }
                        else {
                            alert("Sorry, unable to upload file. There was a problem with the request. Please check that the file does not exceed file size limits.");
                        }
                    }
                }
            }
        });

        $(document).on('drop dragover', function (e) {
            e.preventDefault();
        });
    }

    FD.Images.Uploader.prototype.prompt = function () {
        $("input:file", this.targetElement).trigger('click');
    }

    FD.Images.Library = {
        /*all: function () {
            $.ajaxSetup({ "async": false });
            var result = $.getJSON('/api/imagelibrary/');
            $.ajaxSetup({ "async": true });
            return $.parseJSON(result.responseText);
        },

        single: function (id) {
            alert("single: " + id);
        },*/

        delet: function (id, uri) {
            var result = $.ajax(uri + id,
            {
                "dataType": 'json',
                "async": false,
                "type": "DELETE"
            });
            return true;
        }
    };

    FD.Images.Cropping = {
        crop: function () {
            alert("crop");
        }
    };



    function ImageLibraryViewModel() {
        var self = this;


        self.webApiUrl = ko.observable();

        // Fields
        self.selectedImages = ko.observableArray(); // the images the user has chosen. Populate this on page load for pre-selected images
        self.inProgressImages = ko.observableArray(); // the images that are currently being uploaded
        self.standardFileCount = ko.observable(1); // The number of images able to be uploaded when upsell inactive
        self.upsellFileCount = ko.observable(5); // The number of images able to be uploaded when the upsell is active
        self.upsellActive = ko.observable(false); // Whether or not the upsell is active
        self.maxFileSize = ko.observable(10485760); // Maximum file size
        self.hasPrimaryImage = ko.observable(true); // Whether or not there is a primary image
        self.labelText = ko.observable("Photos"); // The label text
        self.showMoreToggle = ko.observable(true);

        self.fieldPrefix = ko.observable("PrefixNotSet"); // Set the prefx in data-fieldprefix
        self.uploader = null;

        // Properties
        self.maximumFileCount = ko.computed(function () {
            if (this.upsellActive()) { return this.upsellFileCount(); }
            return this.standardFileCount();
        }, this);

        // UI Function to show a maximum number when not "expanded"
        self.showMoreToggleThresholdReached = ko.computed(function () { return this.maximumFileCount() > 9; }, this);
        self.toggleShowMoreToggle = function (setting) {
            self.showMoreToggle(!self.showMoreToggle());
        };
        // END UI toggle function

        self.multipleFilesAllowed = ko.computed(function () {
            var allowed = this.maximumFileCount() > 1;
            return allowed;
        }, this);
        self.canUploadImages = ko.computed(function () {
            return (this.selectedImages().length + this.inProgressImages().length) < this.maximumFileCount();
        }, this);
        self.uploadedImageCount = ko.computed(function () {
            return this.selectedImages().length;
        }, this);
        self.inProgressImagesCount = ko.computed(function () {
            return this.inProgressImages().length;
        }, this);
        self.placeholdersToShow = ko.computed(function () {
            // always show a placeholder for each remaining possible photo. Min:1
            // show extra placeholders based on showMoreToggle
            var maxFileCount = this.maximumFileCount();
            var defaultMaximum = 1;
            if (!this.showMoreToggle()) { // the "show more" toggle will be visible.
                maxFileCount = Math.min(9, this.maximumFileCount());
                defaultMaximum = 0;
            }
            return new Array(Math.max(defaultMaximum, maxFileCount - (this.selectedImages().length + this.inProgressImages().length)));
        }, this);
        self.itemsToShowInList = ko.computed(function () {
            if (this.selectedImages().length > this.maximumFileCount()) {
                // Too many files being used. Remove all but the first up to maximumFileCount()
                this.selectedImages().splice(this.maximumFileCount(), this.selectedImages().length);

            }

            var images = $.map(this.selectedImages(), function (result, i) {
                return {
                    item: result,
                    itemType: 'image'
                };
            });
            var progress = $.map(this.inProgressImages(), function (result, i) {
                return {
                    item: result,
                    itemType: 'progress'
                };
            });
            var placeholders = $.map(this.placeholdersToShow(), function (result, i) {
                return {
                    item: result,
                    itemType: 'placeholder'
                };
            });
            var allItems = images.concat(progress, placeholders);
            // remove extra items if required (they will be progress or placeholders) 
            // this is to prevent the UI showing extra items. 
            if (allItems.length > this.maximumFileCount()) {
                allItems.splice(this.maximumFileCount(), allItems.length);
            }
            return allItems;
        }, this);


        // Functions
        self.uniqueFieldName = function (data, fieldname) {
            if (data.currentKey == undefined) {
                data.currentKey = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }
            return self.fieldPrefix() + ".SelectedPhotos[" + data.currentKey + "]." + fieldname;
        };

        self.keyedFieldName = function (data, fieldname) {
            if (data.currentKey == undefined) {
                data.currentKey = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }
            return self.fieldPrefix() + ".SelectedPhotos." + fieldname;
        };

        self.deleteImage = function (data) {
            FD.Images.Library.delet(data.item.Id, self.webApiUrl());
        };
        self.deselectImage = function (data) {
            if (!confirm("Are you sure you want to remove this image?")) {
                return;
            }
            self.selectedImages.remove(function (item) { return item === data.item });
            if (data.item.Id > 0) {
                self.deleteImage(data);
            }
        };
        self.promptForFiles = function () {
            if (self.uploader != undefined) {
                self.uploader.prompt();
            }
        }

        self.enableUpsell = function (data, event) {
            $this = $(event.target);
            $upsellPanel = $this.closest('.upsellPanel');
            if (CAP.common.PlaceAd.addProduct($upsellPanel.data('key'))) {
                self.upsellActive(true);
                $('.reloadable').reloadPanel(initCartToggle); // reload all panels, in case "swapOut" affects other features
            } else {
                alert('Failed to add product');
            }
        };
        self.disableUpsell = function (data, event) {
            // TODO: Ajax call to disable upsell
            if (self.selectedImages().length > self.standardFileCount()) {
                if (!confirm("You have uploaded more than " + self.standardFileCount() + " image" + (self.standardFileCount() > 1 ? "s" : "") + ". Removing this option will also remove any images other than the first " + self.standardFileCount() + ".\r\nAre you sure you want to remove the option?")) {
                    return;
                }
                // remove the excess images...
                self.selectedImages(self.selectedImages.slice(0, self.standardFileCount()));
            }
            $this = $(event.target);
            $upsellPanel = $this.closest('.upsellPanel');
            if (CAP.common.PlaceAd.removeProduct($upsellPanel.data('key'), false)) {
                self.upsellActive(false);
                $('.reloadable').reloadPanel(initCartToggle); // reload all panels, in case "swapOut" affects other features
            } else {
                alert('Failed to remove product');
            }

        };


    }

    /* Photo Uploader - sortable */
    /*$(".sortable-list").sortable({
    placeholder: "placeholder",
    items: 'li:not(.placeholder-cue)'
    });
    */
    $(".sortable-list").disableSelection();



    $(".uploader").each(function () {
        var u = new FD.Images.Uploader($(this));
        u.init($(this).data("webapiurl"));
    });

    $(document).on('featured-upsell-changed.fd', function (evt, data) {
        if (data) {
            var context = ko.contextFor($('.uploader', $(evt.target)).get(0));
            if (data.isActive) {
                context.$data.upsellActive(true);
            }
            else {
                context.$data.upsellActive(false);
            }
        }
    });

})(jQuery);;
$('a[href*="/PreviewWeb"]').not('.back').click(ShowPreview);
$('a[href*="/PreviewPrint"]').not('.back').click(ShowPreview);

function ShowPreview(evt) {
    var url = $(evt.target).attr('href');
    var isCapSite = $("body").hasClass("cap");
    if (isCapSite)
        PreviewOverlay(url);
    else
        PreviewOverlayNonCAP(url);
    evt.preventDefault();
}

function PreviewOverlayNonCAP(url) {
    $.ajax({
        url: url,
        success: function (data, textStatus, jqXHR) {

            var redirect = jqXHR.getResponseHeader('X-Redirect');

            if (redirect)
                window.location = redirect;
            else {
                // wrap the returned data in a dialog then append it
                var head = '<div class="previewDialog">';
                var tail = '</div>';
                var newdata = head + data + tail;

                $(document.body).append(newdata);
                if (url.indexOf("Web") >= 0) {

                    $('.previewDialog').dialog({
                        title: "Web ad preview",
                        autoOpen: false,
                        bgiframe: true,
                        modal: true,
                        resizable: true,
                        draggable: false,
                        width: 680,
                        height: 580,
                        open: function (event, ui) {
                            $("iframe.autoHeight", this).iframeResize({ "height": "auto" });
                            $('iframe.autoHeight').load(function () {
                                var wrap = $(this).contents().find('div.wrap');
                                wrap.css('width', 'auto');
                                wrap.css('padding-top', '0px');
                            });
                        }
                    });
                } else {
                    $('.previewDialog').dialog({
                        autoOpen: false,
                        bgiframe: true,
                        modal: true,
                        resizable: false,
                        width: 680
                    });
                }
                $('.previewDialog').bind('dialogclose', function (event) {
                    $('.previewDialog').remove();
                });
                $('.previewDialog').dialog('open');
            }
        },
        error: function () {
            alert('error');
        }
    });

    
};

function PreviewOverlay(url) {
    $.ajax({
        url: url,
        success: function (data, textStatus, jqXHR) {

            var redirect = jqXHR.getResponseHeader('X-Redirect');

            if (redirect)
                window.location = redirect;
            else {
                // wrap the returned data in a dialog then append it
                var head = '<div class="previewDialog">';
                var tail = '</div>';
                var newdata = head + data + tail;

                $(document.body).append(newdata);
                if (url.indexOf("Web") >= 0) {
                    $('.previewDialog').addClass("cN-dialog ad-preview");
                    $('.previewDialog').dialog({
                        title: "Online ad preview",
                        autoOpen: false,
                        modal: true,
                        resizable: true,
                        draggable: false,
                        width: 900,
                        height: 680,
                        open: function (event, ui) {
                            var $frames = $("iframe.autoHeight", this);

                            $frames.removeData('loaded'); // Demo only: ensure iframe resizing occurs (not required if dialog injected on trigger click)
                            $frames.iframeResize({ "height": "auto" });
                        }
                    });
                } else {
                    $('.previewDialog').dialog({
                        autoOpen: false,
                        bgiframe: true,
                        modal: true,
                        resizable: false,
                        width: 680
                    });
                }
                $('.previewDialog').bind('dialogclose', function (event) {
                    $('.previewDialog').remove();
                });
                $('.previewDialog').dialog('open');
            }
        },
        error: function () {
            alert('error');
        }
    });


};
;
(function ($) {

    FD.namespace('FD.CasualAds.AdDetails.Common');

    FD.CasualAds.AdDetails.Common.ShowLoadingMessage = function (message) {
        // put up the please wait...
        var theStatusContainer = $("<span id='loadingMessage' />");
        var theMessage = $("<span />");
        //theMessage.append("Loading. Please Wait...");
        theStatusContainer.append(theMessage);
        theStatusContainer.dialog({ autoOpen: true,
            title: message,
            resizable: false,
            dialogClass: "no-close",
            modal: true,
            closeOnEscape: false,
            draggable: false
        });
    };

    FD.CasualAds.AdDetails.Common.HideLoadingMessage = function () {
        $("#loadingMessage:ui-dialog").dialog('close');
        $("#loadingMessage:ui-dialog").dialog('destroy');
        $("#loadingMessage").remove();
    };

    $(document)
        .on('product.adding', function () { FD.CasualAds.AdDetails.Common.ShowLoadingMessage("Adding upgrade..."); })
        .on('product.removing', function () { FD.CasualAds.AdDetails.Common.ShowLoadingMessage("Removing upgrade..."); })
        .on('product.addingError product.removingError product.refreshingError product.refreshed product.added product.removed', FD.CasualAds.AdDetails.Common.HideLoadingMessage);

    var fd_placead_showLoadingMessage = FD.CasualAds.AdDetails.Common.ShowLoadingMessage;

    $(document).on("change", ".submitonchange", function (e) {
        if (!e.isDefaultPrevented()) {
            // attach a hidden field to indicate this submit comes from an autosubmit
            var fld = $("<input />").attr("type", "hidden").attr("name", "autoSubmitOnly").val("true");
            $(this.form).append(fld);
            fd_placead_showLoadingMessage("Loading. Please Wait...");
            $(this.form).validate().settings.ignore = "*"
            this.form.submit(); // submit the form, bypass all validation
        }
    });

} (jQuery));

;
/**
* @license CasualAds workflow
* Copyright 2010 Fairfax Digital.
*/
"use strict";

// Global Declarations for JSLint
/*global FD:true, document:false, window:true, jQuery:false, s_gi:false, s_account:false */

/// <reference path="fd.js" />

(function ($) {
    $.fn.ffxMultiSelectTextBox = function (options) {
        var self = this; // the backing field


        // default settings
        var settings = { 
            'placeholdertext' : '- Please select -',
            'customoptiontext' : 'Other (please specify)',
            'dropdownvalues' : []
        }

        // Merge the default settings with options in order to get custom settings
        if (options) {
            $.extend(settings, options);
        }

        // hide the backing field
        self.hide();

        // "this" will be the hidden field we are dropdowning.
        // add a dropdown
        var newDropDownName = self.attr("id") + "Preset";
        var presetOptions = $("<select />").attr("id", newDropDownName).attr("name", newDropDownName);
        self.attr("invalid-focus-insteadof", newDropDownName);

        presetOptions.addOption(settings.placeholdertext, "-1", false);

        for(var option in settings.dropdownvalues){
            presetOptions.addOption(settings.dropdownvalues[option], settings.dropdownvalues[option], false);
        }

        presetOptions.addOption(settings.customoptiontext, "-2", false);

        presetOptions.insertBefore(this);

        // insert some whitespace to get the spacing properly
        presetOptions.after("\r\n\r\n");

        var customField = $("<input />")
            .attr("type", "text")
            .attr("value", "")
            .attr("placeholder", "please specify...")
            .insertBefore(this);
    
        // handle the dropdown changing
        presetOptions.change(function() {
            var selectedVal = presetOptions.val();
            switch (selectedVal) {
                case "-1": 
                    self.val("");
                    customField.val("");
                    customField.fadeOut();
                    break;
                case "-2":
                    self.val("");
                    customField.val("");
                    customField.fadeIn();
                    break;
                default: 
                    self.val(selectedVal);
                    customField.val("");
                    customField.fadeOut();
                    break;
            } 
        });

        // handler for the custom textbox changing
        customField.change(function() { 
            self.val(customField.val());
        });

        // Initialise the UI correctly for the current val on plugin initialisation
        switch (self.val()){
            case "":
                // hide custom field
                customField.fadeOut();
                break;
            default:
                // see if the value is in the list of available presets and select it
                if (presetOptions.find(":contains('" + self.val() + "')").length > 0)
                {
                    presetOptions.val(self.val());
                    customField.fadeOut();
                }
                else
				{
                    presetOptions.val("-2");
                    customField.val(self.val());
                    customField.fadeIn();
                }

                //
                break;
        }

    };


    // bind an event handler to focus on our inserted fields
    $("form").on("invalid-form.validate", function (e, validator) {
            // If the invalid field has this attribute, then focus on that field instead.
            var focusInstead = $(validator.errorList[0].element).attr("invalid-focus-insteadof");
            if (focusInstead != "")
            {
                try {
                $("#" + focusInstead).focus().trigger("focusin");
                } catch(e) {
                    // empty catch for IE focusing on hidden fields exception
                    // as per same code in jquery.validate.js
                }
                e.preventDefault();
            }
    });

})(jQuery);

;

jQuery(function ($) {
    $(".myAds .toggle.alt").toggleContent({
        btnInject: false,
        toggleBtnTrigger: $(".toggleTrigger"),
        toggleSpeed: 0,
        role: 'button',
        shownByDefault: true
    });

    $(".myads .toggle.alt").toggleContent({
        btnInject: false,
        toggleBtnTrigger: $(".toggleTrigger"),
        toggleSpeed: 0,
        role: 'button',
        shownByDefault: true
    });

    $(".toggle.alt:not(.defaultopen)").toggleContent({
        btnInject: false,
        toggleBtnTrigger: $(".toggleTrigger"),
        toggleSpeed: 0,
        role: 'button',
        shownByDefault: false
    });

    $(".defaultopen.toggle.alt").toggleContent({
        btnInject: false,
        toggleBtnTrigger: $(".toggleTrigger"),
        toggleSpeed: 0,
        role: 'button',
        shownByDefault: true
    });

    $(".list-faq .toggle").toggleContent({
        btnInject: false,
        toggleBtnTrigger: $(".toggleTrigger"),
        toggleSpeed: 0,
        role: 'button'
    });

    $("body.mycareer .faq .toggle").toggleContent({
        btnInject: false,
        toggleBtnTrigger: $(".toggleTrigger a"),
        toggleSpeed: 0,
        role: 'button'
    });

});

(function ($) {

    //Toggle an attribute on an element
    $.fn.toggleAttr = function (attribute, on, off, check) {
        return this.each(function () {
            var $this = $(this);
            if (check)
                $this.attr(attribute, ($this.filter(":visible").length === 0 ? off : on));
            else
                $this.attr(attribute, ($this.attr(attribute) == on ? off : on));
        });
    };

    $.fn.toggleContent = function (options) {
        // Setup defaults
        var defaults = {
            // Define the toggle button's wrapper and element
            toggleBtnWrap: null, // Wrapper around button element
            toggleBtnTrigger: $('<button type="button" class="btnToggle btnFauxLink"></button>'), // Mark up for button element
            toggleContent: ".toggleContent",
            btnTxtOpen: 'Show more', // Text you want in the button *before* toggling
            btnTxtClose: 'Show less', // Text you want in the button *after* toggling
            btnPos: 'insertAfter', // Where you want to inject the button. Values: "insertAfter" || "insertBefore"
            btnOpenClass: 'expand', // Button class when content is hidden and button indicates it can be opened
            btnCloseClass: 'collapse', // Button class when content is shown and button indicates it can be closed
            toggleSpeed: 200,
            shownByDefault: false,
            callBackMethod: null,
            btnInject: false
        }

        return $(this).each(function (i, e) {

            if (!$(e).data('fd.toggleContent'))
            {
                $(e).data('fd.toggleContent', true);

                // Merge defaults and options
                var settings = $.extend(defaults, options);

                var toggleWrap = $(e);
                var toggleContent = toggleWrap.find(settings.toggleContent);
                var toggleBtnWrap = settings.toggleBtnWrap;
                var toggleBtnTrigger = settings.toggleBtnTrigger;
                var btnInject = settings.btnInject;
                var btnTxtOpen = settings.btnTxtOpen;
                var btnTxtClose = settings.btnTxtClose;
                var btnPos = settings.btnPos;
                var btnOpenClass = settings.btnOpenClass;
                var btnCloseClass = settings.btnCloseClass;
                var toggleSpeed = settings.toggleSpeed;
                var shownByDefault = settings.shownByDefault;
                var callBackMethod = settings.callBackMethod;

                // Show content
                showContent = function (toggleBtnTrigger) {
                    toggleBtnTrigger.addClass(btnCloseClass).html(btnTxtClose);
                    toggleContent.show().toggleAttr("aria-expanded", "false", "true", false);
                    toggleBtnTrigger.toggleAttr("aria-expanded", "true", "false", false);

                }

                // Hide content 
                hideContent = function (toggleBtnTrigger) {
                    toggleBtnTrigger.addClass(btnOpenClass);
                    toggleBtnTrigger.html(btnTxtOpen);
                    toggleContent.hide();
                    toggleContent.toggleAttr("aria-expanded", "false", "true", false);
                    toggleBtnTrigger.toggleAttr("aria-expanded", "false", "true", false);
                }

                if (!btnInject) {
                    toggleBtnTrigger = toggleWrap.find(toggleBtnTrigger);
                    btnTxtOpen = toggleBtnTrigger.html();
                    btnTxtClose = toggleBtnTrigger.html();
                }

                // When clicking on the toggle button
                toggleBtnTrigger.click(function () {
                    toggleContent.slideToggle(toggleSpeed, function() {
                        toggleContent.toggleAttr("aria-expanded", "true", "false", false);
                        toggleBtnTrigger.toggleClass(btnCloseClass).toggleClass(btnOpenClass).toggleAttr("aria-expanded", "true", "false", false);
                        if (toggleContent.is(":visible")) {
                            toggleBtnTrigger.html(btnTxtClose);
                            if (callBackMethod)
                                callBackMethod(toggleContent, true);
                        } else {
                            toggleBtnTrigger.html(btnTxtOpen);
                            if (callBackMethod)
                                callBackMethod(toggleContent, false);
                        }
                    });
                });


                // If toggle content is visible by default
                if (shownByDefault) {
                    showContent(toggleBtnTrigger);
                    if (callBackMethod)
                        callBackMethod(toggleContent, true);
                } else {
                    hideContent(toggleBtnTrigger);
                    if (callBackMethod)
                        callBackMethod(toggleContent, false);
                }

                // Create the toggle button (wrapper + button trigger)
                var toggleBtn = null;
                if (toggleBtnWrap !== null)
                    toggleBtn = toggleBtnWrap.append(toggleBtnTrigger);
                else
                    toggleBtn = toggleBtnTrigger;

                // Inject the toogle button
                if (btnInject) {
                    switch (btnPos) {
                        case ("insertAfter"): // insert after the hidden content	
                            toggleBtn.insertAfter(toggleContent);
                            break;
                        case ("insertBefore"): // insert before the hidden content	
                            toggleBtn.insertBefore(toggleContent);
                            break;
                    }
                }
            }
        })
    }

} (jQuery));;
FD.namespace('FD.Classifieds.CasualAds.Web.Billing');

(function ($) {

	populateLocation("BillingAddress");
	populateLocation("PostalAddress");

	function toggleCompanyNameABN(element) {
        if ($(element).prop("checked")) {
            $('.HideCompanyNameABN').slideDown();
            $('.HideCompanyNameABN input').not('.paymentmethod').attr('disabled', false);
        }
        else {
            $('.HideCompanyNameABN').slideUp();
            $('.HideCompanyNameABN input').not('.paymentmethod').attr('disabled', true);
        }
    }

    toggleCompanyNameABN($('#HasBillingCompanyName'));

    $('#HasBillingCompanyName').click(function () {
        toggleCompanyNameABN(this);
    });

    $('input.placeholder').each(function () {
        if ($(this).val().replace(/\s/, '') == '') $(this).removeClass('placeholder-inactive').addClass('placeholder').val(this.title);
    });

    FD.Classifieds.CasualAds.Web.Billing.SetPaymentMethod = function (paymentmethod) {
        if (paymentmethod == "Invoice") {
            //$("#payment-details").hide();
            //$("#payment-details :input").not('.paymentmethod').attr("disabled", true);
            $("#HasBillingCompanyName").closest("li").hide();
            $("#HasBillingCompanyName").attr("checked", "checked"); // force this to checked for invoice
            $(".HideCompanyNameABN").show();
            $('.HideCompanyNameABN input').not('.paymentmethod').prop("disabled", false);
            $("#saveAd").val("Complete booking");
        }
        else // prepaid, paypal, none
        {
            $("#BillingAddress").show();
            $("#HasBillingCompanyName").closest("li").show('fast', function () {
                if ($("#HasBillingCompanyName:checked").length === 0) {
                    $(".HideCompanyNameABN").hide();
                    $('.HideCompanyNameABN input').not('.paymentmethod').attr('disabled', true);
                }
            });
            $(".purchaseordernumber")
                .hide()
                .find("input").attr("disabled", "disabled");
            $("#saveAd").val("Make payment");

        }

        // hide billing details for invoiced commercial accounts
        if ($("#IsCommercialAccount").val() == "True") {
            $("#BillingAddress").hide();
            $(".purchaseordernumber")
                .hide()
                .find("input").attr("disabled", "disabled");
        }

    };

    $("#saveAd.payment").click(function () {
        var paymentMethod = $("input[name$='PaymentMethod']:checked").val();
        ga('send', 'event', 'SSC: Payment Method Selected', paymentMethod);
	});

	
    $("input[name$='PaymentMethod']").change(function () {
		if($(this).prop("checked")){
			FD.Classifieds.CasualAds.Web.Billing.SetPaymentMethod($(this).val());
		}
    });

    if ($("input[name$='PaymentMethod']").length > 0) {
        FD.Classifieds.CasualAds.Web.Billing.SetPaymentMethod($("input[name$='PaymentMethod']:checked").val());
    }


    function disableChildren(formToggle, isShown) {
        if (!isShown) {
            //console.log("closed ===============>");
            formToggle.find('input').not('.paymentmethod').attr('disabled', true);
            formToggle.find('select').not('.paymentmethod').attr('disabled', true);
           // $('.PostalAddress-active').val('false');
            //console.log($('#PostalAddress_Suburb').attr('disabled'));
        } else {
            //console.log("open ===============>");
            formToggle.find('input').prop("disabled", false);
            formToggle.find('select').prop("disabled", false);
            $('.PostalAddress-active').val('true');
        }
    }

    // only collapse the alternate address field if there are no details entered in it.
    
    var showAlternateAddress = false;
    if ($("#alternative-address").find(".field-validation-error").length > 0) {
        showAlternateAddress = true;
    }


    $(".formToggle").toggleContent({
        toggleBtnWrap: $('<div class="formIndent formToggleTriggerWrap"></div>'),
        toggleContent: "#alternative-address",
        toggleBtnTrigger: $('<a href="javascript:;" role="button" class="button alt"></a>'),
        btnTxtOpen: 'Add an alternative mailing address',
        btnTxtClose: 'Remove alternative mailing address',
        btnInject: true,
        btnPos: 'insertAfter',
        role: 'button',
        callBackMethod: disableChildren,
        shownByDefault: showAlternateAddress
    });

    /*postcode validation*/
    $("#BillingAddress_State").change(function () {
        if ($("#BillingAddress_Postcode").val() != '')
            $("#BillingAddress_Postcode").valid();
    });

    $("#PostalAddress_State").change(function () {
        if ($("#PostalAddress_Postcode").val() != '')
            $("#PostalAddress_Postcode").valid();
    });
		

	$("#BillingAddress_Country").change(function () {
		populateLocation("BillingAddress");
	});




	function populateLocation(type) {
		var element = $('#' + type);
 
		if($(element) != 'undefined' || $(element).length > 0)
		{
			 var country = $('#' + type + '_Country').val();
			 if(country == 'au')
			{
				$("#" +  type + " .nationalLocation").show().find('input, select').not('.paymentmethod').prop("disabled", false);
				$("#" + type + " .internationalLocation").hide().find('input, select').not('.paymentmethod').attr('disabled', true);
			     $("label[for="+type+"_State] em").show();
			}else
			{
				$("#" +  type + " .internationalLocation").show().find('input, select').not('.paymentmethod').prop("disabled", false);
				$("#" +  type + " .nationalLocation").hide().find('input, select').not('.paymentmethod').attr('disabled', true);
				$("label[for=" + type + "_State] em").hide(); // if country is not aus then state is optional
			}
		}
    }	

    FD.Classifieds.CasualAds.Web.Billing.ShowProcessingUI = function () {
        //hide the side bar and other element on the page.
        $('.aside').hide();
        $('.progressMeter ').hide();
        $('.fN-serviceLinks').hide();
        $('.nav-network').hide();
        $('.cN-headerMessage').hide();
        //hide the payment form
        $("#paymentform").hide();

        $('.main').append("<div class='processing-payment'><h1>Processing your order</h1><p class='loading'>Please wait....</p><p>Do not click the refresh or back button or this transaction may be interrupted or terminated.</p><p>If you chose to pay with PayPal, you will shortly be redirected to PayPal in order to complete payment.</p></div>");
    };

	$("#FormPayment").on("submit",(function (event) {
        if (!$(this).valid() || $('#PaymentMethodNonce').length) {
	        event.preventDefault();
        }
	    else {
            FD.Classifieds.CasualAds.Web.Billing.ShowProcessingUI();
	    }
	}));


	ko.bindingHandlers.slideVisible = {
	    init: function (element, valueAccessor) {
	        // Initially set the element to be instantly visible/hidden depending on the value
	        var value = valueAccessor();
	        $(element).toggle(ko.utils.unwrapObservable(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
	    },
	    update: function (element, valueAccessor) {
            // slide in / slide out as it changes
	        var value = valueAccessor();
	        ko.utils.unwrapObservable(value) ? $(element).slideDown() : $(element).slideUp();
	    }
	};
	ko.bindingHandlers.valueWithInit = {
	    init: function (element, valueAccessor, allBindingsAccessor, data) {
	        var property = valueAccessor(),
                value = element.value;

	        //create the observable, if it doesn't exist 
	        if (!ko.isWriteableObservable(data[property])) {
	            data[property] = ko.observable();
	        }

	        data[property](value);

	        ko.applyBindingsToNode(element, { value: data[property] });
	    }
	};

	function BillingDetailsViewModel(defaultPaymentMethod) {
	    var self = this;
	    self.paymentMethod = ko.observable(defaultPaymentMethod);
	    self.companyName = ko.observable();
	    self.companyAbn = ko.observable();
	    self.creditCardNumber = ko.observable("");

        // The rest of the model is used to make the right card logo highlight as you type...
	    self.creditCardType = ko.computed(function () {
            if (self.creditCardNumber().substr(0, 1) == "4") {
	            return "visa";
	        } else if (self.creditCardNumber().substr(0, 1) == "5") {
	            return "mastercard";
	        } else if (self.creditCardNumber().substr(0, 2) == "34" || self.creditCardNumber().substr(0, 2) == "37") {
	            return "amex";
	        } else if (self.creditCardNumber().substr(0, 2) == "30" || self.creditCardNumber().substr(0, 2) == "36" || self.creditCardNumber().substr(0, 2) == "38") {
	            return "diners";
	        } else {
	            return "";
	        }
	    });
	    self.isAmex = ko.computed(function () {
	        return self.creditCardType() == "amex" || self.creditCardType() == "";
	    });
	    self.isVisa = ko.computed(function () {
	        return self.creditCardType() == "visa" || self.creditCardType() == "";
	    });
	    self.isDiners = ko.computed(function () {
	        return self.creditCardType() == "diners" || self.creditCardType() == "";
	    });
	    self.isMastercard = ko.computed(function () {
	        return self.creditCardType() == "mastercard" || self.creditCardType() == "";
	    });
	}
	if (document.getElementById("paymentform")) {
	    ko.applyBindings(new BillingDetailsViewModel($("#paymentmethodforknockout").val()), document.getElementById("paymentform"));
	}

})(jQuery);


;
(function ($) {

    $('.status a[href*="/RerunPrint/"]').click(function (evt) {

        var $booking = $(evt.target).closest('.toggleContent');

        $('#rerun-print-dialog:ui-dialog').dialog('destroy');
        $('#rerun-print-dialog').remove();

        $.ajax({
            url: $(evt.target).attr('href'),
            success: function (data, textStatus, jqXHR) {
                var redirect = jqXHR.getResponseHeader('X-Redirect'),
                    title = '';

                if (redirect)
                    window.location = redirect;
                else {
                    var $result = $('<div id="rerun-print-dialog"/>');
                    $(document.body).append($result);
                    $result.append(data);
                    $.validator.unobtrusive.parse($result.find('form'));
                    $result.dialog({
                        bgiframe: true,
                        modal: true,
                        resizable: false,
                        width: 530,
                        title: $result.children().first().attr('title')
                    });
                }
            },
            error: function () {
                alert('error');
            }
        });

        evt.preventDefault();
    });

    $('.dialogCopy').dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        resizable: false,
        width: 530,
        title: 'Copy your ad'
    });

    $(document).on("click", 'a[href*="/Copy/"]', function (evt) {
        FD.log($(evt.target).attr('href'));
        var _this = $(this);

        if (!_this.hasClass('disabled'))
        {    
            _this.text("Copying...");
            _this.addClass('disabled');                    

            $.ajax({
                url: $(evt.target).attr('href'),
                type: "POST",
                success: function (data, textStatus, jqXHR) {
                    if (data.d && data.d.redirect) {
                        window.location.href = data.d.redirect;
                    }
                    else {
                        $('.dialogCopy').find('#copy-web').data('redirect', data.d.webUrl);
                        $('.dialogCopy').find('#copy-bundle').data('redirect', data.d.bundleUrl);

                        $('.dialogCopy').find('.next').on('click', function () {
                            var selectedOption = $('.dialogCopy').find('input:radio:checked').first().data('redirect');

                            window.location.href = selectedOption;

                            $('.dialogCopy').dialog('close');
                        });
                        $('.dialogCopy').find('.cancel').on('click', function () {
                            $('.dialogCopy').dialog('close');
                        });
                        $('.dialogCopy').dialog('open');
                    }
                },
                error: function () {
                    alert('An error occurred. Please try again.');
                    _this.removeClass('disabled');
                    _this.text("Copy");                
                }
            });
        }
        else{
            console.log( _this, " Execution bypassed");                
        }
        evt.preventDefault();
    });

    $(".cT-formFields .date input").datepicker({ dateFormat: "dd/mm/yy" });

} (jQuery));
;
jQuery(function() {

            if($('#AdRemovalReason').val() == 'Other'){ $('#otherReasonDetail').show();}
            $('#AdRemovalReason').change(function(){
                if($('#AdRemovalReason').val() == 'Other')
                {
                    $('#otherReasonDetail').slideDown('fast');
                }else
                {
                     $('#otherReasonDetail').slideUp('fast');
                }
            });
});;
/**
* @license Casualads 
* Copyright 2012 Fairfax Digital.
*/
"use strict";

// Global Declarations for JSLint
/*global FD:true, jQuery:false */

FD.namespace('FD.Classifieds.CasualAds.SessionRenew');

(function ($) {

    var timeoutInitial = null;
    var intervalInitial = null;
    //session timeout time is one hour
    var sessionTime = 3600000;
    var renewTimes = 0;

    FD.Classifieds.CasualAds.SetSessionTime = function(time) 
    {   
        sessionTime = time;
    };

    FD.Classifieds.CasualAds.SessionRenew = function(){

		if(typeof flowID != 'undefined')
		{
			$.ajax({
                    url: "/PlaceAd/RenewSession?flowID=" + flowID,
                    type: 'POST',
                        success: function(data, textStatus, jqXHR) {
                        //console.log(data.d.timedout);
                        if(data.d.timedout)
                        {
                            //session is already timedout
                            alert('Your session has timed out');
                            FD.Classifieds.CasualAds.RedirectToIndex();
//                        }else{
//                            //continue counting the renew session times
//                            renewTimes ++ ;
//                        }

//                        if(renewTimes >= 5)
//                        {
//                            renewTimes = 0;
//                            clearInterval(intervalInitial);

//                            var timeLeftTill = new Date();
//                            timeLeftTill.setMilliseconds(timeLeftTill.getMilliseconds() + sessionTime);

//                            var reply = confirm("Are you still there? Your session is about to timeout at " + timeLeftTill.toLocaleTimeString() +  "and all changes will be lost. Click Ok to renew your session, click Cancel to return to home page.");
//                            if(reply)
//                            {
//								FD.Classifieds.CasualAds.SessionRenew();
//                                //restart the interval
//                                FD.Classifieds.CasualAds.PopupInvocation();
//                            }else{
//								FD.Classifieds.CasualAds.RedirectToIndex(); 
//                            }
                        }
                             
                    },
                    error: function() {
                        //alert('Error occurs');
                    }
              });
		}
    };

    FD.Classifieds.CasualAds.RedirectToIndex = function(){
        var home = "/";
        try {
            if (typeof(FD.Classifieds.CasualAds.HomeUrlRelative) == "undefined") {
                home = "/";
            }
            else {
                home = FD.Classifieds.CasualAds.HomeUrlRelative;
            }
        } catch (e) {
            home = "/";
        }
        window.location.href = home;
    };


    FD.Classifieds.CasualAds.TimeoutInvocation = function(){
        //if the session is not renewed redirect to index page after timeout
        timeoutInitial = window.setTimeout("FD.Classifieds.CasualAds.RedirectToIndex()", sessionTime);
    };

    FD.Classifieds.CasualAds.PopupInvocation = function(){

		//FD.Classifieds.CasualAds.SessionRenew();
		 
        //set the interval as 5 mins (300000ms)
        intervalInitial = window.setInterval("FD.Classifieds.CasualAds.SessionRenew()", 300000);
 
    };

//    FD.Classifieds.CasualAds.DisableSessionRenew = function(){
//        clearInterval(intervalInitial);
//    };

    //if mouse move detected on the page 
    $("body").mousemove(function(){
        renewTimes = 0;
    });

    $("body").keypress(function(){
        renewTimes = 0;
    });

    $.ajaxSetup({
        complete: function(event, xhr, options){
            var redirectUrl = event.getResponseHeader('x-redirect');
            if (redirectUrl != null)
            {
                window.location.href = redirectUrl;
            }
        }//,
        //error: function(e, jqxhr, settings) {
              //alert("An error has occurred. Please call customer support.");
//            var redirectUrl = e.getResponseHeader('x-redirect');
//            if(redirectUrl!= null && redirectUrl != 'undefined')
//                window.location.href = redirectUrl;
//            else
//                window.location.href = '/Error/Unknown'; 
        //}

    });
     
} (jQuery));
;
(function ($) {
    FD.namespace('FD.CasualAds.confirmationDialog');

    FD.CasualAds.confirmationDialog.options = {
        title: "Please confirm...",
        yes_button: "Yes",
        no_button: "No",
        content: "Are you sure?"
    };

    var $confirmDialog = $('<div />').html("<div class='dialogContent'></div>");
    $confirmDialog.addClass('cN-dialog');
    $confirmDialog.append("<div class='dialogFooter'><ul class='cT-formActions'><li><input type='button' class='button next' value='Yes' /></li><li><input type='button' class='button cancel' value='No' /></li></ul></div>")

    function ensureConfirmation(evt, boundElement, options) {
        var isConfirmationReceived = false,
            localOptions = $.extend({}, FD.CasualAds.confirmationDialog.options, options);

        if ($(boundElement).data("confirmation-received")) {
            isConfirmationReceived = true;
        }

        if (!isConfirmationReceived) {

            evt.preventDefault();

            $confirmDialog.find('input.next')
                .off('click')
                .on('click', function () {
                    $confirmDialog.dialog("close");
                    $(boundElement).data("confirmation-received", true);
                    switch (evt.type) {
                        case "click":
                            // must split click out so that <a> tags are followed on click
                            evt.target.click();
                            break;
                        default:
                            $(evt.target).trigger({
                                "type": evt.type,
                            });
                            break;
                    }
                })
                .val(localOptions.yes_button);
            $confirmDialog.find('input.cancel')
                .off('click')
                .on('click', function () {
                    $confirmDialog.dialog("close");
                    $(boundElement).data("confirmation-received", null);
                })
                .val(localOptions.no_button);

            $confirmDialog.find(".dialogContent").html(localOptions.content);

            $confirmDialog.dialog({
                autoOpen: true,
                title: localOptions.title,
                modal: true,
                width: localOptions.width || 360
            });
        }
        else {
            // second time around... clear the flag now
            $(boundElement).data("confirmation-received", null);
        }
    }

    FD.CasualAds.confirmationDialog.ShowUI = function (options) {
        localOptions = $.extend({}, FD.CasualAds.confirmationDialog.options, options);

        $confirmDialog.find('input.next')
            .off('click')
            .on('click', function () {
                $confirmDialog.dialog("close");
                localOptions.confirm();
            })
            .val(localOptions.yes_button);
        $confirmDialog.find('input.cancel')
            .off('click')
            .on('click', function () {
                $confirmDialog.dialog("close");
                localOptions.cancel();
            })
            .val(localOptions.no_button);

        $confirmDialog.find(".dialogContent").html(localOptions.content);

        $confirmDialog.dialog({
            autoOpen: true,
            title: localOptions.title,
            modal: true,
            width: localOptions.width || 360
        });
    };

    function DataPresent() {
        var isPresent = false;

        var dataValues = $("input:visible").not(".button").add("textarea:visible").add(".imageData");
	
        FD.each(dataValues, function (ab) {
            if ($(this).val() !== "") isPresent |= true;
        })

        FD.each(CKEDITOR.instances, function (ab) {
            if (this.getData() !== "") isPresent |= true;
        })
        return isPresent;
    }

    $(function () {
        $(".breadcrumb li a").click(function (evt) {
            if (DataPresent()) {
                ensureConfirmation(evt, this, {
                    content: "<p>Please note that changing the basic details of your Ad (such as the section or publication) will result in the information you have input to be discarded.</p><p>Please confirm that you want to proceed.</p>"
                });
            }
        });
        $(".confirm-data-loss-on-click-template-type-change").click(function (evt) {
            if (DataPresent()) {
                ensureConfirmation(evt, this, {
                    content: "<p>Please note that changing the Ad Type will result in the information you have input to be discarded.</p><p>Please confirm that you want to proceed.</p>"
                });
            }
        });
        $(".confirm-data-loss-on-click-template-change").click(function (evt) {
            if (DataPresent()) {
                ensureConfirmation(evt, this, {
                    content: "<p>Please note that changing the template will result in the information you have input to be discarded.</p><p>Please confirm that you want to proceed.</p>"
                });
            }
        });
        $(".confirm-cancel-ad-placement").click(function (evt) {
            ensureConfirmation(evt, this, {
                title: "Get me out of here",
                content: "<p>You are about to navigate away from this page.<br />All changes will be lost!</p><p>Are you sure you want to cancel these changes?</p>",
                yes_button: "Yes, get me out of here",
                no_button: "No, return to ad"
            });
        });
        $(".confirm-make-payment-method").click(function (evt) {
            var method = $(this).attr("data-method");
            if (method == "PrePaid" || method == "BraintreeCreditCard") {
                method = "Credit Card";
            }

            var form = $("#FormPayment");
            if (!form.valid()) {
                evt.preventDefault();
            }
            else if ($('#PaymentMethodNonce').length && !$('#PaymentMethodNonce').val()) {
                evt.preventDefault();
            }
            else {
                
                ensureConfirmation(evt, this, {
                    title: "Confirm Payment Method",
                    content: "<p>You have chosen to pay for this ad with " + method + ". You will not be able to change the payment method, once you confirm.</p> <p>Please confirm by clicking on Continue to proceed with the payment or Cancel to change to a different payment method option.</p>",
                    yes_button: "Continue",
                    no_button: "Cancel"
                });
            }
        });
        $(".confirm-trade-services-ad").click(function (evt) {
            ensureConfirmation(evt, this, {
                title: "Confirm Trade Services Ad",
                content: "<p>Please note that Trade Services ad placed with Advertisers.com.au will appear in the <strong>general classifieds section</strong> of the newspaper. To place an ad in the double column Trades and Services Directory, please <a href='/Page/ContactUs' rel='noopener noreferrer' target='_blank'>contact Customer Support</a>.</p><p style='text-align:center;margin:auto;'><img src='/Content/Classifieds/images/Trade-Services-example.jpg' style='height:400px' /></p><p>By clicking 'Continue', you confirm that you have understood where your ad will appear.</p>",
                yes_button: "Continue",
                no_button: "Cancel",
                width: 800,
            });
        });
    });
}(jQuery));;
/**
IMplements a graphical radio button or multiselect list. 

Usage:
Markup such as (all attributes after data-max-choices are to enable validation):

<span class="ffx-radio-buttons" data-max-choices="1"  data-validate="true" data-min-choices="2" data-validation-message="You must select at least 2 publishing dates">
<span class="selector">
<input name="publication" type="checkbox" value="some-value" />
<img src="/Content/Classifieds/images/some_logo.gif" />
</span>
<!-- repeat selector class as appropriate -->
<!-- the selected selector will just have "selected" class added, style as you wish -->
</span>
    

And include this script. all .ffx-radio-buttons will be initialised on page load.

TODO: Improvement, instead of handling the click event, should try and leverage <label> but that screwed up CSU styling.
**/
(function ($) {
    var methods = {
        clearselection: function () {
            var selected = $("input:checkbox:checked", $(this));
            selected.prop("checked", false);
            selected.trigger('change');
        },
        refreshselection: function (settings) {
            //FD.log(settings.mode);
            if (settings.mode == "ckeditor") {

                return;
            }
            // refresh the selected status of all items...
            if (settings.display_mode == "dialog") {
                $(".selector", "#chosen_" + settings.id).remove();

            }

            $.each($(settings.selector, $(this)), function (objIndex, eachObj) {
                // attach, or detach, the selected class...
                $(eachObj).toggleClass("selected", $("input", $(eachObj)).is(":checked"));
                // ... and if selected append the value to the currentValues...
                if ($("input", $(eachObj)).is(":checked") && settings.display_mode == "dialog") {
                    $("#chosen_" + settings.id).prepend($(eachObj).clone());
                    $("#chosen_" + settings.id).children().show(); // make sure what we cloned into it is visible
                }

                //$("#chosen_" + settings.id).append(dialogOpener);
            });
            // allow anybody to listen in on this objects changed event
            var remaining = settings.max_choices - $(".selector.selected", $(this)).length;
            $(this).data("remaining-choices", remaining);
            $(this).trigger("selectionchanged");
        }
    };


    $.fn.ffxCoolRadioSelector = function (options) {
        var self = this; // the collecction of container(s) 

        return this.each(function () {
            var radiocontainer = this;
            //FD.log("Initialising ffxCoolRadioSelector on ...");
            //FD.log(radiocontainer);
            dataoptions = { "max_choices": $(radiocontainer).data("max-choices"),
                "min_choices": $(radiocontainer).data("min-choices"),
                "validate": $(radiocontainer).data("validate"),
                "validation_message": $(radiocontainer).data("validation-message"),
                "auto_submit": $(radiocontainer).data("auto-submit"),
                "selection_mode": $(radiocontainer).data("selection-mode"),
                "display_mode": $(radiocontainer).data("display-mode"),
                "dialog_link_text": $(radiocontainer).data("dialog-link-text"),
                "mode": $(radiocontainer).data("mode")
            };
            // default settings for all radio collections
            var settings = {
                'max_choices': '1',
                'selector': '.selector',
                'validate': 'false',
                'min_choices': '0',
                'validation_message': '',
                'auto_submit': false,
                'selection_mode': 'normal',
                'display_mode': 'normal',
                "dialog_link_text": 'Choose Item',
                'guid': '',
                'id': '',
                "mode": ''
            };
            // Merge the default settings with options in order to get custom settings
            $.extend(settings, dataoptions);


            // We need a unique ID for the validation field, so make an inline random v4 GUID: http://stackoverflow.com/a/2117523/58155
            var validatorId = 'coolradio-'
            settings.guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
            settings.id = validatorId = validatorId + settings.guid;


            $(settings.selector, $(radiocontainer)).removeClass("selected"); // hide all the indicators
            //$(settings.selector + " input:checkbox", $(radiocontainer)).hide(); // hide all the checkboxes


            // Insert a validation field...
            var currentCountField = $("<input />")
                .attr("id", validatorId)
                .attr("name", validatorId)
                .attr("data-val", settings.validate)
                .attr("data-val-required", "Required: " + settings.validation_message)
                .attr("data-val-range", settings.validation_message)
                .attr("data-val-range-max", settings.max_choices)
                .attr("data-val-range-min", settings.min_choices)
                .attr("style", "display:none;");         //.attr("type", "hidden"); - Can't use type: hidden as then onkeyup won't trigger properly
            if (settings.auto_submit) {
                currentCountField.attr("class", "submitonchange");
            }



            $(radiocontainer).parent().append(currentCountField);
            //...and corresponding validation message
            var validatorMessage = $("<span />")
            .attr("class", "field-validation-valid")
            .attr("data-valmsg-for", validatorId)
            .attr("data-valmsg-replace", "true");
            $(radiocontainer).parent().append(validatorMessage);


            // Note: must do this after adding all other dynamic objects.
            // As soon as .dialog() is called the selectors are pulled out and placed at the end of the DOM outside of the form.
            if (settings.display_mode == "dialog") {

                var chosenItemsContainer = $("<span />")
                    .attr("class", "chosen-items")
                    .attr("id", "chosen_" + validatorId);
                $(radiocontainer).parent().parent().append(chosenItemsContainer);

                $(chosenItemsContainer).append($("<a />")
                    .text(settings.dialog_link_text)
                    .attr("class", "edit dialog-opener button alt")
                    .attr("id", "open_" + validatorId)
                    .click(function () {
                        $(radiocontainer).parent().dialog("open");
                        //clear the mode data value
                        $(radiocontainer).data("mode", "");

                    })
                );
                $(document).on("click", "#chosen_" + validatorId + " .selector1, #chosen_" + validatorId + " .logo-remover", null, function () {
                    if (confirm("Do you want to remove this selection?")) {
                        methods.clearselection.apply($(radiocontainer));
                        //enable all the tint colour scheme
                        $('.colourSchemeBlock').trigger('enableTint');
                    }
                });

                $(document).on("click", "#chosen_" + validatorId + " .edit", null, function () {
                    $(radiocontainer).parent().dialog("open");
                    $(radiocontainer).data("mode", "");
                });

                var dialogButtons = [{ text: "Close", click: function () { $(this).dialog("close"); } }];
                if ($(radiocontainer).hasClass('logo-selector')) {
                    dialogButtons = [
                            { text: "Use selected logo", click: function () {
                                $(this).dialog("close");
                            }
                            },
                            { text: "Upload another logo", click: function () { $(radiocontainer).trigger("uploadnewlogoclicked"); } }

                            ]
                }

                $(radiocontainer).parent().dialog({ autoOpen: false,
                    title: settings.dialog_link_text,
                    resizable: false,
                    closeOnEscape: false,
                    width: 700,
                    height: 600,
                    modal: true,
                    buttons: dialogButtons
                });
            }

            $(radiocontainer).on("click", settings.selector, function (evt) {
                if (!evt.isDefaultPrevented()) {
                    clickedSelector = this;
                    if ($(this).hasClass("disabled")) {
                        //alert("This selection is not valid. You may need to de-select one of the other options first");
                        return false;
                    }

                    $(settings.selector, $(radiocontainer)).data("clicked-by-user", "false");
                    $(clickedSelector).data("clicked-by-user", "true");
                    $(clickedSelector).children("input:checkbox").prop("checked", !$(clickedSelector).children("input:checkbox").prop("checked"));
                    $(clickedSelector).children("input:checkbox").trigger("change");
                }
            });

            // Whenever one of the print days checkbox values change, hide/show the icon correctly/
            $(radiocontainer).on('change', settings.selector + " input:checkbox", function () {
                var changedCheckbox = this;
                var remaining = settings.max_choices - $(settings.selector + " input:checked", $(radiocontainer)).length;
                switch (settings.selection_mode) {
                    case 'ownerlogic':
                        // do nothing, but trigger event with clicked one
                        // i.e. normal functionality + own logic + no restriction
                        $(radiocontainer).trigger("selectionstarted", [$(changedCheckbox).parent()]);
                        break;
                    case 'radio':
                        if (remaining == 1 && settings.min_choices > 0 && $(changedCheckbox).parent().data("clicked-by-user") == "true") {
                            // in rdaio mode, disallow deselecting the last chosen option, so re-check it
                            $(changedCheckbox).prop("checked", true);
                        } else if (remaining < 0) {
                            // work in "radio" mode, deselct the other choice(s)
                            $(settings.selector + " input:checked", $(radiocontainer)).prop("checked", false);
                            // select the clicked choice
                            $(changedCheckbox).prop("checked", true);
                        }
                        break;
                    default: // normal
                        // prevent selecting a new checkbox if they have no selections remaining
                        if (remaining < 0) {
                            $(changedCheckbox).prop("checked", false);
                            alert("You must deselect another choice before continuing");
                            return;
                        }
                        break;


                }

                // hook into the jquery validation to show/hide the validation message
                currentCountField.val($(settings.selector + " input:checked", $(radiocontainer)).length);
                currentCountField.trigger("keyup"); // this works with the dynamic hide/show functionality


                if (settings.auto_submit && $(changedCheckbox).parent().data("clicked-by-user") == "true") {
                    currentCountField.trigger("change");
                }

                settings.mode = $(radiocontainer).data("mode");

                if (settings.mode == "ckeditor") {
                    $(radiocontainer).trigger("itemSelected");
                }


                // refresh the selected status of all items...
                methods.refreshselection.apply($(radiocontainer), [settings]);
            });


            // On initialisation, trigger all the change events to synchronise the icons.
            //$(settings.selector, $(radiocontainer)).find("input").trigger("change");
            currentCountField.val($(settings.selector + " input:checked", $(radiocontainer)).length);
            methods.refreshselection.apply($(radiocontainer), [settings]);
        });

    }

    $(document).ready(function () {
        try {
            //FD.log("Initialising ffxCoolRadioSelector...");
            $(".ffx-radio-buttons").ffxCoolRadioSelector();
        }
        catch (err) {
            alert("Failed to initialise some elements of the page. Please Press Refresh.");
            FD.log(err);
        }
    });
} (jQuery));


;
/*
Implements a "quicksand" style dom filter.
Required structure:
<div class="ffx-quicksand">
<a class="ffx-quicksand-action" data-grouping="ALL"></a> // optional
<a class="ffx-quicksand-action" data-grouping="ABC"></a>
<a class="ffx-quicksand-action" data-grouping="DEF"></a>

<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
</div>
*/
(function ($) {
    var plugin = {
		createguid: function () {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
				var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
				return v.toString(16);
			});
		},
		// Get the quicksand containers current selection value
		currentselection: function () {
			var selectedItem = $(".ffx-quicksand-action.selected", $(this));
			return selectedItem.data("grouping");
		},
		updateselection: function (selected) {
			$(".ffx-quicksand-action", $(this)).toggleClass("selected", false);
			$(selected).toggleClass("selected", true);
		},
		showgroup: function (grouptoshow) {
		    var opts = $(this).data("options");

			if (grouptoshow == "ALL" || opts.disableActionItems) {
				$(".ffx-quicksand-item", $(this)).show();
			} else {
				$(".ffx-quicksand-item", $(this)).hide();
				$(".ffx-quicksand-item[data-grouping='" + grouptoshow + "']", $(this)).show();
			}
			
			if (opts.alwaysShowSelected) {
			    $(".ffx-quicksand-item.selected", $(this)).show();
			}
		},
		init: function (options) {
		    

			return this.each(function () {
			    var $sortingcontainer = $(this);
			    var opts = $.extend({}, $.fn.ffxQuicksand.defaults, options);
				$sortingcontainer.attr('name', 'quicksand-' + plugin.createguid());

				// Setup click events for each action
				$sortingcontainer.on("click", '.ffx-quicksand-action', function () {
					plugin.updateselection.apply($sortingcontainer, [$(this)]);
					plugin.showgroup.apply($sortingcontainer, [plugin.currentselection.apply($sortingcontainer)]);
				});

			    // count items
				var allItems = $(".ffx-quicksand-item", $(this));
				if (allItems.length <= opts.hideActionsForMinItems || opts.disableActionItems) {
				    $(".ffx-quicksand-action", $(this)).parent().hide();
				    opts.disableActionItems = true;
				    allItems.show();
				    $sortingcontainer.data("options", opts);
				} else { // select a default group
				    $sortingcontainer.data("options", opts);
				    // Select the first item
				    $(".ffx-quicksand-action:first", $sortingcontainer).trigger('click');
				
				    // Select the default logo group if it exists.
				    $(".default-logo-group", $(this)).trigger("click");

				    // If the user has selected a logo, then select that group...
				    var groupToHighlight = $(".ffx-quicksand-item.selected", this).data("grouping");
				    var selectedGroup = $(".ffx-quicksand-action[data-grouping='" + groupToHighlight + "']", $(this));
				   $(".ffx-quicksand-action[data-grouping='" + groupToHighlight + "']", $(this)).trigger("click");
				}
				
			});
		}
	};

	$.fn.ffxQuicksand = function (methodOrOptions) {
	    if (plugin[methodOrOptions]) {
	        return plugin[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
	    } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
			return plugin.init.apply(this, arguments);
		} else {
	        $.error('Method ' + methodOrOptions + ' does not exist on jQuery.ffxQuicksand');
		}
	};

	$.fn.ffxQuicksand.defaults = {
	    alwaysShowSelected: false, // always show the selected items, even if they would be hidden with currently selected group
	    hideActionsForMinItems: 5, // only show action items if there are > this many items in selection pool
        disableActionItems: false // disable action items even if more than min items...
	}

	// Why .ffx-quicksand? Because I was going to use the jQuery Quicksand or jQuery Isotope plugins, but decided they were a bit heavy to include for a single purpose.
	$(document).ready(function () {
	    $(".ffx-quicksand").not(".always-show-selected").ffxQuicksand();
	    $(".ffx-quicksand.always-show-selected").ffxQuicksand({ alwaysShowSelected: true });
	});

} (jQuery));
;
/*
Implements a "quicksand" style dom filter.
Required structure:
<div class="ffx-quicksand">
<a class="ffx-quicksand-action" data-grouping="ALL"></a> // optional
<a class="ffx-quicksand-action" data-grouping="ABC"></a>
<a class="ffx-quicksand-action" data-grouping="DEF"></a>

<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
</div>
*/
(function ($) {
    var plugin = {
        createguid: function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        },
        resetui: function () {
            var $uploadcontainer = $(this);
            var disclaimer = $uploadcontainer.data("disclaimer");
            // Put UI in state: show thumb if available, show link to change uploaded image.
            $("input:file", $(this)).hide();
            $("a.change", $(this)).show();
            $("a.cancel", $(this)).hide();
            $("span.houselogo-choice.selector", $(this)).hide();
            $("a.remove", $(this)).hide();
            var imageSource = $("img", $(this)).attr("src");
            if (imageSource != undefined && imageSource.length > 0) {
                $("span.houselogo-choice.selector", $(this)).show();
                $("a.remove", $(this)).show();
                $("a.change", $(this)).hide();
                if ($('.editor .disclaimer').length == 0) {
                    $(this).closest('.editor').append(disclaimer);
                }
            }
        },
        uploadui: function () {
            // Put UI in state: hide thumb, show upload field and cancel button.
            $("span.houselogo-choice.selector", $(this)).hide();
            $("input:file", $(this)).show();
            $("a.change", $(this)).hide();
            $("a.remove", $(this)).hide();
            $("a.cancel", $(this)).show();
        },
        remove: function () {
            var $uploadcontainer = $(this);
            var imageType = $uploadcontainer.data("imagetype");
            if (confirm("Do you want to remove this " + imageType + "?")) {
                $("img", $(this)).attr("src", "");
                $("input:hidden", $(this)).val("");
                plugin.resetui.apply($(this));
                $('.editor .disclaimer').remove();
            }
        },

        init: function (options) {
            return this.each(function () {
                var $uploadcontainer = $(this);

                $uploadcontainer.attr('name', 'photoupload-' + plugin.createguid());

                var theStatusContainer = $("<div />");
                var theMessage = $("<span />").addClass("statusbar");
                var statusBar = $("<span />");
                theMessage.append(statusBar);
                theStatusContainer.append(theMessage);
                theStatusContainer.dialog({ autoOpen: false,
                    title: "Uploading File. Please Wait...",
                    resizable: false,
                    dialogClass: "no-close",
                    modal: true,
                    closeOnEscape: false,
                    draggable: false
                });

                // uploadcontainer will be a div with just a hidden field, construct the required UI...
                /*
                <div>
                <input hidden/>
                <span class="chosen-items">
                <span class="houselogo-choice selector">
                <img src=thumb>
                <a class="remove"/>
                </span>
                </span>
                <input file/>
                <a class="change" />
                <a class="cancel" />
                </div>
                */
                var theFileField = $('<input type="file"/>');
                $uploadcontainer.append($("<span/>")
                        .addClass("chosen-items")
                        .attr("style", "display: inline-block;")
                        .append($("<span/>")
                            .addClass("houselogo-choice")
                            .addClass("selector")
                            .append("<img/>")
                            .append($('<a title="Edit" class="edit">Edit</a>'))
                            .append($('<a title="Delete" class="remove">Delete</a>'))))
                        .append(theFileField)
                        .append($('<a class="cancel button alt">Cancel</a>'));


                var theThumbnail = $("img", $uploadcontainer);
                theThumbnail.attr("src", $uploadcontainer.data("default-thumb"));
                var theHiddenField_DataValue = $("input:hidden[name$=DataValue]", $uploadcontainer);
                var theHiddenField_MaterialPath = $("input:hidden[name$=MaterialPath]", $uploadcontainer);
                var theHiddenField_RecomendedColCount = $("input:hidden[name$=RecomendedColumns]", $uploadcontainer);
                var theHiddenField_MaxColCount = $("input:hidden[name$=MaxColumns]", $uploadcontainer);

                var imageType = $uploadcontainer.data("imagetype");
                //var chooseOrChange = theThumbnail.attr("src") == "" ? "Change" : "Choose";
                $uploadcontainer.append($('<a class="change button alt">Choose a ' + imageType + '</a>'));



                //var imageType = $uploadcontainer.data("imagetype");


                $("a.edit", $uploadcontainer).click(function () {
                    plugin.uploadui.apply($uploadcontainer);
                    $('.editor .disclaimer').remove();
                    
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });
                $("a.change", $uploadcontainer).click(function () {
                    plugin.uploadui.apply($uploadcontainer);
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });
                $("a.cancel", $uploadcontainer).click(function () {
                    plugin.resetui.apply($uploadcontainer);
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });
                $("a.remove", $uploadcontainer).click(function () {
                    plugin.remove.apply($uploadcontainer);
                    $('.colourSchemeBlock').trigger('enableTint');
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });

                var fullBar = 259;
                var endPoint = $uploadcontainer.data("default-endpoint");
                var disclaimer = $uploadcontainer.data("disclaimer");
                var pubcode = $('.pubCode').val();
                theFileField.fileupload({
                    dataType: 'json',
                    url: endPoint+ "/?flow=" + flowID,
                    progressInterval: 10,
                    formData: function (form) {
                        var abc = form.serializeArray();
                        abc.push({ name: 'pubCode', value: pubcode });
                        return abc;
                    },
                    done: function (e, data) {
                        $.each(data.result, function (index, file) {
                            if (file.error.id == 0 || file.error.id == 3) {
                                if (file.error.id == 3) {
                                    alert("We performed a print quality check and fixed some errors in the PDF provided. The updates made were: " + file.error.message);
                                }
                                theThumbnail.attr("src", file.result[0].thumbnailUri);
                                theHiddenField_DataValue.val(file.result[0].uri);
                                if (imageType === "Material File") {
                                    theHiddenField_MaterialPath.val(file.result[0].uri);
                                    theHiddenField_RecomendedColCount.val(data.result.d.result[0].recommendedColCount);
                                    theHiddenField_MaxColCount.val(data.result.d.result[0].maxColCount);
                                    var startPoint = data.result.d.result[0].recommendedColCount;
                                    var endPoint = data.result.d.result[0].maxColCount;
                                    updateColDropDown(startPoint, endPoint);
                                }
 
                                $("a.change", $(this)).hide();
                                if ($('.editor .disclaimer').length == 0) {
                                    theThumbnail.closest('.editor').append(disclaimer);
                                }
                            } else if (file.error.id == 2) {
                                didError = true;
                                // there has been an error returned from the preflight system.
                                alert("We performed a print quality check and found some errors in the PDF provided. Please re-upload corrected file to fix the error. The errors are:" + file.error.message);
                            }
                            else {
                                didError = true;
                                alert("Problem uploading file: " + file.error.message);
                            }

                        });
                        plugin.resetui.apply($uploadcontainer);
                    },
                    progressall: function (e, data) {

                        var progress = parseInt(data.loaded / data.total * 100, 10);

                        $(statusBar).css("width", fullBar * 0.2 + "px").animate({ width: fullBar + "px" },
                        {
                            duration: 500, complete: function () {
                                $(statusBar).text("Upload Complete. Processing....");
                            }
                        });

                        if (progress != "100") {
                            $(statusBar).text("");
                            $(statusBar).css("width", (progress / 100) * fullBar + "px");
                        }
                    },
                    start: function (e) {
                        didError = false;
                        statusBar.css("width", fullBar * 0.1 + "px");
                        theStatusContainer.dialog('open');
                    },
                    stop: function (e) {
                        statusBar.css("width", fullBar + "px");
                        //theInputContainer.show();
                        theStatusContainer.dialog('close');
                        plugin.resetui.apply($uploadcontainer);
                    },
                    fail: function (e, data) {
                        didError = true;
                        alert("Sorry, unable to upload file. Try again after checking that the file wasn't too large and is of the correct format.");
                    }
                });


                plugin.resetui.apply($uploadcontainer);
            });
        }
    };


    function updateColDropDown(startPoint, endPoint) {
        // if the selected section is the Services or Professional section then set start and end point to 2.
        var section = $("input:hidden[name$=ClassificationSection]").val();
        if (section === "SERVICES" || section === "PROFESSIONAL") {
            startPoint = 2;
            endPoint = 2;
        }
        var colSelect = $('select[id$=ColumnCount]');
        var currentSelection = colSelect.val();
        colSelect.children().remove();
        for (var x = startPoint; x <= endPoint; x += 1) {
            if (x != 5 && x != 7) {
                colSelect.append($('<option></option>').val(x).html(x + ' column'));
            }
        }
        colSelect.children().filter(function () { return ($(this).val() == currentSelection); }).prop('selected', true);
    }

    $.fn.fdPhotoUpload = function (method) {
        if (plugin[method]) {
            return plugin[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return plugin.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on fdPhotoUpload');
        }
    };

    // Why .ffx-quicksand? Because I was going to use the jQuery Quicksand or jQuery Isotope plugins, but decided they were a bit heavy to include for a single purpose.
    $(document).ready(function () {
        $(".fd-photouploader").fdPhotoUpload();
    });

} (jQuery));
;
/*
Implements a "quicksand" style dom filter.
Required structure:
<div class="ffx-quicksand">
<a class="ffx-quicksand-action" data-grouping="ALL"></a> // optional
<a class="ffx-quicksand-action" data-grouping="ABC"></a>
<a class="ffx-quicksand-action" data-grouping="DEF"></a>

<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="ABC"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
<div class="ffx-quicksand-item" data-grouping="DEF"></div>
</div>
*/
(function ($) {
    var plugin = {
        MATERIAL_CHECK_INTERVAL: 10 * 1000, // Check material every 10 secs

        MATERIAL_VALIDATION_STATUS: {
            //Init Status
            Initialised: 0,

            // Started status code
            DimensionValidationStarted: 1,
            ResolutionValidationStarted: 2,

            // Success status code
            Successful: 10,
            SuccessfulWithWarning: 11,

            // Failed status code, range starts from 
            DimensionValidationFailed: 51,
            ResolutionValidationFailed: 52,
            AmazonS3UploadFailed: 53,
            InvalidMaterialValidationId: 54,
            InvalidFileFormat: 55,
            FileTooLarge : 56,
            GenericException : 57,
        },
        
        createguid: function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        },
        resetui: function () {
            var $uploadcontainer = $(this);
            var disclaimer = $uploadcontainer.data("disclaimer");
            // Put UI in state: show thumb if available, show link to change uploaded image.
            $("input:file", $(this)).hide();
            $("a.change", $(this)).show();
            $("a.cancel", $(this)).hide();
            $("span.houselogo-choice.selector", $(this)).hide();
            $("a.remove", $(this)).hide();
            var imageSource = $("img", $(this)).attr("src");
            if (imageSource != undefined && imageSource.length > 0) {
                $("span.houselogo-choice.selector", $(this)).show();
                $("a.remove", $(this)).show();
                $("a.change", $(this)).hide();
                if ($('.editor .disclaimer').length == 0) {
                    $(this).closest('.editor').append(disclaimer);
                }
            }
        },
        uploadui: function () {
            // Put UI in state: hide thumb, show upload field and cancel button.
            $("span.houselogo-choice.selector", $(this)).hide();
            $("input:file", $(this)).show();
            $("a.change", $(this)).hide();
            $("a.remove", $(this)).hide();
            $("a.cancel", $(this)).show();
        },
        remove: function () {
            var $uploadcontainer = $(this);
            var imageType = $uploadcontainer.data("imagetype");
            if (confirm("Do you want to remove this " + imageType + "?")) {
                $("img", $(this)).attr("src", "");
                $("input:hidden", $(this)).val("");
                plugin.resetui.apply($(this));
                $('.editor .disclaimer').remove();
            }
        },        
        init: function (options) {
            return this.each(function () {
                var $uploadcontainer = $(this);

                $uploadcontainer.attr('name', 'materialupload-' + plugin.createguid());

                var theStatusContainer = $("<div />");
                var message = $("<p />");
                var statusBarWrapper = $("<span />").addClass("statusbar"); 
                var statusBar = $("<span />");
                statusBarWrapper.append(statusBar);
                theStatusContainer.append(message);
                theStatusContainer.append(statusBarWrapper);
                theStatusContainer.dialog({ autoOpen: false,
                    title: "Material File Upload",
                    resizable: false,
                    dialogClass: "no-close",
                    modal: true,
                    closeOnEscape: false,
                    draggable: false,
                    width: 350,
                });

                // uploadcontainer will be a div with just a hidden field, construct the required UI...
                /*
                <div>
                <input hidden/>
                <span class="chosen-items">
                <span class="houselogo-choice selector">
                <img src=thumb>
                <a class="remove"/>
                </span>
                </span>
                <input file/>
                <a class="change" />
                <a class="cancel" />
                </div>
                */
                var theFileField = $('<input type="file"/>');
                $uploadcontainer.append($("<span/>")
                    .addClass("chosen-items")
                    .attr("style", "display: inline-block;")
                    .append($("<span/>")
                        .addClass("houselogo-choice")
                        .addClass("selector")
                        .append("<img/>")
                        .append($('<a title="Edit" class="edit">Edit</a>'))
                        .append($('<a title="Delete" class="remove">Delete</a>'))))
                    .append(theFileField)
                    .append($('<a class="cancel button alt">Cancel</a>'));

                var theThumbnail = $("img", $uploadcontainer);
                theThumbnail.attr("src", $uploadcontainer.data("default-thumb"));
                var theHiddenField_DataValue = $("input:hidden[name$=DataValue]", $uploadcontainer);
                var theHiddenField_MaterialPath = $("input:hidden[name$=MaterialPath]", $uploadcontainer);
                var theHiddenField_RecomendedColCount = $("input:hidden[name$=RecomendedColumns]", $uploadcontainer);
                var theHiddenField_MaxColCount = $("input:hidden[name$=MaxColumns]", $uploadcontainer);

                var imageType = $uploadcontainer.data("imagetype");
                //var chooseOrChange = theThumbnail.attr("src") == "" ? "Change" : "Choose";
                $uploadcontainer.append($('<a class="change button alt">Choose a ' + imageType + '</a>'));
                
                //var imageType = $uploadcontainer.data("imagetype");

                $("a.edit", $uploadcontainer).click(function () {
                    plugin.uploadui.apply($uploadcontainer);
                    $('.editor .disclaimer').remove();
                    
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });
                $("a.change", $uploadcontainer).click(function () {
                    var $editor = $(this).closest('.editor');
                    $("div.preflight-user-msg", $editor).remove();
                    
                    plugin.uploadui.apply($uploadcontainer);
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });
                $("a.cancel", $uploadcontainer).click(function () {
                    plugin.resetui.apply($uploadcontainer);
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });
                $("a.remove", $uploadcontainer).click(function () {
                    plugin.remove.apply($uploadcontainer);
                    $('.colourSchemeBlock').trigger('enableTint');
                    if (imageType === "Material File") {
                        updateColDropDown(1, 8);
                    }
                });

                var fullBar = 309;
                var uploadEndPoint = $uploadcontainer.data("default-upload-endpoint");
                var checkUploadEndPoint = $uploadcontainer.data("default-checkupload-endpoint");
                var disclaimer = $uploadcontainer.data("disclaimer");
                var pubcodes = $('.pubCodes').val();
                theFileField.fileupload({
                    dataType: 'json',
                    url: uploadEndPoint+ "/?flow=" + flowID,
                    progressInterval: 10,
                    formData: function (form) {
                        var abc = form.serializeArray();
                        abc.push({ name: 'pubCode', value: pubcodes });
                        return abc;
                    },
                    done: function (e, data) {
                        //$.each(data.result, function (index, file) {
                        //    if (file.error.id == 0 || file.error.id == 3) {
                        //        if (file.error.id == 3) {
                        //            alert("We performed a print quality check and fixed some errors in the PDF provided. The updates made were: " + file.error.message);
                        //        }
                        //        theThumbnail.attr("src", file.result[0].thumbnailUri);
                        //        theHiddenField_DataValue.val(file.result[0].uri);
                        //        if (imageType === "Material File") {
                        //            theHiddenField_MaterialPath.val(file.result[0].uri);
                        //            theHiddenField_RecomendedColCount.val(data.result.d.result[0].recommendedColCount);
                        //            theHiddenField_MaxColCount.val(data.result.d.result[0].maxColCount);
                        //            var startPoint = data.result.d.result[0].recommendedColCount;
                        //            var endPoint = data.result.d.result[0].maxColCount;
                        //            updateColDropDown(startPoint, endPoint);
                        //        }
 
                        //        $("a.change", $(this)).hide();
                        //        if ($('.editor .disclaimer').length == 0) {
                        //            theThumbnail.closest('.editor').append(disclaimer);
                        //        }
                        //    } else if (file.error.id == 2) {
                        //        didError = true;
                        //        // there has been an error returned from the preflight system.
                        //        alert("We performed a print quality check and found some errors in the PDF provided. Please re-upload corrected file to fix the error. The errors are:" + file.error.message);
                        //    }
                        //    else {
                        //        didError = true;
                        //        alert("Problem uploading file: " + file.error.message);
                        //    }

                        //});
                        //plugin.resetui.apply($uploadcontainer);

                        var initMaterialCheckResponse = data.result.d;

                        if (initMaterialCheckResponse == null)
                        {
                            // Something is wrong with Material Service
                            console.log("Invalid response from the Material Service. Check the Material Service logs for more information.");
                            theStatusContainer.dialog('close');
                            $(this).closest('.editor').remove("div.field-validation-error");
                            $(this).closest('.editor').append($('<div class="preflight-user-msg field-validation-error">We\'re sorry, but there was a problem uploading your material file. <p>Please <a href=\"/Page/ContactUs\" target=\"_blank\">contact our Customer Support team</a> for further assistance.</div>'));

                            plugin.resetui.apply($uploadcontainer);
                            return;
                        }

                        var materialValidationId = initMaterialCheckResponse.MaterialValidationId;
                        var materialValidationStatus = initMaterialCheckResponse.MaterialValidationStatus;

                        
                        if (materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.AmazonS3UploadFailed ||
                            materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.DimensionValidationFailed ||
                            materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.ResolutionValidationFailed ||
                            materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.InvalidMaterialValidationId ||
                            materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.FileTooLarge ||
                            materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.GenericException ||
                            materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.InvalidFileFormat) {

                            var userMessage = initMaterialCheckResponse.UserMessages;

                            console.log("materialValidationStatus = " + materialValidationStatus + " userMessage = " + userMessage);

                            // Display the error div
                            $(this).closest('.editor').append($('<div class="preflight-user-msg field-validation-error">' + userMessage + '</div>'));


                            theStatusContainer.dialog('close');
                            plugin.resetui.apply($uploadcontainer);
                        }
                        else if (materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.DimensionValidationStarted ||
                                    materialValidationStatus == plugin.MATERIAL_VALIDATION_STATUS.ResolutionValidationStarted) {
                            // Set up a polling with the server, check it in next 10 secs
                            setTimeout(checkmaterial, plugin.MATERIAL_CHECK_INTERVAL, checkUploadEndPoint, materialValidationId);
                        }
                        else {
                            console.log("materialValidationStatus = " + materialValidationStatus + ", status error.");
                        }

                        function checkmaterial(checkEndPoint, materialValidationId) {
                            var checkUploadUrl = checkEndPoint + "/?flow=" + flowID + "&materialValidationId=" + materialValidationId;

                            // Check server for the given material validation id
                            $.post(checkUploadUrl, function (data) {
                                var response = data.d;
                                var checkMaterialResponse = response.checkMaterialResponse;
                                var now = new Date();
                                var nowString = ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2) + ":" + ("0" + now.getSeconds()).slice(-2) + " - ";

                                var debugMsg = nowString + ": Material Check for validation id: " + materialValidationId + " ";

                                function updateForm(result) {
                                    theThumbnail.attr("src", result.thumbnailUri);
                                    theHiddenField_DataValue.val(result.uri);

                                    theHiddenField_MaterialPath.val(result.uri);
                                    theHiddenField_RecomendedColCount.val(result.recommendedColCount);
                                    theHiddenField_MaxColCount.val(result.maxColCount);
                                    var startPoint = theHiddenField_RecomendedColCount.val();
                                    var endPoint = theHiddenField_MaxColCount.val();
                                    updateColDropDown(startPoint, endPoint);
                                }

                                function closeProgressDialog() {
                                    statusBar.css("width", fullBar + "px");
                                    theStatusContainer.dialog('close');
                                }

                                function showErrorMessage(response) {
                                    var userMessage = response.UserMessages;
                                    var id = response.MaterialValidationId;

                                    var errorMessage = "There was a problem with your material file. <br/>" + userMessage + ". <p>Please <a href=\"/Page/ContactUs\" target=\"_blank\">contact our Customer Support team</a> for further assistance.";

                                    if (id != null && id != 'undefined') {
                                        errorMessage += " (Material Validation ID: " + id + ")";
                                    }

                                    errorMessage += "</p>";

                                    // Display the error div
                                    $(".fd-materialuploader").closest('.editor').append($('<div class="preflight-user-msg field-validation-error">' + errorMessage + '</div>'));
                                }

                                switch (checkMaterialResponse.MaterialValidationStatus) {
                                    case plugin.MATERIAL_VALIDATION_STATUS.DimensionValidationStarted:
                                    case plugin.MATERIAL_VALIDATION_STATUS.ResolutionValidationStarted:
                                        console.log(debugMsg + "status: " + checkMaterialResponse.MaterialValidationStatus + ", check again in " + (plugin.MATERIAL_CHECK_INTERVAL / 1000) + " secs");

                                        //$(statusBar).text(nowString + " still processing... check again in " + (plugin.MATERIAL_CHECK_INTERVAL / 1000) + " secs");

                                        toastr.info(nowString + " Still processing... Check again in " + (plugin.MATERIAL_CHECK_INTERVAL / 1000) + " secs");

                                        // Not yet finished, retry in 10 secs
                                        setTimeout(checkmaterial, plugin.MATERIAL_CHECK_INTERVAL, checkEndPoint, materialValidationId);
                                        break;
                                    case plugin.MATERIAL_VALIDATION_STATUS.Successful:
                                        console.log(debugMsg + "Successful");                                     
                                        updateForm(response.result[0]);
                                        closeProgressDialog();
                                        plugin.resetui.apply($uploadcontainer);
                                        break;
                                    case plugin.MATERIAL_VALIDATION_STATUS.SuccessfulWithWarning:
                                        console.log(debugMsg + "Successful with Warning");
                                        updateForm(response.result[0]);
                                        closeProgressDialog();
                                        plugin.resetui.apply($uploadcontainer);
                                        break;
                                    case plugin.MATERIAL_VALIDATION_STATUS.AmazonS3UploadFailed:
                                        console.log(debugMsg + "Amazon upload failed");
                                        theStatusContainer.dialog('close');
                                        showErrorMessage(checkMaterialResponse);
                                        plugin.resetui.apply($uploadcontainer);
                                        break;
                                    case plugin.MATERIAL_VALIDATION_STATUS.DimensionValidationFailed:
                                        console.log(debugMsg + "Dimension check failed");
                                        theStatusContainer.dialog('close');
                                        showErrorMessage(checkMaterialResponse);
                                        plugin.resetui.apply($uploadcontainer);
                                        break;
                                    case plugin.MATERIAL_VALIDATION_STATUS.ResolutionValidationFailed:
                                        console.log(debugMsg + "Resolution check failed");
                                        theStatusContainer.dialog('close');
                                        showErrorMessage(checkMaterialResponse);
                                        plugin.resetui.apply($uploadcontainer);
                                        break;
                                    case plugin.MATERIAL_VALIDATION_STATUS.InvalidMaterialValidationId:
                                        console.log(debugMsg + "Invalid Material Validation ID detected");
                                        theStatusContainer.dialog('close');
                                        showErrorMessage(checkMaterialResponse);
                                        plugin.resetui.apply($uploadcontainer);
                                        break;
                                }                                
                            });
                        }
                    },

                    progressall: function (e, data) {

                        var progress = parseInt(data.loaded / data.total * 100, 10);

                        $(statusBar).css("width", fullBar * 0.2 + "px").animate({ width: fullBar + "px" },
                        {
                            duration: 500, complete: function () {
                                $(message).text("Upload Complete. Processing can take up to 5 minutes. Please wait until the operation has completed.")
                                $(statusBar).text("Processing...");
                            }
                        });

                        if (progress != "100") {
                            $(statusBar).text("");
                            $(statusBar).css("width", (progress / 100) * fullBar + "px");
                        }
                    },
                    start: function (e) {
                        didError = false;
                        statusBar.css("width", fullBar * 0.1 + "px");
                        theStatusContainer.dialog('open');
                    },
                    stop: function (e) {
                        //statusBar.css("width", fullBar + "px");
                        ////theInputContainer.show();
                        //theStatusContainer.dialog('close');
                        //plugin.resetui.apply($uploadcontainer);
                    },
                    fail: function (e, data) {
                        didError = true;
                        alert("Sorry, unable to upload file. Try again after checking that the file wasn't too large and is of the correct format.");
                    }
                });


                plugin.resetui.apply($uploadcontainer);
            });
        }
    };


    function updateColDropDown(startPoint, endPoint) {
        // if the selected section is the Services or Professional section then set start and end point to 2.
        var section = $("input:hidden[name$=ClassificationSection]").val();
        if (section === "SERVICES" || section === "PROFESSIONAL") {
            startPoint = 2;
            endPoint = 2;
        }
        var colSelect = $('select[id$=ColumnCount]');
        var currentSelection = colSelect.val();
        colSelect.children().remove();
        for (var x = startPoint; x <= endPoint; x += 1) {
            if (x != 5 && x != 7) {
                colSelect.append($('<option></option>').val(x).html(x + ' column'));
            }
        }
        colSelect.children().filter(function () { return ($(this).val() == currentSelection); }).prop('selected', true);
    }

    $.fn.fdMaterialUpload = function (method) {
        if (plugin[method]) {
            return plugin[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return plugin.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on fdMaterialUpload');
        }
    };

    // Why .ffx-quicksand? Because I was going to use the jQuery Quicksand or jQuery Isotope plugins, but decided they were a bit heavy to include for a single purpose.
    $(document).ready(function () {
        $(".fd-materialuploader").fdMaterialUpload();
    });

} (jQuery));
;
(function ($) {
    $.fn.ffxLogoSelector = function () {
        var logoSelectors = this;
        return logoSelectors.each(function () {
            var logoSelector = this;

            // init all the delete links...
            $(logoSelector).on('click', "a.delete", function (evt) {
                if (confirm("Do you really want to remove this logo from our database?")) {
                    $.ajax({
                        url: '/printlogos/delete/?flow=' + flowID,
                        data: {
                            'imageId': $(evt.target).parent().parent().data('image-id')
                        },
                        type: 'POST',
                        success: function () {
                            $(evt.target).parent().parent().remove();
                        },
                        error: function (d) {
                            alert('Could not delete file: ' + d.statusText);
                        }
                    });
                }
                return false; // prevent the parent click running
            });
        });
    };


    // attach a handler to the upload new logo buttons...
    $('body').on('uploadnewlogoclicked', '.ffx-radio-buttons.logo-selector', function (evt) {
        var logoSelectorContainer = evt.target;
        var menuContainer = $(logoSelectorContainer).siblings('ul.tabNav');

        var $allLogoSelectorDialogs = $(".ffx-radio-buttons.logo-selector");
        //var theForm = $('<form/>'); //.attr('action', '/printlogos/UploadViaJquery');
        var theForm = $('<div />');
        theForm.dialog({ autoOpen: true,
            title: "Choose a file to upload",
            resizable: false,
            width: 500,
            height: 340,
            modal: true,
            closeOnEscape: false,
            buttons: [{ text: "Close", click: function () { $(this).dialog("close"); } }/*,
                        { text: "Upload", click: function () { $(this).dialog("close"); } }*/]
        });
        var theInputContainer = $("<span />");
        var theInput = $('<input />')
                .attr("name", "files[]")
                .attr('type', 'file')
                .prop("multiple", false);

        var theStatusContainer = $("<div />");
        var theMessage = $("<span />").addClass("statusbar");
        var statusBar = $("<span />");
        theMessage.append(statusBar);

        theStatusContainer.append(theMessage);
        theStatusContainer.dialog({ autoOpen: false,
            title: "Uploading File. Please Wait...",
            resizable: false,
            dialogClass: "no-close",
            modal: true,
            closeOnEscape: false,
            draggable: false
        });

        var didError = false;

        var fullBar = 259;
        theInput.fileupload({
            dataType: 'json',
            url: "/printlogos/upload/?flow=" + flowID,
            progressInterval: 10,
            done: function (e, data) {
                $.each(data.result, function (index, file) {
                    if (file.error.id == 0) {

                        // If the 'My Logos" menu tab doesn't exist, create it.
                        if ($(".ffx-quicksand-action[data-grouping=My]", menuContainer).length === 0) {
                            $(menuContainer).append($('<span/>').append($('<li/>')
											.addClass('ffx-quicksand-action')
											.attr('data-grouping', 'My')
											.append('<a>My Logos</a>')));
                        }

                        $allLogoSelectorDialogs.each(function (index1, element) {

                            // Todo: get the details, append to the selector.
                            var logoSelectorKey = $(element).data("logo-selector-key") + "-systemoption";

                            // Add the logo item
                            var selectorSpan = $("<span/>")
                                .addClass("ffx-quicksand-item")
                                .addClass("indicator-icon")
                                .addClass("houselogo-choice")
                                .addClass("selector")
                                .addClass("cursor-hand")
                                .addClass("newly-uploaded")
								.attr("data-id", "CUSTOM")
								.attr("data-image-id", file.result[0].id)
                                .attr("data-filename", file.result[0].filename)
                                .attr("data-originalfilename", file.result[0].originalfilename)
                                .attr("data-grouping", "My");
                            var selectorCheckbox = $("<input />")
                                .attr("type", "checkbox")
                                .css("display", "none")
                                .attr("name", logoSelectorKey)
                                .attr("value", "CUSTOM|" + file.result[0].uri);

                            selectorSpan.append(selectorCheckbox);
                            selectorSpan.append($('<span class="icon icon-approve"></span>'));
                            selectorSpan.append($('<img src="' + file.result[0].thumbnailUri + '" alt="CUSTOM">'));
                            selectorSpan.append($('<a title="Edit" class="edit">Edit</a>"'));
                            selectorSpan.append($('<a class="delete" title="Delete this image"><span class="icon-remove"></span></a>'));
                            selectorSpan.append($('<a title="Delete" class="remove logo-remover">Delete</a>'));
                            $(element).prepend(selectorSpan);

                            if (element === logoSelectorContainer) {
                                // select it
                                // set the filter tab to it.
                                $(selectorSpan).trigger("click");
                                $(selectorSpan).effect('highlight', {}, 10000);
                                $(".ffx-quicksand-action[data-grouping=My]").trigger("click");
                            }
                        });
                    } else {
                        didError = true;
                        alert("Problem uploading file: " + file.error.message);
                    }
                });
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $(statusBar).css("width", fullBar * 0.2 + "px").animate({ width: fullBar + "px" },
                { duration: 500, complete: function () {
                    $(statusBar).text("Upload Complete. Processing....");
                }
                });

                if (progress != "100") {
                    $(statusBar).text("");
                    $(statusBar).css("width", (progress / 100) * fullBar + "px");
                }
            },
            start: function (e) {
                didError = false;
                statusBar.css("width", fullBar * 0.1 + "px");
                theStatusContainer.dialog('open');
            },

            stop: function (e) {
                statusBar.css("width", fullBar + "px");
                //theInputContainer.show();
                theStatusContainer.dialog('close');
                if (!didError) {
                    theForm.dialog("close");
                }

            },
            fail: function (e, data) {
                didError = true;
                alert("Sorry, unable to upload file. Try again after checking that the file wasn't too large and is of the correct format.");
            } /*,
            send: function (e, data) {
                console.log(data.files[0].name);
                if (data.files.length > 10) {
                    return false;
                }
            }*/
        });
        theInputContainer.append("<p>To ensure the logo you upload is appropriate for publication, please check that it meets the following criteria:</p><p><strong>Maximum Size:</strong> Uploaded file cannot be larger than 10MB </p><p><strong>Vector Images:</strong> In order to make the logo acceptable for newspaper publication, it is advisable to upload a vector image (PDF, PS, EPS). If you do not have a vector image, but have a different picture file type. you can convert it for free with http://vectormagic.com/online/how_it_works. Note if a JPG, JPEG, GIF, PNG, BMP is uploaded then the image will automatically be converted to grey scale </p>");
        theInputContainer.append(theInput);
        theForm.append(theInputContainer);
        //theForm.append(theStatusContainer);



    });


    $('body').on('selectionchanged', '.logo-selector.ffx-radio-buttons', function (evt, currentValue) {
        var selectorKey = $(evt.target).data('logo-selector-key');
        var currentVal = $('input:checked', (evt.target)).val();
        $('input:hidden', $('.logo-selector-container.' + selectorKey)).val(currentVal);
        // hide the "choose" button if there is a sleection
        if (currentVal != undefined) {
            $('a.edit.dialog-opener', $('.logo-selector-container.' + selectorKey)).hide();
        } else {
            $('a.edit.dialog-opener', $('.logo-selector-container.' + selectorKey)).show();
        }
    });





    // initialise all the logoselectors
    $(document).ready(function () {
        $(".ffx-radio-buttons.logo-selector").ffxLogoSelector();
    });

} (jQuery));


;

/* [Timespan picker]
------------------------------------------------------*/
(function () {
    var CONSTANTS = {
        start: 'start',
        end: 'end'
    };

    $.widget("ffx.timespanpicker", {
        options: {
            // Date
            date: true,
            dateDefault: new Date(),
            dateMin: null,
            dateMax: null,
            //dateFormat: "D M d Y",
            //dateAltFormat: "",
            dateSelector: ".datepicker",
            // Time
            time: true,
            timeDefault: new Date(),
            timeMin: null,
            timeMax: null,
            timeStep: 30,
            timeDuration: false,
            timeFormat: "g:i:sa",
            //timeAltFormat: "",
            timeSelector: ".timepicker",
            timeStartSelector: ".start",
            timeEndSelector: ".end"
        },
        _create: function (options) {
            var self = this,
				options = self.options;

            self.elements = {};

            var element = self.element,
				elements = self.elements;

            // Add container class
            element.addClass(self.widgetBaseClass);

            // Date (optional)
            if (options.date) {
                // Add sub-element to collection
                elements.date = element.find(options.dateSelector);

                // Attach change event handlers (set to widget scope)
                elements.date.on('change', $.proxy(self._dateChange, self));
            }

            // Times (optional)
            if (options.time) {
                elements.time = {};

                // Add sub-elements to collection
                elements.time.all = element.find(options.timeSelector);
                elements.time.start = elements.time.all.filter(options.timeStartSelector);
                elements.time.end = elements.time.all.filter(options.timeEndSelector);

                // Attach change event handlers (set to widget scope)
                elements.time.start.on('change', $.proxy(self._startTimeChange, self));
                elements.time.end.on('change', $.proxy(self._endTimeChange, self));
            }
        },
        _init: function () {
            var self = this,
				options = self.options,
				elements = self.elements;

            var now = new Date();

            // Initialise sub-elements
            if (options.date) {
                var date = elements.date;

                // Setup datepicker widget
                date.datepicker();

                date.datepicker('option', {
                    minDate: options.dateMin,
                    maxDate: options.dateMax,
                    showOn: 'focus'
                });

                date.datepicker('setDate', options.dateDefault);
            }

            if (options.time) {
                var time = elements.time;

                // Setup timepicker widgets
                time.all.timepicker();

                time.all.timepicker('option', {
                    minTime: options.timeMin,
                    maxTime: options.timeMax,
                    step: options.timeStep
                });

                time.end.timepicker('option', {
                    showDuration: options.timeDuration
                });
            }
        },
        // Date
        _calculateDate: function (date) {
            var result = date;

            // Reset time values in date
            result.setHours(0);
            result.setMinutes(0);
            result.setSeconds(0);
            result.setMilliseconds(0);

            return result;
        },
        _getDate: function () {
            var date = this.elements.date.datepicker('getDate');

            return this._calculateDate(date);
        },
        getDate: function (format) {
            var date = this._getDate();

            return (format) ? date.format(format) : date;
        },
        // Times
        _calculateTime: function (date, time) {
            var result = date;

            // Copy time values into date
            result.setHours(time.getHours());
            result.setMinutes(time.getMinutes());
            result.setSeconds(time.getSeconds());
            result.setMilliseconds(time.getMilliseconds());

            return result;
        },
        _getTime: function (type) {
            var date = this.elements.date.datepicker('getDate'),
				time = this.elements.time[type].timepicker('getTime');

            return this._calculateTime(date, time);
        },
        getTime: function (type, format) {
            var time = this._getTime(type);

            return (format) ? time.toString(format) : time;
        },
        getStartTime: function (format) {
            return this.getTime(CONSTANTS.start, format);
        },
        getEndTime: function (format) {
            return this.getTime(CONSTANTS.end, format);
        },
        getJsonStartTime: function()
        {
            return this._dateToJson(this._getTime(CONSTANTS.start));
        },
        getJsonEndTime: function()
        {
            return this._dateToJson(this._getTime(CONSTANTS.end));
        },
        _dateToJson: function(time)
        {
            return "/Date(" + time.getMilliseconds() + ")/";
        },
        // Events
        _dateChange: function (event) {
            // TODO: Update start / end times in background
        },
        _startTimeChange: function (event) {
            var self = this,
				time = self.elements.time;

            // Update end min time
            time.end.timepicker('option', {
                minTime: time.start.timepicker('getTime')
            });
        },
        _endTimeChange: function (event) {
            var self = this,
				time = self.elements.time;

            // Update start max time
            time.start.timepicker('option', {
                maxTime: time.end.timepicker('getTime')
            });
        }
    });
})();
;
/* [animateFeedback] - Set feedback and animate (fades/slides)
------------------------------------------------------*/
$.fn.animateFeedback = function(options) {

	var defaults = {
		interval: 10,		// Interval time in seconds
		effect: 'slide',	// Animation effect - slide | fade
		text: '',			// Default feedback message
		trigger: 'normal',	// Default trigger action - normal (on page) | modal (set the feedback based on external action)
		mode: 'confirm'		// Display mode - confirm | info | error
	},	
	options = $.extend(defaults, options);	
	
	function setEffect(e) {
		var $this = $(e);
		if (options.effect == "fade") {$this.fadeOut(function() {$this.remove()} )}
		else {$this.slideUp(function() {$this.remove()} )}
	}

	function displayFeedback(message) {
		var $panel = message,
			intervalID;

		if ($panel.length == 0)
		{
			$panel = $(html);
		}
		// limit to one grid feeback per click action. Allow global feedbacks to always display - e.g. delete and cancel 
		if ((!$panel.length && (options.trigger == "normal")) || (options.trigger == "modal")) {
			/* add live region 
			- "role=alert" when class is error
			- "aria-live="polite" when class is info or success
			*/
			if (options.mode == ("info")) {
				$panel.addClass("message-info").attr({"aria-live":"polite"});;
			} else if (options.mode == ("error")) {
				$panel.addClass("message-error").attr({"role":"alert"});
			} else {
				$panel.addClass("message-confirm").attr({"aria-live":"polite"});;
			}
			
			$panel.show("slide", { direction: "down" });
			clearTimeout(intervalID);

			// append close button & add click event to close buttons
			$panel.append('<button type="button" title="Close" class="button-close">Close</button>');
			$panel.find('.button-close').click(function(){
				setEffect($panel);
			});
			
			// disappear after the delay is reached
			if ($panel.is(":visible") || ($panel.css('display').toLowerCase() != 'none')) {	// Visible or displayed (tabs: not visible)
				intervalID = setInterval( function() {setEffect($panel)}, options.interval*1000);
			}
		}
	}

	var $this = $(this); 
	return $this.each(function () {
		$this.hide();
		displayFeedback($this);
	});
};;
(function ($) {

    function DateAdd(ItemType, DateToWorkOn, ValueToBeAdded) {
        switch (ItemType) {
            //date portion                                           
            case 'd': //add days
                DateToWorkOn.setDate(DateToWorkOn.getDate() + ValueToBeAdded)
                break;
            case 'm': //add months
                DateToWorkOn.setMonth(DateToWorkOn.getMonth() + ValueToBeAdded)
                break;
            case 'y': //add years
                DateToWorkOn.setYear(DateToWorkOn.getFullYear() + ValueToBeAdded)
                break;
            //time portion                                           
            case 'h': //add days
                DateToWorkOn.setHours(DateToWorkOn.getHours() + ValueToBeAdded)
                break;
            case 'n': //add minutes
                DateToWorkOn.setMinutes(DateToWorkOn.getMinutes() + ValueToBeAdded)
                break;
            case 's': //add seconds
                DateToWorkOn.setSeconds(DateToWorkOn.getSeconds() + ValueToBeAdded)
                break;
        }
        return DateToWorkOn;
    }

    $.validator.addMethod('abn', function (value, element, params) {
        if (value || value.length) {
            var weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
            var abn = value.replace(/\s/g, "").split("");
            // Check for 11 digits
            if (abn.length != 11) {
                return false;
            }
            var i = 0;
            for (i = 0; i < 11; i++) {
                if (isNaN(abn[i] = parseInt(abn[i]))) {
                    return false;
                }
            }
            abn[0] = abn[0] - 1;
            var sum = 0;
            for (i = 0; i < 11; i++) {
                sum = sum + (abn[i] * weights[i]);
            }
            if ((sum % 89) != 0) {
                return false;
            }
        }
        return true;
    }, "Fail");

    $.validator.addMethod('mustagreeifselected', function (value, element, params) {
        if ($('input[name$="' + params.enablerproperty + '"]:checked').val() === params.enablervalue) {
            return $(element).prop('checked');
        }
        else {
            return true;
        }
    }, "Fail");
    $.validator.addMethod('ckstringlength', function (value, element, params) {
        return FD.Convert.toText(CKEDITOR.instances[$(element).attr('id')].getData()).length <= params.maxlength;
    }, "Fail");

    var requireifselectedValidateFunction = function (value, element, params) {
        var checkTheElement = false;

        var disabled = (params.disabled != null && params.disabled.toLowerCase() == "true");
        var matchValues = (params.valuesmustmatch != null && params.valuesmustmatch.toLowerCase() == "true");
        var enablerValue = params.enablervalue;
        var enablerProperty = $('[name$="' + params.enablerproperty + '"]').filter(":input");

        if (disabled)
        {
            return true;
        }

        if (enablerProperty.attr("type") == "checkbox") {
            var enablerCheckbox = $('input[name$="' + params.enablerproperty + '"][type="checkbox"]');
            if ((matchValues && enablerCheckbox.prop("checked") == true) ||
                (!matchValues && enablerCheckbox.prop("checked") == false)) {
                checkTheElement = true;
            }
        }
        else if (enablerProperty.attr("type") == "radio") {
            var enablerRadio = $('input[name$="' + params.enablerproperty + '"][type="radio"]:checked');
            if (typeof enablerRadio.val === 'function' && typeof enablerRadio.val() != 'undefined') {
                if ((matchValues && enablerRadio.val && enablerRadio.val().toLowerCase() == enablerValue.toLowerCase()) ||
                    (!matchValues && enablerRadio.val && enablerRadio.val().toLowerCase() != enablerValue.toLowerCase())) {
                    checkTheElement = true;
                }
            }
    
        }
        else {
            if (typeof enablerValue != 'undefined') {
                if ((matchValues && enablerProperty.val && enablerProperty.val().toLowerCase() == enablerValue.toLowerCase()) ||
                    (!matchValues && enablerProperty.val && enablerProperty.val().toLowerCase() != enablerValue.toLowerCase())) {
                    checkTheElement = true;
                }
            }
        }

        if (checkTheElement) {
            if (element.type === "radio") {
                return $('input[name="' + element.name + '"]:checked').length != 0;
            }
            else {
                return (value || value.length);
            }
        }

        return true;
    };

    var compareiffilledValidateFunction = function (value, element, params) {

        FD.log("value = " + value);
        FD.log("element = " + element);
        FD.log("params = " + params);

        var filledproperties = $('[name$="' + params.filledproperty + '"]');

        if (filledproperties.length <= 0) {
            // nothing to check
            return true;
        }

        if (typeof (filledproperties[0].value) == 'undefined' || filledproperties[0].value == '') {
            return true;
        }

        var filledpropertyvalue = filledproperties[0].value;

        switch (params.compareoperator) {
            case 'GreaterThan':
                if ((filledpropertyvalue > value)) {
                    return false;
                }
                break;
            case 'GreaterEqual':
                if ((filledpropertyvalue >= value)) {
                    return false;
                }
                break;
            case 'Equal':
                if (filledpropertyvalue != value) {
                    return false;
                }
                break;
            case 'LessThan':
                if ((filledpropertyvalue < value)) {
                    return false;
                }
                break;
            case 'LessEqual':
                if ((filledpropertyvalue <= value)) {
                    return false;
                }
                break;
        }

        return true;
    };

    function settobeginingofdate(value) {
        value.setMilliseconds(0);
        value.setSeconds(0);
        value.setMinutes(0);
        value.setHours(0);

        return value;
    }

    var daterangeValidateFunction = function (value, element, params) {
        var minDate = DateAdd('d', new Date(), parseInt(params.mindays));
        settobeginingofdate(minDate);

        var maxDate = DateAdd('d', new Date(), parseInt(params.maxdays));
        settobeginingofdate(maxDate);

        var selectedDate = new Date(value);
        if (value.indexOf('/') > 0) {
            selectedDate = new Date($.datepicker.parseDate('dd/mm/yy', value));
        }
       
        if (selectedDate < minDate || selectedDate > maxDate) {
            return false;
        }
        else {
            return true;
        }
    };

    $.validator.addMethod('compareiffilled', compareiffilledValidateFunction, "Fail");
    $.validator.addMethod('daterange', daterangeValidateFunction, "Fail");
    $.validator.addMethod('requiredifselected', requireifselectedValidateFunction, "Fail");
    $.validator.addMethod('requiredifselectedtwo', requireifselectedValidateFunction, "Fail");


    /*Note: below is commmented out for Bug#16556: UAT/Sbest - error when typing salary range (Pls do not delete LL)*/
    //	$.validator.addMethod('requiredamountifselected', function (value, element, params) {
    //		if ($('input[name$="' + params.enablerproperty + '"]:checked').val() === params.enablervalue) {
    //			var regExp = new RegExp(params.expression);
    //			matches = regExp.exec(value);
    //			return (matches && (matches.index === 0) && (matches[0].length === value.length));
    //		}
    //		return true;
    //	}, "Fail");

    //	$.validator.addMethod('rangeamountifselected', function (value, element, params) {
    //		if ($('input[name$="' + params.enablerproperty + '"]:checked').val() === params.enablervalue) {
    //			var min = 0;
    //			var max = 0;
    //			var otherelement = $('input[name$="' + params.baseproperty + '"]');
    //			if (params.type === "Min") {
    //				min = FormatSalary(value);
    //				max = FormatSalary(otherelement.val());
    //			}
    //			else {
    //				min = FormatSalary(otherelement.val());
    //				max = FormatSalary(value);
    //			}

    //			if (max > min) {
    //				// Then the other element is also valid
    //				$('span[data-valmsg-for="Order.Products[0].' + params.baseproperty + '"]').empty();
    //				console.log('error msg cleared...' + params.baseproperty);
    //				return true;
    //			}
    //			else {
    //				return false;
    //			}
    //		}
    //		return true;
    //	}, "Fail");


    $.validator.addMethod('stringcompare', function (value, element, params) {
        var subsector1 = $('select[name$="' + params.baseProperty + '"]:selected').val();
        var subsector2 = $('select[name$="' + params.comparedProperty + '"]:selected').val();
        var isequalerror = params.comparedProperty;

        if (((subsector1 == subsector2) && isequalerror) || ((subsector1 != subsector2) && !isequalerror)) {
            return false;
        }
        else {
            return true;
        }

    }, "Fail");

    $.validator.addMethod('conditionalrequired', function (value, element, params) {
        if (value || value.length) {
            return true;
        }
        else {
            var otherValue = $('input[name$="' + params.other + '"]').val();
            if (typeof otherValue === "undefined" || otherValue.length) {
                return true;
            }

            return false;
        }
    }, "Fail");

    $.validator.addMethod('fullregularexpression', function (value, element, params) {
        if (!value || !value.length)
            return true;

        var regExp = new RegExp(params.pattern, params.options),
            matches = regExp.exec(value);
        if (params.negate == "True" || params.negate == "true") {
            return (!matches || !matches.length);
        }
        else {
            return (matches && (matches.index === 0) && (matches[0].length === value.length));
        }
    }, "Fail");

    $.validator.addMethod('preprocessedregularexpression', function (value, element, params) {
        var 
                preprocessRegexp = new RegExp(params.preprocessregex, "g" + params.preprocessregexoptions),
                processedValue,
                validationRegexp = new RegExp(params.validationregex, "g" + params.validationregexoptions);

        if (value !== null && value !== "") {
            processedValue = value.replace(preprocessRegexp, params.preprocessreplacement);
            return validationRegexp.test(processedValue);
        }

        return true;
    }, "Fail");

    $.validator.addMethod(
        "collectioncountrange",
        function (value, element, params) {
            var collection = $('li input[name$="' + params.propertyname + '"]');
            switch (params.operation) {
                case "eq":
                    return (collection && collection.length === params.minimum);
                case "bt":
                    return (collection && collection.length >= params.minimum && element.length <= params.maximum);
                case "gt":
                    return (collection && collection.length >= params.minimum);
                case "lt":
                    return (collection && collection.length <= params.maximum);
            }
        }, "Fail");

    $.validator.addMethod(
        "requiredignoredefaultvalue",
        function (value, element, params) {
            if (!value || !value.length) {
                return false;
            }
            if (value === params.defaultvalue) {
                return false;
            }
            return true;
        }, "Fail");

    $.validator.addMethod(
        "phonewithdefaultvalue",
        function (value, element, params) {
            if (!value || !value.length) {
                return true; //pas
            }
            if (value === params.defaultvalue) {
                return true; //pass
            }
            //if parse regex validation
            var regExp = new RegExp(params.pattern, "i"),
            matches = regExp.exec(value);
            if (params.negate == "True" || params.negate == "true") {
                return (!matches || !matches.length);
            }
            else {
                return (matches && (matches.index === 0) && (matches[0].length === value.length));
            }
            return true;
        }, "Fail");

    // This validator will prompt the user not to move forward if they have added the premium image pack but not added any photos
    // also will prevent submitting while photos are still uploading.
    $.validator.addMethod("imagelibraryfree", function (value, element, params) {
        var $element = $(element);
        var inProgressCount = $element.attr('data-val-imagelibraryfree-inprogress');
        if (inProgressCount > 0) { // don't let the user continue if they are still uploading.
            alert("Please wait for all uploads to complete before continuing");
            return false;
        }
        // NOTE: Rather than using parmas.* here I need to access teh attr() directly as it is not updating properly.
        // Also, using .data() didn't work either. Not sure if issue with jquery vs knockout ?
        var actualCount = $element.attr('data-val-imagelibraryfree-actualcount'); // how many they have
        var standardCount = $element.attr('data-val-imagelibraryfree-standardcount'); // how many they get for free
        var premiumActive = $element.attr('data-val-imagelibraryfree-premiumactive');
        var hasBeenPromptedAlready = $element.attr('data-alreadyprompted-for-free') != undefined;
        if (premiumActive != undefined) { // if undefined, then they have the full enhanced pack, so don't prompt
            if (!hasBeenPromptedAlready && premiumActive == "true" && actualCount <= standardCount) {
                $element.attr('data-alreadyprompted-for-free', "true"); // prevent multiple promptings
                $("#dialog-confirm-imagelibraryfree").dialog({
                    resizable: false,
                    close: false,
                    height: 200,
                    width: 350,
                    modal: true,
                    buttons: {
                        "Stay On Page": function () {
                            $(this).dialog("close");
                        },
                        Continue: function () {
                            $(this).dialog("close");
                            $($element[0].form).submit();
                        }
                    }
                });
                return false;
            }
        }
        return true;
    }, "Fail");

    $.validator.unobtrusive.adapters.add("imagelibraryfree", ['inprogress', 'standardcount', 'actualcount', 'premiumactive'], function (options) { options.rules["imagelibraryfree"] = options.params; });

    $.validator.unobtrusive.adapters.add('fullregularexpression', ['pattern', 'options', 'negate'],
        function (options) { options.rules['fullregularexpression'] = options.params; options.messages['fullregularexpression'] = options.message; });
    $.validator.unobtrusive.adapters.add('preprocessedregularexpression', ['preprocessregex', 'preprocessregexoptions', 'preprocessreplacement', 'validationregex', 'validationregexoptions'],
        function (options) { options.rules['preprocessedregularexpression'] = options.params; options.messages['preprocessedregularexpression'] = options.message; });
    $.validator.unobtrusive.adapters.add('collectioncountrange', ['maximum', 'minimum', 'operation', 'propertyname'],
        function (options) { options.rules['collectioncountrange'] = options.params; options.messages['collectioncountrange'] = options.message; });
    $.validator.unobtrusive.adapters.add('conditionalrequired', ['other'],
        function (options) { options.rules['conditionalrequired'] = options.params; options.messages['conditionalrequired'] = options.message; });

    $.validator.unobtrusive.adapters.add('requiredifselected', ['enablerproperty', 'enablervalue', 'valuesmustmatch'],
        function (options) { options.rules['requiredifselected'] = options.params; options.messages['requiredifselected'] = options.message; });

    $.validator.unobtrusive.adapters.add('daterange', ['mindays', 'maxdays'],
        function (options) { options.rules['daterange'] = options.params; options.messages['daterange'] = options.message; });

    $.validator.unobtrusive.adapters.add('compareiffilled', ['filledproperty', 'compareoperator'],
        function (options) { options.rules['compareiffilled'] = options.params; options.messages['compareiffilled'] = options.message; });

    $.validator.unobtrusive.adapters.add('requiredifselectedtwo', ['enablerproperty', 'enablervalue', 'valuesmustmatch'],
        function (options) { options.rules['requiredifselectedtwo'] = options.params; options.messages['requiredifselectedtwo'] = options.message; });
    /*Note: below is commmented out for Bug#16556: UAT/Sbest - error when typing salary range (Pls do not delete LL)*/
    //	$.validator.unobtrusive.adapters.add('salaryamountifselected', ['expression', 'enablerproperty', 'enablervalue'],
    //        function (options) { options.rules['salaryamountifselected'] = options.params; options.messages['salaryamountifselected'] = options.message; });
    //	$.validator.unobtrusive.adapters.add('salaryrangeifselected', ['baseproperty', 'type', 'enablerproperty', 'enablervalue'],
    //        function (options) { options.rules['salaryrangeifselected'] = options.params; options.messages['salaryrangeifselected'] = options.message; });
    $.validator.unobtrusive.adapters.add('mustagreeifselected', ['enablerproperty', 'enablervalue'],
        function (options) { options.rules['mustagreeifselected'] = options.params; options.messages['mustagreeifselected'] = options.message; });
    $.validator.unobtrusive.adapters.add('requiredignoredefaultvalue', ['defaultvalue'],
        function (options) { options.rules['requiredignoredefaultvalue'] = options.params; options.messages['requiredignoredefaultvalue'] = options.message; });
    $.validator.unobtrusive.adapters.add('phonewithdefaultvalue', ['defaultvalue', 'pattern'],
        function (options) { options.rules['phonewithdefaultvalue'] = options.params; options.messages['phonewithdefaultvalue'] = options.message; });
    $.validator.unobtrusive.adapters.add('ckstringlength', ['maxlength'],
        function (options) { options.rules['ckstringlength'] = options.params; options.messages['ckstringlength'] = options.message; });
    $.validator.unobtrusive.adapters.addBool('mustagree', 'required');
    $.validator.unobtrusive.adapters.addBool('abn');
    $.validator.unobtrusive.adapters.add('stringcompare', ['baseproperty', 'comparedproperty'],
        function (options) { options.rules['stringcompare'] = options.params; options.messages['stringcompare'] = options.message; });

    // KB 20130419 - Fix the MVC StringLength validation inconsistency when line breaks are involved.
    // Reference: http://stackoverflow.com/questions/11241076/new-line-characters-in-text-area-increases-text-length-in-c-sharp
    if ($.validator) {

        if ($.validator.settings) {
            $.validator.settings.onkeyup = false; // disable validation on keyup
        }

        //get the reference to the original function into a local variable
        var _getLength = $.validator.prototype.getLength;

        //overwrite existing getLength of validator
        $.validator.prototype.getLength = function (value, element) {

            //double count line breaks for textareas only
            if (element.nodeName.toLowerCase() === 'textarea') {

                //Counts all the newline characters (\r = return for macs, \r\n for Windows, \n for Linux/unix)
                var newLineCharacterRegexMatch = /\r?\n|\r/g;

                //use [element.value] rather than [value] since I found that the value passed in does cut off leading and trailing line breaks.
                if (element.value) {

                    //count newline characters
                    var regexResult = element.value.match(newLineCharacterRegexMatch);
                    var newLineCount = regexResult ? regexResult.length : 0;

                    //replace newline characters with nothing
                    var replacedValue = element.value.replace(newLineCharacterRegexMatch, "");

                    //return the length of text without newline characters + doubled newline character count
                    return replacedValue.length + (newLineCount * 2);
                } else {
                    return 0;
                }
            }
            //call the original function reference with apply
            return _getLength.apply(this, arguments);
        };
    }
})(jQuery);

/*Note: below is commmented out for Bug#16556: UAT/Sbest - error when typing salary range (Pls do not delete LL)*/
//// returns salary in decimal
//function FormatSalary(value) {
//    var salary;
//    if (value.indexOf("K") != -1 || value.indexOf("k") != -1) {
//        var clean = value.replace("K", "").replace("k", "");
//        salary = parseFloat(clean);
//        salary = salary * 1000;
//    }
//    else 
//    {
//        salary = parseFloat(value);
//    }

//    return salary;
//}
;
(function ($) {
    FD.namespace('FD.CasualAds.Payments.Braintree');

    FD.CasualAds.Payments.Braintree.ShowUI = function (options) {
        var form = document.querySelector(options.formId);
        var button = document.querySelector(options.buttonId);

        var dropInOptions = {
            authorization: options.authorization,
            container: options.containerId,
            card: {
                cardholderName: {
                    required: true
                }
            }
        };

        if (options.paypal) {
            dropInOptions.paypal = {
                flow: 'vault'
            };
        }
        
        braintree.dropin.create(dropInOptions, function (createErr, instance) {
            if (createErr) {
                $("#braintree-payment-details div.message-error").remove();
                $("#braintree-dropin-container").prepend("<div class=\"cN-headerMessage message-error\"><p>Error: " + createErr.message + " Please contact Customer Service for assistance.</p>");
                button.setAttribute("disabled", true);
                console.error(createErr);
                return;
            }

            button.addEventListener('click', function (event) {
                event.preventDefault();

                instance.requestPaymentMethod(function (err, payload) {
                    if (err) {
                        if (err.message === "No payment method is available.") return;

                        $("#braintree-payment-details div.message-error").remove();
                        $("#braintree-dropin-container").prepend("<div class=\"cN-headerMessage message-error\"><p>Error: " + err.message + " Please try again or contact Customer Service for assistance.</p>");
                        console.error(err);
                        return;
                    }
                    else {
                        // Add the nonce to the form
                        document.querySelector('#PaymentMethodNonce').value = payload.nonce;

                        var paymentMethod = "Credit Card";
                        if (payload.type === "PayPalAccount") {
                            paymentMethod = "PayPal";
                            document.querySelector('#PaymentMethod').value = "BraintreePayPal";
                            document.querySelector('#paymentmethodforknockout').value = "BraintreePayPal";
                        }
                        else {
                            paymentMethod = "Credit Card";
                            document.querySelector('#PaymentMethod').value = "BraintreeCreditCard";
                            document.querySelector('#paymentmethodforknockout').value = "BraintreeCreditCard";
                        }

                        if ($(form).valid()) {
                            // Show confirmation dialog
                            FD.CasualAds.confirmationDialog.ShowUI({
                                title: "Confirm Payment Method",
                                content: "<p>You have chosen to pay for this ad with " + paymentMethod + ". You will not be able to change the payment method, once you confirm.</p> <p>Please confirm by clicking on Continue to proceed with the payment or Cancel to change to a different payment method option.</p>",
                                yes_button: "Continue",
                                no_button: "Cancel",
                                confirm: function () {
                                    FD.Classifieds.CasualAds.Web.Billing.ShowProcessingUI();
                                    form.submit();
                                },
                                cancel: function () {
                                    return;
                                }
                            });
                        }
                    }
                });
            });

        });
    };
}) (jQuery);;
/**
* @license Drive Casualads workflow
* Copyright 2010 Fairfax Digital.
*/

// Global Declarations for JSLint
/*global FD:true, jQuery:false */

(function () {

    "use strict";

    FD.namespace('FD.Classifieds.CKEditor');
    (
    /*
    * Determines whether a keyCode represents a character on the screen.
    */
        FD.Classifieds.CKEditor.isChar = function (keyCode) {
            var isCharKeyCode = true;
            if (keyCode) {
                isCharKeyCode = !(
                    keyCode === 8 // backspace
                    || keyCode === 16 // shift
                    || keyCode === 17 // ctrl
                    || keyCode === 18 // alt
                    || keyCode === 19 // pause/break
                    || keyCode === 20 // caps lock
                    || keyCode === 27 // escape
                    || keyCode === 33 // page up
                    || keyCode === 34 // page down
                    || keyCode === 35 // end
                    || keyCode === 36 // home
                    || (keyCode >= 37 && keyCode <= 40) // arrow keys
                    || keyCode === 45 // insert
                    || keyCode === 46 // delete
                    || keyCode === 91 // left windows key
                    || keyCode === 92 // right windows key
                    || (keyCode >= 112 && keyCode <= 123) // function keys
                    || keyCode === 144 // num lock
                    || keyCode === 145 // scroll lock
                    || (keyCode >= 1000 && keyCode <= 1999) // ctrl + any key
                    || (keyCode >= 2033 && keyCode <= 2040) // shift + direction keys
                    || (keyCode >= 2112 && keyCode <= 2123) // shift + function keys
                    || (keyCode >= 3000 && keyCode <= 3999) // ctrl + shift + any key
                    || (keyCode >= 4000 && keyCode <= 4999) // alt + any key
                    || (keyCode >= 5000 && keyCode <= 5999) // ctrl + alt + any key
                    || (keyCode >= 6000 && keyCode <= 6999) // shift + alt + any key
                    );
            }
            return isCharKeyCode;
        }
    );

    FD.namespace('FD.Classifieds.CKEditor.MaxLength');
    (
    /*
    * onKey event handler to check the max length
    */
        FD.Classifieds.CKEditor.MaxLength.onKey = function (e) {
            var text = null;
            if (e
                && e.sender
                && e.sender.config
                && e.sender.config.maxLength) {
                text = FD.Convert.toText(this.getData());
                if (text === null) {
                    text = "";
                }
                if (text.length >= e.sender.config.maxLength
                    &&
                    FD.Classifieds.CKEditor.isChar(e.data.keyCode)) {
                    FD.log("FD.Classifieds.CKEditor.MaxLength.onKey: KeyCode - " + e.data.keyCode);
                    e.cancel();
                }
            }
        },

        FD.Classifieds.CKEditor.MaxLength.onPaste = function (e) {
            var text = null;
            if (e
                && e.sender
                && e.sender.config
                && e.sender.config.maxLength) {
                text = FD.Convert.toText(this.getData());
                if (text === null) {
                    text = "";
                }
                if (FD.Classifieds.CKEditor.isChar(e.data)) {
                    var newTextLength = text.length + e.data.text.length;
                    if (newTextLength >= e.sender.config.maxLength) {
                        // Get selected text
                        var selectedText;
                        var mySelection = this.getSelection();

                        if (CKEDITOR.env.ie) {
                            mySelection.unlock(true);
                            selectedText = mySelection.getNative().createRange().text;
                        } else {
                            selectedText = mySelection.getNative();
                            selectedText = "" + selectedText;
                        }

                        // Max length - Current length - Selection length
                        var substringLength = e.sender.config.maxLength - (text.length - selectedText.length);

                        // Truncate
                        e.data.text = e.data.text.substring(0, substringLength);
                        FD.log("FD.Classifieds.CKEditor.MaxLength.onPaste: " + e.data);
                    }
                }
            }
        }
    );

    FD.namespace('FD.Classifieds.CKEditor');
    (
    /*
    * Base event handler to call to extend the CKEditor
    */
        FD.Classifieds.CKEditor.onInstanceReady = function (e) {
            if (e
                && e.sender
                && e.sender.config
                && e.sender.config.maxLength) {
                e.sender.on('key', FD.Classifieds.CKEditor.MaxLength.onKey);
                e.sender.on('paste', FD.Classifieds.CKEditor.MaxLength.onPaste);
            }
        }
    );
} ());;
 /**
* @license CasualAds workflow
* Copyright 2010 Fairfax Digital.
*/
"use strict";

// Global Declarations for JSLint
/*global FD:true, document:false, window:true, jQuery:false, s_gi:false, s_account:false */

/// <reference path="fd.js" />
FD.namespace("FD.Classifieds.Utils");
(function($) {
    FD.Classifieds.Utils.highlight = function (element, color) {
        element = $(element || this);
        color = color || '#feffbf';
        element.effect("highlight", {color: color}, 1500);
    };
}(jQuery));


(function ($) {

    FD.namespace("FD.Classifieds.CasualAds.Account");
    FD.Classifieds.CasualAds.Account.AjaxLogon = (function () {

        var 
            _buttonText,
            _returnUrl,
            _container,
			_isPopup,
            _logonUrlTemplate = "/account/ajaxlogon?buttonText=$buttonText$&returnUrl=$returnUrl$",
            _formSubmitHandler;


        function _getReturnUrl() {
        /// <summary>
        /// Gets the return Url with the required replacements made.
        /// </summary>
            var url,
                encodedReturnUrl;

            encodedReturnUrl = encodeURI(_returnUrl);
            url = _logonUrlTemplate
                    .replace(/\$buttonText\$/g, _buttonText)
                    .replace(/\$returnUrl\$/g, encodedReturnUrl);

            return url;
        }

        function _displaySuccess(data, status, request) {
        /// <summary>
        /// Handler for successful return of AjaxLogon.
        /// </summary>

            // Check for a redirect header
            var redirect = request.getResponseHeader('X-Redirect');
            if (redirect) {
                window.location = redirect;
            } else {
                _container.html(data);
                _container
                    .find("div.hint")
                        .popupHint()
                    .end()
                    .find("form")
                        .submit(_formSubmitHandler);

				if(_isPopup)
				{
					$(".cN-dialog .z-position").zPosition(2000);
				}
            }
        }

        function _ajaxLoadPanel(method, data) {
        /// <summary>
        /// Initiate load of AjaxLogon
        /// </summary>

            $.ajax({
                "cache": false, 
                "url": _getReturnUrl(),
                "type": method,
                "success": _displaySuccess,
                "data": data
            });
        }

        _formSubmitHandler = function () {
        /// <summary>
        /// Handler for submit of AjaxLogon
        /// </summary>

            var data = $(this).find(":input").serializeArray();
            _ajaxLoadPanel("POST", data);
            return false;
        };

        return {
            initialize : function (settings) {
                settings = $.extend({}, { buttonText: "Log in", returnUrl: "/"}, settings);
                _buttonText = settings.buttonText;
                _returnUrl = settings.returnUrl;
                _container = $(settings.container);
				_isPopup = settings.isPopup;

                $(function() { 
                    _container.find("a.forgotPassword").live('click', function(evt) {
                        var emailParam = "", 
                            email = "";

                        evt.preventDefault();
                        if (evt.target) {
                            email = $.URLEncode(_container.find("input#UserName").val());
                            if (email) {
                                emailParam = "?Email=" + email;
                            }
                        }
                        window.open("https://membercentre.fairfax.com.au/ForgottenPassword.aspx" + emailParam, "_blank");
                    });
                });

                _ajaxLoadPanel("GET");
            }
        };
    }());
} (jQuery));


FD.namespace("FD.Classifieds.CasualAds.Address");
(function ($) {
    FD.Classifieds.CasualAds.Address.create = function (
        suburbSuggestInputId, postcodeId, suburbId, stateId, countryId, showFullLinkId, showTownSuburbOnlyId) {

        /// <summary>
        /// Controls the toggling of the address inputs.
        /// </summary>
        $(function () {
            var 
                suburbSuggestInputObj = $(suburbSuggestInputId),
                suburbSuggestContainerObj = $(suburbSuggestInputObj).parents("li").eq(0),
                addressViewSwitchObj = $(showFullLinkId),
                townSuburbSwitchObj =  $(showTownSuburbOnlyId),
                postcodeObj = $(postcodeId),
                suburbObj = $(suburbId),
                stateObj = $(stateId),
                countryObj = $(countryId),
                postcodeVal = postcodeObj.val(),
                suburbVal = suburbObj.val(),
                stateVal = stateObj.val();

                $([postcodeObj, suburbObj, stateObj, countryObj]).each(function (index) {
                    $(this).parents("li").hide();
                });

            addressViewSwitchObj.click(function (e) {
                e.preventDefault();

                suburbSuggestContainerObj.fadeOut(function () {
                    $([postcodeObj, suburbObj, stateObj, countryObj]).each(function () {
                        $(this).parents("li").fadeIn(FD.Classifieds.Utils.highlight);
                    });
                    suburbObj.focus();
                });
            });

            townSuburbSwitchObj.click(function (e) {
                e.preventDefault();

                $([suburbObj, stateObj, countryObj]).each(function (index) {
                    $(this).parents("li").fadeOut();
                });
                postcodeObj.parents("li").fadeOut(function () {
                    suburbSuggestContainerObj.fadeIn(FD.Classifieds.Utils.highlight).find('input').first().focus();
                });
            });

            // <%-- Registers a call back to populate the postcode, suburb and state field
            // when the suburb suggestion input has selected a suburb. --%>
            FD.Classifieds.CasualAds.SuburbSuggest.cb[suburbSuggestInputId] = function (suburbInfo) {
                postcodeObj.val(suburbInfo.Postcode);
                suburbObj.val(suburbInfo.Suburb);
                stateObj.val(suburbInfo.State);
            };
        });
    };
}(jQuery));


FD.namespace("FD.Classifieds.CasualAds.AdminToolbar");
(function ($) {
    FD.Classifieds.CasualAds.AdminToolbar.init = function (actions) {
        var adminBar = $('#adminToolbar'),
            offsetTop = adminBar.offset().top,
            webOptions = $('.web', adminBar), 
            printOptions = $('.print',adminBar),
            bundleOptions = $('.bundle',adminBar);
           
        adminBar.css('height', adminBar.children().height());

        $(document).scroll(function () {
            var scrollTop = $(this).scrollTop();
            if (scrollTop > offsetTop) {
                if (!adminBar.hasClass('float')) {
                    adminBar.addClass('float').children().css('position', 'fixed').fadeTo('slow', 0.9);
                }
            } else {
                if (adminBar.hasClass('float')) {
                    adminBar.removeClass('float').children().css('position', 'relative').fadeTo('slow', 1);
                }
            }
        });

        $.each(actions, function () {
            var a = $('<a>').text(this.label);
            if ($.isFunction(this.action)) {
                a.attr('href', '#');
                var action = this.action;
                a.click(function () { 
                    action(); 
                });
            } 
            else {
                var navUri = this.action;
                a.attr('href', navUri);

                // Redundant as confirm deletion happens on next step
                /*if (this.action.indexOf("Delete") > 0) {
                    a.click(function(evt) {
                        var confirmDialog = $('<div />').html('<p>Are you sure you want to delete this ad?<br />This cannot be undone.</p>');
                        evt.preventDefault();

                        confirmDialog.dialog({
                            autoOpen: true,
                            title: 'Confirm delete.',
                            modal: true,
                            width: 400,
                            height: 140,
                            buttons: {
                                "Yes": function () {
                                    $(this).dialog("close");
                                    window.location = navUri;
                                },
                                "No": function () {
                                    $(this).dialog("close");
                                }
                            }
                        });
                    });
                }*/
            }
            
            if(typeof(this.group) != 'undefined')
            {
                switch(this.group)
                {
                    case 'WEB': 
                        $('<li>', {'class': this["class"] }).append(a).appendTo(webOptions);
                        break;
                    case 'PRN':
                        $('<li>', {'class': this["class"] }).append(a).appendTo(printOptions);
                        break;
                    case 'BUNDLE': 
                        $('<li>', {'class': this["class"] }).append(a).appendTo(printOptions);
                        break;
                    default:  break;
                }

            }else
            {
                 var options = $('<ul class="options"></ul>');
                 $('<li>', {'class': this["class"] }).append(a).appendTo(options);
                 options.appendTo($('.functions'));
            }

        });

        $('.options').each(function(){
            if($(this).find('li').length > 0)
            {
                if($(this).hasClass('web'))  
                    $(this).before('<span class="label" style="float:left;">Web Advert: </span>');
                else if($(this).hasClass('print')) 
                    $(this).before('<span class="label" style="float:left;">Print Advert: </span>');
            }
        });
    };
} (jQuery));

FD.namespace("FD.Classifieds.CasualAds.Workflow");
(function ($) {

    var confirmDialog = $('<div />').html('<p>You are about to navigate away from this page.<br />All changes will be lost!</p>');

    FD.Classifieds.CasualAds.Workflow.confirmExit = function (evt) {
        var linkObj = this,
            navUri = $(this).attr('href');

        // check if we currently are in a flow
        if (window.location
            && window.location.search
            && window.location.search.match(/\bflow\b/gi)
            && !navUri.match(/^javascript\b/gi)
            && (typeof(confirmExitOverride) === 'undefined' || confirmExitOverride) // ensure display hasn't been overridden
            ) { 

            evt.preventDefault();

            confirmDialog.dialog({
                autoOpen: true,
                title: 'Please Confirm!',
                modal: true,
                width: 400,
                height: 240,
                buttons: {
                    "Yes, get me out of here": function () {
                        $(this).dialog("close");
                        window.location = navUri;
                    },
                    "No, return to ad": function () {
                        $(this).dialog("close");
                    }
                }
            });
        }
    };

    $(function() {
        if (typeof(confirmExitOverride) === 'undefined' || confirmExitOverride) {
            $("p.mh-logo a")
            .add("div.nN-whiteStrip a[target!='_blank']") // adds confirm exit dialog to whitestrip links
            .add("div.footer a[target!='_blank']") // adds confirm exit dialog to footer links
            .add("div.header a[target!='_blank']")  // adds confirm exit dialog to header links
            .not("div.header #adminToolbar a")  // removes confirm exit dialog from admin toolbar buttons
            .click(FD.Classifieds.CasualAds.Workflow.confirmExit);
        }
    });
    
    $(".save").on('click', function (e) {
        // set value of save and exit element to true
        $('<input type=\'hidden\' id=\'saveAndExit\' name=\'saveAndExit\' value=\'true\'>').insertBefore($(e.currentTarget));
        var form = $(e.currentTarget).closest('form');
        if (form != undefined)
            form.validate().settings.ignore = "*";
    });

    $("#goBackButton").on('click', function (e) {
        // set value of go back element to true
        $('<input type=\'hidden\' id=\'goBack\' name=\'goBack\' value=\'true\'>').insertBefore($(e.currentTarget));
        var form = $(e.currentTarget).closest('form');
        if (form != undefined)
            form.validate().settings.ignore = "*";
    });

    // Prevent the enter key in any single line input or select box from submitting the form.
    $('#PlaceAdForm input, #PlaceAdForm select').keypress(function (event) { return event.keyCode != 13; });

    $("#savePreview").on('click', function (e) {
        var form = $(e.currentTarget).attr("form");        
        var previewUrl = $(e.currentTarget).attr("data-preview-url");

        var $placeAdForm = $("#" + form);
        if ($placeAdForm.valid()) {
            $('<input type=\'hidden\' id=\'saveAndPreview\' name=\'saveAndPreview\' value=\'true\' form=\'' + form + '\'>').appendTo($placeAdForm);
            //$("#" + form).validate().settings.ignore = "*"

            var data = $placeAdForm.serialize();
            $.post($placeAdForm.attr("action"), data, function (data, textStatus, jqXHR) {
                $placeAdForm.find("#saveAndPreview").remove();
                PreviewOverlay(previewUrl);
            });
        } else {
            alert("Please complete the form before previewing the ad.");
        }
    });

    $("a.dialogTrigger.isAjax").click(function (e) {
        var defaults = {
            width: "640",
            height: "480",
            title: ""
        },
        options = {
            width: $(this).data("dialog-width") || defaults.width,
            height: $(this).data("dialog-height") || defaults.height,
            title: $(this).data("dialog-title") || defaults.title
        };

        e.preventDefault();
        $.get($(this).attr("href"), function (data, textStatus, jqXHR) {
            if ($("#tmpDialog").length == 0) {
                $("body").append($("<div id='tmpDialog' />"));
            }
            $("#tmpDialog").html(data).dialog(options);
        });
    });
} (jQuery));
;

(function ($) {

    FD.namespace('FD.Classifieds.CasualAds');

    FD.Classifieds.CasualAds.tabs = function (e) {

        var $this = $(e),
            tabId,
            thisTabPages = $(e),
            tabList = $(".tabNav", e).attr({ "role": "tablist" }),
            tabPanels = $(".tabPanel", e).attr({ "role": "tabpanel", "aria-hidden": "true" });

        //For each tab
        $("li > a", tabList).each(function (index) {
            // Get href of of tab list as tabs ID.
            tabId = $(this).attr("href").slice(1);

            // Set aria and tabindex attributes. We also set the <li> to role presentation because in the tab structure the <li> is no longer a list but a tablist.
            $(this).attr({ "role": "tab", "aria-selected": "false", "tabindex": "-1" }).parent().attr({ "role": "presentation" });

            // Pair up tab list and tab panels using aria-labelledby
            tabPanels.eq(index).attr("aria-labelledby", tabId);
        })
        // Set aria-selected to true for selected tab
        $this.find("li.selected a", tabList).attr({ "aria-selected": "true", "tabindex": "0" });
        // Set aria-hidden to false for tab that's shown by default. Also set tabindex to 0 so user can tab into it. 
        $this.find("div.selected").attr({ "aria-hidden": "false", "tabindex": "0" });

        $("li > a", tabList).click(function () {
            var selectedTabId = $(this).attr('href');

            // Set selected link as selected.
            $('li > a[href$="' + selectedTabId + '"]', tabList).parents('ul').children().removeClass('selected').children("a").attr({ "aria-selected": "false", "tabindex": "-1" });
            $('li > a[href$="' + selectedTabId + '"]', tabList).parents('li').addClass('selected').children("a").attr({ "aria-selected": "true", "tabindex": "0" });

        });

        tabList.on("a", "keydown", function (e) {
            /* if left arrow key */
            if (e.keyCode == 37) {
                // If there's another list item before the selected tab
                if ($(this).parent().prev().length != 0) {
                    $(this).parent().prev().children("a").focus().click();
                } else {
                    // Reached the first tab, go select the last tab
                    tabList.find("li:last > a").focus().click();
                }
            }
            /* if right arrow key */
            if (e.keyCode == 39) {
                // If there's another list item after the selected tab
                if ($(this).parent().next().length != 0) {
                    $(this).parent().next().children("a").focus().click();
                } else {
                    // Reached the last tab, go select the first tab
                    tabList.find("li:first > a").focus().click();
                }
            }
        });
    };

    /* Tabs */

    $('.tabs').each(function (i, e) { new FD.Classifieds.CasualAds.tabs(e); });

})(jQuery);;
/**
The root of the CAP namespace.

@class CAP
**/

/**
Creates the specified namespace objects if they don't exist already

@method namespace
@param {String} dot notation namespace 
@return {Object} The empty, or existing namespace object
**/
function namespace(namespaceString) {
    var parts = namespaceString.split('.'),
        parent = window,
        currentPart = '';

    for (var i = 0, length = parts.length; i < length; i++) {
        currentPart = parts[i];
        parent[currentPart] = parent[currentPart] || {};
        parent = parent[currentPart];
    }

    return parent;
};
/**
CAP UI Related functions

@class CAP.UI
@constructor
**/
namespace('CAP').UI = (function ($) {
    return {
        /**
        Reloads the specified div via the data-reload-url attribute 

        @method reloadPanel
        **/
        reloadPanel: function (callback) {
            this.each(function () {
                var $panelToReload = $(this);
                //$panelToReload.block();
                if ($panelToReload.data("reload-method") === "POST") {
                    $.post($panelToReload.data("reload-url"), function (data) {
                        $panelToReload.replaceWith(data);
                        if (typeof callback === 'function') {
                            callback.call(); // Call your callback
                        }
                    });
                } else {
                    $.get($panelToReload.data("reload-url"), function (data) {
                        $panelToReload.replaceWith(data);
                        if (typeof callback === 'function') {
                            callback.call(); // Call your callback
                        }
                    });
                }
            });
        },
        /**
        Collapse or expand the shopping cart

        @method cartToggle
        **/
        cartToggle: function () {
            return this.each(function () {
                var cartToggle = $(this);
                var id = cartToggle.attr("id");
                var row = cartToggle.closest("tr");
                var breakdownClass = ".breakdown-" + id;
                var toggleRow = row.siblings(breakdownClass);
                toggleRow.attr("aria-labelledby", id);

                //Add aria-expanded and make element focusable
                cartToggle.attr({ "aria-expanded": "false", "tabindex": "0", "aria-controls": id });
                cartToggle.off("click keydown"); // ensure the click is only handled once
                cartToggle.on("click keydown", function (e) {
                    if (e.keyCode === 13 || e.type === "click") {
                        //Toggle aria-expanded attribute value
                        cartToggle.toggleAttr("aria-expanded", "true", "false", false).toggleClass("expanded");
                        row.children(".price").toggleClass("collapsed");
                        toggleRow.toggleClass("collapsed");
                    }
                });

            });
        },
        /**
        Toggle attribute of a DOM element

        @method toggleAttr
        @param {String} attribute: attribute to set
        @param {String} on : expression true value
        @param {String} off: expression false value
        @param {Boolean} check: expression
        **/
        toggleAttr: function (attribute, on, off, check) {
            return this.each(function () {
                var $this = $(this);
                if (check)
                    $this.attr(attribute, ($this.filter(":visible").length === 0 ? off : on));
                else
                    $this.attr(attribute, ($this.attr(attribute) === on ? off : on));
            });
        },
        /**
        Toggle content

        @method toggleContent
        @param {String} options: options for the toggle
        **/
        toggleContent: function (options) {
            // Setup defaults
            var defaults = {
                // Define the toggle button's wrapper and element
                toggleBtnWrap: null, // Wrapper around button element
                toggleBtnTrigger: $('<button type="button" class="btnToggle btnFauxLink"></button>'), // Mark up for button element
                toggleContent: ".toggleContent",
                btnTxtOpen: 'Show more', // Text you want in the button *before* toggling
                btnTxtClose: 'Show less', // Text you want in the button *after* toggling
                btnPos: 'insertAfter', // Where you want to inject the button. Values: "insertAfter" || "insertBefore"
                btnOpenClass: 'expand', // Button class when content is hidden and button indicates it can be opened
                btnCloseClass: 'collapse', // Button class when content is shown and button indicates it can be closed
                toggleSpeed: 200,
                shownByDefault: false,
                callBackMethod: null,
                btnInject: false
            }

            return $(this).each(function (i, e) {

                if (!$(e).data('fd.toggleContent'))
                {
                    $(e).data('fd.toggleContent', true);

                    // Merge defaults and options
                    var settings = $.extend(defaults, options);

                    var toggleWrap = $(e);
                    var toggleContent = toggleWrap.find(settings.toggleContent);
                    var toggleBtnWrap = settings.toggleBtnWrap;
                    var toggleBtnTrigger = settings.toggleBtnTrigger;
                    var btnInject = settings.btnInject;
                    var btnTxtOpen = settings.btnTxtOpen;
                    var btnTxtClose = settings.btnTxtClose;
                    var btnPos = settings.btnPos;
                    var btnOpenClass = settings.btnOpenClass;
                    var btnCloseClass = settings.btnCloseClass;
                    var toggleSpeed = settings.toggleSpeed;
                    var shownByDefault = settings.shownByDefault;
                    var callBackMethod = settings.callBackMethod;

                    // Show content
                    showContent = function (toggleBtnTrigger) {
                        toggleBtnTrigger.addClass(btnCloseClass).text(btnTxtClose);
                        toggleContent.show().toggleAttr("aria-expanded", "false", "true", false);
                        toggleBtnTrigger.toggleAttr("aria-expanded", "true", "false", false);

                    }

                    // Hide content 
                    hideContent = function (toggleBtnTrigger) {
                        toggleBtnTrigger.addClass(btnOpenClass);
                        toggleBtnTrigger.text(btnTxtOpen);
                        toggleContent.hide();
                        toggleContent.toggleAttr("aria-expanded", "false", "true", false);
                        toggleBtnTrigger.toggleAttr("aria-expanded", "false", "true", false);
                    }

                    if (!btnInject) {
                        toggleBtnTrigger = toggleWrap.find(toggleBtnTrigger);
                        btnTxtOpen = toggleBtnTrigger.text();
                        btnTxtClose = toggleBtnTrigger.text();
                    }

                    // When clicking on the toggle button
                    toggleBtnTrigger.click(function () {
                        toggleContent.slideToggle(toggleSpeed, function() {
                            toggleContent.toggleAttr("aria-expanded", "true", "false", false);
                            toggleBtnTrigger.toggleClass(btnCloseClass).toggleClass(btnOpenClass).toggleAttr("aria-expanded", "true", "false", false);
                            if (toggleContent.is(":visible")) {
                                toggleBtnTrigger.text(btnTxtClose);
                                if (callBackMethod)
                                    callBackMethod(toggleContent, true);
                            } else {
                                toggleBtnTrigger.text(btnTxtOpen);
                                if (callBackMethod)
                                    callBackMethod(toggleContent, false);
                            }
                        });
                    });


                    // If toggle content is visible by default (or if there is an error message showing within)
                    if (shownByDefault || $(".field-validation-error", toggleContent).length > 0) {
                        showContent(toggleBtnTrigger);
                        if (callBackMethod)
                            callBackMethod(toggleContent, true);
                    } else {
                        hideContent(toggleBtnTrigger);
                        if (callBackMethod)
                            callBackMethod(toggleContent, false);
                    }

                    // Create the toggle button (wrapper + button trigger)
                    var toggleBtn = null;
                    if (toggleBtnWrap !== null)
                        toggleBtn = toggleBtnWrap.append(toggleBtnTrigger);
                    else
                        toggleBtn = toggleBtnTrigger;

                    // Inject the toogle button
                    if (btnInject) {
                        switch (btnPos) {
                            case ("insertAfter"): // insert after the hidden content	
                                toggleBtn.insertAfter(toggleContent);
                                break;
                            case ("insertBefore"): // insert before the hidden content	
                                toggleBtn.insertBefore(toggleContent);
                                break;
                        }
                    }
                }
            })
        }
    };
})(jQuery);
;
/**
CAP Extensions to the jQuery $.fn scope.

All methods should be references into the CAP namespace

@class CAP-jQueryExtensions 
@constructor
**/
(function ($) {
    /**
    Reload the specified DIV from the source URL

    @method reloadPanel
    **/
    $.fn.reloadPanel = CAP.UI.reloadPanel;

    /**
    Allow the shopping cart to be opened/closed

    @method cartToggle
    **/
    $.fn.cartToggle = CAP.UI.cartToggle;

    /**
    Alternate the state of an attribute on a DOM element

    @method toggleAttr
    **/
    $.fn.toggleAttr = CAP.UI.toggleAttr;

    /**
    Toggle function for content pages

    @method toggleContent
    **/
    $.fn.toggleContent = CAP.UI.toggleContent;

    /**
    Override the number validator to use globalise plugin
    See SSCPRODUCTION-1243
    **/
    $.validator.methods.number = function (value, element) {
        return this.optional(element) || !isNaN(Globalize.parseFloat(value));
    }

    /**
    Override the range validator to use the globalise plugin.
    See SSCPRODUCTION-1243
    **/
    $.validator.methods.range = function (value, element, param) {
        return this.optional(element) || (Globalize.parseFloat(value) >= param[0] && Globalize.parseFloat(value) <= param[1]);
    }
})(jQuery);



;
/**
Class to access place ad methods specific to Domain place ad flow.

@class CAP.DateTimePicker
@constructor
**/

namespace('CAP').DateTimePicker = (function ($) {
    return {
        init: function () {
            $('.datepicker').datepicker(
            {
                dateFormat: "dd/mm/yy",
                minDate: "+1d",
                maxDate: "+1y",
                onSelect: function () {
                    CAP.DateTimePicker.initTimePicker();
                }
            });

            // Override timespan picker defaults
            $.extend($.ffx.timespanpicker.prototype.options, {
                // Date
                dateMin: new Date(),
                // Time
                timeMin: "8:00am",
                timeMax: "8:00pm",
                timeStep: 30
            });

            this.initTimePicker();

            $(".timespanpicker").timespanpicker();

            var viewModel = new DateTimePickerViewModel();
            // load from server
            var currentElement = $(".timespanpicker").parent();
            viewModel.selectedDates(currentElement.data("initial"));

            // apply the viewmodel to the html.
            ko.applyBindings(viewModel, currentElement[0]);
        },
        initTimePicker: function () {
            /* Time pickers */
            $(".timepicker").timepicker({
                minTime: "8:00am",
                maxTime: "8:00pm"
            });
        },
        formatDateTimeDisplay: function (startParam, endParam) {
            startTime = CAP.DateTimePicker.getDateValue(startParam);
            endTime = CAP.DateTimePicker.getDateValue(endParam);
 
            var curr_month = startTime.getMonthName(true);
            var curr_day = startTime.getDayName(true);
            var curr_date = startTime.getDate();

            var start_hour = startTime.getHours();
            var start_min = startTime.getMinutes();

            var end_hour = endTime.getHours();
            var end_min = endTime.getMinutes();

            if (start_hour > 12) {
                start_hour -= 12;
            }

            var ap_m = "AM" // decide am/pm based on end hour
            if (end_hour > 11) {
                ap_m = "PM";
                if (end_hour > 12) { end_hour -= 12; }
            }

            if (start_min == 0) start_min = "00";
            if (end_min == 0) end_min = "00";

            return (curr_day + " " + curr_date + " " + curr_month + " " + start_hour + ":" + start_min + " - " + end_hour + ":" + end_min + " " + ap_m);
        },
        getDateValue: function (dateParam)
        {
            var year, month, day, hour, minute;
            if (typeof (dateParam) == "string") {
                var date = $.datepicker.parseDate("yy-mm-dd", dateParam.split('T')[0]);
                var timestring = dateParam.split('T')[1];
                hour = timestring.split(':')[0];
                minute = timestring.split(':')[1];
                if (date != "NaN")
                {
                    date.setHours(hour, minute, 0);
                }
                return date;
            } else {
                //this fix for IE8
                year = dateParam.getFullYear(),
                     month = dateParam.getMonth(),
                     day = dateParam.getDate(),
                     hour = dateParam.getHours(),
                     minute = dateParam.getMinutes();
                var date = new Date(year, month, day, hour, minute, 0);
                return date;
            }
        }
    }
})(jQuery);

function DateTimePickerViewModel() {
    var self = this;
    self.selectedDates = ko.observableArray();
    var $picker = $('.timespanpicker');
    self.addDate = function () {
        var startTime = $picker.timespanpicker('getStartTime');
        var endTime = $picker.timespanpicker('getEndTime');
        if (!self.validateDates(startTime, endTime))
        {
            return false;
        }
        self.clearErrorMessage();

        FD.log('startTime: ' + startTime.toLocaleString());
        FD.log('endTime: ' + endTime.toLocaleString());

        FD.log(CAP.DateTimePicker.formatDateTimeDisplay(startTime, endTime));
        startTime = startTime.toJSONLocal();
        endTime = endTime.toJSONLocal();

        self.selectedDates.push({ StartTime: startTime, EndTime: endTime });
        self.saveDate();
    };
    self.removeDate = function () {
        self.selectedDates.remove(this);
        self.saveDate();
    };
    self.saveDate = function () {
        var dateTimeJsonString = ko.toJSON(self.selectedDates);
        FD.log('json: ' + dateTimeJsonString);
        $('.DateTimePickerValues').val(dateTimeJsonString);

    };
    self.validateDates = function (selectedStartTime, selectedEndTime) {
        var isValidPeriod = true;
        //rule 1:  the start time must be earlier than end time
        isValidPeriod = selectedEndTime > selectedStartTime;

        if (!isValidPeriod) {
            self.showErrorMessage('Please enter a valid start and end time.');
            return false;
        }

        //rule 2: no overlapping of the preriods
        var selectedDates = self.selectedDates();
        if (selectedDates.length > 0) {
            for (var i = 0; i < selectedDates.length; i++) {
                var startTime = CAP.DateTimePicker.getDateValue(selectedDates[i].StartTime);
                var endTime = CAP.DateTimePicker.getDateValue(selectedDates[i].EndTime);

                isValidPeriod = (selectedStartTime > endTime) || (selectedEndTime < startTime);
                if (!isValidPeriod)
                    break;
            }
        }

        if (!isValidPeriod) self.showErrorMessage('The selected date overlaps with an existing date.');

        return isValidPeriod;
    };
    self.showErrorMessage = function (errMsg) {
        self.clearErrorMessage();
        $picker.append("<span class='field-validation-error' width='200px'>" + errMsg + "</span>");
    };
    self.clearErrorMessage = function () {
        $picker.find('.field-validation-error').remove();
    };
}

Date.prototype.toJSONLocal = (function () {
    function addZ(n) {
        return (n < 10 ? '0' : '') + n;
    }
    return function () {
        return this.getFullYear() + '-' +
               addZ(this.getMonth() + 1) + '-' +
               addZ(this.getDate()) + 'T' + 
               addZ(this.getHours()) + ":" +
               addZ(this.getMinutes()) + ":00"
                
    };
}());
/**
CAP common UI calls.

**/

$(function () {

	$(".myads .toggle.alt").toggleContent({
		btnInject: false,
		toggleBtnTrigger: $(".toggleTrigger"),
		toggleSpeed: 0,
		role: 'button',
		shownByDefault: true
	});

	$(".toggle.alt").toggleContent({
		btnInject: false,
		toggleBtnTrigger: $(".toggleTrigger"),
		toggleSpeed: 0,
		role: 'button',
		shownByDefault: false
	});

	$(".defaultopen .toggle.alt").toggleContent({
		btnInject: false,
		toggleBtnTrigger: $(".toggleTrigger"),
		toggleSpeed: 0,
		role: 'button',
		shownByDefault: true
	});

	$(".list-faq .toggle").toggleContent({
		btnInject: false,
		toggleBtnTrigger: $(".toggleTrigger"),
		toggleSpeed: 0,
		role: 'button'
	});

    $("body").on("click", ".toggle-trigger", function (evt) {
        evt.preventDefault();
        return false;
    });

    $("body").on("click", ".toggleAll .expand", function () {
        $(".toggleTrigger").children().removeClass("expand").addClass("collapse");
        $(".toggleContent").show();
    });

    $("body").on("click", ".toggleAll .collapse", function () {
        $(".toggleTrigger").children().removeClass("collapse").addClass("expand");
        $(".toggleContent").hide();
    });


});

/**
Class to access place ad methods on the server controller

@class CAP.common.PlaceAd 
@constructor
**/
namespace('CAP.common').PlaceAd = (function ($) {
    return {

        /**
        * Activate the specified product by key
        * 
        * @method addProduct
        * @param {String} Key of product on shopping cart
        * @return {Boolean} Indicating success or failure
        */
        addProduct: function (key, activeChildrenKeys) {
            var addProductUrl = $('body').data('upsell-add');
            activeChildrenKeys = activeChildrenKeys || "null";
            var result = $.ajax({
                url: addProductUrl + '?flow=' + flowID + '&productKey=' + key + '&swapOut=false&activeChildrenKeys=' + activeChildrenKeys,
                type: 'POST',
                success: function(data) {
                    CAP.common.PlaceAd.updateActiveUpsellProducts(data);
                }
            });
            return true;
        },

        /**
        * Deactivate the specified product by key
        * 
        * @method removeProduct
        * @param {String} Key of product on shopping cart
        * @return {Boolean} Indicating success or failure
        */
        removeProduct: function (key, disableParent) {
            var removeProductUrl = $('body').data('upsell-remove');
            disableParent = (typeof(disableParent) === 'undefined' ? 'true' : disableParent);
            var result = $.ajax({
                url: removeProductUrl + '?flow=' + flowID + '&productKey=' + key + '&disableParent=' + disableParent,
                type: 'POST',
                success: function(data, status) {
                    CAP.common.PlaceAd.updateActiveUpsellProducts(data);
                }
            });
            return true;
        },

        /**
        * Following activating or deactivating a product, update all upsell products
        * 
        * @method updateActiveUpsellProducts
        * @param {String} Key of active products on cart
        */
        updateActiveUpsellProducts: function (data) {
            if (data.d != undefined) {
                $(".upsellPanel").each(function (index, element) {
                    // disable all of them, this doesn't cause a flicker because knockout defers the updates for a moment
                    var dataForModel = ko.dataFor(element);
                    if (dataForModel != undefined && dataForModel.upsellViewModel != undefined) {
                        dataForModel.upsellViewModel.IsActive(false);
                    }
                });
                for (var i = 0; i < data.d.length; i++) {
                    var element = document.getElementById("UpsellViewModel_" + data.d[i].replace(/[^0-9a-f]+/g, ''));
                    if (element != undefined) {
                        var dataForModel = ko.dataFor(element);
                        if (dataForModel != undefined && dataForModel.upsellViewModel != undefined) {
                            dataForModel.upsellViewModel.IsActive(true);
                        }
                    }
                }
            }
        },

        /**
        * Setup CKEditor for Detail description
        * 
        * @method setupDetailsEditor
        */
        setupDetailsEditor: function(elementId, maxLength) {
            CKEDITOR.replace(elementId,
            {
                customConfig: 'config.js',
                maxLength: maxLength,
                on: {
                paste: function (e) {
                    e.data.text = $.trim(FD.Convert.toText(e.data.text));
                }
            },
                width: 420
            });
        },

        /**
        * Setup CKEditor for Summary description
        * 
        * @method setupSummaryEditor
        */
        setupSummaryEditor: function (elementId, maxLength) {
            CKEDITOR.replace(elementId,
            {
                toolbar: [[]],
                height: 80,
                maxLength: maxLength,
                toolbarCanCollapse: false,
                on:
                {
                    instanceReady: function (e) {
                        FD.Classifieds.CKEditor.onInstanceReady(e);
                        // Output paragraphs as <p>Text</p>.
                        this.dataProcessor.writer.setRules('p',
                            {
                                indent: false,
                                breakBeforeOpen: false,
                                breakAfterOpen: false,
                                breakBeforeClose: false,
                                breakAfterClose: false
                            });
                    },
                    key: function (e) {
                        if (e.data.keyCode == 13) e.cancel();
                        //setTimeout(function () { updateCharactersRemaining(elementId) }, 0);
                    },
                    dataReady: function (e) {
                        //setTimeout(function () { updateCharactersRemaining(elementId) }, 0);

                    },
                    paste: function (e) {
                        e.data.text = $.trim(FD.Convert.toText(e.data.text));
                        //setTimeout(function () { updateCharactersRemaining(elementId) }, 0);
                    }
                },
                width: 420
            });
        },

        /**
        * Update CKEditors
        * 
        * @method updateEditors
        */
        updateEditors: function() {
            $(".editor.ckeditor textarea").each(function () {
                var id = $(this).attr("id");
                CKEDITOR.instances[id].updateElement();
            });
        },
        initJobCategories: function () {
            var
                category = $("[name$='ClassificationCategory']"),
                subsector = $("[name$='Subsector']");

            var uri = "/api/JobService/";

            var jsonP = "";

            category.changeLoadGet(uri + "GetSubsectors", subsector, jsonP, function () {
                return { parentCategory: $(this).val(), json: true };
            });
        },
    };
})(jQuery);

var initCartToggle = function () {
    $(".cN-cartSummary .cartToggle").cartToggle();
};

$(document).ready(function() {
    initCartToggle();
});


$('body').on('click', '.upsellPanel .button.remove', function () {
    $this = $(this);
    $upsellPanel = $this.closest('.upsellPanel');
    $this.attr('disabled', 'disabled');
    if (CAP.common.PlaceAd.removeProduct($upsellPanel.data('key'))) {
        $('.reloadable').reloadPanel(initCartToggle); // reload all panels, really just the shopping cart
    } else {
        alert('Failed to remove product');
    }
    $this.prop("disabled", false);
});

$('body').on('click', '.upsellPanel .button.upgrade', function () {
    $this = $(this);
    $upsellPanel = $this.closest('.upsellPanel');
    $this.attr('disabled', 'disabled');
    if (CAP.common.PlaceAd.addProduct($upsellPanel.data('key'), $upsellPanel.data('active-children-key'))) {
        $('.reloadable').reloadPanel(initCartToggle); // reload all panels, really just the shopping cart
    } else {
        alert('Failed to add product');
    }
    $this.prop("disabled", false);
});

$('body').on('click','#saveAd, #saveAndExit, #adminSave', function () { 
    CAP.common.PlaceAd.updateEditors();   
});

$('body').on('mousedown', '#savePreview', function () { 
    CAP.common.PlaceAd.updateEditors(); 
});




$(document).ready(function(){
    
    $.getJSON("/Scripts/CAP/classifieds/vehicle/VehicleMaker.js", null)
            .done(function( json ) {
                console.log( json );
                window.Make = json.maker;
                var makeSelectBox = $('#CarMakeContainer select');
                $.each(window.Make, function(i, value) {
                    makeSelectBox.append($('<option>').attr('value', value).text(value));
                });
                var selectedMake = $('#CarMakeContainer input[type="hidden"]').val();
                makeSelectBox.val(selectedMake);
            })
            .fail(function( jqxhr, textStatus, error ) {
            var err = textStatus + ", " + error;
            console.log( "Request Failed: " + err );
            });
    
    $.getJSON("/Scripts/CAP/classifieds/vehicle/VehicleModel.js", null)
        .done(function( json ) {
            console.log( json );
            window.MakeModels = json.model;
            var refreshList = function() {
                if (!this.value)
                    return false;
                var selectedIndex = this.selectedIndex - 1;
                //var make = window.MakeModels.find(function(x){return x.Name == selectedValue});
                console.log(selectedIndex);
                var makeModels = window.MakeModels[selectedIndex];
                if (makeModels!= null) {
                    var modelSelectBox = $('#CarModelContainer select');
                    modelSelectBox.empty();
                    $.each(makeModels, function(i, value) {
                        modelSelectBox.append($('<option>').attr('value', value).text(value));
                    });
                    var selectedModel = $('#CarModelContainer input[type="hidden"]').val();
                    modelSelectBox.val(selectedModel);
                }
            }
            $('#CarMakeContainer select').change(refreshList);
            $('#CarMakeContainer select').each(refreshList);
        })
        .fail(function( jqxhr, textStatus, error ) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
    });
    $.getJSON("/Scripts/CAP/classifieds/vehicle/VehicleLocation.js", null)
        .done(function( json ) {
            console.log( json );
            var regionSelectBox = $('#StateRegionContainer select');
            var stateSelectBox = $('#StateContainer select');
            window.Locations = json;
            var refreshList = function() {
                var selectedValue = this.value;
                var regions = window.Locations[selectedValue];
                if (regions!= null) {
                    regionSelectBox.empty();
                    $.each(regions, function(i, value) {
                        regionSelectBox.append($('<option>').attr('value', value).text(value));
                    });
                    var selectedRegion = $('#StateRegionContainer input[type="hidden"]').val();
                    regionSelectBox.val(selectedRegion);
                }
            }
            stateSelectBox.change(refreshList);
            stateSelectBox.each(refreshList);
        })
        .fail(function( jqxhr, textStatus, error ) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
    });
    $.getJSON("/Scripts/CAP/classifieds/vehicle/VehicleBodyStyle.js", null)
        .done(function(json) {
            console.log(json);
            window.BodyStyles = json.bodystyles;
            var refreshList = function() {
                var selectedValue = this.value;
                var body = window.BodyStyles.find(function(x){return x.name == selectedValue});
                console.log(body);
                if (body!= null && body.variants != null) {
                    var modelSelectBox = $('#CarBodyVariantContainer select');
                    modelSelectBox.empty();
                    $.each(body.variants, function(i, value) {
                        modelSelectBox.append($('<option>').attr('value', value.name).text(value.name));
                    });
                }
            }
            $('#CarBodyStyleContainer select').change(refreshList);
            $('#CarBodyStyleContainer select').each(refreshList);
        })
        .fail(function( jqxhr, textStatus, error ) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
    });
});

// extend knockout with a binding handler to prevent binding children
// http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html
ko.bindingHandlers.stopBinding = {
    init: function () {
        return { controlsDescendantBindings: true };
    }
};

// Attach to an element, all child form fields will be enabled/disabled as appropriate
ko.bindingHandlers.disableAllInput = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(':input[data-val!="true"], :input[type!="hidden"]', $(element)).not(':radio').each(function (index, elem) {
            $(elem).attr('readonly', value);
        });
        $(':input[data-val="true"], :input[type="hidden"]', $(element)).not(':radio').each(function (index, elem) {
            $(elem).attr('disabled', value);
        });
        // treat radio buttons different... data-val only appears on the first instance
        var radios = $(':radio', $(element));
        var i = 0; // set upper limit of 500 iterations to prevent infinite loop
        while (radios.length > 0 && i < 500) {
            var radio_name = $(radios[0]).attr('name');

            var tmp_array = [];
            radios.each(function (index, elem) {
                if ($(elem).attr('name') === radio_name) {
                    tmp_array.push(elem);
                }
            });
            var radios_with_same_name = $($.makeArray(tmp_array));

            // determine if "data-val='true'" appears on any of the radios
            var is_data_val_true = false;
            radios_with_same_name.each(function (index, elem) {
                if ($(elem).data('val') === true) {
                    is_data_val_true = true;
                }
            });

            // change accordingly
            if (is_data_val_true) {
                radios_with_same_name.each(function (index, elem) {
                    $(elem).attr('disabled', value);
                });
            }
            else {
                radios_with_same_name.each(function (index, elem) {
                    $(elem).attr('readonly', value);
                });
            }

            // reduce set to proces
            radios = radios.not(radios_with_same_name);
            i++;
        }
        return {};
    }
};

// This is the upsell view model
function UpsellViewModel(key, defaultActiveValue, defaultAvailableValue, defaultMandatoryValue) {
    var self = this;
    var key = key;

    self.IsActive = ko.observable(defaultActiveValue);
    self.Active = ko.computed(function () {
        return self.IsActive().toString() == "true";
    });

    self.IsAvailable = ko.observable(defaultAvailableValue);
    self.Available = ko.computed(function () {
        return self.IsAvailable().toString() == "true";
    });

    self.IsMandatory = ko.observable(defaultMandatoryValue);
    self.Mandatory = ko.computed(function () {
        return self.IsMandatory().toString() == "true";
    });

}


function CustomArrayViewModel(element) {
    var self = this;
    self.customArray = ko.observableArray();
    var currentElement = element; 

    self.addItem = function () {
        var featureField = $('#input_tag');
        var feature = featureField.val();

        FD.log('Entered feature: ' + feature);
        if (typeof feature != undefined && feature != '') {
            if (self.customArray.indexOf(feature) < 0) {
                self.clearErrorMessage();
                self.customArray.push(feature);
            } else {
                self.showErrorMessage('"'+ feature + '" already exists');
                return false;
            }
        }

        featureField.val(""); //clear the feature field after adding
    };
    self.removeItem = function (feature) {
        self.customArray.remove(feature);
        self.clearErrorMessage();
    };
    self.showErrorMessage = function (errMsg) {
        self.clearErrorMessage();
        currentElement.append("<span class='field-validation-error' width='200px'>" + errMsg + "</span>");
    };
    self.clearErrorMessage = function () {
        currentElement.find('.field-validation-error').remove();
    };
};

/**
Class to access Summary methods on the server controller

@class CAP.common.Summary 
@constructor
**/

var removedKeys = new Array();
var couponMessage;

namespace('CAP.common').Summary = (function ($) {
    return {

        /**
        * Applies the coupon given the coupon code
        * 
        * @method applyCoupon
        * @param {String} Code of coupon
        * @return {Boolean} Indicating success or failure
        */
        applyCoupon: function (couponCode) {
            var addCouponAction = $("body").attr("data-purchase-addCoupon");

            $.ajax({
                cache: false,
                success: function (data, textStatus, jqXHR) {
                    couponMessage = data;
                },
                error: function (request, status, error) {
                    alert('An error occurred.  Please call us on 1300 067 173.');
                },
                url: addCouponAction + '?flow=' + flowID + '&code=' + couponCode,
                type: 'POST'
            });
            return true;
        },

        /**
        * Remove the coupon from the summary
        * 
        * @method removeCoupon
        * @return {Boolean} Indicating success or failure
        */
        removeCoupon: function () {
            var removeCouponAction = $("body").attr("data-purchase-removeCoupon");

            $.ajax({
                cache: false,
                success: function (data, textStatus, jqXHR) {
                    /*$('div#invoice').html(data);
                    FD.Classifieds.CasualAds.Purchase.adjustEnhancementDisplay();
                    InitDialog();*/
                    couponMessage = data;
                },
                error: function () {
                    alert('An error occurred.  Please call us on 1300 067 173.');
                },
                url: removeCouponAction + '?flow=' + flowID,
                type: 'POST'
            });
            return true;
        },

        /**
        * Reloads the invoice
        * 
        * @method reloadInvoice
        */
        reloadInvoice: function () {
            var url = $('#invoice .reloadable').data("reload-url");
            var couponError = (couponMessage !== undefined && couponMessage != "Success") ? couponMessage : "";

            $('#invoice .reloadable').data("reload-url", url + "&couponError=" + couponError);

            var callback = function () {
                CAP.common.Summary.initHints();
                CAP.common.Summary.adjustEnhancementDisplay();
                CAP.common.Summary.initMultipleDatesDialog();
            };
            $('#invoice .reloadable').reloadPanel(callback);
        },

        /**
        * Initialise hints
        * 
        * @method initHints
        */
        initHints: function () {
            $("div.hint").each(function () { if ($(this).prev('a.hint').length == 0) $(this).popupHint(); });
        },

        /**
        * Adjust the display of enhancements on the invoice
        * 
        * @method adjustEnhancementDisplay
        */
        adjustEnhancementDisplay: function() {
            // assumes that print is first before web
            var firstPrintEnh = $('tr.newspaper + tr.enhancement');
            var lastPrintEnh = $('tr.web').prev('tr.enhancement');
            if (!firstPrintEnh.hasClass('header')) firstPrintEnh.before("<tr class='enhancement th'><th class='description' scope='col' colspan='4'><span class='access'>Newspaper ad</span>Enhancements</th></tr>");
            if (!lastPrintEnh.hasClass("last"))
                lastPrintEnh.addClass("last");

            var firstWebEnh = $('tr.web + tr.enhancement');
            var lastWebEnh = $('tr.enhancement:last');
            if (!firstWebEnh.hasClass('header'))
                firstWebEnh.before("<tr class='enhancement th'><th class='description' scope='col' colspan='4'><span class='access'>Web ad</span>Enhancements</th></tr>");
            if (!lastWebEnh.hasClass("last"))
                lastWebEnh.addClass("last");
        },

        /**
        * Initialise multiple schedules dialog
        * 
        * @method initMultipleDatesDialog
        */
        initMultipleDatesDialog: function() {
            /* FCN multiple date Ad schedule dialog */

            var options = {
                autoOpen: false,
                modal: true,
                resizable: false,
                draggable: false,
                width: 700,
                title: "Your newspaper ad will run on the following schedule"
            };

            var dlFcnAdSchedule = $(".printDate .dialogContent").dialog(options);

            $(".cN-cartSummaryExtended .dialogTrigger").click(function () {
                dlFcnAdSchedule.dialog('open');
            });

        }

    };

})(jQuery);

$("body").on('click', "#ApplyCoupon", function () {
    $this = $(this);
    $this.attr('disabled', 'disabled');
    var couponCode = $('input[name$=CouponCode]').val();
    if (CAP.common.Summary.applyCoupon(couponCode)) {
        CAP.common.Summary.reloadInvoice();
    } else {
        alert('Failed to apply the coupon.');
        $this.removeAttr('disabled');
    }
    return false;
});

$("body").on('keypress', "#CouponCode", function (e) {
    if (e.which == 13) {
        $(this).blur();
        $('#ApplyCoupon').focus().click();
        return false;
    }
});

CAP.common.Summary.initHints();
CAP.common.Summary.adjustEnhancementDisplay();
CAP.common.Summary.initMultipleDatesDialog();;

/**
Class to access manage ad methods on the server controller

@class CAP.common.ManageAd  
@constructor
**/
namespace('CAP.common').ManageAd = (function ($) {
    return {
        initDeleteAdDialog: function (src, evt, returnUrl) {
            var $src = $(src),
                deleteUri = $src.attr('href'),
                orderRef = $src.data('bookingref');

            evt.preventDefault();
            evt.stopPropagation();

            var title = 'Delete your ad?';

            var $confirmDialog = $('<div class="dialog-wrap sml" />').html('<div class="dialog-header"><h2>' + title + '</h2></div><div class="dialog-content"><p>You are about to delete your ad <strong>(Ref No: ' + orderRef + ')</strong>. This means it will be removed permanently. All the changes you have made will be lost and can\'t be retrieved later.</p><p>Are you sure you want to delete your ad <strong>(Ref No: ' + orderRef + ')</strong>?</p></div>');
            $confirmDialog.append('<div class="dialog-footer"><button class="button feedback-trigger delete dialog-close" type="button">Yes, delete my ad</button><!-- UI NOTE: classes feedback-trigger online dialog-close are for demo only - dev to integrate [dialog-close closes the dialog. feedback-trigger online triggers the online feedback - see modal()] --><button class="button alt dialog-close cancel" type="button">No, I\'d like to keep my ad</button></div>');

            $confirmDialog.dialog({
                dialogClass: "custom-dialog",
                autoOpen: true,
                modal: true,
                width: 500
            });

            $confirmDialog.on('click', '.dialog-footer button.feedback-trigger.delete', function (e) {
                $confirmDialog.dialog("close");
                $.post(deleteUri, function (data) {
                    if (returnUrl != null)
                        window.location.replace(returnUrl);
                    else
                        location.reload();
                });
            });

            $confirmDialog.on('click', '.dialog-footer button.dialog-close.cancel', function (e) {
                $confirmDialog.dialog("close");
            });
            
        },
        initExtendAdDialog: function (site) {
            if (site == "domain" || site == "commercialrealestate" || site == "domainbusiness") {
                $('.action a').each(function () {
                    if ($(this).html() == "Extend ad") {
                        $(this).addClass('dialog-trigger');
                    }
                });
            }
        },
        initDomainPlaceAdDialog: function (src, evt, site) {
            var linkObj = src,
                placedAdUri = $(src).attr('href');

            var rootURL = location.protocol + "//" + location.host;

            var webPlaceAdUrl_DOM_Sale = rootURL + "/domain/PlaceAd?sku=domsale&packageCode=dompkg";
            var webPlaceAdUrl_DOM_Rent = rootURL + "/domain/PlaceAd?sku=domrent&packageCode=dompkg";
            var webPlaceAdUrl_DOM_Share = rootURL + "/domain/PlaceAd?sku=domshare&packageCode=dompkg";
            var webPlaceAdUrl_DOM_Business = rootURL + "/domain/PlaceAd?sku=dombusiness&packageCode=dompkg";
            var webPlaceAdUrl_BIZ = rootURL + "/business/PlaceAd?sku=dombusiness&packageCode=dombizpkg&option=sale";
            var webPlaceAdUrl_CRE_Sale = rootURL + "/commercialrealestate/PlaceAd?sku=crelisting&packageCode=crepkg&option=sale";
            var webPlaceAdUrl_CRE_Lease = rootURL + "/commercialrealestate/PlaceAd?sku=crelisting&packageCode=crepkg&option=lease";
            var webPlaceAdUrl_CRE_Business = rootURL + "/commercialrealestate/PlaceAd?sku=crebusiness&packageCode=crebizpkg";

            var agePlaceAdUrl = rootURL + "/PlaceAd/?sku=GCPROPERTY&packageCode=GCKCPKG&pubNoTheme=AGE";
            var smhPlaceAdUrl = rootURL + "/PlaceAd/?sku=GCPROPERTY&packageCode=GCKCPKG&pubNoTheme=SMH";

            evt.preventDefault();
            evt.stopPropagation();

            var title = 'Place an ad';

            $confirmDialog = $('<div class="dialog-wrap sml" />');

            var printFields = '<li style="height: 175px;"><span class="icon paper sml"></span><h3 style="font-size:1.4em;font-weight:bold;width:241px;">Place a newspaper ad</h3>'
                + '<table style="margin-left:20px;"><tr><td height="25px"><input id="ad-print-smh" name="ad-print" value="smh" checked="" type="radio"><label for="ad-print-smh">Sydney Morning Herald</label></td></tr><tr><td height="25px"><input id="ad-print-age" name="ad-print" value="age" type="radio"><label for="ad-print-age">The Age</label></td></tr>'
                + '<tr><td height="24px"></td></tr>'
                + '<tr><td><a id="PlaceNewspaperAdButton" class="button" style="margin-top: 5px;" href="' + rootURL + '/PlaceAd/?sku=GCPROPERTY&packageCode=GCKCPKG&pubNoTheme=SMH">Place ad</a></td></tr></table></li>';

            if (site == "domain"){
                $confirmDialog.html('<div class="dialog-header"><h2>' + title + '</h2></div><div class="dialog-content">.'
                + '<ul id="WorkflowChoice" class="workflow-choice cf" data-url-sale="' + webPlaceAdUrl_DOM_Sale + '" data-url-rent="' + webPlaceAdUrl_DOM_Rent + '" data-url-share="' + webPlaceAdUrl_DOM_Share + '" data-url-business="' + webPlaceAdUrl_DOM_Business + '" data-url-smh="' + smhPlaceAdUrl + '" data-url-age="' + agePlaceAdUrl + '" data-price-age="$27.19" data-price-smh="$46.64" data-price-share="$30.25" data-price-rent="$193.60" data-price-sale="$275.00"><li style="height: 175px;"><span class="icon web sml"></span><h3 style="font-size:1.4em; font-weight:bold;">Place an online ad</h3>'
                + '<table style="margin-left:20px;width:155px;"><tr><td height="25px"><input id="ad-online-sell" name="ad-online" value="sale" checked="" type="radio"><label for="ad-online-sell">Selling a property</label></td></tr>'
                + '<tr><td height="25px"><input id="ad-online-rent" name="ad-online" value="rent" type="radio"><label for="ad-online-rent">Renting a property</label></td></tr>'
                + '<tr><td height="25px"><input id="ad-online-share" name="ad-online" value="share" type="radio"><label for="ad-online-share">Looking for a flatmate</label></td></tr>'
                + '<tr><td><a id="PlaceOnlineAdButton" href="' + webPlaceAdUrl_DOM_Sale + '" class="button" style="margin-top: 5px;">Place ad</a></td></tr></table></li>'
                + printFields
                + '</ul></div>');
            }
            else if (site == "domainbusiness") {
                $confirmDialog.html('<div class="dialog-header"><h2>' + title + '</h2></div><div class="dialog-content">.'
                    + '<ul id="WorkflowChoice" class="workflow-choice cf" data-url-sale="' + webPlaceAdUrl_BIZ + '" ' +
                    'data-url-smh="' + smhPlaceAdUrl + '" ' +
                    'data-url-age="' + agePlaceAdUrl + '" ' +
                    'data-price-age="$42.68" data-price-smh="$51.44" data-price-sale="$181.50"><li style="height: 175px;"><span class="icon web sml"></span><h3 style="font-size:1.4em; font-weight:bold;">Place an online ad</h3>'
                    + '<table style="margin-left:20px;width:155px;"><tr><td height="25px"><input id="ad-online-sell" name="ad-online" value="sale" checked="" type="radio"><label for="ad-online-sell">Selling a business</label></td></tr>'
                    + '<tr><td height="51px"></td></tr>'
                    + '<tr><td><a id="PlaceOnlineAdButton" href="' + webPlaceAdUrl_BIZ + '" class="button" style="margin-top: 5px;">Place ad</a></td></tr><tr><td><p>from <strong id="PlaceOnlineAdPrice">$181.50</strong> (incl. GST)</p></td></tr></table></li>'
                    + printFields
                    + '</ul></div>');
            }
            else {
                $confirmDialog.html('<div class="dialog-header"><h2>' + title + '</h2></div><div class="dialog-content">.'
                + '<ul id="WorkflowChoice" class="workflow-choice cf" data-url-sale="' + webPlaceAdUrl_CRE_Sale + '" data-url-rent="' + webPlaceAdUrl_CRE_Lease + '" data-url-business="' + webPlaceAdUrl_CRE_Business + '" data-url-share="" data-url-smh="' + smhPlaceAdUrl + '" data-url-age="' + agePlaceAdUrl + '" data-price-age="$42.68" data-price-smh="$51.44" data-price-share="$30.25" data-price-rent="$330.00" data-price-sale="$330.00"><li style="height: 175px;"><span class="icon web sml"></span><h3 style="font-size:1.4em; font-weight:bold;">Place an online ad</h3>'
                + '<table style="margin-left:20px;width:155px;"><tr><td height="25px"><input id="ad-online-sell" name="ad-online" value="sale" checked="" type="radio"><label for="ad-online-sell">Selling a property</label></td></tr>'
                + '<tr><td height="25px"><input id="ad-online-rent" name="ad-online" value="rent" type="radio"><label for="ad-online-rent">Leasing a property</label></td></tr>'
                + '<tr><td height="25px"><input id="ad-online-business" name="ad-online" value="business" type="radio"><label for="ad-online-business">Selling a business</label></td></tr>'
                + '<tr><td height="15px"></td></tr>'
                + '<tr><td><a id="PlaceOnlineAdButton" href="' + webPlaceAdUrl_CRE_Sale + '" class="button" style="margin-top: 5px;">Place ad</a></td></tr><tr><td><p>from <strong id="PlaceOnlineAdPrice">$330.00</strong> (incl. GST)</p></td></tr></table></li>'
                + printFields
                + '</ul></div>');
            }
            $confirmDialog.append('<div class="dialog-footer"><button class="btn-faux-link dialog-close" type="button">Cancel</button></div>');
                
            $confirmDialog.dialog({
                dialogClass: "custom-dialog",
                autoOpen: true,
                modal: true,
                width: 570
            });

            // clear dialog content on close so that it reinitialises correctly when reloaded.
            $confirmDialog.on('dialogclose', function (e) {
                $confirmDialog.html('');
            });

            $confirmDialog.on('click', '.dialog-footer button.dialog-close', function (e) {
                $confirmDialog.dialog("close");
            });

        },
        AnimateFeedback: function () {
            $('.cN-headerMessage.message-confirm').each(function () {
                $(this).addClass('disappear').animateFeedback({ trigger: "modal" });
            });
        },
        changeRerunScheduleRunDays: function (element) {
            var checkbox = $(element).find('input');

            var selectedCouponId = checkbox.val();

            $("#extend-ad-schedule input[name='offer']").each(function () {
                if ($(this).val() != selectedCouponId) {
                    $(this).closest(".selector").removeClass('selected');
                    $(this).next(".icon").removeClass('icon-approve');
                    $(this).prop("checked", "");
                }
                else {
                    $(this).closest(".selector").addClass('selected');
                    $(this).next(".icon").addClass('icon-approve');
                    $(this).prop("checked", "checked");
                }
            });
        },
        initRemoveAdDialog: function (src, evt, site) {

            var $src = $(src),
                removeUri = $src.attr('href'),
                orderRef = $src.data('bookingref');

            if (typeof orderref == 'undefined') {
                $(src).closest('.status').data('booking-ref');
            }
            evt.preventDefault();
            evt.stopPropagation();

            var title = 'Take your ad offline?';

            var $confirmDialog = $('<div class="dialog-wrap sml" />').html('<div class="dialog-header"><h2>' + title + '</h2></div><div class="dialog-content"><p>You are about to take your ad <strong>(Ref No: ' + orderRef + ')</strong> \'offline\'. This means your ad will no longer appear on ' + site + '.com.au.</p><p>Are you sure you want to take your ad <strong>(Ref No: ' + orderRef + ')</strong> \'offline\'?</p></div>');
            $confirmDialog.append('<div class="dialog-footer"><button class="button feedback-trigger remove dialog-close" type="button">Yes, take my ad offline</button><!-- UI NOTE: classes feedback-trigger online dialog-close are for demo only - dev to integrate [dialog-close closes the dialog. feedback-trigger online triggers the online feedback - see modal()] --><button class="button alt dialog-close cancel" type="button">Cancel</button></div>');

            $confirmDialog.dialog({
                dialogClass: "custom-dialog",
                autoOpen: true,
                modal: true,
                width: 500
            });

            $confirmDialog.on('click', '.dialog-footer button.feedback-trigger.remove', function (e) {
                $confirmDialog.dialog("close");
                $.post(removeUri).done(function (data) {
                    location.reload();
                });
            });


            $confirmDialog.on('click', '.dialog-footer button.dialog-close.cancel', function (e) {
                $confirmDialog.dialog("close");
            });
        }
    }
})(jQuery);

$(function () {
    var site = $('body').data('site');
    if (typeof site == 'undefined') {
        if ($('body').hasClass('mycareer')) {
            site = "mycareer";
        }

        if ($('body').hasClass('jobs')) {
            site = "jobs";
        }
    }

    if (site !== "classifieds") {
        // Omit dialog behaviour for GC. The "remove" action takes user to refund confirmation screen.

        $('body').on('click', '.tblMyAds .action .icon-remove', function (evt) {
            CAP.common.ManageAd.initDeleteAdDialog(this, evt, null);
        });

        $('body').on('click', '#adminToolbar .options .delete a', function (evt) {
            CAP.common.ManageAd.initDeleteAdDialog(this, evt, $("body").data("manageads-index"));
        });
    }

    // specific dialog for Domain, CRE and DomainBusiness only
    if (site == "domain" || site == "commercialrealestate" || site == "domainbusiness") {
        $('body').on('click', '.sticky-wrapper .button', function (evt) {
            CAP.common.ManageAd.initDomainPlaceAdDialog(this, evt, site);
        });

        $('body').on('click', '.tabPanel .button.placead', function (evt) {
            CAP.common.ManageAd.initDomainPlaceAdDialog(this, evt, site);
        });
    }

    if ($('.manage-ads').length > 0) {
        //ensure only manage ads have the animated feedback
        CAP.common.ManageAd.AnimateFeedback();
    }
    CAP.common.ManageAd.initExtendAdDialog(site);

    $(".manage-ads a[data-action='repost']").click(function (evt) {
        evt.preventDefault();
        $.post($(this).attr("href"))
            .always(function () {
                location.reload();
            });
    });

    $('body').on('click', '.tblMyAds .action .icon-offline', function (evt) {
        CAP.common.ManageAd.initRemoveAdDialog(this, evt, site);
    });

    $('body').on('click', '#adminToolbar .options .remove a', function (evt) {
        CAP.common.ManageAd.initRemoveAdDialog(this, evt, site);
    });

});

$('body').on('click', '#extend-ad-schedule .offer-choice .selector', function (event) {
    CAP.common.ManageAd.changeRerunScheduleRunDays($(this));
});

$('body').on('click', '.tblMyAds .extend.button', function (event) {
    if ($("#extend-ad-schedule .selector.selected").length == 0) {
        //none of the rerun schedule has been selected
        event.preventDefault();
        event.stopPropagation();

        $('.dialog-content').append("Please select at least one schedule to extend your ad.");
    }
});


;
(function ($) {
    FD.namespace('FD.CasualAds.GC.PlaceAd');

    function fd_placead_submitPrintFormForPreview() {
        if ($(".formPrintAd").valid()) {
            var fld = $("<input />").attr("type", "hidden").attr("name", "updatePreviewAndQuoteOnly").val("true");
            $(".formPrintAd").append(fld);
            FD.CasualAds.AdDetails.Common.ShowLoadingMessage("Updating Preview. Please Wait...");
            $(".formPrintAd").submit();
        } else {
            alert("Cannot update print preview and pricing quote until all form errors are resolved.");
        }
    }

    function fd_placead_autoSubmitPrintForm() {
        if ($(".formPrintAd").valid()) {
            var fld = $("<input />").attr("type", "hidden").attr("name", "autoSubmitOnly").val("true");
            $(".formPrintAd").append(fld);
            FD.CasualAds.AdDetails.Common.ShowLoadingMessage("Loading. Please Wait...");
            $(".formPrintAd").submit();
        } else {
            alert("Cannot update the chosen deal until all form errors are resolved.");
        }
    }

    $(document).on("change", ".updatepreviewonchange", function () {
        fd_placead_submitPrintFormForPreview();
    });

    $(document).on("click", "#defaultDealSelector-remover", function () {
        fd_placead_autoSubmitPrintForm();
    });

    $(document).on("click", "#updatePreviewAndQuoteOnly", function () {
        fd_placead_submitPrintFormForPreview();
    });

    // the .datepicker is used for templated DATE fields
    $(document).ready(function () {
        $(".datePicker").attr('readonly', 'true').datepicker({
            yearRange: 'c-110:c+10',
            changeYear: true,
            dateFormat: "d MM yy",
            showOn: "both",
            showButtonPanel: true
        });
    }
    );


    // Do special case stuff to the date picker for dates
    FD.namespace('FD.CasualAds.GC.PrintAdSchedule');
    FD.CasualAds.GC.PrintAdSchedule.selectionStartedHandler = function (evt, clickedSelector) {
        var $container = $(this);
        var settings = {
            pattern: $container.data("date-pattern"),
            range: $container.data("date-range"),
            remaining: $container.data("remaining-choices"),
            maximum: $container.data("max-choices"),
            minimum: $container.data("min-choices")
        }
        var $clicked = $(clickedSelector);

        if ($clicked && settings.pattern == "CONSECUTIVE") {
            // deselect all, start chained selection at the clicked one
            // must select the "min_choices" in a row:
            // 1. Deselect EVERYTHING
            $(".selector input:checked", $container).prop("checked", false);
            // 2. Check the one they clicked.
            $("input:checkbox", $clicked).prop("checked", true);
            var $selectedCheckbox = $("input:checkbox", $clicked);
            $selectedCheckbox.prop("checked", true);

            // 3. try and select min_choices items starting at the clicked one
            var toCheck = settings.minimum - 1;
            var $curSelector = $clicked;
            while (toCheck > 0) {
                $curSelector = $curSelector.next(".selector");
                if ($curSelector.length == 0) {
                    break;
                }
                $curSelector.find("input").prop("checked", true);
                toCheck--;
            }
            // 4. Start again at the clicked one, select backwards.
            $curSelector = $clicked;
            while (toCheck > 0) {
                $curSelector = $curSelector.prev(".selector");
                if ($curSelector.length == 0) {
                    break;
                }
                $curSelector.find("input").prop("checked", true);
                toCheck--;
            }

            return;
        }

    };

    $(".ffx-radio-buttons.runday-selection").on("selectionstarted", FD.CasualAds.GC.PrintAdSchedule.selectionStartedHandler);

    // Post selection changed, disable options that are outside the valid range
    FD.CasualAds.GC.PrintAdSchedule.selectionChangedHandler = function () {
        var $container = $(this);
        var settings = {
            pattern: $container.data("date-pattern"),
            range: $container.data("date-range"),
            remaining: $container.data("remaining-choices"),
            maximum: $container.data("max-choices"),
            minimum: $container.data("min-choices")
        }

        // if chained, don't disable anything
        if (settings.pattern == "CONSECUTIVE" || (settings.range == 0 && settings.remaining > 0)) {
            // make sure all options are active:
            $(".selector", $(this)).toggleClass("disabled", false);
            return;
        }




        var firstChosenIndex = 1000;
        var lastChosenIndex = -1;
        $(".selector.selected", $(this)).each(function (objIndex, eachObj) {
            var thisItemIndex = $(eachObj).data("dayindex");
            if (thisItemIndex < firstChosenIndex) { firstChosenIndex = thisItemIndex; }
            if (thisItemIndex > lastChosenIndex) { lastChosenIndex = thisItemIndex; }
        });




        // limit active to correct number of days either side of the first and last selection...
        if (settings.range > 0) {
            // calculate the minimum and maximum index, using range
            var minSelection = lastChosenIndex - (settings.range - 1);
            var maxSelection = firstChosenIndex + (settings.range - 1);
            /*var minSelection = lastSelection - (settings.range - 1);
            var maxSelection = firstSelection + (settings.range - 1);*/

            $(".selector", $(this)).each(function (objIndex, eachObj) {
                var thisItemIndex = $(eachObj).data("dayindex");
                $(eachObj).toggleClass("disabled", lastChosenIndex > -1 && (thisItemIndex < minSelection || thisItemIndex > maxSelection));
            });

        }

        // deactivate all remaining choices if no more choices available
        if (settings.remaining == 0) {
            $(".selector", $(this)).not(".selected").toggleClass("disabled", true);
        }

        // reactivate all selected items so they can always be deselected
        $(".selector.selected", $(this)).toggleClass("disabled", false);
    };
    $(".ffx-radio-buttons.runday-selection").on("selectionchanged", FD.CasualAds.GC.PrintAdSchedule.selectionChangedHandler);

    FD.CasualAds.GC.PrintAdSchedule.printWeekChooserRunDate = function (date, options) {
        var self = this,
            defaults = {
                is_readonly: false,
                is_status_show: false,
                is_cancelled: false,
                is_published: false
            },
            opt = $.extend({}, defaults, options, { date: date });

        self.date = opt.date;  // This is used to communicate with the server
        self.dateUTCKind = self.date.setUTCKind(); // This is used for filtering. As fromDate and toDate is in setUTCKind()
        self.is_readonly = opt.is_readonly;
        self.is_status_shown = opt.is_status_shown;
        self.is_cancelled = opt.is_cancelled;
        self.is_published = opt.is_published;
        self.get_icon_css = function () {
            var result = "";
            if (self.is_status_shown) {
                result += " icon";
                if (self.is_cancelled) {
                    result += " icon-cross";
                }
                else if (self.is_published) {
                    result += " icon-approve";
                }
            }
            return result;
        };
        self.get_css = function () {
            var result = "calDateStatus indicator-icon selector selected";
            if ((self.is_status_shown && (self.is_cancelled || self.is_published))
                || (!self.is_status_shown && self.is_readonly)) {
                result += " disabled";
            }
            return result;
        };
    };
    FD.CasualAds.GC.PrintAdSchedule.printWeekChooser = function (element, options) {

        var e = element,
            $e = $(e),
            prefix = "printweekchooser",
            chosen_publishing_days = $e.data(prefix + "-chosen-publishing-days"),
            cancelled_days = $e.data(prefix + "-cancelled-days"),
            cancelled_days_millis = [],
            // publishing_detail_by_pubs is in the format of [{Item1 = pubCode, Item2 = pubName, Item3 = PublishDate}]
            publishing_detail_by_pubs = $e.data(prefix + "-publishing-detail-by-pubs"),
            publishing_detail_by_dates = $e.data(prefix + "-publishing-detail-by-dates"),
            is_readonly = $e.data(prefix + "-is-readonly"),
            is_status_shown = $e.data(prefix + "-is-status-shown"),
            fromDate,
            toDate,
            millisecondsPerDay = 86400000,
            normalizedNow = new Date().setUTCKind().getTime(),
            filtered_publishing_detail_by_pubs = ko.observableArray(),
            publishing_detail_by_dates_map = [];

        // nomalize the publishing_detail_by_dates for calendar display tooltips and set the minDateToShow / maxDateToShow
        var minDateToShow = null;
        var maxDateToShow = null;
        $.each(publishing_detail_by_dates, function (index, value) {
            var theDate = new Date(value.Item1);
            publishing_detail_by_dates_map[theDate.setUTCKind().getTime()] = publishing_detail_by_dates[index];

            if (minDateToShow == null && maxDateToShow == null) {
                minDateToShow = theDate;
                maxDateToShow = theDate;
            }
            else if (minDateToShow > theDate) {
                minDateToShow = theDate;
            }
            else if (maxDateToShow < theDate) {
                maxDateToShow = theDate;
            }
        });

        if (minDateToShow != null && maxDateToShow != null) {
            minDateToShow = minDateToShow.setLocalKind();
            maxDateToShow = maxDateToShow.setLocalKind();
        }

        // initialize cancelled_days_millis
        $.each(cancelled_days, function (index, value) {
            var timeArray = [];
            $.each(value, function (index, value) {
                timeArray[index] = new Date(value).getTime();
            });
            cancelled_days_millis[index] = timeArray;
        });

        // translate rundays
        for (var i = 0; i < publishing_detail_by_pubs.length; i++) {
            var pubDetails = publishing_detail_by_pubs[i];
            for (var j = 0; j < pubDetails.Item3.length; j++) {
                var date = new Date(pubDetails.Item3[j]);
                var is_cancelled = ($.inArray(date.getTime(), cancelled_days_millis[pubDetails.Item1]) >= 0);
                pubDetails.Item3[j] = new FD.CasualAds.GC.PrintAdSchedule.printWeekChooserRunDate(
                    date,
                    {
                        is_readonly: is_readonly,
                        is_status_shown: is_status_shown,
                        is_cancelled: is_cancelled,
                        is_published: (!is_cancelled && date.getTime() < normalizedNow)
                    });
            }
        }

        var viewmodel = {
            "is_readonly": is_readonly,
            "publishing_detail_by_pubs": filtered_publishing_detail_by_pubs
        };

        function updateFromToDates() {
            var selectedDate = $e.find("input[name='rundayFrom']").datepicker("getDate");
            if (selectedDate === null
                || typeof (selectedDate.setUTCKind) !== "function") {
                fromDate = null;
            }
            else {
                fromDate = selectedDate.setUTCKind();
            }

            var selectedDate = $e.find("input[name='rundayTo']").datepicker("getDate");
            if (selectedDate === null
                || typeof (selectedDate.setUTCKind) !== "function") {
                toDate = null;
            }
            else {
                toDate = selectedDate.setUTCKind();
            }
        }

        function onFromToDatesChanged(e) {

            updateFromToDates();
            toDate = adjustToDate(fromDate, toDate);
            $e.find("input[name='rundayTo']").val(formatDate(toDate));
            updateViewModel(fromDate, toDate);
        }

        function updateViewModel(fromDate, toDate) {
            var result = FilterPublishing_detail_by_pubs(fromDate, toDate);

            // Get the internal array
            var internalArray = filtered_publishing_detail_by_pubs();
            // Empty the internal array
            internalArray.length = 0;
            // Push all elements into the internalArray
            ko.utils.arrayPushAll(internalArray, result);
            // Notify the UI update
            filtered_publishing_detail_by_pubs.valueHasMutated();
        }

        function formatDate(srcDate) {
            if (srcDate == null)
                return "";

            var datePart = srcDate.getDate();
            var monthPart = srcDate.getMonth() + 1;
            var yearPart = srcDate.getFullYear();

            if (datePart < 10)
                datePart = "0" + datePart;

            if (monthPart < 10)
                monthPart = "0" + monthPart;

            return datePart + "/" + monthPart + "/" + yearPart;
        }

        function adjustToDate(fromDate, toDate) {
            // If fromDate is null, no adjustment
            if (fromDate == null) {
                return toDate;
            }

            // If toDate is null or fromDate is later than toDate, set toDate to be the same day as the fromDate                
            if (toDate == null || fromDate.getTime() > toDate.getTime()) {
                toDate = fromDate;
                return toDate;
            }

            // No adjustment, just retun the toDate
            return toDate;
        }

        function FilterPublishing_detail_by_pubs(fromDate, toDate) {
            var result = [];
            var temp_publishing_detail_by_pubs;
            // Clone a new copy for modification
            temp_publishing_detail_by_pubs = clone_publishing_detail_by_pubs(publishing_detail_by_pubs);

            for (var index in temp_publishing_detail_by_pubs) {
                var pubDeatils = {};
                pubDeatils.Item1 = temp_publishing_detail_by_pubs[index].Item1; // This is the pubCode
                pubDeatils.Item2 = [temp_publishing_detail_by_pubs[index].Item2]; // This is [pubName]. To be merged next
                if (fromDate == null && toDate == null) {
                    // nothing to filter, return the entire Item3
                    pubDeatils.Item3 = temp_publishing_detail_by_pubs[index].Item3;
                }
                else if (fromDate != null && toDate != null) {
                    pubDeatils.Item3 = $.grep(temp_publishing_detail_by_pubs[index].Item3, function (runDate) {
                        return runDate.dateUTCKind >= fromDate && runDate.dateUTCKind <= toDate
                    });
                }
                else if (fromDate != null) {
                    pubDeatils.Item3 = $.grep(temp_publishing_detail_by_pubs[index].Item3, function (runDate) {
                        return runDate.dateUTCKind >= fromDate
                    });
                }
                else if (toDate != null) {
                    pubDeatils.Item3 = $.grep(temp_publishing_detail_by_pubs[index].Item3, function (runDate) {
                        return runDate.dateUTCKind <= toDate
                    });
                }
                var stringifyDates = "";
                $.each(pubDeatils.Item3, function (index, value) {
                    stringifyDates += "|" + value.date.getTime();
                });
                pubDeatils.StringnifyDates = stringifyDates;
                result[index] = pubDeatils;
            }

            result.sort(function (pubDetail1, pubDetail2) {
                if (pubDetail1.StringnifyDates == pubDetail2.StringnifyDates) {
                    return 0;
                }
                else if (pubDetail1.StringnifyDates > pubDetail2.StringnifyDates) {
                    return 1;
                }
                else {
                    return -1;
                }
            });

            // Merging pubs with the same publication dates
            for (var i = 0; i < result.length - 1; i++) {
                // Compare their publishing dates
                if (result[i].StringnifyDates == result[i + 1].StringnifyDates) {
                    // Merge the two
                    result[i].Item1 = result[i].Item1 + "," + result[i + 1].Item1; // The pubCode
                    result[i].Item2 = result[i].Item2.concat(result[i + 1].Item2); // The pub name array
                    // Remove the next item
                    result.splice(i + 1, 1);
                    // Reset the index to the current so that can check the one after
                    i--;
                }
            }
            return result;
        }

        // deep clone of a given publishing_detail_by_pubs
        function clone_publishing_detail_by_pubs(publishing_detail_by_pubs) {
            var result = [];
            for (var index in publishing_detail_by_pubs) {
                var pubDetail = {};
                pubDetail.Item1 = publishing_detail_by_pubs[index].Item1;
                pubDetail.Item2 = publishing_detail_by_pubs[index].Item2;
                pubDetail.Item3 = [];
                for (var i in publishing_detail_by_pubs[index].Item3) {
                    pubDetail.Item3.push(publishing_detail_by_pubs[index].Item3[i]);
                }
                result.push(pubDetail);
            }
            return result;
        }

        function beforeShowDay(date) {
            var normalizedDate = date.setUTCKind(),
                normalizedMillis = normalizedDate.getTime(),
                cssClass = "",
                toolTip = "";

            if (publishing_detail_by_dates_map[normalizedMillis] != null) {
                var item = publishing_detail_by_dates_map[normalizedMillis];
                cssClass += " publishingDay";
                toolTip = item.Item2.join(", ") + " will be published on this day";
            }
            return [true, cssClass, toolTip];
        };

        /*
         * Initialize controls
         */

        $e.find(".fromDate").datepicker({
            dateFormat: "dd/mm/yy",
            numberOfMonths: 3,
            showOn: "both",
            showButtonPanel: true,
            closeText: "close",
            onClose: function (selectedDate) {
                $e.find(".toDate").datepicker("option", "minDate", selectedDate);
            },
            beforeShowDay: beforeShowDay
        });
        $e.find(".toDate").datepicker({
            dateFormat: "dd/mm/yy",
            numberOfMonths: 3,
            showOn: "both",
            showButtonPanel: true,
            closeText: "close",
            onClose: function (selectedDate) {
                $e.find(".fromDate").datepicker("option", "maxDate", selectedDate);
            },
            beforeShowDay: beforeShowDay
        });
        if (minDateToShow !== null) {
            $e.find(".fromDate").datepicker("option", "minDate", minDateToShow);
            $e.find(".toDate").datepicker("option", "minDate", minDateToShow);
        }
        if (maxDateToShow !== null) {
            $e.find(".fromDate").datepicker("option", "maxDate", maxDateToShow);
            $e.find(".toDate").datepicker("option", "maxDate", maxDateToShow);
        }

        is_readonly = ($e.find("input[name='rundayFrom']").add("input[name='rundayTo']").length === 0);

        ko.applyBindings(viewmodel, element);

        if (!is_readonly) {
            $e.find("input[name='rundayFrom']").on("change", onFromToDatesChanged);
            $e.find("input[name='rundayTo']").on("change", onFromToDatesChanged);
            onFromToDatesChanged();
        }
        else {
            // passing in null dates to select all publication details.
            updateViewModel(null, null);
        }
    };

    $.fn.printWeekChooser = function (options) {
        this.each(function () {
            if (!$(this).data("printWeekChooser")) {
                FD.CasualAds.GC.PrintAdSchedule.printWeekChooser(this, options);
                $(this).data("printWeekChooser", true);
            }
        });
    };

    // Ken's work start
    FD.namespace('FD.CasualAds.GC.PrintAd');
    FD.CasualAds.GC.PrintAd.publicationChooser = function (element, options) {

        // Class to represent a publication
        function Publication(Code, Name, DisplayTab, ImagePath, ViewModel) {
            var self = this;
            self.Code = Code;
            self.Name = Name;
            self.DisplayTab = DisplayTab;
            self.ImagePath = ImagePath;
            self.icon_css = ko.computed(function () {
                if (ViewModel.selectedPublications.indexOf(self) >= 0)
                    return "icon icon-approve";
                else
                    return "icon";
            });
        }

        // Class to represent a covid19ImpactedPublication
        function covid19ImpactedPublication(Code, Name, DisplayTab, ImagePath, ViewModel, covid19ImpactedGroup) {
            var self = this;
            self.Code = Code;
            self.Name = Name;
            self.DisplayTab = DisplayTab;
            self.ImagePath = ImagePath;
            self.icon_css = ko.computed(function () {
                if (ViewModel.selectedPublications.indexOf(self) >= 0)
                    return "icon icon-approve";
                else
                    return "icon";
            });
            self.covid19ImpactedGroup = covid19ImpactedGroup;
        }

        function PublicationsViewModel() {
            var self = this;
            self.currentDisplayTab = ko.observable("Sydney");
            self.selectedPublications = new ko.observableArray();

            self.selectedPubCodes = selectedPubCodes.split('-');

            self.CyberPublications = new ko.observableArray();
            for (var i = 0; i < CyberPublications.length; i++) {
                var extension = "-landscape.png";
                if (CyberPublications[i].Code == "CT")
                    extension = ".png";

                var pub = new Publication(
                    CyberPublications[i].Code,
                    CyberPublications[i].Name,
                    CyberPublications[i].DisplayTab,
                    "/Content/Main/Img/Classifieds/icons/icon-" + CyberPublications[i].Code + extension,
                    self);
                self.CyberPublications.push(pub);
            }

            self.PongrassPublications = new ko.observableArray();
            var Covid19ImpactedPubCodesG1 = ["HP", "MG", "ME", "PE", "NWM", "BOR", "NE", "GM", "CBC"];
            var Covid19ImpactedPubCodesG2 = ["HC", "AWO-KII", "AVO", "BLH", "BO", "TG", "CQA", "CBO", "COL", "CCH", "CR", "DBK", "ERC", "EEE", "EPT", "GYA", "CHM", "WG", "ADV", "JSC", "KII", "MBC", "GN", "NVI", "NN", "NS", "ST", "CNA", "NO", "OTC", "SC", "LML", "RIL", "WN", "WT", "WCC", "WC", "YP", "BCS", "NP", "BY", "MM", "HV", "HG", "CH", "CA", "IM", "MNW", "NA"];

            for (var i = 0; i < PongrassPublications.length; i++) {
                var extension = PongrassPublications[i].Code == "AWO-KII" ? ".gif" : ".png";

                /* The codes below this comment needs to be removed when the covid-19 period is over*/
                var covid19ImpactedGroup = 0;

                if (Covid19ImpactedPubCodesG1.indexOf(PongrassPublications[i].Code) >= 0) {
                    covid19ImpactedGroup = 1;
                }

                if (Covid19ImpactedPubCodesG2.indexOf(PongrassPublications[i].Code) >= 0) {
                    covid19ImpactedGroup = 2;
                }

                var pub = new covid19ImpactedPublication(
                    PongrassPublications[i].Code,
                    PongrassPublications[i].Name,
                    PongrassPublications[i].DisplayTab,
                    "/Content/Main/Img/Classifieds/icons/icon-" + PongrassPublications[i].Code + extension,
                    self,
                    covid19ImpactedGroup
                );
                /* The part above this comment needs to be removed when the covid-19 period is over*/


                /* This part needs to be un-commented when the covid-19 period is over
                 * var pub = new Publication(
                    PongrassPublications[i].Code,
                    PongrassPublications[i].Name,
                    PongrassPublications[i].DisplayTab,
                    "/Content/Main/Img/Classifieds/icons/icon-" + PongrassPublications[i].Code + extension,
                    self);
                */
                self.PongrassPublications.push(pub);
            }

            self.displayTabs = displayTabs;

            self.selectDisplayTab = function () {
                self.currentDisplayTab(this);
                self.updateUIMaxHeight();

                //Turn off multi publication discount message for Ags group
                if (this.valueOf() === agsGroup)
                    $('#discount-message.highlight').hide();
                else
                    $('#discount-message.highlight').show();
            }

            self.updateUIMaxHeight = function () {
                var selectedPublications = $(".selected-publications ul");
                if (selectedPublications != null && selectedPublications.length > 0) {
                    // Update the height of the seleced publications side panel
                    var toppos = $(".selected-publications ul").offset().top;
                    var $bottombutton = $("ul.cT-formActions .back");
                    var bottompos = $bottombutton.offset().top + $bottombutton.outerHeight(true);
                    var maxheight = bottompos - toppos;
                    var maxheightcss = "max-height: " + maxheight + "px"
                    $(".selected-publications ul").attr("style", maxheightcss);
                }
            } // self.updateUIMaxHeight 

            self.togglePublication = function () {
                $(".publcationsselectionerror").text('');

                var publication = this;
                if (self.selectedPublications.indexOf(publication) < 0) {
                    // Publication not yet exist, add it
                    self.selectedPublications.push(publication);
                    // Disable pubs that are not using the same publisher and templates
                    // Disable Cyber publications
                    $(".publication-choice.fcn-choice.cyberpublications li").addClass("disabled");

                    if (publication.DisplayTab == agsGroup) {
                        // Disable other non ags groups
                        $(".tabNav span[data-group!='" + agsGroup + "']").addClass("disabled");
                    }
                    else {
                        // Disable Ags
                        $(".tabNav span[data-group='" + agsGroup + "']").addClass("disabled");
                    }
                }
                else {
                    // Publication already exists, remove it
                    self.selectedPublications.remove(publication);
                    if (self.selectedPublications().length <= 0) {
                        // Enable Cyber publications
                        $(".publication-choice.fcn-choice.cyberpublications li").removeClass("disabled");
                        $(".tabNav span").removeClass("disabled");
                    }
                }
            } // self.togglePublication

            self.selectSinglePublication = function (data, event) {
                var publication = this;
                if (self.selectedPublications.indexOf(publication) < 0) {
                    // Publication not yet exist, add it
                    self.selectedPublications.push(publication);
                }
                $('#btnNext').click();
            }

            self.submitForm = function (data, event) {
                if (self.selectedPublications().length <= 0) {
                    $(".publcationsselectionerror").text("Please select at least one publication to continue.");
                }
                else {
                    var $form = $(event.target.form);
                    var publications = "";
                    for (var i = 0; i < self.selectedPublications().length; i++) {
                        publications += self.selectedPublications()[i].Code;
                        if (i < self.selectedPublications().length - 1) {
                            // Not the last element, add "-" sepearator
                            publications += "-";
                        }
                    }
                    var publicationsFld = $("<input />").attr("type", "hidden").attr("name", "publication").val(publications);
                    $form.append(publicationsFld);
                    $(event.target).trigger("change");
                }
            }
        }

        var viewModel = new PublicationsViewModel();
        ko.applyBindings(viewModel);
        viewModel.updateUIMaxHeight();
    };

    $.fn.publicationChooser = function (options) {
        this.each(function () {
            if (!$(this).data("publicationChooser")) {
                FD.CasualAds.GC.PrintAd.publicationChooser(this, options);
                $(this).data("publicationChooser", true);
            }
        });
    };
    // Ken's work end

    // Kristina's work start
    FD.namespace('FD.CasualAds.GC.PrintAd');
    FD.CasualAds.GC.PrintAd.printDayChooser = function (element, options) {
        function DayOnOffer(PubCode, PublishDate, DeadlineDate, IsDefault, IsExcluded, ViewModel) {
            var self = this;
            self.PubCode = PubCode;
            self.PublishDateString = PublishDate;
            self.PublishDate = new Date(PublishDate);
            self.DeadlineDate = new Date(DeadlineDate);
            self.IsDefault = IsDefault;
            self.IsExcluded = IsExcluded;
            self.icon_css = ko.computed(function () {
                if (ViewModel.selectedDaysOnOffer.indexOf(self) >= 0)
                    return "icon icon-approve";
                else
                    return "icon";
            });

            self.GetPublishDateDisplay = function () {
                return self.PublishDate.getDayName() + ' ' +
                    self.PublishDate.getDate() + ' ' +
                    self.PublishDate.getMonthName() + ' ' +
                    self.PublishDate.getFullYear();
            };

            self.GetRunDay = function () {
                return self.PubCode + '|' +
                    self.PublishDateString;
            };

            self.IsRunDaySelected = function () {
                return ViewModel.selectedDaysOnOffer.indexOf(self) >= 0;
            };

            self.li_css = ko.computed(function () {
                var defaultCss = "indicator-icon date-choice selector calDateStatus cursor-hand"
                var currentOffer = ViewModel.currentOffer();
                if (currentOffer != null &&
                    currentOffer.Schedule.NumberOfDays <= ViewModel.selectedDaysOnOffer().length &&
                    ViewModel.selectedDaysOnOffer().indexOf(self) < 0) {
                    return defaultCss + " disabled";
                }
                else {
                    return defaultCss;
                }
            });
        }

        function Offer(code, name, description, schedule, defaultDays, ViewModel) {
            var self = this;
            self.code = code;
            self.name = name;
            self.description = description;
            self.Schedule = schedule;
            self.DefaultDays = defaultDays;
            self.icon_css = ko.computed(function () {
                if (self == ViewModel.currentOffer())
                    return "icon icon-approve";
                else
                    return "icon";
            });
        }

        // Get difference for dates
        function getDaysDifference(dateFrom, dateTo) {
            var oneDay = 24 * 60 * 60 * 1000;
            return Math.round((dateTo - dateFrom) / oneDay) + 1;
        }

        function DaysOnOfferViewModel() {
            var self = this;

            self.DaysOnOffer = [];
            self.FilteredDaysOnOffer = new ko.observableArray();
            self.selectedDaysOnOffer = new ko.observableArray();
            self.currentOffer = ko.observable(null);

            self.InitializeDaysOnOffer = function (offer) {
                // For initialzation, fill everything from DaysOnOffer
                for (var i = 0; i < chosenSchedule.DaysOnOffer.length; i++) {
                    var dayOnOffer = new DayOnOffer(
                        chosenSchedule.PublicationCode,
                        chosenSchedule.DaysOnOffer[i].PublishDate,
                        chosenSchedule.DaysOnOffer[i].DeadlineDate,
                        chosenSchedule.DaysOnOffer[i].IsDefault,
                        chosenSchedule.DaysOnOffer[i].IsExcluded,
                        self
                    );
                    self.DaysOnOffer.push(dayOnOffer);
                }
            };

            self.UpdateDaysOnOffer = function (offer, setDefault) {
                self.FilteredDaysOnOffer.removeAll();
                self.selectedDaysOnOffer.removeAll();
                for (var i = 0; i < self.DaysOnOffer.length; i++) {
                    if (offer == null ||
                        offer.Schedule.AvailableDays.indexOf(self.DaysOnOffer[i].PublishDate.getDay()) >= 0) {
                        // When offer is null, it is for initialzation, fill everything from DaysOnOffer   
                        // Or when the day is within the Offer's Schedule's AvailableDays, select it.             
                        self.FilteredDaysOnOffer.push(self.DaysOnOffer[i]);
                    }
                }

                if (offer != null && setDefault == true) {
                    var startIndex = 0, done = false;
                    while (!done && startIndex < self.FilteredDaysOnOffer().length) {
                        var dayOnOfferIndex = startIndex, result = [];
                        for (var defaultDayIndex = 0; defaultDayIndex < offer.DefaultDays.length; defaultDayIndex++) {
                            while (dayOnOfferIndex < self.FilteredDaysOnOffer().length) {
                                if (offer.DefaultDays[defaultDayIndex].indexOf(
                                    self.FilteredDaysOnOffer()[dayOnOfferIndex].PublishDate.getDay()) >= 0) {
                                    if (result.length == 0) {
                                        // Frist entry found, set startIndex to dayOnOfferIndex, in case the selectionPeriod check fails and need to do it again in the next iteration
                                        startIndex = dayOnOfferIndex;
                                    }
                                    result.push(self.FilteredDaysOnOffer()[dayOnOfferIndex]);
                                    dayOnOfferIndex++;
                                    break;
                                }
                                else
                                    dayOnOfferIndex++;
                            } //while(dayOnOfferIndex < self.FilteredDaysOnOffer().length)
                        } // for(var defaultDayIndex = 0; defaultDayIndex < offer.DefaultDays.length; defaultDayIndex++)

                        // Verify the selectionPeriod
                        var daysDifference = getDaysDifference(result[0].PublishDate, result[result.length - 1].PublishDate);
                        if (daysDifference <= offer.Schedule.SelectionPeriod) {
                            // Selection period check is fine, copy over the result
                            done = true;
                            for (var k = 0; k < result.length; k++) {
                                self.selectedDaysOnOffer.push(result[k]);
                            }
                        } // if (daysDifference <= offer.Schedule.SelectionPeriod)
                        else {
                            // Increment startIndex, and go for another iteration
                            startIndex++;
                        }
                    }
                }
            };

            // Update selectedDaysOnOffer if chosenPublishingDays has been set by the server
            self.UpdateSelectedDaysOnOffer = function () {
                if (chosenPublishingDays && chosenPublishingDays.length == 1) {
                    var choosenDayArray = chosenPublishingDays[0].Item3;
                    for (var i = 0; i < choosenDayArray.length; i++) {
                        for (var j = 0; j < self.FilteredDaysOnOffer().length; j++) {
                            if (choosenDayArray[i].substr(0, 10) ==
                                self.FilteredDaysOnOffer()[j].PublishDateString.substr(0, 10)) {
                                self.selectedDaysOnOffer.push(self.FilteredDaysOnOffer()[j]);
                            }
                        }
                    }
                }
            };

            self.availableOffers = ko.observableArray([]);
            for (var i = 0; i < AvailableOffers.length; i++) {
                var offer = new Offer(
                    AvailableOffers[i].Code,
                    AvailableOffers[i].Name,
                    AvailableOffers[i].Description,
                    AvailableOffers[i].Schedule,
                    AvailableOffers[i].DefaultDays,
                    self);

                self.availableOffers.push(offer);

                if (CurrentOffer && CurrentOffer.Code == offer.code) {
                    // Offer code matched, update current offer
                    self.currentOffer(offer);
                }
            }

            // Note: DaysOnOffer means the days being displayed on the calendar    
            self.InitializeDaysOnOffer();
            self.UpdateDaysOnOffer(self.currentOffer());
            self.UpdateSelectedDaysOnOffer();


            self.isEditable = ko.observable(IsEditable);
            self.isOldOffer = function () {
                if (!self.currentOffer()) return false;
                if (!self.currentOffer().code) return false;
                if (self.availableOffers().length == 0) return false;
                return (self.availableOffers().filter(function (o) { return o.code === self.currentOffer().code }).length == 0);
            };

            self.toggleOffer = function (offer) {
                // Clear the error message as user making new selection
                $(".rundayselectionserror").text('');

                if (self.currentOffer() && self.currentOffer().code === offer.code) {
                    self.currentOffer(null);
                    self.UpdateDaysOnOffer(null);
                }
                else {
                    self.currentOffer(offer);
                    self.UpdateDaysOnOffer(offer, true);
                }
            }

            self.toggleDayOnOffer = function () {
                // Clear the error message as user making new selection
                $(".rundayselectionserror").text('');

                var dayOnOffer = this;
                if (self.selectedDaysOnOffer().indexOf(dayOnOffer) < 0) {
                    var currentOffer = self.currentOffer();
                    if (currentOffer != null) {
                        var selectedDaysOnOffer = self.selectedDaysOnOffer();

                        if (selectedDaysOnOffer.length >= currentOffer.Schedule.NumberOfDays) {
                            var errMsg = "You have selected the max " + current.Schedule.NumberOfDays + " days of the offer, no more day can be added";
                            $(".rundayselectionserror").text(errMsg);
                            return;
                        }
                    }

                    // Publication not yet exist, add it
                    self.selectedDaysOnOffer.push(dayOnOffer);
                    var sortedArray = self.selectedDaysOnOffer.sort(function (left, right) {
                        return left.PublishDate == right.PublishDate ? 0 : (left.PublishDate < right.PublishDate ? -1 : 1)
                    });

                    var daysDifference = getDaysDifference(sortedArray[0].PublishDate, sortedArray[sortedArray.length - 1].PublishDate);
                    if (currentOffer && daysDifference > currentOffer.Schedule.SelectionPeriod) {
                        var errMsg = "Please select " + currentOffer.Schedule.NumberOfDays + " dates within " + currentOffer.Schedule.SelectionPeriod + " days.";
                        $(".rundayselectionserror").text(errMsg);
                        self.selectedDaysOnOffer.remove(dayOnOffer);
                    }
                    else {
                        var scheduleDate = dayOnOffer.PublishDateString.replace(/ 00:00:00 GMT/g, '').replace(/^[A-Za-z]+, /g, '');
                        ga('send', 'event', 'Advert Schedule', scheduleDate);
                    }
                }
                else {
                    self.selectedDaysOnOffer.remove(dayOnOffer);
                }
            }
        }

        var viewModel = new DaysOnOfferViewModel();
        ko.applyBindings(viewModel);
    };

    $.fn.printDayChooser = function (options) {
        this.each(function () {
            if (!$(this).data("printDayChooser")) {
                FD.CasualAds.GC.PrintAd.printDayChooser(this, options);
                $(this).data("printDayChooser", true);
            }
        });
    };
    // Kristina's work end

    $(".sortable").sortable({
        handle: ".grab-handle",
        placeholder: "placeholder",
        items: ".sortable-field"
    });

    // Radio button label selectors...
    var isInLoop = false; // loop breaker for IE which triggers the click on the lable if you trigger the click on the input
    $(document).on("click", ".radio-toolbar-buttons label", function () {
        $(this).addClass('selected').siblings().removeClass('selected');
        if ($.browser.msie && !isInLoop) {
            isInLoop = true;
            $("input", this).click();
        } else {
            isInLoop = false;
        }
    });
    $(document).ready(function () {
        // toggle the correct selection on the radio button toolbars
        var checkedRadios = $("input:checked", ".radio-toolbar-buttons");
        checkedRadios.parent().addClass("selected");
    });


    $(document).on("click", ".delete-link", function () {
        if (confirm("Delete this field?")) {
            $(this).parent().remove();
        }
    });

    function fdPlaceAd_GenerateGuid() {
        // Source: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/105074#105074
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    };
    $(document).ready(function () {
        // move the ".templated-fields-buttons-activator" to be in the spot where it will be inserting fields...
        var oldActivator = $(".templated-fields-buttons-activator").parent().parent();
        var newActivator = oldActivator.clone();
        oldActivator.remove();
        var sortableFieldItems = $(".templated-fields-list").find(".sortable-field");
        if (sortableFieldItems.length > 0) {
            sortableFieldItems.last().after(newActivator);
        } else {
            $(".templated-fields-list").append(newActivator);
        }

        newActivator.show();

        //if a logo or photo is selected need to disable colour tint options
        var colourschemeChoiceSelector = $(".ffx-radio-buttons.colourSchemeBlock").first();
        colourschemeChoiceSelector.on('disableTint', function (e, a, b) {
            $('.colourscheme-choice.scheme-tint').each(function (i) {
                $(this).addClass("disabled");
                $(this).attr('title', "This option is not available when a logo or photo is being used");
            });
            // find out if the currently selected colourscheme is a bordered scheme
            var isUnBordered = $('.colourscheme-choice').find(':checked').val().indexOf('UNBORDERED') >= 0;

            // force selection to first non-disabled option of the same borderd state
            if (isUnBordered) {
                $('.colourscheme-choice').not('.disabled').filter(":first").click();
            } else {
                $('.colourscheme-choice').not('.disabled').not('.scheme-borderless').filter(":first").click();
            }

            // select the first (mono) tab
            $(this).closest(".ffx-quicksand").find(".ffx-quicksand-action").filter(":first").click();
        });

        colourschemeChoiceSelector.on('enableTint', function (e, a, b) {
            var pubCodeET = $('input.pubCode').val();
            if ((pubCodeET == 'SMH') || (pubCodeET == 'AGE')) {
                $('.colourscheme-choice.scheme-tint').each(function (i) {
                    $(this).removeClass("disabled");
                    $(this).attr('title', "Pick colour scheme");
                });
            }
        });

    });

    $(document).on("click", "#colourScheme-remover", function (event) {
        //clear the colour scheme to default
        $('.colour-tab li:first').click();
        $('.colourSchemeBlock span:first').click();
    });

    $(document).on("click", ".templated-fields-buttons-activator", function (event) {
        // two modes:
        var availableButtons = $(".add-templated-field", ".templated-fields-buttons");
        if (availableButtons.length == 1) {
            // single button: add that:
            availableButtons.trigger("click");
        } else {
            // multi button: dialog and show:
            $(".templated-fields-buttons").dialog({
                title: "Choose Field Type",
                modal: true
            });
        }
        event.preventDefault();
    });

    $(document).on("click", ".add-templated-field", function () {
        var type = $(this).data("type");
        // CHange to not do dynamically insert
        // We just construct a div will all the fields as hidden fields, and append it to the form
        var fieldContainer = $("<div />");

        var fieldKey = fdPlaceAd_GenerateGuid();
        var fieldNamePrefix = "Order.Products[0].TemplateFields[" + fieldKey + "]";
        // Fields required: DataValue, SecondaryDataValue, Alignment, Type, Foramt, FieldBindingKey, Index
        $(fieldContainer).append('<input type="hidden" name="Order.Products[0].TemplateFields.Index" value="' + fieldKey + '"/>');
        $(fieldContainer).append('<input type="hidden" name="' + fieldNamePrefix + '.FieldBindingKey" value="' + fieldKey + '"/>');
        $(fieldContainer).append('<input type="hidden" name="' + fieldNamePrefix + '.Type" value="' + type + '"/>');

        $(fieldContainer).append('<input type="hidden" name="' + fieldNamePrefix + '.Alignment" value="Centered"/>');


        if (type == "Heading") {
            $(fieldContainer).append('<input type="hidden" name="' + fieldNamePrefix + '.Format" value="Themed"/>');
            $(fieldContainer).append('<input type="hidden" name="' + fieldNamePrefix + '.SecondaryDataValue" value="Subheading"/>');
        } else {
            $(fieldContainer).append('<input type="hidden" name="' + fieldNamePrefix + '.Format" value="Standard"/>');
            $(fieldContainer).append('<input type="hidden" name="' + fieldNamePrefix + '.SecondaryDataValue" value=""/>');
        }

        // insert this new field into its rightful position..
        var sortableFieldItems = $(".templated-fields-list").find(".sortable-field");
        if (sortableFieldItems.length > 0) {
            sortableFieldItems.last().after(fieldContainer);
        } else {
            $(".templated-fields-list").append(fieldContainer);
        }

        // Submit the form for a preview....
        var submitOnChange = $('<input type="hidden" class="submitonchange" value=""/>');
        $(".templated-fields-list").append(submitOnChange);
        var fieldForm = $(submitOnChange).closest("form");
        var submitAction = fieldForm.attr("action");
        fieldForm.attr("action", submitAction + "#infojump");

        $(submitOnChange).trigger('change');

        $(".templated-fields-buttons").dialog('close');
    });

    //    //disable back button for the flow
    //    window.location.hash = 'end';
    //    $(window).on('hashchange', function (e) {
    //        var hash = window.location.hash.substring(1);
    //        if (hash != 'end') {
    //            window.location.hash = 'end';
    //            return false;
    //        }
    //    });             

    // Licence Number Behavior
    $('.trade-licence-number input[type="checkbox"]').click(function () {
        var textbox = $(this).parent().find("input[type='text']");
        if (this.checked) {
            var message = textbox.attr("data-default");
            textbox.attr("data-oldvalue", textbox.val());
            textbox.val(message);
            textbox.attr('readonly', true);
        } else {
            textbox.attr('readonly', false);
            textbox.val(textbox.attr("data-oldvalue"));
        }
    });

    // Template Checkbox Behavior
    $('.template-checkbox input[type="checkbox"]').click(function () {
        var datavalue = $(this).parent().find("input[type='hidden']");
        if (this.checked) {
            datavalue.val("true");
        } else {
            datavalue.val("");
        }
    });

    // Selector Grid
    $(".selectorGrid").on('mouseenter mouseleave click', ":table-cell:has(.selector)", function (event) {
        var $cell = $(this),
            $table = $cell.closest("table"),
            $container = $table.closest("div"),
            $cells = $table.find(":table-cell"),
            $selectors = $table.find(".selector"),
            $selectorCells = $cells.has($selectors),
            $rows = $table.find(":table-row"),
            $row = $cell.closest(":table-row"),
            $rowCells = $row.children(":table-cell"),
            colIndex = $rowCells.index($cell),
            $colCells = $rows.find(":table-cell:eq(" + colIndex + ")"),
            $colSelectors = $colCells.find(".selector"),
            selectionMode = $container.data('selection-mode');

        switch (event.type) {
            case 'mouseenter':
                $colCells.addClass('hover');
                $colSelectors.addClass('hover');
                break;
            case 'mouseleave':
                $colCells.removeClass('hover');
                $colSelectors.removeClass('hover');
                break;
            case 'click':
                if (selectionMode === 'radio') {
                    $selectorCells.removeClass('selected');
                    $selectors.removeClass('selected');
                }
                $colCells.toggleClass('selected');
                $colSelectors.toggleClass('selected');
                //event.stopPropagation();
                //event.stopImmediatePropagation();
                break;
        }
    });

    /* ======================================================================================
    EXPRESSIONS
    ====================================================================================== */

    /* [Lists]
    -------------------------------------------------------*/
    $.extend($.expr.pseudos, {
        'list': function (element) {
            return $(element).is("ol, ul");
        }
    });

    $.extend($.expr.pseudos, {
        'list-item': function (element) {
            return $(element).is("li");
        }
    });

    /* [Tables]
    -------------------------------------------------------*/
    $.extend($.expr.pseudos, {
        'table-header-group': function (element) {
            return $(element).is("thead");
        }
    });

    $.extend($.expr.pseudos, {
        'table-content-group': function (element) {
            return $(element).is("tbody");
        }
    });

    $.extend($.expr.pseudos, {
        'table-footer-group': function (element) {
            return $(element).is("tfoot");
        }
    });

    $.extend($.expr.pseudos, {
        'table-group': function (element) {
            return $(element).is(":table-header-group, :table-content-group, :table-footer-group");
        }
    });

    $.extend($.expr.pseudos, {
        'table-row': function (element) {
            return $(element).is("tr");
        }
    });

    $.extend($.expr.pseudos, {
        'table-header-cell': function (element) {
            return $(element).is("th");
        }
    });

    $.extend($.expr.pseudos, {
        'table-content-cell': function (element) {
            return $(element).is("td");
        }
    });

    $.extend($.expr.pseudos, {
        'table-cell': function (element) {
            return $(element).is(":table-header-cell, :table-content-cell");
        }
    });

    // CAP Sticky Panels
    $(".sticky-wrapper").stickyScroller({ stopper: ".footer", topspacing: 10 });

    /*helper text for section/pub */
    $(document).on('click', 'a.dialog-link', function () {
        var dialog_id = $(this).attr('id');

        $.get('/PrintPlaceAd/HelpContent', { flow: flowID, type: 'ClassificationHelper' }, function (data) {
            $('.deal-info-dialog').html(data);
        });


        $('.deal-info-dialog').dialog({
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 925
        });

        $('.deal-info-dialog').dialog('open');
    });

    if (flowID && $('.TemporaryTextPerSectionPub')) {
        $.get('/PrintPlaceAd/HelpContent', { flow: flowID, type: 'Temporary' }, function (data) {
            $('.TemporaryTextPerSectionPub').html(data);
        });
    }

}(jQuery));


$(function () {
    CAP.domain.Address.SuburbAutocomplete($("#PropertyAddress"));

    var myCarousel = $('#carousel-design').jcarousel({
        scroll: 1,
        buttonPrevHTML: "<button type='button'><span class='icon arrows left ir'>Previous option</span></button>",
        buttonNextHTML: "<button type='button'><span class='icon arrows right ir'>Next option</span></button>",
        itemFallbackDimension: 309
    });

    // Scroll to the selected item to ensure it is visible
    if (myCarousel.length) {
        var selectedIndex = $("#carousel-design ul li.selected").index(); // returns -1 if no selected item found
        if (selectedIndex >= 0) {
            myCarousel.jcarousel('scroll', selectedIndex + 1, true);
        }
    }

    $("#printWeekChooser").printWeekChooser();
    $("#publicationChooser").publicationChooser();
    $("#printDayChooser").printDayChooser();
});

$(function () {
    // ACM Under $100 classification
    var option = $('select[id$="__ClassificationCategory"] option[value="675"]');
    option.css("color", "red").css("font-weight", "bold");

    var blankOption = $('select[id$="__ClassificationCategory"] option[value=""]');
    option.insertAfter(blankOption);

    if (blankOption == undefined || blankOption.length == 0)
        option.insertBefore($('select[id$="__ClassificationCategory"] option:eq(0)'));

});

$(function () {
    // Trades and Services Dialog
    var options = {
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        width: 1000,
        title: "Choose Trades and Services Ad Type"
    };

    var dialogTradesAndServices = $("#dialog-tradesAndServices .dialogContent").dialog(options);

    $(".choose-trade-services-ad").click(function () {
        dialogTradesAndServices.dialog('open');
    });
});

;
      // <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
      // Set this tag in your page: <div id="player"></div>

      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var listOfPlayers = [];
      function onYouTubeIframeAPIReady() {
        $(".youtubeiframe").each(function( index ) {
            var player;
            var playerId = $(this).attr('id');
            player = new YT.Player(playerId, {
              events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
              }
            });
            listOfPlayers.push(player);
        });        
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        //event.target.playVideo();
        console.log("player is ready")
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      // var done = false;
      function onPlayerStateChange(event) {
        console.log("event state updated: " + event.data);
        if (event.data == YT.PlayerState.PLAYING)
        {
            stopAllOtherPlayers(event.target);
        }
      }

      function stopAllOtherPlayers(currentPlayer) {
        for (var i = 0, len = listOfPlayers.length; i < len; i++) {
          var player = listOfPlayers[i];
          if (player != currentPlayer)
          {
            player.stopVideo();    
          }
        }        
      };

/**
Javascript to serve Domain property address suburb auto-suggest
*/

namespace("CAP.domain").Address = (function ($) {
    return{
        SuburbAutocomplete: function (container, callback) {
            var cache = {};
            var suburbTextField = $(container).find('.suburb');
            var loadingObj = $(container).find(".loader");
            loadingObj.hide();
            $(suburbTextField).autocomplete({
                minLength:3,
                source: function (request, response) {
                    var keyword = request.keyword;
                    loadingObj.show();
                    $.ajax({
                        url: "/domain/api/Location/GetSuburbSuggestion",
                        dataType: "json",
                        data: { keyword: request.term },
                        error: function () {
                            loadingObj.hide();
                        },
                        success: function (data) {
                            var
                                term = $(suburbTextField).val(),
                            highlightedData = {};
                            highlightedData = $.map(data, function (item) {
                                var
                        findExpr = new RegExp("(" + term + ")", "gi"),
                        highlightedItem = {
                            Postcode: item.Postcode.replace(findExpr, "$1"),
                            Suburb: item.Suburb.replace(findExpr, "$1"),
                            State: item.State.replace(findExpr, "$1>")
                        };

                                return {
                                    value: item.Suburb + " " + item.State + " " + item.Postcode,
                                    label: highlightedItem.Suburb + ", " + highlightedItem.State + " " + highlightedItem.Postcode,
                                    payload: item
                                };
                            });
                            cache[keyword] = highlightedData;
                            response(highlightedData);
                            loadingObj.hide();
                        }
                    });

                },
                select: function (event, ui) {
                    $(container).find('.postcode').val(ui.item.payload.Postcode.trim());
                    $(container).find('.state').val(ui.item.payload.State.trim());
                    $(container).find('.suburb').val(ui.item.payload.Suburb.trim());
                    $(container).find('.field-validation-error').empty();
                    if (typeof callback === 'function') {
                        callback.call(ui.item); // Call your callback
                    }
                    
                    return false;
                }
            });
        }
}
 })(jQuery);

;
FD.namespace('FD.Classifieds.CasualAds.Classified');

(function ($) {

    var toolbarconfig = {
        'A': 'Bold',
        'B': 'Styles',
        'C': 'longdash',
        'D': 'leaderfill',
        'E': 'leftrightjustify',
        'F': 'logouploader',
        'J': 'JustifyLeft',
        'I': 'JustifyCenter',
        'H': 'JustifyRight',
        'G': 'JustifyBlock',
        'K': 'StarredList', // star bullet
        'L': 'BulletedList', // spot bullet
        //'M': 'equalspacing'
        'N': 'Smiley' // emojis
    };

    // Default toolbar has no smileys because it is not offered on all templates
    var defaultToolBar = [['Bold', 'Styles', 'longdash', 'leaderfill', "leftrightjustify", 'logouploader'], '/', ['BulletedList', 'StarredList'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']];

    var devToolBarGroup1 = ['A', 'C', 'D', 'E',];
    var devToolBarGroup2 = ['J', 'I', 'H', 'G'];
    var devToolBarGroup3 = ['L', 'K', '-', 'F', 'N', 'B'];
    
    var editorSize = {'1':{'width':'276', 'height':'400'}, '2':{'width':'400','height':'400'}};

    var composeType = "AOL";

    FD.Classifieds.CasualAds.Classified.EasyPrintEditor = function (el, options)
    {
        var base = this;
        base.$el = $(el);
        base.el = el;


        var limitNum = 150;
        var defaultColumnWidth = options.defaultColumWidth;
        var enableItalicHeading = options.enableItalicHeading;
//        var configFile = 'printconfig.js';
//        var adComposeConfigFile = 'printconfig_adcompose.js';
        base.$el.data("easyprinteditor", base);

        base.init = function () {
            base.options = $.extend({}, FD.Classifieds.CasualAds.Classified.EasyPrintEditor.defaultOptions, options);
            
            var easyeditor = base.$el;
        
            var headTagErrorMsg = $('<div class="status status-success" role="alert" aria-live="polite">The heading tags (H1, H2 and/or H3) must be used with a text line or paragraph. \nThere appears to be no text for one of your tags. Please correct this and proceed.</div>');
            
            //var width = 270, height = 400;
            var bodyClass = "single";
            var columNumber = $('.columnchoice').val();

            if(typeof columNumber == 'undefined')
            {
                if($('iframe').first().hasClass('double'))
                    columNumber = 2;
                else
                    columNumber = defaultColumnWidth;
            }
           customiseEditor($('.printAdvertEditor').attr('id'), columNumber, enableItalicHeading);
         };

         base.init();
 
    };


    function customiseEditor(ckeditorInstanceId, columNumber, enableItalicHeading)
    {
        var customisedToolbarConfig = [];
        var allowedtoolbar = $('.printAdvertEditor').data('toolbar-' + columNumber + 'col');
        var extraPlugins = $('.printAdvertEditor').data('extra-plugins');
        var defaultPlugins = 'longdash,leaderfill,leftrightjustify,logouploader,photouploader,starlist,smiley';

        if (extraPlugins) {
            defaultPlugins += ',' + extraPlugins;
            
        }
        if (typeof (allowedtoolbar) != 'undefined') {
 
            var listOfAllowedToolbar = allowedtoolbar.split(',');
            var group1 = [], group2 = [], group3 = [];
            $.each(listOfAllowedToolbar, function (i, j) {
                if (jQuery.inArray(j, devToolBarGroup1) > -1) {
                    group1.push(toolbarconfig[j]);
                }
                if (jQuery.inArray(j, devToolBarGroup2) > -1)
                {
                    group2.push(toolbarconfig[j]);
                }
                if (jQuery.inArray(j, devToolBarGroup3) > -1) {
                    group3.push(toolbarconfig[j]);
                }                
            });

            customisedToolbarConfig.push(group1);
            customisedToolbarConfig.push(group2);
            customisedToolbarConfig.push(group3);
        } else {
            //if no customised toolbarconfig is provided the default would be full toolbar
            customisedToolbarConfig = defaultToolBar;
        }

        if(!CKEDITOR.stylesSet.registered['default'])
        {
            if(enableItalicHeading == 'True')
            {
                CKEDITOR.stylesSet.add('default', [
                            { name: 'Heading 1', element: 'h1',styles:{ 'text-align':'center'} }, 
                            { name: 'Heading 2', element: 'h2',styles:{ 'text-align':'center'} },
                            { name: 'Italic Heading 1', element: 'h1', styles:{ 'font-style':'italic'}},
                            { name: 'Italic Heading 2', element: 'h2', styles:{'font-style':'italic'}},
                            { name: 'Normal', element: 'p', styles:{ 'text-align':'justify'}}]);
            }else{
                CKEDITOR.stylesSet.add('default', [{ name: 'Heading 1', element: 'h1', styles:{ 'text-align':'center'} }, { name: 'Heading 2', element: 'h2',styles:{ 'text-align':'center'}}, { name: 'Normal', element: 'p',styles:{ 'text-align':'justify'}}]);
            }
        }
       
        CKEDITOR.replace(ckeditorInstanceId,//$('.printAdvertEditor').attr('id'),
        {
                toolbar : customisedToolbarConfig,
                removePlugins: 'elementspath, liststyle, tabletools, contextmenu',
                resize_enabled : false,
                forcePasteAsPlainText: true,
                toolbarCanCollapse: false,
                entities_processNumerical: 'force',
                extraPlugins: defaultPlugins,
                on: {
                    instanceReady: function (e) {
                        e.sender.on('key', FD.Classifieds.CasualAds.Classified.EnableColourScheme);
            		    e.sender.on('blur', FD.Classifieds.CasualAds.Classified.EnableColourScheme);
            	    },
                    paste: function (e) {
                        e.data.text = $.trim(FD.Convert.toText(e.data.text || e.data.html));
                    },
                    beforeCommandExec: function(e) {
                        if (e.data.name == "bulletedlist" || e.data.name == "numberedlist" || e.data.name == "starredlist")
                        {
                            if(!enablebulletlist(ckeditorInstanceId, e.data.name))
                            { 
                                e.data.command.disable();
                            }
                        }

                        if(/justifyleft|justifyright|justifycenter/g.test(e.data.name))
                        {
                            if(!enableAlignment(ckeditorInstanceId, e.data.name))
                            { 
                                e.data.command.disable();
                            }
                        }
                    },
                    afterCommandExec: function(e){
                        if( e.data.name== "numberedlist")
                        {
                            renderStarredList(ckeditorInstanceId, e.data.name);
                        }
                        },
                    saveSnapshot: function(e) { FD.Classifieds.CasualAds.Classified.EditorContentChange(e);}
                },
            width: editorSize[columNumber]['width'] + "px",
            height: editorSize[columNumber]['height'] + "px",
            bodyClass: (columNumber== 1)?'single':'double',
            styleSet: 'default',
            fillEmptyBlocks: false,
            skin: 'moono-lisa',
            autoParagraph : true,
            UseBROnCarriageReturn: true,
        });

        if ((typeof (emojiImages) != 'undefined') && (typeof (emojiDescriptions) != 'undefined'))
        {
            CKEDITOR.config.smiley_path = 'https://cdn.addirect.com.au/emojithumbs/'
            CKEDITOR.config.smiley_columns = 10;
            CKEDITOR.config.smiley_images = emojiImages;    // defined in GCLINER.cshtml
            CKEDITOR.config.smiley_descriptions = emojiDescriptions; // defined in GCLINER.cshtml
            CKEDITOR.config.smiley_page_size = 100;
        }
      
            //$('.minlines').text("Minimum of " + columNumber * 4 + " lines of text");
            //$('.minlines').text("Minimum of  4 lines of text");
            
    }

        $('.columnchoice').on('change', function(){
           
            var columNumber = $(this).val();
            var o =  CKEDITOR.instances[$('.printAdvertEditor').attr('id')];
            if (o) o.destroy();

            var width, height, bodyClass;

            if(columNumber == '1'){
                   width = 357, height = 400, bodyClass = 'single'; 
                }
                else{
                      width = 286, height=400,bodyClass = 'double'; 
                }

            customiseEditor($('.printAdvertEditor').attr('id'), columNumber, $('input[name=enableItalic]').val());

        });

         $('.showhtml').on("click", function(){
            var htmlData = $('.printAdvertEditor').val();
            $('.HtmlSource').val(htmlData);
         });


              $('.transform_to_symbols').on("click", function() {
                //validate the text
                
                var htmlData = CKEDITOR.instances[$('.printAdvertEditor').attr('id')].getData();
                if(typeof htmlData != 'undefined')
                {
                    $.ajax({
                url: "/MarkupGenerator/TransformHtmlToMarkup/",
                type: "POST",
                async: true,
                success: function (data, textStatus, jqXHR) {
                    $('.PrintAdFormatText').val(data);
                },
                data: { htmlText: htmlData, composeType:composeType},
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('error');
                }
            });
                }
                
            });


    //decide if the bullet list should be enabled
    function enablebulletlist(elementId, event)
    {
        var selectedHtmlText = CKEDITOR.getSelectedHtml();//CKEDITOR.instances[elementId].getSelectedHtml();
        if(selectedHtmlText.indexOf('<h1')>= 0|| selectedHtmlText.indexOf('<h2')>= 0 || selectedHtmlText.indexOf('class="logo"')>= 0)
        {
            alert("This function is disabled for headings and logos.");
            return false;
        }

        var selectedRange = CKEDITOR.instances[elementId].getSelection().getRanges()[0];

        if (selectedRange && selectedRange.startContainer)
        {
            var node = selectedRange.startContainer;
            var nodeName = "";
            if(node.type != 3) //3 is native text node, getName() would fail
            {
                nodeName = node.getName();
            
            }else{
                var parentNode = node.getParent();
                nodeName = parentNode.getName();
            }
        
            if(nodeName == "h1" || nodeName == "h2")
            {
                alert("This function is disabled for headings.");
                return false;
            }
        }
        return true;
    }

    // decide if alignment should be enabled
    function enableAlignment(elementId, event)
    {
        var selectedHtmlText = CKEDITOR.getSelectedHtml();
        if(selectedHtmlText.indexOf('class="logo"')>= 0)
        {
            alert("This function is disabled for logos.");
            return false;
        }

        var selectedRange = CKEDITOR.instances[elementId].getSelection().getRanges()[0];

        if (selectedRange && selectedRange.startContainer)
        {
            var node = selectedRange.startContainer;
            var selectedNode;
            if(node.type != 3) //3 is native text node, getName() would fail
            {
                selectedNode = node;
            
            }else{
                var parentNode = node.getParent();
                selectedNode = parentNode;
            }
        
            if(selectedNode && selectedNode.hasClass("logo"))
            {
                alert("This function is disabled for logos.");
                return false;
            }
        }
        return true;
    }

    //render starred list with class 'starlist'
    function renderStarredList(elementId, event)
    {

        var editor = CKEDITOR.currentInstance;
            var element = editor.getSelection().getStartElement().getParent();
            element.addClass('starlist');
 
    }
     
 //rule check on the ckeditor on blur or keydown, ensure the html in the editor is clean..
        FD.Classifieds.CasualAds.Classified.EnableColourScheme = function (e) {
            var text = null;
            if (e && e.sender) {
                var editor = CKEDITOR.instances[$('.printAdvertEditor').attr('id')];
                var isNoExternalLogoSelected = ($('.logo-selector-container .chosen-items img').length == 0);
                if(typeof e.data != 'undefined')
                {
                    if(e.data.keyCode == 8 || e.data.keyCode == 46)
                    {
                        //DELETE OR BACKSPACE
                        var selectedHtml =  CKEDITOR.getSelectedHtml();
                        if(selectedHtml.indexOf('class="logo"') <0 && isNoExternalLogoSelected)
                        {
                            //selected html including image
                            $('.colourscheme-choice').trigger('enableTint');
                        }
                    }
                }else {

                    if(editor.checkDirty())
                    {
                        var textData = editor.getData();
                        if(textData.indexOf('class="logo"') <0 && isNoExternalLogoSelected)
                        {
                            //remove disable on the colour scheme
                            $('.colourscheme-choice').trigger('enableTint');
                        }         
                          
                    }
                }
                   
            }
        }

        //detect the content change when apply style
        FD.Classifieds.CasualAds.Classified.EditorContentChange = function(e)
        {
            if (e && e.sender && e.sender.getSelection()) {
               
                var selectedRange = e.sender.getSelection().getRanges()[0];

                if (selectedRange && selectedRange.startContainer) {
                    var node = selectedRange.startContainer;
                              
                    if(node.type != 3) //3 is native text node, getName() would fail
                    {
                        var nodeName = node.getName();
                        if(nodeName == "h1" || nodeName == "h2")
                        {
                            if(node.getParent().getName() == "li")
                            {
                                 //the heading is set in a prent of li
                                 node.getParent().appendText(node.getText()); 
                                 node.remove();
                            }
                        }
                    }
                }
            }
        }
        

})(jQuery);

CKEDITOR.getSelectedHtml = function () {
    //note: next line works for IE, but not other browsers, so not using (createRange() not supported)
    //return editor.getSelection().getNative().createRange().htmlText;

    //assumes only one ckeditor on   a page
    //find the iframe and see what is selected
    var iframe = $(".cke_wysiwyg_frame");
    var sel = "";

    sel = iframe[0].contentDocument.getSelection();

    if (sel.rangeCount > 0) {
        range = sel.getRangeAt(0);
        var clonedSelection = range.cloneContents();
        return $("<div></div>").append(clonedSelection).html();
    }
    else
        return "";
};;
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;((t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).braintree||(t.braintree={})).dropin=e()}}(function(){return function a(o,s,l){function d(t,e){if(!s[t]){if(!o[t]){var i="function"==typeof require&&require;if(!e&&i)return i(t,!0);if(c)return c(t,!0);var r=new Error("Cannot find module '"+t+"'");throw r.code="MODULE_NOT_FOUND",r}var n=s[t]={exports:{}};o[t][0].call(n.exports,function(e){return d(o[t][1][e]||e)},n,n.exports,a,o,s,l)}return s[t].exports}for(var c="function"==typeof require&&require,e=0;e<l.length;e++)d(l[e]);return d}({1:[function(e,t,i){"use strict";var r=e("./load-script"),n=e("./load-stylesheet");t.exports={loadScript:r,loadStylesheet:n}},{"./load-script":3,"./load-stylesheet":4}],2:[function(i,r,e){(function(e){"use strict";var t=i("promise-polyfill");r.exports=e.Promise||t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"promise-polyfill":121}],3:[function(e,t,i){"use strict";var o=e("./lib/promise"),s={};function r(i){var t,r,n,e,a=JSON.stringify(i);return!i.forceScriptReload&&(e=s[a])?e:(n=document.createElement("script"),t=i.dataAttributes||{},r=i.container||document.head,n.src=i.src,n.id=i.id,n.async=!0,Object.keys(t).forEach(function(e){n.setAttribute("data-"+e,t[e])}),e=new o(function(e,t){n.addEventListener("load",function(){e(n)}),n.addEventListener("error",function(){t(new Error(i.src+" failed to load."))}),n.addEventListener("abort",function(){t(new Error(i.src+" has aborted."))}),r.appendChild(n)}),s[a]=e)}r.clearCache=function(){s={}},t.exports=r},{"./lib/promise":2}],4:[function(e,t,i){"use strict";var r=e("./lib/promise");t.exports=function(e){var t,i=document.querySelector('link[href="'+e.href+'"]');return i||(i=document.createElement("link"),t=e.container||document.head,i.setAttribute("rel","stylesheet"),i.setAttribute("type","text/css"),i.setAttribute("href",e.href),i.setAttribute("id",e.id),t.firstChild?t.insertBefore(i,t.firstChild):t.appendChild(i)),r.resolve(i)}},{"./lib/promise":2}],5:[function(e,i,t){(function(t){"use strict";i.exports=function(e){return e=e||t.navigator.userAgent,/Android/.test(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],6:[function(e,t,i){"use strict";var r=e("./is-edge"),n=e("./is-samsung");t.exports=function(e){return!(-1===(e=e||navigator.userAgent).indexOf("Chrome")&&-1===e.indexOf("CriOS")||r(e)||n(e))}},{"./is-edge":7,"./is-samsung":17}],7:[function(e,t,i){"use strict";t.exports=function(e){return-1!==(e=e||navigator.userAgent).indexOf("Edge/")}},{}],8:[function(e,r,t){(function(t){"use strict";var i=e("./is-ie11");r.exports=function(e){return-1!==(e=e||t.navigator.userAgent).indexOf("MSIE")||i(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./is-ie11":10}],9:[function(e,t,i){"use strict";t.exports=function(e){return-1!==(e=e||navigator.userAgent).indexOf("MSIE 10")}},{}],10:[function(e,t,i){"use strict";t.exports=function(e){return-1!==(e=e||navigator.userAgent).indexOf("Trident/7")}},{}],11:[function(e,t,i){"use strict";t.exports=function(e){return-1!==(e=e||navigator.userAgent).indexOf("MSIE 9")}},{}],12:[function(e,i,t){(function(t){"use strict";i.exports=function(e){return e=e||t.navigator.userAgent,/FxiOS/i.test(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],13:[function(e,t,i){"use strict";var r=e("./is-ios"),n=/webkit/i;t.exports=function(e){return e=e||navigator.userAgent,r(e)&&e.match(n)&&-1===e.indexOf("CriOS")}},{"./is-ios":15}],14:[function(e,r,t){(function(t){"use strict";var i=e("./is-ios");r.exports=function(e){return e=e||t.navigator.userAgent,!!i(e)&&(!!/\bGSA\b/.test(e)||/.+AppleWebKit(?!.*Safari)/.test(e))}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./is-ios":15}],15:[function(e,i,t){(function(t){"use strict";i.exports=function(e){return e=e||t.navigator.userAgent,/iPhone|iPod|iPad/i.test(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],16:[function(e,r,t){(function(t){"use strict";var i=e("./is-ios-firefox");r.exports=function(e){return e=e||t.navigator.userAgent,i(e)||/iPhone|iPod|iPad|Mobile|Tablet/i.test(e)&&/Firefox/i.test(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./is-ios-firefox":12}],17:[function(e,i,t){(function(t){"use strict";i.exports=function(e){return e=e||t.navigator.userAgent,/SamsungBrowser/i.test(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],18:[function(e,t,i){"use strict";function r(e){return e.className.trim().split(/\s+/)}function n(e){var t=Array.prototype.slice.call(arguments,1),i=r(e).filter(function(e){return-1===t.indexOf(e)}).concat(t).join(" ");e.className=i}function a(e){var t=Array.prototype.slice.call(arguments,1),i=r(e).filter(function(e){return-1===t.indexOf(e)}).join(" ");e.className=i}t.exports={add:n,remove:a,toggle:function(e,t,i){i?n(e,t):a(e,t)}}},{}],19:[function(e,t,i){"use strict";var r=e("./lib/set-attributes"),n=e("./lib/default-attributes"),a=e("./lib/assign");t.exports=function(e){var t=document.createElement("iframe"),i=a({},n,e);return i.style&&"string"!=typeof i.style&&(a(t.style,i.style),delete i.style),r(t,i),t.getAttribute("id")||(t.id=t.name),t}},{"./lib/assign":20,"./lib/default-attributes":21,"./lib/set-attributes":22}],20:[function(e,t,i){"use strict";t.exports=function(i){return Array.prototype.slice.call(arguments,1).forEach(function(t){"object"==typeof t&&Object.keys(t).forEach(function(e){i[e]=t[e]})}),i}},{}],21:[function(e,t,i){"use strict";t.exports={src:"about:blank",frameBorder:0,allowtransparency:!0,scrolling:"no"}},{}],22:[function(e,t,i){"use strict";t.exports=function(e,t){var i;for(var r in t)t.hasOwnProperty(r)&&(null==(i=t[r])?e.removeAttribute(r):e.setAttribute(r,i))}},{}],23:[function(e,t,i){"use strict";t.exports=function(t){return function(){var e=arguments;setTimeout(function(){t.apply(null,e)},1)}}},{}],24:[function(e,t,i){"use strict";t.exports=function(e){var t=!1;return function(){t||(t=!0,e.apply(null,arguments))}}},{}],25:[function(e,t,i){"use strict";t.exports=function(e,t){if(!t)return e;e.then(function(e){t(null,e)}).catch(function(e){t(e)})}},{}],26:[function(e,t,i){"use strict";var r=e("./lib/deferred"),n=e("./lib/once"),a=e("./lib/promise-or-callback");function s(i){return function(){var e,t=Array.prototype.slice.call(arguments);return"function"==typeof t[t.length-1]&&(e=t.pop(),e=n(r(e))),a(i.apply(this,t),e)}}s.wrapPrototype=function(n,e){var a,o;return a=(e=e||{}).ignoreMethods||[],o=!0===e.transformPrivateMethods,Object.getOwnPropertyNames(n.prototype).filter(function(e){var t,i="constructor"!==e&&"function"==typeof n.prototype[e],r=-1===a.indexOf(e);return t=!!o||"_"!==e.charAt(0),i&&t&&r}).forEach(function(e){var t=n.prototype[e];n.prototype[e]=s(t)}),n},t.exports=s},{"./lib/deferred":23,"./lib/once":24,"./lib/promise-or-callback":25}],27:[function(d,c,e){(function(r){"use strict";var n=d("../lib/braintree-error"),a=d("../lib/analytics"),o=d("./errors"),s=d("../lib/promise"),e=d("../lib/methods"),t=d("../lib/convert-methods-to-error"),i=d("@braintree/wrap-promise");function l(e){this._client=e.client,Object.defineProperty(this,"merchantIdentifier",{value:this._client.getConfiguration().gatewayConfiguration.applePayWeb.merchantIdentifier,configurable:!1,writable:!1})}l.prototype.createPaymentRequest=function(e){var t=this._client.getConfiguration().gatewayConfiguration.applePayWeb,i={countryCode:t.countryCode,currencyCode:t.currencyCode,merchantCapabilities:t.merchantCapabilities||["supports3DS"],supportedNetworks:t.supportedNetworks.map(function(e){return"mastercard"===e?"masterCard":e})};return Object.assign({},i,e)},l.prototype.performValidation=function(e){var t,i=this;return e&&e.validationURL?(t={validationUrl:e.validationURL,domainName:e.domainName||r.location.hostname,merchantIdentifier:e.merchantIdentifier||this.merchantIdentifier},null!=e.displayName&&(t.displayName=e.displayName),this._client.request({method:"post",endpoint:"apple_pay_web/sessions",data:{_meta:{source:"apple-pay"},applePayWebSession:t}}).then(function(e){return a.sendEvent(i._client,"applepay.performValidation.succeeded"),s.resolve(e)}).catch(function(e){return a.sendEvent(i._client,"applepay.performValidation.failed"),"CLIENT_REQUEST_ERROR"===e.code?s.reject(new n({type:o.APPLE_PAY_MERCHANT_VALIDATION_FAILED.type,code:o.APPLE_PAY_MERCHANT_VALIDATION_FAILED.code,message:o.APPLE_PAY_MERCHANT_VALIDATION_FAILED.message,details:{originalError:e.details.originalError}})):s.reject(new n({type:o.APPLE_PAY_MERCHANT_VALIDATION_NETWORK.type,code:o.APPLE_PAY_MERCHANT_VALIDATION_NETWORK.code,message:o.APPLE_PAY_MERCHANT_VALIDATION_NETWORK.message,details:{originalError:e}}))})):s.reject(new n(o.APPLE_PAY_VALIDATION_URL_REQUIRED))},l.prototype.tokenize=function(e){var t=this;return e.token?this._client.request({method:"post",endpoint:"payment_methods/apple_payment_tokens",data:{_meta:{source:"apple-pay"},applePaymentToken:Object.assign({},e.token,{paymentData:btoa(JSON.stringify(e.token.paymentData))})}}).then(function(e){return a.sendEvent(t._client,"applepay.tokenize.succeeded"),s.resolve(e.applePayCards[0])}).catch(function(e){return a.sendEvent(t._client,"applepay.tokenize.failed"),s.reject(new n({type:o.APPLE_PAY_TOKENIZATION.type,code:o.APPLE_PAY_TOKENIZATION.code,message:o.APPLE_PAY_TOKENIZATION.message,details:{originalError:e}}))}):s.reject(new n(o.APPLE_PAY_PAYMENT_TOKEN_REQUIRED))},l.prototype.teardown=function(){return t(this,e(l.prototype)),s.resolve()},c.exports=i.wrapPrototype(l)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lib/analytics":67,"../lib/braintree-error":72,"../lib/convert-methods-to-error":77,"../lib/methods":93,"../lib/promise":95,"./errors":28,"@braintree/wrap-promise":26}],28:[function(e,t,i){"use strict";var r=e("../lib/braintree-error");t.exports={APPLE_PAY_NOT_ENABLED:{type:r.types.MERCHANT,code:"APPLE_PAY_NOT_ENABLED",message:"Apple Pay is not enabled for this merchant."},APPLE_PAY_VALIDATION_URL_REQUIRED:{type:r.types.MERCHANT,code:"APPLE_PAY_VALIDATION_URL_REQUIRED",message:"performValidation must be called with a validationURL."},APPLE_PAY_MERCHANT_VALIDATION_NETWORK:{type:r.types.NETWORK,code:"APPLE_PAY_MERCHANT_VALIDATION_NETWORK",message:"A network error occurred when validating the Apple Pay merchant."},APPLE_PAY_MERCHANT_VALIDATION_FAILED:{type:r.types.MERCHANT,code:"APPLE_PAY_MERCHANT_VALIDATION_FAILED",message:"Make sure you have registered your domain name in the Braintree Control Panel."},APPLE_PAY_PAYMENT_TOKEN_REQUIRED:{type:r.types.MERCHANT,code:"APPLE_PAY_PAYMENT_TOKEN_REQUIRED",message:"tokenize must be called with a payment token."},APPLE_PAY_TOKENIZATION:{type:r.types.NETWORK,code:"APPLE_PAY_TOKENIZATION",message:"A network error occurred when processing the Apple Pay payment."}}},{"../lib/braintree-error":72}],29:[function(e,t,i){"use strict";var r=e("../lib/braintree-error"),n=e("./apple-pay"),a=e("../lib/analytics"),o=e("../lib/basic-component-verification"),s=e("../lib/create-deferred-client"),l=e("../lib/create-assets-url"),d=e("./errors"),c=e("../lib/promise"),p=e("@braintree/wrap-promise");t.exports={create:p(function(t){var e="Apple Pay";return o.verify({name:e,client:t.client,authorization:t.authorization}).then(function(){return s.create({authorization:t.authorization,client:t.client,debug:t.debug,assetsUrl:l.create(t.authorization),name:e})}).then(function(e){return t.client=e,t.client.getConfiguration().gatewayConfiguration.applePayWeb?(a.sendEvent(t.client,"applepay.initialized"),new n(t)):c.reject(new r(d.APPLE_PAY_NOT_ENABLED))})}),VERSION:"3.42.0"}},{"../lib/analytics":67,"../lib/basic-component-verification":70,"../lib/braintree-error":72,"../lib/create-assets-url":79,"../lib/create-deferred-client":81,"../lib/promise":95,"./apple-pay":27,"./errors":28,"@braintree/wrap-promise":26}],30:[function(e,t,i){"use strict";var r=e("@braintree/browser-detection/is-ie"),n=e("@braintree/browser-detection/is-ie9");t.exports={isIe:r,isIe9:n}},{"@braintree/browser-detection/is-ie":8,"@braintree/browser-detection/is-ie9":11}],31:[function(e,t,i){"use strict";var p=e("./constants").BRAINTREE_VERSION,n=e("./request/graphql"),a=e("./request"),o=e("../lib/is-verified-domain"),u=e("../lib/braintree-error"),h=e("../lib/convert-to-braintree-error"),m=e("../lib/create-authorization-data"),r=e("./get-configuration").getConfiguration,y=e("../lib/add-metadata"),s=e("../lib/promise"),l=e("@braintree/wrap-promise"),f=e("../lib/once"),g=e("../lib/deferred"),v=e("../lib/assign").assign,b=e("../lib/analytics"),E=e("./constants"),_=e("./errors"),C=e("../lib/errors"),d=e("../lib/constants").VERSION,P=e("../lib/constants").GRAPHQL_URLS,c=e("../lib/methods"),T=e("../lib/convert-methods-to-error"),A=e("../lib/assets"),I=e("../lib/constants").FRAUDNET_FNCLS,D=e("../lib/constants").FRAUDNET_SOURCE,w=e("../lib/constants").FRAUDNET_URL,N={};function M(e){var t,i,r;if(e=e||{},t=JSON.stringify(e),!(i=e.gatewayConfiguration))throw new u(_.CLIENT_MISSING_GATEWAY_CONFIGURATION);if(["assetsUrl","clientApiUrl","configUrl"].forEach(function(e){if(e in i&&!o(i[e]))throw new u({type:_.CLIENT_GATEWAY_CONFIGURATION_INVALID_DOMAIN.type,code:_.CLIENT_GATEWAY_CONFIGURATION_INVALID_DOMAIN.code,message:e+" property is on an invalid domain."})}),this.getConfiguration=function(){return JSON.parse(t)},this._request=a,this._configuration=this.getConfiguration(),this._clientApiBaseUrl=i.clientApiUrl+"/v1/",(r=i.braintreeApi)&&(this._braintreeApi={baseUrl:r.url+"/",accessToken:r.accessToken},!o(this._braintreeApi.baseUrl)))throw new u({type:_.CLIENT_GATEWAY_CONFIGURATION_INVALID_DOMAIN.type,code:_.CLIENT_GATEWAY_CONFIGURATION_INVALID_DOMAIN.code,message:"braintreeApi URL is on an invalid domain."});i.graphQL&&(this._graphQL=new n({graphQL:i.graphQL}))}M.initialize=function(t){var i,e=N[t.authorization];return e?(b.sendEvent(e,"custom.client.load.cached"),e):(e=r(t).then(function(e){return t.debug&&(e.isDebug=!0),i=new M(e)}),N[t.authorization]=e,b.sendEvent(e,"custom.client.load.initialized"),e.then(function(e){return b.sendEvent(i,"custom.client.load.succeeded"),e}).catch(function(e){return delete N[t.authorization],s.reject(e)}))},M.clearCache=function(){N={}},M.prototype._findOrCreateFraudnetJSON=function(e){var t,i,r,n,a=document.querySelector('script[fncls="'+I+'"]');a||((a=document.body.appendChild(document.createElement("script"))).type="application/json",a.setAttribute("fncls",I)),t=this.getConfiguration(),i={rda_tenant:"bt_card",mid:t.gatewayConfiguration.merchantId},(r=m(t.authorization).attrs.authorizationFingerprint)&&r.split("&").forEach(function(e){var t=e.split("=");"customer_id"===t[0]&&1<t.length&&(i.cid=t[1])}),n={f:e.substr(0,32),fp:i,bu:!1,s:D},a.text=JSON.stringify(n)},M.prototype.request=function(d,i){var c=this,e=new s(function(a,o){var e,s,t,i,r,n,l=Boolean("payment_methods/credit_cards"===d.endpoint&&c.getConfiguration().gatewayConfiguration.creditCards.collectDeviceData);if("graphQLApi"!==d.api&&(d.method?d.endpoint||(e="options.endpoint"):e="options.method"),e)throw new u({type:_.CLIENT_OPTION_REQUIRED.type,code:_.CLIENT_OPTION_REQUIRED.code,message:e+" is required when making a request."});if(s="api"in d?d.api:"clientApi",i={method:d.method,graphQL:c._graphQL,timeout:d.timeout,metadata:c._configuration.analyticsMetadata},"clientApi"===s)t=c._clientApiBaseUrl,i.data=y(c._configuration,d.data);else if("braintreeApi"===s){if(!c._braintreeApi)throw new u(C.BRAINTREE_API_ACCESS_RESTRICTED);t=c._braintreeApi.baseUrl,i.data=d.data,i.headers={"Braintree-Version":E.BRAINTREE_API_VERSION_HEADER,Authorization:"Bearer "+c._braintreeApi.accessToken}}else{if("graphQLApi"!==s)throw new u({type:_.CLIENT_OPTION_INVALID.type,code:_.CLIENT_OPTION_INVALID.code,message:"options.api is invalid."});t=P[c._configuration.gatewayConfiguration.environment],d.endpoint="",i.method="post",i.data=v({clientSdkMetadata:{source:c._configuration.analyticsMetadata.source,integration:c._configuration.analyticsMetadata.integration,sessionId:c._configuration.analyticsMetadata.sessionId}},d.data),i.headers=(r=c._configuration.authorization,{Authorization:"Bearer "+((n=m(r).attrs).authorizationFingerprint||n.tokenizationKey),"Braintree-Version":p})}i.url=t+d.endpoint,i.sendAnalyticsEvent=function(e){b.sendEvent(c,e)},c._request(i,function(e,t,i){var r,n;(n=function(e,t){var i;-1===e?i=new u(_.CLIENT_REQUEST_TIMEOUT):403===e?i=new u(_.CLIENT_AUTHORIZATION_INSUFFICIENT):429===e?i=new u(_.CLIENT_RATE_LIMITED):500<=e?i=new u(_.CLIENT_GATEWAY_NETWORK):(e<200||400<=e)&&(i=h(t,{type:_.CLIENT_REQUEST_ERROR.type,code:_.CLIENT_REQUEST_ERROR.code,message:_.CLIENT_REQUEST_ERROR.message}));if(i)return i.details=i.details||{},i.details.httpStatus=e,i}(i,e))?o(n):"graphQLApi"===s&&t.errors?o(h(t.errors,{type:_.CLIENT_GRAPHQL_REQUEST_ERROR.type,code:_.CLIENT_GRAPHQL_REQUEST_ERROR.code,message:_.CLIENT_GRAPHQL_REQUEST_ERROR.message})):(r=v({_httpStatus:i},t),l&&r.creditCards&&0<r.creditCards.length&&(c._findOrCreateFraudnetJSON(r.creditCards[0].nonce),A.loadScript({src:w,forceScriptReload:!0})),a(r))})});return"function"==typeof i?(i=f(g(i)),void e.then(function(e){i(null,e,e._httpStatus)}).catch(function(e){var t=e&&e.details&&e.details.httpStatus;i(e,null,t)})):e},M.prototype.toJSON=function(){return this.getConfiguration()},M.prototype.getVersion=function(){return d},M.prototype.teardown=l(function(){return delete N[this.getConfiguration().authorization],T(this,c(M.prototype)),s.resolve()}),t.exports=M},{"../lib/add-metadata":66,"../lib/analytics":67,"../lib/assets":68,"../lib/assign":69,"../lib/braintree-error":72,"../lib/constants":76,"../lib/convert-methods-to-error":77,"../lib/convert-to-braintree-error":78,"../lib/create-authorization-data":80,"../lib/deferred":82,"../lib/errors":85,"../lib/is-verified-domain":91,"../lib/methods":93,"../lib/once":94,"../lib/promise":95,"./constants":32,"./errors":33,"./get-configuration":34,"./request":46,"./request/graphql":44,"@braintree/wrap-promise":26}],32:[function(e,t,i){"use strict";t.exports={BRAINTREE_API_VERSION_HEADER:"2017-04-03",BRAINTREE_VERSION:"2018-05-10"}},{}],33:[function(e,t,i){"use strict";var r=e("../lib/braintree-error");t.exports={CLIENT_GATEWAY_CONFIGURATION_INVALID_DOMAIN:{type:r.types.MERCHANT,code:"CLIENT_GATEWAY_CONFIGURATION_INVALID_DOMAIN"},CLIENT_OPTION_REQUIRED:{type:r.types.MERCHANT,code:"CLIENT_OPTION_REQUIRED"},CLIENT_OPTION_INVALID:{type:r.types.MERCHANT,code:"CLIENT_OPTION_INVALID"},CLIENT_MISSING_GATEWAY_CONFIGURATION:{type:r.types.INTERNAL,code:"CLIENT_MISSING_GATEWAY_CONFIGURATION",message:"Missing gatewayConfiguration."},CLIENT_INVALID_AUTHORIZATION:{type:r.types.MERCHANT,code:"CLIENT_INVALID_AUTHORIZATION",message:"Authorization is invalid. Make sure your client token or tokenization key is valid."},CLIENT_GATEWAY_NETWORK:{type:r.types.NETWORK,code:"CLIENT_GATEWAY_NETWORK",message:"Cannot contact the gateway at this time."},CLIENT_REQUEST_TIMEOUT:{type:r.types.NETWORK,code:"CLIENT_REQUEST_TIMEOUT",message:"Request timed out waiting for a reply."},CLIENT_REQUEST_ERROR:{type:r.types.NETWORK,code:"CLIENT_REQUEST_ERROR",message:"There was a problem with your request."},CLIENT_GRAPHQL_REQUEST_ERROR:{type:r.types.NETWORK,code:"CLIENT_GRAPHQL_REQUEST_ERROR",message:"There was a problem with your request."},CLIENT_RATE_LIMITED:{type:r.types.MERCHANT,code:"CLIENT_RATE_LIMITED",message:"You are being rate-limited; please try again in a few minutes."},CLIENT_AUTHORIZATION_INSUFFICIENT:{type:r.types.MERCHANT,code:"CLIENT_AUTHORIZATION_INSUFFICIENT",message:"The authorization used has insufficient privileges."}}},{"../lib/braintree-error":72}],34:[function(i,r,e){(function(c){"use strict";var p=i("../lib/braintree-error"),e=i("../lib/promise"),t=i("@braintree/wrap-promise"),u=i("./request"),h=i("../lib/vendor/uuid"),m=i("../lib/constants"),y=i("../lib/create-authorization-data"),f=i("./errors"),g=i("./request/graphql"),v=i("../lib/is-date-string-before-or-on"),b=i("./constants").BRAINTREE_VERSION;r.exports={getConfiguration:t(function(d){return new e(function(n,a){var o,e,s,t,i,r=h(),l={merchantAppId:c.location.host,platform:m.PLATFORM,sdkVersion:m.VERSION,source:m.SOURCE,integration:m.INTEGRATION,integrationType:m.INTEGRATION,sessionId:r};try{e=y(d.authorization)}catch(e){return void a(new p(f.CLIENT_INVALID_AUTHORIZATION))}s=e.attrs,t=e.configUrl,s._meta=l,s.braintreeLibraryVersion=m.BRAINTREE_LIBRARY_VERSION,s.configVersion="3",i={url:t,method:"GET",data:s},s.authorizationFingerprint&&e.graphQL&&(v(e.graphQL.date,b)&&(i.graphQL=new g({graphQL:{url:e.graphQL.url,features:["configuration"]}})),i.metadata=l),u(i,function(e,t,i){var r;if(e)return r=403===i?f.CLIENT_AUTHORIZATION_INSUFFICIENT:f.CLIENT_GATEWAY_NETWORK,void a(new p({type:r.type,code:r.code,message:r.message,details:{originalError:e}}));o={authorization:d.authorization,authorizationType:s.tokenizationKey?"TOKENIZATION_KEY":"CLIENT_TOKEN",analyticsMetadata:l,gatewayConfiguration:t},n(o)})})})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lib/braintree-error":72,"../lib/constants":76,"../lib/create-authorization-data":80,"../lib/is-date-string-before-or-on":89,"../lib/promise":95,"../lib/vendor/uuid":99,"./constants":32,"./errors":33,"./request":46,"./request/graphql":44,"@braintree/wrap-promise":26}],35:[function(e,t,i){"use strict";var r=e("../lib/braintree-error"),n=e("./client"),a=e("../lib/promise"),o=e("@braintree/wrap-promise"),s=e("../lib/errors");t.exports={create:o(function(e){return e.authorization?n.initialize(e):a.reject(new r({type:s.INSTANTIATION_OPTION_REQUIRED.type,code:s.INSTANTIATION_OPTION_REQUIRED.code,message:"options.authorization is required when instantiating a client."}))}),VERSION:"3.42.0"}},{"../lib/braintree-error":72,"../lib/errors":85,"../lib/promise":95,"./client":31,"@braintree/wrap-promise":26}],36:[function(e,t,i){"use strict";var f=e("../../lib/querystring"),g=e("../browser-detection"),v=e("../../lib/assign").assign,b=e("./prep-body"),E=e("./parse-body"),_=e("./xhr"),C=_.isAvailable,P=e("./graphql/request"),T=e("./default-request"),A=1,I=408;function D(r,n,a){var o,s,l,e,t,i,d,c=r.url,p=r.graphQL,u=r.timeout,h=_.getRequestObject(),m=a,y=Boolean(p&&p.isGraphQLRequest(c,r.data));r.headers=v({"Content-Type":"application/json"},r.headers),c=(l=y?new P(r):new T(r)).getUrl(),e=l.getBody(),t=l.getMethod(),i=l.getHeaders(),"GET"===t&&(c=f.queryify(c,e),e=null),C?h.onreadystatechange=function(){if(4===h.readyState){if(0===h.status&&y)return delete r.graphQL,void D(r,n,a);if(d=E(h.responseText),s=l.adaptResponseBody(d),400<=(o=l.determineStatus(h.status,d))||o<200){if(y&&("UNKNOWN"===(i=!(t=d).data&&t.errors&&t.errors[0]&&t.errors[0].extensions&&t.errors[0].extensions.errorClass)||"INTERNAL"===i))return delete r.graphQL,void D(r,n,a);if(n<A&&((!(e=o)||e===I)&&g.isIe()))return void D(r,++n,a);m(s||"error",null,o||500)}else m(null,s,o);var e,t,i}}:(r.headers&&(c=f.queryify(c,i)),h.onload=function(){m(null,E(h.responseText),h.status)},h.onerror=function(){m("error",null,500)},h.onprogress=function(){},h.ontimeout=function(){m("timeout",null,-1)});try{h.open(t,c,!0)}catch(e){if(!y)throw e;return delete r.graphQL,void D(r,n,a)}h.timeout=u,C&&Object.keys(i).forEach(function(e){h.setRequestHeader(e,i[e])});try{h.send(b(t,e))}catch(e){}}t.exports={request:function(e,t){D(e,0,t)}}},{"../../lib/assign":69,"../../lib/querystring":96,"../browser-detection":30,"./default-request":37,"./graphql/request":45,"./parse-body":49,"./prep-body":50,"./xhr":51}],37:[function(e,t,i){"use strict";function r(e){this._url=e.url,this._data=e.data,this._method=e.method,this._headers=e.headers}r.prototype.getUrl=function(){return this._url},r.prototype.getBody=function(){return this._data},r.prototype.getMethod=function(){return this._method},r.prototype.getHeaders=function(){return this._headers},r.prototype.adaptResponseBody=function(e){return e},r.prototype.determineStatus=function(e){return e},t.exports=r},{}],38:[function(e,t,i){(function(e){"use strict";t.exports=function(){return e.navigator.userAgent}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],39:[function(e,t,i){"use strict";var o=e("./error"),s=e("../../../../lib/assign").assign,l={creditCard:{AMERICAN_EXPRESS:"American Express",DISCOVER:"Discover",INTERNATIONAL_MAESTRO:"Maestro",JCB:"JCB",MASTERCARD:"MasterCard",SOLO:"Solo",UK_MAESTRO:"UK Maestro",UNION_PAY:"UnionPay",VISA:"Visa"},applePayWeb:{VISA:"visa",MASTERCARD:"mastercard",DISCOVER:"discover",AMERICAN_EXPRESS:"amex"},visaCheckout:{VISA:"Visa",MASTERCARD:"MasterCard",DISCOVER:"Discover",AMERICAN_EXPRESS:"American Express"},googlePay:{VISA:"visa",MASTERCARD:"mastercard",DISCOVER:"discover",AMERICAN_EXPRESS:"amex"},masterpass:{VISA:"visa",MASTERCARD:"master",DISCOVER:"discover",AMERICAN_EXPRESS:"amex",DINERS:"diners",INTERNATIONAL_MAESTRO:"maestro",JCB:"jcb"}};function d(e,i){return e.reduce(function(e,t){return i.hasOwnProperty(t)?e.concat(i[t]):e},[])}t.exports=function(e,t){return e.data&&!e.errors?(i=e,r=t,a=i.data.clientConfiguration,n={environment:a.environment.toLowerCase(),clientApiUrl:a.clientApiUrl,assetsUrl:a.assetsUrl,analytics:{url:a.analyticsUrl},merchantId:a.merchantId,venmo:"off"},a.supportedFeatures&&(n.graphQL={url:r._graphQL._config.url,features:a.supportedFeatures.map(function(e){return e.toLowerCase()})}),a.braintreeApi&&(n.braintreeApi=a.braintreeApi),a.applePayWeb&&(n.applePayWeb=a.applePayWeb,n.applePayWeb.supportedNetworks=d(a.applePayWeb.supportedCardBrands,l.applePayWeb),delete n.applePayWeb.supportedCardBrands),a.ideal&&(n.ideal=a.ideal),a.kount&&(n.kount={kountMerchantId:a.kount.merchantId}),a.creditCard?(n.challenges=a.creditCard.challenges.map(function(e){return e.toLowerCase()}),n.creditCards={supportedCardTypes:d(a.creditCard.supportedCardBrands,l.creditCard)},n.threeDSecureEnabled=a.creditCard.threeDSecureEnabled):(n.challenges=[],n.creditCards={supportedCardTypes:[]},n.threeDSecureEnabled=!1),a.googlePay&&(n.androidPay={displayName:a.googlePay.displayName,enabled:!0,environment:a.googlePay.environment.toLowerCase(),googleAuthorizationFingerprint:a.googlePay.googleAuthorization,supportedNetworks:d(a.googlePay.supportedCardBrands,l.googlePay)}),a.venmo&&(n.payWithVenmo={merchantId:a.venmo.merchantId,accessToken:a.venmo.accessToken,environment:a.venmo.environment.toLowerCase()}),a.paypal?(n.paypalEnabled=!0,n.paypal=s({},a.paypal),n.paypal.currencyIsoCode=n.paypal.currencyCode,n.paypal.environment=n.paypal.environment.toLowerCase(),delete n.paypal.currencyCode):n.paypalEnabled=!1,a.unionPay&&(n.unionPay={enabled:!0,merchantAccountId:a.unionPay.merchantAccountId}),a.visaCheckout&&(n.visaCheckout={apikey:a.visaCheckout.apiKey,externalClientId:a.visaCheckout.externalClientId,supportedCardTypes:d(a.visaCheckout.supportedCardBrands,l.visaCheckout)}),a.masterpass&&(n.masterpass={merchantCheckoutId:a.masterpass.merchantCheckoutId,supportedNetworks:d(a.masterpass.supportedCardBrands,l.masterpass)}),a.usBankAccount&&(n.usBankAccount={routeId:a.usBankAccount.routeId,plaid:{publicKey:a.usBankAccount.plaidPublicKey}}),n):o(e);var i,r,n,a}},{"../../../../lib/assign":69,"./error":41}],40:[function(e,t,i){"use strict";var o=e("./error"),s={AMERICAN_EXPRESS:"American Express",DINERS:"Discover",DISCOVER:"Discover",INTERNATIONAL_MAESTRO:"Maestro",JCB:"JCB",MASTERCARD:"MasterCard",UK_MAESTRO:"Maestro",UNION_PAY:"Union Pay",VISA:"Visa"},l={YES:"Yes",NO:"No",UNKNOWN:"Unknown"};t.exports=function(e){return e.data&&!e.errors?(t=e,i=t.data.tokenizeCreditCard,r=i.creditCard,n=r.last4?r.last4.substr(2,4):"",a=r.binData,a&&(["commercial","debit","durbinRegulated","healthcare","payroll","prepaid"].forEach(function(e){a[e]?a[e]=l[a[e]]:a[e]="Unknown"}),["issuingBank","countryOfIssuance","productId"].forEach(function(e){a[e]||(a[e]="Unknown")})),{creditCards:[{binData:a,consumed:!1,description:n?"ending in "+n:"",nonce:i.token,details:{cardType:s[r.brandCode]||"Unknown",lastFour:r.last4||"",lastTwo:n},type:"CreditCard",threeDSecureInfo:null}]}):o(e);var t,i,r,n,a}},{"./error":41}],41:[function(e,t,i){"use strict";t.exports=function(e){var t,i,r,n,a,o=e.errors&&e.errors[0]&&e.errors[0].extensions&&e.errors[0].extensions.errorClass;return"VALIDATION"===o?(i=e.errors,r=[],i.forEach(function(e){!function e(t,i,r){var n,a=i.extensions.legacyCode,o=t[0];1!==t.length?(r.forEach(function(e){e.field===o&&(n=e)}),n||(n={field:o,fieldErrors:[]},r.push(n)),e(t.slice(1),i,n.fieldErrors)):r.push({code:a,field:o,message:i.message})}(e.extensions.inputPath.slice(1),e,r)}),{error:{message:(n=t=r,a=n[0].field,{creditCard:"Credit card is invalid"}[a])},fieldErrors:t}):o?{error:{message:e.errors[0].message},fieldErrors:[]}:{error:{message:"There was a problem serving your request"},fieldErrors:[]}}},{}],42:[function(e,t,i){"use strict";t.exports=function(){return{query:"query ClientConfiguration {   clientConfiguration {     analyticsUrl     environment     merchantId     assetsUrl     clientApiUrl     creditCard {       supportedCardBrands       challenges       threeDSecureEnabled     }     applePayWeb {       countryCode       currencyCode       merchantIdentifier       supportedCardBrands     }     googlePay {       displayName       supportedCardBrands       environment       googleAuthorization     }     ideal {       routeId       assetsUrl     }     kount {       merchantId     }     masterpass {       merchantCheckoutId       supportedCardBrands     }     paypal {       displayName       clientId       privacyUrl       userAgreementUrl       assetsUrl       environment       environmentNoNetwork       unvettedMerchant       braintreeClientId       billingAgreementsEnabled       merchantAccountId       currencyCode       payeeEmail     }     unionPay {       merchantAccountId     }     usBankAccount {       routeId       plaidPublicKey     }     venmo {       merchantId       accessToken       environment     }     visaCheckout {       apiKey       externalClientId       supportedCardBrands     }     braintreeApi {       accessToken       url     }     supportedFeatures   } }",operationName:"ClientConfiguration"}}},{}],43:[function(e,t,i){"use strict";var s=e("../../../../lib/assign").assign;function r(e){var t=e.creditCard,i=t&&t.billingAddress,r=t&&t.expirationDate,n=t&&(t.expirationMonth||r&&r.split("/")[0].trim()),a=t&&(t.expirationYear||r&&r.split("/")[1].trim()),o={input:{creditCard:{number:t&&t.number,expirationMonth:n,expirationYear:a,cvv:t&&t.cvv,cardholderName:t&&t.cardholderName},options:{}}};return i&&(o.input.creditCard.billingAddress=i),o.input=function(e,t){var i;e.creditCard&&e.creditCard.options&&"boolean"==typeof e.creditCard.options.validate?i=e.creditCard.options.validate:e.authorizationFingerprint&&e.tokenizationKey||e.authorizationFingerprint?i=!0:e.tokenizationKey&&(i=!1);"boolean"==typeof i&&(t.options=s({validate:i},t.options));return t}(e,o.input),o}t.exports=function(e){return{query:"mutation TokenizeCreditCard($input: TokenizeCreditCardInput!) {   tokenizeCreditCard(input: $input) {     token     creditCard {       brandCode       last4       binData {         prepaid         healthcare         debit         durbinRegulated         commercial         payroll         issuingBank         countryOfIssuance         productId       }     }   } }",variables:r(e),operationName:"TokenizeCreditCard"}}},{"../../../../lib/assign":69}],44:[function(e,t,i){"use strict";var a=e("../../browser-detection"),o={tokenize_credit_cards:"payment_methods/credit_cards",configuration:"configuration"},s=["creditCard.options.unionPayEnrollment"];function r(e){this._config=e.graphQL}r.prototype.getGraphQLEndpoint=function(){return this._config.url},r.prototype.isGraphQLRequest=function(e,t){var i,r,n=this.getClientApiPath(e);return!(!this._isGraphQLEnabled()||!n||a.isIe9())&&(i=this._config.features.some(function(e){return o[e]===n}),r=t,!s.some(function(e){var t=e.split(".").reduce(function(e,t){return e&&e[t]},r);return void 0!==t})&&i)},r.prototype.getClientApiPath=function(e){var t,i=e.split("/client_api/v1/");return 1<i.length&&(t=i[1].split("?")[0]),t},r.prototype._isGraphQLEnabled=function(){return Boolean(this._config)},t.exports=r},{"../../browser-detection":30}],45:[function(e,t,i){"use strict";var r=e("../../constants").BRAINTREE_VERSION,n=e("../../../lib/assign").assign,a=e("./generators/credit-card-tokenization"),o=e("./adapters/credit-card-tokenization"),s=e("./generators/configuration"),l=e("./adapters/configuration"),d={"payment_methods/credit_cards":a,configuration:s},c={"payment_methods/credit_cards":o,configuration:l};function p(e){var t=e.graphQL.getClientApiPath(e.url);this._graphQL=e.graphQL,this._data=e.data,this._method=e.method,this._headers=e.headers,this._clientSdkMetadata={source:e.metadata.source,integration:e.metadata.integration,sessionId:e.metadata.sessionId},this._sendAnalyticsEvent=e.sendAnalyticsEvent||Function.prototype,this._generator=d[t],this._adapter=c[t],this._sendAnalyticsEvent("graphql.init")}function u(e){return-1===e.indexOf("_")?e:e.toLowerCase().replace(/(\_\w)/g,function(e){return e[1].toUpperCase()})}p.prototype.getUrl=function(){return this._graphQL.getGraphQLEndpoint()},p.prototype.getBody=function(){var e=function i(r){var n={};Object.keys(r).forEach(function(e){var t=u(e);"object"==typeof r[e]?n[t]=i(r[e]):"number"==typeof r[e]?n[t]=String(r[e]):n[t]=r[e]});return n}(this._data),t=this._generator(e),i=n({clientSdkMetadata:this._clientSdkMetadata},t);return JSON.stringify(i)},p.prototype.getMethod=function(){return"POST"},p.prototype.getHeaders=function(){var e;return e={Authorization:"Bearer "+(this._data.authorizationFingerprint?(this._sendAnalyticsEvent("graphql.authorization-fingerprint"),this._data.authorizationFingerprint):(this._sendAnalyticsEvent("graphql.tokenization-key"),this._data.tokenizationKey)),"Braintree-Version":r},n({},this._headers,e)},p.prototype.adaptResponseBody=function(e){return this._adapter(e,this)},p.prototype.determineStatus=function(e,t){var i,r,n;return i=200===e?(r=t.errors&&t.errors[0]&&t.errors[0].extensions&&t.errors[0].extensions.errorClass,t.data&&!t.errors?200:"VALIDATION"===r?422:"AUTHORIZATION"===r?403:"AUTHENTICATION"===r?401:(n=t,!r&&n.errors[0].message?403:500)):e||500,this._sendAnalyticsEvent("graphql.status."+e),this._sendAnalyticsEvent("graphql.determinedStatus."+i),i},t.exports=p},{"../../../lib/assign":69,"../../constants":32,"./adapters/configuration":39,"./adapters/credit-card-tokenization":40,"./generators/configuration":42,"./generators/credit-card-tokenization":43}],46:[function(e,t,i){"use strict";var r,n=e("../../lib/once"),a=e("./jsonp-driver"),o=e("./ajax-driver"),s=e("./get-user-agent"),l=e("./is-http");t.exports=function(e,t){t=n(t||Function.prototype),e.method=(e.method||"GET").toUpperCase(),e.timeout=null==e.timeout?6e4:e.timeout,e.data=e.data||{},null==r&&(r=!(l()&&/MSIE\s(8|9)/.test(s()))),r?o.request(e,t):a.request(e,t)}},{"../../lib/once":94,"./ajax-driver":36,"./get-user-agent":38,"./is-http":47,"./jsonp-driver":48}],47:[function(e,t,i){(function(e){"use strict";t.exports=function(){return"http:"===e.location.protocol}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],48:[function(e,t,i){(function(g){"use strict";var v,b=e("../../lib/vendor/uuid"),E=e("../../lib/querystring"),_={};function C(t){try{delete g[t]}catch(e){g[t]=null}}t.exports={request:function(e,t){var i,r,n,a,o,s,l,d,c,p,u="callback_json_"+b().replace(/-/g,""),h=e.url,m=e.data,y=e.method,f=e.timeout;h=E.queryify(h,m),h=E.queryify(h,{_method:y,callback:u}),r=h,n=u,a=document.createElement("script"),o=!1,a.src=r,a.async=!0,a.onerror=function(){g[n]({message:"error",status:500})},a.onload=a.onreadystatechange=function(){o||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(o=!0,a.onload=a.onreadystatechange=null)},s=i=a,l=t,g[d=u]=function(e){var t,i=e.status||500,r=null,n=null;delete e.status,400<=i||i<200?r=e:n=e,C(d),(t=s)&&t.parentNode&&t.parentNode.removeChild(t),clearTimeout(_[d]),l(r,n,i)},c=f,_[p=u]=setTimeout(function(){_[p]=null,g[p]({error:"timeout",status:-1}),g[p]=function(){C(p)}},c),v||(v=document.getElementsByTagName("head")[0]),v.appendChild(i)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../lib/querystring":96,"../../lib/vendor/uuid":99}],49:[function(e,t,i){"use strict";t.exports=function(e){try{e=JSON.parse(e)}catch(e){}return e}},{}],50:[function(e,t,i){"use strict";t.exports=function(e,t){if("string"!=typeof e)throw new Error("Method must be a string");return"get"!==e.toLowerCase()&&null!=t&&(t="string"==typeof t?t:JSON.stringify(t)),t}},{}],51:[function(e,i,t){(function(e){"use strict";var t=e.XMLHttpRequest&&"withCredentials"in new e.XMLHttpRequest;i.exports={isAvailable:t,getRequestObject:function(){return t?new XMLHttpRequest:new XDomainRequest}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,i){"use strict";var r=e("../lib/braintree-error");t.exports={GOOGLE_PAYMENT_NOT_ENABLED:{type:r.types.MERCHANT,code:"GOOGLE_PAYMENT_NOT_ENABLED",message:"Google Pay is not enabled for this merchant."},GOOGLE_PAYMENT_GATEWAY_ERROR:{code:"GOOGLE_PAYMENT_GATEWAY_ERROR",message:"There was an error when tokenizing the Google Pay payment method.",type:r.types.UNKNOWN}}},{"../lib/braintree-error":72}],53:[function(e,t,i){"use strict";var o=e("../lib/analytics"),s=e("../lib/assign").assign,r=e("../lib/convert-methods-to-error"),l=e("../lib/find"),n=e("../lib/generate-google-pay-configuration"),d=e("../lib/braintree-error"),c=e("./errors"),a=e("../lib/methods"),p=e("../lib/promise"),u=e("@braintree/wrap-promise"),h=["AMEX","DISCOVER","MASTERCARD","VISA"];function m(e){this._client=e.client,this._googlePayVersion=e.googlePayVersion||1,this._googleMerchantId=e.googleMerchantId}m.prototype._createV1PaymentDataRequest=function(e,t){var i=t.cardRequirements&&t.cardRequirements.allowedCardNetworks,r=e.cardRequirements.allowedCardNetworks,n=i||r;return(t=s({},e,t)).cardRequirements.allowedCardNetworks=n,t},m.prototype._createV2PaymentDataRequest=function(e,t){var i,r,n,a=e.allowedPaymentMethods;return t.allowedPaymentMethods&&(i=l(t.allowedPaymentMethods,"type","CARD"),r=l(a,"type","CARD"),i&&(i.parameters=s({},i.parameters),(!(n=i.parameters).allowedCardNetworks||n.allowedCardNetworks&&0===n.allowedCardNetworks.length)&&(r&&r.parameters&&r.parameters.allowedCardNetworks?n.allowedCardNetworks=r.parameters.allowedCardNetworks:n.allowedCardNetworks=h))),t=s({},e,t)},m.prototype.createPaymentDataRequest=function(e){var t=s({},e),i=n(this._client.getConfiguration(),this._googlePayVersion,this._googleMerchantId);return 2===this._googlePayVersion?(t=this._createV2PaymentDataRequest(i,t),o.sendEvent(this._client,"google-payment.v2.createPaymentDataRequest")):(t=this._createV1PaymentDataRequest(i,t),o.sendEvent(this._client,"google-payment.v1.createPaymentDataRequest")),t},m.prototype.parseResponse=function(n){var a=this._client;return p.resolve().then(function(){var e,t=2===n.apiVersion?n.paymentMethodData.tokenizationData.token:n.paymentMethodToken.token,i=JSON.parse(t),r=i.error;return r?p.reject(r):(o.sendEvent(a,"google-payment.parseResponse.succeeded"),i.paypalAccounts?(e=i.paypalAccounts[0],o.sendEvent(a,"google-payment.parseResponse.succeeded.paypal"),p.resolve({nonce:e.nonce,type:e.type,description:e.description})):(e=i.androidPayCards[0],o.sendEvent(a,"google-payment.parseResponse.succeeded.google-payment"),p.resolve({nonce:e.nonce,type:e.type,description:e.description,details:{cardType:e.details.cardType,lastFour:e.details.lastFour,lastTwo:e.details.lastTwo},binData:e.binData})))}).catch(function(e){return o.sendEvent(a,"google-payment.parseResponse.failed"),p.reject(new d({code:c.GOOGLE_PAYMENT_GATEWAY_ERROR.code,message:c.GOOGLE_PAYMENT_GATEWAY_ERROR.message,type:c.GOOGLE_PAYMENT_GATEWAY_ERROR.type,details:{originalError:e}}))})},m.prototype.teardown=function(){return r(this,a(m.prototype)),p.resolve()},t.exports=u.wrapPrototype(m)},{"../lib/analytics":67,"../lib/assign":69,"../lib/braintree-error":72,"../lib/convert-methods-to-error":77,"../lib/find":87,"../lib/generate-google-pay-configuration":88,"../lib/methods":93,"../lib/promise":95,"./errors":52,"@braintree/wrap-promise":26}],54:[function(e,t,i){"use strict";var r=e("../lib/basic-component-verification"),n=e("../lib/braintree-error"),a=e("./errors"),o=e("./google-payment"),s=e("../lib/create-deferred-client"),l=e("../lib/create-assets-url"),d=e("../lib/promise"),c=e("@braintree/wrap-promise");t.exports={create:c(function(t){var e="Google Pay";return r.verify({name:e,client:t.client,authorization:t.authorization}).then(function(){return s.create({authorization:t.authorization,client:t.client,debug:t.debug,assetsUrl:l.create(t.authorization),name:e})}).then(function(e){return t.client=e,t.client.getConfiguration().gatewayConfiguration.androidPay?new o(t):d.reject(new n(a.GOOGLE_PAYMENT_NOT_ENABLED))})}),VERSION:"3.42.0"}},{"../lib/basic-component-verification":70,"../lib/braintree-error":72,"../lib/create-assets-url":79,"../lib/create-deferred-client":81,"../lib/promise":95,"./errors":52,"./google-payment":53,"@braintree/wrap-promise":26}],55:[function(e,t,i){"use strict";var a=e("../../lib/braintree-error"),o=e("../shared/errors"),s=e("../shared/constants").allowedAttributes;t.exports=function(e,t){var i;return s.hasOwnProperty(e)?null==t||(r=e,n=t,"string"===s[r]?"string"==typeof n||"number"==typeof n:"boolean"===s[r]&&("true"===String(n)||"false"===String(n)))||(i=new a({type:o.HOSTED_FIELDS_ATTRIBUTE_VALUE_NOT_ALLOWED.type,code:o.HOSTED_FIELDS_ATTRIBUTE_VALUE_NOT_ALLOWED.code,message:'Value "'+t+'" is not allowed for "'+e+'" attribute.'})):i=new a({type:o.HOSTED_FIELDS_ATTRIBUTE_NOT_SUPPORTED.type,code:o.HOSTED_FIELDS_ATTRIBUTE_NOT_SUPPORTED.code,message:'The "'+e+'" attribute is not supported in Hosted Fields.'}),i;var r,n}},{"../../lib/braintree-error":72,"../shared/constants":62,"../shared/errors":63}],56:[function(e,t,i){"use strict";var r=e("../shared/constants"),n=e("../../lib/use-min");t.exports=function(e,t,i){return e+"/web/"+r.VERSION+"/html/hosted-fields-frame"+n(i)+".html#"+t}},{"../../lib/use-min":97,"../shared/constants":62}],57:[function(e,t,i){(function(n){"use strict";var a=e("../shared/constants").allowedStyles;t.exports=function(e){var i,t=document.createElement("input"),r={};return"."===e[0]&&(e=e.substring(1)),t.className=e,t.style.display="none !important",t.style.position="fixed !important",t.style.left="-99999px !important",t.style.top="-99999px !important",n.document.body.appendChild(t),i=n.getComputedStyle(t),a.forEach(function(e){var t=i[e];t&&(r[e]=t)}),n.document.body.removeChild(t),r}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../shared/constants":62}],58:[function(e,t,i){"use strict";var u=e("../../lib/assign").assign,h=e("../../lib/create-assets-url"),m=e("../../lib/destructor"),y=e("@braintree/class-list"),f=e("@braintree/iframer"),g=e("../../lib/bus"),v=e("../../lib/create-deferred-client"),b=e("../../lib/braintree-error"),E=e("./compose-url"),_=e("./get-styles-from-class"),C=e("../shared/constants"),P=e("../shared/errors"),T=e("../../lib/constants").INTEGRATION_TIMEOUT_MS,A=e("../../lib/vendor/uuid"),s=e("../shared/find-parent-tags"),I=e("../shared/browser-detection"),D=C.events,w=e("../../lib/event-emitter"),N=e("./inject-frame"),M=e("../../lib/analytics"),r=C.allowedFields,F=e("../../lib/methods"),L=e("../../lib/convert-methods-to-error"),S=e("../../lib/errors"),O=e("../shared/get-card-types"),n=e("./attribute-validation-error"),k=e("../../lib/promise"),a=e("@braintree/wrap-promise");function V(a){return function(e){var t,i=e.merchantPayload,r=i.emittedBy,n=a[r].containerElement;Object.keys(i.fields).forEach(function(e){i.fields[e].container=a[e].containerElement}),t=i.fields[r],"blur"===e.type&&function(e){var t;if(!I.isIos())return;document.activeElement===document.body&&((t=e.querySelector("input"))||((t=document.createElement("input")).type="button",t.style.height="0px",t.style.width="0px",t.style.opacity="0",t.style.padding="0",t.style.position="absolute",t.style.left="-200%",t.style.top="0px",e.insertBefore(t,e.firstChild)),t.focus(),t.blur())}(n),y.toggle(n,C.externalClasses.FOCUSED,t.isFocused),y.toggle(n,C.externalClasses.VALID,t.isValid),y.toggle(n,C.externalClasses.INVALID,!t.isPotentiallyValid),this._state={cards:i.cards,fields:i.fields},this._emit(e.type,i)}}function R(a){var i,e,t,r,o,n=this,s={},l=u({},a),d={},c=[],p=A();if(r=a.client?(t=(e=a.client.getConfiguration()).gatewayConfiguration.assetsUrl,e.isDebug):(t=h.create(a.authorization),Boolean(a.isDebug)),this._clientPromise=v.create({client:a.client,authorization:a.authorization,debug:r,assetsUrl:t,name:"Hosted Fields"}),o=E(t,p,r),!a.fields||0===Object.keys(a.fields).length)throw new b({type:S.INSTANTIATION_OPTION_REQUIRED.type,code:S.INSTANTIATION_OPTION_REQUIRED.code,message:"options.fields is required when instantiating Hosted Fields."});w.call(this),this._injectedNodes=[],this._destructor=new m,this._fields=s,this._state={fields:{},cards:O("")},this._bus=new g({channel:p,merchantUrl:location.href}),this._destructor.registerFunctionForTeardown(function(){n._bus.teardown()}),M.sendEvent(this._clientPromise,"custom.hosted-fields.initialized"),Object.keys(a.fields).forEach(function(t){var e,i,r,n;if(!C.allowedFields.hasOwnProperty(t))throw new b({type:P.HOSTED_FIELDS_INVALID_FIELD_KEY.type,code:P.HOSTED_FIELDS_INVALID_FIELD_KEY.code,message:'"'+t+'" is not a valid field.'});if(e=a.fields[t],!(i=document.querySelector(e.selector)))throw new b({type:P.HOSTED_FIELDS_INVALID_FIELD_SELECTOR.type,code:P.HOSTED_FIELDS_INVALID_FIELD_SELECTOR.code,message:P.HOSTED_FIELDS_INVALID_FIELD_SELECTOR.message,details:{fieldSelector:e.selector,fieldKey:t}});if(i.querySelector('iframe[name^="braintree-"]'))throw new b({type:P.HOSTED_FIELDS_FIELD_DUPLICATE_IFRAME.type,code:P.HOSTED_FIELDS_FIELD_DUPLICATE_IFRAME.code,message:P.HOSTED_FIELDS_FIELD_DUPLICATE_IFRAME.message,details:{fieldSelector:e.selector,fieldKey:t}});if(e.maxlength&&"number"!=typeof e.maxlength)throw new b({type:P.HOSTED_FIELDS_FIELD_PROPERTY_INVALID.type,code:P.HOSTED_FIELDS_FIELD_PROPERTY_INVALID.code,message:"The value for maxlength must be a number.",details:{fieldKey:t}});if(e.minlength&&"number"!=typeof e.minlength)throw new b({type:P.HOSTED_FIELDS_FIELD_PROPERTY_INVALID.type,code:P.HOSTED_FIELDS_FIELD_PROPERTY_INVALID.code,message:"The value for minlength must be a number.",details:{fieldKey:t}});r=f({type:t,name:"braintree-hosted-field-"+t,style:C.defaultIFrameStyle,title:"Secure Credit Card Frame - "+C.allowedFields[t].label}),this._injectedNodes.push.apply(this._injectedNodes,N(r,i)),this._setupLabelFocus(t,i),s[t]={frameElement:r,containerElement:i},n=new k(function(e){d[t]=e}),c.push(n),this._state.fields[t]={isEmpty:!0,isValid:!1,isPotentiallyValid:!0,isFocused:!1,container:i},setTimeout(function(){I.isIE()||I.isEdge()?(r.src="about:blank",setTimeout(function(){r.src=o},0)):r.src=o},0)}.bind(this)),l.styles&&Object.keys(l.styles).forEach(function(e){var t=l.styles[e];"string"==typeof t&&(l.styles[e]=_(t))}),this._bus.on(D.READY_FOR_CLIENT,function(t){n._clientPromise.then(function(e){t(e)})}),i=setTimeout(function(){M.sendEvent(n._clientPromise,"custom.hosted-fields.load.timed-out"),n._emit("timeout")},T),k.all(c).then(function(e){var t=e[0];clearTimeout(i),t(l),n._emit("ready")}),this._bus.on(D.FRAME_READY,function(e,t){d[e.field](t)}),this._bus.on(D.INPUT_EVENT,V(s).bind(this)),this._destructor.registerFunctionForTeardown(function(){var e,t,i;for(e=0;e<n._injectedNodes.length;e++)(i=(t=n._injectedNodes[e]).parentNode).removeChild(t),y.remove(i,C.externalClasses.FOCUSED,C.externalClasses.INVALID,C.externalClasses.VALID)}),this._destructor.registerFunctionForTeardown(function(){var e=F(R.prototype).concat(F(w.prototype));L(n,e)})}(R.prototype=Object.create(w.prototype,{constructor:R}))._setupLabelFocus=function(e,t){var i,r,n=I.isIos(),a=this._bus;if(!n&&null!=t.id){for(i=(i=Array.prototype.slice.call(document.querySelectorAll('label[for="'+t.id+'"]'))).concat(s(t,"label")),r=0;r<i.length;r++)i[r].addEventListener("click",o,!1);this._destructor.registerFunctionForTeardown(function(){for(r=0;r<i.length;r++)i[r].removeEventListener("click",o,!1)})}function o(){a.emit(D.TRIGGER_INPUT_FOCUS,e)}},R.prototype._attachInvalidFieldContainersToError=function(t){t.details&&t.details.invalidFieldKeys&&0<t.details.invalidFieldKeys.length&&(t.details.invalidFields={},t.details.invalidFieldKeys.forEach(function(e){t.details.invalidFields[e]=this._fields[e].containerElement}.bind(this)))},R.prototype.teardown=function(){var r=this;return new k(function(t,i){r._destructor.teardown(function(e){M.sendEvent(r._clientPromise,"custom.hosted-fields.teardown-completed"),e?i(e):t()})})},R.prototype.tokenize=function(e){var a=this;return e||(e={}),new k(function(r,n){a._bus.emit(D.TOKENIZATION_REQUEST,e,function(e){var t=e[0],i=e[1];t?(a._attachInvalidFieldContainersToError(t),n(new b(t))):r(i)})})},R.prototype.addClass=function(e,t){var i;return r.hasOwnProperty(e)?this._fields.hasOwnProperty(e)?this._bus.emit(D.ADD_CLASS,e,t):i=new b({type:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.type,code:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.code,message:'Cannot add class to "'+e+'" field because it is not part of the current Hosted Fields options.'}):i=new b({type:P.HOSTED_FIELDS_FIELD_INVALID.type,code:P.HOSTED_FIELDS_FIELD_INVALID.code,message:'"'+e+'" is not a valid field. You must use a valid field option when adding a class.'}),i?k.reject(i):k.resolve()},R.prototype.removeClass=function(e,t){var i;return r.hasOwnProperty(e)?this._fields.hasOwnProperty(e)?this._bus.emit(D.REMOVE_CLASS,e,t):i=new b({type:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.type,code:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.code,message:'Cannot remove class from "'+e+'" field because it is not part of the current Hosted Fields options.'}):i=new b({type:P.HOSTED_FIELDS_FIELD_INVALID.type,code:P.HOSTED_FIELDS_FIELD_INVALID.code,message:'"'+e+'" is not a valid field. You must use a valid field option when removing a class.'}),i?k.reject(i):k.resolve()},R.prototype.setAttribute=function(e){var t,i;return r.hasOwnProperty(e.field)?this._fields.hasOwnProperty(e.field)?(t=n(e.attribute,e.value))?i=t:this._bus.emit(D.SET_ATTRIBUTE,e.field,e.attribute,e.value):i=new b({type:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.type,code:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.code,message:'Cannot set attribute for "'+e.field+'" field because it is not part of the current Hosted Fields options.'}):i=new b({type:P.HOSTED_FIELDS_FIELD_INVALID.type,code:P.HOSTED_FIELDS_FIELD_INVALID.code,message:'"'+e.field+'" is not a valid field. You must use a valid field option when setting an attribute.'}),i?k.reject(i):k.resolve()},R.prototype.setMessage=function(e){this._bus.emit(D.SET_MESSAGE,e.field,e.message)},R.prototype.removeAttribute=function(e){var t,i;return r.hasOwnProperty(e.field)?this._fields.hasOwnProperty(e.field)?(t=n(e.attribute))?i=t:this._bus.emit(D.REMOVE_ATTRIBUTE,e.field,e.attribute):i=new b({type:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.type,code:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.code,message:'Cannot remove attribute for "'+e.field+'" field because it is not part of the current Hosted Fields options.'}):i=new b({type:P.HOSTED_FIELDS_FIELD_INVALID.type,code:P.HOSTED_FIELDS_FIELD_INVALID.code,message:'"'+e.field+'" is not a valid field. You must use a valid field option when removing an attribute.'}),i?k.reject(i):k.resolve()},R.prototype.setPlaceholder=function(e,t){return this.setAttribute({field:e,attribute:"placeholder",value:t})},R.prototype.clear=function(e){var t;return r.hasOwnProperty(e)?this._fields.hasOwnProperty(e)?this._bus.emit(D.CLEAR_FIELD,e):t=new b({type:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.type,code:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.code,message:'Cannot clear "'+e+'" field because it is not part of the current Hosted Fields options.'}):t=new b({type:P.HOSTED_FIELDS_FIELD_INVALID.type,code:P.HOSTED_FIELDS_FIELD_INVALID.code,message:'"'+e+'" is not a valid field. You must use a valid field option when clearing a field.'}),t?k.reject(t):k.resolve()},R.prototype.focus=function(e){var t;return r.hasOwnProperty(e)?this._fields.hasOwnProperty(e)?this._bus.emit(D.TRIGGER_INPUT_FOCUS,e):t=new b({type:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.type,code:P.HOSTED_FIELDS_FIELD_NOT_PRESENT.code,message:'Cannot focus "'+e+'" field because it is not part of the current Hosted Fields options.'}):t=new b({type:P.HOSTED_FIELDS_FIELD_INVALID.type,code:P.HOSTED_FIELDS_FIELD_INVALID.code,message:'"'+e+'" is not a valid field. You must use a valid field option when focusing a field.'}),t?k.reject(t):k.resolve()},R.prototype.getState=function(){return this._state},t.exports=a.wrapPrototype(R)},{"../../lib/analytics":67,"../../lib/assign":69,"../../lib/braintree-error":72,"../../lib/bus":75,"../../lib/constants":76,"../../lib/convert-methods-to-error":77,"../../lib/create-assets-url":79,"../../lib/create-deferred-client":81,"../../lib/destructor":83,"../../lib/errors":85,"../../lib/event-emitter":86,"../../lib/methods":93,"../../lib/promise":95,"../../lib/vendor/uuid":99,"../shared/browser-detection":61,"../shared/constants":62,"../shared/errors":63,"../shared/find-parent-tags":64,"../shared/get-card-types":65,"./attribute-validation-error":55,"./compose-url":56,"./get-styles-from-class":57,"./inject-frame":59,"@braintree/class-list":18,"@braintree/iframer":19,"@braintree/wrap-promise":26}],59:[function(e,t,i){"use strict";t.exports=function(e,t){var i=document.createElement("div"),r=document.createDocumentFragment();return i.style.clear="both",r.appendChild(e),r.appendChild(i),t.appendChild(r),[e,i]}},{}],60:[function(e,t,i){"use strict";var r=e("./external/hosted-fields"),n=e("../lib/basic-component-verification"),a=e("./shared/errors"),o=e("restricted-input/supports-input-formatting"),s=e("@braintree/wrap-promise"),l=e("../lib/braintree-error"),d=e("../lib/promise");t.exports={supportsInputFormatting:o,create:s(function(e){return n.verify({name:"Hosted Fields",authorization:e.authorization,client:e.client}).then(function(){var i=new r(e);return new d(function(e,t){i.on("ready",function(){e(i)}),i.on("timeout",function(){t(new l(a.HOSTED_FIELDS_TIMEOUT))})})})}),VERSION:"3.42.0"}},{"../lib/basic-component-verification":70,"../lib/braintree-error":72,"../lib/promise":95,"./external/hosted-fields":58,"./shared/errors":63,"@braintree/wrap-promise":26,"restricted-input/supports-input-formatting":123}],61:[function(e,t,i){"use strict";t.exports={isIE:e("@braintree/browser-detection/is-ie"),isEdge:e("@braintree/browser-detection/is-edge"),isIe9:e("@braintree/browser-detection/is-ie9"),isIos:e("@braintree/browser-detection/is-ios"),isIosWebview:e("@braintree/browser-detection/is-ios-webview")}},{"@braintree/browser-detection/is-edge":7,"@braintree/browser-detection/is-ie":8,"@braintree/browser-detection/is-ie9":11,"@braintree/browser-detection/is-ios":15,"@braintree/browser-detection/is-ios-webview":14}],62:[function(e,t,i){"use strict";var r=e("../../lib/enumerate"),n=e("./errors"),a={VERSION:"3.42.0",maxExpirationYearAge:19,externalEvents:{FOCUS:"focus",BLUR:"blur",EMPTY:"empty",NOT_EMPTY:"notEmpty",VALIDITY_CHANGE:"validityChange",CARD_TYPE_CHANGE:"cardTypeChange"},defaultMaxLengths:{number:19,postalCode:8,expirationDate:7,expirationMonth:2,expirationYear:4,cvv:3},externalClasses:{FOCUSED:"braintree-hosted-fields-focused",INVALID:"braintree-hosted-fields-invalid",VALID:"braintree-hosted-fields-valid"},defaultIFrameStyle:{border:"none",width:"100%",height:"100%",float:"left"},tokenizationErrorCodes:{81724:n.HOSTED_FIELDS_TOKENIZATION_FAIL_ON_DUPLICATE,81736:n.HOSTED_FIELDS_TOKENIZATION_CVV_VERIFICATION_FAILED},allowedStyles:["-moz-appearance","-moz-osx-font-smoothing","-moz-tap-highlight-color","-moz-transition","-webkit-appearance","-webkit-font-smoothing","-webkit-tap-highlight-color","-webkit-transition","appearance","color","direction","font","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-weight","letter-spacing","line-height","padding","opacity","outline","text-shadow","transition"],allowedFields:{number:{name:"credit-card-number",label:"Credit Card Number"},cvv:{name:"cvv",label:"CVV"},expirationDate:{name:"expiration",label:"Expiration Date"},expirationMonth:{name:"expiration-month",label:"Expiration Month"},expirationYear:{name:"expiration-year",label:"Expiration Year"},postalCode:{name:"postal-code",label:"Postal Code"}},allowedAttributes:{"aria-invalid":"boolean","aria-required":"boolean",disabled:"boolean",placeholder:"string"},autocompleteMappings:{"credit-card-number":"cc-number",expiration:"cc-exp","expiration-month":"cc-exp-month","expiration-year":"cc-exp-year",cvv:"cc-csc","postal-code":"billing postal-code"}};a.events=r(["READY_FOR_CLIENT","FRAME_READY","VALIDATE_STRICT","CONFIGURATION","TOKENIZATION_REQUEST","INPUT_EVENT","TRIGGER_INPUT_FOCUS","ADD_CLASS","REMOVE_CLASS","SET_ATTRIBUTE","REMOVE_ATTRIBUTE","CLEAR_FIELD","AUTOFILL_EXPIRATION_DATE","SET_MESSAGE"],"hosted-fields:"),t.exports=a},{"../../lib/enumerate":84,"./errors":63}],63:[function(e,t,i){"use strict";var r=e("../../lib/braintree-error");t.exports={HOSTED_FIELDS_TIMEOUT:{type:r.types.UNKNOWN,code:"HOSTED_FIELDS_TIMEOUT",message:"Hosted Fields timed out when attempting to set up."},HOSTED_FIELDS_INVALID_FIELD_KEY:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_INVALID_FIELD_KEY"},HOSTED_FIELDS_INVALID_FIELD_SELECTOR:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_INVALID_FIELD_SELECTOR",message:"Selector does not reference a valid DOM node."},HOSTED_FIELDS_FIELD_DUPLICATE_IFRAME:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_FIELD_DUPLICATE_IFRAME",message:"Element already contains a Braintree iframe."},HOSTED_FIELDS_FIELD_INVALID:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_FIELD_INVALID"},HOSTED_FIELDS_FIELD_NOT_PRESENT:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_FIELD_NOT_PRESENT"},HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR:{type:r.types.NETWORK,code:"HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR",message:"A tokenization network error occurred."},HOSTED_FIELDS_TOKENIZATION_FAIL_ON_DUPLICATE:{type:r.types.CUSTOMER,code:"HOSTED_FIELDS_TOKENIZATION_FAIL_ON_DUPLICATE",message:"This credit card already exists in the merchant's vault."},HOSTED_FIELDS_TOKENIZATION_CVV_VERIFICATION_FAILED:{type:r.types.CUSTOMER,code:"HOSTED_FIELDS_TOKENIZATION_CVV_VERIFICATION_FAILED",message:"CVV verification failed during tokenization."},HOSTED_FIELDS_FAILED_TOKENIZATION:{type:r.types.CUSTOMER,code:"HOSTED_FIELDS_FAILED_TOKENIZATION",message:"The supplied card data failed tokenization."},HOSTED_FIELDS_FIELDS_EMPTY:{type:r.types.CUSTOMER,code:"HOSTED_FIELDS_FIELDS_EMPTY",message:"All fields are empty. Cannot tokenize empty card fields."},HOSTED_FIELDS_FIELDS_INVALID:{type:r.types.CUSTOMER,code:"HOSTED_FIELDS_FIELDS_INVALID",message:"Some payment input fields are invalid. Cannot tokenize invalid card fields."},HOSTED_FIELDS_ATTRIBUTE_NOT_SUPPORTED:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_ATTRIBUTE_NOT_SUPPORTED"},HOSTED_FIELDS_ATTRIBUTE_VALUE_NOT_ALLOWED:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_ATTRIBUTE_VALUE_NOT_ALLOWED"},HOSTED_FIELDS_FIELD_PROPERTY_INVALID:{type:r.types.MERCHANT,code:"HOSTED_FIELDS_FIELD_PROPERTY_INVALID"}}},{"../../lib/braintree-error":72}],64:[function(e,t,i){"use strict";t.exports=function(e,t){for(var i=e.parentNode,r=[];null!=i;)null!=i.tagName&&i.tagName.toLowerCase()===t&&r.push(i),i=i.parentNode;return r}},{}],65:[function(e,t,i){"use strict";var r=e("credit-card-type");t.exports=function(e){var t=r(e);return t.forEach(function(e){"mastercard"===e.type&&(e.type="master-card")}),t}},{"credit-card-type":118}],66:[function(e,t,i){"use strict";var o=e("./create-authorization-data"),s=e("./json-clone"),l=e("./constants");t.exports=function(e,t){var i,r=t?s(t):{},n=o(e.authorization).attrs,a=s(e.analyticsMetadata);for(i in r.braintreeLibraryVersion=l.BRAINTREE_LIBRARY_VERSION,r._meta)r._meta.hasOwnProperty(i)&&(a[i]=r._meta[i]);return r._meta=a,n.tokenizationKey?r.tokenizationKey=n.tokenizationKey:r.authorizationFingerprint=n.authorizationFingerprint,r}},{"./constants":76,"./create-authorization-data":80,"./json-clone":92}],67:[function(e,t,i){"use strict";var r=e("./promise"),d=e("./constants"),c=e("./add-metadata");function p(e){return Math.floor(e/1e3)}t.exports={sendEvent:function(e,o,s){var l=p(Date.now());return r.resolve(e).then(function(e){var t=p(Date.now()),i=e.getConfiguration(),r=e._request,n=i.gatewayConfiguration.analytics.url,a={analytics:[{kind:d.ANALYTICS_PREFIX+o,isAsync:t!==l,timestamp:l}]};r({url:n,method:"post",data:c(i,a),timeout:d.ANALYTICS_REQUEST_TIMEOUT_MS},s)})}}},{"./add-metadata":66,"./constants":76,"./promise":95}],68:[function(e,t,i){"use strict";var r=e("@braintree/asset-loader/load-script");t.exports={loadScript:r}},{"@braintree/asset-loader/load-script":3}],69:[function(e,t,i){"use strict";var r="function"==typeof Object.assign?Object.assign:n;function n(e){var t,i,r;for(t=1;t<arguments.length;t++)for(r in i=arguments[t])i.hasOwnProperty(r)&&(e[r]=i[r]);return e}t.exports={assign:r,_assign:n}},{}],70:[function(e,t,i){"use strict";var n=e("./braintree-error"),a=e("./promise"),o=e("./errors");t.exports={verify:function(e){var t,i,r;return e?(r=e.name,t=e.client,i=e.authorization,null==t&&null==i?a.reject(new n({type:o.INSTANTIATION_OPTION_REQUIRED.type,code:o.INSTANTIATION_OPTION_REQUIRED.code,message:"options.client is required when instantiating "+r+"."})):i||"3.42.0"===t.getVersion()?a.resolve():a.reject(new n({type:o.INCOMPATIBLE_VERSIONS.type,code:o.INCOMPATIBLE_VERSIONS.code,message:"Client (version "+t.getVersion()+") and "+r+" (version 3.42.0) components must be from the same SDK version."}))):a.reject(new n({type:o.INVALID_USE_OF_INTERNAL_FUNCTION.type,code:o.INVALID_USE_OF_INTERNAL_FUNCTION.code,message:"Options must be passed to basicComponentVerification function."}))}}},{"./braintree-error":72,"./errors":85,"./promise":95}],71:[function(e,t,i){"use strict";var d=e("./once");t.exports=function(e,t){var i,r,n,a=e.length,o=a,s=d(t);if(0!==a)for(i=0;i<a;i++)r=e[i],n=l,0===r.length?(r(),n(null)):r(n);else s(null);function l(e){e?s(e):0===(o-=1)&&s(null)}}},{"./once":94}],72:[function(e,t,i){"use strict";var r=e("./enumerate");function n(e){if(!n.types.hasOwnProperty(e.type))throw new Error(e.type+" is not a valid type.");if(!e.code)throw new Error("Error code required.");if(!e.message)throw new Error("Error message required.");this.name="BraintreeError",this.code=e.code,this.message=e.message,this.type=e.type,this.details=e.details}((n.prototype=Object.create(Error.prototype)).constructor=n).types=r(["CUSTOMER","MERCHANT","NETWORK","INTERNAL","UNKNOWN"]),n.findRootError=function(e){return e instanceof n&&e.details&&e.details.originalError?n.findRootError(e.details.originalError):e},t.exports=n},{"./enumerate":84}],73:[function(e,t,i){"use strict";var n=e("../is-verified-domain");t.exports={checkOrigin:function(e,t){var i,r=document.createElement("a");return r.href=t,i="https:"===r.protocol?r.host.replace(/:443$/,""):"http:"===r.protocol?r.host.replace(/:80$/,""):r.host,r.protocol+"//"+i===e||(r.href=e,n(e))}}},{"../is-verified-domain":91}],74:[function(e,t,i){"use strict";var r=e("../enumerate");t.exports=r(["CONFIGURATION_REQUEST"],"bus:")},{"../enumerate":84}],75:[function(e,t,i){"use strict";var o=e("framebus"),r=e("./events"),s=e("./check-origin").checkOrigin,n=e("../braintree-error");function a(e){if(e=e||{},this.channel=e.channel,!this.channel)throw new n({type:n.types.INTERNAL,code:"MISSING_CHANNEL_ID",message:"Channel ID must be specified."});this.merchantUrl=e.merchantUrl,this._isDestroyed=!1,this._isVerbose=!1,this._listeners=[],this._log("new bus on channel "+this.channel,[location.href])}a.prototype.on=function(e,t){var i,r,n=t,a=this;this._isDestroyed||(this.merchantUrl&&(n=function(){s(this.origin,a.merchantUrl)&&t.apply(this,arguments)}),i=this._namespaceEvent(e),(r=Array.prototype.slice.call(arguments))[0]=i,r[1]=n,this._log("on",r),o.on.apply(o,r),this._listeners.push({eventName:e,handler:n,originalHandler:t}))},a.prototype.emit=function(e){var t;this._isDestroyed||((t=Array.prototype.slice.call(arguments))[0]=this._namespaceEvent(e),this._log("emit",t),o.emit.apply(o,t))},a.prototype._offDirect=function(e){var t=Array.prototype.slice.call(arguments);this._isDestroyed||(t[0]=this._namespaceEvent(e),this._log("off",t),o.off.apply(o,t))},a.prototype.off=function(e,t){var i,r,n=t;if(!this._isDestroyed){if(this.merchantUrl)for(i=0;i<this._listeners.length;i++)(r=this._listeners[i]).originalHandler===t&&(n=r.handler);this._offDirect(e,n)}},a.prototype._namespaceEvent=function(e){return["braintree",this.channel,e].join(":")},a.prototype.teardown=function(){var e,t;for(t=0;t<this._listeners.length;t++)e=this._listeners[t],this._offDirect(e.eventName,e.handler);this._listeners.length=0,this._isDestroyed=!0},a.prototype._log=function(e,t){this._isVerbose&&console.log(e,t)},a.events=r,t.exports=a},{"../braintree-error":72,"./check-origin":73,"./events":74,framebus:119}],76:[function(e,t,i){"use strict";t.exports={ANALYTICS_PREFIX:"web.",ANALYTICS_REQUEST_TIMEOUT_MS:2e3,ASSETS_URLS:{production:"https://assets.braintreegateway.com",sandbox:"https://assets.braintreegateway.com"},CLIENT_API_URLS:{production:"https://api.braintreegateway.com:443",sandbox:"https://api.sandbox.braintreegateway.com:443"},FRAUDNET_SOURCE:"BRAINTREE_SIGNIN",FRAUDNET_FNCLS:"fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99",FRAUDNET_URL:"https://c.paypal.com/da/r/fb.js",GRAPHQL_URLS:{production:"https://payments.braintree-api.com/graphql",sandbox:"https://payments.sandbox.braintree-api.com/graphql"},INTEGRATION_TIMEOUT_MS:6e4,VERSION:"3.42.0",INTEGRATION:"custom",SOURCE:"client",PLATFORM:"web",BRAINTREE_LIBRARY_VERSION:"braintree/web/3.42.0"}},{}],77:[function(e,t,i){"use strict";var r=e("./braintree-error"),n=e("./errors");t.exports=function(t,e){e.forEach(function(e){t[e]=function(){throw new r({type:n.METHOD_CALLED_AFTER_TEARDOWN.type,code:n.METHOD_CALLED_AFTER_TEARDOWN.code,message:e+" cannot be called after teardown."})}})}},{"./braintree-error":72,"./errors":85}],78:[function(e,t,i){"use strict";var r=e("./braintree-error");t.exports=function(e,t){return e instanceof r?e:new r({type:t.type,code:t.code,message:t.message,details:{originalError:e}})}},{"./braintree-error":72}],79:[function(e,t,i){"use strict";var r=e("./constants").ASSETS_URLS;t.exports={create:function(e){return r.production}}},{"./constants":76}],80:[function(e,t,i){"use strict";var o=e("../lib/vendor/polyfill").atob,s=e("../lib/constants").CLIENT_API_URLS;t.exports=function(e){var t,i,r,n,a={attrs:{},configUrl:""};return/^[a-zA-Z0-9]+_[a-zA-Z0-9]+_[a-zA-Z0-9_]+$/.test(e)?(r=e.split("_"),n=r[0],i={merchantId:r.slice(2).join("_"),environment:n},a.environment=i.environment,a.attrs.tokenizationKey=e,a.configUrl=s[i.environment]+"/merchants/"+i.merchantId+"/client_api/v1/configuration"):(t=JSON.parse(o(e)),a.environment=t.environment,a.attrs.authorizationFingerprint=t.authorizationFingerprint,a.configUrl=t.configUrl,a.graphQL=t.graphQL),a}},{"../lib/constants":76,"../lib/vendor/polyfill":98}],81:[function(e,t,i){(function(i){"use strict";var r=e("./braintree-error"),n=e("./promise"),a=e("./assets"),o=e("./errors"),s="3.42.0";t.exports={create:function(e){var t=n.resolve();return e.client?n.resolve(e.client):(i.braintree&&i.braintree.client||(t=a.loadScript({src:e.assetsUrl+"/web/"+s+"/js/client.min.js"}).catch(function(e){return n.reject(new r({type:o.CLIENT_SCRIPT_FAILED_TO_LOAD.type,code:o.CLIENT_SCRIPT_FAILED_TO_LOAD.code,message:o.CLIENT_SCRIPT_FAILED_TO_LOAD.message,details:{originalError:e}}))})),t.then(function(){return i.braintree.client.VERSION!==s?n.reject(new r({type:o.INCOMPATIBLE_VERSIONS.type,code:o.INCOMPATIBLE_VERSIONS.code,message:"Client (version "+i.braintree.client.VERSION+") and "+e.name+" (version "+s+") components must be from the same SDK version."})):i.braintree.client.create({authorization:e.authorization,debug:e.debug})}))}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./assets":68,"./braintree-error":72,"./errors":85,"./promise":95}],82:[function(e,t,i){"use strict";t.exports=function(t){return function(){var e=arguments;setTimeout(function(){t.apply(null,e)},1)}}},{}],83:[function(e,t,i){"use strict";var r=e("./batch-execute-functions");function n(){this._teardownRegistry=[],this._isTearingDown=!1}n.prototype.registerFunctionForTeardown=function(e){"function"==typeof e&&this._teardownRegistry.push(e)},n.prototype.teardown=function(t){this._isTearingDown?t(new Error("Destructor is already tearing down")):(this._isTearingDown=!0,r(this._teardownRegistry,function(e){this._teardownRegistry=[],this._isTearingDown=!1,"function"==typeof t&&t(e)}.bind(this)))},t.exports=n},{"./batch-execute-functions":71}],84:[function(e,t,i){"use strict";t.exports=function(e,i){return i=null==i?"":i,e.reduce(function(e,t){return e[t]=i+t,e},{})}},{}],85:[function(e,t,i){"use strict";var r=e("./braintree-error");t.exports={INVALID_USE_OF_INTERNAL_FUNCTION:{type:r.types.INTERNAL,code:"INVALID_USE_OF_INTERNAL_FUNCTION"},INSTANTIATION_OPTION_REQUIRED:{type:r.types.MERCHANT,code:"INSTANTIATION_OPTION_REQUIRED"},INCOMPATIBLE_VERSIONS:{type:r.types.MERCHANT,code:"INCOMPATIBLE_VERSIONS"},CLIENT_SCRIPT_FAILED_TO_LOAD:{type:r.types.NETWORK,code:"CLIENT_SCRIPT_FAILED_TO_LOAD",message:"Braintree client script could not be loaded."},METHOD_CALLED_AFTER_TEARDOWN:{type:r.types.MERCHANT,code:"METHOD_CALLED_AFTER_TEARDOWN"},BRAINTREE_API_ACCESS_RESTRICTED:{type:r.types.MERCHANT,code:"BRAINTREE_API_ACCESS_RESTRICTED",message:"Your access is restricted and cannot use this part of the Braintree API."}}},{"./braintree-error":72}],86:[function(e,t,i){"use strict";function r(){this._events={}}r.prototype.on=function(e,t){this._events[e]?this._events[e].push(t):this._events[e]=[t]},r.prototype._emit=function(e){var t,i,r=this._events[e];if(r)for(i=Array.prototype.slice.call(arguments,1),t=0;t<r.length;t++)r[t].apply(null,i)},t.exports=r},{}],87:[function(e,t,i){"use strict";t.exports=function(e,t,i){var r;for(r=0;r<e.length;r++)if(e[r].hasOwnProperty(t)&&e[r][t]===i)return e[r];return null}},{}],88:[function(e,t,i){"use strict";var n=e("./assign").assign;function l(e,t){var i=e.analyticsMetadata,r={gateway:"braintree","braintree:merchantId":e.gatewayConfiguration.merchantId,"braintree:apiVersion":"v1","braintree:sdkVersion":"3.42.0","braintree:metadata":JSON.stringify({source:i.source,integration:i.integration,sessionId:i.sessionId,version:"3.42.0",platform:i.platform})};return n({},r,t)}t.exports=function(e,t,i){var r,n,a,o=e.gatewayConfiguration.androidPay,s="production"===e.gatewayConfiguration.environment?"PRODUCTION":"TEST";return 2===t?(r={apiVersion:2,apiVersionMinor:0,environment:s,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:o.supportedNetworks.map(function(e){return e.toUpperCase()})},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:l(e,{"braintree:authorizationFingerprint":o.googleAuthorizationFingerprint})}}]},i&&(r.merchantInfo={merchantId:i}),"TOKENIZATION_KEY"===e.authorizationType&&(n=find(r.allowedPaymentMethods,"type","CARD"))&&(n.tokenizationSpecification.parameters["braintree:clientKey"]=e.authorization),e.gatewayConfiguration.paypal&&e.gatewayConfiguration.paypal.clientId&&!1===e.gatewayConfiguration.paypal.environmentNoNetwork&&(a={type:"PAYPAL",parameters:{purchase_context:{purchase_units:[{payee:{client_id:e.gatewayConfiguration.paypal.clientId},recurring_payment:!0}]}},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:l(e,{"braintree:paypalClientId":e.gatewayConfiguration.paypal.clientId})}},r.allowedPaymentMethods.push(a))):(r={environment:s,allowedPaymentMethods:["CARD","TOKENIZED_CARD"],paymentMethodTokenizationParameters:{tokenizationType:"PAYMENT_GATEWAY",parameters:l(e,{"braintree:authorizationFingerprint":o.googleAuthorizationFingerprint})},cardRequirements:{allowedCardNetworks:o.supportedNetworks.map(function(e){return e.toUpperCase()})}},"TOKENIZATION_KEY"===e.authorizationType&&(r.paymentMethodTokenizationParameters.parameters["braintree:clientKey"]=e.authorization),i&&(r.merchantId=i),t&&(r.apiVersion=t)),r}},{"./assign":69}],89:[function(e,t,i){"use strict";function r(e){var t=e.split("-");return new Date(t[0],t[1],t[2])}t.exports=function(e,t){return r(e)<=r(t)}},{}],90:[function(e,i,t){(function(t){"use strict";i.exports={isHTTPS:function(e){return"https:"===(e=e||t.location.protocol)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],91:[function(e,t,i){"use strict";var r,n={"paypal.com":1,"braintreepayments.com":1,"braintreegateway.com":1,"braintree-api.com":1};t.exports=function(e){var t;return e=e.toLowerCase(),!!/^https:/.test(e)&&((r=r||document.createElement("a")).href=e,t=r.hostname.split(".").slice(-2).join("."),n.hasOwnProperty(t))}},{}],92:[function(e,t,i){"use strict";t.exports=function(e){return JSON.parse(JSON.stringify(e))}},{}],93:[function(e,t,i){"use strict";t.exports=function(t){return Object.keys(t).filter(function(e){return"function"==typeof t[e]})}},{}],94:[function(e,t,i){arguments[4][24][0].apply(i,arguments)},{dup:24}],95:[function(i,r,e){(function(e){"use strict";var t=e.Promise||i("promise-polyfill");r.exports=t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"promise-polyfill":121}],96:[function(e,i,t){(function(t){"use strict";function s(e,t){var i,r,n,a,o=[];for(n in e)e.hasOwnProperty(n)&&(r=e[n],i=t?(a=e)&&"object"==typeof a&&"number"==typeof a.length&&"[object Array]"===Object.prototype.toString.call(a)?t+"[]":t+"["+n+"]":n,"object"==typeof r?o.push(s(r,i)):o.push(encodeURIComponent(i)+"="+encodeURIComponent(r)));return o.join("&")}i.exports={parse:function(e){return e=e||t.location.href,/\?/.test(e)?e.replace(/#.*$/,"").replace(/^.*\?/,"").split("&").reduce(function(e,t){var i=t.split("="),r=decodeURIComponent(i[0]),n=decodeURIComponent(i[1]);return e[r]=n,e},{}):{}},stringify:s,queryify:function(e,t){return e=e||"",null!=t&&"object"==typeof t&&function(e){var t;for(t in e)if(e.hasOwnProperty(t))return!0;return!1}(t)&&(e+=-1===e.indexOf("?")?"?":"",e+=-1!==e.indexOf("=")?"&":"",e+=s(t)),e}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],97:[function(e,t,i){"use strict";t.exports=function(e){return e?"":".min"}},{}],98:[function(e,r,t){(function(t){"use strict";var i="function"==typeof t.atob?t.atob:e;function e(e){var t,i,r,n,a,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l="";if(!new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$").test(e))throw new Error("Non base64 encoded input passed to window.atob polyfill");for(o=0;t=(63&s.indexOf(e.charAt(o++)))<<2|(n=s.indexOf(e.charAt(o++)))>>4&3,i=(15&n)<<4|(a=s.indexOf(e.charAt(o++)))>>2&15,r=(3&a)<<6|63&s.indexOf(e.charAt(o++)),l+=String.fromCharCode(t)+(i?String.fromCharCode(i):"")+(r?String.fromCharCode(r):""),o<e.length;);return l}r.exports={atob:function(e){return i.call(t,e)},_atob:e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],99:[function(e,t,i){"use strict";t.exports=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}},{}],100:[function(e,t,i){"use strict";var r=e("../lib/braintree-error");t.exports={PAYPAL_NOT_ENABLED:{type:r.types.MERCHANT,code:"PAYPAL_NOT_ENABLED",message:"PayPal is not enabled for this merchant."},PAYPAL_SANDBOX_ACCOUNT_NOT_LINKED:{type:r.types.MERCHANT,code:"PAYPAL_SANDBOX_ACCOUNT_NOT_LINKED",message:"A linked PayPal Sandbox account is required to use PayPal Checkout in Sandbox. See https://developers.braintreepayments.com/guides/paypal/testing-go-live/#linked-paypal-testing for details on linking your PayPal sandbox with Braintree."},PAYPAL_ACCOUNT_TOKENIZATION_FAILED:{type:r.types.NETWORK,code:"PAYPAL_ACCOUNT_TOKENIZATION_FAILED",message:"Could not tokenize user's PayPal account."},PAYPAL_FLOW_FAILED:{type:r.types.NETWORK,code:"PAYPAL_FLOW_FAILED",message:"Could not initialize PayPal flow."},PAYPAL_FLOW_OPTION_REQUIRED:{type:r.types.MERCHANT,code:"PAYPAL_FLOW_OPTION_REQUIRED",message:"PayPal flow property is invalid or missing."},PAYPAL_INVALID_PAYMENT_OPTION:{type:r.types.MERCHANT,code:"PAYPAL_INVALID_PAYMENT_OPTION",message:"PayPal payment options are invalid."}}},{"../lib/braintree-error":72}],101:[function(e,t,i){"use strict";var r=e("../lib/basic-component-verification"),n=e("@braintree/wrap-promise"),a=e("./paypal-checkout");t.exports={create:n(function(e){return r.verify({name:"PayPal Checkout",client:e.client,authorization:e.authorization}).then(function(){return new a(e)._initialize(e)})}),isSupported:function(){return!0},VERSION:"3.42.0"}},{"../lib/basic-component-verification":70,"./paypal-checkout":102,"@braintree/wrap-promise":26}],102:[function(e,t,i){"use strict";var a=e("../lib/analytics"),r=e("../lib/create-deferred-client"),n=e("../lib/create-assets-url"),o=e("../lib/promise"),s=e("@braintree/wrap-promise"),l=e("../lib/braintree-error"),d=e("../lib/convert-to-braintree-error"),c=e("./errors"),p=e("../paypal/shared/constants"),u=e("../lib/methods"),h=e("../lib/convert-methods-to-error");function m(e){this._merchantAccountId=e.merchantAccountId}m.prototype._initialize=function(e){return this._clientPromise=r.create({authorization:e.authorization,client:e.client,debug:e.debug,assetsUrl:n.create(e.authorization),name:"PayPal Checkout"}).then(function(e){return this._configuration=e.getConfiguration(),this._merchantAccountId||(this._configuration.gatewayConfiguration.paypalEnabled?!0===this._configuration.gatewayConfiguration.paypal.environmentNoNetwork&&(this._setupError=new l(c.PAYPAL_SANDBOX_ACCOUNT_NOT_LINKED)):this._setupError=new l(c.PAYPAL_NOT_ENABLED)),this._setupError?o.reject(this._setupError):(a.sendEvent(e,"paypal-checkout.initialized"),e)}.bind(this)),e.client?this._clientPromise.then(function(){return this}.bind(this)):o.resolve(this)},m.prototype.createPayment=function(t){var i,r=this;return t&&p.FLOW_ENDPOINTS.hasOwnProperty(t.flow)?(i="paypal_hermes/"+p.FLOW_ENDPOINTS[t.flow],a.sendEvent(this._clientPromise,"paypal-checkout.createPayment"),!0===t.offerCredit&&a.sendEvent(this._clientPromise,"paypal-checkout.credit.offered"),this._clientPromise.then(function(e){return e.request({endpoint:i,method:"post",data:r._formatPaymentResourceData(t)})}).then(function(e){return"checkout"===t.flow?e.paymentResource.paymentToken:e.agreementSetup.tokenId}).catch(function(e){return r._setupError?o.reject(r._setupError):422===(e.details&&e.details.httpStatus)?o.reject(new l({type:c.PAYPAL_INVALID_PAYMENT_OPTION.type,code:c.PAYPAL_INVALID_PAYMENT_OPTION.code,message:c.PAYPAL_INVALID_PAYMENT_OPTION.message,details:{originalError:e}})):o.reject(d(e,{type:c.PAYPAL_FLOW_FAILED.type,code:c.PAYPAL_FLOW_FAILED.code,message:c.PAYPAL_FLOW_FAILED.message}))})):o.reject(new l(c.PAYPAL_FLOW_OPTION_REQUIRED))},m.prototype.tokenizePayment=function(e){var t,i=this,r={flow:e.billingToken?"vault":"checkout",intent:e.intent},n={ecToken:e.paymentToken,billingToken:e.billingToken,payerId:e.payerID,paymentId:e.paymentID};return a.sendEvent(this._clientPromise,"paypal-checkout.tokenization.started"),this._clientPromise.then(function(e){return e.request({endpoint:"payment_methods/paypal_accounts",method:"post",data:i._formatTokenizeData(r,n)})}).then(function(e){return t=i._formatTokenizePayload(e),a.sendEvent(i._clientPromise,"paypal-checkout.tokenization.success"),t.creditFinancingOffered&&a.sendEvent(i._clientPromise,"paypal-checkout.credit.accepted"),t}).catch(function(e){return i._setupError?o.reject(i._setupError):(a.sendEvent(i._clientPromise,"paypal-checkout.tokenization.failed"),o.reject(d(e,{type:c.PAYPAL_ACCOUNT_TOKENIZATION_FAILED.type,code:c.PAYPAL_ACCOUNT_TOKENIZATION_FAILED.code,message:c.PAYPAL_ACCOUNT_TOKENIZATION_FAILED.message})))})},m.prototype._formatPaymentResourceData=function(e){var t,i=this._configuration.gatewayConfiguration,r={returnUrl:"x",cancelUrl:"x",offerPaypalCredit:!0===e.offerCredit,merchantAccountId:this._merchantAccountId,experienceProfile:{brandName:e.displayName||i.paypal.displayName,localeCode:e.locale,noShipping:(!e.enableShippingAddress).toString(),addressOverride:!1===e.shippingAddressEditable,landingPageType:e.landingPageType}};if("checkout"===e.flow)for(t in r.amount=e.amount,r.currencyIsoCode=e.currency,e.hasOwnProperty("intent")&&(r.intent=e.intent),e.hasOwnProperty("lineItems")&&(r.lineItems=e.lineItems),e.shippingAddressOverride)e.shippingAddressOverride.hasOwnProperty(t)&&(r[t]=e.shippingAddressOverride[t]);else r.shippingAddress=e.shippingAddressOverride,e.billingAgreementDescription&&(r.description=e.billingAgreementDescription);return r},m.prototype._formatTokenizeData=function(e,t){var i=this._configuration,r=i.gatewayConfiguration,n="TOKENIZATION_KEY"===i.authorizationType,a={paypalAccount:{correlationId:t.billingToken||t.ecToken,options:{validate:"vault"===e.flow&&!n}}};return t.billingToken?a.paypalAccount.billingAgreementToken=t.billingToken:(a.paypalAccount.paymentToken=t.paymentId,a.paypalAccount.payerId=t.payerId,a.paypalAccount.unilateral=r.paypal.unvettedMerchant,e.intent&&(a.paypalAccount.intent=e.intent),this._merchantAccountId&&(a.merchantAccountId=this._merchantAccountId)),a},m.prototype._formatTokenizePayload=function(e){var t,i={};return e.paypalAccounts&&(i=e.paypalAccounts[0]),t={nonce:i.nonce,details:{},type:i.type},i.details&&i.details.payerInfo&&(t.details=i.details.payerInfo),i.details&&i.details.creditFinancingOffered&&(t.creditFinancingOffered=i.details.creditFinancingOffered),t},m.prototype.teardown=function(){return h(this,u(m.prototype)),o.resolve()},t.exports=s.wrapPrototype(m)},{"../lib/analytics":67,"../lib/braintree-error":72,"../lib/convert-methods-to-error":77,"../lib/convert-to-braintree-error":78,"../lib/create-assets-url":79,"../lib/create-deferred-client":81,"../lib/methods":93,"../lib/promise":95,"../paypal/shared/constants":103,"./errors":100,"@braintree/wrap-promise":26}],103:[function(e,t,i){"use strict";t.exports={LANDING_FRAME_NAME:"braintreepaypallanding",FLOW_ENDPOINTS:{checkout:"create_payment_resource",vault:"setup_billing_agreement"}}},{}],104:[function(e,t,i){"use strict";var l=e("../../lib/braintree-error"),r=e("../../lib/analytics"),d=e("../../lib/assign").assign,n=e("../../lib/methods"),a=e("../../lib/convert-methods-to-error"),o=e("../shared/constants"),s=e("../../lib/use-min"),c=e("../../lib/bus"),p=e("../../lib/vendor/uuid"),u=e("../../lib/deferred"),h=e("../shared/errors"),m=e("../shared/events"),y="3.42.0",f=e("@braintree/iframer"),g=e("../../lib/promise"),v=e("@braintree/wrap-promise");function b(e){this._options=e,this._assetsUrl=e.client.getConfiguration().gatewayConfiguration.assetsUrl,this._isDebug=e.client.getConfiguration().isDebug,this._client=e.client}b.prototype.verifyCard=function(e){var t,n,a,o,i,r,s=this;return(e=d({},e)).customer&&e.customer.billingAddress&&(e.customer.billingAddress.line1=e.customer.billingAddress.streetAddress,e.customer.billingAddress.line2=e.customer.billingAddress.extendedAddress,e.customer.billingAddress.city=e.customer.billingAddress.locality,e.customer.billingAddress.state=e.customer.billingAddress.region,e.customer.billingAddress.countryCode=e.customer.billingAddress.countryCodeAlpha2,delete e.customer.billingAddress.streetAddress,delete e.customer.billingAddress.extendedAddress,delete e.customer.billingAddress.locality,delete e.customer.billingAddress.region,delete e.customer.billingAddress.countryCodeAlpha2),!0===this._verifyCardInProgress?i=h.THREEDS_AUTHENTICATION_IN_PROGRESS:e.nonce?e.amount?"function"!=typeof e.addFrame?r="an addFrame function":"function"!=typeof e.removeFrame&&(r="a removeFrame function"):r="an amount":r="a nonce",r&&(i={type:h.THREEDS_MISSING_VERIFY_CARD_OPTION.type,code:h.THREEDS_MISSING_VERIFY_CARD_OPTION.code,message:"verifyCard options must include "+r+"."}),i?g.reject(new l(i)):(n=!1!==e.showLoader,this._verifyCardInProgress=!0,a=u(e.addFrame),o=u(e.removeFrame),t="payment_methods/"+e.nonce+"/three_d_secure/lookup",this._client.request({endpoint:t,method:"post",data:{amount:e.amount,customer:e.customer}}).then(function(e){return s._lookupPaymentMethod=e.paymentMethod,new g(function(i,r){s._verifyCardCallback=function(e,t){s._verifyCardInProgress=!1,e?r(e):i(t)},s._handleLookupResponse({showLoader:n,lookupResponse:e,addFrame:a,removeFrame:o})})}).catch(function(e){return s._verifyCardInProgress=!1,g.reject(e)}))},b.prototype.cancelVerifyCard=function(){var e;return this._verifyCardInProgress=!1,this._lookupPaymentMethod?(e=d({},this._lookupPaymentMethod,{liabilityShiftPossible:this._lookupPaymentMethod.threeDSecureInfo.liabilityShiftPossible,liabilityShifted:this._lookupPaymentMethod.threeDSecureInfo.liabilityShifted,verificationDetails:this._lookupPaymentMethod.threeDSecureInfo.verificationDetails}),g.resolve(e)):g.reject(new l(h.THREEDS_NO_VERIFICATION_PAYLOAD))},b.prototype._handleLookupResponse=function(e){var t,i=e.lookupResponse;i.lookup&&i.lookup.acsUrl&&0<i.lookup.acsUrl.length?e.addFrame(null,this._createIframe({showLoader:e.showLoader,response:i.lookup,removeFrame:e.removeFrame})):((t=this._formatAuthResponse(i.paymentMethod,i.threeDSecureInfo)).verificationDetails=i.threeDSecureInfo,this._verifyCardCallback(null,t))},b.prototype._createIframe=function(t){var e,i,r=window.location.href,n=t.response;return this._bus=new c({channel:p(),merchantUrl:location.href}),i=this._assetsUrl+"/web/"+y+"/html/three-d-secure-authentication-complete-frame.html?channel="+encodeURIComponent(this._bus.channel)+"&",-1<r.indexOf("#")&&(r=r.split("#")[0]),this._bus.on(c.events.CONFIGURATION_REQUEST,function(e){e({acsUrl:n.acsUrl,pareq:n.pareq,termUrl:n.termUrl+"&three_d_secure_version="+y+"&authentication_complete_base_url="+encodeURIComponent(i),md:n.md,parentUrl:r})}),this._bus.on(m.AUTHENTICATION_COMPLETE,function(e){this._handleAuthResponse(e,t)}.bind(this)),e=this._assetsUrl+"/web/"+y+"/html/three-d-secure-bank-frame"+s(this._isDebug)+".html?showLoader="+t.showLoader,this._bankIframe=f({src:e,height:400,width:400,name:o.LANDING_FRAME_NAME+"_"+this._bus.channel,title:"3D Secure Authorization Frame"}),this._bankIframe},b.prototype._handleAuthResponse=function(e,t){var i=JSON.parse(e.auth_response);this._bus.teardown(),t.removeFrame(),u(function(){i.success?this._verifyCardCallback(null,this._formatAuthResponse(i.paymentMethod,i.threeDSecureInfo)):i.threeDSecureInfo&&i.threeDSecureInfo.liabilityShiftPossible?this._verifyCardCallback(null,this._formatAuthResponse(this._lookupPaymentMethod,i.threeDSecureInfo)):this._verifyCardCallback(new l({type:l.types.UNKNOWN,code:"UNKNOWN_AUTH_RESPONSE",message:i.error.message}))}.bind(this))()},b.prototype._formatAuthResponse=function(e,t){return{nonce:e.nonce,binData:e.binData,details:e.details,description:e.description&&e.description.replace(/\+/g," "),liabilityShifted:t.liabilityShifted,liabilityShiftPossible:t.liabilityShiftPossible}},b.prototype.teardown=function(){var e;return a(this,n(b.prototype)),r.sendEvent(this._options.client,"threedsecure.teardown-completed"),this._bus&&this._bus.teardown(),this._bankIframe&&(e=this._bankIframe.parentNode)&&e.removeChild(this._bankIframe),g.resolve()},t.exports=v.wrapPrototype(b)},{"../../lib/analytics":67,"../../lib/assign":69,"../../lib/braintree-error":72,"../../lib/bus":75,"../../lib/convert-methods-to-error":77,"../../lib/deferred":82,"../../lib/methods":93,"../../lib/promise":95,"../../lib/use-min":97,"../../lib/vendor/uuid":99,"../shared/constants":106,"../shared/errors":107,"../shared/events":108,"@braintree/iframer":19,"@braintree/wrap-promise":26}],105:[function(e,t,i){"use strict";var n=e("./external/three-d-secure"),a=e("../lib/is-https").isHTTPS,o=e("../lib/basic-component-verification"),s=e("../lib/create-deferred-client"),l=e("../lib/create-assets-url"),d=e("../lib/braintree-error"),c=e("../lib/analytics"),p=e("./shared/errors"),u=e("../lib/promise"),r=e("@braintree/wrap-promise");t.exports={create:r(function(r){var e="3D Secure";return o.verify({name:e,client:r.client,authorization:r.authorization}).then(function(){return s.create({authorization:r.authorization,client:r.client,debug:r.debug,assetsUrl:l.create(r.authorization),name:e})}).then(function(e){var t,i=e.getConfiguration();return r.client=e,i.gatewayConfiguration.threeDSecureEnabled||(t=p.THREEDS_NOT_ENABLED),"TOKENIZATION_KEY"===i.authorizationType&&(t=p.THREEDS_CAN_NOT_USE_TOKENIZATION_KEY),"production"===i.gatewayConfiguration.environment&&!a()&&(t=p.THREEDS_HTTPS_REQUIRED),t?u.reject(new d(t)):(c.sendEvent(r.client,"threedsecure.initialized"),new n(r))})}),VERSION:"3.42.0"}},{"../lib/analytics":67,"../lib/basic-component-verification":70,"../lib/braintree-error":72,"../lib/create-assets-url":79,"../lib/create-deferred-client":81,"../lib/is-https":90,"../lib/promise":95,"./external/three-d-secure":104,"./shared/errors":107,"@braintree/wrap-promise":26}],106:[function(e,t,i){"use strict";t.exports={LANDING_FRAME_NAME:"braintreethreedsecurelanding"}},{}],107:[function(e,t,i){"use strict";var r=e("../../lib/braintree-error");t.exports={THREEDS_NOT_ENABLED:{type:r.types.MERCHANT,code:"THREEDS_NOT_ENABLED",message:"3D Secure is not enabled for this merchant."},THREEDS_CAN_NOT_USE_TOKENIZATION_KEY:{type:r.types.MERCHANT,code:"THREEDS_CAN_NOT_USE_TOKENIZATION_KEY",message:"3D Secure can not use a tokenization key for authorization."},THREEDS_HTTPS_REQUIRED:{type:r.types.MERCHANT,code:"THREEDS_HTTPS_REQUIRED",message:"3D Secure requires HTTPS."},THREEDS_AUTHENTICATION_IN_PROGRESS:{type:r.types.MERCHANT,code:"THREEDS_AUTHENTICATION_IN_PROGRESS",message:"Cannot call verifyCard while existing authentication is in progress."},THREEDS_MISSING_VERIFY_CARD_OPTION:{type:r.types.MERCHANT,code:"THREEDS_MISSING_VERIFY_CARD_OPTION"},THREEDS_NO_VERIFICATION_PAYLOAD:{type:r.types.MERCHANT,code:"THREEDS_NO_VERIFICATION_PAYLOAD",message:"No verification payload available."},THREEDS_TERM_URL_REQUIRES_BRAINTREE_DOMAIN:{type:r.types.INTERNAL,code:"THREEDS_TERM_URL_REQUIRES_BRAINTREE_DOMAIN",message:"Term Url must be on a Braintree domain."}}},{"../../lib/braintree-error":72}],108:[function(e,t,i){"use strict";var r=e("../../lib/enumerate");t.exports=r(["AUTHENTICATION_COMPLETE"],"threedsecure:")},{"../../lib/enumerate":84}],109:[function(e,t,i){"use strict";var r=e("../lib/braintree-error");t.exports={VAULT_MANAGER_DELETE_PAYMENT_METHOD_NONCE_REQUIRES_CLIENT_TOKEN:{type:r.types.MERCHANT,code:"VAULT_MANAGER_DELETE_PAYMENT_METHOD_NONCE_REQUIRES_CLIENT_TOKEN",message:"A client token with a customer id must be used to delete a payment method nonce."},VAULT_MANAGER_PAYMENT_METHOD_NONCE_NOT_FOUND:{type:r.types.MERCHANT,code:"VAULT_MANAGER_PAYMENT_METHOD_NONCE_NOT_FOUND"},VAULT_MANAGER_DELETE_PAYMENT_METHOD_UNKNOWN_ERROR:{type:r.types.UNKNOWN,code:"VAULT_MANAGER_DELETE_PAYMENT_METHOD_UNKNOWN_ERROR"}}},{"../lib/braintree-error":72}],110:[function(e,t,i){"use strict";var r=e("../lib/basic-component-verification"),n=e("../lib/create-deferred-client"),a=e("../lib/create-assets-url"),o=e("./vault-manager"),s=e("@braintree/wrap-promise");t.exports={create:s(function(t){var e="Vault Manager";return r.verify({name:e,client:t.client,authorization:t.authorization}).then(function(){return n.create({authorization:t.authorization,client:t.client,debug:t.debug,assetsUrl:a.create(t.authorization),name:e})}).then(function(e){return t.client=e,new o(t)})}),VERSION:"3.42.0"}},{"../lib/basic-component-verification":70,"../lib/create-assets-url":79,"../lib/create-deferred-client":81,"./vault-manager":111,"@braintree/wrap-promise":26}],111:[function(e,t,i){"use strict";var a=e("../lib/analytics"),o=e("../lib/braintree-error"),s=e("./errors"),r=e("../lib/convert-methods-to-error"),n=e("../lib/methods"),l=e("../lib/promise"),d=e("@braintree/wrap-promise");function c(e){this._client=e.client}function p(e){var t={nonce:e.nonce,default:e.default,details:e.details,hasSubscription:e.hasSubscription,type:e.type};return e.description&&(t.description=e.description),e.binData&&(t.binData=e.binData),t}c.prototype.fetchPaymentMethods=function(e){var t;return t=!0===(e=e||{}).defaultFirst?1:0,this._client.request({endpoint:"payment_methods",method:"get",data:{defaultFirst:t}}).then(function(e){return a.sendEvent(this._client,"vault-manager.fetch-payment-methods.succeeded"),e.paymentMethods.map(p)}.bind(this))},c.prototype.deletePaymentMethod=function(r){var n=this._client;return"CLIENT_TOKEN"===this._client.getConfiguration().authorizationType?this._client.request({api:"graphQLApi",data:{query:"mutation DeletePaymentMethodFromSingleUseToken($input: DeletePaymentMethodFromSingleUseTokenInput!) {  deletePaymentMethodFromSingleUseToken(input: $input) {    clientMutationId  }}",variables:{input:{singleUseTokenId:r}},operationName:"DeletePaymentMethodFromSingleUseToken"}}).then(function(){a.sendEvent(n,"vault-manager.delete-payment-method.succeeded")}).catch(function(e){var t,i=e.details.originalError;return a.sendEvent(n,"vault-manager.delete-payment-method.failed"),i[0]&&"NOT_FOUND"===i[0].extensions.errorClass&&(t=new o({type:s.VAULT_MANAGER_PAYMENT_METHOD_NONCE_NOT_FOUND.type,code:s.VAULT_MANAGER_PAYMENT_METHOD_NONCE_NOT_FOUND.code,message:"A payment method for payment method nonce `"+r+"` could not be found.",details:{originalError:i}})),t||(t=new o({type:s.VAULT_MANAGER_DELETE_PAYMENT_METHOD_UNKNOWN_ERROR.type,code:s.VAULT_MANAGER_DELETE_PAYMENT_METHOD_UNKNOWN_ERROR.code,message:"An unknown error occured when attempting to delete the payment method assocaited with the payment method nonce `"+r+"`.",details:{originalError:i}})),l.reject(t)}):l.reject(new o(s.VAULT_MANAGER_DELETE_PAYMENT_METHOD_NONCE_REQUIRES_CLIENT_TOKEN))},c.prototype.teardown=function(){return r(this,n(c.prototype)),l.resolve()},t.exports=d.wrapPrototype(c)},{"../lib/analytics":67,"../lib/braintree-error":72,"../lib/convert-methods-to-error":77,"../lib/methods":93,"../lib/promise":95,"./errors":109,"@braintree/wrap-promise":26}],112:[function(e,t,i){"use strict";var n=e("../lib/analytics"),a=e("../lib/basic-component-verification"),o=e("../lib/create-deferred-client"),s=e("../lib/create-assets-url"),l=e("./shared/errors"),r=e("@braintree/wrap-promise"),d=e("../lib/braintree-error"),c=e("./venmo"),p=e("../lib/promise"),u=e("./shared/supports-venmo");t.exports={create:r(function(r){return a.verify({name:"Venmo",client:r.client,authorization:r.authorization}).then(function(){return o.create({authorization:r.authorization,client:r.client,debug:r.debug,assetsUrl:s.create(r.authorization),name:"Venmo"})}).then(function(e){var t,i=e.getConfiguration();return r.client=e,i.gatewayConfiguration.payWithVenmo?r.profileId&&"string"!=typeof r.profileId?p.reject(new d(l.VENMO_INVALID_PROFILE_ID)):r.deepLinkReturnUrl&&"string"!=typeof r.deepLinkReturnUrl?p.reject(new d(l.VENMO_INVALID_DEEP_LINK_RETURN_URL)):(t=new c(r),n.sendEvent(r.client,"venmo.initialized"),t._initialize()):p.reject(new d(l.VENMO_NOT_ENABLED))})}),isBrowserSupported:function(e){return u.isBrowserSupported(e)},VERSION:"3.42.0"}},{"../lib/analytics":67,"../lib/basic-component-verification":70,"../lib/braintree-error":72,"../lib/create-assets-url":79,"../lib/create-deferred-client":81,"../lib/promise":95,"./shared/errors":115,"./shared/supports-venmo":116,"./venmo":117,"@braintree/wrap-promise":26}],113:[function(e,t,i){"use strict";var r=e("@braintree/browser-detection/is-android"),n=e("@braintree/browser-detection/is-chrome"),a=e("@braintree/browser-detection/is-ios"),o=e("@braintree/browser-detection/is-ios-safari"),s=e("@braintree/browser-detection/is-samsung"),l=e("@braintree/browser-detection/is-mobile-firefox");t.exports={isAndroid:r,isChrome:n,isIos:a,isIosSafari:o,isSamsungBrowser:s,isMobileFirefox:l}},{"@braintree/browser-detection/is-android":5,"@braintree/browser-detection/is-chrome":6,"@braintree/browser-detection/is-ios":15,"@braintree/browser-detection/is-ios-safari":13,"@braintree/browser-detection/is-mobile-firefox":16,"@braintree/browser-detection/is-samsung":17}],114:[function(e,t,i){"use strict";t.exports={DOCUMENT_VISIBILITY_CHANGE_EVENT_DELAY:500,PROCESS_RESULTS_DELAY:1e3,VENMO_OPEN_URL:"https://venmo.com/braintree/checkout"}},{}],115:[function(e,t,i){"use strict";var r=e("../../lib/braintree-error");t.exports={VENMO_NOT_ENABLED:{type:r.types.MERCHANT,code:"VENMO_NOT_ENABLED",message:"Venmo is not enabled for this merchant."},VENMO_TOKENIZATION_REQUEST_ACTIVE:{type:r.types.MERCHANT,code:"VENMO_TOKENIZATION_REQUEST_ACTIVE",message:"Another tokenization request is active."},VENMO_APP_FAILED:{type:r.types.UNKNOWN,code:"VENMO_APP_FAILED",message:"Venmo app encountered a problem."},VENMO_APP_CANCELED:{type:r.types.CUSTOMER,code:"VENMO_APP_CANCELED",message:"Venmo app authorization was canceled."},VENMO_CANCELED:{type:r.types.CUSTOMER,code:"VENMO_CANCELED",message:"User canceled Venmo authorization, or Venmo app is not available."},VENMO_INVALID_PROFILE_ID:{type:r.types.MERCHANT,code:"VENMO_INVALID_PROFILE_ID",message:"Venmo profile ID is invalid."},VENMO_INVALID_DEEP_LINK_RETURN_URL:{type:r.types.MERCHANT,code:"VENMO_INVALID_DEEP_LINK_RETURN_URL",message:"Venmo deep link return URL is invalid."}}},{"../../lib/braintree-error":72}],116:[function(e,t,i){"use strict";var a=e("./browser-detection");t.exports={isBrowserSupported:function(e){var t=a.isAndroid()&&a.isChrome(),i=a.isIos()&&a.isChrome(),r=a.isIosSafari()||t,n=i||a.isSamsungBrowser()||a.isMobileFirefox();return e=e||{allowNewBrowserTab:!0},r||e.allowNewBrowserTab&&n}}},{"./browser-detection":113}],117:[function(m,y,e){(function(a){"use strict";var o=m("../lib/analytics"),e=m("./shared/supports-venmo"),s=m("./shared/constants"),l=m("./shared/errors"),d=m("../lib/querystring"),t=m("../lib/methods"),i=m("../lib/convert-methods-to-error"),r=m("@braintree/wrap-promise"),c=m("../lib/braintree-error"),p=m("../lib/promise");function n(e){var t;this._client=e.client,t=this._client.getConfiguration(),this._isDebug=t.isDebug,this._assetsUrl=t.gatewayConfiguration.assetsUrl+"/web/3.42.0",this._allowNewBrowserTab=!1!==e.allowNewBrowserTab,this._profileId=e.profileId,this._deepLinkReturnUrl=e.deepLinkReturnUrl}function u(){return a.location.hash.substring(1).split("&").reduce(function(e,t){var i=t.split("="),r=decodeURIComponent(i[0]),n=decodeURIComponent(i[1]);return e[r]=n,e},{})}function h(){var e;return void 0!==a.document.hidden?e="visibilitychange":void 0!==a.document.msHidden?e="msvisibilitychange":void 0!==a.document.webkitHidden&&(e="webkitvisibilitychange"),e}n.prototype._initialize=function(){var e={},t=this._deepLinkReturnUrl||a.location.href.replace(a.location.hash,""),i=this._client.getConfiguration().gatewayConfiguration.payWithVenmo,r=this._client.getConfiguration().analyticsMetadata,n={_meta:{version:r.sdkVersion,integration:r.integration,platform:r.platform,sessionId:r.sessionId}};return e["x-success"]=t+"#venmoSuccess=1",e["x-cancel"]=t+"#venmoCancel=1",e["x-error"]=t+"#venmoError=1",e.ua=a.navigator.userAgent,e.braintree_merchant_id=this._profileId||i.merchantId,e.braintree_access_token=i.accessToken,e.braintree_environment=i.environment,e.braintree_sdk_data=btoa(JSON.stringify(n)),this._url=s.VENMO_OPEN_URL+"?"+d.stringify(e),p.resolve(this)},n.prototype.isBrowserSupported=function(){return e.isBrowserSupported({allowNewBrowserTab:this._allowNewBrowserTab})},n.prototype.hasTokenizationResult=function(){var e=u();return void 0!==(e.venmoSuccess||e.venmoError||e.venmoCancel)},n.prototype.tokenize=function(){var i=this;return!0===this._tokenizationInProgress?p.reject(new c(l.VENMO_TOKENIZATION_REQUEST_ACTIVE)):this.hasTokenizationResult()?this._processResults():new p(function(e,t){i._tokenizationInProgress=!0,i._previousHash=a.location.hash,i._deepLinkReturnUrl?a.location=i._url:a.open(i._url),i._visibilityChangeListener=function(){a.document.hidden||(i._tokenizationInProgress=!1,setTimeout(function(){i._processResults().then(e).catch(t).then(function(){a.location.hash=i._previousHash,i._removeVisibilityEventListener(),delete i._visibilityChangeListener})},s.PROCESS_RESULTS_DELAY))},setTimeout(function(){a.document.addEventListener(h(),i._visibilityChangeListener)},s.DOCUMENT_VISIBILITY_CHANGE_EVENT_DELAY)})},n.prototype.teardown=function(){return this._removeVisibilityEventListener(),i(this,t(n.prototype)),p.resolve()},n.prototype._removeVisibilityEventListener=function(){a.document.removeEventListener(h(),this._visibilityChangeListener)},n.prototype._processResults=function(){var r=this,n=u();return new p(function(e,t){var i;n.venmoSuccess?(o.sendEvent(r._client,"venmo.appswitch.handle.success"),e({nonce:(i=n).paymentMethodNonce,type:"VenmoAccount",details:{username:i.username}})):n.venmoError?(o.sendEvent(r._client,"venmo.appswitch.handle.error"),t(new c({type:l.VENMO_APP_FAILED.type,code:l.VENMO_APP_FAILED.code,message:l.VENMO_APP_FAILED.message,details:{originalError:{message:decodeURIComponent(n.errorMessage),code:n.errorCode}}}))):n.venmoCancel?(o.sendEvent(r._client,"venmo.appswitch.handle.cancel"),t(new c(l.VENMO_APP_CANCELED))):(o.sendEvent(r._client,"venmo.appswitch.cancel-or-unavailable"),t(new c(l.VENMO_CANCELED))),"function"==typeof a.history.replaceState&&a.location.hash&&history.pushState({},"",a.location.href.slice(0,a.location.href.indexOf("#")))})},y.exports=r.wrapPrototype(n)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lib/analytics":67,"../lib/braintree-error":72,"../lib/convert-methods-to-error":77,"../lib/methods":93,"../lib/promise":95,"../lib/querystring":96,"./shared/constants":114,"./shared/errors":115,"./shared/supports-venmo":116,"@braintree/wrap-promise":26}],118:[function(e,t,i){"use strict";var n,a={},o={},r="visa",s="mastercard",l="american-express",d="diners-club",c="discover",p="elo",u="jcb",h="unionpay",m="maestro",y="mir",f=[r,s,l,d,c,u,h,m,p,y];function g(e){return e?JSON.parse(JSON.stringify(e)):null}function v(e){return o[e]||a[e]}function b(i){var e,t,r=[];return"string"==typeof(t=i)||t instanceof String?0===i.length?n.map(function(e){return g(v(e))}):(n.forEach(function(e){var t=v(e);!function(e,t,i){var r,n,a,o;for(r=0;r<t.patterns.length;r++)if(n=t.patterns[r],E(e,n)){o=g(t),a=Array.isArray(n)?String(n[0]).length:String(n).length,e.length>=a&&(o.matchStrength=a),i.push(o);break}}(i,t,r)}),(e=function(e){var t,i;if(0<(i=(t=e).filter(function(e){return e.matchStrength}).length)&&i===t.length)return e.reduce(function(e,t){return e?e.matchStrength<t.matchStrength?t:e:t})}(r))?[e]:r):[]}function E(e,t){return Array.isArray(t)?(i=e,r=t[0],n=t[1],a=String(r).length,o=i.substr(0,a),s=parseInt(o,10),r=parseInt(String(r).substr(0,o.length),10),n=parseInt(String(n).substr(0,o.length),10),r<=s&&s<=n):(l=e,d=t,(d=String(d)).substring(0,l.length)===l.substring(0,d.length));var i,r,n,a,o,s,l,d}function _(e,t){var i=n.indexOf(e);if(!t&&-1===i)throw new Error('"'+e+'" is not a supported card type.');return i}n=g(f),a[r]={niceType:"Visa",type:r,patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},a[s]={niceType:"Mastercard",type:s,patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},a[l]={niceType:"American Express",type:l,patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},a[d]={niceType:"Diners Club",type:d,patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},a[c]={niceType:"Discover",type:c,patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},a.jcb={niceType:"JCB",type:u,patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},a[h]={niceType:"UnionPay",type:h,patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVN",size:3}},a[m]={niceType:"Maestro",type:m,patterns:[493698,[5e5,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},a.elo={niceType:"Elo",type:p,patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},a.mir={niceType:"Mir",type:y,patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},b.getTypeInfo=function(e){return g(v(e))},b.removeCard=function(e){var t=_(e);n.splice(t,1)},b.addCard=function(e){var t=_(e.type,!0);o[e.type]=e,-1===t&&n.push(e.type)},b.updateCard=function(e,t){var i,r=o[e]||a[e];if(!r)throw new Error('"'+e+'" is not a recognized type. Use `addCard` instead.');if(t.type&&r.type!==t.type)throw new Error("Cannot overwrite type parameter.");i=g(r),Object.keys(i).forEach(function(e){t[e]&&(i[e]=t[e])}),o[i.type]=i},b.changeOrder=function(e,t){var i=_(e);n.splice(i,1),n.splice(t,0,e)},b.resetModifications=function(){n=g(f),o={}},b.types={VISA:r,MASTERCARD:s,AMERICAN_EXPRESS:l,DINERS_CLUB:d,DISCOVER:c,JCB:u,UNIONPAY:h,MAESTRO:m,ELO:p,MIR:y},t.exports=b},{}],119:[function(e,E,t){(function(t){"use strict";var r,o,a=[],s={},l="/*framebus*/";function e(e){var t,i=d(this);return!c(e)&&(!c(i)&&(!1!==(t=p(e,Array.prototype.slice.call(arguments,1),i))&&(g(r.top||r.self,t,i),!0)))}function i(e,t){var i=d(this);return!b(e,t,i)&&(s[i]=s[i]||{},s[i][e]=s[i][e]||[],s[i][e].push(t),!0)}function n(e,t){var i,r,n=d(this);if(b(e,t,n))return!1;if(!(r=s[n]&&s[n][e]))return!1;for(i=0;i<r.length;i++)if(r[i]===t)return r.splice(i,1),!0;return!1}function d(e){return e&&e._origin||"*"}function c(e){return"string"!=typeof e}function p(e,t,i){var r=!1,n={event:e,origin:i},a=t[t.length-1];"function"==typeof a&&(n.reply=v(a,i),t=t.slice(0,-1)),n.args=t;try{r=l+JSON.stringify(n)}catch(e){throw new Error("Could not stringify event: "+e.message)}return r}function u(e){var t,i,r,n;if(e.data.slice(0,l.length)!==l)return!1;try{t=JSON.parse(e.data.slice(l.length))}catch(e){return!1}return null!=t.reply&&(i=e.origin,r=e.source,n=t.reply,t.reply=function(e){var t;return!!r&&(!1!==(t=p(n,[e],i))&&void r.postMessage(t,i))},t.args.push(t.reply)),t}function h(e){r||((r=e||t).addEventListener?r.addEventListener("message",y,!1):r.attachEvent?r.attachEvent("onmessage",y):null===r.onmessage?r.onmessage=y:r=null)}function m(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function y(e){var t;c(e.data)||(t=u(e))&&(f("*",t.event,t.args,e),f(e.origin,t.event,t.args,e),function(e,t,i){var r,n;for(r=a.length-1;0<=r;r--)!0===(n=a[r]).closed?a=a.slice(r,1):i!==n&&g(n.top,e,t)}(e.data,t.origin,e.source))}function f(e,t,i,r){var n;if(s[e]&&s[e][t])for(n=0;n<s[e][t].length;n++)s[e][t][n].apply(r,i)}function g(e,t,i){var r,n,a=0;try{for(e.postMessage(t,i),(n=e).top===n&&null!=n.opener&&n.opener!==n&&!0!==n.opener.closed&&g(e.opener.top,t,i);r=e.frames[a];)g(r,t,i),a++}catch(e){}}function v(r,n){var a=m();return o.target(n).subscribe(a,function e(t,i){r(t,i),o.target(n).unsubscribe(a,e)}),a}function b(e,t,i){return!!c(e)||("function"!=typeof t||!!c(i))}h(),o={target:function(e){var t,i={};for(t in o)o.hasOwnProperty(t)&&(i[t]=o[t]);return i._origin=e||"*",i},_packagePayload:p,_unpackPayload:u,_attach:h,_detach:function(){null!=r&&(r.removeEventListener?r.removeEventListener("message",y,!1):r.detachEvent?r.detachEvent("onmessage",y):r.onmessage===y&&(r.onmessage=null),r=null,a=[],s={})},_dispatch:f,_broadcast:g,_subscribeReplier:v,_subscriptionArgsInvalid:b,_onmessage:y,_uuid:m,_getSubscribers:function(){return s},_win:function(){return r},include:function(e){return null!=e&&null!=e.Window&&e.constructor===e.Window&&(a.push(e),!0)},publish:e,pub:e,trigger:e,emit:e,subscribe:i,sub:i,on:i,unsubscribe:n,unsub:n,off:n},E.exports=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],120:[function(e,t,i){var r,n,a=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function l(t){if(r===setTimeout)return setTimeout(t,0);if((r===o||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:o}catch(e){r=o}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(e){n=s}}();var d,c=[],p=!1,u=-1;function h(){p&&d&&(p=!1,d.length?c=d.concat(c):u=-1,c.length&&m())}function m(){if(!p){var e=l(h);p=!0;for(var t=c.length;t;){for(d=c,c=[];++u<t;)d&&d[u].run();u=-1,t=c.length}d=null,p=!1,function(t){if(n===clearTimeout)return clearTimeout(t);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(t);try{n(t)}catch(e){try{return n.call(null,t)}catch(e){return n.call(this,t)}}}(e)}}function y(e,t){this.fun=e,this.array=t}function f(){}a.nextTick=function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];c.push(new y(e,t)),1!==c.length||p||l(m)},y.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=f,a.addListener=f,a.once=f,a.off=f,a.removeListener=f,a.removeAllListeners=f,a.emit=f,a.prependListener=f,a.prependOnceListener=f,a.listeners=function(e){return[]},a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],121:[function(e,p,t){(function(t){"use strict";var i=setTimeout;function r(){}function a(e){if(!(this instanceof a))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],c(e,this)}function n(i,r){for(;3===i._state;)i=i._value;0!==i._state?(i._handled=!0,a._immediateFn(function(){var e=1===i._state?r.onFulfilled:r.onRejected;if(null!==e){var t;try{t=e(i._value)}catch(e){return void s(r.promise,e)}o(r.promise,t)}else(1===i._state?o:s)(r.promise,i._value)})):i._deferreds.push(r)}function o(t,e){try{if(e===t)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"==typeof e||"function"==typeof e)){var i=e.then;if(e instanceof a)return t._state=3,t._value=e,void l(t);if("function"==typeof i)return void c((r=i,n=e,function(){r.apply(n,arguments)}),t)}t._state=1,t._value=e,l(t)}catch(e){s(t,e)}var r,n}function s(e,t){e._state=2,e._value=t,l(e)}function l(e){2===e._state&&0===e._deferreds.length&&a._immediateFn(function(){e._handled||a._unhandledRejectionFn(e._value)});for(var t=0,i=e._deferreds.length;t<i;t++)n(e,e._deferreds[t]);e._deferreds=null}function d(e,t,i){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=i}function c(e,t){var i=!1;try{e(function(e){i||(i=!0,o(t,e))},function(e){i||(i=!0,s(t,e))})}catch(e){if(i)return;i=!0,s(t,e)}}a.prototype.catch=function(e){return this.then(null,e)},a.prototype.then=function(e,t){var i=new this.constructor(r);return n(this,new d(e,t,i)),i},a.prototype.finally=function(t){var i=this.constructor;return this.then(function(e){return i.resolve(t()).then(function(){return e})},function(e){return i.resolve(t()).then(function(){return i.reject(e)})})},a.all=function(t){return new a(function(r,n){if(!t||void 0===t.length)throw new TypeError("Promise.all accepts an array");var a=Array.prototype.slice.call(t);if(0===a.length)return r([]);var o=a.length;function s(t,e){try{if(e&&("object"==typeof e||"function"==typeof e)){var i=e.then;if("function"==typeof i)return void i.call(e,function(e){s(t,e)},n)}a[t]=e,0==--o&&r(a)}catch(e){n(e)}}for(var e=0;e<a.length;e++)s(e,a[e])})},a.resolve=function(t){return t&&"object"==typeof t&&t.constructor===a?t:new a(function(e){e(t)})},a.reject=function(i){return new a(function(e,t){t(i)})},a.race=function(n){return new a(function(e,t){for(var i=0,r=n.length;i<r;i++)n[i].then(e,t)})},a._immediateFn="function"==typeof t&&function(e){t(e)}||function(e){i(e,0)},a._unhandledRejectionFn=function(e){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)},p.exports=a}).call(this,e("timers").setImmediate)},{timers:124}],122:[function(s,l,e){(function(e){"use strict";var i=e.navigator&&e.navigator.userAgent,r=s("@braintree/browser-detection/is-android"),n=s("@braintree/browser-detection/is-chrome"),t=s("@braintree/browser-detection/is-ios"),a=s("@braintree/browser-detection/is-ie9"),o=/Version\/\d\.\d* Chrome\/\d*\.0\.0\.0/;l.exports={isIE9:a,isAndroidChrome:function(e){var t=e||i;return r(t)&&n(t)},isIos:t,isKitKatWebview:function(e){var t=e||i;return r(t)&&o.test(t)},isSamsungBrowser:function(e){return/SamsungBrowser/.test(e=e||i)||!n(t=e)&&-1<t.indexOf("Samsung");var t}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"@braintree/browser-detection/is-android":5,"@braintree/browser-detection/is-chrome":6,"@braintree/browser-detection/is-ie9":11,"@braintree/browser-detection/is-ios":15}],123:[function(e,t,i){"use strict";var r=e("./lib/device");t.exports=function(){return!r.isSamsungBrowser()}},{"./lib/device":122}],124:[function(l,e,d){(function(e,t){var r=l("process/browser.js").nextTick,i=Function.prototype.apply,n=Array.prototype.slice,a={},o=0;function s(e,t){this._id=e,this._clearFn=t}d.setTimeout=function(){return new s(i.call(setTimeout,window,arguments),clearTimeout)},d.setInterval=function(){return new s(i.call(setInterval,window,arguments),clearInterval)},d.clearTimeout=d.clearInterval=function(e){e.close()},s.prototype.unref=s.prototype.ref=function(){},s.prototype.close=function(){this._clearFn.call(window,this._id)},d.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},d.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},d._unrefActive=d.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;0<=t&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},d.setImmediate="function"==typeof e?e:function(e){var t=o++,i=!(arguments.length<2)&&n.call(arguments,1);return a[t]=!0,r(function(){a[t]&&(i?e.apply(null,i):e.call(null),d.clearImmediate(t))}),t},d.clearImmediate="function"==typeof t?t:function(e){delete a[e]}}).call(this,l("timers").setImmediate,l("timers").clearImmediate)},{"process/browser.js":120,timers:124}],125:[function(e,t,i){"use strict";t.exports={paymentOptionIDs:{card:"card",paypal:"paypal",paypalCredit:"paypalCredit",applePay:"applePay",venmo:"venmo",googlePay:"googlePay"},paymentMethodTypes:{card:"CreditCard",paypal:"PayPalAccount",paypalCredit:"PayPalAccount",applePay:"ApplePayCard",venmo:"VenmoAccount",googlePay:"AndroidPayCard"},analyticsKinds:{CreditCard:"card",PayPalAccount:"paypal",ApplePayCard:"applepay",VenmoAccount:"venmo",AndroidPayCard:"googlepay"},paymentMethodCardTypes:{Visa:"visa",MasterCard:"master-card","American Express":"american-express","Diners Club":"diners-club",Discover:"discover",JCB:"jcb",UnionPay:"unionpay",Maestro:"maestro"},configurationCardTypes:{visa:"Visa","master-card":"MasterCard","american-express":"American Express","diners-club":"Discover",discover:"Discover",jcb:"JCB",unionpay:"UnionPay",maestro:"Maestro"},errors:{NO_PAYMENT_METHOD_ERROR:"No payment method is available.",DEVELOPER_MISCONFIGURATION_MESSAGE:"Developer Error: Something went wrong. Check the console for details."},ANALYTICS_REQUEST_TIMEOUT_MS:2e3,ANALYTICS_PREFIX:"web.dropin.",CHANGE_ACTIVE_PAYMENT_METHOD_TIMEOUT:200,CHECKOUT_JS_SOURCE:"https://www.paypalobjects.com/api/checkout.min.js",GOOGLE_PAYMENT_SOURCE:"https://pay.google.com/gp/p/js/pay.js",INTEGRATION:"dropin2",PAYPAL_CHECKOUT_SCRIPT_ID:"braintree-dropin-paypal-checkout-script",GOOGLE_PAYMENT_SCRIPT_ID:"braintree-dropin-google-payment-script",DATA_COLLECTOR_SCRIPT_ID:"braintree-dropin-data-collector-script",STYLESHEET_ID:"braintree-dropin-stylesheet"}},{}],126:[function(e,t,i){"use strict";var r=e("./lib/analytics"),o=e("./lib/dropin-error"),n=e("./lib/event-emitter"),a=e("./constants"),s=a.paymentMethodTypes,l=a.paymentOptionIDs,d=e("./lib/is-guest-checkout"),c=e("./lib/promise"),p=e("./views/payment-sheet-views"),u=e("braintree-web/vault-manager"),h=[s.applePay,s.googlePay,s.venmo],m=[l.card,l.paypal,l.paypalCredit,l.venmo,l.applePay,l.googlePay];function y(e){this.componentID=e.componentID,this.merchantConfiguration=e.merchantConfiguration,this.isGuestCheckout=d(e.client),this.dependenciesInitializing=0,this.dependencySuccessCount=0,this.failedDependencies={},this._options=e,n.call(this)}(y.prototype=Object.create(n.prototype,{constructor:y})).initialize=function(){var t=this;return u.create({client:t._options.client}).then(function(e){return t._vaultManager=e,function(a){var e,i=a.merchantConfiguration.paymentOptionPriority||m;if(i instanceof Array)return i=i.filter(function(e,t){return i.indexOf(e)===t}),e=i.map(function(e){return(i=t=e,r=a,n=p[l[i]],n?n.isEnabled({client:r.client,merchantConfiguration:r.merchantConfiguration}).catch(function(e){return console.error(n.ID+" view errored when checking if it was supported."),console.error(e),c.resolve(!1)}):c.reject(new o("paymentOptionPriority: Invalid payment option specified."))).then(function(e){return{success:e,id:l[t]}});var t,i,r,n}),c.all(e).then(function(e){return 0===(e=e.filter(function(e){return e.success})).length?c.reject(new o("No valid payment options available.")):e.map(function(e){return e.id})});throw new o("paymentOptionPriority must be an array.")}(t._options)}).then(function(e){return t.supportedPaymentOptions=e,t.getVaultedPaymentMethods()}).then(function(e){t._paymentMethods=e,t._paymentMethodIsRequestable=0<t._paymentMethods.length})},y.prototype.isPaymentMethodRequestable=function(){return Boolean(this._paymentMethodIsRequestable)},y.prototype.addPaymentMethod=function(e){this._paymentMethods.push(e),this._emit("addPaymentMethod",e),this.changeActivePaymentMethod(e)},y.prototype.removePaymentMethod=function(e){var t=this._paymentMethods.indexOf(e);-1!==t&&(this._paymentMethods.splice(t,1),this._emit("removePaymentMethod",e))},y.prototype.refreshPaymentMethods=function(){var t=this;return t.getVaultedPaymentMethods().then(function(e){t._paymentMethods=e,t._emit("refreshPaymentMethods")})},y.prototype.changeActivePaymentMethod=function(e){this._activePaymentMethod=e,this._emit("changeActivePaymentMethod",e)},y.prototype.changeActivePaymentView=function(e){this._activePaymentView=e,this._emit("changeActivePaymentView",e)},y.prototype.removeActivePaymentMethod=function(){this._activePaymentMethod=null,this._emit("removeActivePaymentMethod"),this.setPaymentMethodRequestable({isRequestable:!1})},y.prototype.selectPaymentOption=function(e){this._emit("paymentOptionSelected",{paymentOption:e})},y.prototype.enableEditMode=function(){r.sendEvent(this._options.client,"manager.appeared"),this._isInEditMode=!0,this._emit("enableEditMode")},y.prototype.disableEditMode=function(){this._isInEditMode=!1,this._emit("disableEditMode")},y.prototype.isInEditMode=function(){return Boolean(this._isInEditMode)},y.prototype.confirmPaymentMethodDeletion=function(e){this._paymentMethodWaitingToBeDeleted=e,this._emit("confirmPaymentMethodDeletion",e)},y.prototype._shouldEmitRequestableEvent=function(e){var t=this.isPaymentMethodRequestable()===e.isRequestable,i=e.type===this._paymentMethodRequestableType;return!(t&&(!e.isRequestable||i))},y.prototype.setPaymentMethodRequestable=function(e){var t=this._shouldEmitRequestableEvent(e),i={paymentMethodIsSelected:Boolean(e.selectedPaymentMethod),type:e.type};this._paymentMethodIsRequestable=e.isRequestable,e.isRequestable?this._paymentMethodRequestableType=e.type:delete this._paymentMethodRequestableType,t&&(e.isRequestable?this._emit("paymentMethodRequestable",i):this._emit("noPaymentMethodRequestable"))},y.prototype.getPaymentMethods=function(){return this._paymentMethods.slice()},y.prototype.getActivePaymentMethod=function(){return this._activePaymentMethod},y.prototype.getActivePaymentView=function(){return this._activePaymentView},y.prototype.reportAppSwitchPayload=function(e){this.appSwitchPayload=e},y.prototype.reportAppSwitchError=function(e,t){this.appSwitchError={id:e,error:t}},y.prototype.asyncDependencyStarting=function(){this.dependenciesInitializing++},y.prototype.asyncDependencyReady=function(){this.dependencySuccessCount++,this.dependenciesInitializing--,this._checkAsyncDependencyFinished()},y.prototype.asyncDependencyFailed=function(e){this.failedDependencies.hasOwnProperty(e.view)||(this.failedDependencies[e.view]=e.error,this.dependenciesInitializing--,this._checkAsyncDependencyFinished())},y.prototype._checkAsyncDependencyFinished=function(){0===this.dependenciesInitializing&&this._emit("asyncDependenciesReady")},y.prototype.cancelInitialization=function(e){this._emit("cancelInitialization",e)},y.prototype.reportError=function(e){this._emit("errorOccurred",e)},y.prototype.clearError=function(){this._emit("errorCleared")},y.prototype.preventUserAction=function(){this._emit("preventUserAction")},y.prototype.allowUserAction=function(){this._emit("allowUserAction")},y.prototype.deleteVaultedPaymentMethod=function(){var t,e=this,i=c.resolve();return this._emit("startVaultedPaymentMethodDeletion"),e.isGuestCheckout||(i=this._vaultManager.deletePaymentMethod(this._paymentMethodWaitingToBeDeleted.nonce).catch(function(e){t=e})),i.then(function(){return delete e._paymentMethodWaitingToBeDeleted,e.refreshPaymentMethods()}).then(function(){e.disableEditMode(),e._emit("finishVaultedPaymentMethodDeletion",t)})},y.prototype.cancelDeleteVaultedPaymentMethod=function(){this._emit("cancelVaultedPaymentMethodDeletion"),delete this._paymentMethodWaitingToBeDeleted},y.prototype.getVaultedPaymentMethods=function(){var t=this;return t.isGuestCheckout?c.resolve([]):t._vaultManager.fetchPaymentMethods({defaultFirst:!0}).then(function(e){return t._getSupportedPaymentMethods(e).map(function(e){return e.vaulted=!0,e})}).catch(function(){return c.resolve([])})},y.prototype._getSupportedPaymentMethods=function(e){var t=this.supportedPaymentOptions.reduce(function(e,t){var i,r=s[t];return(i=r)&&-1===h.indexOf(i)&&e.push(r),e},[]);return e.filter(function(e){return-1<t.indexOf(e.type)})},t.exports=y},{"./constants":125,"./lib/analytics":130,"./lib/dropin-error":135,"./lib/event-emitter":136,"./lib/is-guest-checkout":138,"./lib/promise":143,"./views/payment-sheet-views":183,"braintree-web/vault-manager":110}],127:[function(e,t,i){"use strict";var a=e("./lib/assign").assign,o=e("./lib/analytics"),s=e("@braintree/class-list"),l=e("./constants"),d=e("./lib/dropin-error"),c=e("./dropin-model"),r=e("./lib/event-emitter"),n=e("@braintree/asset-loader"),p=e("./views/main-view"),u=e("./views/payment-methods-view").ID,h=e("./views/payment-options-view").ID,m=l.paymentOptionIDs,y=e("./translations").translations,f=e("./lib/is-utf-8"),g=e("./lib/uuid"),v=e("./lib/promise"),b=e("./lib/sanitize-html"),E=e("./lib/data-collector"),_=e("./lib/three-d-secure"),C=e("@braintree/wrap-promise").wrapPrototype,P=[m.paypal,m.paypalCredit,m.applePay,m.googlePay,"threeDSecure"],T=[m.paypal,m.paypalCredit,m.applePay,m.googlePay],A={};function I(e){this._client=e.client,this._componentID=g(),this._dropinWrapper=document.createElement("div"),this._dropinWrapper.id="braintree--dropin__"+this._componentID,this._dropinWrapper.setAttribute("data-braintree-id","wrapper"),this._dropinWrapper.style.display="none",this._dropinWrapper.className="braintree-loading",this._merchantConfiguration=e.merchantConfiguration,r.call(this)}A[l.paymentMethodTypes.googlePay]=!0,A[l.paymentMethodTypes.applePay]=!0,(I.prototype=Object.create(r.prototype,{constructor:I}))._initialize=function(t){var e,i,r=this,n=r._merchantConfiguration.container||r._merchantConfiguration.selector;return r._injectStylesheet(),n?r._merchantConfiguration.container&&r._merchantConfiguration.selector?(o.sendEvent(r._client,"configuration-error"),void t(new d("Must only have one options.selector or options.container."))):("string"==typeof n&&(n=document.querySelector(n)),n&&1===n.nodeType?n.innerHTML.trim()?(o.sendEvent(r._client,"configuration-error"),void t(new d("options.selector or options.container must reference an empty DOM node."))):(r._strings=a({},y.en),r._merchantConfiguration.locale&&(e=y[r._merchantConfiguration.locale]||y[r._merchantConfiguration.locale.split("_")[0]],r._strings=a(r._strings,e)),f()||(r._strings.endingIn=r._strings.endingIn.replace(/•/g,"*")),r._merchantConfiguration.translations&&Object.keys(r._merchantConfiguration.translations).forEach(function(e){r._strings[e]=b(r._merchantConfiguration.translations[e])}),i=Object.keys(r._strings).reduce(function(e,t){var i=r._strings[t];return e.replace(RegExp("{{"+t+"}}","g"),i)},'<div class="braintree-dropin">\n  <div data-braintree-id="methods-label" class="braintree-heading">&nbsp;</div>\n  <div data-braintree-id="methods-edit" class="braintree-hidden braintree-heading">{{edit}}</div>\n  <div data-braintree-id="choose-a-way-to-pay" class="braintree-heading">{{chooseAWayToPay}}</div>\n  <div class="braintree-placeholder">&nbsp;</div>\n\n  <div data-braintree-id="upper-container" class="braintree-upper-container">\n    <div data-braintree-id="loading-container" class="braintree-loader__container">\n      <div data-braintree-id="loading-indicator" class="braintree-loader__indicator">\n        <svg width="14" height="16" class="braintree-loader__lock">\n          <use xlink:href="#iconLockLoader"></use>\n        </svg>\n      </div>\n    </div>\n\n    <div data-braintree-id="delete-confirmation" class="braintree-delete-confirmation braintree-sheet">\n      <div data-braintree-id="delete-confirmation__message"></div>\n      <div class="braintree-delete-confirmation__button-container">\n        <div role="button" data-braintree-id="delete-confirmation__no" class="braintree-delete-confirmation__button">{{deleteCancelButton}}</div>\n        <div role="button" data-braintree-id="delete-confirmation__yes" class="braintree-delete-confirmation__button">{{deleteConfirmationButton}}</div>\n      </div>\n    </div>\n\n    <div data-braintree-id="methods" class="braintree-methods braintree-methods-initial">\n      <div data-braintree-id="methods-container"></div>\n    </div>\n\n    <div data-braintree-id="options" class="braintree-test-class braintree-options braintree-options-initial">\n      <div data-braintree-id="payment-options-container" class="braintree-options-list"></div>\n    </div>\n\n    <div data-braintree-id="sheet-container" class="braintree-sheet__container">\n      <div data-braintree-id="paypal" class="braintree-paypal braintree-sheet">\n        <div data-braintree-id="paypal-sheet-header" class="braintree-sheet__header">\n          <div class="braintree-sheet__header-label">\n            <div class="braintree-sheet__logo--header">\n              <svg width="40" height="24">\n                <use xlink:href="#logoPayPal"></use>\n              </svg>\n            </div>\n            <div class="braintree-sheet__label">{{PayPal}}</div>\n          </div>\n        </div>\n        <div class="braintree-sheet__content braintree-sheet__content--button">\n          <div data-braintree-id="paypal-button" class="braintree-sheet__button--paypal"></div>\n        </div>\n      </div>\n      <div data-braintree-id="paypalCredit" class="braintree-paypalCredit braintree-sheet">\n        <div data-braintree-id="paypal-credit-sheet-header" class="braintree-sheet__header">\n          <div class="braintree-sheet__header-label">\n            <div class="braintree-sheet__logo--header">\n              <svg width="40" height="24">\n                <use xlink:href="#logoPayPalCredit"></use>\n              </svg>\n            </div>\n            <div class="braintree-sheet__label">{{PayPal Credit}}</div>\n          </div>\n        </div>\n        <div class="braintree-sheet__content braintree-sheet__content--button">\n          <div data-braintree-id="paypal-credit-button" class="braintree-sheet__button--paypal"></div>\n        </div>\n      </div>\n      <div data-braintree-id="applePay" class="braintree-applePay braintree-sheet">\n        <div data-braintree-id="apple-pay-sheet-header" class="braintree-sheet__header">\n          <div class="braintree-sheet__header-label">\n            <div class="braintree-sheet__logo--header">\n              <svg height="24" width="40">\n              <use xlink:href="#logoApplePay"></use>\n              </svg>\n            </div>\n            <div class="braintree-sheet__label">{{Apple Pay}}</div>\n          </div>\n        </div>\n        <div class="braintree-sheet__content braintree-sheet__content--button">\n          <div data-braintree-id="apple-pay-button" class="braintree-sheet__button--apple-pay apple-pay-button"></div>\n        </div>\n      </div>\n      <div data-braintree-id="googlePay" class="braintree-googlePay braintree-sheet">\n        <div data-braintree-id="google-pay-sheet-header" class="braintree-sheet__header">\n          <div class="braintree-sheet__header-label">\n            <div class="braintree-sheet__logo--header">\n              <svg height="24" width="40">\n              <use xlink:href="#logoGooglePay"></use>\n              </svg>\n            </div>\n            <div class="braintree-sheet__label">{{Google Pay}}</div>\n          </div>\n        </div>\n        <div class="braintree-sheet__content braintree-sheet__content--button">\n          <div data-braintree-id="google-pay-button"></div>\n        </div>\n      </div>\n      <div data-braintree-id="venmo" class="braintree-venmo braintree-sheet">\n        <div data-braintree-id="venmo-sheet-header" class="braintree-sheet__header">\n          <div class="braintree-sheet__header-label">\n            <div class="braintree-sheet__logo--header">\n              <svg height="24" width="40">\n              <use xlink:href="#logoVenmo"></use>\n              </svg>\n            </div>\n            <div class="braintree-sheet__label">{{Venmo}}</div>\n          </div>\n        </div>\n        <div class="braintree-sheet__content braintree-sheet__content--button">\n          <svg data-braintree-id="venmo-button" class="braintree-sheet__button--venmo">\n            <use xlink:href="#buttonVenmo"></use>\n          </svg>\n        </div>\n      </div>\n      <div data-braintree-id="card" class="braintree-card braintree-form braintree-sheet">\n        <div data-braintree-id="card-sheet-header" class="braintree-sheet__header">\n          <div class="braintree-sheet__header-label">\n            <div class="braintree-sheet__logo--header">\n              <svg width="40" height="24" class="braintree-icon--bordered">\n                <use xlink:href="#iconCardFront"></use>\n              </svg>\n            </div>\n            <div class="braintree-sheet__text">{{payWithCard}}</div>\n          </div>\n          <div data-braintree-id="card-view-icons" class="braintree-sheet__icons"></div>\n        </div>\n        <div class="braintree-sheet__content braintree-sheet__content--form">\n          <div data-braintree-id="cardholder-name-field-group" class="braintree-form__field-group">\n            <label for="braintree__card-view-input__cardholder-name">\n              <div class="braintree-form__label">{{cardholderNameLabel}}</div>\n              <div class="braintree-form__field">\n                <div class="braintree-form-cardholder-name braintree-form__hosted-field">\n                  <input class="braintree-form__raw-input" id="braintree__card-view-input__cardholder-name" type="text" placeholder="{{cardholderNamePlaceholder}}"/>\n                </div>\n                <div class="braintree-form__icon-container">\n                  <div class="braintree-form__icon braintree-form__field-error-icon">\n                    <svg width="24" height="24">\n                      <use xlink:href="#iconError"></use>\n                    </svg>\n                  </div>\n                </div>\n              </div>\n            </label>\n            <div data-braintree-id="cardholder-name-field-error" class="braintree-form__field-error"></div>\n          </div>\n          <div data-braintree-id="number-field-group" class="braintree-form__field-group">\n            <label>\n              <div class="braintree-form__label">{{cardNumberLabel}}</div>\n              <div class="braintree-form__field">\n                <div class="braintree-form-number braintree-form__hosted-field"></div>\n                <div class="braintree-form__icon-container">\n                  <div data-braintree-id="card-number-icon" class="braintree-form__icon braintree-form__field-secondary-icon">\n                    <svg width="40" height="24" class="braintree-icon--bordered">\n                    <use data-braintree-id="card-number-icon-svg" xlink:href="#iconCardFront"></use>\n                    </svg>\n                  </div>\n                  <div class="braintree-form__icon braintree-form__field-error-icon">\n                    <svg width="24" height="24">\n                      <use xlink:href="#iconError"></use>\n                    </svg>\n                  </div>\n                </div>\n              </div>\n            </label>\n            <div data-braintree-id="number-field-error" class="braintree-form__field-error"></div>\n          </div>\n\n          <div class="braintree-form__flexible-fields">\n            <div data-braintree-id="expiration-date-field-group" class="braintree-form__field-group">\n              <label>\n                <div class="braintree-form__label">{{expirationDateLabel}}\n                  <span class="braintree-form__descriptor">{{expirationDateLabelSubheading}}</span>\n                </div>\n                <div class="braintree-form__field">\n                  <div class="braintree-form__hosted-field braintree-form-expiration"></div>\n                  <div class="braintree-form__icon-container">\n                    <div class="braintree-form__icon braintree-form__field-error-icon">\n                      <svg width="24" height="24">\n                        <use xlink:href="#iconError"></use>\n                      </svg>\n                    </div>\n                  </div>\n                </div>\n              </label>\n              <div data-braintree-id="expiration-date-field-error" class="braintree-form__field-error"></div>\n            </div>\n            \n\n            <div data-braintree-id="cvv-field-group" class="braintree-form__field-group">\n              <label>\n                <div class="braintree-form__label">{{cvvLabel}}\n                  <span data-braintree-id="cvv-label-descriptor" class="braintree-form__descriptor">{{cvvThreeDigitLabelSubheading}}</span>\n                </div>\n                <div class="braintree-form__field">\n                  <div class="braintree-form__hosted-field braintree-form-cvv"></div>\n                  <div class="braintree-form__icon-container">\n                    <div data-braintree-id="cvv-icon" class="braintree-form__icon braintree-form__field-secondary-icon">\n                      <svg width="40" height="24" class="braintree-icon--bordered">\n                      <use data-braintree-id="cvv-icon-svg" xlink:href="#iconCVVBack"></use>\n                      </svg>\n                    </div>\n                    <div class="braintree-form__icon braintree-form__field-error-icon">\n                      <svg width="24" height="24">\n                        <use xlink:href="#iconError"></use>\n                      </svg>\n                    </div>\n                  </div>\n                </div>\n              </label>\n              <div data-braintree-id="cvv-field-error" class="braintree-form__field-error"></div>\n            </div>\n\n            <div data-braintree-id="postal-code-field-group" class="braintree-form__field-group">\n              <label>\n                <div class="braintree-form__label">{{postalCodeLabel}}</div>\n                <div class="braintree-form__field">\n                  <div class="braintree-form__hosted-field braintree-form-postal-code"></div>\n                  <div class="braintree-form__icon-container">\n                    <div class="braintree-form__icon braintree-form__field-error-icon">\n                      <svg width="24" height="24">\n                        <use xlink:href="#iconError"></use>\n                      </svg>\n                    </div>\n                  </div>\n                </div>\n              </label>\n              <div data-braintree-id="postal-code-field-error" class="braintree-form__field-error"></div>\n            </div>\n          </div>\n        </div>\n      </div>\n      <div data-braintree-id="sheet-error" class="braintree-sheet__error">\n        <div class="braintree-form__icon braintree-sheet__error-icon">\n          <svg width="24" height="24">\n            <use xlink:href="#iconError"></use>\n          </svg>\n        </div>\n        <div data-braintree-id="sheet-error-text" class="braintree-sheet__error-text"></div>\n      </div>\n    </div>\n  </div>\n\n  <div data-braintree-id="lower-container" class="braintree-test-class braintree-options braintree-hidden">\n    <div data-braintree-id="other-ways-to-pay" class="braintree-heading">{{otherWaysToPay}}</div>\n  </div>\n\n  <div data-braintree-id="toggle" class="braintree-large-button braintree-toggle braintree-hidden" tabindex="0">\n    <span>{{chooseAnotherWayToPay}}</span>\n  </div>\n</div>\n<div data-braintree-id="disable-wrapper" class="braintree-dropin__disabled braintree-hidden"></div>\n'),r._dropinWrapper.innerHTML='<svg data-braintree-id="svgs" style="display: none">\n  <defs>\n    <symbol id="icon-visa" viewBox="0 0 40 24">\n      <title>Visa</title>\n      <path d="M0 1.927C0 .863.892 0 1.992 0h36.016C39.108 0 40 .863 40 1.927v20.146C40 23.137 39.108 24 38.008 24H1.992C.892 24 0 23.137 0 22.073V1.927z" style="fill: #FFF" />\n      <path d="M0 22.033C0 23.12.892 24 1.992 24h36.016c1.1 0 1.992-.88 1.992-1.967V20.08H0v1.953z" style="fill: #F8B600" />\n      <path d="M0 3.92h40V1.967C40 .88 39.108 0 38.008 0H1.992C.892 0 0 .88 0 1.967V3.92zM19.596 7.885l-2.11 9.478H14.93l2.11-9.478h2.554zm10.743 6.12l1.343-3.56.773 3.56H30.34zm2.85 3.358h2.36l-2.063-9.478H31.31c-.492 0-.905.274-1.088.695l-3.832 8.783h2.682l.532-1.415h3.276l.31 1.415zm-6.667-3.094c.01-2.502-3.6-2.64-3.577-3.76.008-.338.345-.7 1.083-.793.365-.045 1.373-.08 2.517.425l.448-2.01c-.615-.214-1.405-.42-2.39-.42-2.523 0-4.3 1.288-4.313 3.133-.016 1.364 1.268 2.125 2.234 2.58.996.464 1.33.762 1.325 1.177-.006.636-.793.918-1.526.928-1.285.02-2.03-.333-2.623-.6l-.462 2.08c.598.262 1.7.49 2.84.502 2.682 0 4.437-1.273 4.445-3.243zM15.948 7.884l-4.138 9.478h-2.7L7.076 9.8c-.123-.466-.23-.637-.606-.834-.615-.32-1.63-.62-2.52-.806l.06-.275h4.345c.554 0 1.052.354 1.178.966l1.076 5.486 2.655-6.45h2.683z" style="fill: #1A1F71" />\n    </symbol>\n\n    <symbol id="icon-master-card" viewBox="0 0 40 24">\n      <title>MasterCard</title>\n      <path d="M0 1.927C0 .863.892 0 1.992 0h36.016C39.108 0 40 .863 40 1.927v20.146C40 23.137 39.108 24 38.008 24H1.992C.892 24 0 23.137 0 22.073V1.927z" style="fill: #FFF" />\n      <path d="M11.085 22.2v-1.36c0-.522-.318-.863-.864-.863-.272 0-.568.09-.773.386-.16-.25-.386-.386-.727-.386-.228 0-.455.068-.637.318v-.272h-.478V22.2h.478v-1.202c0-.386.204-.567.523-.567.318 0 .478.205.478.568V22.2h.477v-1.202c0-.386.23-.567.524-.567.32 0 .478.205.478.568V22.2h.523zm7.075-2.177h-.774v-.658h-.478v.658h-.432v.43h.432v.998c0 .5.205.795.75.795.206 0 .433-.068.592-.16l-.136-.407c-.136.09-.296.114-.41.114-.227 0-.318-.137-.318-.363v-.976h.774v-.43zm4.048-.046c-.273 0-.454.136-.568.318v-.272h-.478V22.2h.478v-1.225c0-.363.16-.567.455-.567.09 0 .204.023.295.046l.137-.454c-.09-.023-.228-.023-.32-.023zm-6.118.227c-.228-.16-.546-.227-.888-.227-.546 0-.91.272-.91.703 0 .363.274.567.75.635l.23.023c.25.045.385.113.385.227 0 .16-.182.272-.5.272-.32 0-.57-.113-.728-.227l-.228.363c.25.18.59.272.932.272.637 0 1-.295 1-.703 0-.385-.295-.59-.75-.658l-.227-.022c-.205-.023-.364-.068-.364-.204 0-.16.16-.25.41-.25.272 0 .545.114.682.182l.205-.386zm12.692-.227c-.273 0-.455.136-.568.318v-.272h-.478V22.2h.478v-1.225c0-.363.16-.567.455-.567.09 0 .203.023.294.046L29.1 20c-.09-.023-.227-.023-.318-.023zm-6.096 1.134c0 .66.455 1.135 1.16 1.135.32 0 .546-.068.774-.25l-.228-.385c-.182.136-.364.204-.57.204-.385 0-.658-.272-.658-.703 0-.407.273-.68.66-.702.204 0 .386.068.568.204l.228-.385c-.228-.182-.455-.25-.774-.25-.705 0-1.16.477-1.16 1.134zm4.413 0v-1.087h-.48v.272c-.158-.204-.385-.318-.68-.318-.615 0-1.093.477-1.093 1.134 0 .66.478 1.135 1.092 1.135.317 0 .545-.113.68-.317v.272h.48v-1.09zm-1.753 0c0-.384.25-.702.66-.702.387 0 .66.295.66.703 0 .387-.273.704-.66.704-.41-.022-.66-.317-.66-.703zm-5.71-1.133c-.636 0-1.09.454-1.09 1.134 0 .682.454 1.135 1.114 1.135.32 0 .638-.09.888-.295l-.228-.34c-.18.136-.41.227-.636.227-.296 0-.592-.136-.66-.522h1.615v-.18c.022-.704-.388-1.158-1.002-1.158zm0 .41c.297 0 .502.18.547.52h-1.137c.045-.295.25-.52.59-.52zm11.852.724v-1.95h-.48v1.135c-.158-.204-.385-.318-.68-.318-.615 0-1.093.477-1.093 1.134 0 .66.478 1.135 1.092 1.135.318 0 .545-.113.68-.317v.272h.48v-1.09zm-1.752 0c0-.384.25-.702.66-.702.386 0 .66.295.66.703 0 .387-.274.704-.66.704-.41-.022-.66-.317-.66-.703zm-15.97 0v-1.087h-.476v.272c-.16-.204-.387-.318-.683-.318-.615 0-1.093.477-1.093 1.134 0 .66.478 1.135 1.092 1.135.318 0 .545-.113.682-.317v.272h.477v-1.09zm-1.773 0c0-.384.25-.702.66-.702.386 0 .66.295.66.703 0 .387-.274.704-.66.704-.41-.022-.66-.317-.66-.703z" style="fill: #000" />\n      <path style="fill: #FF5F00" d="M23.095 3.49H15.93v12.836h7.165" />\n      <path d="M16.382 9.91c0-2.61 1.23-4.922 3.117-6.42-1.39-1.087-3.14-1.745-5.05-1.745-4.528 0-8.19 3.65-8.19 8.164 0 4.51 3.662 8.162 8.19 8.162 1.91 0 3.66-.657 5.05-1.746-1.89-1.474-3.118-3.81-3.118-6.417z" style="fill: #EB001B" />\n      <path d="M32.76 9.91c0 4.51-3.664 8.162-8.19 8.162-1.91 0-3.662-.657-5.05-1.746 1.91-1.496 3.116-3.81 3.116-6.417 0-2.61-1.228-4.922-3.116-6.42 1.388-1.087 3.14-1.745 5.05-1.745 4.526 0 8.19 3.674 8.19 8.164z" style="fill: #F79E1B" />\n    </symbol>\n\n    <symbol id="icon-unionpay" viewBox="0 0 40 24">\n      <title>Union Pay</title>\n      <path d="M38.333 24H1.667C.75 24 0 23.28 0 22.4V1.6C0 .72.75 0 1.667 0h36.666C39.25 0 40 .72 40 1.6v20.8c0 .88-.75 1.6-1.667 1.6z" style="fill: #FFF" />\n      <path d="M9.877 2h8.126c1.135 0 1.84.93 1.575 2.077l-3.783 16.35c-.267 1.142-1.403 2.073-2.538 2.073H5.13c-1.134 0-1.84-.93-1.574-2.073L7.34 4.076C7.607 2.93 8.74 2 9.878 2z" style="fill: #E21836" />\n      <path d="M17.325 2h9.345c1.134 0 .623.93.356 2.077l-3.783 16.35c-.265 1.142-.182 2.073-1.32 2.073H12.58c-1.137 0-1.84-.93-1.574-2.073l3.783-16.35C15.056 2.93 16.19 2 17.324 2z" style="fill: #00447B" />\n      <path d="M26.3 2h8.126c1.136 0 1.84.93 1.575 2.077l-3.782 16.35c-.266 1.142-1.402 2.073-2.54 2.073h-8.122c-1.137 0-1.842-.93-1.574-2.073l3.78-16.35C24.03 2.93 25.166 2 26.303 2z" style="fill: #007B84" />\n      <path d="M27.633 14.072l-.99 3.3h.266l-.208.68h-.266l-.062.212h-.942l.064-.21H23.58l.193-.632h.194l1.005-3.35.2-.676h.962l-.1.34s.255-.184.498-.248c.242-.064 1.636-.088 1.636-.088l-.206.672h-.33zm-1.695 0l-.254.843s.285-.13.44-.172c.16-.04.395-.057.395-.057l.182-.614h-.764zm-.38 1.262l-.263.877s.29-.15.447-.196c.157-.037.396-.066.396-.066l.185-.614h-.766zm-.614 2.046h.767l.222-.74h-.765l-.223.74z" style="fill: #FEFEFE" />\n      <path d="M28.055 13.4h1.027l.01.385c-.005.065.05.096.17.096h.208l-.19.637h-.555c-.48.035-.662-.172-.65-.406l-.02-.71zM28.193 16.415h-.978l.167-.566H28.5l.16-.517h-1.104l.19-.638h3.072l-.193.638h-1.03l-.16.516h1.032l-.17.565H29.18l-.2.24h.454l.11.712c.013.07.014.116.036.147.023.026.158.038.238.038h.137l-.21.694h-.348c-.054 0-.133-.004-.243-.01-.105-.008-.18-.07-.25-.105-.064-.03-.16-.11-.182-.24l-.11-.712-.507.7c-.162.222-.38.39-.748.39h-.712l.186-.62h.273c.078 0 .15-.03.2-.056.052-.023.098-.05.15-.126l.74-1.05zM17.478 14.867h2.59l-.19.622H18.84l-.16.53h1.06l-.194.64h-1.06l-.256.863c-.03.095.25.108.353.108l.53-.072-.212.71h-1.193c-.096 0-.168-.013-.272-.037-.1-.023-.145-.07-.19-.138-.043-.07-.11-.128-.064-.278l.343-1.143h-.588l.195-.65h.592l.156-.53h-.588l.188-.623zM19.223 13.75h1.063l-.194.65H18.64l-.157.136c-.067.066-.09.038-.18.087-.08.04-.254.123-.477.123h-.466l.19-.625h.14c.118 0 .198-.01.238-.036.046-.03.098-.096.157-.203l.267-.487h1.057l-.187.356zM20.74 13.4h.905l-.132.46s.286-.23.487-.313c.2-.075.65-.143.65-.143l1.464-.007-.498 1.672c-.085.286-.183.472-.244.555-.055.087-.12.16-.248.23-.124.066-.236.104-.34.115-.096.007-.244.01-.45.012h-1.41l-.4 1.324c-.037.13-.055.194-.03.23.02.03.068.066.135.066l.62-.06-.21.726h-.698c-.22 0-.383-.004-.495-.013-.108-.01-.22 0-.295-.058-.065-.058-.164-.133-.162-.21.007-.073.037-.192.082-.356l1.268-4.23zm1.922 1.69h-1.484l-.09.3h1.283c.152-.018.184.004.196-.003l.096-.297zm-1.402-.272s.29-.266.786-.353c.112-.022.82-.015.82-.015l.106-.357h-1.496l-.216.725z" style="fill: #FEFEFE" />\n      <path d="M23.382 16.1l-.084.402c-.036.125-.067.22-.16.302-.1.084-.216.172-.488.172l-.502.02-.004.455c-.006.13.028.117.048.138.024.022.045.032.067.04l.157-.008.48-.028-.198.663h-.552c-.385 0-.67-.008-.765-.084-.092-.057-.105-.132-.103-.26l.035-1.77h.88l-.013.362h.212c.072 0 .12-.007.15-.026.027-.02.047-.048.06-.093l.087-.282h.692zM10.84 7.222c-.032.143-.596 2.763-.598 2.764-.12.53-.21.91-.508 1.152-.172.14-.37.21-.6.21-.37 0-.587-.185-.624-.537l-.007-.12.113-.712s.593-2.388.7-2.703c.002-.017.005-.026.007-.035-1.152.01-1.357 0-1.37-.018-.007.024-.037.173-.037.173l-.605 2.688-.05.23-.1.746c0 .22.042.4.13.553.275.485 1.06.557 1.504.557.573 0 1.11-.123 1.47-.345.63-.375.797-.962.944-1.48l.067-.267s.61-2.48.716-2.803c.003-.017.006-.026.01-.035-.835.01-1.08 0-1.16-.018zM14.21 12.144c-.407-.006-.55-.006-1.03.018l-.018-.036c.042-.182.087-.363.127-.548l.06-.25c.086-.39.173-.843.184-.98.007-.084.036-.29-.2-.29-.1 0-.203.048-.307.096-.058.207-.174.79-.23 1.055-.118.558-.126.62-.178.897l-.036.037c-.42-.006-.566-.006-1.05.018l-.024-.04c.08-.332.162-.668.24-.998.203-.9.25-1.245.307-1.702l.04-.028c.47-.067.585-.08 1.097-.185l.043.047-.077.287c.086-.052.168-.104.257-.15.242-.12.51-.155.658-.155.223 0 .468.062.57.323.098.232.034.52-.094 1.084l-.066.287c-.13.627-.152.743-.225 1.174l-.05.036zM15.87 12.144c-.245 0-.405-.006-.56 0-.153 0-.303.008-.532.018l-.013-.02-.015-.02c.062-.238.097-.322.128-.406.03-.084.06-.17.115-.41.072-.315.116-.535.147-.728.033-.187.052-.346.075-.53l.02-.014.02-.018c.244-.036.4-.057.56-.082.16-.024.32-.055.574-.103l.008.023.008.022c-.047.195-.094.39-.14.588-.047.197-.094.392-.137.587-.093.414-.13.57-.152.68-.02.105-.026.163-.063.377l-.022.02-.023.017zM19.542 10.728c.143-.633.033-.928-.108-1.11-.213-.273-.59-.36-.978-.36-.235 0-.793.023-1.23.43-.312.29-.458.687-.546 1.066-.088.387-.19 1.086.447 1.344.198.085.48.108.662.108.466 0 .945-.13 1.304-.513.278-.312.405-.775.448-.965zm-1.07-.046c-.02.106-.113.503-.24.673-.086.123-.19.198-.305.198-.033 0-.235 0-.238-.3-.003-.15.027-.304.063-.47.108-.478.236-.88.56-.88.255 0 .27.298.16.78zM29.536 12.187c-.493-.004-.635-.004-1.09.015l-.03-.037c.124-.472.248-.943.358-1.42.142-.62.175-.882.223-1.244l.037-.03c.49-.07.625-.09 1.135-.186l.015.044c-.093.388-.186.777-.275 1.166-.19.816-.258 1.23-.33 1.658l-.044.035z" style="fill: #FEFEFE" />\n      <path d="M29.77 10.784c.144-.63-.432-.056-.525-.264-.14-.323-.052-.98-.62-1.2-.22-.085-.732.025-1.17.428-.31.29-.458.683-.544 1.062-.088.38-.19 1.078.444 1.328.2.085.384.11.567.103.638-.034 1.124-1.002 1.483-1.386.277-.303.326.115.368-.07zm-.974-.047c-.024.1-.117.503-.244.67-.083.117-.283.192-.397.192-.032 0-.232 0-.24-.3 0-.146.03-.3.067-.467.11-.47.235-.87.56-.87.254 0 .363.293.254.774zM22.332 12.144c-.41-.006-.55-.006-1.03.018l-.018-.036c.04-.182.087-.363.13-.548l.057-.25c.09-.39.176-.843.186-.98.008-.084.036-.29-.198-.29-.1 0-.203.048-.308.096-.057.207-.175.79-.232 1.055-.115.558-.124.62-.176.897l-.035.037c-.42-.006-.566-.006-1.05.018l-.022-.04.238-.998c.203-.9.25-1.245.307-1.702l.038-.028c.472-.067.587-.08 1.098-.185l.04.047-.073.287c.084-.052.17-.104.257-.15.24-.12.51-.155.655-.155.224 0 .47.062.575.323.095.232.03.52-.098 1.084l-.065.287c-.133.627-.154.743-.225 1.174l-.05.036zM26.32 8.756c-.07.326-.282.603-.554.736-.225.114-.498.123-.78.123h-.183l.013-.074.336-1.468.01-.076.007-.058.132.015.71.062c.275.105.388.38.31.74zM25.88 7.22l-.34.003c-.883.01-1.238.006-1.383-.012l-.037.182-.315 1.478-.793 3.288c.77-.01 1.088-.01 1.22.004l.21-1.024s.153-.644.163-.667c0 0 .047-.066.096-.092h.07c.665 0 1.417 0 2.005-.437.4-.298.675-.74.797-1.274.03-.132.054-.29.054-.446 0-.205-.04-.41-.16-.568-.3-.423-.896-.43-1.588-.433zM33.572 9.28l-.04-.043c-.502.1-.594.118-1.058.18l-.034.034-.005.023-.003-.007c-.345.803-.334.63-.615 1.26-.003-.03-.003-.048-.004-.077l-.07-1.37-.044-.043c-.53.1-.542.118-1.03.18l-.04.034-.006.056.003.007c.06.315.047.244.108.738.03.244.065.49.093.73.05.4.077.6.134 1.21-.328.55-.408.757-.722 1.238l.017.044c.478-.018.587-.018.94-.018l.08-.088c.265-.578 2.295-4.085 2.295-4.085zM16.318 9.62c.27-.19.304-.45.076-.586-.23-.137-.634-.094-.906.095-.273.186-.304.45-.075.586.228.134.633.094.905-.096z" style="fill: #FEFEFE" />\n      <path d="M31.238 13.415l-.397.684c-.124.232-.357.407-.728.41l-.632-.01.184-.618h.124c.064 0 .11-.004.148-.022.03-.01.054-.035.08-.072l.233-.373h.988z" style="fill: #FEFEFE" />\n    </symbol>\n\n    <symbol id="icon-american-express" viewBox="0 0 40 24">\n      <title>American Express</title>\n      <path d="M38.333 24H1.667C.75 24 0 23.28 0 22.4V1.6C0 .72.75 0 1.667 0h36.666C39.25 0 40 .72 40 1.6v20.8c0 .88-.75 1.6-1.667 1.6z" style="fill: #FFF" />\n      <path style="fill: #1478BE" d="M6.26 12.32h2.313L7.415 9.66M27.353 9.977h-3.738v1.23h3.666v1.384h-3.675v1.385h3.821v1.005c.623-.77 1.33-1.466 2.025-2.235l.707-.77c-.934-1.004-1.87-2.08-2.804-3.075v1.077z" />\n      <path d="M38.25 7h-5.605l-1.328 1.4L30.072 7H16.984l-1.017 2.416L14.877 7h-9.58L1.25 16.5h4.826l.623-1.556h1.4l.623 1.556H29.99l1.327-1.483 1.328 1.483h5.605l-4.36-4.667L38.25 7zm-17.685 8.1h-1.557V9.883L16.673 15.1h-1.33L13.01 9.883l-.084 5.217H9.73l-.623-1.556h-3.27L5.132 15.1H3.42l2.884-6.772h2.42l2.645 6.233V8.33h2.646l2.107 4.51 1.868-4.51h2.575V15.1zm14.727 0h-2.024l-2.024-2.26-2.023 2.26H22.06V8.328H29.53l1.795 2.177 2.024-2.177h2.025L32.26 11.75l3.032 3.35z" style="fill: #1478BE" />\n    </symbol>\n\n    <symbol id="icon-jcb" viewBox="0 0 40 24">\n      <title>JCB</title>\n      <path d="M38.333 24H1.667C.75 24 0 23.28 0 22.4V1.6C0 .72.75 0 1.667 0h36.666C39.25 0 40 .72 40 1.6v20.8c0 .88-.75 1.6-1.667 1.6z" style="fill: #FFF" />\n      <path d="M33.273 2.01h.013v17.062c-.004 1.078-.513 2.103-1.372 2.746-.63.47-1.366.67-2.14.67-.437 0-4.833.026-4.855 0-.01-.01 0-.07 0-.082v-6.82c0-.04.004-.064.033-.064h5.253c.867 0 1.344-.257 1.692-.61.44-.448.574-1.162.294-1.732-.24-.488-.736-.78-1.244-.913-.158-.04-.32-.068-.483-.083-.01 0-.064 0-.07-.006-.03-.034.023-.04.038-.046.102-.033.215-.042.32-.073.532-.164.993-.547 1.137-1.105.15-.577-.05-1.194-.524-1.552-.34-.257-.768-.376-1.187-.413-.43-.038-4.774-.022-5.21-.022-.072 0-.05-.02-.05-.09V5.63c0-.31.01-.616.073-.92.126-.592.41-1.144.815-1.59.558-.615 1.337-1.01 2.16-1.093.478-.048 4.89-.017 5.305-.017zm-4.06 8.616c.06.272-.01.567-.204.77-.173.176-.407.25-.648.253-.195.003-1.725 0-1.788 0l.003-1.645c.012-.027.02-.018.06-.018.097 0 1.713-.004 1.823.005.232.02.45.12.598.306.076.096.128.208.155.328zm-2.636 2.038h1.944c.242.002.47.063.652.228.226.204.327.515.283.815-.04.263-.194.5-.422.634-.187.112-.39.125-.6.125h-1.857v-1.8z" style="fill: #53B230" />\n      <path d="M6.574 13.89c-.06-.03-.06-.018-.07-.06-.006-.026-.005-8.365.003-8.558.04-.95.487-1.857 1.21-2.47.517-.434 1.16-.71 1.83-.778.396-.04.803-.018 1.2-.018.69 0 4.11-.013 4.12 0 .008.008.002 16.758 0 17.074-.003.956-.403 1.878-1.105 2.523-.506.465-1.15.77-1.83.86-.41.056-5.02.032-5.363.032-.066 0-.054.013-.066-.024-.01-.025 0-7 0-7.17.66.178 1.35.28 2.03.348.662.067 1.33.093 1.993.062.93-.044 1.947-.192 2.712-.762.32-.238.574-.553.73-.922.148-.353.2-.736.2-1.117 0-.348.006-3.93-.016-3.942-.023-.014-2.885-.015-2.9.012-.012.022 0 3.87 0 3.95-.003.47-.16.933-.514 1.252-.468.42-1.11.47-1.707.423-.687-.055-1.357-.245-1.993-.508-.157-.065-.312-.135-.466-.208z" style="fill: #006CB9" />\n      <path d="M15.95 9.835c-.025.02-.05.04-.072.06V6.05c0-.295-.012-.594.01-.888.12-1.593 1.373-2.923 2.944-3.126.382-.05 5.397-.042 5.41-.026.01.01 0 .062 0 .074v16.957c0 1.304-.725 2.52-1.89 3.1-.504.25-1.045.35-1.605.35-.322 0-4.757.015-4.834 0-.05-.01-.023.01-.035-.02-.007-.022 0-6.548 0-7.44v-.422c.554.48 1.256.75 1.96.908.536.12 1.084.176 1.63.196.537.02 1.076.01 1.61-.037.546-.05 1.088-.136 1.625-.244.137-.028.274-.057.41-.09.033-.006.17-.017.187-.044.013-.02 0-.097 0-.12v-1.324c-.582.292-1.19.525-1.83.652-.778.155-1.64.198-2.385-.123-.752-.326-1.2-1.024-1.274-1.837-.076-.837.173-1.716.883-2.212.736-.513 1.7-.517 2.553-.38.634.1 1.245.305 1.825.58.078.037.154.075.23.113V9.322c0-.02.013-.1 0-.118-.02-.028-.152-.038-.188-.046-.066-.016-.133-.03-.2-.045C22.38 9 21.84 8.908 21.3 8.85c-.533-.06-1.068-.077-1.603-.066-.542.01-1.086.054-1.62.154-.662.125-1.32.337-1.883.716-.085.056-.167.117-.245.18z" style="fill: #E20138" />\n    </symbol>\n\n    <symbol id="icon-discover" viewBox="0 0 40 24">\n      <title>Discover</title>\n      <path d="M38.333 24H1.667C.75 24 0 23.28 0 22.4V1.6C0 .72.75 0 1.667 0h36.666C39.25 0 40 .72 40 1.6v20.8c0 .88-.75 1.6-1.667 1.6z" style="fill: #FFF" />\n      <path d="M38.995 11.75S27.522 20.1 6.5 23.5h31.495c.552 0 1-.448 1-1V11.75z" style="fill: #F48024" />\n      <path d="M5.332 11.758c-.338.305-.776.438-1.47.438h-.29V8.55h.29c.694 0 1.115.124 1.47.446.37.33.595.844.595 1.372 0 .53-.224 1.06-.595 1.39zM4.077 7.615H2.5v5.515h1.57c.833 0 1.435-.197 1.963-.637.63-.52 1-1.305 1-2.116 0-1.628-1.214-2.762-2.956-2.762zM7.53 13.13h1.074V7.616H7.53M11.227 9.732c-.645-.24-.834-.397-.834-.695 0-.347.338-.61.8-.61.322 0 .587.132.867.446l.562-.737c-.462-.405-1.015-.612-1.618-.612-.975 0-1.718.678-1.718 1.58 0 .76.346 1.15 1.355 1.513.42.148.635.247.743.314.215.14.322.34.322.57 0 .448-.354.78-.834.78-.51 0-.924-.258-1.17-.736l-.695.67c.495.726 1.09 1.05 1.907 1.05 1.116 0 1.9-.745 1.9-1.812 0-.876-.363-1.273-1.585-1.72zM13.15 10.377c0 1.62 1.27 2.877 2.907 2.877.462 0 .858-.09 1.347-.32v-1.267c-.43.43-.81.604-1.297.604-1.082 0-1.85-.785-1.85-1.9 0-1.06.792-1.895 1.8-1.895.512 0 .9.183 1.347.62V7.83c-.472-.24-.86-.34-1.322-.34-1.627 0-2.932 1.283-2.932 2.887zM25.922 11.32l-1.468-3.705H23.28l2.337 5.656h.578l2.38-5.655H27.41M29.06 13.13h3.046v-.934h-1.973v-1.488h1.9v-.934h-1.9V8.55h1.973v-.935H29.06M34.207 10.154h-.314v-1.67h.33c.67 0 1.034.28 1.034.818 0 .554-.364.852-1.05.852zm2.155-.91c0-1.033-.71-1.628-1.95-1.628H32.82v5.514h1.073v-2.215h.14l1.487 2.215h1.32l-1.733-2.323c.81-.165 1.255-.72 1.255-1.563z" style="fill: #221F20" />\n      <path d="M23.6 10.377c0 1.62-1.31 2.93-2.927 2.93-1.617.002-2.928-1.31-2.928-2.93s1.31-2.932 2.928-2.932c1.618 0 2.928 1.312 2.928 2.932z" style="fill: #F48024" />\n    </symbol>\n\n    <symbol id="icon-diners-club" viewBox="0 0 40 24">\n      <title>Diners Club</title>\n      <path d="M38.333 24H1.667C.75 24 0 23.28 0 22.4V1.6C0 .72.75 0 1.667 0h36.666C39.25 0 40 .72 40 1.6v20.8c0 .88-.75 1.6-1.667 1.6z" style="fill: #FFF" />\n      <path d="M9.02 11.83c0-5.456 4.54-9.88 10.14-9.88 5.6 0 10.139 4.424 10.139 9.88-.002 5.456-4.54 9.88-10.14 9.88-5.6 0-10.14-4.424-10.14-9.88z" style="fill: #FEFEFE" />\n      <path style="fill: #FFF" d="M32.522 22H8.5V1.5h24.022" />\n      <path d="M25.02 11.732c-.003-2.534-1.607-4.695-3.868-5.55v11.102c2.26-.857 3.865-3.017 3.87-5.552zm-8.182 5.55V6.18c-2.26.86-3.86 3.017-3.867 5.55.007 2.533 1.61 4.69 3.868 5.55zm2.158-14.934c-5.25.002-9.503 4.202-9.504 9.384 0 5.182 4.254 9.38 9.504 9.382 5.25 0 9.504-4.2 9.505-9.382 0-5.182-4.254-9.382-9.504-9.384zM18.973 22C13.228 22.027 8.5 17.432 8.5 11.84 8.5 5.726 13.228 1.5 18.973 1.5h2.692c5.677 0 10.857 4.225 10.857 10.34 0 5.59-5.18 10.16-10.857 10.16h-2.692z" style="fill: #004A97" />\n    </symbol>\n\n    <symbol id="icon-maestro" viewBox="0 0 40 24">\n      <title>Maestro</title>\n      <path d="M38.333 24H1.667C.75 24 0 23.28 0 22.4V1.6C0 .72.75 0 1.667 0h36.666C39.25 0 40 .72 40 1.6v20.8c0 .88-.75 1.6-1.667 1.6z" style="fill: #FFF" />\n      <path d="M14.67 22.39V21c.022-.465-.303-.86-.767-.882h-.116c-.3-.023-.603.14-.788.394-.164-.255-.442-.417-.743-.394-.256-.023-.51.116-.65.324v-.278h-.487v2.203h.487v-1.183c-.046-.278.162-.533.44-.58h.094c.325 0 .488.21.488.58v1.23h.487v-1.23c-.047-.278.162-.556.44-.58h.093c.325 0 .487.21.487.58v1.23l.534-.024zm2.712-1.09v-1.113h-.487v.28c-.162-.21-.417-.326-.695-.326-.65 0-1.16.51-1.16 1.16 0 .65.51 1.16 1.16 1.16.278 0 .533-.117.695-.325v.278h.487V21.3zm-1.786 0c.024-.37.348-.65.72-.626.37.023.65.348.626.72-.023.347-.302.625-.673.625-.372 0-.674-.28-.674-.65-.023-.047-.023-.047 0-.07zm12.085-1.16c.163 0 .325.024.465.094.14.046.278.14.37.255.117.115.186.23.256.37.117.3.117.626 0 .927-.046.14-.138.255-.254.37-.116.117-.232.186-.37.256-.303.116-.65.116-.952 0-.14-.046-.28-.14-.37-.255-.118-.116-.187-.232-.257-.37-.116-.302-.116-.627 0-.928.047-.14.14-.255.256-.37.115-.117.23-.187.37-.256.163-.07.325-.116.488-.093zm0 .465c-.092 0-.185.023-.278.046-.092.024-.162.094-.232.14-.07.07-.116.14-.14.232-.068.185-.068.394 0 .58.024.092.094.162.14.23.07.07.14.117.232.14.186.07.37.07.557 0 .092-.023.16-.092.23-.14.07-.068.117-.138.14-.23.07-.186.07-.395 0-.58-.023-.093-.093-.162-.14-.232-.07-.07-.138-.116-.23-.14-.094-.045-.187-.07-.28-.045zm-7.677.695c0-.695-.44-1.16-1.043-1.16-.65 0-1.16.534-1.137 1.183.023.65.534 1.16 1.183 1.136.325 0 .65-.093.905-.302l-.23-.348c-.187.14-.42.232-.65.232-.326.023-.627-.21-.673-.533h1.646v-.21zm-1.646-.21c.023-.3.278-.532.58-.532.3 0 .556.232.556.533h-1.136zm3.664-.346c-.207-.116-.44-.186-.695-.186-.255 0-.417.093-.417.255 0 .163.162.186.37.21l.233.022c.488.07.766.278.766.672 0 .395-.37.72-1.02.72-.348 0-.673-.094-.95-.28l.23-.37c.21.162.465.232.743.232.324 0 .51-.094.51-.28 0-.115-.117-.185-.395-.23l-.232-.024c-.487-.07-.765-.302-.765-.65 0-.44.37-.718.927-.718.325 0 .627.07.905.232l-.21.394zm2.32-.116h-.788v.997c0 .23.07.37.325.37.14 0 .3-.046.417-.115l.14.417c-.186.116-.395.162-.604.162-.58 0-.765-.302-.765-.812v-1.02h-.44v-.44h.44v-.673h.487v.672h.79v.44zm1.67-.51c.117 0 .233.023.35.07l-.14.463c-.093-.045-.21-.045-.302-.045-.325 0-.464.208-.464.58v1.25h-.487v-2.2h.487v.277c.116-.255.325-.37.557-.394z" style="fill: #000" />\n      <path style="fill: #7673C0" d="M23.64 3.287h-7.305V16.41h7.306" />\n      <path d="M16.8 9.848c0-2.55 1.183-4.985 3.2-6.56C16.384.435 11.12 1.06 8.29 4.7 5.435 8.32 6.06 13.58 9.703 16.41c3.038 2.387 7.283 2.387 10.32 0-2.04-1.578-3.223-3.99-3.223-6.562z" style="fill: #EB001B" />\n      <path d="M33.5 9.848c0 4.613-3.735 8.346-8.35 8.346-1.88 0-3.69-.626-5.15-1.785 3.618-2.83 4.245-8.092 1.415-11.71-.418-.532-.882-.996-1.415-1.413C23.618.437 28.883 1.06 31.736 4.7 32.873 6.163 33.5 7.994 33.5 9.85z" style="fill: #00A1DF" />\n    </symbol>\n\n    <symbol id="logoPayPal" viewBox="0 0 48 29">\n      <title>PayPal Logo</title>\n      <path d="M46 29H2c-1.1 0-2-.87-2-1.932V1.934C0 .87.9 0 2 0h44c1.1 0 2 .87 2 1.934v25.134C48 28.13 47.1 29 46 29z" fill-opacity="0" style="fill: #FFF" />\n      <path d="M31.216 16.4c.394-.7.69-1.5.886-2.4.196-.8.196-1.6.1-2.2-.1-.7-.396-1.2-.79-1.7-.195-.3-.59-.5-.885-.7.1-.8.1-1.5 0-2.1-.1-.6-.394-1.1-.886-1.6-.885-1-2.56-1.6-4.922-1.6h-6.4c-.492 0-.787.3-.886.8l-2.658 17.2c0 .2 0 .3.1.4.097.1.294.2.393.2h4.036l-.295 1.8c0 .1 0 .3.1.4.098.1.195.2.393.2h3.35c.393 0 .688-.3.786-.7v-.2l.59-4.1v-.2c.1-.4.395-.7.788-.7h.59c1.675 0 3.152-.4 4.137-1.1.59-.5 1.083-1 1.478-1.7h-.002z" style="fill: #263B80" />\n      <path d="M21.364 9.4c0-.3.196-.5.492-.6.098-.1.196-.1.394-.1h5.02c.592 0 1.183 0 1.675.1.1 0 .295.1.394.1.098 0 .294.1.393.1.1 0 .1 0 .197.102.295.1.492.2.69.3.295-1.6 0-2.7-.887-3.8-.985-1.1-2.658-1.6-4.923-1.6h-6.4c-.49 0-.885.3-.885.8l-2.758 17.3c-.098.3.197.6.59.6h3.94l.985-6.4 1.083-6.9z" style="fill: #263B80" />\n      <path d="M30.523 9.4c0 .1 0 .3-.098.4-.887 4.4-3.742 5.9-7.484 5.9h-1.87c-.492 0-.787.3-.886.8l-.985 6.2-.296 1.8c0 .3.196.6.492.6h3.348c.394 0 .69-.3.787-.7v-.2l.592-4.1v-.2c.1-.4.394-.7.787-.7h.69c3.248 0 5.808-1.3 6.497-5.2.296-1.6.197-3-.69-3.9-.196-.3-.49-.5-.885-.7z" style="fill: #159BD7" />\n      <path d="M29.635 9c-.098 0-.295-.1-.394-.1-.098 0-.294-.1-.393-.1-.492-.102-1.083-.102-1.673-.102h-5.022c-.1 0-.197 0-.394.1-.198.1-.394.3-.492.6l-1.083 6.9v.2c.1-.5.492-.8.886-.8h1.87c3.742 0 6.598-1.5 7.484-5.9 0-.1 0-.3.098-.4-.196-.1-.492-.2-.69-.3 0-.1-.098-.1-.196-.1z" style="fill: #232C65" />\n    </symbol>\n\n    <symbol id="logoPayPalCredit" viewBox="0 0 48 29">\n      <title>PayPal Credit Logo</title>\n      <path d="M46 29H2c-1.1 0-2-.87-2-1.932V1.934C0 .87.9 0 2 0h44c1.1 0 2 .87 2 1.934v25.134C48 28.13 47.1 29 46 29z" fill-opacity="0" style="fill: #FFF" fill-rule="nonzero" />\n      <path d="M27.44 21.6h.518c1.377 0 2.67-.754 2.953-2.484.248-1.588-.658-2.482-2.14-2.482h-.38c-.093 0-.172.067-.187.16l-.763 4.805zm-1.254-6.646c.024-.158.16-.273.32-.273h2.993c2.47 0 4.2 1.942 3.81 4.436-.4 2.495-2.752 4.436-5.21 4.436h-3.05c-.116 0-.205-.104-.187-.218l1.323-8.38zM22.308 16.907l-.192 1.21h2.38c.116 0 .204.103.186.217l-.23 1.462c-.023.157-.16.273-.318.273h-2.048c-.16 0-.294.114-.32.27l-.203 1.26h2.52c.117 0 .205.102.187.217l-.228 1.46c-.025.16-.16.275-.32.275h-4.55c-.116 0-.204-.104-.186-.218l1.322-8.38c.025-.158.16-.273.32-.273h4.55c.116 0 .205.104.187.22l-.23 1.46c-.024.158-.16.274-.32.274H22.63c-.16 0-.295.115-.32.273M35.325 23.552h-1.81c-.115 0-.203-.104-.185-.218l1.322-8.38c.025-.158.16-.273.32-.273h1.81c.115 0 .203.104.185.22l-1.322 8.38c-.025.156-.16.272-.32.272M14.397 18.657h.224c.754 0 1.62-.14 1.777-1.106.158-.963-.345-1.102-1.15-1.104h-.326c-.097 0-.18.07-.197.168l-.326 2.043zm3.96 4.895h-2.37c-.102 0-.194-.058-.238-.15l-1.565-3.262h-.023l-.506 3.19c-.02.128-.13.222-.26.222h-1.86c-.116 0-.205-.104-.187-.218l1.33-8.432c.02-.128.13-.22.26-.22h3.222c1.753 0 2.953.834 2.66 2.728-.2 1.224-1.048 2.283-2.342 2.506l2.037 3.35c.076.125-.014.286-.16.286zM40.216 23.552h-1.808c-.116 0-.205-.104-.187-.218l1.06-6.7h-1.684c-.116 0-.205-.104-.187-.218l.228-1.462c.025-.157.16-.273.32-.273h5.62c.116 0 .205.104.186.22l-.228 1.46c-.025.158-.16.274-.32.274h-1.63l-1.05 6.645c-.025.156-.16.272-.32.272M11.467 17.202c-.027.164-.228.223-.345.104-.395-.405-.975-.62-1.6-.62-1.41 0-2.526 1.083-2.75 2.458-.21 1.4.588 2.41 2.022 2.41.592 0 1.22-.225 1.74-.6.144-.105.34.02.313.194l-.328 2.03c-.02.12-.108.22-.226.254-.702.207-1.24.355-1.9.355-3.823 0-4.435-3.266-4.238-4.655.553-3.894 3.712-4.786 5.65-4.678.623.034 1.182.117 1.73.323.177.067.282.25.252.436l-.32 1.99" style="fill: #21306F" />\n      <path d="M23.184 7.67c-.11.717-.657.717-1.186.717h-.302l.212-1.34c.013-.08.082-.14.164-.14h.138c.36 0 .702 0 .877.206.105.123.137.305.097.557zm-.23-1.87h-1.998c-.137 0-.253.098-.274.233l-.808 5.123c-.016.1.062.192.165.192h1.024c.095 0 .177-.07.192-.164l.23-1.452c.02-.135.136-.235.273-.235h.63c1.317 0 2.076-.636 2.275-1.898.09-.553.003-.987-.255-1.29-.284-.334-.788-.51-1.456-.51z" style="fill: #0093C7" />\n      <path d="M8.936 7.67c-.11.717-.656.717-1.186.717h-.302l.212-1.34c.013-.08.082-.14.164-.14h.138c.36 0 .702 0 .877.206.104.123.136.305.096.557zm-.23-1.87H6.708c-.136 0-.253.098-.274.233l-.808 5.123c-.016.1.062.192.165.192h.955c.136 0 .252-.1.274-.234l.217-1.382c.02-.135.137-.235.274-.235h.633c1.316 0 2.075-.636 2.274-1.898.09-.553.003-.987-.255-1.29-.284-.334-.788-.51-1.456-.51zM13.343 9.51c-.092.545-.526.912-1.08.912-.277 0-.5-.09-.642-.258-.14-.168-.193-.406-.148-.672.086-.542.527-.92 1.072-.92.27 0 .492.09.637.26.148.172.205.412.163.677zm1.334-1.863h-.957c-.082 0-.152.06-.164.14l-.042.268-.067-.097c-.208-.3-.67-.4-1.13-.4-1.057 0-1.96.8-2.135 1.923-.092.56.038 1.097.356 1.47.29.344.708.487 1.204.487.852 0 1.325-.548 1.325-.548l-.043.265c-.016.1.062.193.164.193h.862c.136 0 .253-.1.274-.234l.517-3.275c.017-.102-.06-.193-.163-.193z" style="fill: #21306F" />\n      <path d="M27.59 9.51c-.09.545-.525.912-1.078.912-.278 0-.5-.09-.643-.258-.142-.168-.195-.406-.15-.672.086-.542.526-.92 1.07-.92.273 0 .494.09.64.26.146.172.203.412.16.677zm1.334-1.863h-.956c-.082 0-.152.06-.164.14l-.043.268-.065-.097c-.208-.3-.67-.4-1.13-.4-1.057 0-1.96.8-2.136 1.923-.092.56.038 1.097.355 1.47.292.344.71.487 1.205.487.852 0 1.325-.548 1.325-.548l-.043.265c-.016.1.062.193.164.193h.862c.136 0 .253-.1.274-.234l.517-3.275c.015-.102-.063-.193-.166-.193z" style="fill: #0093C7" />\n      <path d="M19.77 7.647h-.96c-.092 0-.178.045-.23.122L17.254 9.72l-.562-1.877c-.035-.118-.143-.198-.266-.198h-.945c-.113 0-.194.112-.157.22l1.06 3.108-.997 1.404c-.078.11 0 .262.136.262h.96c.092 0 .177-.044.23-.12l3.196-4.614c.077-.11-.002-.26-.137-.26" style="fill: #21306F" />\n      <path d="M30.052 5.94l-.82 5.216c-.016.1.062.192.165.192h.824c.138 0 .254-.1.275-.234l.81-5.122c.015-.1-.064-.193-.166-.193h-.924c-.082 0-.15.06-.164.14" style="fill: #0093C7" />\n    </symbol>\n\n    <symbol id="iconCardFront" viewBox="0 0 48 29">\n      <title>Generic Card</title>\n      <path d="M46.177 29H1.823C.9 29 0 28.13 0 27.187V1.813C0 .87.9 0 1.823 0h44.354C47.1 0 48 .87 48 1.813v25.375C48 28.13 47.1 29 46.177 29z" style="fill: #FFF" />\n      <path d="M4.8 9.14c0-.427.57-.973 1.067-.973h7.466c.496 0 1.067.546 1.067.972v3.888c0 .425-.57.972-1.067.972H5.867c-.496 0-1.067-.547-1.067-.972v-3.89z" style="fill: #828282" />\n      <rect style="fill: #828282" x="10.8" y="22.167" width="3.6" height="2.333" rx="1.167" />\n      <rect style="fill: #828282" x="4.8" y="22.167" width="3.6" height="2.333" rx="1.167" />\n      <path d="M6.55 16.333h34.9c.966 0 1.75.784 1.75 1.75 0 .967-.784 1.75-1.75 1.75H6.55c-.966 0-1.75-.783-1.75-1.75 0-.966.784-1.75 1.75-1.75z" style="fill: #828282" />\n      <ellipse style="fill: #828282" cx="40.2" cy="6.417" rx="3" ry="2.917" />\n    </symbol>\n\n    <symbol id="iconCVVBack" viewBox="0 0 40 24">\n      <title>CVV Back</title>\n      <path d="M38.48 24H1.52C.75 24 0 23.28 0 22.5v-21C0 .72.75 0 1.52 0h36.96C39.25 0 40 .72 40 1.5v21c0 .78-.75 1.5-1.52 1.5z" style="fill: #FFF"/>\n      <path style="fill: #828282" d="M0 5h40v4H0z" />\n      <path d="M20 13.772v5.456c0 .423.37.772.82.772h13.36c.45 0 .82-.35.82-.772v-5.456c0-.423-.37-.772-.82-.772H20.82c-.45 0-.82.35-.82.772zm-1-.142c0-.9.76-1.63 1.68-1.63h13.64c.928 0 1.68.737 1.68 1.63v5.74c0 .9-.76 1.63-1.68 1.63H20.68c-.928 0-1.68-.737-1.68-1.63v-5.74z" style="fill: #000" fill-rule="nonzero" />\n      <circle style="fill: #828282" cx="23.5" cy="16.5" r="1.5" />\n      <circle style="fill: #828282" cx="27.5" cy="16.5" r="1.5" />\n      <circle style="fill: #828282" cx="31.5" cy="16.5" r="1.5" />\n    </symbol>\n\n    <symbol id="iconCVVFront" viewBox="0 0 40 24">\n      <title>CVV Front</title>\n      <path d="M38.48 24H1.52C.75 24 0 23.28 0 22.5v-21C0 .72.75 0 1.52 0h36.96C39.25 0 40 .72 40 1.5v21c0 .78-.75 1.5-1.52 1.5z" style="fill: #FFF" />\n      <path d="M16 5.772v5.456c0 .423.366.772.81.772h17.38c.444 0 .81-.348.81-.772V5.772C35 5.35 34.634 5 34.19 5H16.81c-.444 0-.81.348-.81.772zm-1-.142c0-.9.75-1.63 1.66-1.63h17.68c.917 0 1.66.737 1.66 1.63v5.74c0 .9-.75 1.63-1.66 1.63H16.66c-.917 0-1.66-.737-1.66-1.63V5.63z" style="fill: #000" fill-rule="nonzero" />\n      <circle style="fill: #828282" cx="19.5" cy="8.5" r="1.5" />\n      <circle style="fill: #828282" cx="27.5" cy="8.5" r="1.5" />\n      <circle style="fill: #828282" cx="23.5" cy="8.5" r="1.5" />\n      <circle style="fill: #828282" cx="31.5" cy="8.5" r="1.5" />\n      <path d="M4 7.833C4 7.47 4.476 7 4.89 7h6.22c.414 0 .89.47.89.833v3.334c0 .364-.476.833-.89.833H4.89c-.414 0-.89-.47-.89-.833V7.833zM4 18.5c0-.828.668-1.5 1.5-1.5h29c.828 0 1.5.666 1.5 1.5 0 .828-.668 1.5-1.5 1.5h-29c-.828 0-1.5-.666-1.5-1.5z" style="fill: #828282" />\n    </symbol>\n\n    <symbol id="iconCheck" viewBox="0 0 42 32">\n      <title>Check</title>\n      <path class="path1" d="M14.379 29.76L39.741 3.415 36.194.001l-21.815 22.79-10.86-11.17L0 15.064z" />\n    </symbol>\n\n    <symbol id="iconX" viewBox="0 0 32 32">\n      <title>X</title>\n      <path d="M29 3.54L25.46 0 14.5 10.97 3.54 0.01 0 3.54 10.96 14.5 0.01 25.46 3.54 28.99 14.5 18.04 25.46 29 28.99 25.46 18.03 14.5 29 3.54z"/>\n    </symbol>\n\n    <symbol id="iconLockLoader" viewBox="0 0 28 32">\n      <title>Lock Loader</title>\n      <path d="M6 10V8c0-4.422 3.582-8 8-8 4.41 0 8 3.582 8 8v2h-4V7.995C18 5.79 16.205 4 14 4c-2.21 0-4 1.792-4 3.995V10H6zM.997 14c-.55 0-.997.445-.997.993v16.014c0 .548.44.993.997.993h26.006c.55 0 .997-.445.997-.993V14.993c0-.548-.44-.993-.997-.993H.997z" />\n    </symbol>\n\n    <symbol id="iconError" height="24" viewBox="0 0 24 24" width="24">\n      <path d="M0 0h24v24H0z" style="fill: none" />\n      <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" />\n    </symbol>\n\n    <symbol id="logoApplePay" viewBox="0 0 165.52 105.97" width="24">\n      <title>Apple Pay Logo</title>\n      <defs>\n      <style>\n        .cls-1{fill:#231f20;}.cls-2{fill:#fff;}\n      </style>\n      </defs>\n      <path id="_Path_" data-name="&lt;Path&gt;" class="cls-1" d="M150.7 0h-139a20.78 20.78 0 0 0-3.12.3 10.51 10.51 0 0 0-3 1 9.94 9.94 0 0 0-4.31 4.32 10.46 10.46 0 0 0-1 3A20.65 20.65 0 0 0 0 11.7v82.57a20.64 20.64 0 0 0 .3 3.11 10.46 10.46 0 0 0 1 3 9.94 9.94 0 0 0 4.35 4.35 10.47 10.47 0 0 0 3 1 20.94 20.94 0 0 0 3.11.27h142.06a21 21 0 0 0 3.11-.27 10.48 10.48 0 0 0 3-1 9.94 9.94 0 0 0 4.35-4.35 10.4 10.4 0 0 0 1-3 20.63 20.63 0 0 0 .27-3.11V11.69a20.64 20.64 0 0 0-.27-3.11 10.4 10.4 0 0 0-1-3 9.94 9.94 0 0 0-4.35-4.35 10.52 10.52 0 0 0-3-1 20.84 20.84 0 0 0-3.1-.23h-1.43z"/>\n      <path id="_Path_2" data-name="&lt;Path&gt;" class="cls-2" d="M150.7 3.53h3.03a17.66 17.66 0 0 1 2.58.22 7 7 0 0 1 2 .65 6.41 6.41 0 0 1 2.8 2.81 6.88 6.88 0 0 1 .64 2 17.56 17.56 0 0 1 .22 2.58v82.38a17.54 17.54 0 0 1-.22 2.59 6.85 6.85 0 0 1-.64 2 6.41 6.41 0 0 1-2.81 2.81 6.92 6.92 0 0 1-2 .65 18 18 0 0 1-2.57.22H11.79a18 18 0 0 1-2.58-.22 6.94 6.94 0 0 1-2-.65 6.41 6.41 0 0 1-2.8-2.8 6.93 6.93 0 0 1-.65-2 17.47 17.47 0 0 1-.22-2.58v-82.4a17.49 17.49 0 0 1 .22-2.59 6.92 6.92 0 0 1 .65-2 6.41 6.41 0 0 1 2.8-2.8 7 7 0 0 1 2-.65 17.63 17.63 0 0 1 2.58-.22H150.7"/>\n      <g id="_Group_" data-name="&lt;Group&gt;">\n      <g id="_Group_2" data-name="&lt;Group&gt;">\n      <path id="_Path_3" data-name="&lt;Path&gt;" class="cls-1" d="M43.51 35.77a9.15 9.15 0 0 0 2.1-6.52 9.07 9.07 0 0 0-6 3.11 8.56 8.56 0 0 0-2.16 6.27 7.57 7.57 0 0 0 6.06-2.86"/>\n      <path id="_Path_4" data-name="&lt;Path&gt;" class="cls-1" d="M45.59 39.08c-3.35-.2-6.2 1.9-7.79 1.9s-4-1.8-6.7-1.75a9.87 9.87 0 0 0-8.4 5.1c-3.6 6.2-.95 15.4 2.55 20.45 1.7 2.5 3.75 5.25 6.45 5.15s3.55-1.65 6.65-1.65 4 1.65 6.7 1.6 4.55-2.5 6.25-5a22.2 22.2 0 0 0 2.8-5.75 9.08 9.08 0 0 1-5.45-8.25A9.26 9.26 0 0 1 53 43.13a9.57 9.57 0 0 0-7.45-4"/>\n      </g>\n      <g id="_Group_3" data-name="&lt;Group&gt;">\n      <path id="_Compound_Path_" data-name="&lt;Compound Path&gt;" class="cls-1" d="M79 32.11c7.28 0 12.35 5 12.35 12.32S86.15 56.8 78.79 56.8h-8.06v12.82h-5.82V32.11zm-8.27 19.81h6.68c5.07 0 8-2.73 8-7.46S82.48 37 77.44 37h-6.71z"/>\n      <path id="_Compound_Path_2" data-name="&lt;Compound Path&gt;" class="cls-1" d="M92.76 61.85c0-4.81 3.67-7.56 10.42-8l7.25-.44v-2.06c0-3-2-4.7-5.56-4.7-2.94 0-5.07 1.51-5.51 3.82h-5.24c.16-4.86 4.73-8.4 10.92-8.4 6.65 0 11 3.48 11 8.89v18.66h-5.38v-4.5h-.13a9.59 9.59 0 0 1-8.58 4.78c-5.42 0-9.19-3.22-9.19-8.05zm17.68-2.42v-2.11l-6.47.42c-3.64.23-5.54 1.59-5.54 4s2 3.77 5.07 3.77c3.95-.05 6.94-2.57 6.94-6.08z"/>\n      <path id="_Compound_Path_3" data-name="&lt;Compound Path&gt;" class="cls-1" d="M121 79.65v-4.5a17.14 17.14 0 0 0 1.72.1c2.57 0 4-1.09 4.91-3.9l.52-1.66-9.88-27.29h6.08l6.86 22.15h.13l6.86-22.15h5.93l-10.21 28.67c-2.34 6.58-5 8.73-10.68 8.73a15.93 15.93 0 0 1-2.24-.15z"/>\n      </g>\n      </g>\n    </symbol>\n    <symbol id="logoGooglePay" viewBox="0 0 60.51 24.04">\n      <title>GooglePay_AcceptanceMark_RGB_60x24pt</title>\n      <path d="M28.67,11.76v7H26.43V1.42h5.92a5.39,5.39,0,0,1,3.84,1.51A5,5,0,0,1,36.44,10l-.25.26a5.35,5.35,0,0,1-3.84,1.48Zm0-8.2V9.62H32.4a2.93,2.93,0,0,0,2.21-.9A3,3,0,0,0,32.4,3.56Z" fill="#5f6368"/>\n      <path d="M42.93,6.52a5.56,5.56,0,0,1,3.91,1.32,4.71,4.71,0,0,1,1.43,3.63v7.32H46.13V17.14H46a4.28,4.28,0,0,1-3.69,2A4.83,4.83,0,0,1,39.06,18a3.74,3.74,0,0,1-1.32-2.92,3.52,3.52,0,0,1,1.39-2.93,5.87,5.87,0,0,1,3.73-1.09,6.65,6.65,0,0,1,3.27.72v-.51a2.5,2.5,0,0,0-.92-2,3.17,3.17,0,0,0-2.16-.81,3.4,3.4,0,0,0-2.95,1.57l-2-1.23A5.45,5.45,0,0,1,42.93,6.52ZM40,15.15a1.82,1.82,0,0,0,.74,1.46,2.74,2.74,0,0,0,1.74.58,3.58,3.58,0,0,0,2.51-1,3.26,3.26,0,0,0,1.11-2.45,4.54,4.54,0,0,0-2.91-.83,3.74,3.74,0,0,0-2.27.66A2,2,0,0,0,40,15.15Z" fill="#5f6368"/>\n      <path d="M60.52,6.9,53.07,24H50.76l2.77-6L48.63,6.91h2.43l3.54,8.54h0l3.44-8.54Z" fill="#5f6368"/>\n      <path d="M19.65,10.24a12.54,12.54,0,0,0-.17-2H10.06v3.84h5.39a4.61,4.61,0,0,1-2,3v2.49h3.22A9.75,9.75,0,0,0,19.65,10.24Z" fill="#4285f4"/>\n      <path d="M10.06,20a9.54,9.54,0,0,0,6.62-2.41l-3.22-2.49a6,6,0,0,1-3.4.95,6,6,0,0,1-5.6-4.12H1.15V14.5A10,10,0,0,0,10.06,20Z" fill="#34a853"/>\n      <path d="M4.46,11.92a6,6,0,0,1,0-3.82V5.53H1.15a10,10,0,0,0,0,9Z" fill="#fbbc04"/>\n      <path d="M10.06,4a5.44,5.44,0,0,1,3.83,1.5h0l2.85-2.85A9.58,9.58,0,0,0,10.06,0a10,10,0,0,0-8.91,5.5L4.46,8.1A6,6,0,0,1,10.06,4Z" fill="#ea4335"/>\n    </symbol>\n\n    <symbol id="logoVenmo" viewBox="0 0 48 32">\n      <title>Venmo</title>\n      <g fill="none" fill-rule="evenodd">\n        <rect fill="#3D95CE" width="47.4074074" height="31.6049383" rx="3.16049383"/>\n        <path d="M33.1851852,10.1131555 C33.1851852,14.8373944 29.2425262,20.9745161 26.0425868,25.2839506 L18.7337285,25.2839506 L15.8024691,7.35534396 L22.202175,6.73384536 L23.7519727,19.4912014 C25.2000422,17.0781163 26.9870326,13.2859484 26.9870326,10.7005 C26.9870326,9.28531656 26.7500128,8.32139205 26.3796046,7.52770719 L32.207522,6.32098765 C32.8813847,7.45939896 33.1851852,8.63196439 33.1851852,10.1131555 Z" fill="#FFF"/>\n      </g>\n    </symbol>\n    <symbol id="buttonVenmo" viewBox="0 0 295 42">\n      <g fill="none" fill-rule="evenodd">\n        <rect fill="#3D95CE" width="295" height="42" rx="3"/>\n        <path d="M11.3250791 0C11.7902741.780434316 12 1.58428287 12 2.59970884 12 5.838396 9.27822123 10.0456806 7.06917212 13L2.02356829 13 0 .709099732 4.41797878.283033306 5.48786751 9.02879887C6.48752911 7.3745159 7.72116169 4.77480706 7.72116169 3.00236102 7.72116169 2.03218642 7.55753727 1.37137098 7.30182933.827262801L11.3250791 0 11.3250791 0zM17.5051689 5.68512193C18.333931 5.68512193 20.4203856 5.28483546 20.4203856 4.03281548 20.4203856 3.43161451 20.0177536 3.13172102 19.5432882 3.13172102 18.7131868 3.13172102 17.6238766 4.18269796 17.5051689 5.68512193L17.5051689 5.68512193zM17.4102028 8.1647385C17.4102028 9.69351403 18.2153451 10.293301 19.2827401 10.293301 20.4451012 10.293301 21.5580312 9.99340752 23.0045601 9.21725797L22.4597224 13.1234575C21.440541 13.649203 19.8521716 14 18.310433 14 14.3996547 14 13 11.49596 13 8.36552446 13 4.30815704 15.2767521 0 19.9706358 0 22.554932 0 24 1.52864698 24 3.65720949 24.0002435 7.08869546 19.8287953 8.13992948 17.4102028 8.1647385L17.4102028 8.1647385zM37 2.84753211C37 3.32189757 36.9261179 4.00994664 36.8526108 4.45959542L35.4649774 12.9998782 30.9621694 12.9998782 32.2279161 5.1711436C32.2519185 4.95879931 32.3256755 4.53131032 32.3256755 4.29412759 32.3256755 3.72466988 31.9603904 3.5825794 31.5212232 3.5825794 30.9379171 3.5825794 30.3532359 3.84326124 29.9638234 4.03356751L28.5281854 13 24 13 26.0686989.213683657 29.9878258.213683657 30.0374555 1.23425123C30.9620444.641294408 32.1795365 3.90379019e-8 33.9069526 3.90379019e-8 36.1955476-.000243475057 37 1.1387937 37 2.84753211L37 2.84753211zM51.2981937 1.39967969C52.6582977.49918987 53.9425913 0 55.7133897 0 58.1518468 0 59 1.13900518 59 2.84769558 59 3.32204771 58.9223438 4.01007745 58.8448195 4.4597136L57.3830637 12.9997565 52.6328518 12.9997565 53.9932194 5.00577861C54.0182698 4.792101 54.0708756 4.53142648 54.0708756 4.36608506 54.0708756 3.72493046 53.6854953 3.58272222 53.2224587 3.58272222 52.6325881 3.58272222 52.0429812 3.81989829 51.6052587 4.03369766L50.0914245 12.9998782 45.3423992 12.9998782 46.7027668 5.00590037C46.7278172 4.79222275 46.7788409 4.53154824 46.7788409 4.36620681 46.7788409 3.72505221 46.3933287 3.58284398 45.9318743 3.58284398 45.3153711 3.58284398 44.7000546 3.84351849 44.2893602 4.03381941L42.7740757 13 38 13 40.1814929.214042876 44.2643098.214042876 44.3925941 1.28145692C45.3423992.641763367 46.6253743.000487014507 48.3452809.000487014507 49.8344603 0 50.8094476.593061916 51.2981937 1.39967969L51.2981937 1.39967969zM67.5285327 5.39061542C67.5285327 4.29258876 67.2694573 3.54396333 66.4936812 3.54396333 64.7759775 3.54396333 64.4232531 6.76273249 64.4232531 8.4093242 64.4232531 9.65848482 64.7530184 10.4315735 65.5285529 10.4315735 67.1521242 10.4315735 67.5285327 7.03707905 67.5285327 5.39061542L67.5285327 5.39061542zM60 8.21054461C60 3.96893154 62.1170713 0 66.988027 0 70.6583423 0 72 2.29633967 72 5.46592624 72 9.65835674 69.905767 14 64.9173573 14 61.2233579 14 60 11.4294418 60 8.21054461L60 8.21054461z" transform="translate(112 14)" fill="#FFF"/>\n      </g>\n    </symbol>\n\n    <symbol id="iconClose" width="21" height="21" viewBox="0 0 21 21" overflow="visible">\n      <path d="M16 5.414L14.586 4 10 8.586 5.414 4 4 5.414 8.586 10 4 14.586 5.414 16 10 11.414 14.586 16 16 14.586 11.414 10"/>\n    </symbol>\n  </defs>\n</svg>\n'+i,n.appendChild(r._dropinWrapper),r._model=new c({client:r._client,componentID:r._componentID,merchantConfiguration:r._merchantConfiguration}),void r._model.initialize().then(function(){return r._model.on("cancelInitialization",function(e){r._dropinWrapper.innerHTML="",o.sendEvent(r._client,"load-error"),t(e)}),r._model.on("asyncDependenciesReady",function(){1<=r._model.dependencySuccessCount?(o.sendEvent(r._client,"appeared"),r._disableErroredPaymentMethods(),r._handleAppSwitch(),t(null,r)):r._model.cancelInitialization(new d("All payment options failed to load."))}),r._model.on("paymentMethodRequestable",function(e){r._emit("paymentMethodRequestable",e)}),r._model.on("noPaymentMethodRequestable",function(){r._emit("noPaymentMethodRequestable")}),r._model.on("paymentOptionSelected",function(e){r._emit("paymentOptionSelected",e)}),r._setUpDependenciesAndViews()}).catch(function(e){r.teardown().then(function(){t(e)})})):(o.sendEvent(r._client,"configuration-error"),void t(new d("options.selector or options.container must reference a valid DOM node.")))):(o.sendEvent(r._client,"configuration-error"),void t(new d("options.container is required.")))},I.prototype.updateConfiguration=function(t,e,i){var r;-1!==P.indexOf(t)&&("threeDSecure"!==t?(r=this._mainView.getView(t))&&(r.updateConfiguration(e,i),-1!==T.indexOf(t)&&(this._removeUnvaultedPaymentMethods(function(e){return e.type===l.paymentMethodTypes[t]}),this._navigateToInitialView())):this._threeDSecure&&this._threeDSecure.updateConfiguration(e,i))},I.prototype.clearSelectedPaymentMethod=function(){this._removeUnvaultedPaymentMethods(),this._model.removeActivePaymentMethod(),0!==this._model.getPaymentMethods().length?(this._mainView.showLoadingIndicator(),this._model.refreshPaymentMethods().then(function(){this._navigateToInitialView(),this._mainView.hideLoadingIndicator()}.bind(this))):this._navigateToInitialView()},I.prototype._setUpDataCollector=function(){var t=this,e=a({},t._merchantConfiguration.dataCollector,{client:t._client});this._model.asyncDependencyStarting(),this._dataCollector=new E(e),this._dataCollector.initialize().then(function(){t._model.asyncDependencyReady()}).catch(function(e){t._model.cancelInitialization(new d({message:"Data Collector failed to set up.",braintreeWebError:e}))})},I.prototype._setUpThreeDSecure=function(){var t=this,e=a({},this._merchantConfiguration.threeDSecure);this._model.asyncDependencyStarting(),this._threeDSecure=new _(this._client,e,this._strings.cardVerification),this._threeDSecure.initialize().then(function(){t._model.asyncDependencyReady()}).catch(function(e){t._model.cancelInitialization(new d({message:"3D Secure failed to set up.",braintreeWebError:e}))})},I.prototype._setUpDependenciesAndViews=function(){this._merchantConfiguration.dataCollector&&this._setUpDataCollector(),this._merchantConfiguration.threeDSecure&&this._setUpThreeDSecure(),this._mainView=new p({client:this._client,element:this._dropinWrapper,model:this._model,strings:this._strings})},I.prototype._removeUnvaultedPaymentMethods=function(t){t=t||function(){return!0},this._model.getPaymentMethods().forEach(function(e){t(e)&&!e.vaulted&&this._model.removePaymentMethod(e)}.bind(this))},I.prototype._navigateToInitialView=function(){this._mainView.primaryView.ID===u&&0===this._model.getPaymentMethods().length&&(1===this._model.supportedPaymentOptions.length?this._mainView.setPrimaryView(this._model.supportedPaymentOptions[0]):this._mainView.setPrimaryView(h))},I.prototype._supportsPaymentOption=function(e){return-1!==this._model.supportedPaymentOptions.indexOf(e)},I.prototype._disableErroredPaymentMethods=function(){var o,e=Object.keys(this._model.failedDependencies);0!==e.length&&(o=this._mainView.getOptionsElements(),e.forEach(function(e){var t=o[e],i=t.div,r=t.clickHandler,n=this._model.failedDependencies[e],a=i.querySelector(".braintree-option__disabled-message");s.add(i,"braintree-disabled"),i.removeEventListener("click",r),a.innerHTML=l.errors.DEVELOPER_MISCONFIGURATION_MESSAGE,console.error(n)}.bind(this)))},I.prototype._handleAppSwitch=function(){this._model.appSwitchError?(this._mainView.setPrimaryView(this._model.appSwitchError.id),this._model.reportError(this._model.appSwitchError.error)):this._model.appSwitchPayload&&this._model.addPaymentMethod(this._model.appSwitchPayload)},I.prototype.requestPaymentMethod=function(){return this._mainView.requestPaymentMethod().then(function(t){return this._threeDSecure&&t.type===l.paymentMethodTypes.card&&null==t.liabilityShifted?this._threeDSecure.verify(t.nonce).then(function(e){return t.nonce=e.nonce,t.liabilityShifted=e.liabilityShifted,t.liabilityShiftPossible=e.liabilityShiftPossible,t}):t}.bind(this)).then(function(e){return this._dataCollector&&(e.deviceData=this._dataCollector.getDeviceData()),e}.bind(this)).then(function(e){return function(e){var t={nonce:e.nonce,details:e.details,type:e.type};null!=e.vaulted&&(t.vaulted=e.vaulted);e.type===l.paymentMethodTypes.card&&(t.description=e.description);e.type in A&&(t.details.rawPaymentData=e.rawPaymentData);"boolean"==typeof e.liabilityShiftPossible&&(t.liabilityShifted=e.liabilityShifted,t.liabilityShiftPossible=e.liabilityShiftPossible);e.deviceData&&(t.deviceData=e.deviceData);e.binData&&(t.binData=e.binData);return t}(e)})},I.prototype._removeStylesheet=function(){var e=document.getElementById(l.STYLESHEET_ID);e&&e.parentNode.removeChild(e)},I.prototype._injectStylesheet=function(){var e;document.getElementById(l.STYLESHEET_ID)||(e=this._client.getConfiguration().gatewayConfiguration.assetsUrl+"/web/dropin/1.15.0/css/dropin.min.css",n.loadStylesheet({href:e,id:l.STYLESHEET_ID}))},I.prototype.teardown=function(){var t,e=v.resolve(),i=this;return this._removeStylesheet(),this._mainView&&e.then(function(){return i._mainView.teardown().catch(function(e){t=e})}),this._dataCollector&&e.then(function(){return this._dataCollector.teardown().catch(function(e){t=new d({message:"Drop-in errored tearing down Data Collector.",braintreeWebError:e})})}.bind(this)),this._threeDSecure&&e.then(function(){return this._threeDSecure.teardown().catch(function(e){t=new d({message:"Drop-in errored tearing down 3D Secure.",braintreeWebError:e})})}.bind(this)),e.then(function(){return i._removeDropinWrapper()}).then(function(){return t?v.reject(t):v.resolve()})},I.prototype.isPaymentMethodRequestable=function(){return this._model.isPaymentMethodRequestable()},I.prototype._removeDropinWrapper=function(){return this._dropinWrapper.parentNode.removeChild(this._dropinWrapper),v.resolve()},t.exports=C(I)},{"./constants":125,"./dropin-model":126,"./lib/analytics":130,"./lib/assign":131,"./lib/data-collector":134,"./lib/dropin-error":135,"./lib/event-emitter":136,"./lib/is-utf-8":140,"./lib/promise":143,"./lib/sanitize-html":144,"./lib/three-d-secure":146,"./lib/uuid":148,"./translations":158,"./views/main-view":175,"./views/payment-methods-view":177,"./views/payment-options-view":178,"@braintree/asset-loader":1,"@braintree/class-list":18,"@braintree/wrap-promise":26}],128:[function(e,t,i){"use strict";var a=e("./dropin"),r=e("braintree-web/client"),n=e("./lib/create-from-script-tag"),o=e("./constants"),s=e("./lib/analytics"),l=e("./lib/dropin-error"),d=e("./lib/promise"),c=e("@braintree/wrap-promise"),p="1.15.0";function u(n){return n.authorization?r.create({authorization:n.authorization}).catch(function(e){return d.reject(new l({message:"There was an error creating Drop-in.",braintreeWebError:e}))}).then(function(e){var t,i;return(i=(t=e).getConfiguration()).analyticsMetadata.integration=o.INTEGRATION,i.analyticsMetadata.integrationType=o.INTEGRATION,i.analyticsMetadata.dropinVersion=p,t.getConfiguration=function(){return i},"TOKENIZATION_KEY"===(e=t).getConfiguration().authorizationType?s.sendEvent(e,"started.tokenization-key"):s.sendEvent(e,"started.client-token"),new d(function(i,r){new a({merchantConfiguration:n,client:e})._initialize(function(e,t){e?r(e):i(t)})})}):d.reject(new l("options.authorization is required."))}n(u,"undefined"!=typeof document&&document.querySelector("script[data-braintree-dropin-authorization]")),t.exports={create:c(u),VERSION:p}},{"./constants":125,"./dropin":127,"./lib/analytics":130,"./lib/create-from-script-tag":133,"./lib/dropin-error":135,"./lib/promise":143,"@braintree/wrap-promise":26,"braintree-web/client":35}],129:[function(e,t,i){"use strict";t.exports=function(e,t){e.addEventListener("click",t),e.addEventListener("keyup",function(e){13===e.keyCode&&t()})}},{}],130:[function(e,t,i){"use strict";var d=e("./polyfill").atob,c=e("../constants"),p=e("braintree-web/client").VERSION;t.exports={sendEvent:function(e,t,i){var r,n=e.getConfiguration(),a=e._request,o=(r=Date.now(),Math.floor(r/1e3)),s=n.gatewayConfiguration.analytics.url,l={analytics:[{kind:c.ANALYTICS_PREFIX+t,timestamp:o}],_meta:n.analyticsMetadata,braintreeLibraryVersion:p};"TOKENIZATION_KEY"===n.authorizationType?l.tokenizationKey=n.authorization:l.authorizationFingerprint=JSON.parse(d(n.authorization)).authorizationFingerprint,a({url:s,method:"post",data:l,timeout:c.ANALYTICS_REQUEST_TIMEOUT_MS},i)}}},{"../constants":125,"./polyfill":142,"braintree-web/client":35}],131:[function(e,t,i){arguments[4][69][0].apply(i,arguments)},{dup:69}],132:[function(e,t,i){"use strict";var r=e("@braintree/browser-detection/is-ie9"),n=e("@braintree/browser-detection/is-ie10");t.exports={isIe9:r,isIe10:n}},{"@braintree/browser-detection/is-ie10":9,"@braintree/browser-detection/is-ie9":11}],133:[function(e,t,i){"use strict";var o=e("./analytics"),s=e("./find-parent-form"),l=e("./uuid"),d=e("./dropin-error"),a=e("./kebab-case-to-camel-case"),c=["locale","payment-option-priority","data-collector.kount","data-collector.paypal","card.cardholderName","card.cardholderName.required","card.cardholder-name","card.cardholder-name.required","paypal.amount","paypal.currency","paypal.flow","paypal.landing-page-type","paypal-credit.amount","paypal-credit.currency","paypal-credit.flow","paypal-credit.landing-page-type"];function p(e,t,i){var r=i.querySelector('[name="'+e+'"]');r||((r=document.createElement("input")).type="hidden",r.name=e,i.appendChild(r)),r.value=t}function u(e,t,i){var r=t.split("."),n=a(r[0]);1===r.length?e[n]=function(t){try{return JSON.parse(t)}catch(e){return t}}(i):(e[n]=e[n]||{},u(e[n],r.slice(1).join("."),i))}t.exports=function(e,i){var t,r,n,a;if(i){if(!(t=i.getAttribute("data-braintree-dropin-authorization")))throw new d("Authorization not found in data-braintree-dropin-authorization attribute");if((r=document.createElement("div")).id="braintree-dropin-"+l(),!(a=s.findParentForm(i)))throw new d("No form found for script tag integration.");a.addEventListener("submit",function(e){e.preventDefault()}),i.parentNode.insertBefore(r,i),n={authorization:t,container:r},c.forEach(function(e){var t=i.getAttribute("data-"+e);null!=t&&u(n,e,t)}),e(n).then(function(e){o.sendEvent(e._client,"integration-type.script-tag"),a.addEventListener("submit",function(){e.requestPaymentMethod(function(e,t){e||(p("payment_method_nonce",t.nonce,a),t.deviceData&&p("device_data",t.deviceData,a),a.submit())})})})}}},{"./analytics":130,"./dropin-error":135,"./find-parent-form":137,"./kebab-case-to-camel-case":141,"./uuid":148}],134:[function(t,o,e){(function(i){"use strict";var r=t("../constants"),n=t("@braintree/asset-loader"),a=t("./promise");function e(e){this._config=e}e.prototype.initialize=function(){var t=this;return a.resolve().then(function(){var e;return i.braintree&&i.braintree.dataCollector?a.resolve():(e=t._config.client.getVersion(),n.loadScript({src:"https://js.braintreegateway.com/web/"+e+"/js/data-collector.min.js",id:r.DATA_COLLECTOR_SCRIPT_ID}))}).then(function(){return i.braintree.dataCollector.create(t._config)}).then(function(e){t._instance=e})},e.prototype.getDeviceData=function(){return this._instance.deviceData},e.prototype.teardown=function(){return this._instance.teardown()},o.exports=e}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../constants":125,"./promise":143,"@braintree/asset-loader":1}],135:[function(e,t,i){"use strict";function r(e){this.name="DropinError",this.message="string"==typeof e?e:e.message,"BraintreeError"===e.name?this._braintreeWebError=e:this._braintreeWebError=e.braintreeWebError}(r.prototype=Object.create(Error.prototype)).constructor=r,t.exports=r},{}],136:[function(e,t,i){arguments[4][86][0].apply(i,arguments)},{dup:86}],137:[function(e,t,i){"use strict";t.exports={findParentForm:function e(t){var i=t.parentNode;return i&&"FORM"!==i.nodeName?e(i):i}}},{}],138:[function(e,t,i){"use strict";var r=e("./polyfill").atob;t.exports=function(e){var t,i=e.getConfiguration();return"TOKENIZATION_KEY"===i.authorizationType||(!(t=JSON.parse(r(i.authorization)).authorizationFingerprint)||-1===t.indexOf("customer_id="))}},{"./polyfill":142}],139:[function(e,t,i){(function(e){"use strict";t.exports={isHTTPS:function(){return"https:"===e.location.protocol}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],140:[function(e,i,t){(function(t){"use strict";i.exports=function(e){return e=e||t,Boolean(e.document.characterSet&&"utf-8"===e.document.characterSet.toLowerCase())}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],141:[function(e,t,i){"use strict";t.exports=function(e){var t=e.split("-"),i=t.shift(),r=t.map(function(e){return e.charAt(0).toUpperCase()+e.substring(1)});return[i].concat(r).join("")}},{}],142:[function(e,r,t){(function(t){"use strict";var i="function"==typeof t.atob?t.atob:e;function e(e){var t,i,r,n,a,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l="";if(!new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$").test(e))throw new Error("Non base64 encoded input passed to window.atob polyfill");for(o=0;t=(63&s.indexOf(e.charAt(o++)))<<2|(n=s.indexOf(e.charAt(o++)))>>4&3,i=(15&n)<<4|(a=s.indexOf(e.charAt(o++)))>>2&15,r=(3&a)<<6|63&s.indexOf(e.charAt(o++)),l+=String.fromCharCode(t)+(i?String.fromCharCode(i):"")+(r?String.fromCharCode(r):""),o<e.length;);return l}r.exports={atob:function(e){return i.call(t,e)},_atob:e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],143:[function(e,t,i){arguments[4][95][0].apply(i,arguments)},{dup:95,"promise-polyfill":121}],144:[function(e,t,i){"use strict";t.exports=function(e){return"string"!=typeof e?"":e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}},{}],145:[function(e,t,i){"use strict";t.exports=function(){var t=document.createElement("div");return["-webkit-","-moz-","-ms-","-o-",""].forEach(function(e){t.style.cssText+=e+"flex-basis: 1px"}),Boolean(t.style.length)}},{}],146:[function(e,t,i){"use strict";var n=e("@braintree/class-list"),r=e("braintree-web/three-d-secure"),a=e("./promise");function o(e,t,i){this._client=e,this._config=t,this._modal=this._setupModal(i)}o.prototype.initialize=function(){var t=this;return r.create({client:this._client}).then(function(e){t._instance=e})},o.prototype.verify=function(e){var r=this;return this._revealModal(),a.all([this._waitForThreeDSecure(),this._instance.verifyCard({nonce:e,amount:this._config.amount,showLoader:!1,addFrame:function(e,t){var i=r._modal.querySelector(".braintree-three-d-secure__modal-body");t.onload=function(){n.add(i,"braintree-three-d-secure__frame-active")},i.appendChild(t)},removeFrame:function(){r._cleanupModal()}}).then(function(e){return r._resolveThreeDSecure(),e})]).then(function(e){return r._cleanupModal(),e[1]}).catch(function(e){return r._cleanupModal(),"THREE_D_SECURE_CANCELLED"===e.type?a.resolve(e.payload):a.reject(e)})},o.prototype.cancel=function(){var t=this;return this._instance.cancelVerifyCard().then(function(e){t._rejectThreeDSecure({type:"THREE_D_SECURE_CANCELLED",payload:{nonce:e.nonce,liabilityShifted:e.liabilityShifted,liabilityShiftPossible:e.liabilityShiftPossible}})}).catch(function(){}).then(function(){t._cleanupModal()})},o.prototype.updateConfiguration=function(e,t){this._config[e]=t},o.prototype.teardown=function(){return a.all([this._cleanupModal(),this._instance.teardown()])},o.prototype._cleanupModal=function(){var e=this._modal.querySelector("iframe"),t=this;return n.remove(this._modal.querySelector(".braintree-three-d-secure__modal"),"braintree-three-d-secure__frame_visible"),n.remove(this._modal.querySelector(".braintree-three-d-secure__backdrop"),"braintree-three-d-secure__frame_visible"),e&&e.parentNode&&e.parentNode.removeChild(e),new a(function(e){setTimeout(function(){t._modal.parentNode&&t._modal.parentNode.removeChild(t._modal),e()},300)})},o.prototype._setupModal=function(e){var t=this,i=document.createElement("div");return i.innerHTML='<div class="braintree-three-d-secure">\n  <div class="braintree-three-d-secure__backdrop"></div>\n  <div class="braintree-three-d-secure__modal">\n    <div data-braintree-id="three-d-secure-loading-container" class="braintree-loader__container">\n      <div data-braintree-id="three-d-secure-loading-indicator" class="braintree-loader__indicator">\n        <svg width="14" height="16" class="braintree-loader__lock">\n          <use xlink:href="#iconLockLoader"></use>\n        </svg>\n      </div>\n    </div>\n    <div class="braintree-three-d-secure__modal-header">\n      {{cardVerification}}\n      <div class="braintree-three-d-secure__modal-close">\n        <svg width="21" height="21">\n          <use xlink:href="#iconClose"></use>\n        </svg>\n      </div>\n    </div>\n    <div class="braintree-three-d-secure__modal-body">\n    </div>\n  </div>\n</div>\n'.replace("{{cardVerification}}",e),i.querySelector(".braintree-three-d-secure__modal-close").addEventListener("click",function(){t.cancel()}),i},o.prototype._waitForThreeDSecure=function(){var i=this;return new a(function(e,t){i._resolveThreeDSecure=e,i._rejectThreeDSecure=t})},o.prototype._revealModal=function(){document.body.appendChild(this._modal),n.add(this._modal.querySelector(".braintree-three-d-secure__backdrop"),"braintree-three-d-secure__frame_visible"),setTimeout(function(){n.add(this._modal.querySelector(".braintree-three-d-secure__modal"),"braintree-three-d-secure__frame_visible")}.bind(this),10)},t.exports=o},{"./promise":143,"@braintree/class-list":18,"braintree-web/three-d-secure":105}],147:[function(e,t,i){"use strict";var a=e("./browser-detection");t.exports={onTransitionEnd:function(i,r,n){a.isIe9()||function e(t){return!!t&&("none"===t.style.display||e(t.parentNode))}(i)?n():i.addEventListener("transitionend",function e(t){t.propertyName===r&&(i.removeEventListener("transitionend",e),n())})}}},{"./browser-detection":132}],148:[function(e,t,i){"use strict";t.exports=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}},{}],149:[function(e,t,i){"use strict";t.exports={payingWith:"Betaler med {{paymentSource}}",chooseAnotherWayToPay:"Vælg en anden betalingsmetode",chooseAWayToPay:"Vælg, hvordan du vil betale",otherWaysToPay:"Andre betalingsmetoder",edit:"Rediger",doneEditing:"Udført",editPaymentMethods:"Rediger betalingsmetoder",CreditCardDeleteConfirmationMessage:"Vil du slette {{secondaryIdentifier}}-kortet, der slutter på {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Vil du slette PayPal-kontoen {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Er du sikker på, at du vil slette Venmo-kontoen med brugernavnet {{identifier}}?",genericDeleteConfirmationMessage:"Er du sikker på, at du vil slette denne betalingsmetode?",deleteCancelButton:"Annuller",deleteConfirmationButton:"Slet",cardVerification:"Bekræftelse af kort",fieldEmptyForCvv:"Du skal angive kontrolcifrene.",fieldEmptyForExpirationDate:"Du skal angive udløbsdatoen.",fieldEmptyForCardholderName:"Du skal angive kortindehaverens navn.",fieldTooLongForCardholderName:"Kortejerens navn skal være mindre end 256 tegn.",fieldEmptyForNumber:"Du skal angive et nummer.",fieldEmptyForPostalCode:"Du skal angive et postnummer.",fieldInvalidForCvv:"Sikkerhedskoden er ugyldig.",fieldInvalidForExpirationDate:"Udløbsdatoen er ugyldig.",fieldInvalidForNumber:"Kortnummeret er ugyldigt.",fieldInvalidForPostalCode:"Postnummeret er ugyldigt.",genericError:"Der opstod en fejl.",hostedFieldsTokenizationFailOnDuplicateError:"Dette betalingskort er allerede en gemt betalingsmetode.",hostedFieldsFailedTokenizationError:"Tjek oplysningerne, og prøv igen.",hostedFieldsFieldsInvalidError:"Tjek oplysningerne, og prøv igen.",hostedFieldsTokenizationNetworkErrorError:"Netværksfejl. Prøv igen.",hostedFieldsTokenizationCvvVerificationFailedError:"Betalingskortet blev ikke bekræftet. Kontrollér oplysningerne, og prøv igen.",paypalAccountTokenizationFailedError:"PayPal-kontoen blev ikke tilføjet. Prøv igen.",paypalFlowFailedError:"Der kunne ikke oprettes forbindelse til PayPal. Prøv igen.",paypalTokenizationRequestActiveError:"PayPal-betalingen er i gang med at blive autoriseret.",venmoCanceledError:"Der opstod en fejl. Sørg for, at du har den seneste version af Venmo-appen installeret på din enhed, og at din browser understøtter skift til Venmo.",vaultManagerPaymentMethodDeletionError:"Vi kunne ikke slette betalingsmetode. Prøv igen.",venmoAppFailedError:"Venmo-appen blev ikke fundet på din enhed.",unsupportedCardTypeError:"Korttypen understøttes ikke. Prøv et andet kort.",applePayTokenizationError:"Der opstod en netværksfejl under behandlingen af betalingen med Apple Pay. Prøv igen.",applePayActiveCardError:"Knyt et understøttet kort til din Apple Pay-e-pung.",cardholderNameLabel:"Kortindehaverens navn",cardNumberLabel:"Kortnummer",cvvLabel:"Kontrolcifre",cvvThreeDigitLabelSubheading:"(3 cifre)",cvvFourDigitLabelSubheading:"(4 cifre)",cardholderNamePlaceholder:"Kortindehaverens navn",expirationDateLabel:"Udløbsdato",expirationDateLabelSubheading:"(MM/ÅÅ)",expirationDatePlaceholder:"MM/ÅÅ",postalCodeLabel:"Postnummer",payWithCard:"Betal med kort",endingIn:"Der slutter på {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Kort",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],150:[function(e,t,i){"use strict";t.exports={payingWith:"Zahlen mit {{paymentSource}}",chooseAnotherWayToPay:"Andere Zahlungsmethode wählen",chooseAWayToPay:"Wie möchten Sie bezahlen?",otherWaysToPay:"Andere Zahlungsmethoden",edit:"Bearbeiten",doneEditing:"Fertig",editPaymentMethods:"Zahlungsquellen bearbeiten",CreditCardDeleteConfirmationMessage:"{{secondaryIdentifier}} Karte mit den Endziffern {{identifier}} löschen?",PayPalAccountDeleteConfirmationMessage:"PayPal-Konto {{identifier}} löschen?",VenmoAccountDeleteConfirmationMessage:"Wollen Sie das Venmo-Konto mit dem Benutzernamen {{identifier}} wirklich löschen?",genericDeleteConfirmationMessage:"Wollen Sie diese Zahlungsquelle wirklich löschen?",deleteCancelButton:"Abbrechen",deleteConfirmationButton:"Löschen",cardVerification:"Kartenbestätigung",fieldEmptyForCvv:"Geben Sie die Kartenprüfnummer ein.",fieldEmptyForExpirationDate:"Geben Sie das Ablaufdatum ein.",fieldEmptyForCardholderName:"Geben Sie den Namen des Karteninhabers ein.",fieldTooLongForCardholderName:"Der Name des Karteninhabers darf 255 Zeichen nicht übersteigen.",fieldEmptyForNumber:"Geben Sie die Nummer ein.",fieldEmptyForPostalCode:"Geben Sie die PLZ ein.",fieldInvalidForCvv:"Die Kartenprüfnummer ist ungültig.",fieldInvalidForExpirationDate:"Das Ablaufdatum ist ungültig.",fieldInvalidForNumber:"Die Kreditkartennummer ist ungültig.",fieldInvalidForPostalCode:"Die PLZ ist ungültig.",genericError:"Bei uns ist ein Problem aufgetreten.",hostedFieldsTokenizationFailOnDuplicateError:"Diese Kreditkarte ist bereits als gespeicherte Zahlungsmethode vorhanden.",hostedFieldsFailedTokenizationError:"Überprüfen Sie Ihre Eingabe und versuchen Sie es erneut.",hostedFieldsFieldsInvalidError:"Überprüfen Sie Ihre Eingabe und versuchen Sie es erneut.",hostedFieldsTokenizationNetworkErrorError:"Netzwerkfehler. Versuchen Sie es erneut.",hostedFieldsTokenizationCvvVerificationFailedError:"Überprüfung der Karte fehlgeschlagen. Überprüfen Sie Ihre Eingabe und versuchen Sie es erneut.",paypalAccountTokenizationFailedError:"Beim Hinzufügen des PayPal-Kontos ist ein Problem aufgetreten. Versuchen Sie es erneut.",paypalFlowFailedError:"Beim Verbinden mit PayPal ist ein Problem aufgetreten. Versuchen Sie es erneut.",paypalTokenizationRequestActiveError:"Die PayPal-Zahlung wird bereits autorisiert.",venmoCanceledError:"Etwas ist schief gelaufen. Vergewissern Sie sich, dass Sie die neueste Version der Venmo-App auf Ihrem Gerät installiert haben und Ihr Browser den Wechsel zu Venmo unterstützt.",vaultManagerPaymentMethodDeletionError:"Die Zahlungsquelle konnte nicht gelöscht werden. Versuchen Sie es erneut.",venmoAppFailedError:"Die Venmo-App wurde auf Ihrem Gerät nicht gefunden.",unsupportedCardTypeError:"Dieser Kreditkartentyp wird nicht unterstützt. Versuchen Sie es mit einer anderen Karte.",applePayTokenizationError:"Netzwerkfehler bei der Zahlungsabwicklung mit Apple Pay. Versuchen Sie es erneut.",applePayActiveCardError:"Fügen Sie der Apple-Pay-Börse eine unterstützte Kreditkarte hinzu.",cardholderNameLabel:"Name des Karteninhabers",cardNumberLabel:"Kartennummer",cvvLabel:"Prüfnr.",cvvThreeDigitLabelSubheading:"(3-stellig)",cvvFourDigitLabelSubheading:"(4-stellig)",cardholderNamePlaceholder:"Name des Karteninhabers",expirationDateLabel:"Gültig bis",expirationDateLabelSubheading:"(MM/JJ)",expirationDatePlaceholder:"MM/JJ",postalCodeLabel:"PLZ",payWithCard:"Mit Kreditkarte zahlen",endingIn:"Mit den Endziffern {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Kreditkarte",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],151:[function(e,t,i){"use strict";t.exports={payingWith:"Paying with {{paymentSource}}",chooseAnotherWayToPay:"Choose another way to pay",chooseAWayToPay:"Choose a way to pay",otherWaysToPay:"Other ways to pay",edit:"Edit",doneEditing:"Done",editPaymentMethods:"Edit payment methods",CreditCardDeleteConfirmationMessage:"Delete {{secondaryIdentifier}} card ending in {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Delete PayPal account {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Are you sure you want to delete the Venmo account with username {{identifier}}?",genericDeleteConfirmationMessage:"Are you sure you want to delete this payment method?",deleteCancelButton:"Cancel",deleteConfirmationButton:"Delete",cardVerification:"Card verification",fieldEmptyForCvv:"Please fill out a CVV.",fieldEmptyForExpirationDate:"Please fill out an expiry date.",fieldEmptyForCardholderName:"Please fill out a cardholder name.",fieldTooLongForCardholderName:"Cardholder name must be less than 256 characters.",fieldEmptyForNumber:"Please fill out a number.",fieldEmptyForPostalCode:"Please fill out a postcode.",fieldInvalidForCvv:"This security code is not valid.",fieldInvalidForExpirationDate:"This expiry date is not valid.",fieldInvalidForNumber:"This card number is not valid.",fieldInvalidForPostalCode:"This postcode is not valid.",genericError:"Something went wrong on our end.",hostedFieldsTokenizationFailOnDuplicateError:"This credit card already exists as a saved payment method.",hostedFieldsFailedTokenizationError:"Check your entries and try again.",hostedFieldsFieldsInvalidError:"Check your entries and try again.",hostedFieldsTokenizationNetworkErrorError:"Network error. Please try again.",hostedFieldsTokenizationCvvVerificationFailedError:"Credit card verification failed. Check your entries and try again.",paypalAccountTokenizationFailedError:"Something went wrong while adding the PayPal account. Please try again.",paypalFlowFailedError:"Something went wrong while connecting to PayPal. Please try again.",paypalTokenizationRequestActiveError:"PayPal payment authorisation is already in progress.",venmoCanceledError:"We're sorry, something seems to have gone wrong. Please ensure you have the most recent version of the Venmo app installed on your device and your browser supports switching to Venmo.",vaultManagerPaymentMethodDeletionError:"Unable to delete payment method, try again.",venmoAppFailedError:"The Venmo app wasn't found on your device.",unsupportedCardTypeError:"This card type is not supported. Please try another card.",applePayTokenizationError:"A network error occurred while processing the Apple Pay payment. Please try again.",applePayActiveCardError:"Link a supported card to your Apple Pay wallet.",cardholderNameLabel:"Cardholder Name",cardNumberLabel:"Card Number",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 digits)",cvvFourDigitLabelSubheading:"(4 digits)",cardholderNamePlaceholder:"Cardholder Name",expirationDateLabel:"Expiry date",expirationDateLabelSubheading:"(MM/YY)",expirationDatePlaceholder:"MM/YY",postalCodeLabel:"Postcode",payWithCard:"Pay with credit or debit card",endingIn:"Ending in {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Card",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],152:[function(e,t,i){"use strict";t.exports={payingWith:"Paying with {{paymentSource}}",chooseAnotherWayToPay:"Choose another way to pay",chooseAWayToPay:"Choose a way to pay",otherWaysToPay:"Other ways to pay",edit:"Edit",doneEditing:"Done",editPaymentMethods:"Edit funding sources",CreditCardDeleteConfirmationMessage:"Delete {{secondaryIdentifier}} card ending in {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Delete PayPal account {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Are you sure you want to delete the Venmo account with username {{identifier}}?",genericDeleteConfirmationMessage:"Are you sure you want to delete this funding source?",deleteCancelButton:"Cancel",deleteConfirmationButton:"Delete",cardVerification:"Card Verification",fieldEmptyForCvv:"Please fill in a CSC.",fieldEmptyForExpirationDate:"Please fill in an expiry date.",fieldEmptyForCardholderName:"Please fill in a cardholder name.",fieldTooLongForCardholderName:"Cardholder name must be less than 256 characters.",fieldEmptyForNumber:"Please fill in a number.",fieldEmptyForPostalCode:"Please fill in a postcode.",fieldInvalidForCvv:"This security code is not valid.",fieldInvalidForExpirationDate:"This expiry date is not valid.",fieldInvalidForNumber:"This card number is not valid.",fieldInvalidForPostalCode:"This postcode is not valid.",genericError:"Something went wrong on our end.",hostedFieldsTokenizationFailOnDuplicateError:"This credit card has already been added to your account as a funding source.",hostedFieldsFailedTokenizationError:"Please check your information and try again.",hostedFieldsFieldsInvalidError:"Please check your information and try again.",hostedFieldsTokenizationNetworkErrorError:"Network error. Please try again.",hostedFieldsTokenizationCvvVerificationFailedError:"Credit card verification failed. Please check your information and try again.",paypalAccountTokenizationFailedError:"Something went wrong while adding the PayPal account. Please try again.",paypalFlowFailedError:"Something went wrong while connecting to PayPal. Please try again.",paypalTokenizationRequestActiveError:"PayPal payment authorisation is already in progress.",venmoCanceledError:"We're sorry, something seems to have gone wrong. Make sure you have the most recent version of the Venmo app installed on your device and your browser supports the switch to Venmo.",vaultManagerPaymentMethodDeletionError:"Unable to delete funding source, try again.",venmoAppFailedError:"The Venmo app isn't on your device.",unsupportedCardTypeError:"This card type is not supported. Please try another card.",applePayTokenizationError:"A network error occurred while processing the Apple Pay payment. Please try again.",applePayActiveCardError:"Add a supported card to your Apple Pay wallet.",cardholderNameLabel:"Cardholder Name",cardNumberLabel:"Card Number",cvvLabel:"CSC",cvvThreeDigitLabelSubheading:"(3 digits)",cvvFourDigitLabelSubheading:"(4 digits)",cardholderNamePlaceholder:"Cardholder Name",expirationDateLabel:"Expiry Date",expirationDateLabelSubheading:"(MM/YY)",expirationDatePlaceholder:"MM/YY",postalCodeLabel:"Postcode",payWithCard:"Pay with card",endingIn:"Ending in {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Card",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],153:[function(e,t,i){"use strict";t.exports={payingWith:"Paying with {{paymentSource}}",chooseAnotherWayToPay:"Choose another way to pay",chooseAWayToPay:"Choose a way to pay",otherWaysToPay:"Other ways to pay",edit:"Edit",doneEditing:"Done",editPaymentMethods:"Edit payment methods",CreditCardDeleteConfirmationMessage:"Delete {{secondaryIdentifier}} card ending in {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Delete PayPal account {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Are you sure you want to delete Venmo account with username {{identifier}}?",genericDeleteConfirmationMessage:"Are you sure you want to delete this payment method?",deleteCancelButton:"Cancel",deleteConfirmationButton:"Delete",cardVerification:"Card Verification",fieldEmptyForCvv:"Please fill out a CVV.",fieldEmptyForExpirationDate:"Please fill out an expiration date.",fieldEmptyForCardholderName:"Please fill out a cardholder name.",fieldEmptyForNumber:"Please fill out a card number.",fieldEmptyForPostalCode:"Please fill out a postal code.",fieldInvalidForCvv:"This security code is not valid.",fieldInvalidForExpirationDate:"This expiration date is not valid.",fieldInvalidForNumber:"This card number is not valid.",fieldInvalidForPostalCode:"This postal code is not valid.",fieldTooLongForCardholderName:"Cardholder name must be less than 256 characters.",genericError:"Something went wrong on our end.",hostedFieldsTokenizationFailOnDuplicateError:"This credit card already exists as a saved payment method.",hostedFieldsFailedTokenizationError:"Please check your information and try again.",hostedFieldsTokenizationCvvVerificationFailedError:"Credit card verification failed. Please check your information and try again.",hostedFieldsTokenizationNetworkErrorError:"Network error. Please try again.",hostedFieldsFieldsInvalidError:"Please check your information and try again.",paypalAccountTokenizationFailedError:"Something went wrong adding the PayPal account. Please try again.",paypalFlowFailedError:"Something went wrong connecting to PayPal. Please try again.",paypalTokenizationRequestActiveError:"PayPal payment authorization is already in progress.",applePayTokenizationError:"A network error occurred while processing the Apple Pay payment. Please try again.",applePayActiveCardError:"Add a supported card to your Apple Pay wallet.",vaultManagerPaymentMethodDeletionError:"Unable to delete payment method, try again.",venmoCanceledError:"Something went wrong. Ensure you have the most recent version of the Venmo app installed on your device and your browser supports switching to Venmo.",venmoAppFailedError:"The Venmo app could not be found on your device.",unsupportedCardTypeError:"This card type is not supported. Please try another card.",cardholderNameLabel:"Cardholder Name",cardNumberLabel:"Card Number",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 digits)",cvvFourDigitLabelSubheading:"(4 digits)",expirationDateLabel:"Expiration Date",expirationDateLabelSubheading:"(MM/YY)",cardholderNamePlaceholder:"Cardholder Name",expirationDatePlaceholder:"MM/YY",postalCodeLabel:"Postal Code",payWithCard:"Pay with card",endingIn:"Ending in {{lastFourCardDigits}}",Card:"Card",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Apple Pay":"Apple Pay","Google Pay":"Google Pay",Venmo:"Venmo","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],154:[function(e,t,i){"use strict";t.exports={payingWith:"Pago con {{paymentSource}}",chooseAnotherWayToPay:"Selecciona otra forma de pago.",chooseAWayToPay:"Selecciona una forma de pago.",otherWaysToPay:"Otras formas de pago",edit:"Modificar",doneEditing:"Hecho",editPaymentMethods:"Editar formas de pago",CreditCardDeleteConfirmationMessage:"¿Quieres eliminar la tarjeta {{secondaryIdentifier}} que termina en {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"¿Quieres eliminar la cuenta PayPal {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"¿Seguro de que deseas eliminar la cuenta de Venmo con nombre de usuario {{identifier}}?",genericDeleteConfirmationMessage:"¿Seguro que deseas eliminar esta forma de pago?",deleteCancelButton:"Cancelar",deleteConfirmationButton:"Eliminar",cardVerification:"Verificación de tarjeta",fieldEmptyForCvv:"Escribe el código CVV.",fieldEmptyForExpirationDate:"Escribe la fecha de vencimiento.",fieldEmptyForCardholderName:"Escribe el nombre de un titular de la tarjeta.",fieldTooLongForCardholderName:"El nombre del titular de la tarjeta debe tener menos de 256 caracteres.",fieldEmptyForNumber:"Escribe un número.",fieldEmptyForPostalCode:"Escribe el código postal.",fieldInvalidForCvv:"Este código de seguridad no es válido.",fieldInvalidForExpirationDate:"Esta fecha de vencimiento no es válida.",fieldInvalidForNumber:"Este número de tarjeta no es válido.",fieldInvalidForPostalCode:"Este código postal no es válido.",genericError:"Hemos tenido algún problema.",hostedFieldsTokenizationFailOnDuplicateError:"Esta tarjeta de crédito ya existe como forma de pago guardada.",hostedFieldsFailedTokenizationError:"Comprueba la información e inténtalo de nuevo.",hostedFieldsFieldsInvalidError:"Comprueba la información e inténtalo de nuevo.",hostedFieldsTokenizationNetworkErrorError:"Error de red. Inténtalo de nuevo.",hostedFieldsTokenizationCvvVerificationFailedError:"Error de verificación de la tarjeta de crédito. Comprueba la información e inténtalo de nuevo.",paypalAccountTokenizationFailedError:"Se ha producido un error al vincular la cuenta PayPal. Inténtalo de nuevo.",paypalFlowFailedError:"Se ha producido un error al conectarse a PayPal. Inténtalo de nuevo.",paypalTokenizationRequestActiveError:"Ya hay una autorización de pago de PayPal en curso.",venmoCanceledError:"Ha habido un problema. Asegúrate de que tienes la versión más reciente de la aplicación de Venmo instalada en tu dispositivo y de que tu navegador es compatible con cambiar a Venmo.",vaultManagerPaymentMethodDeletionError:"No se ha podido eliminar la forma de pago. Inténtalo de nuevo.",venmoAppFailedError:"No se ha encontrado la aplicación de Venmo en tu dispositivo.",unsupportedCardTypeError:"No se admite este tipo de tarjeta. Prueba con otra tarjeta.",applePayTokenizationError:"Se ha producido un error de red al procesar el pago con Apple Pay. Inténtalo de nuevo.",applePayActiveCardError:"Añade una tarjeta admitida a tu Wallet de Apple Pay.",cardholderNameLabel:"Nombre del titular de la tarjeta",cardNumberLabel:"Número de tarjeta",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 dígitos)",cvvFourDigitLabelSubheading:"(4 dígitos)",cardholderNamePlaceholder:"Nombre del titular de la tarjeta",expirationDateLabel:"Fecha de vencimiento",expirationDateLabelSubheading:"(MM/AA)",expirationDatePlaceholder:"MM/AA",postalCodeLabel:"Código postal",payWithCard:"Pagar con tarjeta",endingIn:"Terminada en {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Tarjeta",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],155:[function(e,t,i){"use strict";t.exports={payingWith:"Payer avec {{paymentSource}}",chooseAnotherWayToPay:"Choisir un autre mode de paiement",chooseAWayToPay:"Choisir le mode de paiement",otherWaysToPay:"Autres modes de paiement",edit:"Modifier",doneEditing:"Terminé",editPaymentMethods:"Modifier les modes de paiement",CreditCardDeleteConfirmationMessage:"Supprimer la carte {{secondaryIdentifier}} se terminant par {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Supprimer le compte PayPal {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Souhaitez-vous vraiment supprimer le compte Venmo avec le nom d’utilisateur {{identifier}}?",genericDeleteConfirmationMessage:"Voulez-vous vraiment supprimer ce mode de paiement?",deleteCancelButton:"Annuler",deleteConfirmationButton:"Supprimer",cardVerification:"Vérification de la carte",fieldEmptyForCvv:"Veuillez saisir un cryptogramme visuel.",fieldEmptyForExpirationDate:"Veuillez saisir une date d'expiration.",fieldEmptyForCardholderName:"Veuillez saisir un nom de titulaire de la carte.",fieldTooLongForCardholderName:"Le nom du titulaire de la carte doit contenir moins de 256 caractères.",fieldEmptyForNumber:"Veuillez saisir un numéro.",fieldEmptyForPostalCode:"Veuillez saisir un code postal.",fieldInvalidForCvv:"Ce cryptogramme visuel n'est pas valide.",fieldInvalidForExpirationDate:"Cette date d'expiration n'est pas valide.",fieldInvalidForNumber:"Ce numéro de carte n'est pas valide.",fieldInvalidForPostalCode:"Ce code postal n'est pas valide.",genericError:"Une erreur s'est produite de notre côté.",hostedFieldsTokenizationFailOnDuplicateError:"Cette carte de crédit existe déjà comme mode de paiement enregistré.",hostedFieldsFailedTokenizationError:"Vérifiez vos informations, puis réessayez.",hostedFieldsFieldsInvalidError:"Vérifiez vos informations, puis réessayez.",hostedFieldsTokenizationNetworkErrorError:"Erreur réseau. Veuillez réessayer.",hostedFieldsTokenizationCvvVerificationFailedError:"La vérification de la carte de crédit a échoué. Vérifiez vos informations, puis réessayez.",paypalAccountTokenizationFailedError:"Une erreur s'est produite lors de l'enregistrement du compte PayPal. Veuillez réessayer.",paypalFlowFailedError:"Une erreur s'est produite au cours de la connexion à PayPal. Veuillez réessayer.",paypalTokenizationRequestActiveError:"L'autorisation de paiement PayPal est déjà en cours.",venmoCanceledError:"Une erreur s'est produite. Assurez-vous que la version la plus récente de l'application Venmo est installée sur votre appareil et que votre navigateur prend Venmo en charge.",vaultManagerPaymentMethodDeletionError:"Impossible de supprimer le mode de paiement, essayez de nouveau.",venmoAppFailedError:"L'application Venmo est introuvable sur votre appareil.",unsupportedCardTypeError:"Ce type de carte n'est pas pris en charge. Veuillez essayer une autre carte.",applePayTokenizationError:"Une erreur de réseau s'est produite lors du traitement du paiement avec Apple Pay. Veuillez réessayer.",applePayActiveCardError:"Ajoutez une carte prise en charge à Apple Pay.",cardholderNameLabel:"Nom du titulaire de la carte",cardNumberLabel:"Numéro de carte",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 chiffres)",cvvFourDigitLabelSubheading:"(4 chiffres)",cardholderNamePlaceholder:"Nom du titulaire de la carte",expirationDateLabel:"Date d'expiration",expirationDateLabelSubheading:"(MM/AA)",expirationDatePlaceholder:"MM/AA",postalCodeLabel:"Code postal",payWithCard:"Payer par carte",endingIn:"Se terminant par {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Carte",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],156:[function(e,t,i){"use strict";t.exports={payingWith:"Payer avec {{paymentSource}}",chooseAnotherWayToPay:"Choisissez une autre façon de payer.",chooseAWayToPay:"Choisissez comment payer.",otherWaysToPay:"Autres façons de payer",edit:"Modifier",doneEditing:"Terminé",editPaymentMethods:"Modifier les sources d'approvisionnement",CreditCardDeleteConfirmationMessage:"Supprimer la carte {{secondaryIdentifier}} se terminant par {{identifier}} ?",PayPalAccountDeleteConfirmationMessage:"Supprimer le compte PayPal {{identifier}} ?",VenmoAccountDeleteConfirmationMessage:"Êtes-vous sûr de vouloir supprimer le compte Venmo avec le nom d'utilisateur {{identifier}} ?",genericDeleteConfirmationMessage:"Êtes-vous sûr de vouloir supprimer cette source d'approvisionnement ?",deleteCancelButton:"Annuler",deleteConfirmationButton:"Supprimer",cardVerification:"Vérification de la carte",fieldEmptyForCvv:"Entrez un cryptogramme visuel.",fieldEmptyForExpirationDate:"Entrez une date d'expiration.",fieldEmptyForCardholderName:"Entrez un nom du titulaire de la carte.",fieldTooLongForCardholderName:"Le nom du titulaire de la carte doit contenir moins de 256 caractères.",fieldEmptyForNumber:"Entrez un numéro.",fieldEmptyForPostalCode:"Entrez un code postal.",fieldInvalidForCvv:"Ce cryptogramme visuel n'est pas valide.",fieldInvalidForExpirationDate:"Cette date d'expiration n'est pas valide.",fieldInvalidForNumber:"Ce numéro de carte n'est pas valide.",fieldInvalidForPostalCode:"Ce code postal n'est pas valide.",genericError:"Une erreur est survenue.",hostedFieldsTokenizationFailOnDuplicateError:"Cette carte bancaire existe déjà comme mode de paiement enregistré.",hostedFieldsFailedTokenizationError:"Vérifiez vos informations et réessayez.",hostedFieldsFieldsInvalidError:"Vérifiez vos informations et réessayez.",hostedFieldsTokenizationNetworkErrorError:"Erreur réseau. Réessayez.",hostedFieldsTokenizationCvvVerificationFailedError:"Échec de vérification de la carte bancaire. Vérifiez vos informations et réessayez.",paypalAccountTokenizationFailedError:"Une erreur est survenue lors de l'ajout du compte PayPal. Réessayez.",paypalFlowFailedError:"Une erreur est survenue lors de la connexion à PayPal. Réessayez.",paypalTokenizationRequestActiveError:"L'autorisation de paiement PayPal est déjà en cours.",venmoCanceledError:"Une erreur est survenue. Vérifiez que vous disposez de la dernière version de l'application Venmo sur votre appareil et que votre navigateur prend en charge la redirection vers Venmo.",vaultManagerPaymentMethodDeletionError:"Impossible de supprimer la source d'approvisionnement. Réessayez.",venmoAppFailedError:"L'application Venmo est introuvable sur votre appareil.",unsupportedCardTypeError:"Ce type de carte n'est pas pris en charge. Essayez une autre carte.",applePayTokenizationError:"Une erreur réseau s'est produite lors du traitement du paiement Apple Pay. Réessayez.",applePayActiveCardError:"Enregistrez une carte prise en charge sur Apple Pay.",cardholderNameLabel:"Nom du titulaire de la carte",cardNumberLabel:"Nº de carte",cvvLabel:"Cryptogramme visuel",cvvThreeDigitLabelSubheading:"(3 chiffres)",cvvFourDigitLabelSubheading:"(4 chiffres)",cardholderNamePlaceholder:"Nom du titulaire de la carte",expirationDateLabel:"Date d'expiration",expirationDateLabelSubheading:"(MM/AA)",expirationDatePlaceholder:"MM/AA",postalCodeLabel:"Code postal",payWithCard:"Payer par carte",endingIn:"Se terminant par {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Carte",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],157:[function(e,t,i){"use strict";t.exports={payingWith:"Membayar dengan {{paymentSource}}",chooseAnotherWayToPay:"Pilih metode pembayaran lain",chooseAWayToPay:"Pilih metode pembayaran",otherWaysToPay:"Metode pembayaran lain",edit:"Edit",doneEditing:"Selesai",editPaymentMethods:"Edit metode pembayaran",CreditCardDeleteConfirmationMessage:"Hapus kartu {{secondaryIdentifier}} yang berakhiran {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Hapus {{identifier}} rekening PayPal?",VenmoAccountDeleteConfirmationMessage:"Apakah Anda yakin akan menghapus rekening Venmo dengan nama pengguna {{identifier}}?",genericDeleteConfirmationMessage:"Apakah Anda yakin akan menghapus metode pembayaran ini?",deleteCancelButton:"Batalkan",deleteConfirmationButton:"Hapus",cardVerification:"Verifikasi Kartu",fieldEmptyForCvv:"Masukkan CVV.",fieldEmptyForExpirationDate:"Masukkan tanggal akhir berlaku.",fieldEmptyForCardholderName:"Masukkan nama pemegang kartu.",fieldTooLongForCardholderName:"Nama pemegang kartu harus kurang dari 256 karakter.",fieldEmptyForNumber:"Masukkan nomor.",fieldEmptyForPostalCode:"Masukkan kode pos.",fieldInvalidForCvv:"Kode keamanan ini tidak valid.",fieldInvalidForExpirationDate:"Tanggal akhir berlaku ini tidak valid.",fieldInvalidForNumber:"Nomor kartu ini tidak valid.",fieldInvalidForPostalCode:"Kode pos ini tidak valid.",genericError:"Terjadi kesalahan pada sistem kami.",hostedFieldsTokenizationFailOnDuplicateError:"Kartu kredit ini sudah dimasukkan sebagai metode pembayaran tersimpan.",hostedFieldsFailedTokenizationError:"Periksa informasi Anda dan coba lagi.",hostedFieldsFieldsInvalidError:"Periksa informasi Anda dan coba lagi.",hostedFieldsTokenizationNetworkErrorError:"Masalah jaringan. Coba lagi.",hostedFieldsTokenizationCvvVerificationFailedError:"Verifikasi kartu kredit gagal. Periksa informasi Anda dan coba lagi.",paypalAccountTokenizationFailedError:"Terjadi kesalahan saat menambahkan rekening PayPal. Coba lagi.",paypalFlowFailedError:"Terjadi kesalahan saat menyambung ke PayPal. Coba lagi.",paypalTokenizationRequestActiveError:"Otorisasi pembayaran PayPal sedang diproses.",venmoCanceledError:"Terdapat kesalahan. Pastikan Anda telah menginstal aplikasi Venmo versi terbaru pada perangkat dan peramban Anda mendukung untuk beralih ke Venmo.",vaultManagerPaymentMethodDeletionError:"Tidak dapat menghapus metode pembayaran, coba lagi.",venmoAppFailedError:"Aplikasi Venmo tidak dapat ditemukan pada perangkat Anda.",unsupportedCardTypeError:"Jenis kartu ini tidak didukung. Coba kartu lainnya.",applePayTokenizationError:"Terjadi kesalahan jaringan sewaktu memproses pembayaran melalui Apple Pay. Coba lagi.",applePayActiveCardError:"Tambahkan kartu yang didukung ke wallet Apple Pay.",cardholderNameLabel:"Nama Pemegang Kartu",cardNumberLabel:"Nomor Kartu",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 angka)",cvvFourDigitLabelSubheading:"(4 angka)",cardholderNamePlaceholder:"Nama Pemegang Kartu",expirationDateLabel:"Tanggal Kedaluwarsa",expirationDateLabelSubheading:"(BB/TT)",expirationDatePlaceholder:"BB/TT",postalCodeLabel:"Kode Pos",payWithCard:"Bayar dengan kartu",endingIn:"Berakhiran {{lastTwoCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Kartu",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],158:[function(e,t,i){"use strict";var r=e("../lib/assign").assign,n={da_DK:e("./da_DK"),de_DE:e("./de_DE"),en_US:e("./en_US"),en_AU:e("./en_AU"),en_GB:e("./en_GB"),es_ES:e("./es_ES"),fr_CA:e("./fr_CA"),fr_FR:e("./fr_FR"),id_ID:e("./id_ID"),it_IT:e("./it_IT"),ja_JP:e("./ja_JP"),ko_KR:e("./ko_KR"),nl_NL:e("./nl_NL"),no_NO:e("./no_NO"),pl_PL:e("./pl_PL"),pt_BR:e("./pt_BR"),pt_PT:e("./pt_PT"),ru_RU:e("./ru_RU"),sv_SE:e("./sv_SE"),th_TH:e("./th_TH"),zh_CN:e("./zh_CN"),zh_HK:e("./zh_HK"),zh_TW:e("./zh_TW")},a={da:n.da_DK,de:n.de_DE,en:n.en_US,es:n.es_ES,fr:n.fr_FR,id:n.id_ID,it:n.it_IT,ja:n.ja_JP,ko:n.ko_KR,nl:n.nl_NL,no:n.no_NO,pl:n.pl_PL,pt:n.pt_PT,ru:n.ru_RU,sv:n.sv_SE,th:n.th_TH,zh:n.zh_CN};t.exports={twoCharacterLocaleAliases:a,fiveCharacterLocales:n,translations:r({},a,n)}},{"../lib/assign":131,"./da_DK":149,"./de_DE":150,"./en_AU":151,"./en_GB":152,"./en_US":153,"./es_ES":154,"./fr_CA":155,"./fr_FR":156,"./id_ID":157,"./it_IT":159,"./ja_JP":160,"./ko_KR":161,"./nl_NL":162,"./no_NO":163,"./pl_PL":164,"./pt_BR":165,"./pt_PT":166,"./ru_RU":167,"./sv_SE":168,"./th_TH":169,"./zh_CN":170,"./zh_HK":171,"./zh_TW":172}],159:[function(e,t,i){"use strict";t.exports={payingWith:"Pagamento con {{paymentSource}}",chooseAnotherWayToPay:"Scegli di pagare in un altro modo",chooseAWayToPay:"Scegli come pagare",otherWaysToPay:"Altri modi di pagare",edit:"Modifica",doneEditing:"Fine",editPaymentMethods:"Modifica i metodi di pagamento",CreditCardDeleteConfirmationMessage:"Eliminare la carta {{secondaryIdentifier}} le cui ultime cifre sono {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Eliminare il conto PayPal {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Vuoi eliminare il conto Venmo con nome utente {{identifier}}?",genericDeleteConfirmationMessage:"Vuoi eliminare questo metodo di pagamento?",deleteCancelButton:"Annulla",deleteConfirmationButton:"Rimuovi",cardVerification:"Codice di sicurezza",fieldEmptyForCvv:"Immetti il codice di sicurezza (CVV).",fieldEmptyForExpirationDate:"Immetti la data di scadenza.",fieldEmptyForCardholderName:"Immetti il nome del titolare della carta.",fieldTooLongForCardholderName:"Il nome del titolare della carta deve avere meno di 256 caratteri.",fieldEmptyForNumber:"Immetti il numero di carta.",fieldEmptyForPostalCode:"Immetti il CAP.",fieldInvalidForCvv:"Il codice di sicurezza non è valido.",fieldInvalidForExpirationDate:"La data di scadenza non è valida.",fieldInvalidForNumber:"Il numero di carta non è valido.",fieldInvalidForPostalCode:"Il CAP non è valido.",genericError:"Si è verificato un errore nei nostri sistemi.",hostedFieldsTokenizationFailOnDuplicateError:"Questa carta di credito è già registrata come metodo di pagamento salvato.",hostedFieldsFailedTokenizationError:"Controlla e riprova.",hostedFieldsFieldsInvalidError:"Controlla e riprova.",hostedFieldsTokenizationNetworkErrorError:"Errore di rete. Riprova.",hostedFieldsTokenizationCvvVerificationFailedError:"La verifica della carta di credito non è andata a buon fine. Controlla i dati e riprova.",paypalAccountTokenizationFailedError:"Si è verificato un errore nel collegamento del conto PayPal. Riprova.",paypalFlowFailedError:"Si è verificato un errore di connessione a PayPal. Riprova.",paypalTokenizationRequestActiveError:"L'autorizzazione di pagamento PayPal è già in corso.",venmoCanceledError:"Si è verificato un errore. Assicurati di avere la versione più recente dell'app Venmo installata sul tuo dispositivo e che il browser supporti l'uso di Venmo.",vaultManagerPaymentMethodDeletionError:"Impossibile eliminare il metodo di pagamento; riprova.",venmoAppFailedError:"Impossibile trovare l'app Venmo sul dispositivo in uso.",unsupportedCardTypeError:"Questo tipo di carta non è supportato. Prova con un'altra carta.",applePayTokenizationError:"Si è verificato un errore di rete durante l'elaborazione del pagamento con Apple Pay. Riprova.",applePayActiveCardError:"Collega una carta supportata al tuo Apple Pay Wallet.",cardholderNameLabel:"Titolare della carta",cardNumberLabel:"Numero di carta",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 cifre)",cvvFourDigitLabelSubheading:"(4 cifre)",cardholderNamePlaceholder:"Titolare della carta",expirationDateLabel:"Data di scadenza",expirationDateLabelSubheading:"(MM/AA)",expirationDatePlaceholder:"MM/AA",postalCodeLabel:"CAP",payWithCard:"Paga con una carta",endingIn:"Le cui ultime cifre sono {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Carta",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],160:[function(e,t,i){"use strict";t.exports={payingWith:"{{paymentSource}}で支払う",chooseAnotherWayToPay:"別の支払方法を選択する",chooseAWayToPay:"支払方法を選択する",otherWaysToPay:"その他の支払方法",edit:"編集",doneEditing:"完了",editPaymentMethods:"支払方法の編集",CreditCardDeleteConfirmationMessage:"末尾が{{identifier}}の{{secondaryIdentifier}}カードを削除しますか?",PayPalAccountDeleteConfirmationMessage:"PayPalアカウント{{identifier}}を削除しますか?",VenmoAccountDeleteConfirmationMessage:"ユーザー名{{identifier}}のVenmoアカウントを削除してよろしいですか?",genericDeleteConfirmationMessage:"この支払い方法を削除してよろしいですか?",deleteCancelButton:"キャンセル",deleteConfirmationButton:"削除",cardVerification:"カード確認",fieldEmptyForCvv:"セキュリティコードを入力してください。",fieldEmptyForExpirationDate:"有効期限を入力してください。",fieldEmptyForCardholderName:"カード保有者の名前を入力してください。",fieldTooLongForCardholderName:"カード保有者の名前は256文字未満にしてください。",fieldEmptyForNumber:"番号を入力してください。",fieldEmptyForPostalCode:"郵便番号を入力してください。",fieldInvalidForCvv:"このセキュリティコードは無効です。",fieldInvalidForExpirationDate:"この有効期限は無効です。",fieldInvalidForNumber:"このカード番号は無効です。",fieldInvalidForPostalCode:"この郵便番号は無効です。",genericError:"弊社側で問題が発生しました。",hostedFieldsTokenizationFailOnDuplicateError:"このクレジットカードは、保存済みの支払方法としてすでに登録されています。",hostedFieldsFailedTokenizationError:"情報を確認してもう一度お試しください。",hostedFieldsFieldsInvalidError:"情報を確認してもう一度お試しください。",hostedFieldsTokenizationNetworkErrorError:"ネットワークエラーです。もう一度お試しください。",hostedFieldsTokenizationCvvVerificationFailedError:"クレジットカードの認証に失敗しました。情報を確認してもう一度お試しください。",paypalAccountTokenizationFailedError:"PayPalアカウントの追加で問題が発生しました。もう一度お試しください。",paypalFlowFailedError:"PayPalへの接続に問題が発生しました。もう一度お試しください。",paypalTokenizationRequestActiveError:"PayPal支払いの承認はすでに処理中です。",venmoCanceledError:"問題が発生しました。お客さまの端末にインストールされているVenmoアプリが最新のバージョンであること、お使いのブラウザがVenmoへの切り替えをサポートしていることを確認してください。",vaultManagerPaymentMethodDeletionError:"支払方法を削除できません。もう一度お試しください。",venmoAppFailedError:"お客さまの端末でVenmoアプリが見つかりませんでした。",unsupportedCardTypeError:"このカードタイプはサポートされていません。別のカードをご使用ください。",applePayTokenizationError:"Apple Payの支払いを処理する際にネットワークエラーが発生しました。もう一度お試しください。",applePayActiveCardError:"Apple Payウォレットに対応しているカードを追加してください。",cardholderNameLabel:"カード保有者の名前",cardNumberLabel:"カード番号",cvvLabel:"セキュリティコード",cvvThreeDigitLabelSubheading:"(3桁)",cvvFourDigitLabelSubheading:"(4桁)",cardholderNamePlaceholder:"カード保有者の名前",expirationDateLabel:"有効期限",expirationDateLabelSubheading:"(MM/YY)",expirationDatePlaceholder:"MM/YY",postalCodeLabel:"郵便番号",payWithCard:"カードで支払う",endingIn:"末尾が{{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"カード",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"銀聯(UnionPay)"}},{}],161:[function(e,t,i){"use strict";t.exports={payingWith:"{{paymentSource}}(으)로 결제",chooseAnotherWayToPay:"다른 결제수단 선택",chooseAWayToPay:"결제수단 선택",otherWaysToPay:"다른 방법으로 결제",edit:"편집",doneEditing:"완료",editPaymentMethods:"결제수단 편집",CreditCardDeleteConfirmationMessage:"끝번호가 {{identifier}}인 {{secondaryIdentifier}} 카드를 삭제하시겠어요?",PayPalAccountDeleteConfirmationMessage:"PayPal 계정 {{identifier}}을(를) 삭제하시겠어요?",VenmoAccountDeleteConfirmationMessage:"사용자 이름이 {{identifier}}인 Venmo 계정을 삭제하시겠어요?",genericDeleteConfirmationMessage:"이 결제수단을 삭제하시겠어요?",deleteCancelButton:"취소",deleteConfirmationButton:"삭제",cardVerification:"카드 인증",fieldEmptyForCvv:"CVV를 입력하세요.",fieldEmptyForExpirationDate:"만료일을 입력하세요.",fieldEmptyForCardholderName:"카드 소유자 이름을 입력하세요.",fieldTooLongForCardholderName:"카드 소유자 이름은 256자 미만이어야 합니다.",fieldEmptyForNumber:"번호를 입력하세요.",fieldEmptyForPostalCode:"우편번호를 입력하세요.",fieldInvalidForCvv:"이 보안 코드가 올바르지 않습니다.",fieldInvalidForExpirationDate:"이 만료일이 올바르지 않습니다.",fieldInvalidForNumber:"이 카드 번호가 올바르지 않습니다.",fieldInvalidForPostalCode:"이 우편번호가 올바르지 않습니다.",genericError:"저희 쪽에 문제가 발생했습니다.",hostedFieldsTokenizationFailOnDuplicateError:"저장된 결제수단에 이미 이 신용카드가 존재합니다.",hostedFieldsFailedTokenizationError:"정보를 확인하고 다시 시도해 주세요.",hostedFieldsFieldsInvalidError:"정보를 확인하고 다시 시도해 주세요.",hostedFieldsTokenizationNetworkErrorError:"네트워크 오류가 발생했습니다. 다시 시도해 주세요.",hostedFieldsTokenizationCvvVerificationFailedError:"신용카드 인증에 실패했습니다. 정보를 확인하고 다시 시도해 주세요.",paypalAccountTokenizationFailedError:"PayPal 계정을 추가하는 동안 문제가 발생했습니다. 다시 시도해 주세요.",paypalFlowFailedError:"PayPal 계정을 연결하는 동안 문제가 발생했습니다. 다시 시도해 주세요.",paypalTokenizationRequestActiveError:"PayPal 결제 승인이 이미 진행 중입니다.",venmoCanceledError:"오류가 발생했습니다. 기기에 최신 버전의 Venmo 앱이 설치되어 있으며 브라우저가 Venmo로 전환 기능을 지원하는지 확인하세요.",vaultManagerPaymentMethodDeletionError:"결제수단을 삭제할 수 없습니다. 다시 시도해 주세요.",venmoAppFailedError:"기기에서 Venmo 앱을 찾을 수 없습니다.",unsupportedCardTypeError:"이 카드 형식은 지원되지 않습니다. 다른 카드로 시도해 주세요.",applePayTokenizationError:"Apple Pay 결제를 처리하는 동안 네트워크 오류가 발생했습니다. 다시 시도해 주세요.",applePayActiveCardError:"Apple Pay 전자지갑에 지원되는 카드를 추가하세요.",cardholderNameLabel:"카드 소유자 이름",cardNumberLabel:"카드 번호",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3자리)",cvvFourDigitLabelSubheading:"(4자리)",cardholderNamePlaceholder:"카드 소유자 이름",expirationDateLabel:"만료일",expirationDateLabelSubheading:"(MM/YY)",expirationDatePlaceholder:"MM/YY",postalCodeLabel:"우편번호",payWithCard:"카드로 결제",endingIn:"끝번호: {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"카드",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],162:[function(e,t,i){"use strict";t.exports={payingWith:"Betalen met {{paymentSource}}",chooseAnotherWayToPay:"Kies een andere betaalmethode",chooseAWayToPay:"Kies een betaalwijze",otherWaysToPay:"Andere manieren om te betalen",edit:"Bewerk",doneEditing:"Gereed",editPaymentMethods:"Betaalmethoden aanpassen",CreditCardDeleteConfirmationMessage:"{{secondaryIdentifier}}-kaart eindigend op {{identifier}} verwijderen?",PayPalAccountDeleteConfirmationMessage:"PayPal-rekening {{identifier}} verwijderen?",VenmoAccountDeleteConfirmationMessage:"Weet u zeker dat u Venmo-rekening met gebruikersnaam {{identifier}} wilt verwijderen?",genericDeleteConfirmationMessage:"Weet u zeker dat u deze betaalmethode wilt verwijderen?",deleteCancelButton:"Annuleren",deleteConfirmationButton:"Verwijderen",cardVerification:"Kaartcontrole",fieldEmptyForCvv:"Vul een CSC in.",fieldEmptyForExpirationDate:"Vul een vervaldatum in.",fieldEmptyForCardholderName:"Vul een naam voor de kaarthouder in.",fieldTooLongForCardholderName:"De naam van de kaarthouder moet korter zijn dan 256 tekens.",fieldEmptyForNumber:"Vul een nummer in.",fieldEmptyForPostalCode:"Vul een postcode in.",fieldInvalidForCvv:"Deze CSC is ongeldig.",fieldInvalidForExpirationDate:"Deze vervaldatum is ongeldig.",fieldInvalidForNumber:"Dit creditcardnummer is ongeldig.",fieldInvalidForPostalCode:"Deze postcode is ongeldig.",genericError:"Er is iets fout gegaan.",hostedFieldsTokenizationFailOnDuplicateError:"Deze creditcard staat al geregistreerd als een opgeslagen betaalmethode.",hostedFieldsFailedTokenizationError:"Controleer uw gegevens en probeer het opnieuw.",hostedFieldsFieldsInvalidError:"Controleer uw gegevens en probeer het opnieuw.",hostedFieldsTokenizationNetworkErrorError:"Netwerkfout. Probeer het opnieuw.",hostedFieldsTokenizationCvvVerificationFailedError:"De controle van de creditcard is mislukt. Controleer uw gegevens en probeer het opnieuw.",paypalAccountTokenizationFailedError:"Er is iets misgegaan bij het toevoegen van de PayPal-rekening. Probeer het opnieuw.",paypalFlowFailedError:"Er is iets misgegaan bij de verbinding met PayPal. Probeer het opnieuw.",paypalTokenizationRequestActiveError:"De autorisatie van de PayPal-betaling is al in behandeling.",venmoCanceledError:"Er ging iets fout. Controleer of de meest recente versie van de Venmo-app op je apparaat is geïnstalleerd en dat je browser overschakelen naar Venmo ondersteunt.",vaultManagerPaymentMethodDeletionError:"Kan de betaalmethode niet verwijderen, probeer het opnieuw.",venmoAppFailedError:"De Venmo-app is niet aangetroffen op je apparaat.",unsupportedCardTypeError:"Dit type creditcard wordt niet ondersteund. Gebruik een andere creditcard.",applePayTokenizationError:"Er is een netwerkfout opgetreden bij het verwerken van de Apple Pay-betaling. Probeer het opnieuw.",applePayActiveCardError:"Voeg een ondersteunde creditcard toe aan je Apple Pay-wallet.",cardholderNameLabel:"Naam kaarthouder",cardNumberLabel:"Creditcardnummer",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 cijfers)",cvvFourDigitLabelSubheading:"(4 cijfers)",cardholderNamePlaceholder:"Naam kaarthouder",expirationDateLabel:"VervaldatumB",expirationDateLabelSubheading:"(MM/JJ)",expirationDatePlaceholder:"MM/JJ",postalCodeLabel:"Postcode",payWithCard:"Betalen met creditcard",endingIn:"Eindigend op {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Creditcard",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],163:[function(e,t,i){"use strict";t.exports={payingWith:"Betaling med {{paymentSource}}",chooseAnotherWayToPay:"Velg en annen måte å betale på",chooseAWayToPay:"Velg betalingsmåte",otherWaysToPay:"Andre måter å betale på",edit:"Rediger",doneEditing:"Fullført",editPaymentMethods:"Endre betalingsmetodene dine",CreditCardDeleteConfirmationMessage:"Vil du slette {{secondaryIdentifier}}-kortet som slutter på {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Vil du slette PayPal-kontoen {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Er du sikker på at du vil slette Venmo-kontoen med brukernavnet {{identifier}}?",genericDeleteConfirmationMessage:"Er du sikker på at du vil slette denne betalingsmetoden?",deleteCancelButton:"Avbryt",deleteConfirmationButton:"Slett",cardVerification:"Kortbekreftelse",fieldEmptyForCvv:"Oppgi en kortsikkerhetskode (CVV).",fieldEmptyForExpirationDate:"Oppgi en utløpsdato.",fieldEmptyForCardholderName:"Oppgi et navn for kortinnehaveren.",fieldTooLongForCardholderName:"Makslengden for kortinnehaverens navn er 256 tegn.",fieldEmptyForNumber:"Oppgi et nummer.",fieldEmptyForPostalCode:"Oppgi et postnummer.",fieldInvalidForCvv:"Denne sikkerhetskoden er ikke gyldig.",fieldInvalidForExpirationDate:"Denne utløpsdatoen er ikke gyldig.",fieldInvalidForNumber:"Dette kortnummeret er ikke gyldig.",fieldInvalidForPostalCode:"Dette postnummeret er ikke gyldig.",genericError:"Noe gikk galt hos oss.",hostedFieldsTokenizationFailOnDuplicateError:"Dette betalingskortet eksisterer allerede som en lagret betalingsmetode.",hostedFieldsFailedTokenizationError:"Kontroller informasjonen og prøv på nytt.",hostedFieldsFieldsInvalidError:"Kontroller informasjonen og prøv på nytt.",hostedFieldsTokenizationNetworkErrorError:"Nettverksfeil. Prøv på nytt.",hostedFieldsTokenizationCvvVerificationFailedError:"Bekreftelsen av betalingskortet mislyktes. Kontroller informasjonen og prøv på nytt.",paypalAccountTokenizationFailedError:"Noe gikk galt da PayPal-kontoen ble lagt til. Prøv på nytt.",paypalFlowFailedError:"Det oppsto et problem med tilkoblingen til PayPal. Prøv på nytt.",paypalTokenizationRequestActiveError:"Godkjenning av PayPal-betalingen pågår allerede",venmoCanceledError:"Noe gikk galt. Kontroller at du har installert den nyeste versjonen av Venmo-appen på enheten og at nettleseren din støtter bytte til Venmo.",vaultManagerPaymentMethodDeletionError:"Kunne ikke slette betalingsmetoden. Prøv på nytt.",venmoAppFailedError:"Finner ikke Venmo-appen på enheten.",unsupportedCardTypeError:"Denne korttypen støttes ikke. Prøv med et annet kort.",applePayTokenizationError:"Det oppsto en nettverksfeil under behandlingen av Apple Pay-betalingen. Prøv på nytt.",applePayActiveCardError:"Legg til et kort som støttes i Apple Pay-lommeboken din.",cardholderNameLabel:"Kortinnehaverens navn",cardNumberLabel:"Kortnummer",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 siffer)",cvvFourDigitLabelSubheading:"(4 siffer)",cardholderNamePlaceholder:"Kortinnehaverens navn",expirationDateLabel:"Utløpsdato",expirationDateLabelSubheading:"(MM/ÅÅ)",expirationDatePlaceholder:"MM/ÅÅ",postalCodeLabel:"Postnummer",payWithCard:"Betal med kort",endingIn:"Slutter på {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Kort",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],164:[function(e,t,i){"use strict";t.exports={payingWith:"Źródło finansowania płatności: {{paymentSource}}",chooseAnotherWayToPay:"Wybierz inne źródło finansowania płatności",chooseAWayToPay:"Wybierz źródło finansowania płatności",otherWaysToPay:"Inne źródła finansowania płatności",edit:"Edytuj",doneEditing:"Gotowe",editPaymentMethods:"Edytuj źródła finansowania płatności",CreditCardDeleteConfirmationMessage:"Usunąć kartę {{secondaryIdentifier}} o numerze zakończonym cyframi {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Usunąć konto PayPal {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Czy na pewno chcesz usunąć konto Venmo z nazwą użytkownika {{identifier}}?",genericDeleteConfirmationMessage:"Czy na pewno chcesz usunąć to źródło finansowania płatności?",deleteCancelButton:"Anuluj",deleteConfirmationButton:"Usuń",cardVerification:"Weryfikacja karty",fieldEmptyForCvv:"Podaj kod bezpieczeństwa.",fieldEmptyForExpirationDate:"Podaj datę ważności.",fieldEmptyForCardholderName:"Podaj imię i nazwisko posiadacza karty.",fieldTooLongForCardholderName:"Imię i nazwisko posiadacza karty musi mieć mniej niż 256 znaków.",fieldEmptyForNumber:"Podaj numer.",fieldEmptyForPostalCode:"Podaj kod pocztowy.",fieldInvalidForCvv:"Podany kod bezpieczeństwa jest nieprawidłowy.",fieldInvalidForExpirationDate:"Podana data ważności jest nieprawidłowa.",fieldInvalidForNumber:"Podany numer karty jest nieprawidłowy.",fieldInvalidForPostalCode:"Podany kod pocztowy jest nieprawidłowy.",genericError:"Wystąpił błąd po naszej stronie.",hostedFieldsTokenizationFailOnDuplicateError:"Ta karta kredytowa jest już zapisana jako źródło finansowania płatności.",hostedFieldsFailedTokenizationError:"Sprawdź swoje informacje i spróbuj ponownie.",hostedFieldsFieldsInvalidError:"Sprawdź swoje informacje i spróbuj ponownie.",hostedFieldsTokenizationNetworkErrorError:"Błąd sieci. Spróbuj ponownie.",hostedFieldsTokenizationCvvVerificationFailedError:"Weryfikacja karty kredytowej nie powiodła się. Sprawdź swoje informacje i spróbuj ponownie.",paypalAccountTokenizationFailedError:"Coś poszło nie tak podczas dodawania konta PayPal. Spróbuj ponownie.",paypalFlowFailedError:"Coś poszło nie tak podczas łączenia z systemem PayPal. Spróbuj ponownie.",paypalTokenizationRequestActiveError:"Autoryzacja płatności PayPal jest już w trakcie realizacji.",venmoCanceledError:"Wystąpił problem. Upewnij się, czy na swoim urządzeniu masz zainstalowaną najnowszą wersję aplikacji Venmo i Twoja przeglądarka ją obsługuje.",vaultManagerPaymentMethodDeletionError:"Nie można usunąć źródła finansowania płatności. Spróbuj ponownie.",venmoAppFailedError:"Nie można odnaleźć aplikacji Venmo na urządzeniu.",unsupportedCardTypeError:"Ten typ karty nie jest obsługiwany. Spróbuj użyć innej karty.",applePayTokenizationError:"Wystąpił błąd sieci podczas przetwarzania płatności Apple Pay. Spróbuj ponownie.",applePayActiveCardError:"Dodaj obsługiwaną kartę do portfela Apple Pay.",cardholderNameLabel:"Imię i nazwisko posiadacza karty",cardNumberLabel:"Numer karty",cvvLabel:"Kod CVC",cvvThreeDigitLabelSubheading:"(3 cyfry)",cvvFourDigitLabelSubheading:"(4 cyfry)",cardholderNamePlaceholder:"Imię i nazwisko posiadacza karty",expirationDateLabel:"Data ważności",expirationDateLabelSubheading:"(MM/RR)",expirationDatePlaceholder:"MM/RR",postalCodeLabel:"Kod pocztowy",payWithCard:"Zapłać kartą",endingIn:"O numerze zakończonym cyframi {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Karta",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],165:[function(e,t,i){"use strict";t.exports={payingWith:"Pagando com {{paymentSource}}",chooseAnotherWayToPay:"Escolher outro meio de pagamento",chooseAWayToPay:"Escolher um meio de pagamento",otherWaysToPay:"Outro meio de pagamento",edit:"Editar",doneEditing:"Concluído",editPaymentMethods:"Editar meios de pagamento",CreditCardDeleteConfirmationMessage:"Excluir cartão com {{secondaryIdentifier}} com final {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Excluir conta do PayPal {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Tem certeza de que deseja excluir a conta do Venmo com o nome de usuário {{identifier}}?",genericDeleteConfirmationMessage:"Tem certeza de que deseja excluir este meio de pagamento?",deleteCancelButton:"Cancelar",deleteConfirmationButton:"Excluir",cardVerification:"Verificação do cartão",fieldEmptyForCvv:"Informe o Código de Segurança.",fieldEmptyForExpirationDate:"Informe a data de vencimento.",fieldEmptyForCardholderName:"Informe o nome do titular do cartão.",fieldTooLongForCardholderName:"O nome do titular do cartão deve ter menos de 256 caracteres.",fieldEmptyForNumber:"Informe um número.",fieldEmptyForPostalCode:"Informe um CEP.",fieldInvalidForCvv:"Este código de segurança não é válido.",fieldInvalidForExpirationDate:"Esta data de vencimento não é válida.",fieldInvalidForNumber:"O número do cartão não é válido.",fieldInvalidForPostalCode:"Este CEP não é válido.",genericError:"Ocorreu um erro.",hostedFieldsTokenizationFailOnDuplicateError:"Este cartão de crédito já está salvo em seus meios de pagamento.",hostedFieldsFailedTokenizationError:"Verifique as informações e tente novamente.",hostedFieldsFieldsInvalidError:"Verifique as informações e tente novamente.",hostedFieldsTokenizationNetworkErrorError:"Erro de rede. Tente novamente.",hostedFieldsTokenizationCvvVerificationFailedError:"Falha ao verificar o cartão de crédito. Verifique as informações e tente novamente.",paypalAccountTokenizationFailedError:"Ocorreu um erro ao adicionar a conta do PayPal. Tente novamente.",paypalFlowFailedError:"Ocorreu um erro de conexão com o PayPal. Tente novamente.",paypalTokenizationRequestActiveError:"A autorização de pagamento do PayPal já está em andamento.",venmoCanceledError:"Ocorreu um erro. Certifique-se de ter a versão mais recente do aplicativo Venmo instalado no seu dispositivo e que o seu navegador suporte a mudança para o Venmo.",vaultManagerPaymentMethodDeletionError:"Não é possível excluir o meio de pagamento, tente novamente.",venmoAppFailedError:"Não foi possível encontrar o aplicativo Venmo no seu dispositivo.",unsupportedCardTypeError:"Este tipo de cartão não é aceito. Experimente outro cartão.",applePayTokenizationError:"Ocorreu um erro de rede ao processar o pagamento com Apple Pay. Tente novamente.",applePayActiveCardError:"Adicione cartão suportado à sua carteira do Apple Pay.",cardholderNameLabel:"Nome do titular do cartão",cardNumberLabel:"Número do cartão",cvvLabel:"CSC",cvvThreeDigitLabelSubheading:"(3 dígitos)",cvvFourDigitLabelSubheading:"(4 dígitos)",cardholderNamePlaceholder:"Nome do titular do cartão",expirationDateLabel:"Data de vencimento",expirationDateLabelSubheading:"(MM/AA)",expirationDatePlaceholder:"MM/AA",postalCodeLabel:"CEP",payWithCard:"Pague com seu cartão",endingIn:"Com final {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Cartão",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],166:[function(e,t,i){"use strict";t.exports={payingWith:"Pagar com {{paymentSource}}",chooseAnotherWayToPay:"Escolher outra forma de pagamento",chooseAWayToPay:"Escolha um meio de pagamento",otherWaysToPay:"Outras formas de pagamento",edit:"Editar",doneEditing:"Concluído",editPaymentMethods:"Editar meios de pagamento",CreditCardDeleteConfirmationMessage:"Eliminar o cartão {{secondaryIdentifier}} terminado em {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Eliminar {{identifier}} da conta PayPal?",VenmoAccountDeleteConfirmationMessage:"Tem a certeza de que pretende eliminar a conta Venmo com o nome de utilizador {{identifier}}?",genericDeleteConfirmationMessage:"Tem certeza de que pretende eliminar este meio de pagamento?",deleteCancelButton:"Cancelar",deleteConfirmationButton:"Eliminar",cardVerification:"Verificação de cartão",fieldEmptyForCvv:"Introduza o código CVV.",fieldEmptyForExpirationDate:"Introduza a data de validade.",fieldEmptyForCardholderName:"Introduza um nome do titular do cartão.",fieldTooLongForCardholderName:"O nome do titular do cartão tem de ter menos de 256 carateres.",fieldEmptyForNumber:"Introduza um número.",fieldEmptyForPostalCode:"Introduza o código postal.",fieldInvalidForCvv:"Este código de segurança não é válido.",fieldInvalidForExpirationDate:"Esta data de validade não é correta.",fieldInvalidForNumber:"Este número de cartão não é válido.",fieldInvalidForPostalCode:"Este código postal não é válido.",genericError:"Tudo indica que ocorreu um problema.",hostedFieldsTokenizationFailOnDuplicateError:"Este cartão de crédito já está registado como um meio de pagamento guardado.",hostedFieldsFailedTokenizationError:"Verifique os dados e tente novamente.",hostedFieldsFieldsInvalidError:"Verifique os dados e tente novamente.",hostedFieldsTokenizationNetworkErrorError:"Erro de rede. Tente novamente.",hostedFieldsTokenizationCvvVerificationFailedError:"A verificação do cartão de crédito falhou. Verifique os dados e tente novamente.",paypalAccountTokenizationFailedError:"Ocorreu um erro ao associar a conta PayPal. Tente novamente.",paypalFlowFailedError:"Ocorreu um erro na ligação com PayPal. Tente novamente.",paypalTokenizationRequestActiveError:"Já há uma autorização de pagamento PayPal em curso.",venmoCanceledError:"Ocorreu um erro. Certifique-se de que tem a versão mais recente da aplicação Venmo instalada no seu dispositivo e que o navegador suporta a mudança para o Venmo.",vaultManagerPaymentMethodDeletionError:"Não é possível eliminar o meio de pagamento, tente novamente.",venmoAppFailedError:"Não foi possível encontrar a aplicação Venmo no dispositivo.",unsupportedCardTypeError:"Este tipo de cartão não é suportado. Tente usar outro cartão.",applePayTokenizationError:"Ocorreu um erro de rede ao processar o pagamento com Apple Pay. Tente novamente.",applePayActiveCardError:"Adicione um cartão suportado à sua carteira Apple Pay.",cardholderNameLabel:"Nome do titular do cartão",cardNumberLabel:"Número do cartão",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 dígitos)",cvvFourDigitLabelSubheading:"(4 dígitos)",cardholderNamePlaceholder:"Nome do titular do cartão",expirationDateLabel:"Data de validade",expirationDateLabelSubheading:"(MM/AA)",expirationDatePlaceholder:"MM/AA",postalCodeLabel:"Código postal",payWithCard:"Pagar com cartão",endingIn:"Terminado em {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Cartão",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],167:[function(e,t,i){"use strict";t.exports={payingWith:"Способы оплаты: {{paymentSource}}",chooseAnotherWayToPay:"Выберите другой способ оплаты",chooseAWayToPay:"Выберите способ оплаты",otherWaysToPay:"Другие способы оплаты",edit:"Редактировать",doneEditing:"Готово",editPaymentMethods:"Редактировать способы оплаты",CreditCardDeleteConfirmationMessage:"Удалить карту {{secondaryIdentifier}}, оканчивающуюся на {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Удалить счет PayPal {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Вы действительно хотите удалить счет Venmo с именем пользователя {{identifier}}?",genericDeleteConfirmationMessage:"Вы действительно хотите удалить этот способ оплаты?",deleteCancelButton:"Отмена",deleteConfirmationButton:"Удалить",cardVerification:"Проверка карты",fieldEmptyForCvv:"Укажите код безопасности.",fieldEmptyForExpirationDate:"Укажите дату окончания срока действия.",fieldEmptyForCardholderName:"Введите имя и фамилию владельца карты.",fieldTooLongForCardholderName:"Имя владельца карты должно содержать не более 256 символов.",fieldEmptyForNumber:"Введите номер.",fieldEmptyForPostalCode:"Укажите почтовый индекс.",fieldInvalidForCvv:"Этот код безопасности недействителен.",fieldInvalidForExpirationDate:"Эта дата окончания срока действия недействительна.",fieldInvalidForNumber:"Этот номер карты недействителен.",fieldInvalidForPostalCode:"Этот почтовый индекс недействителен.",genericError:"Возникла проблема с нашей стороны.",hostedFieldsTokenizationFailOnDuplicateError:"Эта кредитная карта уже указана как сохраненный источник средств.",hostedFieldsFailedTokenizationError:"Проверьте правильность ввода данных и повторите попытку.",hostedFieldsFieldsInvalidError:"Проверьте правильность ввода данных и повторите попытку.",hostedFieldsTokenizationNetworkErrorError:"Ошибка сети. Повторите попытку.",hostedFieldsTokenizationCvvVerificationFailedError:"Проверка банковской карты не выполнена. Проверьте правильность ввода данных и повторите попытку.",paypalAccountTokenizationFailedError:"Что-то пошло не так — не удалось добавить учетную запись PayPal. Повторите попытку.",paypalFlowFailedError:"Что-то пошло не так — не удалось подключиться к системе PayPal. Повторите попытку.",paypalTokenizationRequestActiveError:"Выполняется авторизация платежа PayPal.",venmoCanceledError:"Возникла ошибка. Просим вас убедиться, что у вас установлена новейшая версия приложения Venmo и ваш браузер поддерживает переключение к Venmo.",vaultManagerPaymentMethodDeletionError:"Не удалось удалить способ оплаты. Повторите попытку.",venmoAppFailedError:"Приложение Venmo не обнаружено на вашем устройстве.",unsupportedCardTypeError:"Этот тип карты не поддерживается. Попробуйте воспользоваться другой картой.",applePayTokenizationError:"При обработке платежа через Apple Pay возникла сетевая ошибка. Повторите попытку.",applePayActiveCardError:"Добавьте поддерживаемую карту к своему счету Apple Pay.",cardholderNameLabel:"Имя и фамилия владельца",cardNumberLabel:"Номер карты",cvvLabel:"Код безопасности",cvvThreeDigitLabelSubheading:"(3 цифры)",cvvFourDigitLabelSubheading:"(4 цифры)",cardholderNamePlaceholder:"Имя и фамилия владельца",expirationDateLabel:"Срок действия",expirationDateLabelSubheading:"(ММ/ГГ)",expirationDatePlaceholder:"ММ/ГГ",postalCodeLabel:"Индекс",payWithCard:"Оплатить картой",endingIn:"Последние четыре цифры номера карты: {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Карта",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],168:[function(e,t,i){"use strict";t.exports={payingWith:"Betalas med {{paymentSource}}",chooseAnotherWayToPay:"Välj ett annat sätt att betala",chooseAWayToPay:"Välj hur du vill betala",otherWaysToPay:"Andra sätt att betala",edit:"Ändra",doneEditing:"Klart",editPaymentMethods:"Redigera betalningsmetoder",CreditCardDeleteConfirmationMessage:"Ta bort {{secondaryIdentifier}}-kort som slutar på {{identifier}}?",PayPalAccountDeleteConfirmationMessage:"Ta bort PayPal-konto {{identifier}}?",VenmoAccountDeleteConfirmationMessage:"Är du säker på att du vill ta bort Venmo-konto med användarnamn {{identifier}}?",genericDeleteConfirmationMessage:"Är du säker på att du vill ta bort den här betalningsmetoden?",deleteCancelButton:"Avbryt",deleteConfirmationButton:"Ta bort",cardVerification:"Kortverifiering",fieldEmptyForCvv:"Fyll i en CVV-kod.",fieldEmptyForExpirationDate:"Fyll i ett utgångsdatum.",fieldEmptyForCardholderName:"Fyll i kortinnehavarens namn.",fieldTooLongForCardholderName:"Kortinnehavarens namn måste vara kortare än 256 tecken.",fieldEmptyForNumber:"Fyll i ett nummer.",fieldEmptyForPostalCode:"Fyll i ett postnummer.",fieldInvalidForCvv:"Den här säkerhetskoden är inte giltig.",fieldInvalidForExpirationDate:"Det här utgångsdatumet är inte giltigt.",fieldInvalidForNumber:"Det här kortnumret är inte giltigt.",fieldInvalidForPostalCode:"Det här postnumret är inte giltigt.",genericError:"Ett fel uppstod.",hostedFieldsTokenizationFailOnDuplicateError:"Det här betalkortet finns redan som en sparad betalningsmetod.",hostedFieldsFailedTokenizationError:"Kontrollera uppgifterna och försök igen.",hostedFieldsFieldsInvalidError:"Kontrollera uppgifterna och försök igen.",hostedFieldsTokenizationNetworkErrorError:"Nätverksfel. Försök igen.",hostedFieldsTokenizationCvvVerificationFailedError:"Verifieringen av betalkort misslyckades. Kontrollera uppgifterna och försök igen.",paypalAccountTokenizationFailedError:"Ett fel uppstod när PayPal-kontot skulle läggas till. Försök igen.",paypalFlowFailedError:"Ett fel uppstod när anslutningen till PayPal skulle upprättas. Försök igen.",paypalTokenizationRequestActiveError:"Betalningsgodkännandet för PayPal behandlas redan.",venmoCanceledError:"Något gick fel. Se till att du har den senaste versionen av Venmo-appen installerad på din enhet och att webbläsaren stöder att gå över till Venmo.",vaultManagerPaymentMethodDeletionError:"Det gick inte att ta bort betalningsmetoden. Försök igen.",venmoAppFailedError:"Venmo-appen kunde inte hittas på din enhet.",unsupportedCardTypeError:"Den här korttypen stöds inte. Pröva med ett annat kort.",applePayTokenizationError:"Ett nätverksfel inträffade när Apple Pay-betalningen skulle behandlas. Försök igen.",applePayActiveCardError:"Lägg till ett kort som stöds i Apple Pay-e-plånboken.",cardholderNameLabel:"Kortinnehavarens namn",cardNumberLabel:"Kortnummer",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 siffror)",cvvFourDigitLabelSubheading:"(4 siffror)",cardholderNamePlaceholder:"Kortinnehavarens namn",expirationDateLabel:"Utgångsdatum",expirationDateLabelSubheading:"(MM/ÅÅ)",expirationDatePlaceholder:"MM/ÅÅ",postalCodeLabel:"Postnummer",payWithCard:"Betala med kort",endingIn:"Slutar på {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"Kort",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],169:[function(e,t,i){"use strict";t.exports={payingWith:"การชำระเงินด้วย {{paymentSource}}",chooseAnotherWayToPay:"เลือกวิธีอื่นเพื่อชำระเงิน",chooseAWayToPay:"เลือกวิธีชำระเงิน",otherWaysToPay:"วิธีอื่นๆ ในการชำระเงิน",edit:"แก้ไข",doneEditing:"เสร็จแล้ว",editPaymentMethods:"แก้ไขวิธีการชำระเงิน",CreditCardDeleteConfirmationMessage:"ลบบัตร {{secondaryIdentifier }} ที่ลงท้ายด้วย {{identifier}} หรือไม่",PayPalAccountDeleteConfirmationMessage:"ลบ {{identifier}} บัญชี PayPal หรือไม่",VenmoAccountDeleteConfirmationMessage:"คุณมั่นใจว่าต้องการลบบัญชี Venmo ที่มีชื่อผู้ใช้ {{identifier}} หรือไม่",genericDeleteConfirmationMessage:"คุณมั่นใจว่าต้องการลบวิธีการชำระเงินนี้หรือไม่",deleteCancelButton:"ยกเลิก",deleteConfirmationButton:"ลบ",cardVerification:"การตรวจสอบยืนยันบัตร",fieldEmptyForCvv:"โปรดกรอก CVV (รหัสการตรวจสอบยืนยันบัตร)",fieldEmptyForExpirationDate:"โปรดกรอกวันที่หมดอายุ",fieldEmptyForCardholderName:"โปรดกรอกชื่อเจ้าของบัตร",fieldTooLongForCardholderName:"ชื่อผู้ถือบัตรจะต้องไม่เกิน 256 อักขระ",fieldEmptyForNumber:"โปรดกรอกหมายเลข",fieldEmptyForPostalCode:"โปรดกรอกรหัสไปรษณีย์",fieldInvalidForCvv:"รหัสความปลอดภัยนี้ไม่ถูกต้อง",fieldInvalidForExpirationDate:"วันที่หมดอายุนี้ไม่ถูกต้อง",fieldInvalidForNumber:"หมายเลขบัตรนี้ไม่ถูกต้อง",fieldInvalidForPostalCode:"รหัสไปรษณีย์นี้ไม่ถูกต้อง",genericError:"เกิดข้อผิดพลาดขึ้นในระบบของเรา",hostedFieldsTokenizationFailOnDuplicateError:"บัตรเครดิตนี้ถูกบันทึกไว้เป็นวิธีการชำระเงิน",hostedFieldsFailedTokenizationError:"โปรดตรวจสอบข้อมูลของคุณ แล้วลองใหม่อีกครั้ง",hostedFieldsFieldsInvalidError:"โปรดตรวจสอบข้อมูลของคุณ แล้วลองใหม่อีกครั้ง",hostedFieldsTokenizationNetworkErrorError:"ข้อผิดพลาดด้านเครือข่าย โปรดลองอีกครั้ง",hostedFieldsTokenizationCvvVerificationFailedError:"การตรวจสอบยืนยันบัตรเครดิตล้มเหลว โปรดตรวจสอบข้อมูลของคุณ แล้วลองใหม่อีกครั้ง",paypalAccountTokenizationFailedError:"เกิดข้อผิดพลาดในการเพิ่มบัญชี PayPal โปรดลองอีกครั้ง",paypalFlowFailedError:"เกิดข้อผิดพลาดในการเชื่อมต่อกับ PayPal โปรดลองอีกครั้ง",paypalTokenizationRequestActiveError:"การอนุญาตการชำระเงินของ PayPal อยู่ในระหว่างดำเนินการ",venmoCanceledError:"เกิดข้อผิดพลาดบางประการ ตรวจสอบว่าคุณมีแอป Venmo เวอร์ชันล่าสุดติดตั้งในอุปกรณ์ของคุณ และมีเบราเซอร์ที่รองรับ Venmo",vaultManagerPaymentMethodDeletionError:"ไม่สามารถลบวิธีการชำระเงินได้ ลองอีกครั้ง",venmoAppFailedError:"ไม่พบแอป Venmo บนอุปกรณ์ของคุณ",unsupportedCardTypeError:"ไม่รองรับบัตรประเภทนี้ โปรดลองใช้บัตรใบอื่น",applePayTokenizationError:"เกิดข้อผิดพลาดด้านเครือข่ายขึ้นขณะดำเนินการชำระเงินด้วย Apple Pay โปรดลองอีกครั้ง",applePayActiveCardError:"เพิ่มบัตรที่รองรับในกระเป๋าสตางค์ Apple Pay ของคุณ",cardholderNameLabel:"ชื่อเจ้าของบัตร",cardNumberLabel:"หมายเลขบัตร",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"(3 หลัก)",cvvFourDigitLabelSubheading:"(4 หลัก)",cardholderNamePlaceholder:"ชื่อเจ้าของบัตร",expirationDateLabel:"วันหมดอายุ",expirationDateLabelSubheading:"(ดด/ปป)",expirationDatePlaceholder:"ดด/ปป",postalCodeLabel:"รหัสไปรษณีย์",payWithCard:"ชำระเงินด้วยบัตร",endingIn:"ลงท้ายด้วย {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"บัตร",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],170:[function(e,t,i){"use strict";t.exports={payingWith:"正在使用{{paymentSource}}付款",chooseAnotherWayToPay:"选择其他付款方式",chooseAWayToPay:"选择付款方式",otherWaysToPay:"其他付款方式",edit:"编辑",doneEditing:"完成",editPaymentMethods:"编辑付款方式",CreditCardDeleteConfirmationMessage:"删除尾号为{{identifier}}的{{secondaryIdentifier}}卡？",PayPalAccountDeleteConfirmationMessage:"删除PayPal账户{{identifier}}？",VenmoAccountDeleteConfirmationMessage:"确定要删除用户名为{{identifier}}的Venmo账户吗？",genericDeleteConfirmationMessage:"确定要删除该付款方式吗？",deleteCancelButton:"取消",deleteConfirmationButton:"删除",cardVerification:"卡验证",fieldEmptyForCvv:"请填写CVV。",fieldEmptyForExpirationDate:"请填写有效期限。",fieldEmptyForCardholderName:"请填写持卡人的姓名。",fieldTooLongForCardholderName:"持卡人姓名必须少于256个字符。",fieldEmptyForNumber:"请填写一个号码。",fieldEmptyForPostalCode:"请填写邮政编码。",fieldInvalidForCvv:"此安全代码无效。",fieldInvalidForExpirationDate:"此有效期限无效。",fieldInvalidForNumber:"此卡号无效。",fieldInvalidForPostalCode:"此邮政编码无效。",genericError:"我们遇到了一些问题",hostedFieldsTokenizationFailOnDuplicateError:"此信用卡已作为保存后的付款方式存在。",hostedFieldsFailedTokenizationError:"请检查您的信息，然后重试。",hostedFieldsFieldsInvalidError:"请检查您的信息，然后重试。",hostedFieldsTokenizationNetworkErrorError:"网络错误。请重试。",hostedFieldsTokenizationCvvVerificationFailedError:"信用卡验证失败。请检查您的信息，然后重试。",paypalAccountTokenizationFailedError:"添加PayPal账户时出错。请重试。",paypalFlowFailedError:"连接到PayPal时出错。请重试。",paypalTokenizationRequestActiveError:"PayPal付款授权已在进行中。",venmoCanceledError:"我们遇到了问题。请确保您的设备上已安装最新版本的Venmo应用，并且您的浏览器支持切换到Venmo。",vaultManagerPaymentMethodDeletionError:"无法删除付款方式，请重试。",venmoAppFailedError:"在您的设备上找不到Venmo应用。",unsupportedCardTypeError:"不支持该卡类型。请尝试其他卡。",applePayTokenizationError:"处理Apple Pay付款时出现网络错误。请重试。",applePayActiveCardError:"请添加受支持的卡到您的Apple Pay钱包。",cardholderNameLabel:"持卡人姓名",cardNumberLabel:"卡号",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"（3位数）",cvvFourDigitLabelSubheading:"（4位数）",cardholderNamePlaceholder:"持卡人姓名",expirationDateLabel:"有效期限",expirationDateLabelSubheading:"（MM/YY）",expirationDatePlaceholder:"MM/YY",postalCodeLabel:"邮政编码",payWithCard:"用卡付款",endingIn:"尾号为{{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"卡",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"银联"}},{}],171:[function(e,t,i){"use strict";t.exports={payingWith:"付款方式為 {{paymentSource}}",chooseAnotherWayToPay:"選擇其他付款方式",chooseAWayToPay:"選擇付款方式",otherWaysToPay:"其他付款方式",edit:"編輯",doneEditing:"完成",editPaymentMethods:"編輯付款方式",CreditCardDeleteConfirmationMessage:"要刪除末碼為 {{identifier}} 的 {{secondaryIdentifier}} 卡嗎？",PayPalAccountDeleteConfirmationMessage:"要刪除 PayPal 帳戶 {{identifier}} 嗎？",VenmoAccountDeleteConfirmationMessage:"確定要刪除使用者名稱為 {{identifier}} 的 Venmo 帳戶嗎？",genericDeleteConfirmationMessage:"確定要刪除此付款方式嗎？",deleteCancelButton:"取消",deleteConfirmationButton:"刪除",cardVerification:"信用卡認證",fieldEmptyForCvv:"請填寫信用卡認證碼。",fieldEmptyForExpirationDate:"請填寫到期日。",fieldEmptyForCardholderName:"請填寫持卡人的名字。",fieldTooLongForCardholderName:"持卡人姓名必須少於 256 個字元。",fieldEmptyForNumber:"請填寫號碼。",fieldEmptyForPostalCode:"請填寫郵遞區號。",fieldInvalidForCvv:"此安全代碼無效。",fieldInvalidForExpirationDate:"此到期日無效。",fieldInvalidForNumber:"此卡號無效。",fieldInvalidForPostalCode:"此郵遞區號無效。",genericError:"系統發生錯誤。",hostedFieldsTokenizationFailOnDuplicateError:"此信用卡已存在，為已儲存的付款方式。",hostedFieldsFailedTokenizationError:"請檢查你的資料並再試一次。",hostedFieldsFieldsInvalidError:"請檢查你的資料並再試一次。",hostedFieldsTokenizationNetworkErrorError:"網絡錯誤。再試一次。",hostedFieldsTokenizationCvvVerificationFailedError:"信用卡認證失敗。請檢查你的資料並再試一次。",paypalAccountTokenizationFailedError:"加入 PayPal 帳戶時發生錯誤。再試一次。",paypalFlowFailedError:"連接 PayPal 時發生錯誤。再試一次。",paypalTokenizationRequestActiveError:"PayPal 付款授權已在處理中。",venmoCanceledError:"系統發生錯誤，請確保你已在裝置上安裝最新版本的 Venmo 應用程式，而且你的瀏覽器支援切換至 Venmo。",vaultManagerPaymentMethodDeletionError:"無法刪除付款方式，請再試一次。",venmoAppFailedError:"在你的裝置上找不到 Venmo 應用程式。",unsupportedCardTypeError:"不可使用此信用卡類型。請改用其他信用卡。",applePayTokenizationError:"處理 Apple Pay 付款時發生網絡錯誤。再試一次。",applePayActiveCardError:"在 Apple Pay 錢包中加入支援的信用卡。",cardholderNameLabel:"持卡人名字",cardNumberLabel:"卡號",cvvLabel:"信用卡認證碼",cvvThreeDigitLabelSubheading:"（3 位數）",cvvFourDigitLabelSubheading:"（4 位數）",cardholderNamePlaceholder:"持卡人名字",expirationDateLabel:"到期日",expirationDateLabelSubheading:"(MM/YY)",expirationDatePlaceholder:"月 / 年",postalCodeLabel:"郵遞區號",payWithCard:"使用信用卡付款",endingIn:"末碼為 {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"信用卡",PayPal:"PayPal","PayPal Credit":"PayPal Credit","Google Pay":"Google Pay","American Express":"American Express",Discover:"Discover","Diners Club":"Diners Club",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],172:[function(e,t,i){"use strict";t.exports={payingWith:"以 {{paymentSource}} 付款",chooseAnotherWayToPay:"選擇付款的以其他方式付款",chooseAWayToPay:"選擇付款方式",otherWaysToPay:"其他付款方式",edit:"編輯",doneEditing:"完成",editPaymentMethods:"編輯付款方式",CreditCardDeleteConfirmationMessage:"確定要刪除末碼為 {{identifier}} 的 {{secondaryIdentifier}} 卡片嗎？",PayPalAccountDeleteConfirmationMessage:"確定要刪除 {{identifier}} PayPal 帳戶嗎？",VenmoAccountDeleteConfirmationMessage:"確定要刪除用戶名稱為 {{identifier}} 的 Venmo 帳戶嗎？",genericDeleteConfirmationMessage:"確定要刪除此付款方式？",deleteCancelButton:"取消",deleteConfirmationButton:"刪除",cardVerification:"信用卡認證",fieldEmptyForCvv:"請填妥信用卡驗證碼。",fieldEmptyForExpirationDate:"請填妥到期日。",fieldEmptyForCardholderName:"請填妥持卡人姓名。",fieldTooLongForCardholderName:"持卡人姓名不能超過 256 個字元。",fieldEmptyForNumber:"請填妥號碼。",fieldEmptyForPostalCode:"請填寫郵遞區號。",fieldInvalidForCvv:"這組安全代碼無效。",fieldInvalidForExpirationDate:"此到期日無效。",fieldInvalidForNumber:"此卡號無效。",fieldInvalidForPostalCode:"此郵遞區號無效。",genericError:"我們的系統發生問題。",hostedFieldsTokenizationFailOnDuplicateError:"此信用卡已存在，為已儲存的付款方式。",hostedFieldsFailedTokenizationError:"請檢查你的資料並重試。",hostedFieldsFieldsInvalidError:"請檢查你的資料並重試。",hostedFieldsTokenizationNetworkErrorError:"網路錯誤。請重試。",hostedFieldsTokenizationCvvVerificationFailedError:"信用卡認證失敗。請檢查你的資料並重試。",paypalAccountTokenizationFailedError:"新增 PayPal 帳戶時，系統發生錯誤。請重試。",paypalFlowFailedError:"連結至 PayPal 時，系統發生錯誤。請重試。",paypalTokenizationRequestActiveError:"PayPal 支付款項的授權已在處理中。",venmoCanceledError:"系統發生錯誤。確認你的裝置上裝有最新版本的 Venmo 應用程式，而且瀏覽器支援切換至 Venmo。",vaultManagerPaymentMethodDeletionError:"無法刪除付款方式，請再試一次。",venmoAppFailedError:"你的裝置上找不到 Venmo 應用程式。",unsupportedCardTypeError:"不支援此卡片類型。請改用其他卡片。",applePayTokenizationError:"在處理 Apple Pay 付款時發生網路錯誤。請重試。",applePayActiveCardError:"新增支援的卡片至你的 Apple Pay 錢包。",cardholderNameLabel:"持卡人姓名",cardNumberLabel:"卡號",cvvLabel:"CVV",cvvThreeDigitLabelSubheading:"（3 位數）",cvvFourDigitLabelSubheading:"（4 位數）",cardholderNamePlaceholder:"持卡人姓名",expirationDateLabel:"到期日",expirationDateLabelSubheading:"（月 / 年）",expirationDatePlaceholder:"月 / 年",postalCodeLabel:"郵遞區號",payWithCard:"使用信用卡 / 扣帳卡付款",endingIn:"末碼為 {{lastFourCardDigits}}","Apple Pay":"Apple Pay",Venmo:"Venmo",Card:"信用卡或扣帳卡",PayPal:"PayPal","PayPal Credit":"PayPal 信貸","Google Pay":"Google Pay","American Express":"美國運通 (American Express)",Discover:"Discover","Diners Club":"大來國際 (Diners Club)",MasterCard:"Mastercard",Visa:"Visa",JCB:"JCB",Maestro:"Maestro",UnionPay:"UnionPay"}},{}],173:[function(e,t,i){"use strict";var r=e("../lib/assign").assign,n=e("@braintree/class-list"),a=e("../lib/dropin-error"),o=e("../constants").errors,s=e("../lib/promise");function l(e){r(this,e=e||{})}l.prototype.getElementById=function(e){return this.element?this.element.querySelector('[data-braintree-id="'+e+'"]'):null},l.prototype.requestPaymentMethod=function(){return s.reject(new a(o.NO_PAYMENT_METHOD_ERROR))},l.prototype.getPaymentMethod=function(){return this.activeMethodView&&this.activeMethodView.paymentMethod},l.prototype.onSelection=function(){},l.prototype.teardown=function(){return s.resolve()},l.prototype.preventUserAction=function(){this.element&&n.add(this.element,"braintree-sheet--loading"),this.model.preventUserAction()},l.prototype.allowUserAction=function(){this.element&&n.remove(this.element,"braintree-sheet--loading"),this.model.allowUserAction()},t.exports=l},{"../constants":125,"../lib/assign":131,"../lib/dropin-error":135,"../lib/promise":143,"@braintree/class-list":18}],174:[function(e,t,i){"use strict";var r=e("./base-view"),n=e("../lib/add-selection-event-handler"),a=e("../constants").paymentMethodTypes;function o(){r.apply(this,arguments),this._initialize()}((o.prototype=Object.create(r.prototype)).constructor=o).ID=o.prototype.ID="delete-confirmation",o.prototype._initialize=function(){this._yesButton=this.getElementById("delete-confirmation__yes"),this._noButton=this.getElementById("delete-confirmation__no"),this._messageBox=this.getElementById("delete-confirmation__message"),n(this._yesButton,function(){this.model.deleteVaultedPaymentMethod()}.bind(this)),n(this._noButton,function(){this.model.cancelDeleteVaultedPaymentMethod()}.bind(this))},o.prototype.applyPaymentMethod=function(e){var t,i,r=this.strings[e.type+"DeleteConfirmationMessage"];if(r){switch(e.type){case a.card:t=e.details.lastFour,i=e.details.cardType,i=this.strings[i]||i;break;case a.paypal:t=e.details.email;break;case a.venmo:t=e.details.username}r=r.replace("{{identifier}}",t),i&&(r=r.replace("{{secondaryIdentifier}}",i))}else r=this.strings.genericDeleteConfirmationMessage;this._messageBox.innerText=r},t.exports=o},{"../constants":125,"../lib/add-selection-event-handler":129,"./base-view":173}],175:[function(e,t,i){"use strict";var r=e("../lib/analytics"),n=e("../constants").analyticsKinds,a=e("./base-view"),o=e("@braintree/class-list"),s=e("./payment-sheet-views"),l=e("./payment-methods-view"),d=e("./payment-options-view"),c=e("./delete-confirmation-view"),p=e("../lib/add-selection-event-handler"),u=e("../lib/promise"),h=e("../lib/supports-flexbox"),m=e("../constants").CHANGE_ACTIVE_PAYMENT_METHOD_TIMEOUT,y=e("../constants").errors.DEVELOPER_MISCONFIGURATION_MESSAGE;function f(){a.apply(this,arguments),this.dependenciesInitializing=0,this._initialize()}function g(e){return"braintree-show-"+e}((f.prototype=Object.create(a.prototype)).constructor=f).prototype._initialize=function(){var e;this._hasMultiplePaymentOptions=1<this.model.supportedPaymentOptions.length,this._views={},this.sheetContainer=this.getElementById("sheet-container"),this.sheetErrorText=this.getElementById("sheet-error-text"),this.toggle=this.getElementById("toggle"),this.disableWrapper=this.getElementById("disable-wrapper"),this.lowerContainer=this.getElementById("lower-container"),this.loadingContainer=this.getElementById("loading-container"),this.dropinContainer=this.element.querySelector(".braintree-dropin"),this.supportsFlexbox=h(),this.model.on("asyncDependenciesReady",this.hideLoadingIndicator.bind(this)),this.model.on("errorOccurred",this.showSheetError.bind(this)),this.model.on("errorCleared",this.hideSheetError.bind(this)),this.model.on("preventUserAction",this.preventUserAction.bind(this)),this.model.on("allowUserAction",this.allowUserAction.bind(this)),this.paymentSheetViewIDs=Object.keys(s).reduce(function(e,t){var i,r;return-1!==this.model.supportedPaymentOptions.indexOf(t)&&((r=new(i=s[t])({element:this.getElementById(i.ID),mainView:this,model:this.model,client:this.client,strings:this.strings})).initialize(),this.addView(r),e.push(r.ID)),e}.bind(this),[]),this.paymentMethodsViews=new l({element:this.element,model:this.model,strings:this.strings}),this.addView(this.paymentMethodsViews),this.deleteConfirmationView=new c({element:this.getElementById("delete-confirmation"),model:this.model,strings:this.strings}),this.addView(this.deleteConfirmationView),p(this.toggle,this.toggleAdditionalOptions.bind(this)),this.model.on("changeActivePaymentMethod",function(){setTimeout(function(){this.setPrimaryView(l.ID)}.bind(this),m)}.bind(this)),this.model.on("changeActivePaymentView",function(e){var t=this.getView(e);e===l.ID?(o.add(this.paymentMethodsViews.container,"braintree-methods--active"),o.remove(this.sheetContainer,"braintree-sheet--active")):(setTimeout(function(){o.add(this.sheetContainer,"braintree-sheet--active")}.bind(this),0),o.remove(this.paymentMethodsViews.container,"braintree-methods--active"),this.getView(e).getPaymentMethod()||this.model.setPaymentMethodRequestable({isRequestable:!1})),t.onSelection()}.bind(this)),this.model.on("removeActivePaymentMethod",function(){var e=this.getView(this.model.getActivePaymentView());e&&"function"==typeof e.removeActivePaymentMethod&&e.removeActivePaymentMethod()}.bind(this)),this.model.on("enableEditMode",this.enableEditMode.bind(this)),this.model.on("disableEditMode",this.disableEditMode.bind(this)),this.model.on("confirmPaymentMethodDeletion",this.openConfirmPaymentMethodDeletionDialog.bind(this)),this.model.on("cancelVaultedPaymentMethodDeletion",this.cancelVaultedPaymentMethodDeletion.bind(this)),this.model.on("startVaultedPaymentMethodDeletion",this.startVaultedPaymentMethodDeletion.bind(this)),this.model.on("finishVaultedPaymentMethodDeletion",this.finishVaultedPaymentMethodDeletion.bind(this)),this._hasMultiplePaymentOptions&&(e=new d({client:this.client,element:this.getElementById(d.ID),mainView:this,model:this.model,strings:this.strings}),this.addView(e)),this._sendToDefaultView()},f.prototype.addView=function(e){this._views[e.ID]=e},f.prototype.getView=function(e){return this._views[e]},f.prototype.setPrimaryView=function(e,t){var i;setTimeout(function(){this.element.className=g(e),t&&o.add(this.element,g(t))}.bind(this),0),this.primaryView=this.getView(e),this.model.changeActivePaymentView(e),-1!==this.paymentSheetViewIDs.indexOf(e)?0<this.model.getPaymentMethods().length||this.getView(d.ID)?this.showToggle():this.hideToggle():e===l.ID?(this.showToggle(),this.getElementById("lower-container").appendChild(this.getElementById("options"))):e===d.ID&&this.hideToggle(),this.supportsFlexbox||this.element.setAttribute("data-braintree-no-flexbox",!0),i=this.primaryView.getPaymentMethod(),this.model.setPaymentMethodRequestable({isRequestable:Boolean(i),type:i&&i.type,selectedPaymentMethod:i}),this.model.clearError()},f.prototype.requestPaymentMethod=function(){return this.getView(this.model.getActivePaymentView()).requestPaymentMethod().then(function(e){return r.sendEvent(this.client,"request-payment-method."+n[e.type]),e}.bind(this)).catch(function(e){return r.sendEvent(this.client,"request-payment-method.error"),u.reject(e)}.bind(this))},f.prototype.hideLoadingIndicator=function(){o.add(this.dropinContainer,"braintree-loaded"),o.add(this.loadingContainer,"braintree-hidden")},f.prototype.showLoadingIndicator=function(){o.remove(this.dropinContainer,"braintree-loaded"),o.remove(this.loadingContainer,"braintree-hidden")},f.prototype.toggleAdditionalOptions=function(){var e,t=-1!==this.paymentSheetViewIDs.indexOf(this.primaryView.ID);this.hideToggle(),this._hasMultiplePaymentOptions?t?0===this.model.getPaymentMethods().length?this.setPrimaryView(d.ID):(this.setPrimaryView(l.ID,d.ID),this.hideToggle()):o.add(this.element,g(d.ID)):(e=this.paymentSheetViewIDs[0],o.add(this.element,g(e)),this.model.changeActivePaymentView(e))},f.prototype.showToggle=function(){this.model.isInEditMode()||(o.remove(this.toggle,"braintree-hidden"),o.add(this.lowerContainer,"braintree-hidden"))},f.prototype.hideToggle=function(){o.add(this.toggle,"braintree-hidden"),o.remove(this.lowerContainer,"braintree-hidden")},f.prototype.showSheetError=function(e){var t,i,r=this.strings.genericError;t=this.strings.hasOwnProperty(e)?this.strings[e]:e&&"string"==typeof e.code?this.strings[(i=e.code,i.toLowerCase().replace(/(\_\w)/g,function(e){return e[1].toUpperCase()})+"Error")]||r:"developerError"===e?y:r,o.add(this.dropinContainer,"braintree-sheet--has-error"),this.sheetErrorText.innerHTML=t},f.prototype.hideSheetError=function(){o.remove(this.dropinContainer,"braintree-sheet--has-error")},f.prototype.getOptionsElements=function(){return this._views.options.elements},f.prototype.preventUserAction=function(){o.remove(this.disableWrapper,"braintree-hidden")},f.prototype.allowUserAction=function(){o.add(this.disableWrapper,"braintree-hidden")},f.prototype.teardown=function(){var t,e=Object.keys(this._views).map(function(e){return this._views[e].teardown().catch(function(e){t=e})}.bind(this));return u.all(e).then(function(){return t?u.reject(t):u.resolve()})},f.prototype.enableEditMode=function(){this.setPrimaryView(this.paymentMethodsViews.ID),this.paymentMethodsViews.enableEditMode(),this.hideToggle(),this.model.setPaymentMethodRequestable({isRequestable:!1})},f.prototype.disableEditMode=function(){var e;this.hideSheetError(),this.paymentMethodsViews.disableEditMode(),this.showToggle(),e=this.primaryView.getPaymentMethod(),this.model.setPaymentMethodRequestable({isRequestable:Boolean(e),type:e&&e.type,selectedPaymentMethod:e})},f.prototype.openConfirmPaymentMethodDeletionDialog=function(e){this.deleteConfirmationView.applyPaymentMethod(e),this.setPrimaryView(this.deleteConfirmationView.ID)},f.prototype.cancelVaultedPaymentMethodDeletion=function(){this.setPrimaryView(this.paymentMethodsViews.ID)},f.prototype.startVaultedPaymentMethodDeletion=function(){this.element.className="",this.showLoadingIndicator()},f.prototype.finishVaultedPaymentMethodDeletion=function(e){var t=this;return this.paymentMethodsViews.refreshPaymentMethods(),e&&0<this.model.getPaymentMethods().length?(this.model.enableEditMode(),this.showSheetError("vaultManagerPaymentMethodDeletionError")):this._sendToDefaultView(),new u(function(e){setTimeout(function(){t.hideLoadingIndicator(),e()},500)})},f.prototype._sendToDefaultView=function(){var e=this.model.getPaymentMethods(),t=!1!==this.model.merchantConfiguration.preselectVaultedPaymentMethod;0<e.length?t?this.model.changeActivePaymentMethod(e[0]):this.setPrimaryView(this.paymentMethodsViews.ID):this._hasMultiplePaymentOptions?this.setPrimaryView(d.ID):this.setPrimaryView(this.paymentSheetViewIDs[0])},t.exports=f},{"../constants":125,"../lib/add-selection-event-handler":129,"../lib/analytics":130,"../lib/promise":143,"../lib/supports-flexbox":145,"./base-view":173,"./delete-confirmation-view":174,"./payment-methods-view":177,"./payment-options-view":178,"./payment-sheet-views":183,"@braintree/class-list":18}],176:[function(e,t,i){"use strict";var r=e("./base-view"),n=e("@braintree/class-list"),a=e("../constants"),o=e("../lib/add-selection-event-handler");function s(){r.apply(this,arguments),this._initialize()}((s.prototype=Object.create(r.prototype)).constructor=s).prototype._initialize=function(){var e,t='<div class="braintre-method__icon-container braintree-method__delete-container">\n  <div class="braintree-method__icon braintree-method__delete">\n    <svg width="48" height="29">\n      <use xlink:href="#iconX"></use>\n    </svg>\n  </div>\n  <div class="braintree-method__disabled-description">@DISABLE_MESSAGE</div>\n</div>\n\n<div class="braintree-method__logo">\n  <svg width="40" height="24" class="@CLASSNAME">\n    <use xlink:href="#@ICON"></use>\n  </svg>\n</div>\n\n<div class="braintree-method__label">@TITLE<br><div class="braintree-method__label--small">@SUBTITLE</div></div>\n\n<div class="braintre-method__icon-container braintree-method__check-container">\n  <div class="braintree-method__icon braintree-method__check">\n    <svg height="100%" width="100%">\n      <use xlink:href="#iconCheck"></use>\n    </svg>\n  </div>\n</div>\n',i=a.paymentMethodCardTypes,r=a.paymentMethodTypes;switch(this.element=document.createElement("div"),this.element.className="braintree-method",this.element.setAttribute("tabindex","0"),o(this.element,this._choosePaymentMethod.bind(this)),t=t.replace(/@DISABLE_MESSAGE/g,this.strings.hasSubscription),this.paymentMethod.type){case r.applePay:t=t.replace(/@ICON/g,"logoApplePay").replace(/@CLASSNAME/g,"").replace(/@TITLE/g,this.strings["Apple Pay"]).replace(/@SUBTITLE/g,"");break;case r.card:e=this.strings.endingIn.replace("{{lastFourCardDigits}}",this.paymentMethod.details.lastFour),t=t.replace(/@ICON/g,"icon-"+i[this.paymentMethod.details.cardType]).replace(/@CLASSNAME/g," braintree-icon--bordered").replace(/@TITLE/g,e).replace(/@SUBTITLE/g,this.strings[this.paymentMethod.details.cardType]);break;case r.googlePay:t=t.replace(/@ICON/g,"logoGooglePay").replace(/@CLASSNAME/g,"").replace(/@TITLE/g,this.strings["Google Pay"]).replace(/@SUBTITLE/g,"");break;case r.paypal:t=t.replace(/@ICON/g,"logoPayPal").replace(/@CLASSNAME/g,"").replace(/@TITLE/g,this.paymentMethod.details.email).replace(/@SUBTITLE/g,this.strings.PayPal);break;case r.venmo:t=t.replace(/@ICON/g,"logoVenmo").replace(/@CLASSNAME/g,"").replace(/@TITLE/g,this.paymentMethod.details.username).replace(/@SUBTITLE/g,this.strings.Venmo)}this.element.innerHTML=t,this.checkMark=this.element.querySelector(".braintree-method__check-container"),o(this.element.querySelector(".braintree-method__delete-container"),this._selectDelete.bind(this))},s.prototype.setActive=function(e){setTimeout(function(){n.toggle(this.element,"braintree-method--active",e)}.bind(this),0)},s.prototype.enableEditMode=function(){n.add(this.checkMark,"braintree-hidden"),this.paymentMethod.hasSubscription&&n.add(this.element,"braintree-method--disabled")},s.prototype.disableEditMode=function(){n.remove(this.checkMark,"braintree-hidden"),n.remove(this.element,"braintree-method--disabled")},s.prototype._choosePaymentMethod=function(){this.model.isInEditMode()||this.model.changeActivePaymentMethod(this.paymentMethod)},s.prototype._selectDelete=function(){this.model.confirmPaymentMethodDeletion(this.paymentMethod)},t.exports=s},{"../constants":125,"../lib/add-selection-event-handler":129,"./base-view":173,"@braintree/class-list":18}],177:[function(e,t,i){"use strict";var r=e("./base-view"),n=e("./payment-method-view"),a=e("../lib/dropin-error"),o=e("@braintree/class-list"),s=e("../constants").errors,l=e("../lib/promise"),d=e("../lib/add-selection-event-handler"),c={CreditCard:"Card",PayPalAccount:"PayPal",ApplePayCard:"Apple Pay",AndroidPayCard:"Google Pay",VenmoAccount:"Venmo"};function p(){r.apply(this,arguments),this._initialize()}((p.prototype=Object.create(r.prototype)).constructor=p).ID=p.prototype.ID="methods",p.prototype._initialize=function(){this.views=[],this.container=this.getElementById("methods-container"),this._headingLabel=this.getElementById("methods-label"),this._editButton=this.getElementById("methods-edit"),this.model.on("addPaymentMethod",this._addPaymentMethod.bind(this)),this.model.on("changeActivePaymentMethod",this._changeActivePaymentMethodView.bind(this)),this.model.on("refreshPaymentMethods",this.refreshPaymentMethods.bind(this)),this.refreshPaymentMethods(),this.model.merchantConfiguration.vaultManager&&(this.model.on("removePaymentMethod",this._removePaymentMethod.bind(this)),d(this._editButton,function(){this.model.isInEditMode()?this.model.disableEditMode():this.model.enableEditMode()}.bind(this)),o.remove(this._editButton,"braintree-hidden"))},p.prototype.removeActivePaymentMethod=function(){this.activeMethodView&&(this.activeMethodView.setActive(!1),this.activeMethodView=null,o.add(this._headingLabel,"braintree-no-payment-method-selected"))},p.prototype._getPaymentMethodString=function(){var e,t;return this.activeMethodView?(e=c[this.activeMethodView.paymentMethod.type],t=this.strings[e],this.strings.payingWith.replace("{{paymentSource}}",t)):""},p.prototype.enableEditMode=function(){o.add(this.container,"braintree-methods--edit"),this._editButton.innerHTML=this.strings.deleteCancelButton,this._headingLabel.innerHTML=this.strings.editPaymentMethods,this.views.forEach(function(e){e.enableEditMode()})},p.prototype.disableEditMode=function(){o.remove(this.container,"braintree-methods--edit"),this._editButton.innerHTML=this.strings.edit,this._headingLabel.innerHTML=this._getPaymentMethodString(),this.views.forEach(function(e){e.disableEditMode()})},p.prototype._addPaymentMethod=function(e){var t=new n({model:this.model,paymentMethod:e,strings:this.strings});this.model.isGuestCheckout&&this.container.firstChild&&(this.container.removeChild(this.container.firstChild),this.views.pop()),this.container.firstChild?this.container.insertBefore(t.element,this.container.firstChild):this.container.appendChild(t.element),this.views.push(t)},p.prototype._removePaymentMethod=function(e){var t;for(t=0;t<this.views.length;t++)if(this.views[t].paymentMethod===e){this.container.removeChild(this.views[t].element),this._headingLabel.innerHTML="&nbsp;",this.views.splice(t,1);break}},p.prototype._changeActivePaymentMethodView=function(e){var t,i=this.activeMethodView;for(t=0;t<this.views.length;t++)if(this.views[t].paymentMethod===e){this.activeMethodView=this.views[t],this._headingLabel.innerHTML=this._getPaymentMethodString();break}i&&i.setActive(!1),this.activeMethodView.setActive(!0),o.remove(this._headingLabel,"braintree-no-payment-method-selected")},p.prototype.requestPaymentMethod=function(){return!this.activeMethodView||this.model.isInEditMode()?l.reject(new a(s.NO_PAYMENT_METHOD_ERROR)):l.resolve(this.activeMethodView.paymentMethod)},p.prototype.refreshPaymentMethods=function(){var e,t=this.model.getPaymentMethods();for(this.views.forEach(function(e){this.container.removeChild(e.element)}.bind(this)),this.views=[],e=t.length-1;0<=e;e--)this._addPaymentMethod(t[e])},t.exports=p},{"../constants":125,"../lib/add-selection-event-handler":129,"../lib/dropin-error":135,"../lib/promise":143,"./base-view":173,"./payment-method-view":176,"@braintree/class-list":18}],178:[function(e,t,i){"use strict";var a=e("../lib/analytics"),o=e("../lib/add-selection-event-handler"),r=e("./base-view"),s=e("../constants").paymentOptionIDs;function n(){r.apply(this,arguments),this._initialize()}((n.prototype=Object.create(r.prototype)).constructor=n).ID=n.prototype.ID="options",n.prototype._initialize=function(){this.container=this.getElementById("payment-options-container"),this.elements={},this.model.supportedPaymentOptions.forEach(function(e){this._addPaymentOption(e)}.bind(this))},n.prototype._addPaymentOption=function(e){var t,i=document.createElement("div"),r='<div class="braintree-option__logo">\n  <svg width="48" height="29" class="@CLASSNAME">\n    <use xlink:href="#@ICON"></use>\n  </svg>\n</div>\n\n<div class="braintree-option__label" aria-label="@OPTION_LABEL">\n  @OPTION_TITLE\n  <div class="braintree-option__disabled-message"></div>\n</div>\n',n=function(){this.mainView.setPrimaryView(e),this.model.selectPaymentOption(e),a.sendEvent(this.client,"selected."+s[e])}.bind(this);switch(i.className="braintree-option braintree-option__"+e,i.setAttribute("tabindex","0"),e){case s.applePay:t=this.strings["Apple Pay"],r=r.replace(/@ICON/g,"logoApplePay");break;case s.card:t=this.strings.Card,r=(r=r.replace(/@ICON/g,"iconCardFront")).replace(/@CLASSNAME/g,"braintree-icon--bordered");break;case s.googlePay:t=this.strings["Google Pay"],r=r.replace(/@ICON/g,"logoGooglePay");break;case s.paypal:t=this.strings.PayPal,r=r.replace(/@ICON/g,"logoPayPal");break;case s.paypalCredit:t=this.strings["PayPal Credit"],r=r.replace(/@ICON/g,"logoPayPalCredit");break;case s.venmo:t=this.strings.Venmo,r=r.replace(/@ICON/g,"logoVenmo")}r=(r=(r=r.replace(/@OPTION_LABEL/g,this._generateOptionLabel(t))).replace(/@OPTION_TITLE/g,t)).replace(/@CLASSNAME/g,""),i.innerHTML=r,o(i,n),this.container.appendChild(i),this.elements[e]={div:i,clickHandler:n}},n.prototype._generateOptionLabel=function(e){return this.strings.payingWith.replace("{{paymentSource}}",e)},t.exports=n},{"../constants":125,"../lib/add-selection-event-handler":129,"../lib/analytics":130,"./base-view":173}],179:[function(d,c,e){(function(n){"use strict";var e=d("../../lib/assign").assign,t=d("../base-view"),r=d("braintree-web/apple-pay"),a=d("../../lib/dropin-error"),i=d("../../lib/is-https"),o=d("../../lib/promise"),s=d("../../constants").paymentOptionIDs;function l(){t.apply(this,arguments)}((l.prototype=Object.create(t.prototype)).constructor=l).ID=l.prototype.ID=s.applePay,l.prototype.initialize=function(){var i=this;return i.applePayConfiguration=e({},i.model.merchantConfiguration.applePay),i.model.asyncDependencyStarting(),r.create({client:this.client}).then(function(e){var t=i.getElementById("apple-pay-button");i.applePayInstance=e,i.model.on("changeActivePaymentView",function(e){e===i.ID&&n.ApplePaySession.canMakePaymentsWithActiveCard(i.applePayInstance.merchantIdentifier).then(function(e){e||i.model.reportError("applePayActiveCardError")})}),t.onclick=i._showPaymentSheet.bind(i),t.style["-apple-pay-button-style"]=i.model.merchantConfiguration.applePay.buttonStyle||"black",i.model.asyncDependencyReady()}).catch(function(e){i.model.asyncDependencyFailed({view:i.ID,error:new a(e)})})},l.prototype._showPaymentSheet=function(){var i=this,e=i.applePayInstance.createPaymentRequest(this.applePayConfiguration.paymentRequest),r=new n.ApplePaySession(2,e);return r.onvalidatemerchant=function(e){i.applePayInstance.performValidation({validationURL:e.validationURL,displayName:i.applePayConfiguration.displayName}).then(function(e){r.completeMerchantValidation(e)}).catch(function(e){i.model.reportError(e),r.abort()})},r.onpaymentauthorized=function(t){i.applePayInstance.tokenize({token:t.payment.token}).then(function(e){r.completePayment(n.ApplePaySession.STATUS_SUCCESS),e.rawPaymentData=t.payment,i.model.addPaymentMethod(e)}).catch(function(e){i.model.reportError(e),r.completePayment(n.ApplePaySession.STATUS_FAILURE)})},r.begin(),!1},l.prototype.updateConfiguration=function(e,t){this.applePayConfiguration[e]=t},l.isEnabled=function(e){return e.client.getConfiguration().gatewayConfiguration.applePayWeb&&Boolean(e.merchantConfiguration.applePay)&&n.ApplePaySession&&i.isHTTPS()?o.resolve(Boolean(n.ApplePaySession.canMakePayments())):o.resolve(!1)},c.exports=l}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../constants":125,"../../lib/assign":131,"../../lib/dropin-error":135,"../../lib/is-https":139,"../../lib/promise":143,"../base-view":173,"braintree-web/apple-pay":29}],180:[function(m,y,e){(function(c){"use strict";var t,i=m("../../lib/analytics"),r=m("../../lib/assign").assign,n=m("../../lib/browser-detection"),e=m("../base-view"),p=m("braintree-web/paypal-checkout"),u=m("../../lib/dropin-error"),a=m("../../constants"),o=m("@braintree/asset-loader"),h=m("../../translations").fiveCharacterLocales,s=m("../../lib/promise"),l=["offerCredit","locale"];function d(){e.apply(this,arguments)}(d.prototype=Object.create(e.prototype)).initialize=function(){var a,o=Boolean(this._isPayPalCredit),s=!1,l=this,e=o?"paypalCredit":"paypal",t=this.model.merchantConfiguration[e];return this.paypalConfiguration=r({},t),this.model.asyncDependencyStarting(),a=setTimeout(function(){l.model.asyncDependencyFailed({view:l.ID,error:new u("There was an error connecting to PayPal.")})},3e4),p.create({client:this.client}).then(function(t){var e,i='[data-braintree-id="paypal-button"]',r="production"===l.client.getConfiguration().gatewayConfiguration.environment?"production":"sandbox",n=l.model.merchantConfiguration.locale;return l.paypalInstance=t,l.paypalConfiguration.offerCredit=Boolean(o),e={env:r,style:l.paypalConfiguration.buttonStyle||{},commit:l.paypalConfiguration.commit,payment:function(){return t.createPayment(l.paypalConfiguration).catch(d)},onAuthorize:function(e){return t.tokenizePayment(e).then(function(e){"vault"!==l.paypalConfiguration.flow||l.model.isGuestCheckout||(e.vaulted=!0),l.model.addPaymentMethod(e)}).catch(d)},onError:d},n&&n in h&&(l.paypalConfiguration.locale=n,e.locale=n),o?(i='[data-braintree-id="paypal-credit-button"]',e.style.label="credit"):e.funding={disallowed:[c.paypal.FUNDING.CREDIT]},c.paypal.Button.render(e,i).then(function(){l.model.asyncDependencyReady(),s=!0,clearTimeout(a)})}).catch(d);function d(e){s?l.model.reportError(e):(l.model.asyncDependencyFailed({view:l.ID,error:e}),clearTimeout(a))}},d.prototype.updateConfiguration=function(e,t){-1===l.indexOf(e)&&(this.paypalConfiguration[e]=t)},d.isEnabled=function(e){return e.client.getConfiguration().gatewayConfiguration.paypalEnabled?n.isIe9()||n.isIe10()?(i.sendEvent(e.client,e.viewID+".checkout.js-browser-not-supported"),s.resolve(!1)):c.paypal&&c.paypal.Button?s.resolve(!0):t||(t=o.loadScript({src:a.CHECKOUT_JS_SOURCE,id:a.PAYPAL_CHECKOUT_SCRIPT_ID,dataAttributes:{"log-level":e.merchantConfiguration.paypal.logLevel||"warn"}}).then(function(){return s.resolve(!0)}).catch(function(){return s.resolve(!1)}).then(function(e){return t=null,s.resolve(e)})):s.resolve(!1)},y.exports=d}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../constants":125,"../../lib/analytics":130,"../../lib/assign":131,"../../lib/browser-detection":132,"../../lib/dropin-error":135,"../../lib/promise":143,"../../translations":158,"../base-view":173,"@braintree/asset-loader":1,"braintree-web/paypal-checkout":101}],181:[function(e,t,i){"use strict";var o=e("../../lib/assign").assign,r=e("../base-view"),s=e("@braintree/class-list"),a=e("../../constants"),n=e("../../lib/dropin-error"),l=e("braintree-web/hosted-fields"),d=e("../../lib/is-utf-8"),c=e("../../lib/transition-helper"),p=e("../../lib/promise");function u(){r.apply(this,arguments)}function h(e){return-1!==e.id.indexOf("braintree__card-view-input")}function m(e){return e.isEmpty&&y()}function y(){var e=document.activeElement&&document.activeElement.id;return document.activeElement instanceof HTMLIFrameElement&&-1!==e.indexOf("braintree-hosted-field")||h(document.activeElement)}function f(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function g(e){return e[0].toUpperCase()+e.substr(1)}function v(e){var t=d()?"•":"*";return Array(e+1).join(t)}((u.prototype=Object.create(r.prototype)).constructor=u).ID=u.prototype.ID=a.paymentOptionIDs.card,u.prototype.initialize=function(){var e,t,i=this.getElementById("cardholder-name-field-group"),r=this.getElementById("card-view-icons"),n=this._generateHostedFieldsOptions();return r.innerHTML='<div data-braintree-id="visa-card-icon" class="braintree-sheet__card-icon">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-visa"></use>\n    </svg>\n</div>\n<div data-braintree-id="master-card-card-icon" class="braintree-sheet__card-icon">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-master-card"></use>\n    </svg>\n</div>\n<div data-braintree-id="unionpay-card-icon" class="braintree-sheet__card-icon braintree-hidden">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-unionpay"></use>\n    </svg>\n</div>\n<div data-braintree-id="american-express-card-icon" class="braintree-sheet__card-icon">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-american-express"></use>\n    </svg>\n</div>\n<div data-braintree-id="jcb-card-icon" class="braintree-sheet__card-icon">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-jcb"></use>\n    </svg>\n</div>\n\x3c!-- Remove braintree-hidden class when supportedCardType accurately indicates Diners Club support --\x3e\n<div data-braintree-id="diners-club-card-icon" class="braintree-sheet__card-icon braintree-hidden">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-diners-club"></use>\n    </svg>\n</div>\n<div data-braintree-id="discover-card-icon" class="braintree-sheet__card-icon">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-discover"></use>\n    </svg>\n</div>\n<div data-braintree-id="maestro-card-icon" class="braintree-sheet__card-icon">\n    <svg width="40" height="24">\n        <use xlink:href="#icon-maestro"></use>\n    </svg>\n</div>\n',this._hideUnsupportedCardIcons(),this.hasCVV=n.fields.cvv,this.hasCardholderName=Boolean(this.model.merchantConfiguration.card&&this.model.merchantConfiguration.card.cardholderName),this.cardholderNameInput=i.querySelector("input"),this.cardNumberIcon=this.getElementById("card-number-icon"),this.cardNumberIconSvg=this.getElementById("card-number-icon-svg"),this.cvvIcon=this.getElementById("cvv-icon"),this.cvvIconSvg=this.getElementById("cvv-icon-svg"),this.cvvLabelDescriptor=this.getElementById("cvv-label-descriptor"),this.fieldErrors={},this.extraInputs=[{fieldName:"cardholderName",enabled:this.hasCardholderName,required:this.hasCardholderName&&this.model.merchantConfiguration.card.cardholderName.required,requiredError:this.strings.fieldEmptyForCardholderName,validations:[{isValid:function(e){return e.length<256},error:this.strings.fieldTooLongForCardholderName}]}],this.hasCVV||(e=this.getElementById("cvv-field-group")).parentNode.removeChild(e),n.fields.postalCode||(t=this.getElementById("postal-code-field-group")).parentNode.removeChild(t),this.extraInputs.forEach(function(e){e.enabled?this._setupExtraInput(e):this._removeExtraInput(e)}.bind(this)),this.model.asyncDependencyStarting(),l.create(n).then(function(e){this.hostedFieldsInstance=e,this.hostedFieldsInstance.on("blur",this._onBlurEvent.bind(this)),this.hostedFieldsInstance.on("cardTypeChange",this._onCardTypeChangeEvent.bind(this)),this.hostedFieldsInstance.on("focus",this._onFocusEvent.bind(this)),this.hostedFieldsInstance.on("notEmpty",this._onNotEmptyEvent.bind(this)),this.hostedFieldsInstance.on("validityChange",this._onValidityChangeEvent.bind(this)),this.model.asyncDependencyReady()}.bind(this)).catch(function(e){this.model.asyncDependencyFailed({view:this.ID,error:e})}.bind(this))},u.prototype._setupExtraInput=function(t){var i=this,e=f(t.fieldName),r=this.getElementById(e+"-field-group"),n=r.querySelector("input"),a=r.querySelector(".braintree-form__hosted-field");n.addEventListener("keyup",function(){var e=i._validateExtraInput(t,!0);s.toggle(a,"braintree-form__field--valid",e),e&&i.hideFieldError(t.fieldName),i._sendRequestableEvent()},!1),t.required&&n.addEventListener("blur",function(){setTimeout(function(){y()&&i._validateExtraInput(t,!0)},0)},!1)},u.prototype._removeExtraInput=function(e){var t=this.getElementById(f(e.fieldName)+"-field-group");t.parentNode.removeChild(t)},u.prototype._sendRequestableEvent=function(){this._isTokenizing||this.model.setPaymentMethodRequestable({isRequestable:this._validateForm(),type:a.paymentMethodTypes.card})},u.prototype._generateHostedFieldsOptions=function(){var e,t=this.client.getConfiguration().gatewayConfiguration.challenges,i=-1!==t.indexOf("cvv"),r=-1!==t.indexOf("postal_code"),n=this.model.merchantConfiguration.card&&this.model.merchantConfiguration.card.overrides,a={client:this.client,fields:{number:{selector:this._generateFieldSelector("number"),placeholder:(e=v(4),[e,e,e,e].join(" "))},expirationDate:{selector:this._generateFieldSelector("expiration"),placeholder:this.strings.expirationDatePlaceholder},cvv:{selector:this._generateFieldSelector("cvv"),placeholder:v(3)},postalCode:{selector:this._generateFieldSelector("postal-code")}},styles:{input:{"font-size":"16px","font-family":'-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif',color:"#000"},":focus":{color:"black"},"::-webkit-input-placeholder":{color:"#6a6a6a"},":-moz-placeholder":{color:"#6a6a6a"},"::-moz-placeholder":{color:"#6a6a6a"},":-ms-input-placeholder ":{color:"#6a6a6a"},"input::-ms-clear":{color:"transparent"}}};return i||delete a.fields.cvv,r||delete a.fields.postalCode,n&&(n.fields&&(n.fields.cvv&&n.fields.cvv.placeholder&&(this._hasCustomCVVPlaceholder=!0),Object.keys(n.fields).forEach(function(e){"cvv"!==e&&"postalCode"!==e||null!==n.fields[e]?a.fields[e]&&o(a.fields[e],n.fields[e],{selector:a.fields[e].selector}):delete a.fields[e]})),n.styles&&Object.keys(n.styles).forEach(function(e){var i;null!==n.styles[e]?(i=n.styles[e],Object.keys(i).forEach(function(e){var t=f(e);i[t]=i[e]}),a.styles[e]=a.styles[e]||{},o(a.styles[e],n.styles[e])):delete a.styles[e]})),a},u.prototype._validateForm=function(i){var e,r,n=!0,t=this.client.getConfiguration().gatewayConfiguration.creditCards.supportedCardTypes;return!!this.hostedFieldsInstance&&(r=this.hostedFieldsInstance.getState(),Object.keys(r.fields).forEach(function(e){var t=r.fields[e];(i||n)&&(t.isEmpty?(n=!1,i&&this.showFieldError(e,this.strings["fieldEmptyFor"+g(e)])):t.isValid||(n=!1,i&&this.showFieldError(e,this.strings["fieldInvalidFor"+g(e)])))}.bind(this)),r.fields.number.isValid&&(e=a.configurationCardTypes[r.cards[0].type],-1!==t.indexOf(e)||(n=!1,i&&this.showFieldError("number",this.strings.unsupportedCardTypeError))),this.extraInputs&&this.extraInputs.forEach(function(e){var t;e.enabled&&(t=this._validateExtraInput(e,i),n=n&&t)}.bind(this)),n)},u.prototype._validateExtraInput=function(i,r){var e=f(i.fieldName),n=this.getElementById(e+"-field-group").querySelector("input"),a=!0;return i.required&&!(a=0<n.value.length)&&r&&this.showFieldError(i.fieldName,i.requiredError),i.validations.forEach(function(e){var t=e.isValid(n.value);!t&&r&&this.showFieldError(i.fieldName,e.error),a=a&&t}.bind(this)),a},u.prototype.getPaymentMethod=function(){if(this._validateForm())return{type:a.paymentMethodTypes.card}},u.prototype.tokenize=function(){var i,r=this,e=r.hostedFieldsInstance.getState(),t={vault:!r.model.isGuestCheckout};return this.model.clearError(),this._validateForm(!0)?(this.hasCardholderName&&(t.cardholderName=this.cardholderNameInput.value),r._isTokenizing=!0,r.hostedFieldsInstance.tokenize(t).then(function(t){return r.model.merchantConfiguration.card&&!1===r.model.merchantConfiguration.card.clearFieldsAfterTokenization||(Object.keys(e.fields).forEach(function(e){r.hostedFieldsInstance.clear(e)}),r.hasCardholderName&&(r.cardholderNameInput.value="")),r.model.isGuestCheckout||(t.vaulted=!0),new p(function(e){i=function(){setTimeout(function(){r.model.addPaymentMethod(t),e(t),s.remove(r.element,"braintree-sheet--tokenized")},0)},c.onTransitionEnd(r.element,"max-height",i),setTimeout(function(){r.allowUserAction(),r._isTokenizing=!1},a.CHANGE_ACTIVE_PAYMENT_METHOD_TIMEOUT),s.add(r.element,"braintree-sheet--tokenized")})}).catch(function(e){return r._isTokenizing=!1,r.model.reportError(e),r.allowUserAction(),p.reject(new n({message:a.errors.NO_PAYMENT_METHOD_ERROR,braintreeWebError:e}))})):(r.model.reportError("hostedFieldsFieldsInvalidError"),r.allowUserAction(),p.reject(new n(a.errors.NO_PAYMENT_METHOD_ERROR)))},u.prototype.showFieldError=function(e,t){var i=this.getElementById(f(e)+"-field-group"),r=i.querySelector("input");this.fieldErrors.hasOwnProperty(e)||(this.fieldErrors[e]=this.getElementById(f(e)+"-field-error")),s.add(i,"braintree-form__field-group--has-error"),this.fieldErrors[e].innerHTML=t,r&&h(r)?r.setAttribute("aria-invalid",!0):(this.hostedFieldsInstance.setAttribute({field:e,attribute:"aria-invalid",value:!0}),this.hostedFieldsInstance.setMessage({field:e,message:t}))},u.prototype.hideFieldError=function(e){var t=this.getElementById(f(e)+"-field-group"),i=t.querySelector("input");this.fieldErrors.hasOwnProperty(e)||(this.fieldErrors[e]=this.getElementById(f(e)+"-field-error")),s.remove(t,"braintree-form__field-group--has-error"),i&&h(i)?i.removeAttribute("aria-invalid"):(this.hostedFieldsInstance.removeAttribute({field:e,attribute:"aria-invalid"}),this.hostedFieldsInstance.setMessage({field:e,message:""}))},u.prototype.teardown=function(){return this.hostedFieldsInstance.teardown()},u.prototype._generateFieldSelector=function(e){return"#braintree--dropin__"+this.model.componentID+" .braintree-form-"+e},u.prototype._onBlurEvent=function(e){var t=e.fields[e.emittedBy],i=this.getElementById(f(e.emittedBy)+"-field-group");s.remove(i,"braintree-form__field-group--is-focused"),m(t)?this.showFieldError(e.emittedBy,this.strings["fieldEmptyFor"+g(e.emittedBy)]):t.isEmpty||t.isValid?"number"!==e.emittedBy||this._isCardTypeSupported(e.cards[0].type)||this.showFieldError("number",this.strings.unsupportedCardTypeError):this.showFieldError(e.emittedBy,this.strings["fieldInvalidFor"+g(e.emittedBy)]),setTimeout(function(){m(t)&&this.showFieldError(e.emittedBy,this.strings["fieldEmptyFor"+g(e.emittedBy)])}.bind(this),150)},u.prototype._onCardTypeChangeEvent=function(e){var t,i="#iconCardFront",r="#iconCVVBack",n=this.strings.cvvThreeDigitLabelSubheading,a=v(3),o=this.getElementById("number-field-group");1===e.cards.length?(i="#icon-"+(t=e.cards[0].type),"american-express"===t&&(r="#iconCVVFront",n=this.strings.cvvFourDigitLabelSubheading,a=v(4)),s.add(o,"braintree-form__field-group--card-type-known")):s.remove(o,"braintree-form__field-group--card-type-known"),this.cardNumberIconSvg.setAttribute("xlink:href",i),this.hasCVV&&(this.cvvIconSvg.setAttribute("xlink:href",r),this.cvvLabelDescriptor.innerHTML=n,this._hasCustomCVVPlaceholder||this.hostedFieldsInstance.setAttribute({field:"cvv",attribute:"placeholder",value:a}))},u.prototype._onFocusEvent=function(e){var t=this.getElementById(f(e.emittedBy)+"-field-group");s.add(t,"braintree-form__field-group--is-focused")},u.prototype._onNotEmptyEvent=function(e){this.hideFieldError(e.emittedBy)},u.prototype._onValidityChangeEvent=function(e){var t,i=e.fields[e.emittedBy];t="number"===e.emittedBy&&e.cards[0]?i.isValid&&this._isCardTypeSupported(e.cards[0].type):i.isValid,s.toggle(i.container,"braintree-form__field--valid",t),i.isPotentiallyValid&&this.hideFieldError(e.emittedBy),this._sendRequestableEvent()},u.prototype.requestPaymentMethod=function(){return this.preventUserAction(),this.tokenize()},u.prototype.onSelection=function(){this.hostedFieldsInstance&&(this.hasCardholderName?setTimeout(function(){this.cardholderNameInput.focus()}.bind(this),1):this.hostedFieldsInstance.focus("number"))},u.prototype._hideUnsupportedCardIcons=function(){var r=this.client.getConfiguration().gatewayConfiguration.creditCards.supportedCardTypes;Object.keys(a.configurationCardTypes).forEach(function(e){var t,i=a.configurationCardTypes[e];-1===r.indexOf(i)&&(t=this.getElementById(e+"-card-icon"),s.add(t,"braintree-hidden"))}.bind(this))},u.prototype._isCardTypeSupported=function(e){var t=a.configurationCardTypes[e];return-1!==this.client.getConfiguration().gatewayConfiguration.creditCards.supportedCardTypes.indexOf(t)},u.isEnabled=function(e){var t=e.client.getConfiguration().gatewayConfiguration;return p.resolve(0<t.creditCards.supportedCardTypes.length)},t.exports=u},{"../../constants":125,"../../lib/assign":131,"../../lib/dropin-error":135,"../../lib/is-utf-8":140,"../../lib/promise":143,"../../lib/transition-helper":147,"../base-view":173,"@braintree/class-list":18,"braintree-web/hosted-fields":60}],182:[function(p,u,e){(function(t){"use strict";var n=p("../../lib/assign").assign,e=p("../base-view"),a=p("braintree-web/google-payment"),o=p("../../lib/dropin-error"),i=p("../../constants"),r=p("@braintree/asset-loader"),s=p("../../lib/promise"),l=p("../../lib/analytics");function d(){e.apply(this,arguments)}function c(e){return new t.google.payments.api.PaymentsClient({environment:"production"===e.getConfiguration().gatewayConfiguration.environment?"PRODUCTION":"TEST"})}((d.prototype=Object.create(e.prototype)).constructor=d).ID=d.prototype.ID=i.paymentOptionIDs.googlePay,d.prototype.initialize=function(){var e,t,i,r=this;return r.googlePayConfiguration=n({},r.model.merchantConfiguration.googlePay),t=r.googlePayConfiguration.googlePayVersion,i=r.googlePayConfiguration.merchantId,delete r.googlePayConfiguration.googlePayVersion,delete r.googlePayConfiguration.merchantId,e=n({buttonType:"short"},r.googlePayConfiguration.button,{onClick:function(e){e.preventDefault(),r.preventUserAction(),r.tokenize().then(function(){r.allowUserAction()})}}),r.model.asyncDependencyStarting(),a.create({client:r.client,googlePayVersion:t,googleMerchantId:i}).then(function(e){r.googlePayInstance=e,r.paymentsClient=c(r.client)}).then(function(){r.getElementById("google-pay-button").appendChild(r.paymentsClient.createButton(e)),r.model.asyncDependencyReady()}).catch(function(e){r.model.asyncDependencyFailed({view:r.ID,error:new o(e)})})},d.prototype.tokenize=function(){var t,i=this,e=i.googlePayInstance.createPaymentDataRequest(i.googlePayConfiguration);return i.paymentsClient.loadPaymentData(e).then(function(e){return t=e,i.googlePayInstance.parseResponse(e)}).then(function(e){e.rawPaymentData=t,i.model.addPaymentMethod(e)}).catch(function(e){var t=e;if("DEVELOPER_ERROR"===e.statusCode)console.error(e),t="developerError";else{if("CANCELED"===e.statusCode)return void l.sendEvent(i.client,"googlepay.loadPaymentData.canceled");e.statusCode&&l.sendEvent(i.client,"googlepay.loadPaymentData.failed")}i.model.reportError(t)})},d.prototype.updateConfiguration=function(e,t){this.googlePayConfiguration[e]=t},d.isEnabled=function(e){return e.client.getConfiguration().gatewayConfiguration.androidPay&&Boolean(e.merchantConfiguration.googlePay)?s.resolve().then(function(){return t.google&&t.google.payments&&t.google.payments.api&&t.google.payments.api.PaymentsClient?s.resolve():r.loadScript({id:i.GOOGLE_PAYMENT_SCRIPT_ID,src:i.GOOGLE_PAYMENT_SOURCE})}).then(function(){return c(e.client).isReadyToPay({allowedPaymentMethods:["CARD","TOKENIZED_CARD"]})}).then(function(e){return Boolean(e.result)}):s.resolve(!1)},u.exports=d}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../constants":125,"../../lib/analytics":130,"../../lib/assign":131,"../../lib/dropin-error":135,"../../lib/promise":143,"../base-view":173,"@braintree/asset-loader":1,"braintree-web/google-payment":54}],183:[function(e,t,i){"use strict";var r=e("../../constants").paymentOptionIDs,n={};n[r.applePay]=e("./apple-pay-view"),n[r.card]=e("./card-view"),n[r.googlePay]=e("./google-pay-view"),n[r.paypal]=e("./paypal-view"),n[r.paypalCredit]=e("./paypal-credit-view"),n[r.venmo]=e("./venmo-view"),t.exports=n},{"../../constants":125,"./apple-pay-view":179,"./card-view":181,"./google-pay-view":182,"./paypal-credit-view":184,"./paypal-view":185,"./venmo-view":186}],184:[function(e,t,i){"use strict";var r=e("../../lib/assign").assign,n=e("../../lib/promise"),a=e("../../constants").paymentOptionIDs,o=e("./base-paypal-view");function s(){o.apply(this,arguments),this._isPayPalCredit=!0}((s.prototype=Object.create(o.prototype)).constructor=s).ID=s.prototype.ID=a.paypalCredit,s.isEnabled=function(e){return e.merchantConfiguration.paypalCredit?o.isEnabled(r({viewID:s.ID},e)):n.resolve(!1)},t.exports=s},{"../../constants":125,"../../lib/assign":131,"../../lib/promise":143,"./base-paypal-view":180}],185:[function(e,t,i){"use strict";var r=e("../../lib/assign").assign,n=e("../../lib/promise"),a=e("../../constants").paymentOptionIDs,o=e("./base-paypal-view");function s(){o.apply(this,arguments)}((s.prototype=Object.create(o.prototype)).constructor=s).ID=s.prototype.ID=a.paypal,s.isEnabled=function(e){return e.merchantConfiguration.paypal?o.isEnabled(r({viewID:s.ID},e)):n.resolve(!1)},t.exports=s},{"../../constants":125,"../../lib/assign":131,"../../lib/promise":143,"./base-paypal-view":180}],186:[function(e,t,i){"use strict";var r=e("../../lib/assign").assign,n=e("../base-view"),a=e("braintree-web/venmo"),o=e("../../lib/dropin-error"),s=e("../../lib/promise"),l=e("../../constants").paymentOptionIDs;function d(){n.apply(this,arguments)}((d.prototype=Object.create(n.prototype)).constructor=d).ID=d.prototype.ID=l.venmo,d.prototype.initialize=function(){var t=this,e=r({},t.model.merchantConfiguration.venmo,{client:this.client});return t.model.asyncDependencyStarting(),a.create(e).then(function(e){return t.venmoInstance=e,t.venmoInstance.hasTokenizationResult()?t.venmoInstance.tokenize().then(function(e){t.model.reportAppSwitchPayload(e)}).catch(function(e){t._isIgnorableError(e)||t.model.reportAppSwitchError(l.venmo,e)}):s.resolve()}).then(function(){t.getElementById("venmo-button").addEventListener("click",function(e){return e.preventDefault(),t.preventUserAction(),t.venmoInstance.tokenize().then(function(e){t.model.addPaymentMethod(e)}).catch(function(e){t._isIgnorableError(e)||t.model.reportError(e)}).then(function(){t.allowUserAction()})}),t.model.asyncDependencyReady()}).catch(function(e){t.model.asyncDependencyFailed({view:t.ID,error:new o(e)})})},d.prototype._isIgnorableError=function(e){return"VENMO_APP_CANCELED"===e.code},d.isEnabled=function(e){return e.client.getConfiguration().gatewayConfiguration.payWithVenmo&&Boolean(e.merchantConfiguration.venmo)?s.resolve(a.isBrowserSupported(e.merchantConfiguration.venmo)):s.resolve(!1)},t.exports=d},{"../../constants":125,"../../lib/assign":131,"../../lib/dropin-error":135,"../../lib/promise":143,"../base-view":173,"braintree-web/venmo":112}]},{},[128])(128)});;
