/*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}S.fn=S.prototype={jquery:f,constructor:S,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=S.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return S.each(this,e)},map:function(n){return this.pushStack(S.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(S.grep(this,function(e,t){return(t+1)%2}))},odd:function(){return this.pushStack(S.grep(this,function(e,t){return t%2}))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},S.extend=S.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||m(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(S.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||S.isPlainObject(n)?n:{},i=!1,a[t]=S.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},S.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=v.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t,n){b(e,{nonce:t&&t.nonce},n)},each:function(e,t){var n,r=0;if(p(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},makeArray:function(e,t){var n=t||[];return null!=e&&(p(Object(e))?S.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(p(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g(a)},guid:1,support:y}),"function"==typeof Symbol&&(S.fn[Symbol.iterator]=t[Symbol.iterator]),S.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var d=function(n){var e,d,b,o,i,h,f,g,w,u,l,T,C,a,E,v,s,c,y,S="sizzle"+1*new Date,p=n.document,k=0,r=0,m=ue(),x=ue(),A=ue(),N=ue(),j=function(e,t){return e===t&&(l=!0),0},D={}.hasOwnProperty,t=[],q=t.pop,L=t.push,H=t.push,O=t.slice,P=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",I="(?:\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",W="\\["+M+"*("+I+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+I+"))|)"+M+"*\\]",F=":("+I+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+W+")*)|.*)\\)|)",B=new RegExp(M+"+","g"),$=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=new RegExp("^"+M+"*,"+M+"*"),z=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="<a id='"+S+"'></a><select id='"+S+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0<se(t,C,null,[e]).length},se.contains=function(e,t){return(e.ownerDocument||e)!=C&&T(e),y(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!=C&&T(e);var n=b.attrHandle[t.toLowerCase()],r=n&&D.call(b.attrHandle,t.toLowerCase())?n(e,t,!E):void 0;return void 0!==r?r:d.attributes||!E?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},se.escape=function(e){return(e+"").replace(re,ie)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],r=0,i=0;if(l=!d.detectDuplicates,u=!d.sortStable&&e.slice(0),e.sort(j),l){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return u=null,e},o=se.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else while(t=e[r++])n+=o(t);return n},(b=se.selectors={cacheLength:50,createPseudo:le,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace(B," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(h,e,t,g,v){var y="nth"!==h.slice(0,3),m="last"!==h.slice(-4),x="of-type"===e;return 1===g&&0===v?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u,l=y!==m?"nextSibling":"previousSibling",c=e.parentNode,f=x&&e.nodeName.toLowerCase(),p=!n&&!x,d=!1;if(c){if(y){while(l){a=e;while(a=a[l])if(x?a.nodeName.toLowerCase()===f:1===a.nodeType)return!1;u=l="only"===h&&!u&&"nextSibling"}return!0}if(u=[m?c.firstChild:c.lastChild],m&&p){d=(s=(r=(i=(o=(a=c)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1])&&r[2],a=s&&c.childNodes[s];while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if(1===a.nodeType&&++d&&a===e){i[h]=[k,s,d];break}}else if(p&&(d=s=(r=(i=(o=(a=e)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1]),!1===d)while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if((x?a.nodeName.toLowerCase()===f:1===a.nodeType)&&++d&&(p&&((i=(o=a[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]=[k,d]),a===e))break;return(d-=v)===g||d%g==0&&0<=d/g}}},PSEUDO:function(e,o){var t,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return a[S]?a(o):1<a.length?(t=[e,e,"",o],b.setFilters.hasOwnProperty(e.toLowerCase())?le(function(e,t){var n,r=a(e,o),i=r.length;while(i--)e[n=P(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:le(function(e){var r=[],i=[],s=f(e.replace($,"$1"));return s[S]?le(function(e,t,n,r){var i,o=s(e,null,r,[]),a=e.length;while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:le(function(t){return function(e){return 0<se(t,e).length}}),contains:le(function(t){return t=t.replace(te,ne),function(e){return-1<(e.textContent||o(e)).indexOf(t)}}),lang:le(function(n){return V.test(n||"")||se.error("unsupported lang: "+n),n=n.replace(te,ne).toLowerCase(),function(e){var t;do{if(t=E?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===a},focus:function(e){return e===C.activeElement&&(!C.hasFocus||C.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:ge(!1),disabled:ge(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!b.pseudos.empty(e)},header:function(e){return J.test(e.nodeName)},input:function(e){return Q.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:ve(function(){return[0]}),last:ve(function(e,t){return[t-1]}),eq:ve(function(e,t,n){return[n<0?n+t:n]}),even:ve(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:ve(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:ve(function(e,t,n){for(var r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:ve(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=b.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[e]=de(e);for(e in{submit:!0,reset:!0})b.pseudos[e]=he(e);function me(){}function xe(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function be(s,e,t){var u=e.dir,l=e.next,c=l||u,f=t&&"parentNode"===c,p=r++;return e.first?function(e,t,n){while(e=e[u])if(1===e.nodeType||f)return s(e,t,n);return!1}:function(e,t,n){var r,i,o,a=[k,p];if(n){while(e=e[u])if((1===e.nodeType||f)&&s(e,t,n))return!0}else while(e=e[u])if(1===e.nodeType||f)if(i=(o=e[S]||(e[S]={}))[e.uniqueID]||(o[e.uniqueID]={}),l&&l===e.nodeName.toLowerCase())e=e[u]||e;else{if((r=i[c])&&r[0]===k&&r[1]===p)return a[2]=r[2];if((i[c]=a)[2]=s(e,t,n))return!0}return!1}}function we(i){return 1<i.length?function(e,t,n){var r=i.length;while(r--)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Te(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Ce(d,h,g,v,y,e){return v&&!v[S]&&(v=Ce(v)),y&&!y[S]&&(y=Ce(y,e)),le(function(e,t,n,r){var i,o,a,s=[],u=[],l=t.length,c=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)se(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),f=!d||!e&&h?c:Te(c,s,d,n,r),p=g?y||(e?d:l||v)?[]:t:f;if(g&&g(f,p,n,r),v){i=Te(p,u),v(i,[],n,r),o=i.length;while(o--)(a=i[o])&&(p[u[o]]=!(f[u[o]]=a))}if(e){if(y||d){if(y){i=[],o=p.length;while(o--)(a=p[o])&&i.push(f[o]=a);y(null,p=[],i,r)}o=p.length;while(o--)(a=p[o])&&-1<(i=y?P(e,a):s[o])&&(e[i]=!(t[i]=a))}}else p=Te(p===t?p.splice(l,p.length):p),y?y(null,t,p,r):H.apply(t,p)})}function Ee(e){for(var i,t,n,r=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,u=be(function(e){return e===i},a,!0),l=be(function(e){return-1<P(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!==w)||((i=t).nodeType?u(e,t,n):l(e,t,n));return i=null,r}];s<r;s++)if(t=b.relative[e[s].type])c=[be(we(c),t)];else{if((t=b.filter[e[s].type].apply(null,e[s].matches))[S]){for(n=++s;n<r;n++)if(b.relative[e[n].type])break;return Ce(1<s&&we(c),1<s&&xe(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace($,"$1"),t,s<n&&Ee(e.slice(s,n)),n<r&&Ee(e=e.slice(n)),n<r&&xe(e))}c.push(t)}return we(c)}return me.prototype=b.filters=b.pseudos,b.setFilters=new me,h=se.tokenize=function(e,t){var n,r,i,o,a,s,u,l=x[e+" "];if(l)return t?0:l.slice(0);a=e,s=[],u=b.preFilter;while(a){for(o in n&&!(r=_.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=z.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace($," ")}),a=a.slice(n.length)),b.filter)!(r=G[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?se.error(e):x(e,s).slice(0)},f=se.compile=function(e,t){var n,v,y,m,x,r,i=[],o=[],a=A[e+" "];if(!a){t||(t=h(e)),n=t.length;while(n--)(a=Ee(t[n]))[S]?i.push(a):o.push(a);(a=A(e,(v=o,m=0<(y=i).length,x=0<v.length,r=function(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],p=w,d=e||x&&b.find.TAG("*",i),h=k+=null==p?1:Math.random()||.1,g=d.length;for(i&&(w=t==C||t||i);l!==g&&null!=(o=d[l]);l++){if(x&&o){a=0,t||o.ownerDocument==C||(T(o),n=!E);while(s=v[a++])if(s(o,t||C,n)){r.push(o);break}i&&(k=h)}m&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,m&&l!==u){a=0;while(s=y[a++])s(c,f,t,n);if(e){if(0<u)while(l--)c[l]||f[l]||(f[l]=q.call(r));f=Te(f)}H.apply(r,f),i&&!e&&0<f.length&&1<u+y.length&&se.uniqueSort(r)}return i&&(k=h,w=p),c},m?le(r):r))).selector=e}return a},g=se.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&h(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&E&&b.relative[o[1].type]){if(!(t=(b.find.ID(a.matches[0].replace(te,ne),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}i=G.needsContext.test(e)?0:o.length;while(i--){if(a=o[i],b.relative[s=a.type])break;if((u=b.find[s])&&(r=u(a.matches[0].replace(te,ne),ee.test(o[0].type)&&ye(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&xe(o)))return H.apply(n,r),n;break}}}return(l||f(e,c))(r,t,!E,n,!t||ee.test(e)&&ye(t.parentNode)||t),n},d.sortStable=S.split("").sort(j).join("")===S,d.detectDuplicates=!!l,T(),d.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(C.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),d.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||fe(R,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),se}(C);S.find=d,S.expr=d.selectors,S.expr[":"]=S.expr.pseudos,S.uniqueSort=S.unique=d.uniqueSort,S.text=d.getText,S.isXMLDoc=d.isXML,S.contains=d.contains,S.escapeSelector=d.escape;var h=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&S(e).is(n))break;r.push(e)}return r},T=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},k=S.expr.match.needsContext;function A(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var N=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1<i.call(n,e)!==r}):S.filter(n,e,r)}S.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?S.find.matchesSelector(r,e)?[r]:[]:S.find.matches(e,S.grep(t,function(e){return 1===e.nodeType}))},S.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(S(e).filter(function(){for(t=0;t<r;t++)if(S.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)S.find(e,i[t],n);return 1<r?S.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&k.test(e)?S(e):e||[],!1).length}});var D,q=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(S.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&S(e);if(!k.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&S.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?S.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?i.call(S(e),this[0]):i.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(S.uniqueSort(S.merge(this.get(),S(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),S.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return h(e,"parentNode")},parentsUntil:function(e,t,n){return h(e,"parentNode",n)},next:function(e){return O(e,"nextSibling")},prev:function(e){return O(e,"previousSibling")},nextAll:function(e){return h(e,"nextSibling")},prevAll:function(e){return h(e,"previousSibling")},nextUntil:function(e,t,n){return h(e,"nextSibling",n)},prevUntil:function(e,t,n){return h(e,"previousSibling",n)},siblings:function(e){return T((e.parentNode||{}).firstChild,e)},children:function(e){return T(e.firstChild)},contents:function(e){return null!=e.contentDocument&&r(e.contentDocument)?e.contentDocument:(A(e,"template")&&(e=e.content||e),S.merge([],e.childNodes))}},function(r,i){S.fn[r]=function(e,t){var n=S.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=S.filter(t,n)),1<this.length&&(H[r]||S.uniqueSort(n),L.test(r)&&n.reverse()),this.pushStack(n)}});var P=/[^\x20\t\r\n\f]+/g;function R(e){return e}function M(e){throw e}function I(e,t,n,r){var i;try{e&&m(i=e.promise)?i.call(e).done(t).fail(n):e&&m(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}S.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},S.each(e.match(P)||[],function(e,t){n[t]=!0}),n):S.extend({},r);var i,t,o,a,s=[],u=[],l=-1,c=function(){for(a=a||r.once,o=i=!0;u.length;l=-1){t=u.shift();while(++l<s.length)!1===s[l].apply(t[0],t[1])&&r.stopOnFalse&&(l=s.length,t=!1)}r.memory||(t=!1),i=!1,a&&(s=t?[]:"")},f={add:function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){S.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this},remove:function(){return S.each(arguments,function(e,t){var n;while(-1<(n=S.inArray(t,s,n)))s.splice(n,1),n<=l&&l--}),this},has:function(e){return e?-1<S.inArray(e,s):0<s.length},empty:function(){return s&&(s=[]),this},disable:function(){return a=u=[],s=t="",this},disabled:function(){return!s},lock:function(){return a=u=[],t||i||(s=t=""),this},locked:function(){return!!a},fireWith:function(e,t){return a||(t=[e,(t=t||[]).slice?t.slice():t],u.push(t),i||c()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},S.extend({Deferred:function(e){var o=[["notify","progress",S.Callbacks("memory"),S.Callbacks("memory"),2],["resolve","done",S.Callbacks("once memory"),S.Callbacks("once memory"),0,"resolved"],["reject","fail",S.Callbacks("once memory"),S.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},"catch":function(e){return a.then(null,e)},pipe:function(){var i=arguments;return S.Deferred(function(r){S.each(o,function(e,t){var n=m(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&m(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,m(t)?s?t.call(e,l(u,o,R,s),l(u,o,M,s)):(u++,t.call(e,l(u,o,R,s),l(u,o,M,s),l(u,o,R,o.notifyWith))):(a!==R&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){S.Deferred.exceptionHook&&S.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==M&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(S.Deferred.getStackHook&&(t.stackTrace=S.Deferred.getStackHook()),C.setTimeout(t))}}return S.Deferred(function(e){o[0][3].add(l(0,e,m(r)?r:R,e.notifyWith)),o[1][3].add(l(0,e,m(t)?t:R)),o[2][3].add(l(0,e,m(n)?n:M))}).promise()},promise:function(e){return null!=e?S.extend(e,a):a}},s={};return S.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){var n=arguments.length,t=n,r=Array(t),i=s.call(arguments),o=S.Deferred(),a=function(t){return function(e){r[t]=this,i[t]=1<arguments.length?s.call(arguments):e,--n||o.resolveWith(r,i)}};if(n<=1&&(I(e,o.done(a(t)).resolve,o.reject,!n),"pending"===o.state()||m(i[t]&&i[t].then)))return o.then();while(t--)I(i[t],a(t),o.reject);return o.promise()}});var W=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;S.Deferred.exceptionHook=function(e,t){C.console&&C.console.warn&&e&&W.test(e.name)&&C.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},S.readyException=function(e){C.setTimeout(function(){throw e})};var F=S.Deferred();function B(){E.removeEventListener("DOMContentLoaded",B),C.removeEventListener("load",B),S.ready()}S.fn.ready=function(e){return F.then(e)["catch"](function(e){S.readyException(e)}),this},S.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--S.readyWait:S.isReady)||(S.isReady=!0)!==e&&0<--S.readyWait||F.resolveWith(E,[S])}}),S.ready.then=F.then,"complete"===E.readyState||"loading"!==E.readyState&&!E.documentElement.doScroll?C.setTimeout(S.ready):(E.addEventListener("DOMContentLoaded",B),C.addEventListener("load",B));var $=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===w(n))for(s in i=!0,n)$(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,m(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(S(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},_=/^-ms-/,z=/-([a-z])/g;function U(e,t){return t.toUpperCase()}function X(e){return e.replace(_,"ms-").replace(z,U)}var V=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function G(){this.expando=S.expando+G.uid++}G.uid=1,G.prototype={cache:function(e){var t=e[this.expando];return t||(t={},V(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[X(t)]=n;else for(r in t)i[X(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][X(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(X):(t=X(t))in r?[t]:t.match(P)||[]).length;while(n--)delete r[t[n]]}(void 0===t||S.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!S.isEmptyObject(t)}};var Y=new G,Q=new G,J=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,K=/[A-Z]/g;function Z(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(K,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+""?+i:J.test(i)?JSON.parse(i):i)}catch(e){}Q.set(e,t,n)}else n=void 0;return n}S.extend({hasData:function(e){return Q.hasData(e)||Y.hasData(e)},data:function(e,t,n){return Q.access(e,t,n)},removeData:function(e,t){Q.remove(e,t)},_data:function(e,t,n){return Y.access(e,t,n)},_removeData:function(e,t){Y.remove(e,t)}}),S.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0===n){if(this.length&&(i=Q.get(o),1===o.nodeType&&!Y.get(o,"hasDataAttrs"))){t=a.length;while(t--)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=X(r.slice(5)),Z(o,r,i[r]));Y.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof n?this.each(function(){Q.set(this,n)}):$(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=Q.get(o,n))?t:void 0!==(t=Z(o,n))?t:void 0;this.each(function(){Q.set(this,n,e)})},null,e,1<arguments.length,null,!0)},removeData:function(e){return this.each(function(){Q.remove(this,e)})}}),S.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Y.get(e,t),n&&(!r||Array.isArray(n)?r=Y.access(e,t,S.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=S.queue(e,t),r=n.length,i=n.shift(),o=S._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){S.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Y.get(e,n)||Y.access(e,n,{empty:S.Callbacks("once memory").add(function(){Y.remove(e,[t+"queue",n])})})}}),S.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?S.queue(this[0],t):void 0===n?this:this.each(function(){var e=S.queue(this,t,n);S._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&S.dequeue(this,t)})},dequeue:function(e){return this.each(function(){S.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=S.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=Y.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var ee=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,te=new RegExp("^(?:([+-])=|)("+ee+")([a-z%]*)$","i"),ne=["Top","Right","Bottom","Left"],re=E.documentElement,ie=function(e){return S.contains(e.ownerDocument,e)},oe={composed:!0};re.getRootNode&&(ie=function(e){return S.contains(e.ownerDocument,e)||e.getRootNode(oe)===e.ownerDocument});var ae=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&ie(e)&&"none"===S.css(e,"display")};function se(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return S.css(e,t,"")},u=s(),l=n&&n[3]||(S.cssNumber[t]?"":"px"),c=e.nodeType&&(S.cssNumber[t]||"px"!==l&&+u)&&te.exec(S.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)S.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,S.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var ue={};function le(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=Y.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&ae(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ue[s])||(o=a.body.appendChild(a.createElement(s)),u=S.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ue[s]=u)))):"none"!==n&&(l[c]="none",Y.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}S.fn.extend({show:function(){return le(this,!0)},hide:function(){return le(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?S(this).show():S(this).hide()})}});var ce,fe,pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="<textarea>x</textarea>",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="<option></option>",y.option=!!ce.lastChild;var ge={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n<r;n++)Y.set(e[n],"globalEval",!t||Y.get(t[n],"globalEval"))}ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td,y.option||(ge.optgroup=ge.option=[1,"<select multiple='multiple'>","</select>"]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===w(o))S.merge(p,o.nodeType?[o]:o);else if(me.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+S.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;S.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&-1<S.inArray(o,r))i&&i.push(o);else if(l=ie(o),a=ve(f.appendChild(o),"script"),l&&ye(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}var be=/^([^.]*)(?:\.(.+)|)/;function we(){return!0}function Te(){return!1}function Ce(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ee(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ee(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Te;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return S().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=S.guid++)),e.each(function(){S.event.add(this,t,i,r,n)})}function Se(e,i,o){o?(Y.set(e,i,!1),S.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Y.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(S.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Y.set(this,i,r),t=o(this,i),this[i](),r!==(n=Y.get(this,i))||t?Y.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n&&n.value}else r.length&&(Y.set(this,i,{value:S.event.trigger(S.extend(r[0],S.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Y.get(e,i)&&S.event.add(e,i,we)}S.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Y.get(t);if(V(t)){n.handler&&(n=(o=n).handler,i=o.selector),i&&S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++),(u=v.events)||(u=v.events=Object.create(null)),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof S&&S.event.triggered!==e.type?S.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(P)||[""]).length;while(l--)d=g=(s=be.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=S.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=S.event.special[d]||{},c=S.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&S.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),S.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Y.hasData(e)&&Y.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(P)||[""]).length;while(l--)if(d=g=(s=be.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=S.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||S.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)S.event.remove(e,d+t[l],n,r,!0);S.isEmptyObject(u)&&Y.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=new Array(arguments.length),u=S.event.fix(e),l=(Y.get(this,"events")||Object.create(null))[u.type]||[],c=S.event.special[u.type]||{};for(s[0]=u,t=1;t<arguments.length;t++)s[t]=arguments[t];if(u.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,u)){a=S.event.handlers.call(this,u,l),t=0;while((i=a[t++])&&!u.isPropagationStopped()){u.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!u.isImmediatePropagationStopped())u.rnamespace&&!1!==o.namespace&&!u.rnamespace.test(o.namespace)||(u.handleObj=o,u.data=o.data,void 0!==(r=((S.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s))&&!1===(u.result=r)&&(u.preventDefault(),u.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,u),u.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&1<=e.button))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?-1<S(i,this).index(l):S.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(t,e){Object.defineProperty(S.Event.prototype,t,{enumerable:!0,configurable:!0,get:m(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[S.expando]?e:new S.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Se(t,"click",we),!1},trigger:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Se(t,"click"),!0},_default:function(e){var t=e.target;return pe.test(t.type)&&t.click&&A(t,"input")&&Y.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},S.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},S.Event=function(e,t){if(!(this instanceof S.Event))return new S.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?we:Te,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&S.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[S.expando]=!0},S.Event.prototype={constructor:S.Event,isDefaultPrevented:Te,isPropagationStopped:Te,isImmediatePropagationStopped:Te,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=we,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=we,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=we,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},S.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:!0},S.event.addProp),S.each({focus:"focusin",blur:"focusout"},function(e,t){S.event.special[e]={setup:function(){return Se(this,e,Ce),!1},trigger:function(){return Se(this,e),!0},_default:function(){return!0},delegateType:t}}),S.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){S.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||S.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),S.fn.extend({on:function(e,t,n,r){return Ee(this,e,t,n,r)},one:function(e,t,n,r){return Ee(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,S(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=Te),this.each(function(){S.event.remove(this,e,n,t)})}});var ke=/<script|<style|<link/i,Ae=/checked\s*(?:[^=]|=\s*.checked.)/i,Ne=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n<r;n++)S.event.add(t,i,s[i][n]);Q.hasData(e)&&(o=Q.access(e),a=S.extend({},o),Q.set(t,a))}}function He(n,r,i,o){r=g(r);var e,t,a,s,u,l,c=0,f=n.length,p=f-1,d=r[0],h=m(d);if(h||1<f&&"string"==typeof d&&!y.checkClone&&Ae.test(d))return n.each(function(e){var t=n.eq(e);h&&(r[0]=d.call(this,e,t.html())),He(t,r,i,o)});if(f&&(t=(e=xe(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=S.map(ve(e,"script"),De)).length;c<f;c++)u=e,c!==p&&(u=S.clone(u,!0,!0),s&&S.merge(a,ve(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,S.map(a,qe),c=0;c<s;c++)u=a[c],he.test(u.type||"")&&!Y.access(u,"globalEval")&&S.contains(l,u)&&(u.src&&"module"!==(u.type||"").toLowerCase()?S._evalUrl&&!u.noModule&&S._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")},l):b(u.textContent.replace(Ne,""),u,l))}return n}function Oe(e,t,n){for(var r,i=t?S.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||S.cleanData(ve(r)),r.parentNode&&(n&&ie(r)&&ye(ve(r,"script")),r.parentNode.removeChild(r));return e}S.extend({htmlPrefilter:function(e){return e},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=ie(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||S.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r<i;r++)s=o[r],u=a[r],void 0,"input"===(l=u.nodeName.toLowerCase())&&pe.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||ve(e),a=a||ve(c),r=0,i=o.length;r<i;r++)Le(o[r],a[r]);else Le(e,c);return 0<(a=ve(c,"script")).length&&ye(a,!f&&ve(e,"script")),c},cleanData:function(e){for(var t,n,r,i=S.event.special,o=0;void 0!==(n=e[o]);o++)if(V(n)){if(t=n[Y.expando]){if(t.events)for(r in t.events)i[r]?S.event.remove(n,r):S.removeEvent(n,r,t.handle);n[Y.expando]=void 0}n[Q.expando]&&(n[Q.expando]=void 0)}}}),S.fn.extend({detach:function(e){return Oe(this,e,!0)},remove:function(e){return Oe(this,e)},text:function(e){return $(this,function(e){return void 0===e?S.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return He(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||je(this,e).appendChild(e)})},prepend:function(){return He(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=je(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(S.cleanData(ve(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return S.clone(this,e,t)})},html:function(e){return $(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!ke.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=S.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(S.cleanData(ve(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return He(this,arguments,function(e){var t=this.parentNode;S.inArray(this,n)<0&&(S.cleanData(ve(this)),t&&t.replaceChild(e,this))},n)}}),S.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){S.fn[e]=function(e){for(var t,n=[],r=S(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),S(r[o])[a](t),u.apply(n,t.get());return this.pushStack(n)}});var Pe=new RegExp("^("+ee+")(?!px)[a-z%]+$","i"),Re=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=C),t.getComputedStyle(e)},Me=function(e,t,n){var r,i,o={};for(i in t)o[i]=e.style[i],e.style[i]=t[i];for(i in r=n.call(e),t)e.style[i]=o[i];return r},Ie=new RegExp(ne.join("|"),"i");function We(e,t,n){var r,i,o,a,s=e.style;return(n=n||Re(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||ie(e)||(a=S.style(e,t)),!y.pixelBoxStyles()&&Pe.test(a)&&Ie.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function Fe(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}!function(){function e(){if(l){u.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",l.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",re.appendChild(u).appendChild(l);var e=C.getComputedStyle(l);n="1%"!==e.top,s=12===t(e.marginLeft),l.style.right="60%",o=36===t(e.right),r=36===t(e.width),l.style.position="absolute",i=12===t(l.offsetWidth/3),re.removeChild(u),l=null}}function t(e){return Math.round(parseFloat(e))}var n,r,i,o,a,s,u=E.createElement("div"),l=E.createElement("div");l.style&&(l.style.backgroundClip="content-box",l.cloneNode(!0).style.backgroundClip="",y.clearCloneStyle="content-box"===l.style.backgroundClip,S.extend(y,{boxSizingReliable:function(){return e(),r},pixelBoxStyles:function(){return e(),o},pixelPosition:function(){return e(),n},reliableMarginLeft:function(){return e(),s},scrollboxSize:function(){return e(),i},reliableTrDimensions:function(){var e,t,n,r;return null==a&&(e=E.createElement("table"),t=E.createElement("tr"),n=E.createElement("div"),e.style.cssText="position:absolute;left:-11111px;border-collapse:separate",t.style.cssText="border:1px solid",t.style.height="1px",n.style.height="9px",n.style.display="block",re.appendChild(e).appendChild(t).appendChild(n),r=C.getComputedStyle(t),a=parseInt(r.height,10)+parseInt(r.borderTopWidth,10)+parseInt(r.borderBottomWidth,10)===t.offsetHeight,re.removeChild(e)),a}}))}();var Be=["Webkit","Moz","ms"],$e=E.createElement("div").style,_e={};function ze(e){var t=S.cssProps[e]||_e[e];return t||(e in $e?e:_e[e]=function(e){var t=e[0].toUpperCase()+e.slice(1),n=Be.length;while(n--)if((e=Be[n]+t)in $e)return e}(e)||e)}var Ue=/^(none|table(?!-c[ea]).+)/,Xe=/^--/,Ve={position:"absolute",visibility:"hidden",display:"block"},Ge={letterSpacing:"0",fontWeight:"400"};function Ye(e,t,n){var r=te.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function Qe(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=S.css(e,n+ne[a],!0,i)),r?("content"===n&&(u-=S.css(e,"padding"+ne[a],!0,i)),"margin"!==n&&(u-=S.css(e,"border"+ne[a]+"Width",!0,i))):(u+=S.css(e,"padding"+ne[a],!0,i),"padding"!==n?u+=S.css(e,"border"+ne[a]+"Width",!0,i):s+=S.css(e,"border"+ne[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u}function Je(e,t,n){var r=Re(e),i=(!y.boxSizingReliable()||n)&&"border-box"===S.css(e,"boxSizing",!1,r),o=i,a=We(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if(Pe.test(a)){if(!n)return a;a="auto"}return(!y.boxSizingReliable()&&i||!y.reliableTrDimensions()&&A(e,"tr")||"auto"===a||!parseFloat(a)&&"inline"===S.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===S.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+Qe(e,t,n||(i?"border":"content"),o,r,a)+"px"}function Ke(e,t,n,r,i){return new Ke.prototype.init(e,t,n,r,i)}S.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=We(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=X(t),u=Xe.test(t),l=e.style;if(u||(t=ze(s)),a=S.cssHooks[t]||S.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"===(o=typeof n)&&(i=te.exec(n))&&i[1]&&(n=se(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(S.cssNumber[s]?"":"px")),y.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=X(t);return Xe.test(t)||(t=ze(s)),(a=S.cssHooks[t]||S.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=We(e,t,r)),"normal"===i&&t in Ge&&(i=Ge[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),S.each(["height","width"],function(e,u){S.cssHooks[u]={get:function(e,t,n){if(t)return!Ue.test(S.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?Je(e,u,n):Me(e,Ve,function(){return Je(e,u,n)})},set:function(e,t,n){var r,i=Re(e),o=!y.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===S.css(e,"boxSizing",!1,i),s=n?Qe(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-Qe(e,u,"border",!1,i)-.5)),s&&(r=te.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=S.css(e,u)),Ye(0,t,s)}}}),S.cssHooks.marginLeft=Fe(y.reliableMarginLeft,function(e,t){if(t)return(parseFloat(We(e,"marginLeft"))||e.getBoundingClientRect().left-Me(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),S.each({margin:"",padding:"",border:"Width"},function(i,o){S.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+ne[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(S.cssHooks[i+o].set=Ye)}),S.fn.extend({css:function(e,t){return $(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Re(e),i=t.length;a<i;a++)o[t[a]]=S.css(e,t[a],!1,r);return o}return void 0!==n?S.style(e,t,n):S.css(e,t)},e,t,1<arguments.length)}}),((S.Tween=Ke).prototype={constructor:Ke,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||S.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(S.cssNumber[n]?"":"px")},cur:function(){var e=Ke.propHooks[this.prop];return e&&e.get?e.get(this):Ke.propHooks._default.get(this)},run:function(e){var t,n=Ke.propHooks[this.prop];return this.options.duration?this.pos=t=S.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Ke.propHooks._default.set(this),this}}).init.prototype=Ke.prototype,(Ke.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=S.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){S.fx.step[e.prop]?S.fx.step[e.prop](e):1!==e.elem.nodeType||!S.cssHooks[e.prop]&&null==e.elem.style[ze(e.prop)]?e.elem[e.prop]=e.now:S.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=Ke.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},S.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},S.fx=Ke.prototype.init,S.fx.step={};var Ze,et,tt,nt,rt=/^(?:toggle|show|hide)$/,it=/queueHooks$/;function ot(){et&&(!1===E.hidden&&C.requestAnimationFrame?C.requestAnimationFrame(ot):C.setTimeout(ot,S.fx.interval),S.fx.tick())}function at(){return C.setTimeout(function(){Ze=void 0}),Ze=Date.now()}function st(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=ne[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function ut(e,t,n){for(var r,i=(lt.tweeners[t]||[]).concat(lt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function lt(o,e,t){var n,a,r=0,i=lt.prefilters.length,s=S.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=Ze||at(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:S.extend({},e),opts:S.extend(!0,{specialEasing:{},easing:S.easing._default},t),originalProperties:e,originalOptions:t,startTime:Ze||at(),duration:t.duration,tweens:[],createTween:function(e,t){var n=S.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=X(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=S.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=lt.prefilters[r].call(l,o,c,l.opts))return m(n.stop)&&(S._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return S.map(c,ut,l),m(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),S.fx.timer(S.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}S.Animation=S.extend(lt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return se(n.elem,e,te.exec(t),n),n}]},tweener:function(e,t){m(e)?(t=e,e=["*"]):e=e.match(P);for(var n,r=0,i=e.length;r<i;r++)n=e[r],lt.tweeners[n]=lt.tweeners[n]||[],lt.tweeners[n].unshift(t)},prefilters:[function(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ae(e),v=Y.get(e,"fxshow");for(r in n.queue||(null==(a=S._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,S.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],rt.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!v||void 0===v[r])continue;g=!0}d[r]=v&&v[r]||S.style(e,r)}if((u=!S.isEmptyObject(t))||!S.isEmptyObject(d))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=v&&v.display)&&(l=Y.get(e,"display")),"none"===(c=S.css(e,"display"))&&(l?c=l:(le([e],!0),l=e.style.display||l,c=S.css(e,"display"),le([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===S.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1,d)u||(v?"hidden"in v&&(g=v.hidden):v=Y.access(e,"fxshow",{display:l}),o&&(v.hidden=!g),g&&le([e],!0),p.done(function(){for(r in g||le([e]),Y.remove(e,"fxshow"),d)S.style(e,r,d[r])})),u=ut(g?v[r]:0,r,p),r in v||(v[r]=u.start,g&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?lt.prefilters.unshift(e):lt.prefilters.push(e)}}),S.speed=function(e,t,n){var r=e&&"object"==typeof e?S.extend({},e):{complete:n||!n&&t||m(e)&&e,duration:e,easing:n&&t||t&&!m(t)&&t};return S.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in S.fx.speeds?r.duration=S.fx.speeds[r.duration]:r.duration=S.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){m(r.old)&&r.old.call(this),r.queue&&S.dequeue(this,r.queue)},r},S.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){var i=S.isEmptyObject(t),o=S.speed(e,n,r),a=function(){var e=lt(this,S.extend({},t),o);(i||Y.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(i,e,o){var a=function(e){var t=e.stop;delete e.stop,t(o)};return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=S.timers,r=Y.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&it.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||S.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=Y.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=S.timers,o=n?n.length:0;for(t.finish=!0,S.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),S.each(["toggle","show","hide"],function(e,r){var i=S.fn[r];S.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(st(r,!0),e,t,n)}}),S.each({slideDown:st("show"),slideUp:st("hide"),slideToggle:st("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){S.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),S.timers=[],S.fx.tick=function(){var e,t=0,n=S.timers;for(Ze=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||S.fx.stop(),Ze=void 0},S.fx.timer=function(e){S.timers.push(e),S.fx.start()},S.fx.interval=13,S.fx.start=function(){et||(et=!0,ot())},S.fx.stop=function(){et=null},S.fx.speeds={slow:600,fast:200,_default:400},S.fn.delay=function(r,e){return r=S.fx&&S.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=C.setTimeout(e,r);t.stop=function(){C.clearTimeout(n)}})},tt=E.createElement("input"),nt=E.createElement("select").appendChild(E.createElement("option")),tt.type="checkbox",y.checkOn=""!==tt.value,y.optSelected=nt.selected,(tt=E.createElement("input")).value="t",tt.type="radio",y.radioValue="t"===tt.value;var ct,ft=S.expr.attrHandle;S.fn.extend({attr:function(e,t){return $(this,S.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){S.removeAttr(this,e)})}}),S.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?S.prop(e,t,n):(1===o&&S.isXMLDoc(e)||(i=S.attrHooks[t.toLowerCase()]||(S.expr.match.bool.test(t)?ct:void 0)),void 0!==n?null===n?void S.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=S.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!y.radioValue&&"radio"===t&&A(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(P);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),ct={set:function(e,t,n){return!1===t?S.removeAttr(e,n):e.setAttribute(n,n),n}},S.each(S.expr.match.bool.source.match(/\w+/g),function(e,t){var a=ft[t]||S.find.attr;ft[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=ft[o],ft[o]=r,r=null!=a(e,t,n)?o:null,ft[o]=i),r}});var pt=/^(?:input|select|textarea|button)$/i,dt=/^(?:a|area)$/i;function ht(e){return(e.match(P)||[]).join(" ")}function gt(e){return e.getAttribute&&e.getAttribute("class")||""}function vt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(P)||[]}S.fn.extend({prop:function(e,t){return $(this,S.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[S.propFix[e]||e]})}}),S.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&S.isXMLDoc(e)||(t=S.propFix[t]||t,i=S.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=S.find.attr(e,"tabindex");return t?parseInt(t,10):pt.test(e.nodeName)||dt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),y.optSelected||(S.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),S.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){S.propFix[this.toLowerCase()]=this}),S.fn.extend({addClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){S(this).addClass(t.call(this,e,gt(this)))});if((e=vt(t)).length)while(n=this[u++])if(i=gt(n),r=1===n.nodeType&&" "+ht(i)+" "){a=0;while(o=e[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=ht(r))&&n.setAttribute("class",s)}return this},removeClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){S(this).removeClass(t.call(this,e,gt(this)))});if(!arguments.length)return this.attr("class","");if((e=vt(t)).length)while(n=this[u++])if(i=gt(n),r=1===n.nodeType&&" "+ht(i)+" "){a=0;while(o=e[a++])while(-1<r.indexOf(" "+o+" "))r=r.replace(" "+o+" "," ");i!==(s=ht(r))&&n.setAttribute("class",s)}return this},toggleClass:function(i,t){var o=typeof i,a="string"===o||Array.isArray(i);return"boolean"==typeof t&&a?t?this.addClass(i):this.removeClass(i):m(i)?this.each(function(e){S(this).toggleClass(i.call(this,e,gt(this),t),t)}):this.each(function(){var e,t,n,r;if(a){t=0,n=S(this),r=vt(i);while(e=r[t++])n.hasClass(e)?n.removeClass(e):n.addClass(e)}else void 0!==i&&"boolean"!==o||((e=gt(this))&&Y.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",e||!1===i?"":Y.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&-1<(" "+ht(gt(n))+" ").indexOf(t))return!0;return!1}});var yt=/\r/g;S.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=m(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,S(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=S.map(t,function(e){return null==e?"":e+""})),(r=S.valHooks[this.type]||S.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=S.valHooks[t.type]||S.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(yt,""):null==e?"":e:void 0}}),S.extend({valHooks:{option:{get:function(e){var t=S.find.attr(e,"value");return null!=t?t:ht(S.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!A(n.parentNode,"optgroup"))){if(t=S(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=S.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=-1<S.inArray(S.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),S.each(["radio","checkbox"],function(){S.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<S.inArray(S(e).val(),t)}},y.checkOn||(S.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),y.focusin="onfocusin"in C;var mt=/^(?:focusinfocus|focusoutblur)$/,xt=function(e){e.stopPropagation()};S.extend(S.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,p=[n||E],d=v.call(e,"type")?e.type:e,h=v.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||E,3!==n.nodeType&&8!==n.nodeType&&!mt.test(d+S.event.triggered)&&(-1<d.indexOf(".")&&(d=(h=d.split(".")).shift(),h.sort()),u=d.indexOf(":")<0&&"on"+d,(e=e[S.expando]?e:new S.Event(d,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:S.makeArray(t,[e]),c=S.event.special[d]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!x(n)){for(s=c.delegateType||d,mt.test(s+d)||(o=o.parentNode);o;o=o.parentNode)p.push(o),a=o;a===(n.ownerDocument||E)&&p.push(a.defaultView||a.parentWindow||C)}i=0;while((o=p[i++])&&!e.isPropagationStopped())f=o,e.type=1<i?s:c.bindType||d,(l=(Y.get(o,"events")||Object.create(null))[e.type]&&Y.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&V(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=d,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(p.pop(),t)||!V(n)||u&&m(n[d])&&!x(n)&&((a=n[u])&&(n[u]=null),S.event.triggered=d,e.isPropagationStopped()&&f.addEventListener(d,xt),n[d](),e.isPropagationStopped()&&f.removeEventListener(d,xt),S.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=S.extend(new S.Event,n,{type:e,isSimulated:!0});S.event.trigger(r,null,t)}}),S.fn.extend({trigger:function(e,t){return this.each(function(){S.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return S.event.trigger(e,t,n,!0)}}),y.focusin||S.each({focus:"focusin",blur:"focusout"},function(n,r){var i=function(e){S.event.simulate(r,e.target,S.event.fix(e))};S.event.special[r]={setup:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r);t||e.addEventListener(n,i,!0),Y.access(e,r,(t||0)+1)},teardown:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r)-1;t?Y.access(e,r,t):(e.removeEventListener(n,i,!0),Y.remove(e,r))}}});var bt=C.location,wt={guid:Date.now()},Tt=/\?/;S.parseXML=function(e){var t,n;if(!e||"string"!=typeof e)return null;try{t=(new C.DOMParser).parseFromString(e,"text/xml")}catch(e){}return n=t&&t.getElementsByTagName("parsererror")[0],t&&!n||S.error("Invalid XML: "+(n?S.map(n.childNodes,function(e){return e.textContent}).join("\n"):e)),t};var Ct=/\[\]$/,Et=/\r?\n/g,St=/^(?:submit|button|image|reset|file)$/i,kt=/^(?:input|select|textarea|keygen)/i;function At(n,e,r,i){var t;if(Array.isArray(e))S.each(e,function(e,t){r||Ct.test(n)?i(n,t):At(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i)});else if(r||"object"!==w(e))i(n,e);else for(t in e)At(n+"["+t+"]",e[t],r,i)}S.param=function(e,t){var n,r=[],i=function(e,t){var n=m(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!S.isPlainObject(e))S.each(e,function(){i(this.name,this.value)});else for(n in e)At(n,e[n],t,i);return r.join("&")},S.fn.extend({serialize:function(){return S.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=S.prop(this,"elements");return e?S.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!S(this).is(":disabled")&&kt.test(this.nodeName)&&!St.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=S(this).val();return null==n?null:Array.isArray(n)?S.map(n,function(e){return{name:t.name,value:e.replace(Et,"\r\n")}}):{name:t.name,value:n.replace(Et,"\r\n")}}).get()}});var Nt=/%20/g,jt=/#.*$/,Dt=/([?&])_=[^&]*/,qt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Lt=/^(?:GET|HEAD)$/,Ht=/^\/\//,Ot={},Pt={},Rt="*/".concat("*"),Mt=E.createElement("a");function It(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(P)||[];if(m(t))while(n=i[r++])"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function Wt(t,i,o,a){var s={},u=t===Pt;function l(e){var r;return s[e]=!0,S.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function Ft(e,t){var n,r,i=S.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&S.extend(!0,e,r),e}Mt.href=bt.href,S.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:bt.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(bt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Rt,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":S.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Ft(Ft(e,S.ajaxSettings),t):Ft(S.ajaxSettings,e)},ajaxPrefilter:It(Ot),ajaxTransport:It(Pt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,p,n,d,r,h,g,i,o,v=S.ajaxSetup({},t),y=v.context||v,m=v.context&&(y.nodeType||y.jquery)?S(y):S.event,x=S.Deferred(),b=S.Callbacks("once memory"),w=v.statusCode||{},a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n){n={};while(t=qt.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?p:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(v.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(x.promise(T),v.url=((e||v.url||bt.href)+"").replace(Ht,bt.protocol+"//"),v.type=t.method||t.type||v.method||v.type,v.dataTypes=(v.dataType||"*").toLowerCase().match(P)||[""],null==v.crossDomain){r=E.createElement("a");try{r.href=v.url,r.href=r.href,v.crossDomain=Mt.protocol+"//"+Mt.host!=r.protocol+"//"+r.host}catch(e){v.crossDomain=!0}}if(v.data&&v.processData&&"string"!=typeof v.data&&(v.data=S.param(v.data,v.traditional)),Wt(Ot,v,t,T),h)return T;for(i in(g=S.event&&v.global)&&0==S.active++&&S.event.trigger("ajaxStart"),v.type=v.type.toUpperCase(),v.hasContent=!Lt.test(v.type),f=v.url.replace(jt,""),v.hasContent?v.data&&v.processData&&0===(v.contentType||"").indexOf("application/x-www-form-urlencoded")&&(v.data=v.data.replace(Nt,"+")):(o=v.url.slice(f.length),v.data&&(v.processData||"string"==typeof v.data)&&(f+=(Tt.test(f)?"&":"?")+v.data,delete v.data),!1===v.cache&&(f=f.replace(Dt,"$1"),o=(Tt.test(f)?"&":"?")+"_="+wt.guid+++o),v.url=f+o),v.ifModified&&(S.lastModified[f]&&T.setRequestHeader("If-Modified-Since",S.lastModified[f]),S.etag[f]&&T.setRequestHeader("If-None-Match",S.etag[f])),(v.data&&v.hasContent&&!1!==v.contentType||t.contentType)&&T.setRequestHeader("Content-Type",v.contentType),T.setRequestHeader("Accept",v.dataTypes[0]&&v.accepts[v.dataTypes[0]]?v.accepts[v.dataTypes[0]]+("*"!==v.dataTypes[0]?", "+Rt+"; q=0.01":""):v.accepts["*"]),v.headers)T.setRequestHeader(i,v.headers[i]);if(v.beforeSend&&(!1===v.beforeSend.call(y,T,v)||h))return T.abort();if(u="abort",b.add(v.complete),T.done(v.success),T.fail(v.error),c=Wt(Pt,v,t,T)){if(T.readyState=1,g&&m.trigger("ajaxSend",[T,v]),h)return T;v.async&&0<v.timeout&&(d=C.setTimeout(function(){T.abort("timeout")},v.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,d&&C.clearTimeout(d),c=void 0,p=r||"",T.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}(v,T,n)),!i&&-1<S.inArray("script",v.dataTypes)&&S.inArray("json",v.dataTypes)<0&&(v.converters["text script"]=function(){}),s=function(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}(v,s,T,i),i?(v.ifModified&&((u=T.getResponseHeader("Last-Modified"))&&(S.lastModified[f]=u),(u=T.getResponseHeader("etag"))&&(S.etag[f]=u)),204===e||"HEAD"===v.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),T.status=e,T.statusText=(t||l)+"",i?x.resolveWith(y,[o,l,T]):x.rejectWith(y,[T,l,a]),T.statusCode(w),w=void 0,g&&m.trigger(i?"ajaxSuccess":"ajaxError",[T,v,i?o:a]),b.fireWith(y,[T,l]),g&&(m.trigger("ajaxComplete",[T,v]),--S.active||S.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return S.get(e,t,n,"json")},getScript:function(e,t){return S.get(e,void 0,t,"script")}}),S.each(["get","post"],function(e,i){S[i]=function(e,t,n,r){return m(t)&&(r=r||n,n=t,t=void 0),S.ajax(S.extend({url:e,type:i,dataType:r,data:t,success:n},S.isPlainObject(e)&&e))}}),S.ajaxPrefilter(function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||"")}),S._evalUrl=function(e,t,n){return S.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){S.globalEval(e,t,n)}})},S.fn.extend({wrapAll:function(e){var t;return this[0]&&(m(e)&&(e=e.call(this[0])),t=S(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(n){return m(n)?this.each(function(e){S(this).wrapInner(n.call(this,e))}):this.each(function(){var e=S(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=m(t);return this.each(function(e){S(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){S(this).replaceWith(this.childNodes)}),this}}),S.expr.pseudos.hidden=function(e){return!S.expr.pseudos.visible(e)},S.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},S.ajaxSettings.xhr=function(){try{return new C.XMLHttpRequest}catch(e){}};var Bt={0:200,1223:204},$t=S.ajaxSettings.xhr();y.cors=!!$t&&"withCredentials"in $t,y.ajax=$t=!!$t,S.ajaxTransport(function(i){var o,a;if(y.cors||$t&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(Bt[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&C.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),S.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),S.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return S.globalEval(e),e}}}),S.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),S.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=S("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=ht(e.slice(s)),e=e.slice(0,s)),m(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&S.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?S("<div>").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}});var Xt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;S.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),m(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||S.guid++,i},S.holdReady=function(e){e?S.readyWait++:S.ready(!0)},S.isArray=Array.isArray,S.parseJSON=JSON.parse,S.nodeName=A,S.isFunction=m,S.isWindow=x,S.camelCase=X,S.type=w,S.now=Date.now,S.isNumeric=function(e){var t=S.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},S.trim=function(e){return null==e?"":(e+"").replace(Xt,"")},"function"==typeof define&&define.amd&&define("jquery",[],function(){return S});var Vt=C.jQuery,Gt=C.$;return S.noConflict=function(e){return C.$===S&&(C.$=Gt),e&&C.jQuery===S&&(C.jQuery=Vt),S},"undefined"==typeof e&&(C.jQuery=C.$=S),S});
;/*! jQuery UI - v1.13.2 - 2022-07-14
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-patch.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

!function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(V){"use strict";V.ui=V.ui||{};V.ui.version="1.13.2";var n,i=0,a=Array.prototype.hasOwnProperty,r=Array.prototype.slice;V.cleanData=(n=V.cleanData,function(t){for(var e,i,s=0;null!=(i=t[s]);s++)(e=V._data(i,"events"))&&e.remove&&V(i).triggerHandler("remove");n(t)}),V.widget=function(t,i,e){var s,n,o,a={},r=t.split(".")[0],l=r+"-"+(t=t.split(".")[1]);return e||(e=i,i=V.Widget),Array.isArray(e)&&(e=V.extend.apply(null,[{}].concat(e))),V.expr.pseudos[l.toLowerCase()]=function(t){return!!V.data(t,l)},V[r]=V[r]||{},s=V[r][t],n=V[r][t]=function(t,e){if(!this||!this._createWidget)return new n(t,e);arguments.length&&this._createWidget(t,e)},V.extend(n,s,{version:e.version,_proto:V.extend({},e),_childConstructors:[]}),(o=new i).options=V.widget.extend({},o.options),V.each(e,function(e,s){function n(){return i.prototype[e].apply(this,arguments)}function o(t){return i.prototype[e].apply(this,t)}a[e]="function"==typeof s?function(){var t,e=this._super,i=this._superApply;return this._super=n,this._superApply=o,t=s.apply(this,arguments),this._super=e,this._superApply=i,t}:s}),n.prototype=V.widget.extend(o,{widgetEventPrefix:s&&o.widgetEventPrefix||t},a,{constructor:n,namespace:r,widgetName:t,widgetFullName:l}),s?(V.each(s._childConstructors,function(t,e){var i=e.prototype;V.widget(i.namespace+"."+i.widgetName,n,e._proto)}),delete s._childConstructors):i._childConstructors.push(n),V.widget.bridge(t,n),n},V.widget.extend=function(t){for(var e,i,s=r.call(arguments,1),n=0,o=s.length;n<o;n++)for(e in s[n])i=s[n][e],a.call(s[n],e)&&void 0!==i&&(V.isPlainObject(i)?t[e]=V.isPlainObject(t[e])?V.widget.extend({},t[e],i):V.widget.extend({},i):t[e]=i);return t},V.widget.bridge=function(o,e){var a=e.prototype.widgetFullName||o;V.fn[o]=function(i){var t="string"==typeof i,s=r.call(arguments,1),n=this;return t?this.length||"instance"!==i?this.each(function(){var t,e=V.data(this,a);return"instance"===i?(n=e,!1):e?"function"!=typeof e[i]||"_"===i.charAt(0)?V.error("no such method '"+i+"' for "+o+" widget instance"):(t=e[i].apply(e,s))!==e&&void 0!==t?(n=t&&t.jquery?n.pushStack(t.get()):t,!1):void 0:V.error("cannot call methods on "+o+" prior to initialization; attempted to call method '"+i+"'")}):n=void 0:(s.length&&(i=V.widget.extend.apply(null,[i].concat(s))),this.each(function(){var t=V.data(this,a);t?(t.option(i||{}),t._init&&t._init()):V.data(this,a,new e(i,this))})),n}},V.Widget=function(){},V.Widget._childConstructors=[],V.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=V(e||this.defaultElement||this)[0],this.element=V(e),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=V(),this.hoverable=V(),this.focusable=V(),this.classesElementLookup={},e!==this&&(V.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=V(e.style?e.ownerDocument:e.document||e),this.window=V(this.document[0].defaultView||this.document[0].parentWindow)),this.options=V.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:V.noop,_create:V.noop,_init:V.noop,destroy:function(){var i=this;this._destroy(),V.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:V.noop,widget:function(){return this.element},option:function(t,e){var i,s,n,o=t;if(0===arguments.length)return V.widget.extend({},this.options);if("string"==typeof t)if(o={},t=(i=t.split(".")).shift(),i.length){for(s=o[t]=V.widget.extend({},this.options[t]),n=0;n<i.length-1;n++)s[i[n]]=s[i[n]]||{},s=s[i[n]];if(t=i.pop(),1===arguments.length)return void 0===s[t]?null:s[t];s[t]=e}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=e}return this._setOptions(o),this},_setOptions:function(t){for(var e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(t){var e,i,s;for(e in t)s=this.classesElementLookup[e],t[e]!==this.options.classes[e]&&s&&s.length&&(i=V(s.get()),this._removeClass(s,e),i.addClass(this._classes({element:i,keys:e,classes:t,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(n){var o=[],a=this;function t(t,e){for(var i,s=0;s<t.length;s++)i=a.classesElementLookup[t[s]]||V(),i=n.add?(function(){var i=[];n.element.each(function(t,e){V.map(a.classesElementLookup,function(t){return t}).some(function(t){return t.is(e)})||i.push(e)}),a._on(V(i),{remove:"_untrackClassesElement"})}(),V(V.uniqueSort(i.get().concat(n.element.get())))):V(i.not(n.element).get()),a.classesElementLookup[t[s]]=i,o.push(t[s]),e&&n.classes[t[s]]&&o.push(n.classes[t[s]])}return(n=V.extend({element:this.element,classes:this.options.classes||{}},n)).keys&&t(n.keys.match(/\S+/g)||[],!0),n.extra&&t(n.extra.match(/\S+/g)||[]),o.join(" ")},_untrackClassesElement:function(i){var s=this;V.each(s.classesElementLookup,function(t,e){-1!==V.inArray(i.target,e)&&(s.classesElementLookup[t]=V(e.not(i.target).get()))}),this._off(V(i.target))},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){var n="string"==typeof t||null===t,i={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s="boolean"==typeof s?s:i};return i.element.toggleClass(this._classes(i),s),this},_on:function(n,o,t){var a,r=this;"boolean"!=typeof n&&(t=o,o=n,n=!1),t?(o=a=V(o),this.bindings=this.bindings.add(o)):(t=o,o=this.element,a=this.widget()),V.each(t,function(t,e){function i(){if(n||!0!==r.options.disabled&&!V(this).hasClass("ui-state-disabled"))return("string"==typeof e?r[e]:e).apply(r,arguments)}"string"!=typeof e&&(i.guid=e.guid=e.guid||i.guid||V.guid++);var s=t.match(/^([\w:-]*)\s*(.*)$/),t=s[1]+r.eventNamespace,s=s[2];s?a.on(t,s,i):o.on(t,i)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.off(e),this.bindings=V(this.bindings.not(t).get()),this.focusable=V(this.focusable.not(t).get()),this.hoverable=V(this.hoverable.not(t).get())},_delay:function(t,e){var i=this;return setTimeout(function(){return("string"==typeof t?i[t]:t).apply(i,arguments)},e||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){this._addClass(V(t.currentTarget),null,"ui-state-hover")},mouseleave:function(t){this._removeClass(V(t.currentTarget),null,"ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){this._addClass(V(t.currentTarget),null,"ui-state-focus")},focusout:function(t){this._removeClass(V(t.currentTarget),null,"ui-state-focus")}})},_trigger:function(t,e,i){var s,n,o=this.options[t];if(i=i||{},(e=V.Event(e)).type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),e.target=this.element[0],n=e.originalEvent)for(s in n)s in e||(e[s]=n[s]);return this.element.trigger(e,i),!("function"==typeof o&&!1===o.apply(this.element[0],[e].concat(i))||e.isDefaultPrevented())}},V.each({show:"fadeIn",hide:"fadeOut"},function(o,a){V.Widget.prototype["_"+o]=function(e,t,i){var s,n=(t="string"==typeof t?{effect:t}:t)?!0!==t&&"number"!=typeof t&&t.effect||a:o;"number"==typeof(t=t||{})?t={duration:t}:!0===t&&(t={}),s=!V.isEmptyObject(t),t.complete=i,t.delay&&e.delay(t.delay),s&&V.effects&&V.effects.effect[n]?e[o](t):n!==o&&e[n]?e[n](t.duration,t.easing,i):e.queue(function(t){V(this)[o](),i&&i.call(e[0]),t()})}});var s,x,k,o,l,h,c,u,C;V.widget;function D(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function I(t,e){return parseInt(V.css(t,e),10)||0}function T(t){return null!=t&&t===t.window}x=Math.max,k=Math.abs,o=/left|center|right/,l=/top|center|bottom/,h=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,C=V.fn.position,V.position={scrollbarWidth:function(){if(void 0!==s)return s;var t,e=V("<div style='display:block;position:absolute;width:200px;height:200px;overflow:hidden;'><div style='height:300px;width:auto;'></div></div>"),i=e.children()[0];return V("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),s=t-i},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.width<t.element[0].scrollWidth;return{width:"scroll"===i||"auto"===i&&t.height<t.element[0].scrollHeight?V.position.scrollbarWidth():0,height:e?V.position.scrollbarWidth():0}},getWithinInfo:function(t){var e=V(t||window),i=T(e[0]),s=!!e[0]&&9===e[0].nodeType;return{element:e,isWindow:i,isDocument:s,offset:!i&&!s?V(t).offset():{left:0,top:0},scrollLeft:e.scrollLeft(),scrollTop:e.scrollTop(),width:e.outerWidth(),height:e.outerHeight()}}},V.fn.position=function(u){if(!u||!u.of)return C.apply(this,arguments);var d,p,f,g,m,t,_="string"==typeof(u=V.extend({},u)).of?V(document).find(u.of):V(u.of),v=V.position.getWithinInfo(u.within),b=V.position.getScrollInfo(v),y=(u.collision||"flip").split(" "),w={},e=9===(t=(e=_)[0]).nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:T(t)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:t.preventDefault?{width:0,height:0,offset:{top:t.pageY,left:t.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()};return _[0].preventDefault&&(u.at="left top"),p=e.width,f=e.height,m=V.extend({},g=e.offset),V.each(["my","at"],function(){var t,e,i=(u[this]||"").split(" ");(i=1===i.length?o.test(i[0])?i.concat(["center"]):l.test(i[0])?["center"].concat(i):["center","center"]:i)[0]=o.test(i[0])?i[0]:"center",i[1]=l.test(i[1])?i[1]:"center",t=h.exec(i[0]),e=h.exec(i[1]),w[this]=[t?t[0]:0,e?e[0]:0],u[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===y.length&&(y[1]=y[0]),"right"===u.at[0]?m.left+=p:"center"===u.at[0]&&(m.left+=p/2),"bottom"===u.at[1]?m.top+=f:"center"===u.at[1]&&(m.top+=f/2),d=D(w.at,p,f),m.left+=d[0],m.top+=d[1],this.each(function(){var i,t,a=V(this),r=a.outerWidth(),l=a.outerHeight(),e=I(this,"marginLeft"),s=I(this,"marginTop"),n=r+e+I(this,"marginRight")+b.width,o=l+s+I(this,"marginBottom")+b.height,h=V.extend({},m),c=D(w.my,a.outerWidth(),a.outerHeight());"right"===u.my[0]?h.left-=r:"center"===u.my[0]&&(h.left-=r/2),"bottom"===u.my[1]?h.top-=l:"center"===u.my[1]&&(h.top-=l/2),h.left+=c[0],h.top+=c[1],i={marginLeft:e,marginTop:s},V.each(["left","top"],function(t,e){V.ui.position[y[t]]&&V.ui.position[y[t]][e](h,{targetWidth:p,targetHeight:f,elemWidth:r,elemHeight:l,collisionPosition:i,collisionWidth:n,collisionHeight:o,offset:[d[0]+c[0],d[1]+c[1]],my:u.my,at:u.at,within:v,elem:a})}),u.using&&(t=function(t){var e=g.left-h.left,i=e+p-r,s=g.top-h.top,n=s+f-l,o={target:{element:_,left:g.left,top:g.top,width:p,height:f},element:{element:a,left:h.left,top:h.top,width:r,height:l},horizontal:i<0?"left":0<e?"right":"center",vertical:n<0?"top":0<s?"bottom":"middle"};p<r&&k(e+i)<p&&(o.horizontal="center"),f<l&&k(s+n)<f&&(o.vertical="middle"),x(k(e),k(i))>x(k(s),k(n))?o.important="horizontal":o.important="vertical",u.using.call(this,t,o)}),a.offset(V.extend(h,{using:t}))})},V.ui.position={fit:{left:function(t,e){var i=e.within,s=i.isWindow?i.scrollLeft:i.offset.left,n=i.width,o=t.left-e.collisionPosition.marginLeft,a=s-o,r=o+e.collisionWidth-n-s;e.collisionWidth>n?0<a&&r<=0?(i=t.left+a+e.collisionWidth-n-s,t.left+=a-i):t.left=!(0<r&&a<=0)&&r<a?s+n-e.collisionWidth:s:0<a?t.left+=a:0<r?t.left-=r:t.left=x(t.left-o,t.left)},top:function(t,e){var i=e.within,s=i.isWindow?i.scrollTop:i.offset.top,n=e.within.height,o=t.top-e.collisionPosition.marginTop,a=s-o,r=o+e.collisionHeight-n-s;e.collisionHeight>n?0<a&&r<=0?(i=t.top+a+e.collisionHeight-n-s,t.top+=a-i):t.top=!(0<r&&a<=0)&&r<a?s+n-e.collisionHeight:s:0<a?t.top+=a:0<r?t.top-=r:t.top=x(t.top-o,t.top)}},flip:{left:function(t,e){var i=e.within,s=i.offset.left+i.scrollLeft,n=i.width,o=i.isWindow?i.scrollLeft:i.offset.left,a=t.left-e.collisionPosition.marginLeft,r=a-o,l=a+e.collisionWidth-n-o,h="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,i="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,a=-2*e.offset[0];r<0?((s=t.left+h+i+a+e.collisionWidth-n-s)<0||s<k(r))&&(t.left+=h+i+a):0<l&&(0<(o=t.left-e.collisionPosition.marginLeft+h+i+a-o)||k(o)<l)&&(t.left+=h+i+a)},top:function(t,e){var i=e.within,s=i.offset.top+i.scrollTop,n=i.height,o=i.isWindow?i.scrollTop:i.offset.top,a=t.top-e.collisionPosition.marginTop,r=a-o,l=a+e.collisionHeight-n-o,h="top"===e.my[1]?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,i="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,a=-2*e.offset[1];r<0?((s=t.top+h+i+a+e.collisionHeight-n-s)<0||s<k(r))&&(t.top+=h+i+a):0<l&&(0<(o=t.top-e.collisionPosition.marginTop+h+i+a-o)||k(o)<l)&&(t.top+=h+i+a)}},flipfit:{left:function(){V.ui.position.flip.left.apply(this,arguments),V.ui.position.fit.left.apply(this,arguments)},top:function(){V.ui.position.flip.top.apply(this,arguments),V.ui.position.fit.top.apply(this,arguments)}}};V.ui.position,V.extend(V.expr.pseudos,{data:V.expr.createPseudo?V.expr.createPseudo(function(e){return function(t){return!!V.data(t,e)}}):function(t,e,i){return!!V.data(t,i[3])}}),V.fn.extend({disableSelection:(t="onselectstart"in document.createElement("div")?"selectstart":"mousedown",function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}),enableSelection:function(){return this.off(".ui-disableSelection")}});var t,d=V,p={},e=p.toString,f=/^([\-+])=\s*(\d+\.?\d*)/,g=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16),t[4]?(parseInt(t[4],16)/255).toFixed(2):1]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),t[4]?(parseInt(t[4]+t[4],16)/255).toFixed(2):1]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],m=d.Color=function(t,e,i,s){return new d.Color.fn.parse(t,e,i,s)},_={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},v={byte:{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},b=m.support={},y=d("<p>")[0],w=d.each;function P(t){return null==t?t+"":"object"==typeof t?p[e.call(t)]||"object":typeof t}function M(t,e,i){var s=v[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:Math.min(s.max,Math.max(0,t)))}function S(s){var n=m(),o=n._rgba=[];return s=s.toLowerCase(),w(g,function(t,e){var i=e.re.exec(s),i=i&&e.parse(i),e=e.space||"rgba";if(i)return i=n[e](i),n[_[e].cache]=i[_[e].cache],o=n._rgba=i._rgba,!1}),o.length?("0,0,0,0"===o.join()&&d.extend(o,B.transparent),n):B[s]}function H(t,e,i){return 6*(i=(i+1)%1)<1?t+(e-t)*i*6:2*i<1?e:3*i<2?t+(e-t)*(2/3-i)*6:t}y.style.cssText="background-color:rgba(1,1,1,.5)",b.rgba=-1<y.style.backgroundColor.indexOf("rgba"),w(_,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),d.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(t,e){p["[object "+e+"]"]=e.toLowerCase()}),(m.fn=d.extend(m.prototype,{parse:function(n,t,e,i){if(void 0===n)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=d(n).css(t),t=void 0);var o=this,s=P(n),a=this._rgba=[];return void 0!==t&&(n=[n,t,e,i],s="array"),"string"===s?this.parse(S(n)||B._default):"array"===s?(w(_.rgba.props,function(t,e){a[e.idx]=M(n[e.idx],e)}),this):"object"===s?(w(_,n instanceof m?function(t,e){n[e.cache]&&(o[e.cache]=n[e.cache].slice())}:function(t,i){var s=i.cache;w(i.props,function(t,e){if(!o[s]&&i.to){if("alpha"===t||null==n[t])return;o[s]=i.to(o._rgba)}o[s][e.idx]=M(n[t],e,!0)}),o[s]&&d.inArray(null,o[s].slice(0,3))<0&&(null==o[s][3]&&(o[s][3]=1),i.from&&(o._rgba=i.from(o[s])))}),this):void 0},is:function(t){var n=m(t),o=!0,a=this;return w(_,function(t,e){var i,s=n[e.cache];return s&&(i=a[e.cache]||e.to&&e.to(a._rgba)||[],w(e.props,function(t,e){if(null!=s[e.idx])return o=s[e.idx]===i[e.idx]})),o}),o},_space:function(){var i=[],s=this;return w(_,function(t,e){s[e.cache]&&i.push(t)}),i.pop()},transition:function(t,a){var e=(h=m(t))._space(),i=_[e],t=0===this.alpha()?m("transparent"):this,r=t[i.cache]||i.to(t._rgba),l=r.slice(),h=h[i.cache];return w(i.props,function(t,e){var i=e.idx,s=r[i],n=h[i],o=v[e.type]||{};null!==n&&(null===s?l[i]=n:(o.mod&&(n-s>o.mod/2?s+=o.mod:s-n>o.mod/2&&(s-=o.mod)),l[i]=M((n-s)*a+s,e)))}),this[e](l)},blend:function(t){if(1===this._rgba[3])return this;var e=this._rgba.slice(),i=e.pop(),s=m(t)._rgba;return m(d.map(e,function(t,e){return(1-i)*s[e]+i*t}))},toRgbaString:function(){var t="rgba(",e=d.map(this._rgba,function(t,e){return null!=t?t:2<e?1:0});return 1===e[3]&&(e.pop(),t="rgb("),t+e.join()+")"},toHslaString:function(){var t="hsla(",e=d.map(this.hsla(),function(t,e){return null==t&&(t=2<e?1:0),t=e&&e<3?Math.round(100*t)+"%":t});return 1===e[3]&&(e.pop(),t="hsl("),t+e.join()+")"},toHexString:function(t){var e=this._rgba.slice(),i=e.pop();return t&&e.push(~~(255*i)),"#"+d.map(e,function(t){return 1===(t=(t||0).toString(16)).length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}})).parse.prototype=m.fn,_.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/255,i=t[1]/255,s=t[2]/255,n=t[3],o=Math.max(e,i,s),a=Math.min(e,i,s),r=o-a,l=o+a,t=.5*l,i=a===o?0:e===o?60*(i-s)/r+360:i===o?60*(s-e)/r+120:60*(e-i)/r+240,l=0==r?0:t<=.5?r/l:r/(2-l);return[Math.round(i)%360,l,t,null==n?1:n]},_.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],t=t[3],i=s<=.5?s*(1+i):s+i-s*i,s=2*s-i;return[Math.round(255*H(s,i,e+1/3)),Math.round(255*H(s,i,e)),Math.round(255*H(s,i,e-1/3)),t]},w(_,function(l,t){var e=t.props,o=t.cache,a=t.to,r=t.from;m.fn[l]=function(t){if(a&&!this[o]&&(this[o]=a(this._rgba)),void 0===t)return this[o].slice();var i=P(t),s="array"===i||"object"===i?t:arguments,n=this[o].slice();return w(e,function(t,e){t=s["object"===i?t:e.idx];null==t&&(t=n[e.idx]),n[e.idx]=M(t,e)}),r?((t=m(r(n)))[o]=n,t):m(n)},w(e,function(a,r){m.fn[a]||(m.fn[a]=function(t){var e,i=P(t),s="alpha"===a?this._hsla?"hsla":"rgba":l,n=this[s](),o=n[r.idx];return"undefined"===i?o:("function"===i&&(i=P(t=t.call(this,o))),null==t&&r.empty?this:("string"===i&&(e=f.exec(t))&&(t=o+parseFloat(e[2])*("+"===e[1]?1:-1)),n[r.idx]=t,this[s](n)))})})}),(m.hook=function(t){t=t.split(" ");w(t,function(t,o){d.cssHooks[o]={set:function(t,e){var i,s,n="";if("transparent"!==e&&("string"!==P(e)||(i=S(e)))){if(e=m(i||e),!b.rgba&&1!==e._rgba[3]){for(s="backgroundColor"===o?t.parentNode:t;(""===n||"transparent"===n)&&s&&s.style;)try{n=d.css(s,"backgroundColor"),s=s.parentNode}catch(t){}e=e.blend(n&&"transparent"!==n?n:"_default")}e=e.toRgbaString()}try{t.style[o]=e}catch(t){}}},d.fx.step[o]=function(t){t.colorInit||(t.start=m(t.elem,o),t.end=m(t.end),t.colorInit=!0),d.cssHooks[o].set(t.elem,t.start.transition(t.end,t.pos))}})})("backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor"),d.cssHooks.borderColor={expand:function(i){var s={};return w(["Top","Right","Bottom","Left"],function(t,e){s["border"+e+"Color"]=i}),s}};var z,A,O,N,E,W,F,L,R,Y,B=d.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"},j="ui-effects-",q="ui-effects-style",K="ui-effects-animated";function U(t){var e,i,s=t.ownerDocument.defaultView?t.ownerDocument.defaultView.getComputedStyle(t,null):t.currentStyle,n={};if(s&&s.length&&s[0]&&s[s[0]])for(i=s.length;i--;)"string"==typeof s[e=s[i]]&&(n[e.replace(/-([\da-z])/gi,function(t,e){return e.toUpperCase()})]=s[e]);else for(e in s)"string"==typeof s[e]&&(n[e]=s[e]);return n}function X(t,e,i,s){return t={effect:t=V.isPlainObject(t)?(e=t).effect:t},"function"==typeof(e=null==e?{}:e)&&(s=e,i=null,e={}),"number"!=typeof e&&!V.fx.speeds[e]||(s=i,i=e,e={}),"function"==typeof i&&(s=i,i=null),e&&V.extend(t,e),i=i||e.duration,t.duration=V.fx.off?0:"number"==typeof i?i:i in V.fx.speeds?V.fx.speeds[i]:V.fx.speeds._default,t.complete=s||e.complete,t}function $(t){return!t||"number"==typeof t||V.fx.speeds[t]||("string"==typeof t&&!V.effects.effect[t]||("function"==typeof t||"object"==typeof t&&!t.effect))}function G(t,e){var i=e.outerWidth(),e=e.outerHeight(),t=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/.exec(t)||["",0,i,e,0];return{top:parseFloat(t[1])||0,right:"auto"===t[2]?i:parseFloat(t[2]),bottom:"auto"===t[3]?e:parseFloat(t[3]),left:parseFloat(t[4])||0}}V.effects={effect:{}},N=["add","remove","toggle"],E={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1},V.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,e){V.fx.step[e]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(d.style(t.elem,e,t.end),t.setAttr=!0)}}),V.fn.addBack||(V.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),V.effects.animateClass=function(n,t,e,i){var o=V.speed(t,e,i);return this.queue(function(){var i=V(this),t=i.attr("class")||"",e=(e=o.children?i.find("*").addBack():i).map(function(){return{el:V(this),start:U(this)}}),s=function(){V.each(N,function(t,e){n[e]&&i[e+"Class"](n[e])})};s(),e=e.map(function(){return this.end=U(this.el[0]),this.diff=function(t,e){var i,s,n={};for(i in e)s=e[i],t[i]!==s&&(E[i]||!V.fx.step[i]&&isNaN(parseFloat(s))||(n[i]=s));return n}(this.start,this.end),this}),i.attr("class",t),e=e.map(function(){var t=this,e=V.Deferred(),i=V.extend({},o,{queue:!1,complete:function(){e.resolve(t)}});return this.el.animate(this.diff,i),e.promise()}),V.when.apply(V,e.get()).done(function(){s(),V.each(arguments,function(){var e=this.el;V.each(this.diff,function(t){e.css(t,"")})}),o.complete.call(i[0])})})},V.fn.extend({addClass:(O=V.fn.addClass,function(t,e,i,s){return e?V.effects.animateClass.call(this,{add:t},e,i,s):O.apply(this,arguments)}),removeClass:(A=V.fn.removeClass,function(t,e,i,s){return 1<arguments.length?V.effects.animateClass.call(this,{remove:t},e,i,s):A.apply(this,arguments)}),toggleClass:(z=V.fn.toggleClass,function(t,e,i,s,n){return"boolean"==typeof e||void 0===e?i?V.effects.animateClass.call(this,e?{add:t}:{remove:t},i,s,n):z.apply(this,arguments):V.effects.animateClass.call(this,{toggle:t},e,i,s)}),switchClass:function(t,e,i,s,n){return V.effects.animateClass.call(this,{add:e,remove:t},i,s,n)}}),V.expr&&V.expr.pseudos&&V.expr.pseudos.animated&&(V.expr.pseudos.animated=(W=V.expr.pseudos.animated,function(t){return!!V(t).data(K)||W(t)})),!1!==V.uiBackCompat&&V.extend(V.effects,{save:function(t,e){for(var i=0,s=e.length;i<s;i++)null!==e[i]&&t.data(j+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;s<n;s++)null!==e[s]&&(i=t.data(j+e[s]),t.css(e[s],i))},setMode:function(t,e){return e="toggle"===e?t.is(":hidden")?"show":"hide":e},createWrapper:function(i){if(i.parent().is(".ui-effects-wrapper"))return i.parent();var s={width:i.outerWidth(!0),height:i.outerHeight(!0),float:i.css("float")},t=V("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e={width:i.width(),height:i.height()},n=document.activeElement;try{n.id}catch(t){n=document.body}return i.wrap(t),i[0]!==n&&!V.contains(i[0],n)||V(n).trigger("focus"),t=i.parent(),"static"===i.css("position")?(t.css({position:"relative"}),i.css({position:"relative"})):(V.extend(s,{position:i.css("position"),zIndex:i.css("z-index")}),V.each(["top","left","bottom","right"],function(t,e){s[e]=i.css(e),isNaN(parseInt(s[e],10))&&(s[e]="auto")}),i.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),i.css(e),t.css(s).show()},removeWrapper:function(t){var e=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),t[0]!==e&&!V.contains(t[0],e)||V(e).trigger("focus")),t}}),V.extend(V.effects,{version:"1.13.2",define:function(t,e,i){return i||(i=e,e="effect"),V.effects.effect[t]=i,V.effects.effect[t].mode=e,i},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,e="vertical"!==i?(e||100)/100:1;return{height:t.height()*e,width:t.width()*s,outerHeight:t.outerHeight()*e,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();1<e&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(q,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(q)||"",t.removeData(q)},mode:function(t,e){t=t.is(":hidden");return"toggle"===e&&(e=t?"show":"hide"),e=(t?"hide"===e:"show"===e)?"none":e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createPlaceholder:function(t){var e,i=t.css("position"),s=t.position();return t.css({marginTop:t.css("marginTop"),marginBottom:t.css("marginBottom"),marginLeft:t.css("marginLeft"),marginRight:t.css("marginRight")}).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()),/^(static|relative)/.test(i)&&(i="absolute",e=V("<"+t[0].nodeName+">").insertAfter(t).css({display:/^(inline|ruby)/.test(t.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:t.css("marginTop"),marginBottom:t.css("marginBottom"),marginLeft:t.css("marginLeft"),marginRight:t.css("marginRight"),float:t.css("float")}).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).addClass("ui-effects-placeholder"),t.data(j+"placeholder",e)),t.css({position:i,left:s.left,top:s.top}),e},removePlaceholder:function(t){var e=j+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(t){V.effects.restoreStyle(t),V.effects.removePlaceholder(t)},setTransition:function(s,t,n,o){return o=o||{},V.each(t,function(t,e){var i=s.cssUnit(e);0<i[0]&&(o[e]=i[0]*n+i[1])}),o}}),V.fn.extend({effect:function(){function t(t){var e=V(this),i=V.effects.mode(e,r)||o;e.data(K,!0),l.push(i),o&&("show"===i||i===o&&"hide"===i)&&e.show(),o&&"none"===i||V.effects.saveStyle(e),"function"==typeof t&&t()}var s=X.apply(this,arguments),n=V.effects.effect[s.effect],o=n.mode,e=s.queue,i=e||"fx",a=s.complete,r=s.mode,l=[];return V.fx.off||!n?r?this[r](s.duration,a):this.each(function(){a&&a.call(this)}):!1===e?this.each(t).each(h):this.queue(i,t).queue(i,h);function h(t){var e=V(this);function i(){"function"==typeof a&&a.call(e[0]),"function"==typeof t&&t()}s.mode=l.shift(),!1===V.uiBackCompat||o?"none"===s.mode?(e[r](),i()):n.call(e[0],s,function(){e.removeData(K),V.effects.cleanUp(e),"hide"===s.mode&&e.hide(),i()}):(e.is(":hidden")?"hide"===r:"show"===r)?(e[r](),i()):n.call(e[0],s,i)}},show:(R=V.fn.show,function(t){if($(t))return R.apply(this,arguments);t=X.apply(this,arguments);return t.mode="show",this.effect.call(this,t)}),hide:(L=V.fn.hide,function(t){if($(t))return L.apply(this,arguments);t=X.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)}),toggle:(F=V.fn.toggle,function(t){if($(t)||"boolean"==typeof t)return F.apply(this,arguments);t=X.apply(this,arguments);return t.mode="toggle",this.effect.call(this,t)}),cssUnit:function(t){var i=this.css(t),s=[];return V.each(["em","px","%","pt"],function(t,e){0<i.indexOf(e)&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):G(this.css("clip"),this)},transfer:function(t,e){var i=V(this),s=V(t.to),n="fixed"===s.css("position"),o=V("body"),a=n?o.scrollTop():0,r=n?o.scrollLeft():0,o=s.offset(),o={top:o.top-a,left:o.left-r,height:s.innerHeight(),width:s.innerWidth()},s=i.offset(),l=V("<div class='ui-effects-transfer'></div>");l.appendTo("body").addClass(t.className).css({top:s.top-a,left:s.left-r,height:i.innerHeight(),width:i.innerWidth(),position:n?"fixed":"absolute"}).animate(o,t.duration,t.easing,function(){l.remove(),"function"==typeof e&&e()})}}),V.fx.step.clip=function(t){t.clipInit||(t.start=V(t.elem).cssClip(),"string"==typeof t.end&&(t.end=G(t.end,t.elem)),t.clipInit=!0),V(t.elem).cssClip({top:t.pos*(t.end.top-t.start.top)+t.start.top,right:t.pos*(t.end.right-t.start.right)+t.start.right,bottom:t.pos*(t.end.bottom-t.start.bottom)+t.start.bottom,left:t.pos*(t.end.left-t.start.left)+t.start.left})},Y={},V.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,t){Y[t]=function(t){return Math.pow(t,e+2)}}),V.extend(Y,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;t<((e=Math.pow(2,--i))-1)/11;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),V.each(Y,function(t,e){V.easing["easeIn"+t]=e,V.easing["easeOut"+t]=function(t){return 1-e(1-t)},V.easing["easeInOut"+t]=function(t){return t<.5?e(2*t)/2:1-e(-2*t+2)/2}});y=V.effects,V.effects.define("blind","hide",function(t,e){var i={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},s=V(this),n=t.direction||"up",o=s.cssClip(),a={clip:V.extend({},o)},r=V.effects.createPlaceholder(s);a.clip[i[n][0]]=a.clip[i[n][1]],"show"===t.mode&&(s.cssClip(a.clip),r&&r.css(V.effects.clipToBox(a)),a.clip=o),r&&r.animate(V.effects.clipToBox(a),t.duration,t.easing),s.animate(a,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("bounce",function(t,e){var i,s,n=V(this),o=t.mode,a="hide"===o,r="show"===o,l=t.direction||"up",h=t.distance,c=t.times||5,o=2*c+(r||a?1:0),u=t.duration/o,d=t.easing,p="up"===l||"down"===l?"top":"left",f="up"===l||"left"===l,g=0,t=n.queue().length;for(V.effects.createPlaceholder(n),l=n.css(p),h=h||n["top"==p?"outerHeight":"outerWidth"]()/3,r&&((s={opacity:1})[p]=l,n.css("opacity",0).css(p,f?2*-h:2*h).animate(s,u,d)),a&&(h/=Math.pow(2,c-1)),(s={})[p]=l;g<c;g++)(i={})[p]=(f?"-=":"+=")+h,n.animate(i,u,d).animate(s,u,d),h=a?2*h:h/2;a&&((i={opacity:0})[p]=(f?"-=":"+=")+h,n.animate(i,u,d)),n.queue(e),V.effects.unshift(n,t,1+o)}),V.effects.define("clip","hide",function(t,e){var i={},s=V(this),n=t.direction||"vertical",o="both"===n,a=o||"horizontal"===n,o=o||"vertical"===n,n=s.cssClip();i.clip={top:o?(n.bottom-n.top)/2:n.top,right:a?(n.right-n.left)/2:n.right,bottom:o?(n.bottom-n.top)/2:n.bottom,left:a?(n.right-n.left)/2:n.left},V.effects.createPlaceholder(s),"show"===t.mode&&(s.cssClip(i.clip),i.clip=n),s.animate(i,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("drop","hide",function(t,e){var i=V(this),s="show"===t.mode,n=t.direction||"left",o="up"===n||"down"===n?"top":"left",a="up"===n||"left"===n?"-=":"+=",r="+="==a?"-=":"+=",l={opacity:0};V.effects.createPlaceholder(i),n=t.distance||i["top"==o?"outerHeight":"outerWidth"](!0)/2,l[o]=a+n,s&&(i.css(l),l[o]=r+n,l.opacity=1),i.animate(l,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("explode","hide",function(t,e){var i,s,n,o,a,r,l=t.pieces?Math.round(Math.sqrt(t.pieces)):3,h=l,c=V(this),u="show"===t.mode,d=c.show().css("visibility","hidden").offset(),p=Math.ceil(c.outerWidth()/h),f=Math.ceil(c.outerHeight()/l),g=[];function m(){g.push(this),g.length===l*h&&(c.css({visibility:"visible"}),V(g).remove(),e())}for(i=0;i<l;i++)for(o=d.top+i*f,r=i-(l-1)/2,s=0;s<h;s++)n=d.left+s*p,a=s-(h-1)/2,c.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-s*p,top:-i*f}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:p,height:f,left:n+(u?a*p:0),top:o+(u?r*f:0),opacity:u?0:1}).animate({left:n+(u?0:a*p),top:o+(u?0:r*f),opacity:u?1:0},t.duration||500,t.easing,m)}),V.effects.define("fade","toggle",function(t,e){var i="show"===t.mode;V(this).css("opacity",i?0:1).animate({opacity:i?1:0},{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("fold","hide",function(e,t){var i=V(this),s=e.mode,n="show"===s,o="hide"===s,a=e.size||15,r=/([0-9]+)%/.exec(a),l=!!e.horizFirst?["right","bottom"]:["bottom","right"],h=e.duration/2,c=V.effects.createPlaceholder(i),u=i.cssClip(),d={clip:V.extend({},u)},p={clip:V.extend({},u)},f=[u[l[0]],u[l[1]]],s=i.queue().length;r&&(a=parseInt(r[1],10)/100*f[o?0:1]),d.clip[l[0]]=a,p.clip[l[0]]=a,p.clip[l[1]]=0,n&&(i.cssClip(p.clip),c&&c.css(V.effects.clipToBox(p)),p.clip=u),i.queue(function(t){c&&c.animate(V.effects.clipToBox(d),h,e.easing).animate(V.effects.clipToBox(p),h,e.easing),t()}).animate(d,h,e.easing).animate(p,h,e.easing).queue(t),V.effects.unshift(i,s,4)}),V.effects.define("highlight","show",function(t,e){var i=V(this),s={backgroundColor:i.css("backgroundColor")};"hide"===t.mode&&(s.opacity=0),V.effects.saveStyle(i),i.css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(s,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("size",function(s,e){var n,i=V(this),t=["fontSize"],o=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],a=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],r=s.mode,l="effect"!==r,h=s.scale||"both",c=s.origin||["middle","center"],u=i.css("position"),d=i.position(),p=V.effects.scaledDimensions(i),f=s.from||p,g=s.to||V.effects.scaledDimensions(i,0);V.effects.createPlaceholder(i),"show"===r&&(r=f,f=g,g=r),n={from:{y:f.height/p.height,x:f.width/p.width},to:{y:g.height/p.height,x:g.width/p.width}},"box"!==h&&"both"!==h||(n.from.y!==n.to.y&&(f=V.effects.setTransition(i,o,n.from.y,f),g=V.effects.setTransition(i,o,n.to.y,g)),n.from.x!==n.to.x&&(f=V.effects.setTransition(i,a,n.from.x,f),g=V.effects.setTransition(i,a,n.to.x,g))),"content"!==h&&"both"!==h||n.from.y!==n.to.y&&(f=V.effects.setTransition(i,t,n.from.y,f),g=V.effects.setTransition(i,t,n.to.y,g)),c&&(c=V.effects.getBaseline(c,p),f.top=(p.outerHeight-f.outerHeight)*c.y+d.top,f.left=(p.outerWidth-f.outerWidth)*c.x+d.left,g.top=(p.outerHeight-g.outerHeight)*c.y+d.top,g.left=(p.outerWidth-g.outerWidth)*c.x+d.left),delete f.outerHeight,delete f.outerWidth,i.css(f),"content"!==h&&"both"!==h||(o=o.concat(["marginTop","marginBottom"]).concat(t),a=a.concat(["marginLeft","marginRight"]),i.find("*[width]").each(function(){var t=V(this),e=V.effects.scaledDimensions(t),i={height:e.height*n.from.y,width:e.width*n.from.x,outerHeight:e.outerHeight*n.from.y,outerWidth:e.outerWidth*n.from.x},e={height:e.height*n.to.y,width:e.width*n.to.x,outerHeight:e.height*n.to.y,outerWidth:e.width*n.to.x};n.from.y!==n.to.y&&(i=V.effects.setTransition(t,o,n.from.y,i),e=V.effects.setTransition(t,o,n.to.y,e)),n.from.x!==n.to.x&&(i=V.effects.setTransition(t,a,n.from.x,i),e=V.effects.setTransition(t,a,n.to.x,e)),l&&V.effects.saveStyle(t),t.css(i),t.animate(e,s.duration,s.easing,function(){l&&V.effects.restoreStyle(t)})})),i.animate(g,{queue:!1,duration:s.duration,easing:s.easing,complete:function(){var t=i.offset();0===g.opacity&&i.css("opacity",f.opacity),l||(i.css("position","static"===u?"relative":u).offset(t),V.effects.saveStyle(i)),e()}})}),V.effects.define("scale",function(t,e){var i=V(this),s=t.mode,s=parseInt(t.percent,10)||(0===parseInt(t.percent,10)||"effect"!==s?0:100),s=V.extend(!0,{from:V.effects.scaledDimensions(i),to:V.effects.scaledDimensions(i,s,t.direction||"both"),origin:t.origin||["middle","center"]},t);t.fade&&(s.from.opacity=1,s.to.opacity=0),V.effects.effect.size.call(this,s,e)}),V.effects.define("puff","hide",function(t,e){t=V.extend(!0,{},t,{fade:!0,percent:parseInt(t.percent,10)||150});V.effects.effect.scale.call(this,t,e)}),V.effects.define("pulsate","show",function(t,e){var i=V(this),s=t.mode,n="show"===s,o=2*(t.times||5)+(n||"hide"===s?1:0),a=t.duration/o,r=0,l=1,s=i.queue().length;for(!n&&i.is(":visible")||(i.css("opacity",0).show(),r=1);l<o;l++)i.animate({opacity:r},a,t.easing),r=1-r;i.animate({opacity:r},a,t.easing),i.queue(e),V.effects.unshift(i,s,1+o)}),V.effects.define("shake",function(t,e){var i=1,s=V(this),n=t.direction||"left",o=t.distance||20,a=t.times||3,r=2*a+1,l=Math.round(t.duration/r),h="up"===n||"down"===n?"top":"left",c="up"===n||"left"===n,u={},d={},p={},n=s.queue().length;for(V.effects.createPlaceholder(s),u[h]=(c?"-=":"+=")+o,d[h]=(c?"+=":"-=")+2*o,p[h]=(c?"-=":"+=")+2*o,s.animate(u,l,t.easing);i<a;i++)s.animate(d,l,t.easing).animate(p,l,t.easing);s.animate(d,l,t.easing).animate(u,l/2,t.easing).queue(e),V.effects.unshift(s,n,1+r)}),V.effects.define("slide","show",function(t,e){var i,s,n=V(this),o={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},a=t.mode,r=t.direction||"left",l="up"===r||"down"===r?"top":"left",h="up"===r||"left"===r,c=t.distance||n["top"==l?"outerHeight":"outerWidth"](!0),u={};V.effects.createPlaceholder(n),i=n.cssClip(),s=n.position()[l],u[l]=(h?-1:1)*c+s,u.clip=n.cssClip(),u.clip[o[r][1]]=u.clip[o[r][0]],"show"===a&&(n.cssClip(u.clip),n.css(l,u[l]),u.clip=i,u[l]=s),n.animate(u,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),y=!1!==V.uiBackCompat?V.effects.define("transfer",function(t,e){V(this).transfer(t,e)}):y;V.ui.focusable=function(t,e){var i,s,n,o,a=t.nodeName.toLowerCase();return"area"===a?(s=(i=t.parentNode).name,!(!t.href||!s||"map"!==i.nodeName.toLowerCase())&&(0<(s=V("img[usemap='#"+s+"']")).length&&s.is(":visible"))):(/^(input|select|textarea|button|object)$/.test(a)?(n=!t.disabled)&&(o=V(t).closest("fieldset")[0])&&(n=!o.disabled):n="a"===a&&t.href||e,n&&V(t).is(":visible")&&function(t){var e=t.css("visibility");for(;"inherit"===e;)t=t.parent(),e=t.css("visibility");return"visible"===e}(V(t)))},V.extend(V.expr.pseudos,{focusable:function(t){return V.ui.focusable(t,null!=V.attr(t,"tabindex"))}});var Q,J;V.ui.focusable,V.fn._form=function(){return"string"==typeof this[0].form?this.closest("form"):V(this[0].form)},V.ui.formResetMixin={_formResetHandler:function(){var e=V(this);setTimeout(function(){var t=e.data("ui-form-reset-instances");V.each(t,function(){this.refresh()})})},_bindFormResetHandler:function(){var t;this.form=this.element._form(),this.form.length&&((t=this.form.data("ui-form-reset-instances")||[]).length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t))},_unbindFormResetHandler:function(){var t;this.form.length&&((t=this.form.data("ui-form-reset-instances")).splice(V.inArray(this,t),1),t.length?this.form.data("ui-form-reset-instances",t):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset"))}};V.expr.pseudos||(V.expr.pseudos=V.expr[":"]),V.uniqueSort||(V.uniqueSort=V.unique),V.escapeSelector||(Q=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,J=function(t,e){return e?"\0"===t?"�":t.slice(0,-1)+"\\"+t.charCodeAt(t.length-1).toString(16)+" ":"\\"+t},V.escapeSelector=function(t){return(t+"").replace(Q,J)}),V.fn.even&&V.fn.odd||V.fn.extend({even:function(){return this.filter(function(t){return t%2==0})},odd:function(){return this.filter(function(t){return t%2==1})}});var Z;V.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},V.fn.labels=function(){var t,e,i;return this.length?this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(e=this.eq(0).parents("label"),(t=this.attr("id"))&&(i=(i=this.eq(0).parents().last()).add((i.length?i:this).siblings()),t="label[for='"+V.escapeSelector(t)+"']",e=e.add(i.find(t).addBack(t))),this.pushStack(e)):this.pushStack([])},V.fn.scrollParent=function(t){var e=this.css("position"),i="absolute"===e,s=t?/(auto|scroll|hidden)/:/(auto|scroll)/,t=this.parents().filter(function(){var t=V(this);return(!i||"static"!==t.css("position"))&&s.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==e&&t.length?t:V(this[0].ownerDocument||document)},V.extend(V.expr.pseudos,{tabbable:function(t){var e=V.attr(t,"tabindex"),i=null!=e;return(!i||0<=e)&&V.ui.focusable(t,i)}}),V.fn.extend({uniqueId:(Z=0,function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++Z)})}),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&V(this).removeAttr("id")})}}),V.widget("ui.accordion",{version:"1.13.2",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:function(t){return t.find("> li > :first-child").add(t.find("> :not(li)").even())},heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var t=this.options;this.prevShow=this.prevHide=V(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),t.collapsible||!1!==t.active&&null!=t.active||(t.active=0),this._processPanels(),t.active<0&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():V()}},_createIcons:function(){var t,e=this.options.icons;e&&(t=V("<span>"),this._addClass(t,"ui-accordion-header-icon","ui-icon "+e.header),t.prependTo(this.headers),t=this.active.children(".ui-accordion-header-icon"),this._removeClass(t,e.header)._addClass(t,null,e.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){"active"!==t?("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||!1!==this.options.active||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons())):this._activate(e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(t){if(!t.altKey&&!t.ctrlKey){var e=V.ui.keyCode,i=this.headers.length,s=this.headers.index(t.target),n=!1;switch(t.keyCode){case e.RIGHT:case e.DOWN:n=this.headers[(s+1)%i];break;case e.LEFT:case e.UP:n=this.headers[(s-1+i)%i];break;case e.SPACE:case e.ENTER:this._eventHandler(t);break;case e.HOME:n=this.headers[0];break;case e.END:n=this.headers[i-1]}n&&(V(t.target).attr("tabIndex",-1),V(n).attr("tabIndex",0),V(n).trigger("focus"),t.preventDefault())}},_panelKeyDown:function(t){t.keyCode===V.ui.keyCode.UP&&t.ctrlKey&&V(t.currentTarget).prev().trigger("focus")},refresh:function(){var t=this.options;this._processPanels(),!1===t.active&&!0===t.collapsible||!this.headers.length?(t.active=!1,this.active=V()):!1===t.active?this._activate(0):this.active.length&&!V.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=V()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;"function"==typeof this.options.header?this.headers=this.options.header(this.element):this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var i,t=this.options,e=t.heightStyle,s=this.element.parent();this.active=this._findActive(t.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var t=V(this),e=t.uniqueId().attr("id"),i=t.next(),s=i.uniqueId().attr("id");t.attr("aria-controls",s),i.attr("aria-labelledby",e)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(t.event),"fill"===e?(i=s.height(),this.element.siblings(":visible").each(function(){var t=V(this),e=t.css("position");"absolute"!==e&&"fixed"!==e&&(i-=t.outerHeight(!0))}),this.headers.each(function(){i-=V(this).outerHeight(!0)}),this.headers.next().each(function(){V(this).height(Math.max(0,i-V(this).innerHeight()+V(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.headers.next().each(function(){var t=V(this).is(":visible");t||V(this).show(),i=Math.max(i,V(this).css("height","").height()),t||V(this).hide()}).height(i))},_activate:function(t){t=this._findActive(t)[0];t!==this.active[0]&&(t=t||this.active[0],this._eventHandler({target:t,currentTarget:t,preventDefault:V.noop}))},_findActive:function(t){return"number"==typeof t?this.headers.eq(t):V()},_setupEvents:function(t){var i={keydown:"_keydown"};t&&V.each(t.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var e=this.options,i=this.active,s=V(t.currentTarget),n=s[0]===i[0],o=n&&e.collapsible,a=o?V():s.next(),r=i.next(),a={oldHeader:i,oldPanel:r,newHeader:o?V():s,newPanel:a};t.preventDefault(),n&&!e.collapsible||!1===this._trigger("beforeActivate",t,a)||(e.active=!o&&this.headers.index(s),this.active=n?V():s,this._toggle(a),this._removeClass(i,"ui-accordion-header-active","ui-state-active"),e.icons&&(i=i.children(".ui-accordion-header-icon"),this._removeClass(i,null,e.icons.activeHeader)._addClass(i,null,e.icons.header)),n||(this._removeClass(s,"ui-accordion-header-collapsed")._addClass(s,"ui-accordion-header-active","ui-state-active"),e.icons&&(n=s.children(".ui-accordion-header-icon"),this._removeClass(n,null,e.icons.header)._addClass(n,null,e.icons.activeHeader)),this._addClass(s.next(),"ui-accordion-content-active")))},_toggle:function(t){var e=t.newPanel,i=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=e,this.prevHide=i,this.options.animate?this._animate(e,i,t):(i.hide(),e.show(),this._toggleComplete(t)),i.attr({"aria-hidden":"true"}),i.prev().attr({"aria-selected":"false","aria-expanded":"false"}),e.length&&i.length?i.prev().attr({tabIndex:-1,"aria-expanded":"false"}):e.length&&this.headers.filter(function(){return 0===parseInt(V(this).attr("tabIndex"),10)}).attr("tabIndex",-1),e.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,i,e){var s,n,o,a=this,r=0,l=t.css("box-sizing"),h=t.length&&(!i.length||t.index()<i.index()),c=this.options.animate||{},u=h&&c.down||c,h=function(){a._toggleComplete(e)};return n=(n="string"==typeof u?u:n)||u.easing||c.easing,o=(o="number"==typeof u?u:o)||u.duration||c.duration,i.length?t.length?(s=t.show().outerHeight(),i.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),void t.hide().animate(this.showProps,{duration:o,easing:n,complete:h,step:function(t,e){e.now=Math.round(t),"height"!==e.prop?"content-box"===l&&(r+=e.now):"content"!==a.options.heightStyle&&(e.now=Math.round(s-i.outerHeight()-r),r=0)}})):i.animate(this.hideProps,o,n,h):t.animate(this.showProps,o,n,h)},_toggleComplete:function(t){var e=t.oldPanel,i=e.prev();this._removeClass(e,"ui-accordion-content-active"),this._removeClass(i,"ui-accordion-header-active")._addClass(i,"ui-accordion-header-collapsed"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}}),V.ui.safeActiveElement=function(e){var i;try{i=e.activeElement}catch(t){i=e.body}return i=!(i=i||e.body).nodeName?e.body:i},V.widget("ui.menu",{version:"1.13.2",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.lastMousePosition={x:null,y:null},this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault(),this._activateItem(t)},"click .ui-menu-item":function(t){var e=V(t.target),i=V(V.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&e.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),e.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&i.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this._menuItems().first();e||this.focus(t,i)},blur:function(t){this._delay(function(){V.contains(this.element[0],V.ui.safeActiveElement(this.document[0]))||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t,!0),this.mouseHandled=!1}})},_activateItem:function(t){var e,i;this.previousFilter||t.clientX===this.lastMousePosition.x&&t.clientY===this.lastMousePosition.y||(this.lastMousePosition={x:t.clientX,y:t.clientY},e=V(t.target).closest(".ui-menu-item"),i=V(t.currentTarget),e[0]===i[0]&&(i.is(".ui-state-active")||(this._removeClass(i.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(t,i))))},_destroy:function(){var t=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),t.children().each(function(){var t=V(this);t.data("ui-menu-submenu-caret")&&t.remove()})},_keydown:function(t){var e,i,s,n=!0;switch(t.keyCode){case V.ui.keyCode.PAGE_UP:this.previousPage(t);break;case V.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case V.ui.keyCode.HOME:this._move("first","first",t);break;case V.ui.keyCode.END:this._move("last","last",t);break;case V.ui.keyCode.UP:this.previous(t);break;case V.ui.keyCode.DOWN:this.next(t);break;case V.ui.keyCode.LEFT:this.collapse(t);break;case V.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case V.ui.keyCode.ENTER:case V.ui.keyCode.SPACE:this._activate(t);break;case V.ui.keyCode.ESCAPE:this.collapse(t);break;default:e=this.previousFilter||"",s=n=!1,i=96<=t.keyCode&&t.keyCode<=105?(t.keyCode-96).toString():String.fromCharCode(t.keyCode),clearTimeout(this.filterTimer),i===e?s=!0:i=e+i,e=this._filterMenuItems(i),(e=s&&-1!==e.index(this.active.next())?this.active.nextAll(".ui-menu-item"):e).length||(i=String.fromCharCode(t.keyCode),e=this._filterMenuItems(i)),e.length?(this.focus(t,e),this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}n&&t.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var t,e,s=this,n=this.options.icons.submenu,i=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),e=i.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=V(this),e=t.prev(),i=V("<span>").data("ui-menu-submenu-caret",!0);s._addClass(i,"ui-menu-icon","ui-icon "+n),e.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",e.attr("id"))}),this._addClass(e,"ui-menu","ui-widget ui-widget-content ui-front"),(t=i.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var t=V(this);s._isDivider(t)&&s._addClass(t,"ui-menu-divider","ui-widget-content")}),i=(e=t.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(e,"ui-menu-item")._addClass(i,"ui-menu-item-wrapper"),t.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!V.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){var i;"icons"===t&&(i=this.element.find(".ui-menu-icon"),this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",String(t)),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),i=this.active.children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",i.attr("id")),i=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=e.children(".ui-menu")).length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(t){var e,i,s;this._hasScroll()&&(i=parseFloat(V.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(V.css(this.activeMenu[0],"paddingTop"))||0,e=t.offset().top-this.activeMenu.offset().top-i-s,i=this.activeMenu.scrollTop(),s=this.activeMenu.height(),t=t.outerHeight(),e<0?this.activeMenu.scrollTop(i+e):s<e+t&&this.activeMenu.scrollTop(i+e-s+t))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(t){var e=V.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(e)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var t=i?this.element:V(e&&e.target).closest(this.element.find(".ui-menu"));t.length||(t=this.element),this._close(t),this.blur(e),this._removeClass(t.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=t},i?0:this.delay)},_close:function(t){(t=t||(this.active?this.active.parent():this.element)).find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(t){return!V(t.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this._menuItems(this.active.children(".ui-menu")).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_menuItems:function(t){return(t||this.element).find(this.options.items).filter(".ui-menu-item")},_move:function(t,e,i){var s;(s=this.active?"first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").last():this.active[t+"All"](".ui-menu-item").first():s)&&s.length&&this.active||(s=this._menuItems(this.activeMenu)[e]()),this.focus(i,s)},nextPage:function(t){var e,i,s;this.active?this.isLastItem()||(this._hasScroll()?(i=this.active.offset().top,s=this.element.innerHeight(),0===V.fn.jquery.indexOf("3.2.")&&(s+=this.element[0].offsetHeight-this.element.outerHeight()),this.active.nextAll(".ui-menu-item").each(function(){return(e=V(this)).offset().top-i-s<0}),this.focus(t,e)):this.focus(t,this._menuItems(this.activeMenu)[this.active?"last":"first"]())):this.next(t)},previousPage:function(t){var e,i,s;this.active?this.isFirstItem()||(this._hasScroll()?(i=this.active.offset().top,s=this.element.innerHeight(),0===V.fn.jquery.indexOf("3.2.")&&(s+=this.element[0].offsetHeight-this.element.outerHeight()),this.active.prevAll(".ui-menu-item").each(function(){return 0<(e=V(this)).offset().top-i+s}),this.focus(t,e)):this.focus(t,this._menuItems(this.activeMenu).first())):this.next(t)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||V(t.target).closest(".ui-menu-item");var e={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,e)},_filterMenuItems:function(t){var t=t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),e=new RegExp("^"+t,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return e.test(String.prototype.trim.call(V(this).children(".ui-menu-item-wrapper").text()))})}});V.widget("ui.autocomplete",{version:"1.13.2",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,liveRegionTimer:null,_create:function(){var i,s,n,t=this.element[0].nodeName.toLowerCase(),e="textarea"===t,t="input"===t;this.isMultiLine=e||!t&&this._isContentEditable(this.element),this.valueMethod=this.element[e||t?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(t){if(this.element.prop("readOnly"))s=n=i=!0;else{s=n=i=!1;var e=V.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:i=!0,this._move("previousPage",t);break;case e.PAGE_DOWN:i=!0,this._move("nextPage",t);break;case e.UP:i=!0,this._keyEvent("previous",t);break;case e.DOWN:i=!0,this._keyEvent("next",t);break;case e.ENTER:this.menu.active&&(i=!0,t.preventDefault(),this.menu.select(t));break;case e.TAB:this.menu.active&&this.menu.select(t);break;case e.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(t),t.preventDefault());break;default:s=!0,this._searchTimeout(t)}}},keypress:function(t){if(i)return i=!1,void(this.isMultiLine&&!this.menu.element.is(":visible")||t.preventDefault());if(!s){var e=V.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:this._move("previousPage",t);break;case e.PAGE_DOWN:this._move("nextPage",t);break;case e.UP:this._keyEvent("previous",t);break;case e.DOWN:this._keyEvent("next",t)}}},input:function(t){if(n)return n=!1,void t.preventDefault();this._searchTimeout(t)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){clearTimeout(this.searching),this.close(t),this._change(t)}}),this._initSource(),this.menu=V("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().attr({unselectable:"on"}).menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault()},menufocus:function(t,e){var i,s;if(this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type)))return this.menu.blur(),void this.document.one("mousemove",function(){V(t.target).trigger(t.originalEvent)});s=e.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:s})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(s.value),(i=e.item.attr("aria-label")||s.value)&&String.prototype.trim.call(i).length&&(clearTimeout(this.liveRegionTimer),this.liveRegionTimer=this._delay(function(){this.liveRegion.html(V("<div>").text(i))},100))},menuselect:function(t,e){var i=e.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==V.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",t,{item:i})&&this._value(i.value),this.term=this._value(),this.close(t),this.selectedItem=i}}),this.liveRegion=V("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(t){var e=this.menu.element[0];return t.target===this.element[0]||t.target===e||V.contains(e,t.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var t=this.options.appendTo;return t=!(t=!(t=t&&(t.jquery||t.nodeType?V(t):this.document.find(t).eq(0)))||!t[0]?this.element.closest(".ui-front, dialog"):t).length?this.document[0].body:t},_initSource:function(){var i,s,n=this;Array.isArray(this.options.source)?(i=this.options.source,this.source=function(t,e){e(V.ui.autocomplete.filter(i,t.term))}):"string"==typeof this.options.source?(s=this.options.source,this.source=function(t,e){n.xhr&&n.xhr.abort(),n.xhr=V.ajax({url:s,data:t,dataType:"json",success:function(t){e(t)},error:function(){e([])}})}):this.source=this.options.source},_searchTimeout:function(s){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),e=this.menu.element.is(":visible"),i=s.altKey||s.ctrlKey||s.metaKey||s.shiftKey;t&&(e||i)||(this.selectedItem=null,this.search(null,s))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):!1!==this._trigger("search",e)?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")}.bind(this)},__response:function(t){t=t&&this._normalize(t),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this._off(this.document,"mousedown"),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:V.map(t,function(t){return"string"==typeof t?{label:t,value:t}:V.extend({},t,{label:t.label||t.value,value:t.value||t.label})})},_suggest:function(t){var e=this.menu.element.empty();this._renderMenu(e,t),this.isNewMenu=!0,this.menu.refresh(),e.show(),this._resizeMenu(),e.position(V.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(),this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(i,t){var s=this;V.each(t,function(t,e){s._renderItemData(i,e)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(t,e){return V("<li>").append(V("<div>").text(e.label)).appendTo(t)},_move:function(t,e){if(this.menu.element.is(":visible"))return this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),void this.menu.blur()):void this.menu[t](e);this.search(null,e)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){this.isMultiLine&&!this.menu.element.is(":visible")||(this._move(t,e),e.preventDefault())},_isContentEditable:function(t){if(!t.length)return!1;var e=t.prop("contentEditable");return"inherit"===e?this._isContentEditable(t.parent()):"true"===e}}),V.extend(V.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,e){var i=new RegExp(V.ui.autocomplete.escapeRegex(e),"i");return V.grep(t,function(t){return i.test(t.label||t.value||t)})}}),V.widget("ui.autocomplete",V.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(1<t?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var e;this._superApply(arguments),this.options.disabled||this.cancelSearch||(e=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,clearTimeout(this.liveRegionTimer),this.liveRegionTimer=this._delay(function(){this.liveRegion.html(V("<div>").text(e))},100))}});V.ui.autocomplete;var tt=/ui-corner-([a-z]){2,6}/g;V.widget("ui.controlgroup",{version:"1.13.2",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:!0,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar"),this.refresh()},_destroy:function(){this._callChildMethod("destroy"),this.childWidgets.removeData("ui-controlgroup-data"),this.element.removeAttr("role"),this.options.items.controlgroupLabel&&this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()},_initWidgets:function(){var o=this,a=[];V.each(this.options.items,function(s,t){var e,n={};if(t)return"controlgroupLabel"===s?((e=o.element.find(t)).each(function(){var t=V(this);t.children(".ui-controlgroup-label-contents").length||t.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),o._addClass(e,null,"ui-widget ui-widget-content ui-state-default"),void(a=a.concat(e.get()))):void(V.fn[s]&&(n=o["_"+s+"Options"]?o["_"+s+"Options"]("middle"):{classes:{}},o.element.find(t).each(function(){var t=V(this),e=t[s]("instance"),i=V.widget.extend({},n);"button"===s&&t.parent(".ui-spinner").length||((e=e||t[s]()[s]("instance"))&&(i.classes=o._resolveClassesValues(i.classes,e)),t[s](i),i=t[s]("widget"),V.data(i[0],"ui-controlgroup-data",e||t[s]("instance")),a.push(i[0]))})))}),this.childWidgets=V(V.uniqueSort(a)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var t=V(this).data("ui-controlgroup-data");t&&t[e]&&t[e]()})},_updateCornerClass:function(t,e){e=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,"ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all"),this._addClass(t,null,e)},_buildSimpleOptions:function(t,e){var i="vertical"===this.options.direction,s={classes:{}};return s.classes[e]={middle:"",first:"ui-corner-"+(i?"top":"left"),last:"ui-corner-"+(i?"bottom":"right"),only:"ui-corner-all"}[t],s},_spinnerOptions:function(t){t=this._buildSimpleOptions(t,"ui-spinner");return t.classes["ui-spinner-up"]="",t.classes["ui-spinner-down"]="",t},_buttonOptions:function(t){return this._buildSimpleOptions(t,"ui-button")},_checkboxradioOptions:function(t){return this._buildSimpleOptions(t,"ui-checkboxradio-label")},_selectmenuOptions:function(t){var e="vertical"===this.options.direction;return{width:e&&"auto",classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(e?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(e?"top":"left")},last:{"ui-selectmenu-button-open":e?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(e?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[t]}},_resolveClassesValues:function(i,s){var n={};return V.each(i,function(t){var e=s.options.classes[t]||"",e=String.prototype.trim.call(e.replace(tt,""));n[t]=(e+" "+i[t]).replace(/\s+/g," ")}),n},_setOption:function(t,e){"direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"!==t?this.refresh():this._callChildMethod(e?"disable":"enable")},refresh:function(){var n,o=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),n=this.childWidgets,(n=this.options.onlyVisible?n.filter(":visible"):n).length&&(V.each(["first","last"],function(t,e){var i,s=n[e]().data("ui-controlgroup-data");s&&o["_"+s.widgetName+"Options"]?((i=o["_"+s.widgetName+"Options"](1===n.length?"only":e)).classes=o._resolveClassesValues(i.classes,s),s.element[s.widgetName](i)):o._updateCornerClass(n[e](),e)}),this._callChildMethod("refresh"))}});V.widget("ui.checkboxradio",[V.ui.formResetMixin,{version:"1.13.2",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var t,e=this._super()||{};return this._readType(),t=this.element.labels(),this.label=V(t[t.length-1]),this.label.length||V.error("No label found for checkboxradio widget"),this.originalLabel="",(t=this.label.contents().not(this.element[0])).length&&(this.originalLabel+=t.clone().wrapAll("<div></div>").parent().html()),this.originalLabel&&(e.label=this.originalLabel),null!=(t=this.element[0].disabled)&&(e.disabled=t),e},_create:function(){var t=this.element[0].checked;this._bindFormResetHandler(),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled),this._setOption("disabled",this.options.disabled),this._addClass("ui-checkboxradio","ui-helper-hidden-accessible"),this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget"),"radio"===this.type&&this._addClass(this.label,"ui-checkboxradio-radio-label"),this.options.label&&this.options.label!==this.originalLabel?this._updateLabel():this.originalLabel&&(this.options.label=this.originalLabel),this._enhance(),t&&this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active"),this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var t=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===t&&/radio|checkbox/.test(this.type)||V.error("Can't create checkboxradio on element.nodeName="+t+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var t=this.element[0].name,e="input[name='"+V.escapeSelector(t)+"']";return t?(this.form.length?V(this.form[0].elements).filter(e):V(e).filter(function(){return 0===V(this)._form().length})).not(this.element):V([])},_toggleClasses:function(){var t=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",t)._toggleClass(this.icon,null,"ui-icon-blank",!t),"radio"===this.type&&this._getRadioGroup().each(function(){var t=V(this).checkboxradio("instance");t&&t._removeClass(t.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){if("label"!==t||e){if(this._super(t,e),"disabled"===t)return this._toggleClass(this.label,null,"ui-state-disabled",e),void(this.element[0].disabled=e);this.refresh()}},_updateIcon:function(t){var e="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=V("<span>"),this.iconSpace=V("<span> </span>"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(e+=t?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,t?"ui-icon-blank":"ui-icon-check")):e+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",e),t||this._removeClass(this.icon,null,"ui-icon-check ui-state-checked"),this.icon.prependTo(this.label).after(this.iconSpace)):void 0!==this.icon&&(this.icon.remove(),this.iconSpace.remove(),delete this.icon)},_updateLabel:function(){var t=this.label.contents().not(this.element[0]);this.icon&&(t=t.not(this.icon[0])),(t=this.iconSpace?t.not(this.iconSpace[0]):t).remove(),this.label.append(this.options.label)},refresh:function(){var t=this.element[0].checked,e=this.element[0].disabled;this._updateIcon(t),this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),null!==this.options.label&&this._updateLabel(),e!==this.options.disabled&&this._setOptions({disabled:e})}}]);var et;V.ui.checkboxradio;V.widget("ui.button",{version:"1.13.2",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:!0},_getCreateOptions:function(){var t,e=this._super()||{};return this.isInput=this.element.is("input"),null!=(t=this.element[0].disabled)&&(e.disabled=t),this.originalLabel=this.isInput?this.element.val():this.element.html(),this.originalLabel&&(e.label=this.originalLabel),e},_create:function(){!this.option.showLabel&!this.options.icon&&(this.options.showLabel=!0),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled||!1),this.hasTitle=!!this.element.attr("title"),this.options.label&&this.options.label!==this.originalLabel&&(this.isInput?this.element.val(this.options.label):this.element.html(this.options.label)),this._addClass("ui-button","ui-widget"),this._setOption("disabled",this.options.disabled),this._enhance(),this.element.is("a")&&this._on({keyup:function(t){t.keyCode===V.ui.keyCode.SPACE&&(t.preventDefault(),this.element[0].click?this.element[0].click():this.element.trigger("click"))}})},_enhance:function(){this.element.is("button")||this.element.attr("role","button"),this.options.icon&&(this._updateIcon("icon",this.options.icon),this._updateTooltip())},_updateTooltip:function(){this.title=this.element.attr("title"),this.options.showLabel||this.title||this.element.attr("title",this.options.label)},_updateIcon:function(t,e){var i="iconPosition"!==t,s=i?this.options.iconPosition:e,t="top"===s||"bottom"===s;this.icon?i&&this._removeClass(this.icon,null,this.options.icon):(this.icon=V("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),i&&this._addClass(this.icon,null,e),this._attachIcon(s),t?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconSpace||(this.iconSpace=V("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(s))},_destroy:function(){this.element.removeAttr("role"),this.icon&&this.icon.remove(),this.iconSpace&&this.iconSpace.remove(),this.hasTitle||this.element.removeAttr("title")},_attachIconSpace:function(t){this.icon[/^(?:end|bottom)/.test(t)?"before":"after"](this.iconSpace)},_attachIcon:function(t){this.element[/^(?:end|bottom)/.test(t)?"append":"prepend"](this.icon)},_setOptions:function(t){var e=(void 0===t.showLabel?this.options:t).showLabel,i=(void 0===t.icon?this.options:t).icon;e||i||(t.showLabel=!0),this._super(t)},_setOption:function(t,e){"icon"===t&&(e?this._updateIcon(t,e):this.icon&&(this.icon.remove(),this.iconSpace&&this.iconSpace.remove())),"iconPosition"===t&&this._updateIcon(t,e),"showLabel"===t&&(this._toggleClass("ui-button-icon-only",null,!e),this._updateTooltip()),"label"===t&&(this.isInput?this.element.val(e):(this.element.html(e),this.icon&&(this._attachIcon(this.options.iconPosition),this._attachIconSpace(this.options.iconPosition)))),this._super(t,e),"disabled"===t&&(this._toggleClass(null,"ui-state-disabled",e),(this.element[0].disabled=e)&&this.element.trigger("blur"))},refresh:function(){var t=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOptions({disabled:t}),this._updateTooltip()}}),!1!==V.uiBackCompat&&(V.widget("ui.button",V.ui.button,{options:{text:!0,icons:{primary:null,secondary:null}},_create:function(){this.options.showLabel&&!this.options.text&&(this.options.showLabel=this.options.text),!this.options.showLabel&&this.options.text&&(this.options.text=this.options.showLabel),this.options.icon||!this.options.icons.primary&&!this.options.icons.secondary?this.options.icon&&(this.options.icons.primary=this.options.icon):this.options.icons.primary?this.options.icon=this.options.icons.primary:(this.options.icon=this.options.icons.secondary,this.options.iconPosition="end"),this._super()},_setOption:function(t,e){"text"!==t?("showLabel"===t&&(this.options.text=e),"icon"===t&&(this.options.icons.primary=e),"icons"===t&&(e.primary?(this._super("icon",e.primary),this._super("iconPosition","beginning")):e.secondary&&(this._super("icon",e.secondary),this._super("iconPosition","end"))),this._superApply(arguments)):this._super("showLabel",e)}}),V.fn.button=(et=V.fn.button,function(i){var t="string"==typeof i,s=Array.prototype.slice.call(arguments,1),n=this;return t?this.length||"instance"!==i?this.each(function(){var t=V(this).attr("type"),e=V.data(this,"ui-"+("checkbox"!==t&&"radio"!==t?"button":"checkboxradio"));return"instance"===i?(n=e,!1):e?"function"!=typeof e[i]||"_"===i.charAt(0)?V.error("no such method '"+i+"' for button widget instance"):(t=e[i].apply(e,s))!==e&&void 0!==t?(n=t&&t.jquery?n.pushStack(t.get()):t,!1):void 0:V.error("cannot call methods on button prior to initialization; attempted to call method '"+i+"'")}):n=void 0:(s.length&&(i=V.widget.extend.apply(null,[i].concat(s))),this.each(function(){var t=V(this).attr("type"),e="checkbox"!==t&&"radio"!==t?"button":"checkboxradio",t=V.data(this,"ui-"+e);t?(t.option(i||{}),t._init&&t._init()):"button"!=e?V(this).checkboxradio(V.extend({icon:!1},i)):et.call(V(this),i)})),n}),V.fn.buttonset=function(){return V.ui.controlgroup||V.error("Controlgroup widget missing"),"option"===arguments[0]&&"items"===arguments[1]&&arguments[2]?this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]):"option"===arguments[0]&&"items"===arguments[1]?this.controlgroup.apply(this,[arguments[0],"items.button"]):("object"==typeof arguments[0]&&arguments[0].items&&(arguments[0].items={button:arguments[0].items}),this.controlgroup.apply(this,arguments))});var it;V.ui.button;function st(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:"",selectMonthLabel:"Select month",selectYearLabel:"Select year"},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,onUpdateDatepicker:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},V.extend(this._defaults,this.regional[""]),this.regional.en=V.extend(!0,{},this.regional[""]),this.regional["en-US"]=V.extend(!0,{},this.regional.en),this.dpDiv=nt(V("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function nt(t){var e="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.on("mouseout",e,function(){V(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&V(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&V(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",e,ot)}function ot(){V.datepicker._isDisabledDatepicker((it.inline?it.dpDiv.parent():it.input)[0])||(V(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),V(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&V(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&V(this).addClass("ui-datepicker-next-hover"))}function at(t,e){for(var i in V.extend(t,e),e)null==e[i]&&(t[i]=e[i]);return t}V.extend(V.ui,{datepicker:{version:"1.13.2"}}),V.extend(st.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return at(this._defaults,t||{}),this},_attachDatepicker:function(t,e){var i,s=t.nodeName.toLowerCase(),n="div"===s||"span"===s;t.id||(this.uuid+=1,t.id="dp"+this.uuid),(i=this._newInst(V(t),n)).settings=V.extend({},e||{}),"input"===s?this._connectDatepicker(t,i):n&&this._inlineDatepicker(t,i)},_newInst:function(t,e){return{id:t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1"),input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:e,dpDiv:e?nt(V("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,e){var i=V(t);e.append=V([]),e.trigger=V([]),i.hasClass(this.markerClassName)||(this._attachments(i,e),i.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(e),V.data(t,"datepicker",e),e.settings.disabled&&this._disableDatepicker(t))},_attachments:function(t,e){var i,s=this._get(e,"appendText"),n=this._get(e,"isRTL");e.append&&e.append.remove(),s&&(e.append=V("<span>").addClass(this._appendClass).text(s),t[n?"before":"after"](e.append)),t.off("focus",this._showDatepicker),e.trigger&&e.trigger.remove(),"focus"!==(i=this._get(e,"showOn"))&&"both"!==i||t.on("focus",this._showDatepicker),"button"!==i&&"both"!==i||(s=this._get(e,"buttonText"),i=this._get(e,"buttonImage"),this._get(e,"buttonImageOnly")?e.trigger=V("<img>").addClass(this._triggerClass).attr({src:i,alt:s,title:s}):(e.trigger=V("<button type='button'>").addClass(this._triggerClass),i?e.trigger.html(V("<img>").attr({src:i,alt:s,title:s})):e.trigger.text(s)),t[n?"before":"after"](e.trigger),e.trigger.on("click",function(){return V.datepicker._datepickerShowing&&V.datepicker._lastInput===t[0]?V.datepicker._hideDatepicker():(V.datepicker._datepickerShowing&&V.datepicker._lastInput!==t[0]&&V.datepicker._hideDatepicker(),V.datepicker._showDatepicker(t[0])),!1}))},_autoSize:function(t){var e,i,s,n,o,a;this._get(t,"autoSize")&&!t.inline&&(o=new Date(2009,11,20),(a=this._get(t,"dateFormat")).match(/[DM]/)&&(e=function(t){for(n=s=i=0;n<t.length;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length))},_inlineDatepicker:function(t,e){var i=V(t);i.hasClass(this.markerClassName)||(i.addClass(this.markerClassName).append(e.dpDiv),V.data(t,"datepicker",e),this._setDate(e,this._getDefaultDate(e),!0),this._updateDatepicker(e),this._updateAlternate(e),e.settings.disabled&&this._disableDatepicker(t),e.dpDiv.css("display","block"))},_dialogDatepicker:function(t,e,i,s,n){var o,a=this._dialogInst;return a||(this.uuid+=1,o="dp"+this.uuid,this._dialogInput=V("<input type='text' id='"+o+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.on("keydown",this._doKeyDown),V("body").append(this._dialogInput),(a=this._dialogInst=this._newInst(this._dialogInput,!1)).settings={},V.data(this._dialogInput[0],"datepicker",a)),at(a.settings,s||{}),e=e&&e.constructor===Date?this._formatDate(a,e):e,this._dialogInput.val(e),this._pos=n?n.length?n:[n.pageX,n.pageY]:null,this._pos||(o=document.documentElement.clientWidth,s=document.documentElement.clientHeight,e=document.documentElement.scrollLeft||document.body.scrollLeft,n=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[o/2-100+e,s/2-150+n]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),a.settings.onSelect=i,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),V.blockUI&&V.blockUI(this.dpDiv),V.data(this._dialogInput[0],"datepicker",a),this},_destroyDatepicker:function(t){var e,i=V(t),s=V.data(t,"datepicker");i.hasClass(this.markerClassName)&&(e=t.nodeName.toLowerCase(),V.removeData(t,"datepicker"),"input"===e?(s.append.remove(),s.trigger.remove(),i.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):"div"!==e&&"span"!==e||i.removeClass(this.markerClassName).empty(),it===s&&(it=null,this._curInst=null))},_enableDatepicker:function(e){var t,i=V(e),s=V.data(e,"datepicker");i.hasClass(this.markerClassName)&&("input"===(t=e.nodeName.toLowerCase())?(e.disabled=!1,s.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):"div"!==t&&"span"!==t||((i=i.children("."+this._inlineClass)).children().removeClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=V.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var t,i=V(e),s=V.data(e,"datepicker");i.hasClass(this.markerClassName)&&("input"===(t=e.nodeName.toLowerCase())?(e.disabled=!0,s.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):"div"!==t&&"span"!==t||((i=i.children("."+this._inlineClass)).children().addClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=V.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;e<this._disabledInputs.length;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(t){try{return V.data(t,"datepicker")}catch(t){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(t,e,i){var s,n,o=this._getInst(t);if(2===arguments.length&&"string"==typeof e)return"defaults"===e?V.extend({},V.datepicker._defaults):o?"all"===e?V.extend({},o.settings):this._get(o,e):null;s=e||{},"string"==typeof e&&((s={})[e]=i),o&&(this._curInst===o&&this._hideDatepicker(),n=this._getDateDatepicker(t,!0),e=this._getMinMaxDate(o,"min"),i=this._getMinMaxDate(o,"max"),at(o.settings,s),null!==e&&void 0!==s.dateFormat&&void 0===s.minDate&&(o.settings.minDate=this._formatDate(o,e)),null!==i&&void 0!==s.dateFormat&&void 0===s.maxDate&&(o.settings.maxDate=this._formatDate(o,i)),"disabled"in s&&(s.disabled?this._disableDatepicker(t):this._enableDatepicker(t)),this._attachments(V(t),o),this._autoSize(o),this._setDate(o,n),this._updateAlternate(o),this._updateDatepicker(o))},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){t=this._getInst(t);t&&this._updateDatepicker(t)},_setDateDatepicker:function(t,e){t=this._getInst(t);t&&(this._setDate(t,e),this._updateDatepicker(t),this._updateAlternate(t))},_getDateDatepicker:function(t,e){t=this._getInst(t);return t&&!t.inline&&this._setDateFromField(t,e),t?this._getDate(t):null},_doKeyDown:function(t){var e,i,s=V.datepicker._getInst(t.target),n=!0,o=s.dpDiv.is(".ui-datepicker-rtl");if(s._keyEvent=!0,V.datepicker._datepickerShowing)switch(t.keyCode){case 9:V.datepicker._hideDatepicker(),n=!1;break;case 13:return(i=V("td."+V.datepicker._dayOverClass+":not(."+V.datepicker._currentClass+")",s.dpDiv))[0]&&V.datepicker._selectDay(t.target,s.selectedMonth,s.selectedYear,i[0]),(e=V.datepicker._get(s,"onSelect"))?(i=V.datepicker._formatDate(s),e.apply(s.input?s.input[0]:null,[i,s])):V.datepicker._hideDatepicker(),!1;case 27:V.datepicker._hideDatepicker();break;case 33:V.datepicker._adjustDate(t.target,t.ctrlKey?-V.datepicker._get(s,"stepBigMonths"):-V.datepicker._get(s,"stepMonths"),"M");break;case 34:V.datepicker._adjustDate(t.target,t.ctrlKey?+V.datepicker._get(s,"stepBigMonths"):+V.datepicker._get(s,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&V.datepicker._clearDate(t.target),n=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&V.datepicker._gotoToday(t.target),n=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,o?1:-1,"D"),n=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&V.datepicker._adjustDate(t.target,t.ctrlKey?-V.datepicker._get(s,"stepBigMonths"):-V.datepicker._get(s,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,-7,"D"),n=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,o?-1:1,"D"),n=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&V.datepicker._adjustDate(t.target,t.ctrlKey?+V.datepicker._get(s,"stepBigMonths"):+V.datepicker._get(s,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&V.datepicker._adjustDate(t.target,7,"D"),n=t.ctrlKey||t.metaKey;break;default:n=!1}else 36===t.keyCode&&t.ctrlKey?V.datepicker._showDatepicker(this):n=!1;n&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(t){var e,i=V.datepicker._getInst(t.target);if(V.datepicker._get(i,"constrainInput"))return e=V.datepicker._possibleChars(V.datepicker._get(i,"dateFormat")),i=String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),t.ctrlKey||t.metaKey||i<" "||!e||-1<e.indexOf(i)},_doKeyUp:function(t){t=V.datepicker._getInst(t.target);if(t.input.val()!==t.lastVal)try{V.datepicker.parseDate(V.datepicker._get(t,"dateFormat"),t.input?t.input.val():null,V.datepicker._getFormatConfig(t))&&(V.datepicker._setDateFromField(t),V.datepicker._updateAlternate(t),V.datepicker._updateDatepicker(t))}catch(t){}return!0},_showDatepicker:function(t){var e,i,s,n;"input"!==(t=t.target||t).nodeName.toLowerCase()&&(t=V("input",t.parentNode)[0]),V.datepicker._isDisabledDatepicker(t)||V.datepicker._lastInput===t||(n=V.datepicker._getInst(t),V.datepicker._curInst&&V.datepicker._curInst!==n&&(V.datepicker._curInst.dpDiv.stop(!0,!0),n&&V.datepicker._datepickerShowing&&V.datepicker._hideDatepicker(V.datepicker._curInst.input[0])),!1!==(i=(s=V.datepicker._get(n,"beforeShow"))?s.apply(t,[t,n]):{})&&(at(n.settings,i),n.lastVal=null,V.datepicker._lastInput=t,V.datepicker._setDateFromField(n),V.datepicker._inDialog&&(t.value=""),V.datepicker._pos||(V.datepicker._pos=V.datepicker._findPos(t),V.datepicker._pos[1]+=t.offsetHeight),e=!1,V(t).parents().each(function(){return!(e|="fixed"===V(this).css("position"))}),s={left:V.datepicker._pos[0],top:V.datepicker._pos[1]},V.datepicker._pos=null,n.dpDiv.empty(),n.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),V.datepicker._updateDatepicker(n),s=V.datepicker._checkOffset(n,s,e),n.dpDiv.css({position:V.datepicker._inDialog&&V.blockUI?"static":e?"fixed":"absolute",display:"none",left:s.left+"px",top:s.top+"px"}),n.inline||(i=V.datepicker._get(n,"showAnim"),s=V.datepicker._get(n,"duration"),n.dpDiv.css("z-index",function(t){for(var e,i;t.length&&t[0]!==document;){if(("absolute"===(e=t.css("position"))||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}(V(t))+1),V.datepicker._datepickerShowing=!0,V.effects&&V.effects.effect[i]?n.dpDiv.show(i,V.datepicker._get(n,"showOptions"),s):n.dpDiv[i||"show"](i?s:null),V.datepicker._shouldFocusInput(n)&&n.input.trigger("focus"),V.datepicker._curInst=n)))},_updateDatepicker:function(t){this.maxRows=4,(it=t).dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t);var e,i=this._getNumberOfMonths(t),s=i[1],n=t.dpDiv.find("."+this._dayOverClass+" a"),o=V.datepicker._get(t,"onUpdateDatepicker");0<n.length&&ot.apply(n.get(0)),t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),1<s&&t.dpDiv.addClass("ui-datepicker-multi-"+s).css("width",17*s+"em"),t.dpDiv[(1!==i[0]||1!==i[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===V.datepicker._curInst&&V.datepicker._datepickerShowing&&V.datepicker._shouldFocusInput(t)&&t.input.trigger("focus"),t.yearshtml&&(e=t.yearshtml,setTimeout(function(){e===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year").first().replaceWith(t.yearshtml),e=t.yearshtml=null},0)),o&&o.apply(t.input?t.input[0]:null,[t])},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(t,e,i){var s=t.dpDiv.outerWidth(),n=t.dpDiv.outerHeight(),o=t.input?t.input.outerWidth():0,a=t.input?t.input.outerHeight():0,r=document.documentElement.clientWidth+(i?0:V(document).scrollLeft()),l=document.documentElement.clientHeight+(i?0:V(document).scrollTop());return e.left-=this._get(t,"isRTL")?s-o:0,e.left-=i&&e.left===t.input.offset().left?V(document).scrollLeft():0,e.top-=i&&e.top===t.input.offset().top+a?V(document).scrollTop():0,e.left-=Math.min(e.left,e.left+s>r&&s<r?Math.abs(e.left+s-r):0),e.top-=Math.min(e.top,e.top+n>l&&n<l?Math.abs(n+a):0),e},_findPos:function(t){for(var e=this._getInst(t),i=this._get(e,"isRTL");t&&("hidden"===t.type||1!==t.nodeType||V.expr.pseudos.hidden(t));)t=t[i?"previousSibling":"nextSibling"];return[(e=V(t).offset()).left,e.top]},_hideDatepicker:function(t){var e,i,s=this._curInst;!s||t&&s!==V.data(t,"datepicker")||this._datepickerShowing&&(e=this._get(s,"showAnim"),i=this._get(s,"duration"),t=function(){V.datepicker._tidyDialog(s)},V.effects&&(V.effects.effect[e]||V.effects[e])?s.dpDiv.hide(e,V.datepicker._get(s,"showOptions"),i,t):s.dpDiv["slideDown"===e?"slideUp":"fadeIn"===e?"fadeOut":"hide"](e?i:null,t),e||t(),this._datepickerShowing=!1,(t=this._get(s,"onClose"))&&t.apply(s.input?s.input[0]:null,[s.input?s.input.val():"",s]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),V.blockUI&&(V.unblockUI(),V("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(t){var e;V.datepicker._curInst&&(e=V(t.target),t=V.datepicker._getInst(e[0]),(e[0].id===V.datepicker._mainDivId||0!==e.parents("#"+V.datepicker._mainDivId).length||e.hasClass(V.datepicker.markerClassName)||e.closest("."+V.datepicker._triggerClass).length||!V.datepicker._datepickerShowing||V.datepicker._inDialog&&V.blockUI)&&(!e.hasClass(V.datepicker.markerClassName)||V.datepicker._curInst===t)||V.datepicker._hideDatepicker())},_adjustDate:function(t,e,i){var s=V(t),t=this._getInst(s[0]);this._isDisabledDatepicker(s[0])||(this._adjustInstDate(t,e,i),this._updateDatepicker(t))},_gotoToday:function(t){var e=V(t),i=this._getInst(e[0]);this._get(i,"gotoCurrent")&&i.currentDay?(i.selectedDay=i.currentDay,i.drawMonth=i.selectedMonth=i.currentMonth,i.drawYear=i.selectedYear=i.currentYear):(t=new Date,i.selectedDay=t.getDate(),i.drawMonth=i.selectedMonth=t.getMonth(),i.drawYear=i.selectedYear=t.getFullYear()),this._notifyChange(i),this._adjustDate(e)},_selectMonthYear:function(t,e,i){var s=V(t),t=this._getInst(s[0]);t["selected"+("M"===i?"Month":"Year")]=t["draw"+("M"===i?"Month":"Year")]=parseInt(e.options[e.selectedIndex].value,10),this._notifyChange(t),this._adjustDate(s)},_selectDay:function(t,e,i,s){var n=V(t);V(s).hasClass(this._unselectableClass)||this._isDisabledDatepicker(n[0])||((n=this._getInst(n[0])).selectedDay=n.currentDay=parseInt(V("a",s).attr("data-date")),n.selectedMonth=n.currentMonth=e,n.selectedYear=n.currentYear=i,this._selectDate(t,this._formatDate(n,n.currentDay,n.currentMonth,n.currentYear)))},_clearDate:function(t){t=V(t);this._selectDate(t,"")},_selectDate:function(t,e){var i=V(t),t=this._getInst(i[0]);e=null!=e?e:this._formatDate(t),t.input&&t.input.val(e),this._updateAlternate(t),(i=this._get(t,"onSelect"))?i.apply(t.input?t.input[0]:null,[e,t]):t.input&&t.input.trigger("change"),t.inline?this._updateDatepicker(t):(this._hideDatepicker(),this._lastInput=t.input[0],"object"!=typeof t.input[0]&&t.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(t){var e,i,s=this._get(t,"altField");s&&(e=this._get(t,"altFormat")||this._get(t,"dateFormat"),i=this._getDate(t),t=this.formatDate(e,i,this._getFormatConfig(t)),V(document).find(s).val(t))},noWeekends:function(t){t=t.getDay();return[0<t&&t<6,""]},iso8601Week:function(t){var e=new Date(t.getTime());return e.setDate(e.getDate()+4-(e.getDay()||7)),t=e.getTime(),e.setMonth(0),e.setDate(1),Math.floor(Math.round((t-e)/864e5)/7)+1},parseDate:function(e,n,t){if(null==e||null==n)throw"Invalid arguments";if(""===(n="object"==typeof n?n.toString():n+""))return null;for(var i,s,o,a=0,r=(t?t.shortYearCutoff:null)||this._defaults.shortYearCutoff,r="string"!=typeof r?r:(new Date).getFullYear()%100+parseInt(r,10),l=(t?t.dayNamesShort:null)||this._defaults.dayNamesShort,h=(t?t.dayNames:null)||this._defaults.dayNames,c=(t?t.monthNamesShort:null)||this._defaults.monthNamesShort,u=(t?t.monthNames:null)||this._defaults.monthNames,d=-1,p=-1,f=-1,g=-1,m=!1,_=function(t){t=w+1<e.length&&e.charAt(w+1)===t;return t&&w++,t},v=function(t){var e=_(t),e="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,e=new RegExp("^\\d{"+("y"===t?e:1)+","+e+"}"),e=n.substring(a).match(e);if(!e)throw"Missing number at position "+a;return a+=e[0].length,parseInt(e[0],10)},b=function(t,e,i){var s=-1,e=V.map(_(t)?i:e,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(V.each(e,function(t,e){var i=e[1];if(n.substr(a,i.length).toLowerCase()===i.toLowerCase())return s=e[0],a+=i.length,!1}),-1!==s)return s+1;throw"Unknown name at position "+a},y=function(){if(n.charAt(a)!==e.charAt(w))throw"Unexpected literal at position "+a;a++},w=0;w<e.length;w++)if(m)"'"!==e.charAt(w)||_("'")?y():m=!1;else switch(e.charAt(w)){case"d":f=v("d");break;case"D":b("D",l,h);break;case"o":g=v("o");break;case"m":p=v("m");break;case"M":p=b("M",c,u);break;case"y":d=v("y");break;case"@":d=(o=new Date(v("@"))).getFullYear(),p=o.getMonth()+1,f=o.getDate();break;case"!":d=(o=new Date((v("!")-this._ticksTo1970)/1e4)).getFullYear(),p=o.getMonth()+1,f=o.getDate();break;case"'":_("'")?y():m=!0;break;default:y()}if(a<n.length&&(s=n.substr(a),!/^\s+/.test(s)))throw"Extra/unparsed characters found in date: "+s;if(-1===d?d=(new Date).getFullYear():d<100&&(d+=(new Date).getFullYear()-(new Date).getFullYear()%100+(d<=r?0:-100)),-1<g)for(p=1,f=g;;){if(f<=(i=this._getDaysInMonth(d,p-1)))break;p++,f-=i}if((o=this._daylightSavingAdjust(new Date(d,p-1,f))).getFullYear()!==d||o.getMonth()+1!==p||o.getDate()!==f)throw"Invalid date";return o},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*60*60*1e7,formatDate:function(e,t,i){if(!t)return"";function s(t,e,i){var s=""+e;if(c(t))for(;s.length<i;)s="0"+s;return s}function n(t,e,i,s){return(c(t)?s:i)[e]}var o,a=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,r=(i?i.dayNames:null)||this._defaults.dayNames,l=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,h=(i?i.monthNames:null)||this._defaults.monthNames,c=function(t){t=o+1<e.length&&e.charAt(o+1)===t;return t&&o++,t},u="",d=!1;if(t)for(o=0;o<e.length;o++)if(d)"'"!==e.charAt(o)||c("'")?u+=e.charAt(o):d=!1;else switch(e.charAt(o)){case"d":u+=s("d",t.getDate(),2);break;case"D":u+=n("D",t.getDay(),a,r);break;case"o":u+=s("o",Math.round((new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()-new Date(t.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=s("m",t.getMonth()+1,2);break;case"M":u+=n("M",t.getMonth(),l,h);break;case"y":u+=c("y")?t.getFullYear():(t.getFullYear()%100<10?"0":"")+t.getFullYear()%100;break;case"@":u+=t.getTime();break;case"!":u+=1e4*t.getTime()+this._ticksTo1970;break;case"'":c("'")?u+="'":d=!0;break;default:u+=e.charAt(o)}return u},_possibleChars:function(e){for(var t="",i=!1,s=function(t){t=n+1<e.length&&e.charAt(n+1)===t;return t&&n++,t},n=0;n<e.length;n++)if(i)"'"!==e.charAt(n)||s("'")?t+=e.charAt(n):i=!1;else switch(e.charAt(n)){case"d":case"m":case"y":case"@":t+="0123456789";break;case"D":case"M":return null;case"'":s("'")?t+="'":i=!0;break;default:t+=e.charAt(n)}return t},_get:function(t,e){return(void 0!==t.settings[e]?t.settings:this._defaults)[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(t){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(r,t,e){var i,s,t=null==t||""===t?e:"string"==typeof t?function(t){try{return V.datepicker.parseDate(V.datepicker._get(r,"dateFormat"),t,V.datepicker._getFormatConfig(r))}catch(t){}for(var e=(t.toLowerCase().match(/^c/)?V.datepicker._getDate(r):null)||new Date,i=e.getFullYear(),s=e.getMonth(),n=e.getDate(),o=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,a=o.exec(t);a;){switch(a[2]||"d"){case"d":case"D":n+=parseInt(a[1],10);break;case"w":case"W":n+=7*parseInt(a[1],10);break;case"m":case"M":s+=parseInt(a[1],10),n=Math.min(n,V.datepicker._getDaysInMonth(i,s));break;case"y":case"Y":i+=parseInt(a[1],10),n=Math.min(n,V.datepicker._getDaysInMonth(i,s))}a=o.exec(t)}return new Date(i,s,n)}(t):"number"==typeof t?isNaN(t)?e:(i=t,(s=new Date).setDate(s.getDate()+i),s):new Date(t.getTime());return(t=t&&"Invalid Date"===t.toString()?e:t)&&(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0)),this._daylightSavingAdjust(t)},_daylightSavingAdjust:function(t){return t?(t.setHours(12<t.getHours()?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,e=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=e.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=e.getMonth(),t.drawYear=t.selectedYear=t.currentYear=e.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){return!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay))},_attachHandlers:function(t){var e=this._get(t,"stepMonths"),i="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){V.datepicker._adjustDate(i,-e,"M")},next:function(){V.datepicker._adjustDate(i,+e,"M")},hide:function(){V.datepicker._hideDatepicker()},today:function(){V.datepicker._gotoToday(i)},selectDay:function(){return V.datepicker._selectDay(i,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return V.datepicker._selectMonthYear(i,this,"M"),!1},selectYear:function(){return V.datepicker._selectMonthYear(i,this,"Y"),!1}};V(this).on(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,l,h,c,u,d,p,f,g,m,_,v,b,y,w,x,k,C,D,I,T,P,M,S,H,z,A=new Date,O=this._daylightSavingAdjust(new Date(A.getFullYear(),A.getMonth(),A.getDate())),N=this._get(t,"isRTL"),E=this._get(t,"showButtonPanel"),W=this._get(t,"hideIfNoPrevNext"),F=this._get(t,"navigationAsDateFormat"),L=this._getNumberOfMonths(t),R=this._get(t,"showCurrentAtPos"),A=this._get(t,"stepMonths"),Y=1!==L[0]||1!==L[1],B=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),j=this._getMinMaxDate(t,"min"),q=this._getMinMaxDate(t,"max"),K=t.drawMonth-R,U=t.drawYear;if(K<0&&(K+=12,U--),q)for(e=this._daylightSavingAdjust(new Date(q.getFullYear(),q.getMonth()-L[0]*L[1]+1,q.getDate())),e=j&&e<j?j:e;this._daylightSavingAdjust(new Date(U,K,1))>e;)--K<0&&(K=11,U--);for(t.drawMonth=K,t.drawYear=U,R=this._get(t,"prevText"),R=F?this.formatDate(R,this._daylightSavingAdjust(new Date(U,K-A,1)),this._getFormatConfig(t)):R,i=this._canAdjustMonth(t,-1,U,K)?V("<a>").attr({class:"ui-datepicker-prev ui-corner-all","data-handler":"prev","data-event":"click",title:R}).append(V("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(N?"e":"w")).text(R))[0].outerHTML:W?"":V("<a>").attr({class:"ui-datepicker-prev ui-corner-all ui-state-disabled",title:R}).append(V("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(N?"e":"w")).text(R))[0].outerHTML,R=this._get(t,"nextText"),R=F?this.formatDate(R,this._daylightSavingAdjust(new Date(U,K+A,1)),this._getFormatConfig(t)):R,s=this._canAdjustMonth(t,1,U,K)?V("<a>").attr({class:"ui-datepicker-next ui-corner-all","data-handler":"next","data-event":"click",title:R}).append(V("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(N?"w":"e")).text(R))[0].outerHTML:W?"":V("<a>").attr({class:"ui-datepicker-next ui-corner-all ui-state-disabled",title:R}).append(V("<span>").attr("class","ui-icon ui-icon-circle-triangle-"+(N?"w":"e")).text(R))[0].outerHTML,A=this._get(t,"currentText"),W=this._get(t,"gotoCurrent")&&t.currentDay?B:O,A=F?this.formatDate(A,W,this._getFormatConfig(t)):A,R="",t.inline||(R=V("<button>").attr({type:"button",class:"ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all","data-handler":"hide","data-event":"click"}).text(this._get(t,"closeText"))[0].outerHTML),F="",E&&(F=V("<div class='ui-datepicker-buttonpane ui-widget-content'>").append(N?R:"").append(this._isInRange(t,W)?V("<button>").attr({type:"button",class:"ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all","data-handler":"today","data-event":"click"}).text(A):"").append(N?"":R)[0].outerHTML),n=parseInt(this._get(t,"firstDay"),10),n=isNaN(n)?0:n,o=this._get(t,"showWeek"),a=this._get(t,"dayNames"),r=this._get(t,"dayNamesMin"),l=this._get(t,"monthNames"),h=this._get(t,"monthNamesShort"),c=this._get(t,"beforeShowDay"),u=this._get(t,"showOtherMonths"),d=this._get(t,"selectOtherMonths"),p=this._getDefaultDate(t),f="",m=0;m<L[0];m++){for(_="",this.maxRows=4,v=0;v<L[1];v++){if(b=this._daylightSavingAdjust(new Date(U,K,t.selectedDay)),y=" ui-corner-all",w="",Y){if(w+="<div class='ui-datepicker-group",1<L[1])switch(v){case 0:w+=" ui-datepicker-group-first",y=" ui-corner-"+(N?"right":"left");break;case L[1]-1:w+=" ui-datepicker-group-last",y=" ui-corner-"+(N?"left":"right");break;default:w+=" ui-datepicker-group-middle",y=""}w+="'>"}for(w+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+y+"'>"+(/all|left/.test(y)&&0===m?N?s:i:"")+(/all|right/.test(y)&&0===m?N?i:s:"")+this._generateMonthYearHeader(t,K,U,j,q,0<m||0<v,l,h)+"</div><table class='ui-datepicker-calendar'><thead><tr>",x=o?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",g=0;g<7;g++)x+="<th scope='col'"+(5<=(g+n+6)%7?" class='ui-datepicker-week-end'":"")+"><span title='"+a[k=(g+n)%7]+"'>"+r[k]+"</span></th>";for(w+=x+"</tr></thead><tbody>",D=this._getDaysInMonth(U,K),U===t.selectedYear&&K===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,D)),C=(this._getFirstDayOfMonth(U,K)-n+7)%7,D=Math.ceil((C+D)/7),I=Y&&this.maxRows>D?this.maxRows:D,this.maxRows=I,T=this._daylightSavingAdjust(new Date(U,K,1-C)),P=0;P<I;P++){for(w+="<tr>",M=o?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(T)+"</td>":"",g=0;g<7;g++)S=c?c.apply(t.input?t.input[0]:null,[T]):[!0,""],z=(H=T.getMonth()!==K)&&!d||!S[0]||j&&T<j||q&&q<T,M+="<td class='"+(5<=(g+n+6)%7?" ui-datepicker-week-end":"")+(H?" ui-datepicker-other-month":"")+(T.getTime()===b.getTime()&&K===t.selectedMonth&&t._keyEvent||p.getTime()===T.getTime()&&p.getTime()===b.getTime()?" "+this._dayOverClass:"")+(z?" "+this._unselectableClass+" ui-state-disabled":"")+(H&&!u?"":" "+S[1]+(T.getTime()===B.getTime()?" "+this._currentClass:"")+(T.getTime()===O.getTime()?" ui-datepicker-today":""))+"'"+(H&&!u||!S[2]?"":" title='"+S[2].replace(/'/g,"&#39;")+"'")+(z?"":" data-handler='selectDay' data-event='click' data-month='"+T.getMonth()+"' data-year='"+T.getFullYear()+"'")+">"+(H&&!u?"&#xa0;":z?"<span class='ui-state-default'>"+T.getDate()+"</span>":"<a class='ui-state-default"+(T.getTime()===O.getTime()?" ui-state-highlight":"")+(T.getTime()===B.getTime()?" ui-state-active":"")+(H?" ui-priority-secondary":"")+"' href='#' aria-current='"+(T.getTime()===B.getTime()?"true":"false")+"' data-date='"+T.getDate()+"'>"+T.getDate()+"</a>")+"</td>",T.setDate(T.getDate()+1),T=this._daylightSavingAdjust(T);w+=M+"</tr>"}11<++K&&(K=0,U++),_+=w+="</tbody></table>"+(Y?"</div>"+(0<L[0]&&v===L[1]-1?"<div class='ui-datepicker-row-break'></div>":""):"")}f+=_}return f+=F,t._keyEvent=!1,f},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var l,h,c,u,d,p,f=this._get(t,"changeMonth"),g=this._get(t,"changeYear"),m=this._get(t,"showMonthAfterYear"),_=this._get(t,"selectMonthLabel"),v=this._get(t,"selectYearLabel"),b="<div class='ui-datepicker-title'>",y="";if(o||!f)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(l=s&&s.getFullYear()===i,h=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' aria-label='"+_+"' data-handler='selectMonth' data-event='change'>",c=0;c<12;c++)(!l||c>=s.getMonth())&&(!h||c<=n.getMonth())&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(m||(b+=y+(!o&&f&&g?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!g)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(a=this._get(t,"yearRange").split(":"),u=(new Date).getFullYear(),d=(_=function(t){t=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?u+parseInt(t,10):parseInt(t,10);return isNaN(t)?u:t})(a[0]),p=Math.max(d,_(a[1]||"")),d=s?Math.max(d,s.getFullYear()):d,p=n?Math.min(p,n.getFullYear()):p,t.yearshtml+="<select class='ui-datepicker-year' aria-label='"+v+"' data-handler='selectYear' data-event='change'>";d<=p;d++)t.yearshtml+="<option value='"+d+"'"+(d===i?" selected='selected'":"")+">"+d+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),m&&(b+=(!o&&f&&g?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),e=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),e=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,e)));t.selectedDay=e.getDate(),t.drawMonth=t.selectedMonth=e.getMonth(),t.drawYear=t.selectedYear=e.getFullYear(),"M"!==i&&"Y"!==i||this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),t=this._getMinMaxDate(t,"max"),e=i&&e<i?i:e;return t&&t<e?t:e},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){t=this._get(t,"numberOfMonths");return null==t?[1,1]:"number"==typeof t?[1,t]:t},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),n=this._daylightSavingAdjust(new Date(i,s+(e<0?e:n[0]*n[1]),1));return e<0&&n.setDate(this._getDaysInMonth(n.getFullYear(),n.getMonth())),this._isInRange(t,n)},_isInRange:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=null,o=null,a=this._get(t,"yearRange");return a&&(t=a.split(":"),a=(new Date).getFullYear(),n=parseInt(t[0],10),o=parseInt(t[1],10),t[0].match(/[+\-].*/)&&(n+=a),t[1].match(/[+\-].*/)&&(o+=a)),(!i||e.getTime()>=i.getTime())&&(!s||e.getTime()<=s.getTime())&&(!n||e.getFullYear()>=n)&&(!o||e.getFullYear()<=o)},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return{shortYearCutoff:e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);e=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),e,this._getFormatConfig(t))}}),V.fn.datepicker=function(t){if(!this.length)return this;V.datepicker.initialized||(V(document).on("mousedown",V.datepicker._checkExternalClick),V.datepicker.initialized=!0),0===V("#"+V.datepicker._mainDivId).length&&V("body").append(V.datepicker.dpDiv);var e=Array.prototype.slice.call(arguments,1);return"string"==typeof t&&("isDisabled"===t||"getDate"===t||"widget"===t)||"option"===t&&2===arguments.length&&"string"==typeof arguments[1]?V.datepicker["_"+t+"Datepicker"].apply(V.datepicker,[this[0]].concat(e)):this.each(function(){"string"==typeof t?V.datepicker["_"+t+"Datepicker"].apply(V.datepicker,[this].concat(e)):V.datepicker._attachDatepicker(this,t)})},V.datepicker=new st,V.datepicker.initialized=!1,V.datepicker.uuid=(new Date).getTime(),V.datepicker.version="1.13.2";V.datepicker,V.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var rt=!1;V(document).on("mouseup",function(){rt=!1});V.widget("ui.mouse",{version:"1.13.2",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(t){if(!0===V.data(t.target,e.widgetName+".preventClickEvent"))return V.removeData(t.target,e.widgetName+".preventClickEvent"),t.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!rt){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var e=this,i=1===t.which,s=!("string"!=typeof this.options.cancel||!t.target.nodeName)&&V(t.target).closest(this.options.cancel).length;return i&&!s&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=!1!==this._mouseStart(t),!this._mouseStarted)?(t.preventDefault(),!0):(!0===V.data(t.target,this.widgetName+".preventClickEvent")&&V.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return e._mouseMove(t)},this._mouseUpDelegate=function(t){return e._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),rt=!0)):!0}},_mouseMove:function(t){if(this._mouseMoved){if(V.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button)return this._mouseUp(t);if(!t.which)if(t.originalEvent.altKey||t.originalEvent.ctrlKey||t.originalEvent.metaKey||t.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(t)}return(t.which||t.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=!1!==this._mouseStart(this._mouseDownEvent,t),this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&V.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,rt=!1,t.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),V.ui.plugin={add:function(t,e,i){var s,n=V.ui[t].prototype;for(s in i)n.plugins[s]=n.plugins[s]||[],n.plugins[s].push([e,i[s]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;n<o.length;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},V.ui.safeBlur=function(t){t&&"body"!==t.nodeName.toLowerCase()&&V(t).trigger("blur")};V.widget("ui.draggable",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){(this.helper||this.element).is(".ui-draggable-dragging")?this.destroyOnClear=!0:(this._removeHandleClassName(),this._mouseDestroy())},_mouseCapture:function(t){var e=this.options;return!(this.helper||e.disabled||0<V(t.target).closest(".ui-resizable-handle").length)&&(this.handle=this._getHandle(t),!!this.handle&&(this._blurActiveElement(t),this._blockFrames(!0===e.iframeFix?"iframe":e.iframeFix),!0))},_blockFrames:function(t){this.iframeBlocks=this.document.find(t).map(function(){var t=V(this);return V("<div>").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var e=V.ui.safeActiveElement(this.document[0]);V(t.target).closest(e).length||V.ui.safeBlur(e)},_mouseStart:function(t){var e=this.options;return this.helper=this._createHelper(t),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),V.ui.ddmanager&&(V.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=0<this.helper.parents().filter(function(){return"fixed"===V(this).css("position")}).length,this.positionAbs=this.element.offset(),this._refreshOffsets(t),this.originalPosition=this.position=this._generatePosition(t,!1),this.originalPageX=t.pageX,this.originalPageY=t.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this._setContainment(),!1===this._trigger("start",t)?(this._clear(),!1):(this._cacheHelperProportions(),V.ui.ddmanager&&!e.dropBehaviour&&V.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),V.ui.ddmanager&&V.ui.ddmanager.dragStart(this,t),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(t,e){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t,!0),this.positionAbs=this._convertPositionTo("absolute"),!e){e=this._uiHash();if(!1===this._trigger("drag",t,e))return this._mouseUp(new V.Event("mouseup",t)),!1;this.position=e.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",V.ui.ddmanager&&V.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var e=this,i=!1;return V.ui.ddmanager&&!this.options.dropBehaviour&&(i=V.ui.ddmanager.drop(this,t)),this.dropped&&(i=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!i||"valid"===this.options.revert&&i||!0===this.options.revert||"function"==typeof this.options.revert&&this.options.revert.call(this.element,i)?V(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){!1!==e._trigger("stop",t)&&e._clear()}):!1!==this._trigger("stop",t)&&this._clear(),!1},_mouseUp:function(t){return this._unblockFrames(),V.ui.ddmanager&&V.ui.ddmanager.dragStop(this,t),this.handleElement.is(t.target)&&this.element.trigger("focus"),V.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new V.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(t){return!this.options.handle||!!V(t.target).closest(this.element.find(this.options.handle)).length},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(t){var e=this.options,i="function"==typeof e.helper,t=i?V(e.helper.apply(this.element[0],[t])):"clone"===e.helper?this.element.clone().removeAttr("id"):this.element;return t.parents("body").length||t.appendTo("parent"===e.appendTo?this.element[0].parentNode:e.appendTo),i&&t[0]===this.element[0]&&this._setPositionRelative(),t[0]===this.element[0]||/(fixed|absolute)/.test(t.css("position"))||t.css("position","absolute"),t},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),"left"in(t=Array.isArray(t)?{left:+t[0],top:+t[1]||0}:t)&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var t=this.offsetParent.offset(),e=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==e&&V.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),{top:(t=this._isRootNode(this.offsetParent[0])?{top:0,left:0}:t).top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,e,i,s=this.options,n=this.document[0];this.relativeContainer=null,s.containment?"window"!==s.containment?"document"!==s.containment?s.containment.constructor!==Array?("parent"===s.containment&&(s.containment=this.helper[0].parentNode),(i=(e=V(s.containment))[0])&&(t=/(scroll|auto)/.test(e.css("overflow")),this.containment=[(parseInt(e.css("borderLeftWidth"),10)||0)+(parseInt(e.css("paddingLeft"),10)||0),(parseInt(e.css("borderTopWidth"),10)||0)+(parseInt(e.css("paddingTop"),10)||0),(t?Math.max(i.scrollWidth,i.offsetWidth):i.offsetWidth)-(parseInt(e.css("borderRightWidth"),10)||0)-(parseInt(e.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(i.scrollHeight,i.offsetHeight):i.offsetHeight)-(parseInt(e.css("borderBottomWidth"),10)||0)-(parseInt(e.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=e)):this.containment=s.containment:this.containment=[0,0,V(n).width()-this.helperProportions.width-this.margins.left,(V(n).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]:this.containment=[V(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,V(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,V(window).scrollLeft()+V(window).width()-this.helperProportions.width-this.margins.left,V(window).scrollTop()+(V(window).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]:this.containment=null},_convertPositionTo:function(t,e){e=e||this.position;var i="absolute"===t?1:-1,t=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:t?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:t?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s=this.options,n=this._isRootNode(this.scrollParent[0]),o=t.pageX,a=t.pageY;return n&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(i=this.relativeContainer?(i=this.relativeContainer.offset(),[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]):this.containment,t.pageX-this.offset.click.left<i[0]&&(o=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(a=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(o=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(a=i[3]+this.offset.click.top)),s.grid&&(t=s.grid[1]?this.originalPageY+Math.round((a-this.originalPageY)/s.grid[1])*s.grid[1]:this.originalPageY,a=!i||t-this.offset.click.top>=i[1]||t-this.offset.click.top>i[3]?t:t-this.offset.click.top>=i[1]?t-s.grid[1]:t+s.grid[1],t=s.grid[0]?this.originalPageX+Math.round((o-this.originalPageX)/s.grid[0])*s.grid[0]:this.originalPageX,o=!i||t-this.offset.click.left>=i[0]||t-this.offset.click.left>i[2]?t:t-this.offset.click.left>=i[0]?t-s.grid[0]:t+s.grid[0]),"y"===s.axis&&(o=this.originalPageX),"x"===s.axis&&(a=this.originalPageY)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:n?0:this.offset.scroll.top),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:n?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(t,e,i){return i=i||this._uiHash(),V.ui.plugin.call(this,t,[e,i,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),i.offset=this.positionAbs),V.Widget.prototype._trigger.call(this,t,e,i)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),V.ui.plugin.add("draggable","connectToSortable",{start:function(e,t,i){var s=V.extend({},t,{item:i.element});i.sortables=[],V(i.options.connectToSortable).each(function(){var t=V(this).sortable("instance");t&&!t.options.disabled&&(i.sortables.push(t),t.refreshPositions(),t._trigger("activate",e,s))})},stop:function(e,t,i){var s=V.extend({},t,{item:i.element});i.cancelHelperRemoval=!1,V.each(i.sortables,function(){var t=this;t.isOver?(t.isOver=0,i.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,s))})},drag:function(i,s,n){V.each(n.sortables,function(){var t=!1,e=this;e.positionAbs=n.positionAbs,e.helperProportions=n.helperProportions,e.offset.click=n.offset.click,e._intersectsWith(e.containerCache)&&(t=!0,V.each(n.sortables,function(){return this.positionAbs=n.positionAbs,this.helperProportions=n.helperProportions,this.offset.click=n.offset.click,t=this!==e&&this._intersectsWith(this.containerCache)&&V.contains(e.element[0],this.element[0])?!1:t})),t?(e.isOver||(e.isOver=1,n._parent=s.helper.parent(),e.currentItem=s.helper.appendTo(e.element).data("ui-sortable-item",!0),e.options._helper=e.options.helper,e.options.helper=function(){return s.helper[0]},i.target=e.currentItem[0],e._mouseCapture(i,!0),e._mouseStart(i,!0,!0),e.offset.click.top=n.offset.click.top,e.offset.click.left=n.offset.click.left,e.offset.parent.left-=n.offset.parent.left-e.offset.parent.left,e.offset.parent.top-=n.offset.parent.top-e.offset.parent.top,n._trigger("toSortable",i),n.dropped=e.element,V.each(n.sortables,function(){this.refreshPositions()}),n.currentItem=n.element,e.fromOutside=n),e.currentItem&&(e._mouseDrag(i),s.position=e.position)):e.isOver&&(e.isOver=0,e.cancelHelperRemoval=!0,e.options._revert=e.options.revert,e.options.revert=!1,e._trigger("out",i,e._uiHash(e)),e._mouseStop(i,!0),e.options.revert=e.options._revert,e.options.helper=e.options._helper,e.placeholder&&e.placeholder.remove(),s.helper.appendTo(n._parent),n._refreshOffsets(i),s.position=n._generatePosition(i,!0),n._trigger("fromSortable",i),n.dropped=!1,V.each(n.sortables,function(){this.refreshPositions()}))})}}),V.ui.plugin.add("draggable","cursor",{start:function(t,e,i){var s=V("body"),i=i.options;s.css("cursor")&&(i._cursor=s.css("cursor")),s.css("cursor",i.cursor)},stop:function(t,e,i){i=i.options;i._cursor&&V("body").css("cursor",i._cursor)}}),V.ui.plugin.add("draggable","opacity",{start:function(t,e,i){e=V(e.helper),i=i.options;e.css("opacity")&&(i._opacity=e.css("opacity")),e.css("opacity",i.opacity)},stop:function(t,e,i){i=i.options;i._opacity&&V(e.helper).css("opacity",i._opacity)}}),V.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(t,e,i){var s=i.options,n=!1,o=i.scrollParentNotHidden[0],a=i.document[0];o!==a&&"HTML"!==o.tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+o.offsetHeight-t.pageY<s.scrollSensitivity?o.scrollTop=n=o.scrollTop+s.scrollSpeed:t.pageY-i.overflowOffset.top<s.scrollSensitivity&&(o.scrollTop=n=o.scrollTop-s.scrollSpeed)),s.axis&&"y"===s.axis||(i.overflowOffset.left+o.offsetWidth-t.pageX<s.scrollSensitivity?o.scrollLeft=n=o.scrollLeft+s.scrollSpeed:t.pageX-i.overflowOffset.left<s.scrollSensitivity&&(o.scrollLeft=n=o.scrollLeft-s.scrollSpeed))):(s.axis&&"x"===s.axis||(t.pageY-V(a).scrollTop()<s.scrollSensitivity?n=V(a).scrollTop(V(a).scrollTop()-s.scrollSpeed):V(window).height()-(t.pageY-V(a).scrollTop())<s.scrollSensitivity&&(n=V(a).scrollTop(V(a).scrollTop()+s.scrollSpeed))),s.axis&&"y"===s.axis||(t.pageX-V(a).scrollLeft()<s.scrollSensitivity?n=V(a).scrollLeft(V(a).scrollLeft()-s.scrollSpeed):V(window).width()-(t.pageX-V(a).scrollLeft())<s.scrollSensitivity&&(n=V(a).scrollLeft(V(a).scrollLeft()+s.scrollSpeed)))),!1!==n&&V.ui.ddmanager&&!s.dropBehaviour&&V.ui.ddmanager.prepareOffsets(i,t)}}),V.ui.plugin.add("draggable","snap",{start:function(t,e,i){var s=i.options;i.snapElements=[],V(s.snap.constructor!==String?s.snap.items||":data(ui-draggable)":s.snap).each(function(){var t=V(this),e=t.offset();this!==i.element[0]&&i.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:e.top,left:e.left})})},drag:function(t,e,i){for(var s,n,o,a,r,l,h,c,u,d=i.options,p=d.snapTolerance,f=e.offset.left,g=f+i.helperProportions.width,m=e.offset.top,_=m+i.helperProportions.height,v=i.snapElements.length-1;0<=v;v--)l=(r=i.snapElements[v].left-i.margins.left)+i.snapElements[v].width,c=(h=i.snapElements[v].top-i.margins.top)+i.snapElements[v].height,g<r-p||l+p<f||_<h-p||c+p<m||!V.contains(i.snapElements[v].item.ownerDocument,i.snapElements[v].item)?(i.snapElements[v].snapping&&i.options.snap.release&&i.options.snap.release.call(i.element,t,V.extend(i._uiHash(),{snapItem:i.snapElements[v].item})),i.snapElements[v].snapping=!1):("inner"!==d.snapMode&&(s=Math.abs(h-_)<=p,n=Math.abs(c-m)<=p,o=Math.abs(r-g)<=p,a=Math.abs(l-f)<=p,s&&(e.position.top=i._convertPositionTo("relative",{top:h-i.helperProportions.height,left:0}).top),n&&(e.position.top=i._convertPositionTo("relative",{top:c,left:0}).top),o&&(e.position.left=i._convertPositionTo("relative",{top:0,left:r-i.helperProportions.width}).left),a&&(e.position.left=i._convertPositionTo("relative",{top:0,left:l}).left)),u=s||n||o||a,"outer"!==d.snapMode&&(s=Math.abs(h-m)<=p,n=Math.abs(c-_)<=p,o=Math.abs(r-f)<=p,a=Math.abs(l-g)<=p,s&&(e.position.top=i._convertPositionTo("relative",{top:h,left:0}).top),n&&(e.position.top=i._convertPositionTo("relative",{top:c-i.helperProportions.height,left:0}).top),o&&(e.position.left=i._convertPositionTo("relative",{top:0,left:r}).left),a&&(e.position.left=i._convertPositionTo("relative",{top:0,left:l-i.helperProportions.width}).left)),!i.snapElements[v].snapping&&(s||n||o||a||u)&&i.options.snap.snap&&i.options.snap.snap.call(i.element,t,V.extend(i._uiHash(),{snapItem:i.snapElements[v].item})),i.snapElements[v].snapping=s||n||o||a||u)}}),V.ui.plugin.add("draggable","stack",{start:function(t,e,i){var s,i=i.options,i=V.makeArray(V(i.stack)).sort(function(t,e){return(parseInt(V(t).css("zIndex"),10)||0)-(parseInt(V(e).css("zIndex"),10)||0)});i.length&&(s=parseInt(V(i[0]).css("zIndex"),10)||0,V(i).each(function(t){V(this).css("zIndex",s+t)}),this.css("zIndex",s+i.length))}}),V.ui.plugin.add("draggable","zIndex",{start:function(t,e,i){e=V(e.helper),i=i.options;e.css("zIndex")&&(i._zIndex=e.css("zIndex")),e.css("zIndex",i.zIndex)},stop:function(t,e,i){i=i.options;i._zIndex&&V(e.helper).css("zIndex",i._zIndex)}});V.ui.draggable;V.widget("ui.resizable",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(t,e){if("hidden"===V(t).css("overflow"))return!1;var i=e&&"left"===e?"scrollLeft":"scrollTop",e=!1;if(0<t[i])return!0;try{t[i]=1,e=0<t[i],t[i]=0}catch(t){}return e},_create:function(){var t,e=this.options,i=this;this._addClass("ui-resizable"),V.extend(this,{_aspectRatio:!!e.aspectRatio,aspectRatio:e.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:e.helper||e.ghost||e.animate?e.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(V("<div class='ui-wrapper'></div>").css({overflow:"hidden",position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,t={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(t),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(t),this._proportionallyResize()),this._setupHandles(),e.autoHide&&V(this.element).on("mouseenter",function(){e.disabled||(i._removeClass("ui-resizable-autohide"),i._handles.show())}).on("mouseleave",function(){e.disabled||i.resizing||(i._addClass("ui-resizable-autohide"),i._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy(),this._addedHandles.remove();function t(t){V(t).removeData("resizable").removeData("ui-resizable").off(".resizable")}var e;return this.elementIsWrapper&&(t(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;case"aspectRatio":this._aspectRatio=!!e}},_setupHandles:function(){var t,e,i,s,n,o=this.options,a=this;if(this.handles=o.handles||(V(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=V(),this._addedHandles=V(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),i=this.handles.split(","),this.handles={},e=0;e<i.length;e++)s="ui-resizable-"+(t=String.prototype.trim.call(i[e])),n=V("<div>"),this._addClass(n,"ui-resizable-handle "+s),n.css({zIndex:o.zIndex}),this.handles[t]=".ui-resizable-"+t,this.element.children(this.handles[t]).length||(this.element.append(n),this._addedHandles=this._addedHandles.add(n));this._renderAxis=function(t){var e,i,s;for(e in t=t||this.element,this.handles)this.handles[e].constructor===String?this.handles[e]=this.element.children(this.handles[e]).first().show():(this.handles[e].jquery||this.handles[e].nodeType)&&(this.handles[e]=V(this.handles[e]),this._on(this.handles[e],{mousedown:a._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(i=V(this.handles[e],this.element),s=/sw|ne|nw|se|n|s/.test(e)?i.outerHeight():i.outerWidth(),i=["padding",/ne|nw|n/.test(e)?"Top":/se|sw|s/.test(e)?"Bottom":/^e$/.test(e)?"Right":"Left"].join(""),t.css(i,s),this._proportionallyResize()),this._handles=this._handles.add(this.handles[e])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){a.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),a.axis=n&&n[1]?n[1]:"se")}),o.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._addedHandles.remove()},_mouseCapture:function(t){var e,i,s=!1;for(e in this.handles)(i=V(this.handles[e])[0])!==t.target&&!V.contains(i,t.target)||(s=!0);return!this.options.disabled&&s},_mouseStart:function(t){var e,i,s=this.options,n=this.element;return this.resizing=!0,this._renderProxy(),e=this._num(this.helper.css("left")),i=this._num(this.helper.css("top")),s.containment&&(e+=V(s.containment).scrollLeft()||0,i+=V(s.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:e,top:i},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:n.width(),height:n.height()},this.originalSize=this._helper?{width:n.outerWidth(),height:n.outerHeight()}:{width:n.width(),height:n.height()},this.sizeDiff={width:n.outerWidth()-n.width(),height:n.outerHeight()-n.height()},this.originalPosition={left:e,top:i},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof s.aspectRatio?s.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=V(".ui-resizable-"+this.axis).css("cursor"),V("body").css("cursor","auto"===s?this.axis+"-resize":s),this._addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var e=this.originalMousePosition,i=this.axis,s=t.pageX-e.left||0,e=t.pageY-e.top||0,i=this._change[i];return this._updatePrevProperties(),i&&(e=i.apply(this,[t,s,e]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(e=this._updateRatio(e,t)),e=this._respectSize(e,t),this._updateCache(e),this._propagate("resize",t),e=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),V.isEmptyObject(e)||(this._updatePrevProperties(),this._trigger("resize",t,this.ui()),this._applyChanges())),!1},_mouseStop:function(t){this.resizing=!1;var e,i,s,n=this.options,o=this;return this._helper&&(s=(e=(i=this._proportionallyResizeElements).length&&/textarea/i.test(i[0].nodeName))&&this._hasScroll(i[0],"left")?0:o.sizeDiff.height,i=e?0:o.sizeDiff.width,e={width:o.helper.width()-i,height:o.helper.height()-s},i=parseFloat(o.element.css("left"))+(o.position.left-o.originalPosition.left)||null,s=parseFloat(o.element.css("top"))+(o.position.top-o.originalPosition.top)||null,n.animate||this.element.css(V.extend(e,{top:s,left:i})),o.helper.height(o.size.height),o.helper.width(o.size.width),this._helper&&!n.animate&&this._proportionallyResize()),V("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s=this.options,n={minWidth:this._isNumber(s.minWidth)?s.minWidth:0,maxWidth:this._isNumber(s.maxWidth)?s.maxWidth:1/0,minHeight:this._isNumber(s.minHeight)?s.minHeight:0,maxHeight:this._isNumber(s.maxHeight)?s.maxHeight:1/0};(this._aspectRatio||t)&&(e=n.minHeight*this.aspectRatio,i=n.minWidth/this.aspectRatio,s=n.maxHeight*this.aspectRatio,t=n.maxWidth/this.aspectRatio,e>n.minWidth&&(n.minWidth=e),i>n.minHeight&&(n.minHeight=i),s<n.maxWidth&&(n.maxWidth=s),t<n.maxHeight&&(n.maxHeight=t)),this._vBoundaries=n},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,l=this.originalPosition.top+this.originalSize.height,h=/sw|nw|w/.test(i),i=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&h&&(t.left=r-e.minWidth),s&&h&&(t.left=r-e.maxWidth),a&&i&&(t.top=l-e.minHeight),n&&i&&(t.top=l-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];e<4;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;e<this._proportionallyResizeElements.length;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var t=this.element,e=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||V("<div></div>").css({overflow:"hidden"}),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++e.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize;return{left:this.originalPosition.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize;return{top:this.originalPosition.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(t,e,i){return V.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},sw:function(t,e,i){return V.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,e,i]))},ne:function(t,e,i){return V.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},nw:function(t,e,i){return V.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,e,i]))}},_propagate:function(t,e){V.ui.plugin.call(this,t,[e,this.ui()]),"resize"!==t&&this._trigger(t,e,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),V.ui.plugin.add("resizable","animate",{stop:function(e){var i=V(this).resizable("instance"),t=i.options,s=i._proportionallyResizeElements,n=s.length&&/textarea/i.test(s[0].nodeName),o=n&&i._hasScroll(s[0],"left")?0:i.sizeDiff.height,a=n?0:i.sizeDiff.width,n={width:i.size.width-a,height:i.size.height-o},a=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,o=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(V.extend(n,o&&a?{top:o,left:a}:{}),{duration:t.animateDuration,easing:t.animateEasing,step:function(){var t={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};s&&s.length&&V(s[0]).css({width:t.width,height:t.height}),i._updateCache(t),i._propagate("resize",e)}})}}),V.ui.plugin.add("resizable","containment",{start:function(){var i,s,n=V(this).resizable("instance"),t=n.options,e=n.element,o=t.containment,a=o instanceof V?o.get(0):/parent/.test(o)?e.parent().get(0):o;a&&(n.containerElement=V(a),/document/.test(o)||o===document?(n.containerOffset={left:0,top:0},n.containerPosition={left:0,top:0},n.parentData={element:V(document),left:0,top:0,width:V(document).width(),height:V(document).height()||document.body.parentNode.scrollHeight}):(i=V(a),s=[],V(["Top","Right","Left","Bottom"]).each(function(t,e){s[t]=n._num(i.css("padding"+e))}),n.containerOffset=i.offset(),n.containerPosition=i.position(),n.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},t=n.containerOffset,e=n.containerSize.height,o=n.containerSize.width,o=n._hasScroll(a,"left")?a.scrollWidth:o,e=n._hasScroll(a)?a.scrollHeight:e,n.parentData={element:a,left:t.left,top:t.top,width:o,height:e}))},resize:function(t){var e=V(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.position,o=e._aspectRatio||t.shiftKey,a={top:0,left:0},r=e.containerElement,t=!0;r[0]!==document&&/static/.test(r.css("position"))&&(a=s),n.left<(e._helper?s.left:0)&&(e.size.width=e.size.width+(e._helper?e.position.left-s.left:e.position.left-a.left),o&&(e.size.height=e.size.width/e.aspectRatio,t=!1),e.position.left=i.helper?s.left:0),n.top<(e._helper?s.top:0)&&(e.size.height=e.size.height+(e._helper?e.position.top-s.top:e.position.top),o&&(e.size.width=e.size.height*e.aspectRatio,t=!1),e.position.top=e._helper?s.top:0),i=e.containerElement.get(0)===e.element.parent().get(0),n=/relative|absolute/.test(e.containerElement.css("position")),i&&n?(e.offset.left=e.parentData.left+e.position.left,e.offset.top=e.parentData.top+e.position.top):(e.offset.left=e.element.offset().left,e.offset.top=e.element.offset().top),n=Math.abs(e.sizeDiff.width+(e._helper?e.offset.left-a.left:e.offset.left-s.left)),s=Math.abs(e.sizeDiff.height+(e._helper?e.offset.top-a.top:e.offset.top-s.top)),n+e.size.width>=e.parentData.width&&(e.size.width=e.parentData.width-n,o&&(e.size.height=e.size.width/e.aspectRatio,t=!1)),s+e.size.height>=e.parentData.height&&(e.size.height=e.parentData.height-s,o&&(e.size.width=e.size.height*e.aspectRatio,t=!1)),t||(e.position.left=e.prevPosition.left,e.position.top=e.prevPosition.top,e.size.width=e.prevSize.width,e.size.height=e.prevSize.height)},stop:function(){var t=V(this).resizable("instance"),e=t.options,i=t.containerOffset,s=t.containerPosition,n=t.containerElement,o=V(t.helper),a=o.offset(),r=o.outerWidth()-t.sizeDiff.width,o=o.outerHeight()-t.sizeDiff.height;t._helper&&!e.animate&&/relative/.test(n.css("position"))&&V(this).css({left:a.left-s.left-i.left,width:r,height:o}),t._helper&&!e.animate&&/static/.test(n.css("position"))&&V(this).css({left:a.left-s.left-i.left,width:r,height:o})}}),V.ui.plugin.add("resizable","alsoResize",{start:function(){var t=V(this).resizable("instance").options;V(t.alsoResize).each(function(){var t=V(this);t.data("ui-resizable-alsoresize",{width:parseFloat(t.width()),height:parseFloat(t.height()),left:parseFloat(t.css("left")),top:parseFloat(t.css("top"))})})},resize:function(t,i){var e=V(this).resizable("instance"),s=e.options,n=e.originalSize,o=e.originalPosition,a={height:e.size.height-n.height||0,width:e.size.width-n.width||0,top:e.position.top-o.top||0,left:e.position.left-o.left||0};V(s.alsoResize).each(function(){var t=V(this),s=V(this).data("ui-resizable-alsoresize"),n={},e=t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];V.each(e,function(t,e){var i=(s[e]||0)+(a[e]||0);i&&0<=i&&(n[e]=i||null)}),t.css(n)})},stop:function(){V(this).removeData("ui-resizable-alsoresize")}}),V.ui.plugin.add("resizable","ghost",{start:function(){var t=V(this).resizable("instance"),e=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:e.height,width:e.width,margin:0,left:0,top:0}),t._addClass(t.ghost,"ui-resizable-ghost"),!1!==V.uiBackCompat&&"string"==typeof t.options.ghost&&t.ghost.addClass(this.options.ghost),t.ghost.appendTo(t.helper)},resize:function(){var t=V(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=V(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),V.ui.plugin.add("resizable","grid",{resize:function(){var t,e=V(this).resizable("instance"),i=e.options,s=e.size,n=e.originalSize,o=e.originalPosition,a=e.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,l=r[0]||1,h=r[1]||1,c=Math.round((s.width-n.width)/l)*l,u=Math.round((s.height-n.height)/h)*h,d=n.width+c,p=n.height+u,f=i.maxWidth&&i.maxWidth<d,g=i.maxHeight&&i.maxHeight<p,m=i.minWidth&&i.minWidth>d,s=i.minHeight&&i.minHeight>p;i.grid=r,m&&(d+=l),s&&(p+=h),f&&(d-=l),g&&(p-=h),/^(se|s|e)$/.test(a)?(e.size.width=d,e.size.height=p):/^(ne)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.top=o.top-u):/^(sw)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.left=o.left-c):((p-h<=0||d-l<=0)&&(t=e._getPaddingPlusBorderDimensions(this)),0<p-h?(e.size.height=p,e.position.top=o.top-u):(p=h-t.height,e.size.height=p,e.position.top=o.top+n.height-p),0<d-l?(e.size.width=d,e.position.left=o.left-c):(d=l-t.width,e.size.width=d,e.position.left=o.left+n.width-d))}});V.ui.resizable;V.widget("ui.dialog",{version:"1.13.2",options:{appendTo:"body",autoOpen:!0,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:!0,closeText:"Close",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var e=V(this).css(t).offset().top;e<0&&V(this).css("top",t.top-e)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),null==this.options.title&&null!=this.originalTitle&&(this.options.title=this.originalTitle),this.options.disabled&&(this.options.disabled=!1),this._createWrapper(),this.element.show().removeAttr("title").appendTo(this.uiDialog),this._addClass("ui-dialog-content","ui-widget-content"),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&V.fn.draggable&&this._makeDraggable(),this.options.resizable&&V.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?V(t):this.document.find(t||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().css(this.originalCss).detach(),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),(t=e.parent.children().eq(e.index)).length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog},disable:V.noop,enable:V.noop,close:function(t){var e=this;this._isOpen&&!1!==this._trigger("beforeClose",t)&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||V.ui.safeBlur(V.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){e._trigger("close",t)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(t,e){var i=!1,s=this.uiDialog.siblings(".ui-front:visible").map(function(){return+V(this).css("z-index")}).get(),s=Math.max.apply(null,s);return s>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",s+1),i=!0),i&&!e&&this._trigger("focus",t),i},open:function(){var t=this;this._isOpen?this._moveToTop()&&this._focusTabbable():(this._isOpen=!0,this.opener=V(V.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){t._focusTabbable(),t._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"))},_focusTabbable:function(){var t=this._focusedElement;(t=!(t=!(t=!(t=!(t=t||this.element.find("[autofocus]")).length?this.element.find(":tabbable"):t).length?this.uiDialogButtonPane.find(":tabbable"):t).length?this.uiDialogTitlebarClose.filter(":tabbable"):t).length?this.uiDialog:t).eq(0).trigger("focus")},_restoreTabbableFocus:function(){var t=V.ui.safeActiveElement(this.document[0]);this.uiDialog[0]===t||V.contains(this.uiDialog[0],t)||this._focusTabbable()},_keepFocus:function(t){t.preventDefault(),this._restoreTabbableFocus(),this._delay(this._restoreTabbableFocus)},_createWrapper:function(){this.uiDialog=V("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===V.ui.keyCode.ESCAPE)return t.preventDefault(),void this.close(t);var e,i,s;t.keyCode!==V.ui.keyCode.TAB||t.isDefaultPrevented()||(e=this.uiDialog.find(":tabbable"),i=e.first(),s=e.last(),t.target!==s[0]&&t.target!==this.uiDialog[0]||t.shiftKey?t.target!==i[0]&&t.target!==this.uiDialog[0]||!t.shiftKey||(this._delay(function(){s.trigger("focus")}),t.preventDefault()):(this._delay(function(){i.trigger("focus")}),t.preventDefault()))},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=V("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(t){V(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=V("<button type='button'></button>").button({label:V("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),t=V("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(t,"ui-dialog-title"),this._title(t),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=V("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=V("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var s=this,t=this.options.buttons;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),V.isEmptyObject(t)||Array.isArray(t)&&!t.length?this._removeClass(this.uiDialog,"ui-dialog-buttons"):(V.each(t,function(t,e){var i;e=V.extend({type:"button"},e="function"==typeof e?{click:e,text:t}:e),i=e.click,t={icon:e.icon,iconPosition:e.iconPosition,showLabel:e.showLabel,icons:e.icons,text:e.text},delete e.click,delete e.icon,delete e.iconPosition,delete e.showLabel,delete e.icons,"boolean"==typeof e.text&&delete e.text,V("<button></button>",e).button(t).appendTo(s.uiButtonSet).on("click",function(){i.apply(s.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog))},_makeDraggable:function(){var n=this,o=this.options;function a(t){return{position:t.position,offset:t.offset}}this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(t,e){n._addClass(V(this),"ui-dialog-dragging"),n._blockFrames(),n._trigger("dragStart",t,a(e))},drag:function(t,e){n._trigger("drag",t,a(e))},stop:function(t,e){var i=e.offset.left-n.document.scrollLeft(),s=e.offset.top-n.document.scrollTop();o.position={my:"left top",at:"left"+(0<=i?"+":"")+i+" top"+(0<=s?"+":"")+s,of:n.window},n._removeClass(V(this),"ui-dialog-dragging"),n._unblockFrames(),n._trigger("dragStop",t,a(e))}})},_makeResizable:function(){var n=this,o=this.options,t=o.resizable,e=this.uiDialog.css("position"),t="string"==typeof t?t:"n,e,s,w,se,sw,ne,nw";function a(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:o.maxWidth,maxHeight:o.maxHeight,minWidth:o.minWidth,minHeight:this._minHeight(),handles:t,start:function(t,e){n._addClass(V(this),"ui-dialog-resizing"),n._blockFrames(),n._trigger("resizeStart",t,a(e))},resize:function(t,e){n._trigger("resize",t,a(e))},stop:function(t,e){var i=n.uiDialog.offset(),s=i.left-n.document.scrollLeft(),i=i.top-n.document.scrollTop();o.height=n.uiDialog.height(),o.width=n.uiDialog.width(),o.position={my:"left top",at:"left"+(0<=s?"+":"")+s+" top"+(0<=i?"+":"")+i,of:n.window},n._removeClass(V(this),"ui-dialog-resizing"),n._unblockFrames(),n._trigger("resizeStop",t,a(e))}}).css("position",e)},_trackFocus:function(){this._on(this.widget(),{focusin:function(t){this._makeFocusTarget(),this._focusedElement=V(t.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var t=this._trackingInstances(),e=V.inArray(this,t);-1!==e&&t.splice(e,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||this.document.data("ui-dialog-instances",t=[]),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(t){var i=this,s=!1,n={};V.each(t,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(t,e){var i,s=this.uiDialog;"disabled"!==t&&(this._super(t,e),"appendTo"===t&&this.uiDialog.appendTo(this._appendTo()),"buttons"===t&&this._createButtons(),"closeText"===t&&this.uiDialogTitlebarClose.button({label:V("<a>").text(""+this.options.closeText).html()}),"draggable"===t&&((i=s.is(":data(ui-draggable)"))&&!e&&s.draggable("destroy"),!i&&e&&this._makeDraggable()),"position"===t&&this._position(),"resizable"===t&&((i=s.is(":data(ui-resizable)"))&&!e&&s.resizable("destroy"),i&&"string"==typeof e&&s.resizable("option","handles",e),i||!1===e||this._makeResizable()),"title"===t&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var t=V(this);return V("<div>").css({position:"absolute",width:t.outerWidth(),height:t.outerHeight()}).appendTo(t.parent()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(t){return!!V(t.target).closest(".ui-dialog").length||!!V(t.target).closest(".ui-datepicker").length},_createOverlay:function(){var i,s;this.options.modal&&(i=V.fn.jquery.substring(0,4),s=!0,this._delay(function(){s=!1}),this.document.data("ui-dialog-overlays")||this.document.on("focusin.ui-dialog",function(t){var e;s||((e=this._trackingInstances()[0])._allowInteraction(t)||(t.preventDefault(),e._focusTabbable(),"3.4."!==i&&"3.5."!==i||e._delay(e._restoreTabbableFocus)))}.bind(this)),this.overlay=V("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1))},_destroyOverlay:function(){var t;this.options.modal&&this.overlay&&((t=this.document.data("ui-dialog-overlays")-1)?this.document.data("ui-dialog-overlays",t):(this.document.off("focusin.ui-dialog"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null)}}),!1!==V.uiBackCompat&&V.widget("ui.dialog",V.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super(),this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(t,e){"dialogClass"===t&&this.uiDialog.removeClass(this.options.dialogClass).addClass(e),this._superApply(arguments)}});V.ui.dialog;function lt(t,e,i){return e<=t&&t<e+i}V.widget("ui.droppable",{version:"1.13.2",widgetEventPrefix:"drop",options:{accept:"*",addClasses:!0,greedy:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t,e=this.options,i=e.accept;this.isover=!1,this.isout=!0,this.accept="function"==typeof i?i:function(t){return t.is(i)},this.proportions=function(){if(!arguments.length)return t=t||{width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};t=arguments[0]},this._addToManager(e.scope),e.addClasses&&this._addClass("ui-droppable")},_addToManager:function(t){V.ui.ddmanager.droppables[t]=V.ui.ddmanager.droppables[t]||[],V.ui.ddmanager.droppables[t].push(this)},_splice:function(t){for(var e=0;e<t.length;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var t=V.ui.ddmanager.droppables[this.options.scope];this._splice(t)},_setOption:function(t,e){var i;"accept"===t?this.accept="function"==typeof e?e:function(t){return t.is(e)}:"scope"===t&&(i=V.ui.ddmanager.droppables[this.options.scope],this._splice(i),this._addToManager(e)),this._super(t,e)},_activate:function(t){var e=V.ui.ddmanager.current;this._addActiveClass(),e&&this._trigger("activate",t,this.ui(e))},_deactivate:function(t){var e=V.ui.ddmanager.current;this._removeActiveClass(),e&&this._trigger("deactivate",t,this.ui(e))},_over:function(t){var e=V.ui.ddmanager.current;e&&(e.currentItem||e.element)[0]!==this.element[0]&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this._addHoverClass(),this._trigger("over",t,this.ui(e)))},_out:function(t){var e=V.ui.ddmanager.current;e&&(e.currentItem||e.element)[0]!==this.element[0]&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this._removeHoverClass(),this._trigger("out",t,this.ui(e)))},_drop:function(e,t){var i=t||V.ui.ddmanager.current,s=!1;return!(!i||(i.currentItem||i.element)[0]===this.element[0])&&(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=V(this).droppable("instance");if(t.options.greedy&&!t.options.disabled&&t.options.scope===i.options.scope&&t.accept.call(t.element[0],i.currentItem||i.element)&&V.ui.intersect(i,V.extend(t,{offset:t.element.offset()}),t.options.tolerance,e))return!(s=!0)}),!s&&(!!this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(i)),this.element)))},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}}),V.ui.intersect=function(t,e,i,s){if(!e.offset)return!1;var n=(t.positionAbs||t.position.absolute).left+t.margins.left,o=(t.positionAbs||t.position.absolute).top+t.margins.top,a=n+t.helperProportions.width,r=o+t.helperProportions.height,l=e.offset.left,h=e.offset.top,c=l+e.proportions().width,u=h+e.proportions().height;switch(i){case"fit":return l<=n&&a<=c&&h<=o&&r<=u;case"intersect":return l<n+t.helperProportions.width/2&&a-t.helperProportions.width/2<c&&h<o+t.helperProportions.height/2&&r-t.helperProportions.height/2<u;case"pointer":return lt(s.pageY,h,e.proportions().height)&&lt(s.pageX,l,e.proportions().width);case"touch":return(h<=o&&o<=u||h<=r&&r<=u||o<h&&u<r)&&(l<=n&&n<=c||l<=a&&a<=c||n<l&&c<a);default:return!1}},!(V.ui.ddmanager={current:null,droppables:{default:[]},prepareOffsets:function(t,e){var i,s,n=V.ui.ddmanager.droppables[t.options.scope]||[],o=e?e.type:null,a=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();t:for(i=0;i<n.length;i++)if(!(n[i].options.disabled||t&&!n[i].accept.call(n[i].element[0],t.currentItem||t.element))){for(s=0;s<a.length;s++)if(a[s]===n[i].element[0]){n[i].proportions().height=0;continue t}n[i].visible="none"!==n[i].element.css("display"),n[i].visible&&("mousedown"===o&&n[i]._activate.call(n[i],e),n[i].offset=n[i].element.offset(),n[i].proportions({width:n[i].element[0].offsetWidth,height:n[i].element[0].offsetHeight}))}},drop:function(t,e){var i=!1;return V.each((V.ui.ddmanager.droppables[t.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&V.ui.intersect(t,this,this.options.tolerance,e)&&(i=this._drop.call(this,e)||i),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,e)))}),i},dragStart:function(t,e){t.element.parentsUntil("body").on("scroll.droppable",function(){t.options.refreshPositions||V.ui.ddmanager.prepareOffsets(t,e)})},drag:function(n,o){n.options.refreshPositions&&V.ui.ddmanager.prepareOffsets(n,o),V.each(V.ui.ddmanager.droppables[n.options.scope]||[],function(){var t,e,i,s;this.options.disabled||this.greedyChild||!this.visible||(s=!(i=V.ui.intersect(n,this,this.options.tolerance,o))&&this.isover?"isout":i&&!this.isover?"isover":null)&&(this.options.greedy&&(e=this.options.scope,(i=this.element.parents(":data(ui-droppable)").filter(function(){return V(this).droppable("instance").options.scope===e})).length&&((t=V(i[0]).droppable("instance")).greedyChild="isover"===s)),t&&"isover"===s&&(t.isover=!1,t.isout=!0,t._out.call(t,o)),this[s]=!0,this["isout"===s?"isover":"isout"]=!1,this["isover"===s?"_over":"_out"].call(this,o),t&&"isout"===s&&(t.isout=!1,t.isover=!0,t._over.call(t,o)))})},dragStop:function(t,e){t.element.parentsUntil("body").off("scroll.droppable"),t.options.refreshPositions||V.ui.ddmanager.prepareOffsets(t,e)}})!==V.uiBackCompat&&V.widget("ui.droppable",V.ui.droppable,{options:{hoverClass:!1,activeClass:!1},_addActiveClass:function(){this._super(),this.options.activeClass&&this.element.addClass(this.options.activeClass)},_removeActiveClass:function(){this._super(),this.options.activeClass&&this.element.removeClass(this.options.activeClass)},_addHoverClass:function(){this._super(),this.options.hoverClass&&this.element.addClass(this.options.hoverClass)},_removeHoverClass:function(){this._super(),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass)}});V.ui.droppable,V.widget("ui.progressbar",{version:"1.13.2",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.attr({role:"progressbar","aria-valuemin":this.min}),this._addClass("ui-progressbar","ui-widget ui-widget-content"),this.valueDiv=V("<div>").appendTo(this.element),this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header"),this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow"),this.valueDiv.remove()},value:function(t){if(void 0===t)return this.options.value;this.options.value=this._constrainedValue(t),this._refreshValue()},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=!1===t,"number"!=typeof t&&(t=0),!this.indeterminate&&Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var t=this.options.value,e=this._percentage();this.valueDiv.toggle(this.indeterminate||t>this.min).width(e.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,t===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=V("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":t}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==t&&(this.oldValue=t,this._trigger("change")),t===this.options.max&&this._trigger("complete")}}),V.widget("ui.selectable",V.ui.mouse,{version:"1.13.2",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var i=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){i.elementPos=V(i.element[0]).offset(),i.selectees=V(i.options.filter,i.element[0]),i._addClass(i.selectees,"ui-selectee"),i.selectees.each(function(){var t=V(this),e=t.offset(),e={left:e.left-i.elementPos.left,top:e.top-i.elementPos.top};V.data(this,"selectable-item",{element:this,$element:t,left:e.left,top:e.top,right:e.left+t.outerWidth(),bottom:e.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=V("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(i){var s=this,t=this.options;this.opos=[i.pageX,i.pageY],this.elementPos=V(this.element[0]).offset(),this.options.disabled||(this.selectees=V(t.filter,this.element[0]),this._trigger("start",i),V(t.appendTo).append(this.helper),this.helper.css({left:i.pageX,top:i.pageY,width:0,height:0}),t.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var t=V.data(this,"selectable-item");t.startselected=!0,i.metaKey||i.ctrlKey||(s._removeClass(t.$element,"ui-selected"),t.selected=!1,s._addClass(t.$element,"ui-unselecting"),t.unselecting=!0,s._trigger("unselecting",i,{unselecting:t.element}))}),V(i.target).parents().addBack().each(function(){var t,e=V.data(this,"selectable-item");if(e)return t=!i.metaKey&&!i.ctrlKey||!e.$element.hasClass("ui-selected"),s._removeClass(e.$element,t?"ui-unselecting":"ui-selected")._addClass(e.$element,t?"ui-selecting":"ui-unselecting"),e.unselecting=!t,e.selecting=t,(e.selected=t)?s._trigger("selecting",i,{selecting:e.element}):s._trigger("unselecting",i,{unselecting:e.element}),!1}))},_mouseDrag:function(s){if(this.dragged=!0,!this.options.disabled){var t,n=this,o=this.options,a=this.opos[0],r=this.opos[1],l=s.pageX,h=s.pageY;return l<a&&(t=l,l=a,a=t),h<r&&(t=h,h=r,r=t),this.helper.css({left:a,top:r,width:l-a,height:h-r}),this.selectees.each(function(){var t=V.data(this,"selectable-item"),e=!1,i={};t&&t.element!==n.element[0]&&(i.left=t.left+n.elementPos.left,i.right=t.right+n.elementPos.left,i.top=t.top+n.elementPos.top,i.bottom=t.bottom+n.elementPos.top,"touch"===o.tolerance?e=!(i.left>l||i.right<a||i.top>h||i.bottom<r):"fit"===o.tolerance&&(e=i.left>a&&i.right<l&&i.top>r&&i.bottom<h),e?(t.selected&&(n._removeClass(t.$element,"ui-selected"),t.selected=!1),t.unselecting&&(n._removeClass(t.$element,"ui-unselecting"),t.unselecting=!1),t.selecting||(n._addClass(t.$element,"ui-selecting"),t.selecting=!0,n._trigger("selecting",s,{selecting:t.element}))):(t.selecting&&((s.metaKey||s.ctrlKey)&&t.startselected?(n._removeClass(t.$element,"ui-selecting"),t.selecting=!1,n._addClass(t.$element,"ui-selected"),t.selected=!0):(n._removeClass(t.$element,"ui-selecting"),t.selecting=!1,t.startselected&&(n._addClass(t.$element,"ui-unselecting"),t.unselecting=!0),n._trigger("unselecting",s,{unselecting:t.element}))),t.selected&&(s.metaKey||s.ctrlKey||t.startselected||(n._removeClass(t.$element,"ui-selected"),t.selected=!1,n._addClass(t.$element,"ui-unselecting"),t.unselecting=!0,n._trigger("unselecting",s,{unselecting:t.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,V(".ui-unselecting",this.element[0]).each(function(){var t=V.data(this,"selectable-item");i._removeClass(t.$element,"ui-unselecting"),t.unselecting=!1,t.startselected=!1,i._trigger("unselected",e,{unselected:t.element})}),V(".ui-selecting",this.element[0]).each(function(){var t=V.data(this,"selectable-item");i._removeClass(t.$element,"ui-selecting")._addClass(t.$element,"ui-selected"),t.selecting=!1,t.selected=!0,t.startselected=!0,i._trigger("selected",e,{selected:t.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),V.widget("ui.selectmenu",[V.ui.formResetMixin,{version:"1.13.2",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:!1,change:null,close:null,focus:null,open:null,select:null},_create:function(){var t=this.element.uniqueId().attr("id");this.ids={element:t,button:t+"-button",menu:t+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=V()},_drawButton:function(){var t,e=this,i=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button),this._on(this.labels,{click:function(t){this.button.trigger("focus"),t.preventDefault()}}),this.element.hide(),this.button=V("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element),this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget"),t=V("<span>").appendTo(this.button),this._addClass(t,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(i).appendTo(this.button),!1!==this.options.width&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){e._rendered||e._refreshMenu()})},_drawMenu:function(){var i=this;this.menu=V("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=V("<div>").append(this.menu),this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front"),this.menuWrap.appendTo(this._appendTo()),this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(t,e){t.preventDefault(),i._setSelection(),i._select(e.item.data("ui-selectmenu-item"),t)},focus:function(t,e){e=e.item.data("ui-selectmenu-item");null!=i.focusIndex&&e.index!==i.focusIndex&&(i._trigger("focus",t,{item:e}),i.isOpen||i._select(e,t)),i.focusIndex=e.index,i.button.attr("aria-activedescendant",i.menuItems.eq(e.index).attr("id"))}}).menu("instance"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{})),null===this.options.width&&this._resizeButton()},_refreshMenu:function(){var t=this.element.find("option");this.menu.empty(),this._parseOptions(t),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper"),this._rendered=!0,t.length&&(t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){this.options.disabled||(this._rendered?(this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.menuItems.length&&(this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t)))},_position:function(){this.menuWrap.position(V.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(t){var e=V("<span>");return this._setText(e,t.label),this._addClass(e,"ui-selectmenu-text"),e},_renderMenu:function(s,t){var n=this,o="";V.each(t,function(t,e){var i;e.optgroup!==o&&(i=V("<li>",{text:e.optgroup}),n._addClass(i,"ui-selectmenu-optgroup","ui-menu-divider"+(e.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),i.appendTo(s),o=e.optgroup),n._renderItemData(s,e)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(t,e){var i=V("<li>"),s=V("<div>",{title:e.element.attr("title")});return e.disabled&&this._addClass(i,null,"ui-state-disabled"),this._setText(s,e.label),i.append(s).appendTo(t)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),s+=":not(.ui-state-disabled)"),(s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](s).eq(-1):i[t+"All"](s).eq(0)).length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&(window.getSelection?((t=window.getSelection()).removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.trigger("focus"))},_documentClick:{mousedown:function(t){this.isOpen&&(V(t.target).closest(".ui-selectmenu-menu, #"+V.escapeSelector(this.ids.button)).length||this.close(t))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection()).rangeCount&&(this.range=t.getRangeAt(0)):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(t){var e=!0;switch(t.keyCode){case V.ui.keyCode.TAB:case V.ui.keyCode.ESCAPE:this.close(t),e=!1;break;case V.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(t);break;case V.ui.keyCode.UP:t.altKey?this._toggle(t):this._move("prev",t);break;case V.ui.keyCode.DOWN:t.altKey?this._toggle(t):this._move("next",t);break;case V.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(t):this._toggle(t);break;case V.ui.keyCode.LEFT:this._move("prev",t);break;case V.ui.keyCode.RIGHT:this._move("next",t);break;case V.ui.keyCode.HOME:case V.ui.keyCode.PAGE_UP:this._move("first",t);break;case V.ui.keyCode.END:case V.ui.keyCode.PAGE_DOWN:this._move("last",t);break;default:this.menu.trigger(t),e=!1}e&&t.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex).parent("li");e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(t)),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){t=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":t,"aria-activedescendant":t}),this.menu.attr("aria-activedescendant",t)},_setOption:function(t,e){var i;"icons"===t&&(i=this.button.find("span.ui-icon"),this._removeClass(i,null,this.options.icons.button)._addClass(i,null,e.button)),this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"width"===t&&this._resizeButton()},_setOptionDisabled:function(t){this._super(t),this.menuInstance.option("disabled",t),this.button.attr("aria-disabled",t),this._toggleClass(this.button,null,"ui-state-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)},_appendTo:function(){var t=this.options.appendTo;return t=!(t=!(t=t&&(t.jquery||t.nodeType?V(t):this.document.find(t).eq(0)))||!t[0]?this.element.closest(".ui-front, dialog"):t).length?this.document[0].body:t},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen),this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;!1!==t?(null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t)):this.button.css("width","")},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){var t=this._super();return t.disabled=this.element.prop("disabled"),t},_parseOptions:function(t){var i=this,s=[];t.each(function(t,e){e.hidden||s.push(i._parseOption(V(e),t))}),this.items=s},_parseOption:function(t,e){var i=t.parent("optgroup");return{element:t,index:e,value:t.val(),label:t.text(),optgroup:i.attr("label")||"",disabled:i.prop("disabled")||t.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler(),this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.labels.attr("for",this.ids.element)}}]),V.widget("ui.slider",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var t,e=this.options,i=this.element.find(".ui-slider-handle"),s=[],n=e.values&&e.values.length||1;for(i.length>n&&(i.slice(n).remove(),i=i.slice(0,n)),t=i.length;t<n;t++)s.push("<span tabindex='0'></span>");this.handles=i.add(V(s.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(t){V(this).data("ui-slider-handle-index",t).attr("tabIndex",0)})},_createRange:function(){var t=this.options;t.range?(!0===t.range&&(t.values?t.values.length&&2!==t.values.length?t.values=[t.values[0],t.values[0]]:Array.isArray(t.values)&&(t.values=t.values.slice(0)):t.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=V("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),"min"!==t.range&&"max"!==t.range||this._addClass(this.range,"ui-slider-range-"+t.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(t){var i,s,n,o,e,a,r=this,l=this.options;return!l.disabled&&(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),a={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(a),s=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var e=Math.abs(i-r.values(t));(e<s||s===e&&(t===r._lastChangedValue||r.values(t)===l.min))&&(s=e,n=V(this),o=t)}),!1!==this._start(t,o)&&(this._mouseSliding=!0,this._handleIndex=o,this._addClass(n,null,"ui-state-active"),n.trigger("focus"),e=n.offset(),a=!V(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=a?{left:0,top:0}:{left:t.pageX-e.left-n.width()/2,top:t.pageY-e.top-n.height()/2-(parseInt(n.css("borderTopWidth"),10)||0)-(parseInt(n.css("borderBottomWidth"),10)||0)+(parseInt(n.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,i),this._animateOff=!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},e=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,e),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,t="horizontal"===this.orientation?(e=this.elementSize.width,t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),t=t/e;return(t=1<t?1:t)<0&&(t=0),"vertical"===this.orientation&&(t=1-t),e=this._valueMax()-this._valueMin(),e=this._valueMin()+t*e,this._trimAlignValue(e)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n=this.value(),o=this.values();this._hasMultipleValues()&&(s=this.values(e?0:1),n=this.values(e),2===this.options.values.length&&!0===this.options.range&&(i=0===e?Math.min(s,i):Math.max(s,i)),o[e]=i),i!==n&&!1!==this._trigger("slide",t,this._uiHash(e,i,o))&&(this._hasMultipleValues()?this.values(e,i):this.value(i))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),void this._change(null,0)):this._value()},values:function(t,e){var i,s,n;if(1<arguments.length)return this.options.values[t]=this._trimAlignValue(e),this._refreshValue(),void this._change(null,t);if(!arguments.length)return this._values();if(!Array.isArray(t))return this._hasMultipleValues()?this._values(t):this.value();for(i=this.options.values,s=t,n=0;n<i.length;n+=1)i[n]=this._trimAlignValue(s[n]),this._change(null,n);this._refreshValue()},_setOption:function(t,e){var i,s=0;switch("range"===t&&!0===this.options.range&&("min"===e?(this.options.value=this._values(0),this.options.values=null):"max"===e&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),Array.isArray(this.options.values)&&(s=this.options.values.length),this._super(t,e),t){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(e),this.handles.css("horizontal"===e?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),i=s-1;0<=i;i--)this._change(null,i);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(t){this._super(t),this._toggleClass(null,"ui-state-disabled",!!t)},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i;if(arguments.length)return t=this.options.values[t],t=this._trimAlignValue(t);if(this._hasMultipleValues()){for(e=this.options.values.slice(),i=0;i<e.length;i+=1)e[i]=this._trimAlignValue(e[i]);return e}return[]},_trimAlignValue:function(t){if(t<=this._valueMin())return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=0<this.options.step?this.options.step:1,i=(t-this._valueMin())%e,t=t-i;return 2*Math.abs(i)>=e&&(t+=0<i?e:-e),parseFloat(t.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step;(t=Math.round((t-e)/i)*i+e)>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return t=null!==this.options.min?Math.max(t,this._precisionOf(this.options.min)):t},_precisionOf:function(t){var e=t.toString(),t=e.indexOf(".");return-1===t?0:e.length-t-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(t){"vertical"===t&&this.range.css({width:"",left:""}),"horizontal"===t&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var e,i,t,s,n,o=this.options.range,a=this.options,r=this,l=!this._animateOff&&a.animate,h={};this._hasMultipleValues()?this.handles.each(function(t){i=(r.values(t)-r._valueMin())/(r._valueMax()-r._valueMin())*100,h["horizontal"===r.orientation?"left":"bottom"]=i+"%",V(this).stop(1,1)[l?"animate":"css"](h,a.animate),!0===r.options.range&&("horizontal"===r.orientation?(0===t&&r.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},a.animate),1===t&&r.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:a.animate})):(0===t&&r.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},a.animate),1===t&&r.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:a.animate}))),e=i}):(t=this.value(),s=this._valueMin(),n=this._valueMax(),i=n!==s?(t-s)/(n-s)*100:0,h["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](h,a.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},a.animate),"max"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:100-i+"%"},a.animate),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},a.animate),"max"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:100-i+"%"},a.animate))},_handleEvents:{keydown:function(t){var e,i,s,n=V(t.target).data("ui-slider-handle-index");switch(t.keyCode){case V.ui.keyCode.HOME:case V.ui.keyCode.END:case V.ui.keyCode.PAGE_UP:case V.ui.keyCode.PAGE_DOWN:case V.ui.keyCode.UP:case V.ui.keyCode.RIGHT:case V.ui.keyCode.DOWN:case V.ui.keyCode.LEFT:if(t.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(V(t.target),null,"ui-state-active"),!1===this._start(t,n)))return}switch(s=this.options.step,e=i=this._hasMultipleValues()?this.values(n):this.value(),t.keyCode){case V.ui.keyCode.HOME:i=this._valueMin();break;case V.ui.keyCode.END:i=this._valueMax();break;case V.ui.keyCode.PAGE_UP:i=this._trimAlignValue(e+(this._valueMax()-this._valueMin())/this.numPages);break;case V.ui.keyCode.PAGE_DOWN:i=this._trimAlignValue(e-(this._valueMax()-this._valueMin())/this.numPages);break;case V.ui.keyCode.UP:case V.ui.keyCode.RIGHT:if(e===this._valueMax())return;i=this._trimAlignValue(e+s);break;case V.ui.keyCode.DOWN:case V.ui.keyCode.LEFT:if(e===this._valueMin())return;i=this._trimAlignValue(e-s)}this._slide(t,n,i)},keyup:function(t){var e=V(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,e),this._change(t,e),this._removeClass(V(t.target),null,"ui-state-active"))}}}),V.widget("ui.sortable",V.ui.mouse,{version:"1.13.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return e<=t&&t<e+i},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var t=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),V.each(this.items,function(){t._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;0<=t;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(t,e){var i=null,s=!1,n=this;return!this.reverting&&(!this.options.disabled&&"static"!==this.options.type&&(this._refreshItems(t),V(t.target).parents().each(function(){if(V.data(this,n.widgetName+"-item")===n)return i=V(this),!1}),!!(i=V.data(t.target,n.widgetName+"-item")===n?V(t.target):i)&&(!(this.options.handle&&!e&&(V(this.options.handle,i).find("*").addBack().each(function(){this===t.target&&(s=!0)}),!s))&&(this.currentItem=i,this._removeCurrentsFromItems(),!0))))},_mouseStart:function(t,e,i){var s,n,o=this.options;if((this.currentContainer=this).refreshPositions(),this.appendTo=V("parent"!==o.appendTo?o.appendTo:this.currentItem.parent()),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},V.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),this.scrollParent=this.placeholder.scrollParent(),V.extend(this.offset,{parent:this._getParentOffset()}),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(n=this.document.find("body"),this.storedCursor=n.css("cursor"),n.css("cursor",o.cursor),this.storedStylesheet=V("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(n)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!i)for(s=this.containers.length-1;0<=s;s--)this.containers[s]._trigger("activate",t,this._uiHash(this));return V.ui.ddmanager&&(V.ui.ddmanager.current=this),V.ui.ddmanager&&!o.dropBehaviour&&V.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this.helper.parent().is(this.appendTo)||(this.helper.detach().appendTo(this.appendTo),this.offset.parent=this._getParentOffset()),this.position=this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,this.lastPositionAbs=this.positionAbs=this._convertPositionTo("absolute"),this._mouseDrag(t),!0},_scroll:function(t){var e=this.options,i=!1;return this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<e.scrollSensitivity?this.scrollParent[0].scrollTop=i=this.scrollParent[0].scrollTop+e.scrollSpeed:t.pageY-this.overflowOffset.top<e.scrollSensitivity&&(this.scrollParent[0].scrollTop=i=this.scrollParent[0].scrollTop-e.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<e.scrollSensitivity?this.scrollParent[0].scrollLeft=i=this.scrollParent[0].scrollLeft+e.scrollSpeed:t.pageX-this.overflowOffset.left<e.scrollSensitivity&&(this.scrollParent[0].scrollLeft=i=this.scrollParent[0].scrollLeft-e.scrollSpeed)):(t.pageY-this.document.scrollTop()<e.scrollSensitivity?i=this.document.scrollTop(this.document.scrollTop()-e.scrollSpeed):this.window.height()-(t.pageY-this.document.scrollTop())<e.scrollSensitivity&&(i=this.document.scrollTop(this.document.scrollTop()+e.scrollSpeed)),t.pageX-this.document.scrollLeft()<e.scrollSensitivity?i=this.document.scrollLeft(this.document.scrollLeft()-e.scrollSpeed):this.window.width()-(t.pageX-this.document.scrollLeft())<e.scrollSensitivity&&(i=this.document.scrollLeft(this.document.scrollLeft()+e.scrollSpeed))),i},_mouseDrag:function(t){var e,i,s,n,o=this.options;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),o.scroll&&!1!==this._scroll(t)&&(this._refreshItemPositions(!0),V.ui.ddmanager&&!o.dropBehaviour&&V.ui.ddmanager.prepareOffsets(this,t)),this.dragDirection={vertical:this._getDragVerticalDirection(),horizontal:this._getDragHorizontalDirection()},e=this.items.length-1;0<=e;e--)if(s=(i=this.items[e]).item[0],(n=this._intersectsWithPointer(i))&&i.instance===this.currentContainer&&!(s===this.currentItem[0]||this.placeholder[1===n?"next":"prev"]()[0]===s||V.contains(this.placeholder[0],s)||"semi-dynamic"===this.options.type&&V.contains(this.element[0],s))){if(this.direction=1===n?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(i))break;this._rearrange(t,i),this._trigger("change",t,this._uiHash());break}return this._contactContainers(t),V.ui.ddmanager&&V.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,e){var i,s,n,o;if(t)return V.ui.ddmanager&&!this.options.dropBehaviour&&V.ui.ddmanager.drop(this,t),this.options.revert?(s=(i=this).placeholder.offset(),o={},(n=this.options.axis)&&"x"!==n||(o.left=s.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),n&&"y"!==n||(o.top=s.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,V(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){i._clear(t)})):this._clear(t,e),!1},cancel:function(){if(this.dragging){this._mouseUp(new V.Event("mouseup",{target:null})),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var t=this.containers.length-1;0<=t;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),V.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?V(this.domPosition.prev).after(this.currentItem):V(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var t=this._getItemsAsjQuery(e&&e.connected),i=[];return e=e||{},V(t).each(function(){var t=(V(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);t&&i.push((e.key||t[1]+"[]")+"="+(e.key&&e.expression?t[1]:t[2]))}),!i.length&&e.key&&i.push(e.key+"="),i.join("&")},toArray:function(t){var e=this._getItemsAsjQuery(t&&t.connected),i=[];return t=t||{},e.each(function(){i.push(V(t.item||this).attr(t.attribute||"id")||"")}),i},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,l=r+t.height,h=this.offset.click.top,c=this.offset.click.left,h="x"===this.options.axis||r<s+h&&s+h<l,c="y"===this.options.axis||o<e+c&&e+c<a;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?h&&c:o<e+this.helperProportions.width/2&&i-this.helperProportions.width/2<a&&r<s+this.helperProportions.height/2&&n-this.helperProportions.height/2<l},_intersectsWithPointer:function(t){var e="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),t="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width);return!(!e||!t)&&(e=this.dragDirection.vertical,t=this.dragDirection.horizontal,this.floating?"right"===t||"down"===e?2:1:e&&("down"===e?2:1))},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this.dragDirection.vertical,t=this.dragDirection.horizontal;return this.floating&&t?"right"===t&&i||"left"===t&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!=t&&(0<t?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!=t&&(0<t?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(t){var e,i,s,n,o=[],a=[],r=this._connectWith();if(r&&t)for(e=r.length-1;0<=e;e--)for(i=(s=V(r[e],this.document[0])).length-1;0<=i;i--)(n=V.data(s[i],this.widgetFullName))&&n!==this&&!n.options.disabled&&a.push(["function"==typeof n.options.items?n.options.items.call(n.element):V(n.options.items,n.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),n]);function l(){o.push(this)}for(a.push(["function"==typeof this.options.items?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):V(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),e=a.length-1;0<=e;e--)a[e][0].each(l);return V(o)},_removeCurrentsFromItems:function(){var i=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=V.grep(this.items,function(t){for(var e=0;e<i.length;e++)if(i[e]===t.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var e,i,s,n,o,a,r,l,h=this.items,c=[["function"==typeof this.options.items?this.options.items.call(this.element[0],t,{item:this.currentItem}):V(this.options.items,this.element),this]],u=this._connectWith();if(u&&this.ready)for(e=u.length-1;0<=e;e--)for(i=(s=V(u[e],this.document[0])).length-1;0<=i;i--)(n=V.data(s[i],this.widgetFullName))&&n!==this&&!n.options.disabled&&(c.push(["function"==typeof n.options.items?n.options.items.call(n.element[0],t,{item:this.currentItem}):V(n.options.items,n.element),n]),this.containers.push(n));for(e=c.length-1;0<=e;e--)for(o=c[e][1],l=(a=c[e][i=0]).length;i<l;i++)(r=V(a[i])).data(this.widgetName+"-item",o),h.push({item:r,instance:o,width:0,height:0,left:0,top:0})},_refreshItemPositions:function(t){for(var e,i,s=this.items.length-1;0<=s;s--)e=this.items[s],this.currentContainer&&e.instance!==this.currentContainer&&e.item[0]!==this.currentItem[0]||(i=this.options.toleranceElement?V(this.options.toleranceElement,e.item):e.item,t||(e.width=i.outerWidth(),e.height=i.outerHeight()),i=i.offset(),e.left=i.left,e.top=i.top)},refreshPositions:function(t){var e,i;if(this.floating=!!this.items.length&&("x"===this.options.axis||this._isFloating(this.items[0].item)),this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset()),this._refreshItemPositions(t),this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(e=this.containers.length-1;0<=e;e--)i=this.containers[e].element.offset(),this.containers[e].containerCache.left=i.left,this.containers[e].containerCache.top=i.top,this.containers[e].containerCache.width=this.containers[e].element.outerWidth(),this.containers[e].containerCache.height=this.containers[e].element.outerHeight();return this},_createPlaceholder:function(i){var s,n,o=(i=i||this).options;o.placeholder&&o.placeholder.constructor!==String||(s=o.placeholder,n=i.currentItem[0].nodeName.toLowerCase(),o.placeholder={element:function(){var t=V("<"+n+">",i.document[0]);return i._addClass(t,"ui-sortable-placeholder",s||i.currentItem[0].className)._removeClass(t,"ui-sortable-helper"),"tbody"===n?i._createTrPlaceholder(i.currentItem.find("tr").eq(0),V("<tr>",i.document[0]).appendTo(t)):"tr"===n?i._createTrPlaceholder(i.currentItem,t):"img"===n&&t.attr("src",i.currentItem.attr("src")),s||t.css("visibility","hidden"),t},update:function(t,e){s&&!o.forcePlaceholderSize||(e.height()&&(!o.forcePlaceholderSize||"tbody"!==n&&"tr"!==n)||e.height(i.currentItem.innerHeight()-parseInt(i.currentItem.css("paddingTop")||0,10)-parseInt(i.currentItem.css("paddingBottom")||0,10)),e.width()||e.width(i.currentItem.innerWidth()-parseInt(i.currentItem.css("paddingLeft")||0,10)-parseInt(i.currentItem.css("paddingRight")||0,10)))}}),i.placeholder=V(o.placeholder.element.call(i.element,i.currentItem)),i.currentItem.after(i.placeholder),o.placeholder.update(i,i.placeholder)},_createTrPlaceholder:function(t,e){var i=this;t.children().each(function(){V("<td>&#160;</td>",i.document[0]).attr("colspan",V(this).attr("colspan")||1).appendTo(e)})},_contactContainers:function(t){for(var e,i,s,n,o,a,r,l,h,c=null,u=null,d=this.containers.length-1;0<=d;d--)V.contains(this.currentItem[0],this.containers[d].element[0])||(this._intersectsWith(this.containers[d].containerCache)?c&&V.contains(this.containers[d].element[0],c.element[0])||(c=this.containers[d],u=d):this.containers[d].containerCache.over&&(this.containers[d]._trigger("out",t,this._uiHash(this)),this.containers[d].containerCache.over=0));if(c)if(1===this.containers.length)this.containers[u].containerCache.over||(this.containers[u]._trigger("over",t,this._uiHash(this)),this.containers[u].containerCache.over=1);else{for(i=1e4,s=null,n=(l=c.floating||this._isFloating(this.currentItem))?"left":"top",o=l?"width":"height",h=l?"pageX":"pageY",e=this.items.length-1;0<=e;e--)V.contains(this.containers[u].element[0],this.items[e].item[0])&&this.items[e].item[0]!==this.currentItem[0]&&(a=this.items[e].item.offset()[n],r=!1,t[h]-a>this.items[e][o]/2&&(r=!0),Math.abs(t[h]-a)<i&&(i=Math.abs(t[h]-a),s=this.items[e],this.direction=r?"up":"down"));(s||this.options.dropOnEmpty)&&(this.currentContainer!==this.containers[u]?(s?this._rearrange(t,s,null,!0):this._rearrange(t,null,this.containers[u].element,!0),this._trigger("change",t,this._uiHash()),this.containers[u]._trigger("change",t,this._uiHash(this)),this.currentContainer=this.containers[u],this.options.placeholder.update(this.currentContainer,this.placeholder),this.scrollParent=this.placeholder.scrollParent(),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this.containers[u]._trigger("over",t,this._uiHash(this)),this.containers[u].containerCache.over=1):this.currentContainer.containerCache.over||(this.containers[u]._trigger("over",t,this._uiHash()),this.currentContainer.containerCache.over=1))}},_createHelper:function(t){var e=this.options,t="function"==typeof e.helper?V(e.helper.apply(this.element[0],[t,this.currentItem])):"clone"===e.helper?this.currentItem.clone():this.currentItem;return t.parents("body").length||this.appendTo[0].appendChild(t[0]),t[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),t[0].style.width&&!e.forceHelperSize||t.width(this.currentItem.width()),t[0].style.height&&!e.forceHelperSize||t.height(this.currentItem.height()),t},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),"left"in(t=Array.isArray(t)?{left:+t[0],top:+t[1]||0}:t)&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&V.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),{top:(t=this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&V.ui.ie?{top:0,left:0}:t).top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,e,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode),"document"!==i.containment&&"window"!==i.containment||(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===i.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===i.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(i.containment)||(t=V(i.containment)[0],e=V(i.containment).offset(),i="hidden"!==V(t).css("overflow"),this.containment=[e.left+(parseInt(V(t).css("borderLeftWidth"),10)||0)+(parseInt(V(t).css("paddingLeft"),10)||0)-this.margins.left,e.top+(parseInt(V(t).css("borderTopWidth"),10)||0)+(parseInt(V(t).css("paddingTop"),10)||0)-this.margins.top,e.left+(i?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(V(t).css("borderLeftWidth"),10)||0)-(parseInt(V(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,e.top+(i?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(V(t).css("borderTopWidth"),10)||0)-(parseInt(V(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,e){e=e||this.position;var i="absolute"===t?1:-1,s="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&V.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,t=/(html|body)/i.test(s[0].tagName);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():t?0:s.scrollTop())*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():t?0:s.scrollLeft())*i}},_generatePosition:function(t){var e=this.options,i=t.pageX,s=t.pageY,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&V.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(i=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(s=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(i=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(s=this.containment[3]+this.offset.click.top)),e.grid&&(t=this.originalPageY+Math.round((s-this.originalPageY)/e.grid[1])*e.grid[1],s=!this.containment||t-this.offset.click.top>=this.containment[1]&&t-this.offset.click.top<=this.containment[3]?t:t-this.offset.click.top>=this.containment[1]?t-e.grid[1]:t+e.grid[1],t=this.originalPageX+Math.round((i-this.originalPageX)/e.grid[0])*e.grid[0],i=!this.containment||t-this.offset.click.left>=this.containment[0]&&t-this.offset.click.left<=this.containment[2]?t:t-this.offset.click.left>=this.containment[0]?t-e.grid[0]:t+e.grid[0])),{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop()),left:i-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){this.reverting=!1;var i,s=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)"auto"!==this._storedCSS[i]&&"static"!==this._storedCSS[i]||(this._storedCSS[i]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();function n(e,i,s){return function(t){s._trigger(e,t,i._uiHash(i))}}for(this.fromOutside&&!e&&s.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||s.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(s.push(function(t){this._trigger("remove",t,this._uiHash())}),s.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),s.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),i=this.containers.length-1;0<=i;i--)e||s.push(n("deactivate",this,this.containers[i])),this.containers[i].containerCache.over&&(s.push(n("out",this,this.containers[i])),this.containers[i].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(i=0;i<s.length;i++)s[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){!1===V.Widget.prototype._trigger.apply(this,arguments)&&this.cancel()},_uiHash:function(t){var e=t||this;return{helper:e.helper,placeholder:e.placeholder||V([]),position:e.position,originalPosition:e.originalPosition,offset:e.positionAbs,item:e.currentItem,sender:t?t.element:null}}});function ht(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger("change")}}V.widget("ui.spinner",{version:"1.13.2",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var s=this._super(),n=this.element;return V.each(["min","max","step"],function(t,e){var i=n.attr(e);null!=i&&i.length&&(s[e]=i)}),s},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){this.cancelBlur?delete this.cancelBlur:(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t))},mousewheel:function(t,e){var i=V.ui.safeActiveElement(this.document[0]);if(this.element[0]===i&&e){if(!this.spinning&&!this._start(t))return!1;this._spin((0<e?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(t){var e;function i(){this.element[0]===V.ui.safeActiveElement(this.document[0])||(this.element.trigger("focus"),this.previous=e,this._delay(function(){this.previous=e}))}e=this.element[0]===V.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),t.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),!1!==this._start(t)&&this._repeat(null,V(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){if(V(t.currentTarget).hasClass("ui-state-active"))return!1!==this._start(t)&&void this._repeat(null,V(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",!0).button({classes:{"ui-button":""}}),this._removeClass(this.buttons,"ui-corner-all"),this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up"),this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down"),this.buttons.first().button({icon:this.options.icons.up,showLabel:!1}),this.buttons.last().button({icon:this.options.icons.down,showLabel:!1}),this.buttons.height()>Math.ceil(.5*this.uiSpinner.height())&&0<this.uiSpinner.height()&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(t){var e=this.options,i=V.ui.keyCode;switch(t.keyCode){case i.UP:return this._repeat(null,1,t),!0;case i.DOWN:return this._repeat(null,-1,t),!0;case i.PAGE_UP:return this._repeat(null,e.page,t),!0;case i.PAGE_DOWN:return this._repeat(null,-e.page,t),!0}return!1},_start:function(t){return!(!this.spinning&&!1===this._trigger("start",t))&&(this.counter||(this.counter=1),this.spinning=!0)},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&!1===this._trigger("spin",e,{value:i})||(this._value(i),this.counter++)},_increment:function(t){var e=this.options.incremental;return e?"function"==typeof e?e(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return t=null!==this.options.min?Math.max(t,this._precisionOf(this.options.min)):t},_precisionOf:function(t){var e=t.toString(),t=e.indexOf(".");return-1===t?0:e.length-t-1},_adjustValue:function(t){var e=this.options,i=null!==e.min?e.min:0,s=t-i;return t=i+Math.round(s/e.step)*e.step,t=parseFloat(t.toFixed(this._precision())),null!==e.max&&t>e.max?e.max:null!==e.min&&t<e.min?e.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){var i;if("culture"===t||"numberFormat"===t)return i=this._parse(this.element.val()),this.options[t]=e,void this.element.val(this._format(i));"max"!==t&&"min"!==t&&"step"!==t||"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(i=this.buttons.first().find(".ui-icon"),this._removeClass(i,null,this.options.icons.up),this._addClass(i,null,e.up),i=this.buttons.last().find(".ui-icon"),this._removeClass(i,null,this.options.icons.down),this._addClass(i,null,e.down)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable")},_setOptions:ht(function(t){this._super(t)}),_parse:function(t){return""===(t="string"==typeof t&&""!==t?window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t:t)||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null!==t&&t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&null!==(i=this._parse(t))&&(e||(i=this._adjustValue(i)),t=this._format(i)),this.element.val(t),this._refresh()},_destroy:function(){this.element.prop("disabled",!1).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:ht(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:ht(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:ht(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:ht(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){if(!arguments.length)return this._parse(this.element.val());ht(this._value).call(this,t)},widget:function(){return this.uiSpinner}}),!1!==V.uiBackCompat&&V.widget("ui.spinner",V.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}});var ct;V.ui.spinner;V.widget("ui.tabs",{version:"1.13.2",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:(ct=/#.*$/,function(t){var e=t.href.replace(ct,""),i=location.href.replace(ct,"");try{e=decodeURIComponent(e)}catch(t){}try{i=decodeURIComponent(i)}catch(t){}return 1<t.hash.length&&e===i}),_create:function(){var e=this,t=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,t.collapsible),this._processTabs(),t.active=this._initialActive(),Array.isArray(t.disabled)&&(t.disabled=V.uniqueSort(t.disabled.concat(V.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),!1!==this.options.active&&this.anchors.length?this.active=this._findActive(t.active):this.active=V(),this._refresh(),this.active.length&&this.load(t.active)},_initialActive:function(){var i=this.options.active,t=this.options.collapsible,s=location.hash.substring(1);return null===i&&(s&&this.tabs.each(function(t,e){if(V(e).attr("aria-controls")===s)return i=t,!1}),null!==(i=null===i?this.tabs.index(this.tabs.filter(".ui-tabs-active")):i)&&-1!==i||(i=!!this.tabs.length&&0)),!1!==i&&-1===(i=this.tabs.index(this.tabs.eq(i)))&&(i=!t&&0),i=!t&&!1===i&&this.anchors.length?0:i},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):V()}},_tabKeydown:function(t){var e=V(V.ui.safeActiveElement(this.document[0])).closest("li"),i=this.tabs.index(e),s=!0;if(!this._handlePageNav(t)){switch(t.keyCode){case V.ui.keyCode.RIGHT:case V.ui.keyCode.DOWN:i++;break;case V.ui.keyCode.UP:case V.ui.keyCode.LEFT:s=!1,i--;break;case V.ui.keyCode.END:i=this.anchors.length-1;break;case V.ui.keyCode.HOME:i=0;break;case V.ui.keyCode.SPACE:return t.preventDefault(),clearTimeout(this.activating),void this._activate(i);case V.ui.keyCode.ENTER:return t.preventDefault(),clearTimeout(this.activating),void this._activate(i!==this.options.active&&i);default:return}t.preventDefault(),clearTimeout(this.activating),i=this._focusNextTab(i,s),t.ctrlKey||t.metaKey||(e.attr("aria-selected","false"),this.tabs.eq(i).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",i)},this.delay))}},_panelKeydown:function(t){this._handlePageNav(t)||t.ctrlKey&&t.keyCode===V.ui.keyCode.UP&&(t.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(t){return t.altKey&&t.keyCode===V.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):t.altKey&&t.keyCode===V.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(t,e){var i=this.tabs.length-1;for(;-1!==V.inArray(t=(t=i<t?0:t)<0?i:t,this.options.disabled);)t=e?t+1:t-1;return t},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){"active"!==t?(this._super(t,e),"collapsible"===t&&(this._toggleClass("ui-tabs-collapsible",null,e),e||!1!==this.options.active||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e)):this._activate(e)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,e=this.tablist.children(":has(a[href])");t.disabled=V.map(e.filter(".ui-state-disabled"),function(t){return e.index(t)}),this._processTabs(),!1!==t.active&&this.anchors.length?this.active.length&&!V.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=V()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active):(t.active=!1,this.active=V()),this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._addClass(this.active,"ui-tabs-active","ui-state-active"),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var l=this,t=this.tabs,e=this.anchors,i=this.panels;this.tablist=this._getList().attr("role","tablist"),this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header"),this.tablist.on("mousedown"+this.eventNamespace,"> li",function(t){V(this).is(".ui-state-disabled")&&t.preventDefault()}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){V(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1}),this._addClass(this.tabs,"ui-tabs-tab","ui-state-default"),this.anchors=this.tabs.map(function(){return V("a",this)[0]}).attr({tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=V(),this.anchors.each(function(t,e){var i,s,n,o=V(e).uniqueId().attr("id"),a=V(e).closest("li"),r=a.attr("aria-controls");l._isLocal(e)?(n=(i=e.hash).substring(1),s=l.element.find(l._sanitizeSelector(i))):(n=a.attr("aria-controls")||V({}).uniqueId()[0].id,(s=l.element.find(i="#"+n)).length||(s=l._createPanel(n)).insertAfter(l.panels[t-1]||l.tablist),s.attr("aria-live","polite")),s.length&&(l.panels=l.panels.add(s)),r&&a.data("ui-tabs-aria-controls",r),a.attr({"aria-controls":n,"aria-labelledby":o}),s.attr("aria-labelledby",o)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),t&&(this._off(t.not(this.tabs)),this._off(e.not(this.anchors)),this._off(i.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(t){return V("<div>").attr("id",t).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(t){var e,i;for(Array.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1),i=0;e=this.tabs[i];i++)e=V(e),!0===t||-1!==V.inArray(i,t)?(e.attr("aria-disabled","true"),this._addClass(e,null,"ui-state-disabled")):(e.removeAttr("aria-disabled"),this._removeClass(e,null,"ui-state-disabled"));this.options.disabled=t,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!0===t)},_setupEvents:function(t){var i={};t&&V.each(t.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var i,e=this.element.parent();"fill"===t?(i=e.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var t=V(this),e=t.css("position");"absolute"!==e&&"fixed"!==e&&(i-=t.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=V(this).outerHeight(!0)}),this.panels.each(function(){V(this).height(Math.max(0,i-V(this).innerHeight()+V(this).height()))}).css("overflow","auto")):"auto"===t&&(i=0,this.panels.each(function(){i=Math.max(i,V(this).height("").height())}).height(i))},_eventHandler:function(t){var e=this.options,i=this.active,s=V(t.currentTarget).closest("li"),n=s[0]===i[0],o=n&&e.collapsible,a=o?V():this._getPanelForTab(s),r=i.length?this._getPanelForTab(i):V(),i={oldTab:i,oldPanel:r,newTab:o?V():s,newPanel:a};t.preventDefault(),s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||n&&!e.collapsible||!1===this._trigger("beforeActivate",t,i)||(e.active=!o&&this.tabs.index(s),this.active=n?V():s,this.xhr&&this.xhr.abort(),r.length||a.length||V.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&&this.load(this.tabs.index(s),t),this._toggle(t,i))},_toggle:function(t,e){var i=this,s=e.newPanel,n=e.oldPanel;function o(){i.running=!1,i._trigger("activate",t,e)}function a(){i._addClass(e.newTab.closest("li"),"ui-tabs-active","ui-state-active"),s.length&&i.options.show?i._show(s,i.options.show,o):(s.show(),o())}this.running=!0,n.length&&this.options.hide?this._hide(n,this.options.hide,function(){i._removeClass(e.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),a()}):(this._removeClass(e.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),n.hide(),a()),n.attr("aria-hidden","true"),e.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),s.length&&n.length?e.oldTab.attr("tabIndex",-1):s.length&&this.tabs.filter(function(){return 0===V(this).attr("tabIndex")}).attr("tabIndex",-1),s.attr("aria-hidden","false"),e.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(t){var t=this._findActive(t);t[0]!==this.active[0]&&(t=(t=!t.length?this.active:t).find(".ui-tabs-anchor")[0],this._eventHandler({target:t,currentTarget:t,preventDefault:V.noop}))},_findActive:function(t){return!1===t?V():this.tabs.eq(t)},_getIndex:function(t){return t="string"==typeof t?this.anchors.index(this.anchors.filter("[href$='"+V.escapeSelector(t)+"']")):t},_destroy:function(){this.xhr&&this.xhr.abort(),this.tablist.removeAttr("role").off(this.eventNamespace),this.anchors.removeAttr("role tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){V.data(this,"ui-tabs-destroy")?V(this).remove():V(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var t=V(this),e=t.data("ui-tabs-aria-controls");e?t.attr("aria-controls",e).removeData("ui-tabs-aria-controls"):t.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(i){var t=this.options.disabled;!1!==t&&(t=void 0!==i&&(i=this._getIndex(i),Array.isArray(t)?V.map(t,function(t){return t!==i?t:null}):V.map(this.tabs,function(t,e){return e!==i?e:null})),this._setOptionDisabled(t))},disable:function(t){var e=this.options.disabled;if(!0!==e){if(void 0===t)e=!0;else{if(t=this._getIndex(t),-1!==V.inArray(t,e))return;e=Array.isArray(e)?V.merge([t],e).sort():[t]}this._setOptionDisabled(e)}},load:function(t,s){t=this._getIndex(t);function n(t,e){"abort"===e&&o.panels.stop(!1,!0),o._removeClass(i,"ui-tabs-loading"),a.removeAttr("aria-busy"),t===o.xhr&&delete o.xhr}var o=this,i=this.tabs.eq(t),t=i.find(".ui-tabs-anchor"),a=this._getPanelForTab(i),r={tab:i,panel:a};this._isLocal(t[0])||(this.xhr=V.ajax(this._ajaxSettings(t,s,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(this._addClass(i,"ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,i){setTimeout(function(){a.html(t),o._trigger("load",s,r),n(i,e)},1)}).fail(function(t,e){setTimeout(function(){n(t,e)},1)})))},_ajaxSettings:function(t,i,s){var n=this;return{url:t.attr("href").replace(/#.*$/,""),beforeSend:function(t,e){return n._trigger("beforeLoad",i,V.extend({jqXHR:t,ajaxSettings:e},s))}}},_getPanelForTab:function(t){t=V(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+t))}}),!1!==V.uiBackCompat&&V.widget("ui.tabs",V.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}});V.ui.tabs;V.widget("ui.tooltip",{version:"1.13.2",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var t=V(this).attr("title");return V("<a>").text(t).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,track:!1,close:null,open:null},_addDescribedBy:function(t,e){var i=(t.attr("aria-describedby")||"").split(/\s+/);i.push(e),t.data("ui-tooltip-id",e).attr("aria-describedby",String.prototype.trim.call(i.join(" ")))},_removeDescribedBy:function(t){var e=t.data("ui-tooltip-id"),i=(t.attr("aria-describedby")||"").split(/\s+/),e=V.inArray(e,i);-1!==e&&i.splice(e,1),t.removeData("ui-tooltip-id"),(i=String.prototype.trim.call(i.join(" ")))?t.attr("aria-describedby",i):t.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=V("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this.disabledTitles=V([])},_setOption:function(t,e){var i=this;this._super(t,e),"content"===t&&V.each(this.tooltips,function(t,e){i._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var s=this;V.each(this.tooltips,function(t,e){var i=V.Event("blur");i.target=i.currentTarget=e.element[0],s.close(i,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var t=V(this);if(t.is("[title]"))return t.data("ui-tooltip-title",t.attr("title")).removeAttr("title")}))},_enable:function(){this.disabledTitles.each(function(){var t=V(this);t.data("ui-tooltip-title")&&t.attr("title",t.data("ui-tooltip-title"))}),this.disabledTitles=V([])},open:function(t){var i=this,e=V(t?t.target:this.element).closest(this.options.items);e.length&&!e.data("ui-tooltip-id")&&(e.attr("title")&&e.data("ui-tooltip-title",e.attr("title")),e.data("ui-tooltip-open",!0),t&&"mouseover"===t.type&&e.parents().each(function(){var t,e=V(this);e.data("ui-tooltip-open")&&((t=V.Event("blur")).target=t.currentTarget=this,i.close(t,!0)),e.attr("title")&&(e.uniqueId(),i.parents[this.id]={element:this,title:e.attr("title")},e.attr("title",""))}),this._registerCloseHandlers(t,e),this._updateContent(e,t))},_updateContent:function(e,i){var t=this.options.content,s=this,n=i?i.type:null;if("string"==typeof t||t.nodeType||t.jquery)return this._open(i,e,t);(t=t.call(e[0],function(t){s._delay(function(){e.data("ui-tooltip-open")&&(i&&(i.type=n),this._open(i,e,t))})}))&&this._open(i,e,t)},_open:function(t,e,i){var s,n,o,a=V.extend({},this.options.position);function r(t){a.of=t,n.is(":hidden")||n.position(a)}i&&((s=this._find(e))?s.tooltip.find(".ui-tooltip-content").html(i):(e.is("[title]")&&(t&&"mouseover"===t.type?e.attr("title",""):e.removeAttr("title")),s=this._tooltip(e),n=s.tooltip,this._addDescribedBy(e,n.attr("id")),n.find(".ui-tooltip-content").html(i),this.liveRegion.children().hide(),(i=V("<div>").html(n.find(".ui-tooltip-content").html())).removeAttr("name").find("[name]").removeAttr("name"),i.removeAttr("id").find("[id]").removeAttr("id"),i.appendTo(this.liveRegion),this.options.track&&t&&/^mouse/.test(t.type)?(this._on(this.document,{mousemove:r}),r(t)):n.position(V.extend({of:e},this.options.position)),n.hide(),this._show(n,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(o=this.delayedShow=setInterval(function(){n.is(":visible")&&(r(a.of),clearInterval(o))},13)),this._trigger("open",t,{tooltip:n})))},_registerCloseHandlers:function(t,e){var i={keyup:function(t){t.keyCode===V.ui.keyCode.ESCAPE&&((t=V.Event(t)).currentTarget=e[0],this.close(t,!0))}};e[0]!==this.element[0]&&(i.remove=function(){var t=this._find(e);t&&this._removeTooltip(t.tooltip)}),t&&"mouseover"!==t.type||(i.mouseleave="close"),t&&"focusin"!==t.type||(i.focusout="close"),this._on(!0,e,i)},close:function(t){var e,i=this,s=V(t?t.currentTarget:this.element),n=this._find(s);n?(e=n.tooltip,n.closing||(clearInterval(this.delayedShow),s.data("ui-tooltip-title")&&!s.attr("title")&&s.attr("title",s.data("ui-tooltip-title")),this._removeDescribedBy(s),n.hiding=!0,e.stop(!0),this._hide(e,this.options.hide,function(){i._removeTooltip(V(this))}),s.removeData("ui-tooltip-open"),this._off(s,"mouseleave focusout keyup"),s[0]!==this.element[0]&&this._off(s,"remove"),this._off(this.document,"mousemove"),t&&"mouseleave"===t.type&&V.each(this.parents,function(t,e){V(e.element).attr("title",e.title),delete i.parents[t]}),n.closing=!0,this._trigger("close",t,{tooltip:e}),n.hiding||(n.closing=!1))):s.removeData("ui-tooltip-open")},_tooltip:function(t){var e=V("<div>").attr("role","tooltip"),i=V("<div>").appendTo(e),s=e.uniqueId().attr("id");return this._addClass(i,"ui-tooltip-content"),this._addClass(e,"ui-tooltip","ui-widget ui-widget-content"),e.appendTo(this._appendTo(t)),this.tooltips[s]={element:t,tooltip:e}},_find:function(t){t=t.data("ui-tooltip-id");return t?this.tooltips[t]:null},_removeTooltip:function(t){clearInterval(this.delayedShow),t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){t=t.closest(".ui-front, dialog");return t=!t.length?this.document[0].body:t},_destroy:function(){var s=this;V.each(this.tooltips,function(t,e){var i=V.Event("blur"),e=e.element;i.target=i.currentTarget=e[0],s.close(i,!0),V("#"+t).remove(),e.data("ui-tooltip-title")&&(e.attr("title")||e.attr("title",e.data("ui-tooltip-title")),e.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),!1!==V.uiBackCompat&&V.widget("ui.tooltip",V.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}});V.ui.tooltip});;/*
 * jQuery UI Autocomplete HTML Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 */
(function ($) {
  var proto = $.ui.autocomplete.prototype,
    initSource = proto._initSource;
  function filter(array, term) {
    var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
    return $.grep(array, function (value) {
      return matcher.test($("<div>").html(value.label || value.value || value).text());
    });
  }
  $.extend(proto, {
    _initSource: function () {
      if (this.options.html && $.isArray(this.options.source)) {
        this.source = function (request, response) {
          response(filter(this.options.source, request.term));
        };
      } else {
        initSource.call(this);
      }
    },
    _renderItem: function (ul, item) {
      return $("<li></li>")
        .data("item.autocomplete", item)
        .append($("<a></a>")[this.options.html ? "html" : "text"](item.label))
        .appendTo(ul);
    }
  });
})(jQuery);
;/* 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);;!function (t) { t.extend(t.fn, { validate: function (e) { if (!this.length) return void (e && e.debug && window.console && console.warn("Nothing selected, can't validate, returning nothing.")); var i = t.data(this[0], "validator"); return i ? i : (this.attr("novalidate", "novalidate"), i = new t.validator(e, this[0]), t.data(this[0], "validator", i), i.settings.onsubmit && (this.validateDelegate(":submit", "click", function (e) { i.settings.submitHandler && (i.submitButton = e.target), t(e.target).hasClass("cancel") && (i.cancelSubmit = !0), void 0 !== t(e.target).attr("formnovalidate") && (i.cancelSubmit = !0) }), this.submit(function (e) { function s() { var s; return i.settings.submitHandler ? (i.submitButton && (s = t("<input type='hidden'/>").attr("name", i.submitButton.name).val(t(i.submitButton).val()).appendTo(i.currentForm)), i.settings.submitHandler.call(i, i.currentForm, e), i.submitButton && s.remove(), !1) : !0 } return i.settings.debug && e.preventDefault(), i.cancelSubmit ? (i.cancelSubmit = !1, s()) : i.form() ? i.pendingRequest ? (i.formSubmitted = !0, !1) : s() : (i.focusInvalid(), !1) })), i) }, valid: function () { var t, e; return $(this[0]).is("form") ? t = this.validate().form() : (t = !0, e = $(this[0].form).validate(), this.each(function () { t = e.element(this) && t })), t }, removeAttrs: function (e) { var i = {}, s = this; return t.each(e.split(/\s/), function (t, e) { i[e] = s.attr(e), s.removeAttr(e) }), i }, rules: function (e, i) { var s = this[0]; if (e) { var r = t.data(s.form, "validator").settings, n = r.rules, a = t.validator.staticRules(s); switch (e) { case "add": t.extend(a, t.validator.normalizeRule(i)), delete a.messages, n[s.name] = a, i.messages && (r.messages[s.name] = t.extend(r.messages[s.name], i.messages)); break; case "remove": if (!i) return delete n[s.name], a; var u = {}; return t.each(i.split(/\s/), function (t, e) { u[e] = a[e], delete a[e] }), u } } var o = t.validator.normalizeRules(t.extend({}, t.validator.classRules(s), t.validator.attributeRules(s), t.validator.dataRules(s), t.validator.staticRules(s)), s); if (o.required) { var l = o.required; delete o.required, o = t.extend({ required: l }, o) } return o } }), t.extend(t.expr[":"], { blank: function (e) { return !t.trim("" + t(e).val()) }, filled: function (e) { return !!t.trim("" + t(e).val()) }, unchecked: function (e) { return !t(e).prop("checked") } }), t.validator = function (e, i) { this.settings = t.extend(!0, {}, t.validator.defaults, e), this.currentForm = i, this.init() }, t.validator.format = function (e, i) { return 1 === arguments.length ? function () { var i = t.makeArray(arguments); return i.unshift(e), t.validator.format.apply(this, i) } : (arguments.length > 2 && i.constructor !== Array && (i = t.makeArray(arguments).slice(1)), i.constructor !== Array && (i = [i]), t.each(i, function (t, i) { e = e.replace(RegExp("\\{" + t + "\\}", "g"), function () { return i }) }), e) }, t.extend(t.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", validClass: "valid", errorElement: "label", focusInvalid: !0, errorContainer: t([]), errorLabelContainer: t([]), onsubmit: !0, ignore: ":hidden", ignoreTitle: !1, onfocusin: function (t) { this.lastActive = t, this.settings.focusCleanup && !this.blockFocusCleanup && (this.settings.unhighlight && this.settings.unhighlight.call(this, t, this.settings.errorClass, this.settings.validClass), this.addWrapper(this.errorsFor(t)).hide()) }, onfocusout: function (t) { this.checkable(t) || !(t.name in this.submitted) && this.optional(t) || this.element(t) }, onkeyup: function (t, e) { (9 !== e.which || "" !== this.elementValue(t)) && (t.name in this.submitted || t === this.lastElement) && this.element(t) }, onclick: function (t) { t.name in this.submitted ? this.element(t) : t.parentNode.name in this.submitted && this.element(t.parentNode) }, highlight: function (e, i, s) { "radio" === e.type ? this.findByName(e.name).addClass(i).removeClass(s) : t(e).addClass(i).removeClass(s) }, unhighlight: function (e, i, s) { "radio" === e.type ? this.findByName(e.name).removeClass(i).addClass(s) : t(e).removeClass(i).addClass(s) } }, setDefaults: function (e) { t.extend(t.validator.defaults, e) }, 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.", creditcard: "Please enter a valid credit card number.", equalTo: "Please enter the same value again.", maxlength: t.validator.format("Please enter no more than {0} characters."), minlength: t.validator.format("Please enter at least {0} characters."), rangelength: t.validator.format("Please enter a value between {0} and {1} characters long."), range: t.validator.format("Please enter a value between {0} and {1}."), max: t.validator.format("Please enter a value less than or equal to {0}."), min: t.validator.format("Please enter a value greater than or equal to {0}.") }, autoCreateRanges: !1, prototype: { init: function () { function e(e) { var i = t.data(this[0].form, "validator"), s = "on" + e.type.replace(/^validate/, ""); i.settings[s] && i.settings[s].call(i, this[0], e) } this.labelContainer = t(this.settings.errorLabelContainer), this.errorContext = this.labelContainer.length && this.labelContainer || t(this.currentForm), this.containers = t(this.settings.errorContainer).add(this.settings.errorLabelContainer), this.submitted = {}, this.valueCache = {}, this.pendingRequest = 0, this.pending = {}, this.invalid = {}, this.reset(); var i = this.groups = {}; t.each(this.settings.groups, function (e, s) { "string" == typeof s && (s = s.split(/\s/)), t.each(s, function (t, s) { i[s] = e }) }); var s = this.settings.rules; t.each(s, function (e, i) { s[e] = t.validator.normalizeRule(i) }), t(this.currentForm).validateDelegate(":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'] ", "focusin focusout keyup", e).validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", e), this.settings.invalidHandler && t(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler) }, form: function () { return this.checkForm(), t.extend(this.submitted, this.errorMap), this.invalid = t.extend({}, this.errorMap), this.valid() || t(this.currentForm).triggerHandler("invalid-form", [this]), this.showErrors(), this.valid() }, checkForm: function () { this.prepareForm(); for (var t = 0, e = this.currentElements = this.elements() ; e[t]; t++) this.check(e[t]); return this.valid() }, element: function (e) { e = this.validationTargetFor(this.clean(e)), this.lastElement = e, this.prepareElement(e), this.currentElements = t(e); var i = this.check(e) !== !1; return i ? delete this.invalid[e.name] : this.invalid[e.name] = !0, this.numberOfInvalids() || (this.toHide = this.toHide.add(this.containers)), this.showErrors(), i }, showErrors: function (e) { if (e) { t.extend(this.errorMap, e), this.errorList = []; for (var i in e) this.errorList.push({ message: e[i], element: this.findByName(i)[0] }); this.successList = t.grep(this.successList, function (t) { return !(t.name in e) }) } this.settings.showErrors ? this.settings.showErrors.call(this, this.errorMap, this.errorList) : this.defaultShowErrors() }, resetForm: function () { t.fn.resetForm && t(this.currentForm).resetForm(), this.submitted = {}, this.lastElement = null, this.prepareForm(), this.hideErrors(), this.elements().removeClass(this.settings.errorClass).removeData("previousValue") }, numberOfInvalids: function () { return this.objectLength(this.invalid) }, objectLength: function (t) { var e = 0; for (var i in t) e++; return e }, hideErrors: function () { this.addWrapper(this.toHide).hide() }, valid: function () { return 0 === this.size() }, size: function () { return this.errorList.length }, focusInvalid: function () { if (this.settings.focusInvalid) try { t(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus().trigger("focusin") } catch (e) { } }, findLastActive: function () { var e = this.lastActive; return e && 1 === t.grep(this.errorList, function (t) { return t.element.name === e.name }).length && e }, elements: function () { var e = this, i = {}; return t(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function () { return !this.name && e.settings.debug && window.console && console.error("%o has no name assigned", this), this.name in i || !e.objectLength(t(this).rules()) ? !1 : (i[this.name] = !0, !0) }) }, clean: function (e) { return t(e)[0] }, errors: function () { var e = this.settings.errorClass.replace(" ", "."); return t(this.settings.errorElement + "." + e, this.errorContext) }, reset: function () { this.successList = [], this.errorList = [], this.errorMap = {}, this.toShow = t([]), this.toHide = t([]), this.currentElements = t([]) }, prepareForm: function () { this.reset(), this.toHide = this.errors().add(this.containers) }, prepareElement: function (t) { this.reset(), this.toHide = this.errorsFor(t) }, elementValue: function (e) { var i = t(e).attr("type"), s = t(e).val(); return "radio" === i || "checkbox" === i ? t("input[name='" + t(e).attr("name") + "']:checked").val() : "string" == typeof s ? s.replace(/\r/g, "") : s }, check: function (e) { e = this.validationTargetFor(this.clean(e)); var i, s = t(e).rules(), r = !1, n = this.elementValue(e); for (var a in s) { var u = { method: a, parameters: s[a] }; try { if (i = t.validator.methods[a].call(this, n, e, u.parameters), "dependency-mismatch" === i) { r = !0; continue } if (r = !1, "pending" === i) return void (this.toHide = this.toHide.not(this.errorsFor(e))); if (!i) return this.formatAndAdd(e, u), !1 } catch (o) { throw this.settings.debug && window.console && console.log("Exception occurred when checking element " + e.id + ", check the '" + u.method + "' method.", o), o } } return r ? void 0 : (this.objectLength(s) && this.successList.push(e), !0) }, customDataMessage: function (e, i) { return t(e).data("msg-" + i.toLowerCase()) || e.attributes && t(e).attr("data-msg-" + i.toLowerCase()) }, customMessage: function (t, e) { var i = this.settings.messages[t]; return i && (i.constructor === String ? i : i[e]) }, findDefined: function () { for (var t = 0; arguments.length > t; t++) if (void 0 !== arguments[t]) return arguments[t]; return void 0 }, defaultMessage: function (e, i) { return this.findDefined(this.customMessage(e.name, i), this.customDataMessage(e, i), !this.settings.ignoreTitle && e.title || void 0, t.validator.messages[i], "<strong>Warning: No message defined for " + e.name + "</strong>") }, formatAndAdd: function (e, i) { var s = this.defaultMessage(e, i.method), r = /\$?\{(\d+)\}/g; "function" == typeof s ? s = s.call(this, i.parameters, e) : r.test(s) && (s = t.validator.format(s.replace(r, "{$1}"), i.parameters)), this.errorList.push({ message: s, element: e }), this.errorMap[e.name] = s, this.submitted[e.name] = s }, addWrapper: function (t) { return this.settings.wrapper && (t = t.add(t.parent(this.settings.wrapper))), t }, defaultShowErrors: function () { var t, e; for (t = 0; this.errorList[t]; t++) { var i = this.errorList[t]; this.settings.highlight && this.settings.highlight.call(this, i.element, this.settings.errorClass, this.settings.validClass), this.showLabel(i.element, i.message) } if (this.errorList.length && (this.toShow = this.toShow.add(this.containers)), this.settings.success) for (t = 0; this.successList[t]; t++) this.showLabel(this.successList[t]); if (this.settings.unhighlight) for (t = 0, e = this.validElements() ; e[t]; t++) this.settings.unhighlight.call(this, e[t], 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 t(this.errorList).map(function () { return this.element }) }, showLabel: function (e, i) { var s = this.errorsFor(e); s.length ? (s.removeClass(this.settings.validClass).addClass(this.settings.errorClass), s.html(i)) : (s = t("<" + this.settings.errorElement + ">").attr("for", this.idOrName(e)).addClass(this.settings.errorClass).html(i || ""), this.settings.wrapper && (s = s.hide().show().wrap("<" + this.settings.wrapper + "/>").parent()), this.labelContainer.append(s).length || (this.settings.errorPlacement ? this.settings.errorPlacement(s, t(e)) : s.insertAfter(e))), !i && this.settings.success && (s.text(""), "string" == typeof this.settings.success ? s.addClass(this.settings.success) : this.settings.success(s, e)), this.toShow = this.toShow.add(s) }, errorsFor: function (e) { var i = this.idOrName(e); return this.errors().filter(function () { return t(this).attr("for") === i }) }, idOrName: function (t) { return this.groups[t.name] || (this.checkable(t) ? t.name : t.id || t.name) }, validationTargetFor: function (t) { return this.checkable(t) && (t = this.findByName(t.name).not(this.settings.ignore)[0]), t }, checkable: function (t) { return /radio|checkbox/i.test(t.type) }, findByName: function (e) { return t(this.currentForm).find("[name='" + e + "']") }, getLength: function (e, i) { switch (i.nodeName.toLowerCase()) { case "select": return t("option:selected", i).length; case "input": if (this.checkable(i)) return this.findByName(i.name).filter(":checked").length } return e.length }, depend: function (t, e) { return this.dependTypes[typeof t] ? this.dependTypes[typeof t](t, e) : !0 }, dependTypes: { "boolean": function (t) { return t }, string: function (e, i) { return !!t(e, i.form).length }, "function": function (t, e) { return t(e) } }, optional: function (e) { var i = this.elementValue(e); return !t.validator.methods.required.call(this, i, e) && "dependency-mismatch" }, startRequest: function (t) { this.pending[t.name] || (this.pendingRequest++, this.pending[t.name] = !0) }, stopRequest: function (e, i) { this.pendingRequest--, 0 > this.pendingRequest && (this.pendingRequest = 0), delete this.pending[e.name], i && 0 === this.pendingRequest && this.formSubmitted && this.form() ? (t(this.currentForm).submit(), this.formSubmitted = !1) : !i && 0 === this.pendingRequest && this.formSubmitted && (t(this.currentForm).triggerHandler("invalid-form", [this]), this.formSubmitted = !1) }, previousValue: function (e) { return t.data(e, "previousValue") || t.data(e, "previousValue", { old: null, valid: !0, message: this.defaultMessage(e, "remote") }) } }, 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 (e, i) { e.constructor === String ? this.classRuleSettings[e] = i : t.extend(this.classRuleSettings, e) }, classRules: function (e) { var i = {}, s = t(e).attr("class"); return s && t.each(s.split(" "), function () { this in t.validator.classRuleSettings && t.extend(i, t.validator.classRuleSettings[this]) }), i }, attributeRules: function (e) { var i = {}, s = t(e), r = s[0].getAttribute("type"); for (var n in t.validator.methods) { var a; "required" === n ? (a = s.get(0).getAttribute(n), "" === a && (a = !0), a = !!a) : a = s.attr(n), /min|max/.test(n) && (null === r || /number|range|text/.test(r)) && (a = Number(a)), a ? i[n] = a : r === n && "range" !== r && (i[n] = !0) } return i.maxlength && /-1|2147483647|524288/.test(i.maxlength) && delete i.maxlength, i }, dataRules: function (e) { var i, s, r = {}, n = t(e); for (i in t.validator.methods) s = n.data("rule-" + i.toLowerCase()), void 0 !== s && (r[i] = s); return r }, staticRules: function (e) { var i = {}, s = t.data(e.form, "validator"); return s.settings.rules && (i = t.validator.normalizeRule(s.settings.rules[e.name]) || {}), i }, normalizeRules: function (e, i) { return t.each(e, function (s, r) { if (r === !1) return void delete e[s]; if (r.param || r.depends) { var n = !0; switch (typeof r.depends) { case "string": n = !!t(r.depends, i.form).length; break; case "function": n = r.depends.call(i, i) } n ? e[s] = void 0 !== r.param ? r.param : !0 : delete e[s] } }), t.each(e, function (s, r) { e[s] = t.isFunction(r) ? r(i) : r }), t.each(["minlength", "maxlength"], function () { e[this] && (e[this] = Number(e[this])) }), t.each(["rangelength", "range"], function () { var i; e[this] && (t.isArray(e[this]) ? e[this] = [Number(e[this][0]), Number(e[this][1])] : "string" == typeof e[this] && (i = e[this].split(/[\s,]+/), e[this] = [Number(i[0]), Number(i[1])])) }), t.validator.autoCreateRanges && (e.min && e.max && (e.range = [e.min, e.max], delete e.min, delete e.max), e.minlength && e.maxlength && (e.rangelength = [e.minlength, e.maxlength], delete e.minlength, delete e.maxlength)), e }, normalizeRule: function (e) { if ("string" == typeof e) { var i = {}; t.each(e.split(/\s/), function () { i[this] = !0 }), e = i } return e }, addMethod: function (e, i, s) { t.validator.methods[e] = i, t.validator.messages[e] = void 0 !== s ? s : t.validator.messages[e], 3 > i.length && t.validator.addClassRules(e, t.validator.normalizeRule(e)) }, methods: { required: function (e, i, s) { if (!this.depend(s, i)) return "dependency-mismatch"; if ("select" === i.nodeName.toLowerCase()) { var r = t(i).val(); return r && r.length > 0 } return this.checkable(i) ? this.getLength(e, i) > 0 : t.trim(e).length > 0 }, email: function (t, e) { return this.optional(e) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(t) }, url: function (t, e) { return this.optional(e) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(t) }, date: function (t, e) { return this.optional(e) || !/Invalid|NaN/.test("" + new Date(t)) }, dateISO: function (t, e) { return this.optional(e) || /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(t) }, number: function (t, e) { return this.optional(e) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(t) }, digits: function (t, e) { return this.optional(e) || /^\d+$/.test(t) }, creditcard: function (t, e) { if (this.optional(e)) return "dependency-mismatch"; if (/[^0-9 \-]+/.test(t)) return !1; var i = 0, s = 0, r = !1; t = t.replace(/\D/g, ""); for (var n = t.length - 1; n >= 0; n--) { var a = t.charAt(n); s = parseInt(a, 10), r && (s *= 2) > 9 && (s -= 9), i += s, r = !r } return 0 === i % 10 }, minlength: function (e, i, s) { var r = t.isArray(e) ? e.length : this.getLength(t.trim(e), i); return this.optional(i) || r >= s }, maxlength: function (e, i, s) { var r = t.isArray(e) ? e.length : this.getLength(t.trim(e), i); return this.optional(i) || s >= r }, rangelength: function (e, i, s) { var r = t.isArray(e) ? e.length : this.getLength(t.trim(e), i); return this.optional(i) || r >= s[0] && s[1] >= r }, min: function (t, e, i) { return this.optional(e) || t >= i }, max: function (t, e, i) { return this.optional(e) || i >= t }, range: function (t, e, i) { return this.optional(e) || t >= i[0] && i[1] >= t }, equalTo: function (e, i, s) { var r = t(s); return this.settings.onfocusout && r.unbind(".validate-equalTo").bind("blur.validate-equalTo", function () { t(i).valid() }), e === r.val() }, remote: function (e, i, s) { if (this.optional(i)) return "dependency-mismatch"; var r = this.previousValue(i); if (this.settings.messages[i.name] || (this.settings.messages[i.name] = {}), r.originalMessage = this.settings.messages[i.name].remote, this.settings.messages[i.name].remote = r.message, s = "string" == typeof s && { url: s } || s, r.old === e) return r.valid; r.old = e; var n = this; this.startRequest(i); var a = {}; return a[i.name] = e, t.ajax(t.extend(!0, { url: s, mode: "abort", port: "validate" + i.name, dataType: "json", data: a, success: function (s) { n.settings.messages[i.name].remote = r.originalMessage; var a = s === !0 || "true" === s; if (a) { var u = n.formSubmitted; n.prepareElement(i), n.formSubmitted = u, n.successList.push(i), delete n.invalid[i.name], n.showErrors() } else { var o = {}, l = s || n.defaultMessage(i, "remote"); o[i.name] = r.message = t.isFunction(l) ? l(e) : l, n.invalid[i.name] = !0, n.showErrors(o) } r.valid = a, n.stopRequest(i, a) } }, s)), "pending" } } }), t.format = t.validator.format }(jQuery), function (t) { var e = {}; if (t.ajaxPrefilter) t.ajaxPrefilter(function (t, i, s) { var r = t.port; "abort" === t.mode && (e[r] && e[r].abort(), e[r] = s) }); else { var i = t.ajax; t.ajax = function (s) { var r = ("mode" in s ? s : t.ajaxSettings).mode, n = ("port" in s ? s : t.ajaxSettings).port; return "abort" === r ? (e[n] && e[n].abort(), e[n] = i.apply(this, arguments), e[n]) : i.apply(this, arguments) } } }(jQuery), function (t) { t.extend(t.fn, { validateDelegate: function (e, i, s) { return this.bind(i, function (i) { var r = t(i.target); return r.is(e) ? s.apply(r, arguments) : void 0 }) } }) }(jQuery);;/* 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?a.parseJSON(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?a.parseJSON(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);b.data("validator").resetForm();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(){return a(b.form).find(":input").filter("[name='"+f(c)+"']").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);;
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.5",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.5",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.5",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.5",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.5",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),
d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);;function registerNS(ns) {
    var nsParts = ns.split(".");
    var root = window;

    for (var i = 0; i < nsParts.length; i++) {
        if (typeof root[nsParts[i]] == "undefined")
            root[nsParts[i]] = new Object();

        root = root[nsParts[i]];
    }
}

/*
 * Adds onEnter function to jQuery.
 * Usage:
 * $('input').onEnter(function () {
 *      // some codemin
 * });
 */
(function ($) {
    $.fn.onEnter = function (func) {
        this.bind('keypress', function (e) {
            if (e.keyCode == 13) func.apply(this, [e]);
        });
        return this;
    };
})(jQuery);

function scrollToTop() {
    $("html, body").animate({ scrollTop: 0 }, "slow");
}

stringToBoolean = function (string) {
    if (string === undefined)
        return false;

    switch (string.toLowerCase()) {
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
}

registerNS("String");
String.Format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }

    return s;
}

registerNS("Globals");
Globals.LogErrors = true;

registerNS("API");
API.LocalBaseUrl = "/api/ccc";;var enableDebug = true;
var toggleMessage, toggleTitle, RefreshLocationOndelete = false;

function _debug(s) {
    if (enableDebug) {
        if (typeof console === "undefined") {
            //console = { log: function(s){ alert(s); } }
        } else {
            //console.log(s);
        }
    }
}

// In-window scrolling, uses jQuery
function scrollToTop(speed, selector) {
    if (!speed) { speed = 300; }

    if (!selector) { selector = "body"; }

    $("html, body").animate({ scrollTop: $(selector).offset().top }, speed);
}


// jQuery plugin for disabled attribute on element
(function ($) {
    $.fn.toggleDisabled = function () {
        return this.each(function () {
            var $this = $(this);
            if ($this.attr('disabled')) {
                $this.removeAttr('disabled');
            } else {
                $this.attr('disabled', 'disabled');
            }
        });
    };
})(jQuery);

function Removetildslashfromstring(str, char) {
    var notildslash = "";
    var newstr = str.split(char);
    for (var i = 0; i < newstr.length; i++) {
        notildslash += newstr[i];
    }
    return notildslash;
}

function BindDeleteConfirmDialog(title, message, deleteUrl) {
    this.ShowPopUp(title, message, deleteUrl);
    return false;
}

function ShowPopUp(title, message, url) {
    if ($("BODY").find("div#popup_container").length == 0) {
        this.CreatePopUp(title);
    }

    $("#popup_title").html(title);
    if (toggleMessage === undefined || toggleMessage === '') {
        $("#popup_message").html(message);
    }
    else {
        $("#popup_message").html(toggleMessage);
    }

    $("#popup_container").dialog({
        resizable: true,
        title: title,
        modal: true,
        stack: true,
        width: 400,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
                Api.deleteRecordById(url, function (response) {
                    var type = "error";
                    if (response.sucess) {
                        type = "success";
                        if (parseInt($("#grid tbody tr").length) === 1) {
                            $("#pagerTxt").val(parseInt($("#pagerTxt").val()) - 1);
                        }
                        if (RefreshLocationOndelete)
                            window.location.reload();
                        else
                            WebgridPagerHelper.UrlHandler();
                    }
                    this.DisplayNotificationMessagesHelper(response.message, type, response.isFadeOut, 5000);
                });
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });
}

function CreatePopUp(title) {
    var popup = '<div id="popup_container" class="ConfirmPopup" style="display:none;">' +
                    '<div class="PopupHeder ClearFix">' +
                    '</div>' +
                    '<div id="popup_content" class="PopupContent ClearFix">' +
                      '<div id="popup_message"></div>' +
                    '</div>' +
        '</div>';
    $("BODY").append(popup);
}

function BlockHtmlTagForTextBox() {
    /* validated all text box in project*/
    $(':input').not('.AllowHtml').on("paste keypress change", function (e) {
        if ($(this).val().indexOf("~") != -1) {
            var _inputValue = Removetildslashfromstring($(this).val(), "~");
            $(this).val(_inputValue);
        }
        if ($(this).val().indexOf("<") != -1) {
            var _inputValue = Removetildslashfromstring($(this).val(), "<");
            $(this).val(_inputValue);
        }
        if ($(this).val().indexOf(">") != -1) {
            var _inputValue = Removetildslashfromstring($(this).val(), ">");
            $(this).val(_inputValue);
        }
        /*new validation*/
        var key = [e.keyCode || e.which];
        if (key[0] != undefined) {
            var keychar = String.fromCharCode([e.keyCode || e.which]).toLowerCase();
            if ((key == null) || (key == 0) || (key == 126) || (key == 60) || (key == 62)) {
                return false;
            }
        }
    });

    /* validated all text box in project*/
    $(':input').not('.AllowHtml').on("paste", function (e) {
        if ($(this).attr('data-datype') === "Int32" || $(this).attr('data-datype') === "Decimal") {
            return false;
        }
    });

    $(":input").not('.AllowHtml').on("keypress", function (e) {
        if (e.which === 32 && !this.value.length)
            e.preventDefault();
    });
}

function DisplayNotificationMessagesHelper(message, type, isFadeOut, fadeOutMilliSeconds) {
    $("#SuccessMessage").html("");
    $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + message + '</div>');
}

/*code for Overlay*/
function overlayforwaitnone() { $("#backgroundddivWait").hide(); } function overlayforwaitblock() { $("#backgroundddivWait").show(); }
/*code for Overlay*/

$(document).ready(function () { BlockHtmlTagForTextBox(); overlayforwaitnone(); });

$(".quick-view-popup .zf-close").on("click", function () {
    $(".modal-backdrop").hide()
},
$("#close-quick-view-popup-ipad").on("click", function () {
    var ipad = navigator.userAgent.match(/iPad/i) != null;
    if (ipad) {
        $('body').css('overflow', 'auto');
        $('body').css('position', 'relative');
    }
}));;
var menuUsed = false;
var global = {
  // Instant method runs inline when this script loads
  instant: function () {
    _debug("global.instant()");

    let loadingDelay = 3500;

    if (location.pathname.includes('/checkout/Payment')) {
      loadingDelay = 1;
    }

    global.waitForElement('#gRecaptchaContainer').then(() => {
      global.loadGoogleRecaptcha(loadingDelay)
        .then(global.loadSignupFormWidget)
        .catch((err) => { console.error(err); });
    }).catch((err) => { console.error(err); });
  },
  executeFunctionByName: function (functionName, context /*, args */) {
    try {
      var args = [].slice.call(arguments).splice(2);
      var namespaces = functionName.split(".");
      var func = namespaces.pop();
      for (var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
      }
      return context[func].apply(this, args);
    }
    catch (ex) {
      _debug("Invalid:" + functionName)
    }
  },

  // Onready method runs when document is loaded and ready
  onready: function () {
    global.bind.init();

    // Set the controller and action names
    var modules = $("body").data("controller").split(".");
    var action = $("body").data("view");
    // Loads modules based on controller and view
    // If init() methods are present, they will be run on load
    modules.forEach(function (module) {
      if (module !== 'undefined') {
        var functionName = module + ".init";
        global.executeFunctionByName(functionName, window, arguments);
      }
    });

    // Display any alert messages that were stored
    global.local.displayAlertMessage();

    // Lazy load async images
    global.local.lazyLoadImages();

    global.local.cartCount();

    global.local.searchPageRequest();

    // add delay behavior to menu hover 
    //global.local.menuHover();

  },

  loadSignupFormWidget: function () {
    window._ctct_m = "d2a98f7d1556096ee2913e1782870844";

    const link = document.createElement('link');

    link.rel = 'preconnect';
    link.href = 'https://static.ctctcdn.com';

    document.head.appendChild(link);

    const createSignupFormWidget = () => {
      const script = document.createElement('script');

      script.id = 'signupScript';
      script.src = '//static.ctctcdn.com/js/signup-form-widget/current/signup-form-widget.min.js';
      script.defer = true;
  
      document.head.appendChild(script);  
    };

    if (document.readyState !== 'loading') {
      createSignupFormWidget();

      return;
    }

    window.addEventListener('load', createSignupFormWidget);
  },
  
  loadGoogleRecaptcha: function (delay) {
    const action = (resolve, reject) => {

      const script = document.createElement('script');

      script.async = true;
      script.src = 'https://www.google.com/recaptcha/api.js';

      script.addEventListener('load', resolve);
      script.addEventListener('error', reject);
  
      const loadGR = () => {
          document.head.appendChild(script);
      };
  
      window.requestIdleCallback(loadGR, { timeout: delay });  
    };

    return new window.Promise(action);
  },

  waitForElement: function (selector, target, timeout) {
    const action = (resolve, reject) => {
      const element = document.querySelector(selector);
      let timeoutId = null;
      let stopChecking = false;

      if (element) {
        resolve(element);
        return;
      }

      const stopCheckingForElement = () => {
        stopChecking = true;
        window.clearTimeout(timeoutId);
      };

      timeoutId = window.setTimeout(stopCheckingForElement, timeout);

      const processMutations = (mutations, _observer) => {
        if (stopChecking) {
          _observer.disconnect();
          resolve(null);
          return;
        }

        const HtmlElement = document.querySelector(selector);

        if (HtmlElement === null) {
          return;
        }

        stopCheckingForElement();
        _observer.disconnect();
        resolve(HtmlElement);
      };

      const observer = new MutationObserver(processMutations);

      const observerOptions = {
        childList: true,
        subtree: true
      };

      observer.observe(document.documentElement, observerOptions);
    };

    return new Promise(action);
  },

  // LOCAL METHODS	
  local: {
    loadPowerReviewsStatus: 'unavailable',
    loadPowerReviewsPromise: undefined,
    loadPowerReviews: () => {
      const createScript = (resolve, reject) => {
        if (typeof window.POWERREVIEWS === 'object') {
          resolve();
          return;
        }

        if (global.local.loadPowerReviewsStatus === 'loading') {
          return;
        }

        global.local.loadPowerReviewsStatus = 'loading';

        const script = document.createElement('script');

        script.async = true;
        script.src = 'https://ui.powerreviews.com/stable/4.1/ui.js';

        script.addEventListener('load', resolve);
        script.addEventListener('error', reject);

        const loadPowerReviews = () => {
          document.head.appendChild(script);
        };

        window.setTimeout(loadPowerReviews, 1000);
      };

      if (typeof global.local.loadPowerReviewsPromise === 'undefined') {
        global.local.loadPowerReviewsPromise = new Promise(createScript);
      }

      return global.local.loadPowerReviewsPromise;
    },

    cartCount: function () {
      _debug("local.cartCount()");

      Api.getCartCount(function (response) {
        var count = 0;

        if (parseInt(response) > 0) {
          count = parseInt(response);
        }

        $(".cartcount").html(count);
        $(".cartcount").css({ "position": "absolute" });
        $("#cartitemcount").val(count);
      });

    },

    // Lazy loader for content/markup. Intended for use with calling method that provides endpoint
    lazyLoadContent: function (container, handlerMethod) {
      _debug("lazy content");

      if (typeof container == "undefined") { container = ""; }

      var items = $(container + " .lazycontent"); // Find all <img> tags with data-src attribute

      $.each(items, function (k, v) {
        var el = $(this);
        var params = el.data("params");
        var appendTo = el.data("append");
        var prependTo = el.data("prepend");
        var replaceHtml = el.data("replace");
        //var accountId = el.data("accountid");

        if (typeof appendTo != "undefined") {
          var render = function (html) { $(appendTo).append(html); }
        }

        if (typeof prependTo != "undefined") {
          var render = function (html) { $(prependTo).prepend(html); }
        }

        if (typeof replaceHtml != "undefined") {
          var render = function (html) { $(prependTo).html(html); }
        }

        handlerMethod(this, params, render);
      });

    },

    // Lazy load images that have required data attributes
    lazyLoadImages: function (container) {
      if (typeof container == "undefined") { container = ""; }

      var images = $(container + " img[data-src]"); // Find all <img> tags with data-src attribute


      _debug("> Lazy loading " + images.length + " images in " + container + " img[data-src]");


      $.each(images, function (k, v) {
        var image = $(v);
        var imgsrc = image.data("src");
        var small = image.data("small");
        var large = image.data("large");



        image.attr("src", imgsrc);
      });
    },

    // Generic element toggler
    toggleElements: function (el) {
      var toggle = el.data("toggle"),
        hide = el.data("hide"),
        inactive = el.data("reset");

      // Remove 'active' class from matching selector
      if (inactive) {
        $(inactive).removeClass("active");
      }

      // Force hides from matching selector
      if (hide) {
        $(hide).hide();
      }

      el.toggleClass("active"); // Add active class to clicked element

      $(toggle).toggle(); // Toggles matching element		
    },


    // Puts alert message in browser session storage
    setAlertMessage: function (message, style) {
      sessionStorage.setItem("alertMessageText", message);
      sessionStorage.setItem("alertMessageStyle", style);
    },

    // Checks for alert message and inserts into DOM
    displayAlertMessage: function () {
      var message = sessionStorage.getItem("alertMessageText"); // Check for message

      if (message) {
        var template = $("#tmpl-alertmessage").html(); // Get inline template
        var render = Mustache.render(template, { "message": message, "style": sessionStorage.getItem("alertMessageStyle") });

        $("#SuccessMessage").html(render); // Insert

        // Clear temp storage vars
        sessionStorage.removeItem("alertMessageText");
        sessionStorage.removeItem("alertMessageStyle");
      }
    },

    // Clears any messages from session storage
    clearAlertMessage: function () {
      sessionStorage.removeItem("alertMessageText");
      sessionStorage.removeItem("alertMessageStyle");
      $("#status-message").remove();
    },



    searchPageRequest: function () {
      $('.search-form').on("submit", function (evt) {
        evt.preventDefault();
      });
      $('.search-button').on('click', function (e) {
        e.preventDefault();
        var searchTerm = $(this).parent().parent().find('[data-action="header-search-input"]').val();
        window.location.href = '/search/' + searchTerm;
      });
    },

    menuHover: function () {
      // need to check if not mobile...
      /*
     var navMenuCategories = document.querySelectorAll('.dropdown');
     var navMenuSubcategories = document.querySelectorAll('.dropdown-menu');
     var delay = 50;
     var timerID = 0;
    
     navMenuCategories.forEach(menu => {
         menu.addEventListener('mouseover', function handleHover(event) {
             console.log("hello");
             // need to figure out how to add event to sub menu - index for loop?
         });
     });

     --- Reference code 
     navMenuCategory.on('mouseenter', function () {
         clearTimeout(timerID);
         navMenuSubcategories.addClass('active');
     });

     navMenuCategory.on('mouseleave', function () {
         clearTimeout(timerID);
         timerID = setTimeout(function () { navMenuSubcategories.removeClass('active'); }, delay);
     });

     navMenuSubcategories.on('mouseenter', function () {
         clearTimeout(timerID);
         navMenuSubcategories.addClass('active');
     });

     navMenuSubcategories.on('mouseleave', function () {
         clearTimeout(timerID);
         timerID = setTimeout(function () { navMenuSubcategories.removeClass('active'); }, delay);
     });
     */
    }
  },


  // TYPEAHEAD
  // Available on every page through header search (medium+)
  typeahead: {
    timer: false,
    start: function (input) {
      // Unset any started timers from previous keyup
      if (typeahead.timer != undefined) {
        clearTimeout(typeahead.timer);
      }

      // Set delay timer, won't fire ajax until timeout reached
      typeahead.timer = setTimeout(function () { typeahead.request(input); }, 300);
    },

    request: function (input) {
      var keyword = $(input).val();
      _debug("> typeahead request for " + keyword);

      // Only make a request if there is a string
      if (keyword != "") {
        $('[data-action="header-search-input"]').autocomplete({
          html: true,
          source: function (request, response) {
            try {
              Api.getCustomSearchSuggestions($.trim(keyword), function (data) {
                response($.map(data, function (item) {
                  return {
                    label: "<table cellpadding='10' width='250'><tr><td>" + (item.ImageUrl != '' ? "<a href='" + item.Url + "' style='display: block;'><img src='" + item.ImageUrl + "' width='100' loading=\"lazy\"></a>" : "") + "</td><td><a href='" + item.Url + "' style='display: block;'>" + "<strong>" + item.DisplayText + "</strong> " + item.SearchType + "</a></td></tr></table>",
                    value: item.EntityId
                  }
                }));
              });
            } catch (err) {
              console.error(err);
            }
          },
          search: function (event, ui) {
            $('.autocomplete-spinner').show();
          },
          select: function (event, ui) {
            return false;
          },
          open: function () {
            $('.autocomplete-spinner').hide();
            $(this).data("ui-autocomplete").menu.element.addClass("quick-order-autocomplete");
          }
        });

      } else {
        $("#typeahead-results").empty().removeClass("active");// Hide overlay if empty search (when deleting)
      }
    },

    close: function () {
      $("#typeahead-results").empty().removeClass("active");
    }
  },
  // BINDINGS
  bind: {
    init: function () {
      _debug("global.bind.init()");
      $('[data-action="header-search-input"]').on("keyup", function () {
        global.typeahead.request(this);
      });

      // Click for "log off" in main menu, submits form with session token
      $(".account-logout").on("click", function (ev) {
        ev.preventDefault();
        $("#logout-form").submit();
      });


      // Generic toggle binding 
      this.attachToggle();

      this.newsLetterSignUp();
    },

    // Generic element toggler binding
    attachToggle: function () {
      _debug("bind.attachToggle()");

      $(".toggle").on("click", function (e) {
        e.preventDefault();
        global.local.toggleElements($(this));
      });
    },

    newsLetterSignUp: function () {
      _debug("bind.newsLetterSignUp()");

      $("#btnNewsLetterSignUp").on("click", function (e) {
        $("#newslettererrormessage").removeClass();
        var signUpEmail = $("#txtNewsLetterSignUp").val();
        var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
        if (signUpEmail != null && signUpEmail != "") {
          if (!pattern.test(signUpEmail)) {
            $("#newslettererrormessage").html("Please use a valid email address.")
            $("#newslettererrormessage").addClass("error-msg");
            $("#newslettererrormessage").show();
            return false;
          }
          else {
            $("#newslettererrormessage").html('');
            $("#newslettererrormessage").removeClass("error-msg");
            $("#newslettererrormessage").hide();
            Api.signUpForNewsLetter(signUpEmail, function (response) {
              if (response.sucess) {
                $("#txtNewsLetterSignUp").val('');
                $("#newslettererrormessage").addClass("success-msg");
                $("#newslettererrormessage").show().html(response.message);
              } else {
                $("#newslettererrormessage").addClass("error-msg");
                $("#newslettererrormessage").show().html(response.message);
              }
            });
          }
        } else {
          $("#newslettererrormessage").html('Email ID is required');
          $("#newslettererrormessage").addClass("error-msg");
          $("#newslettererrormessage").show();
          return false;
        }
      });
      $('#txtNewsLetterSignUp').keyup(function (e) {
        if (e.keyCode == 13) {
          $("#btnNewsLetterSignUp").trigger("click");
        }
      });
    },

    ResetTopCategory: function () {
      var _contenerWidth = $("#navbar-collapse-nav").css("width");
      var _menuWidth = 0;
      var html = document.createElement("div");

      /*
            $("#navbar-collapse-nav .dropdown").each(function () {
                _menuWidth += parseInt($(this).css("width").replace("px", ""));

                if (parseInt(_menuWidth) > (parseInt(_contenerWidth.replace("px", "")) - 50)) {
                    $(html).append($(this))
                    // $(this).remove();
                }
                if (parseInt(_menuWidth) < parseInt(_contenerWidth.replace("px", ""))) {
                    $("#navbar-collapse-nav .navbar-nav").append($("#others-menu li:eq(0)"))
                }
            });
      */

      //$("#others-menu").append($(html));
    }
  }
}


global.instant();

$(window).on("load", function () {
  global.onready();
  global.bind.ResetTopCategory();
  global.typeahead.request();
  if ($("#others-menu .dropdown").length === 0) {
    $(".nav-drop-icon").hide();
  }
  else {
    $(".nav-drop-icon").show();
  }

});

$(window).on('orientationchange', function (event) {
  if ($("#others-menu .dropdown").length === 0) {
    $(".nav-drop-icon").hide();
  }
  else {
    $(".nav-drop-icon").show();
  }
});

$(".control_next").on("click", function () {
  $("#others-menu").toggle();
});
;
var Api = {
  ajax: {
    settings: {
      errorAsAlert: false // True will show error as alert dialog
    },

    // Common ajax request; includes cache buster for IE
    request: function (url, method, parameters, successCallback, responseType) {
      if (!method) { method = "GET"; }
      if (!responseType) { responseType = "json"; }

      // Requests must have callback method
      if (typeof successCallback != "function") {
        ajax.errorOut("Callback is not defined. No request made.");
      } else {
        $.ajax({
          type: method,
          url: url,
          data: Api.ajax.cachestamp(parameters),
          dataType: responseType,
          success: function (response) {
            _debug(response); // Always send response to console after request
            successCallback(response);
          },
          error: function () {
            Api.ajax.errorOut("API Endpoint not available: " + url);
          }
        });
      }
    },

    // Timestamp for cache busting
    cachestamp: function (data) {
      var d = new Date();

      if (typeof data == "string") {
        data += "&_=" + d.getTime();
      } else if (typeof data == "object") {
        data["_"] = d.getTime();
      } else {
        data = { "_": d.getTime() };
      }


      return (data);
    },

    // Error output
    errorOut: function (message) {
      console.error(message);

      if (Api.ajax.settings.errorAsAlert) {
        alert(message);
      }
    },

    pendingRequests: new Map(),
    cache: null,

    init: async () => {
      Api.ajax.cache = await caches.open('fetch-cache')
    },

    makeRequest: async (url, options) => {
      try {
        const cachedResponse = await Api.ajax.cache.match(url);

        if (cachedResponse) {
          const cacheEntry = await cachedResponse.json();
          const timestamp = cacheEntry.timestamp;
          const now = new Date().getTime();
          const cacheDuration = 14 * 24 * 60 * 60 * 1000; // 14 days

          if (now - timestamp < cacheDuration) {
            return cacheEntry.data;
          } else {
            await Api.ajax.cache.delete(url);
          }
        }

        const response = await window.fetch(url, options);

        if (response.ok === false) {
          throw new Error(`API Endpoint not available: ${url}`);
        }

        const json = await response.json();

        const cacheEntry = {
          data: json,
          timestamp: new Date().getTime()
      };

        await Api.ajax.cache.put(url, new window.Response(JSON.stringify(cacheEntry)));

        return json;
      } catch (error) {
        console.error(error.message);
      }
    },

    fetch: async (url, options) => {
      if (Api.ajax.pendingRequests.has(url)) {
        return Api.ajax.pendingRequests.get(url);
      }

      const promise = Api.ajax.makeRequest(url, options);

      Api.ajax.pendingRequests.set(url, promise);

      promise.then(() => {
        Api.ajax.pendingRequests.delete(url);
      });

      return promise;
    }
  },

  //Api App ajax helper to extend api.js from custom js
  getAjaxHelper: function () {
    return Api.ajax;
  },
  // App API endpoints
  // Add methods here as needed for additional API calls
  // All endpoint methods are public

  // Get grid of related products (FBT/YML); Returns raw HTML, not JSON
  getRelatedProducts: function (ids, accountId, callbackMethod) {
    Api.ajax.request("/ProductAsync/GetProductsByIds", "get", { "ids": ids, "accountId": accountId }, callbackMethod, "html");
  },


  // Get grid of related products (FBT/YML); Returns raw HTML, not JSON
  countinueCheckout: function (address, callbackMethod) {
    Api.ajax.request("/Checkout/ContinueCheckout", "post", { "multipleAddress": address }, callbackMethod, "json");
  },


  // get recent product
  getRecentProducts: function (productId, productCount, callbackMethod) {
    Api.ajax.request("/Product/GetRecentProducts", "get", { "productId": productId, "productCount": productCount }, callbackMethod);
  },

  // Get number of items in cart; Returns raw integer value, not JSON
  getCartCount: function (callbackMethod) {
    Api.ajax.request("/Cart/CartCount", "get", false, callbackMethod);
  },

  // Apply coupon code to cart order
  useCouponCode: function (couponCode, callbackMethod) {
    Api.ajax.request("/Cart/ApplyCoupon", "get", { "Coupon": couponCode }, callbackMethod, "json");
  },

  // Returns balance of gift card
  getGiftCardBalance: function (gcNumber, callbackMethod) {
    Api.ajax.request("/Home/GiftCard", "get", { "giftcard": gcNumber }, callbackMethod);
  },

  // Apply gift card to order during checkout
  useGiftCard: function (gcNumber, callbackMethod) {
    Api.ajax.request("/Checkout/ApplyGiftCard", "get", { "number": gcNumber }, callbackMethod);
  },

  // Add single item to wish list
  addProductToWishList: function (productId, sku, callbackMethod) {
    Api.ajax.request("/Product/WishList", "get", { "id": productId, "sku": sku }, callbackMethod);
  },

  // Remove item from account wish list
  removeProductFromWishList: function (wishlistId, callbackMethod) {
    Api.ajax.request("/Account/Wishlist", "post", { "wishid": wishlistId }, callbackMethod);
  },

  // Update product attributes
  getProductAttributes: function (productId, data, callbackMethod) {
    Api.ajax.request("/Product/GetAttributes/" + productId, "get", data, callbackMethod);
  },

  // Get security question of specified user
  getUserSecurityQuestion: function (username, email, callbackMethod) {
    Api.ajax.request("/Account/ForgotPassword/", "post", { "UserName": username, "EmailAddress": email }, callbackMethod);
  },

  // Get suggestions for search term (typeahead)
  getSearchSuggestions: function (searchTerm, callbackMethod) {
    Api.ajax.request("/Search/GetSuggestions", "get", { "searchTerm": searchTerm }, callbackMethod);
  },

  // get list of State bt CountryCode .
  getStateByCountryCode: async function (countryCode, callbackMethod) {
    const fetchRespone = await Api.ajax.fetch(`/Account/GetStateByCountryCode?countryCode=${countryCode}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (typeof callbackMethod != "function") {
      console.error("Callback is not defined. No request made.");
      return;
    }

    callbackMethod(fetchRespone);
  },

  GetPaymentGatwayName: function (paymentOptionId, callbackMethod) {
    Api.ajax.request("/checkout/getpaymentgatwaynamebypaymetoptionid", "get", { "paymentOptionId": paymentOptionId }, callbackMethod);
  },

  LoadCurbstoneIframe: function (callbackMethod) {
    Api.ajax.request("/checkout/opencurbstoneresult", "post", {}, callbackMethod);
  },

  PayPalCreateOrder: function (callbackMethod) {
    Api.ajax.request("/checkout/paypalcreateorder", "post", {}, callbackMethod);
  },

  GetCurbstoneRecaptchaResult: function (token, callbackMethod) {
    Api.ajax.request("/checkout/curbstonerecaptcharesult", "post", { "token": token }, callbackMethod);
  },

  GetProductListBySKU: function (sku, callbackMethod) {
    Api.ajax.request("/Product/GetProductListBySKU", "get", { "sku": sku }, callbackMethod);
  },

  globalAddToCompare: function (productId, categoryId, callbackMethod) {
    Api.ajax.request("/Product/GlobalLevelCompareProduct", "get", { "productId": productId, "categoryId": categoryId }, callbackMethod);
  },

  categoryAddToCompare: function (productId, categoryId, callbackMethod) {
    Api.ajax.request("/Product/CategoryLevelCompareProduct", "get", { "productId": productId, "categoryId": categoryId }, callbackMethod);
  },

  getCompareProducts: function (callBackMethod) {
    Api.ajax.request("/Product/ShowCompareProduct", "get", {}, callBackMethod);
  },

  getProductComparison: function (callBackMethod) {
    Api.ajax.request("/Product/ViewProductComparison", "post", {}, callBackMethod);
  },

  removeProduct: function (productId, control, callBackMethod) {
    Api.ajax.request("/Product/RemoveProductFormSession",
      "post",
      { "productId": productId, "control": control },
      callBackMethod);
  },

  productCompareAddToCart: function (cartItem, callBackMethod) {
    Api.ajax.request("/Product/AddToCart", "post", { "cartItem": cartItem }, callBackMethod, "html");
  },

  getComparedProductSendMailDetails: function (callBackMethod) {
    Api.ajax.request("/Product/SendComparedProductMail", "get", {}, callBackMethod, "html");
  },

  applyDiscount: function (url, couponCode, callBackMethod) {
    Api.ajax.request(url, "get", { "couponCode": couponCode }, callBackMethod, "json");
  },
  removeCoupon: function (couponCode, callBackMethod) {
    Api.ajax.request("/Checkout/RemoveDiscount", "get", { "couponCode": couponCode }, callBackMethod, "json");
  },
  signUpForNewsLetter: function (emailId, callbackMethod) {
    Api.ajax.request("/Account/SignUpForNewsLetter", "post", { "emailId": emailId }, callbackMethod);
  },

  getProductSendMailDetails: function (productId, productName, callBackMethod) {
    Api.ajax.request("/Product/SendMailToFriend", "get", { "productId": productId, "productName": productName }, callBackMethod, "html");
  },
  getQuickView: function (productId, callBackMethod) {
    Api.ajax.request("/Product/Details", "get", { "id": productId, "isQuickView": true }, callBackMethod, "html");
  },
  getProductBreadCrumb: function (productId, productName, isQuickView, callbackMethod) {
    Api.ajax.request("/Product/GetProductBreadCrumb", "get", { "productId": productId, "productName": productName, "isQuickView": isQuickView }, callbackMethod);
  },
  setProductCategory: function (categoryId, categoryName, callbackMethod) {
    Api.ajax.request("/Product/SetProductCategory", "get", { "categoryId": categoryId, "categoryName": categoryName }, callbackMethod);
  },
  isCouponUrlEnabled: function (couponCode, callbackMethod) {
    Api.ajax.request("/Cart/IsCouponUrlEnabled", "get", { "Coupon": couponCode }, callbackMethod, "json");
  },
  ProcessPayPalPayment: function (paymentOptionId, returnUrl, cancelUrl, callbackMethod) {
    Api.ajax.request("/Checkout/ProcessPayPalPayment", "post", { "paymentSettingId": paymentOptionId, "returnUrl": returnUrl, "cancelUrl": cancelUrl }, callbackMethod, "json");
  },
  getProductOutOfStockDetails: function (productId, callBackMethod) {
    Api.ajax.request("/Product/GetProductOutOfStockDetails", "get", { "productId": productId }, callBackMethod, "html");
  },
  submitPayment: function (paymentSettingId, customerProfileId, customerPaymentId, callBackMethod) {
    Api.ajax.request("/Checkout/SubmitPayment", "post", { "paymentSettingId": paymentSettingId, "customerProfileId": customerProfileId, "customerPaymentId": customerPaymentId }, callBackMethod, "json");
  },
  getSenMailNOtification: function (url, productId, senderMailId, recieverMailId, callBackMethod) {
    Api.ajax.request(url, "post", { "productId": productId, "senderMailId": senderMailId, "recieverMailId": recieverMailId }, callBackMethod, "json");
  },
  getCountryShippings: function (data, isCountryStateTax, countryShippingCode, callBackMethod) {
    Api.ajax.request("/Checkout/GetShippingMethodsByCountryCode", "post", { "model": data, "isCountryStateTax": isCountryStateTax, "countryShippingCode": countryShippingCode }, callBackMethod, "html");
  },
  removeCouponCode: function (couponCode, callbackMethod) {
    Api.ajax.request("/Cart/RemoveCoupon", "get", { "Coupon": couponCode }, callbackMethod, "json");
  },
  formatPriceWithCurrency: function (price, callbackMethod) {
    Api.ajax.request("/Order/FormatPriceWithCurrency", "get", { "price": price }, callbackMethod, "json");
  },
  deleteRecordById: function (url, callbackMethod) {
    Api.ajax.request(url, "post", {}, callbackMethod);
  },

  // Get custom suggestions for search term (typeahead)
  getCustomSearchSuggestions: function (searchTerm, callbackMethod) {
    Api.ajax.request("/Search/GetResultSuggestions/" + searchTerm, "get", {}, callbackMethod);
  }
}

const init = async () => {
  await Api.ajax.init();
};

init();
;
;(function (root, factory) {
  if (typeof exports === "object" && exports) {
    factory(exports); // CommonJS
  } else {
    var mustache = {};
    factory(mustache);
    if (typeof define === "function" && define.amd) {
      define(mustache); // AMD
    } else {
      root.Mustache = mustache; // <script>
    }
  }
}(this, function (mustache) {

  var whiteRe = /\s*/;
  var spaceRe = /\s+/;
  var nonSpaceRe = /\S/;
  var eqRe = /\s*=/;
  var curlyRe = /\s*\}/;
  var tagRe = /#|\^|\/|>|\{|&|=|!/;

    // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
    // See https://github.com/janl/mustache.js/issues/189  
  var RegExp_test = RegExp.prototype.test;
  function testRegExp(re, string) {
    return RegExp_test.call(re, string);
  }

  function isWhitespace(string) {
    return !testRegExp(nonSpaceRe, string);
  }

  var Object_toString = Object.prototype.toString;
  var isArray = Array.isArray || function (object) {
    return Object_toString.call(object) === '[object Array]';
  };

  function isFunction(object) {
    return typeof object === 'function';
  }

  function escapeRegExp(string) {
    return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
  }

  var entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  function escapeTags(tags) {
    if (!isArray(tags) || tags.length !== 2) {
      throw new Error('Invalid tags: ' + tags);
    }

    return [
      new RegExp(escapeRegExp(tags[0]) + "\\s*"),
      new RegExp("\\s*" + escapeRegExp(tags[1]))
    ];
  }

    /**
    * Breaks up the given `template` string into a tree of tokens. If the `tags`
    * argument is given here it must be an array with two string values: the
    * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
    * course, the default is to use mustaches (i.e. mustache.tags).
    *
    * A token is an array with at least 4 elements. The first element is the
    * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
    * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
    * all template text that appears outside a symbol this element is "text".
    *
    * The second element of a token is its "value". For mustache tags this is
    * whatever else was inside the tag besides the opening symbol. For text tokens
    * this is the text itself.
    *
    * The third and fourth elements of the token are the start and end indices
    * in the original template of the token, respectively.
    *
    * Tokens that are the root node of a subtree contain two more elements: an
    * array of tokens in the subtree and the index in the original template at which
    * the closing tag for that section begins.
    */
  function parseTemplate(template, tags) {
    tags = tags || mustache.tags;
    template = template || '';

    if (typeof tags === 'string') {
      tags = tags.split(spaceRe);
    }

    var tagRes = escapeTags(tags);
    var scanner = new Scanner(template);

    var sections = [];     // Stack to hold section tokens
    var tokens = [];       // Buffer to hold the tokens
    var spaces = [];       // Indices of whitespace tokens on the current line
    var hasTag = false;    // Is there a {{tag}} on the current line?
    var nonSpace = false;  // Is there a non-space char on the current line?

      // Strips all whitespace tokens array for the current line
          // if there was a {{#tag}} on it and otherwise only space.  
    function stripSpace() {
      if (hasTag && !nonSpace) {
        while (spaces.length) {
          delete tokens[spaces.pop()];
        }
      } else {
        spaces = [];
      }

      hasTag = false;
      nonSpace = false;
    }

    var start, type, value, chr, token, openSection;
    while (!scanner.eos()) {
      start = scanner.pos;

      // Match any text between tags.
      value = scanner.scanUntil(tagRes[0]);
      if (value) {
        for (var i = 0, len = value.length; i < len; ++i) {
          chr = value.charAt(i);

          if (isWhitespace(chr)) {
            spaces.push(tokens.length);
          } else {
            nonSpace = true;
          }

          tokens.push(['text', chr, start, start + 1]);
          start += 1;

          // Check for whitespace on the current line.
          if (chr === '\n') {
            stripSpace();
          }
        }
      }

      // Match the opening tag.
      if (!scanner.scan(tagRes[0])) break;
      hasTag = true;

      // Get the tag type.
      type = scanner.scan(tagRe) || 'name';
      scanner.scan(whiteRe);

      // Get the tag value.
      if (type === '=') {
        value = scanner.scanUntil(eqRe);
        scanner.scan(eqRe);
        scanner.scanUntil(tagRes[1]);
      } else if (type === '{') {
        value = scanner.scanUntil(new RegExp('\\s*' + escapeRegExp('}' + tags[1])));
        scanner.scan(curlyRe);
        scanner.scanUntil(tagRes[1]);
        type = '&';
      } else {
        value = scanner.scanUntil(tagRes[1]);
      }

      // Match the closing tag.
      if (!scanner.scan(tagRes[1])) {
        throw new Error('Unclosed tag at ' + scanner.pos);
      }

      token = [ type, value, start, scanner.pos ];
      tokens.push(token);

      if (type === '#' || type === '^') {
        sections.push(token);
      } else if (type === '/') {
        // Check section nesting.
        openSection = sections.pop();

        if (!openSection) {
          throw new Error('Unopened section "' + value + '" at ' + start);
        }
        if (openSection[1] !== value) {
          throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
        }
      } else if (type === 'name' || type === '{' || type === '&') {
        nonSpace = true;
      } else if (type === '=') {
        // Set the tags for the next time around.
        tagRes = escapeTags(tags = value.split(spaceRe));
      }
    }

    // Make sure there are no open sections when we're done.
    openSection = sections.pop();
    if (openSection) {
      throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
    }

    return nestTokens(squashTokens(tokens));
  }

    /**
    * Combines the values of consecutive text tokens in the given `tokens` array
    * to a single token.
    */
  function squashTokens(tokens) {
    var squashedTokens = [];

    var token, lastToken;
    for (var i = 0, len = tokens.length; i < len; ++i) {
      token = tokens[i];

      if (token) {
        if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
          lastToken[1] += token[1];
          lastToken[3] = token[3];
        } else {
          squashedTokens.push(token);
          lastToken = token;
        }
      }
    }

    return squashedTokens;
  }
    /**
       * Forms the given array of `tokens` into a nested tree structure where
       * tokens that represent a section have two additional items: 1) an array of
       * all tokens that appear in that section and 2) the index in the original
       * template that represents the end of that section.
       */
  function nestTokens(tokens) {
    var nestedTokens = [];
    var collector = nestedTokens;
    var sections = [];

    var token, section;
    for (var i = 0, len = tokens.length; i < len; ++i) {
      token = tokens[i];

      switch (token[0]) {
      case '#':
      case '^':
        collector.push(token);
        sections.push(token);
        collector = token[4] = [];
        break;
      case '/':
        section = sections.pop();
        section[5] = token[2];
        collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
        break;
      default:
        collector.push(token);
      }
    }

    return nestedTokens;
  }

    /**
      * A simple string scanner that is used by the template parser to find
      * tokens in template strings.
      */
  function Scanner(string) {
    this.string = string;
    this.tail = string;
    this.pos = 0;
  }

    /**
      * Returns `true` if the tail is empty (end of string).
      */
  Scanner.prototype.eos = function () {
    return this.tail === "";
  };

    /**
     * Tries to match the given regular expression at the current position.
     * Returns the matched text if it can match, the empty string otherwise.
     */
  Scanner.prototype.scan = function (re) {
    var match = this.tail.match(re);

    if (match && match.index === 0) {
      var string = match[0];
      this.tail = this.tail.substring(string.length);
      this.pos += string.length;
      return string;
    }

    return "";
  };

    /**
     * Skips all text until the given regular expression can be matched. Returns
     * the skipped string, which is the entire tail if no match can be made.
     */
  Scanner.prototype.scanUntil = function (re) {
    var index = this.tail.search(re), match;

    switch (index) {
    case -1:
      match = this.tail;
      this.tail = "";
      break;
    case 0:
      match = "";
      break;
    default:
      match = this.tail.substring(0, index);
      this.tail = this.tail.substring(index);
    }

    this.pos += match.length;

    return match;
  };

    /**
     * Represents a rendering context by wrapping a view object and
     * maintaining a reference to the parent context.
     */
  function Context(view, parentContext) {
    this.view = view == null ? {} : view;
    this.cache = { '.': this.view };
    this.parent = parentContext;
  }
    /**
      * Creates a new context using the given view with this context
      * as the parent.
      */
  Context.prototype.push = function (view) {
    return new Context(view, this);
  };

    /**
     * Returns the value of the given name in this context, traversing
     * up the context hierarchy if the value is absent in this context's view.
     */
  Context.prototype.lookup = function (name) {
    var value;
    if (name in this.cache) {
      value = this.cache[name];
    } else {
      var context = this;

      while (context) {
        if (name.indexOf('.') > 0) {
          value = context.view;

          var names = name.split('.'), i = 0;
          while (value != null && i < names.length) {
            value = value[names[i++]];
          }
        } else {
          value = context.view[name];
        }

        if (value != null) break;

        context = context.parent;
      }

      this.cache[name] = value;
    }

    if (isFunction(value)) {
      value = value.call(this.view);
    }

    return value;
  };

    /**
     * A Writer knows how to take a stream of tokens and render them to a
     * string, given a context. It also maintains a cache of templates to
     * avoid the need to parse the same template twice.
     */
  function Writer() {
    this.cache = {};
  }

    /**
      * Clears all cached templates in this writer.
      */
  Writer.prototype.clearCache = function () {
    this.cache = {};
  };

    /**
     * Parses and caches the given `template` and returns the array of tokens
     * that is generated from the parse.
     */
  Writer.prototype.parse = function (template, tags) {
    if (!(template in this.cache)) {
      this.cache[template] = parseTemplate(template, tags);
    }

    return this.cache[template];
  };
    
    /**
         * High-level method that is used to render the given `template` with
         * the given `view`.
         *
         * The optional `partials` argument may be an object that contains the
         * names and templates of partials that are used in the template. It may
         * also be a function that is used to load partial templates on the fly
         * that takes a single argument: the name of the partial.
         */
  Writer.prototype.render = function (template, view, partials) {
    var tokens = this.parse(template);
    var context = (view instanceof Context) ? view : new Context(view);
    return this.renderTokens(tokens, context, partials, template);
  };
       /**
          * Low-level method that renders the given array of `tokens` using
          * the given `context` and `partials`.
          *
          * Note: The `originalTemplate` is only ever used to extract the portion
          * of the original template that was contained in a higher-order section.
          * If the template doesn't use higher-order sections, this argument may
          * be omitted.
          */
  Writer.prototype.renderTokens = function (tokens, context, partials, originalTemplate) {
    var buffer = '';

    // This function is used to render an arbitrary template
    // in the current context by higher-order sections.
    var self = this;
    function subRender(template) {
      return self.render(template, context, partials);
    }

    var token, value;
    for (var i = 0, len = tokens.length; i < len; ++i) {
      token = tokens[i];

      switch (token[0]) {
      case '#':
        value = context.lookup(token[1]);
        if (!value) continue;

        if (isArray(value)) {
          for (var j = 0, jlen = value.length; j < jlen; ++j) {
            buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
          }
        } else if (typeof value === 'object' || typeof value === 'string') {
          buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
        } else if (isFunction(value)) {
          if (typeof originalTemplate !== 'string') {
            throw new Error('Cannot use higher-order sections without the original template');
          }

          // Extract the portion of the original template that the section contains.
          value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);

          if (value != null) buffer += value;
        } else {
          buffer += this.renderTokens(token[4], context, partials, originalTemplate);
        }

        break;
      case '^':
        value = context.lookup(token[1]);

        // Use JavaScript's definition of falsy. Include empty arrays.
        // See https://github.com/janl/mustache.js/issues/186
        if (!value || (isArray(value) && value.length === 0)) {
          buffer += this.renderTokens(token[4], context, partials, originalTemplate);
        }

        break;
      case '>':
        if (!partials) continue;
        value = this.parse(isFunction(partials) ? partials(token[1]) : partials[token[1]]);
        if (value != null) buffer += this.renderTokens(value, context, partials, originalTemplate);
        break;
      case '&':
        value = context.lookup(token[1]);
        if (value != null) buffer += value;
        break;
      case 'name':
        value = context.lookup(token[1]);
        if (value != null) buffer += mustache.escape(value);
        break;
      case 'text':
        buffer += token[1];
        break;
      }
    }

    return buffer;
  };

  mustache.name = "mustache.js";
  mustache.version = "0.8.0";
  mustache.tags = [ "{{", "}}" ];

  // All high-level mustache.* functions use this writer.
  var defaultWriter = new Writer();

    /**
      * Clears all cached templates in the default writer.
      */
  mustache.clearCache = function () {
    return defaultWriter.clearCache();
  };

    /**
      * Parses and caches the given template in the default writer and returns the
      * array of tokens it contains. Doing this ahead of time avoids the need to
      * parse templates on the fly as they are rendered.
      */
  mustache.parse = function (template, tags) {
    return defaultWriter.parse(template, tags);
  };

    /**
      * Renders the `template` with the given `view` and `partials` using the
      * default writer.
      */
  mustache.render = function (template, view, partials) {
    return defaultWriter.render(template, view, partials);
  };

  // This is here for backwards compatibility with 0.4.x.
  mustache.to_html = function (template, view, partials, send) {
    var result = mustache.render(template, view, partials);

    if (isFunction(send)) {
      send(result);
    } else {
      return result;
    }
  };

  // Export the escaping function so that the user may override it.
 
  mustache.escape = escapeHtml;

  // Export these mainly for testing, but also for advanced usage.
  mustache.Scanner = Scanner;
  mustache.Context = Context;
  mustache.Writer = Writer;

}));
;/*!

 handlebars v4.0.5

Copyright (C) 2011-2015 by Yehuda Katz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@license
*/
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["Handlebars"] = factory();
	else
		root["Handlebars"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}


/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;

	var _handlebarsRuntime = __webpack_require__(2);

	var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);

	// Compiler imports

	var _handlebarsCompilerAst = __webpack_require__(21);

	var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);

	var _handlebarsCompilerBase = __webpack_require__(22);

	var _handlebarsCompilerCompiler = __webpack_require__(27);

	var _handlebarsCompilerJavascriptCompiler = __webpack_require__(28);

	var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);

	var _handlebarsCompilerVisitor = __webpack_require__(25);

	var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);

	var _handlebarsNoConflict = __webpack_require__(20);

	var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);

	var _create = _handlebarsRuntime2['default'].create;
	function create() {
	  var hb = _create();

	  hb.compile = function (input, options) {
	    return _handlebarsCompilerCompiler.compile(input, options, hb);
	  };
	  hb.precompile = function (input, options) {
	    return _handlebarsCompilerCompiler.precompile(input, options, hb);
	  };

	  hb.AST = _handlebarsCompilerAst2['default'];
	  hb.Compiler = _handlebarsCompilerCompiler.Compiler;
	  hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
	  hb.Parser = _handlebarsCompilerBase.parser;
	  hb.parse = _handlebarsCompilerBase.parse;

	  return hb;
	}

	var inst = create();
	inst.create = create;

	_handlebarsNoConflict2['default'](inst);

	inst.Visitor = _handlebarsCompilerVisitor2['default'];

	inst['default'] = inst;

	exports['default'] = inst;
	module.exports = exports['default'];

/***/ },
/* 1 */
/***/ function(module, exports) {

	"use strict";

	exports["default"] = function (obj) {
	  return obj && obj.__esModule ? obj : {
	    "default": obj
	  };
	};

	exports.__esModule = true;

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireWildcard = __webpack_require__(3)['default'];

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;

	var _handlebarsBase = __webpack_require__(4);

	var base = _interopRequireWildcard(_handlebarsBase);

	// Each of these augment the Handlebars object. No need to setup here.
	// (This is done to easily share code between commonjs and browse envs)

	var _handlebarsSafeString = __webpack_require__(18);

	var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);

	var _handlebarsException = __webpack_require__(6);

	var _handlebarsException2 = _interopRequireDefault(_handlebarsException);

	var _handlebarsUtils = __webpack_require__(5);

	var Utils = _interopRequireWildcard(_handlebarsUtils);

	var _handlebarsRuntime = __webpack_require__(19);

	var runtime = _interopRequireWildcard(_handlebarsRuntime);

	var _handlebarsNoConflict = __webpack_require__(20);

	var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);

	// For compatibility and usage outside of module systems, make the Handlebars object a namespace
	function create() {
	  var hb = new base.HandlebarsEnvironment();

	  Utils.extend(hb, base);
	  hb.SafeString = _handlebarsSafeString2['default'];
	  hb.Exception = _handlebarsException2['default'];
	  hb.Utils = Utils;
	  hb.escapeExpression = Utils.escapeExpression;

	  hb.VM = runtime;
	  hb.template = function (spec) {
	    return runtime.template(spec, hb);
	  };

	  return hb;
	}

	var inst = create();
	inst.create = create;

	_handlebarsNoConflict2['default'](inst);

	inst['default'] = inst;

	exports['default'] = inst;
	module.exports = exports['default'];

/***/ },
/* 3 */
/***/ function(module, exports) {

	"use strict";

	exports["default"] = function (obj) {
	  if (obj && obj.__esModule) {
	    return obj;
	  } else {
	    var newObj = {};

	    if (obj != null) {
	      for (var key in obj) {
	        if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
	      }
	    }

	    newObj["default"] = obj;
	    return newObj;
	  }
	};

	exports.__esModule = true;

/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;
	exports.HandlebarsEnvironment = HandlebarsEnvironment;

	var _utils = __webpack_require__(5);

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	var _helpers = __webpack_require__(7);

	var _decorators = __webpack_require__(15);

	var _logger = __webpack_require__(17);

	var _logger2 = _interopRequireDefault(_logger);

	var VERSION = '4.0.5';
	exports.VERSION = VERSION;
	var COMPILER_REVISION = 7;

	exports.COMPILER_REVISION = COMPILER_REVISION;
	var REVISION_CHANGES = {
	  1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
	  2: '== 1.0.0-rc.3',
	  3: '== 1.0.0-rc.4',
	  4: '== 1.x.x',
	  5: '== 2.0.0-alpha.x',
	  6: '>= 2.0.0-beta.1',
	  7: '>= 4.0.0'
	};

	exports.REVISION_CHANGES = REVISION_CHANGES;
	var objectType = '[object Object]';

	function HandlebarsEnvironment(helpers, partials, decorators) {
	  this.helpers = helpers || {};
	  this.partials = partials || {};
	  this.decorators = decorators || {};

	  _helpers.registerDefaultHelpers(this);
	  _decorators.registerDefaultDecorators(this);
	}

	HandlebarsEnvironment.prototype = {
	  constructor: HandlebarsEnvironment,

	  logger: _logger2['default'],
	  log: _logger2['default'].log,

	  registerHelper: function registerHelper(name, fn) {
	    if (_utils.toString.call(name) === objectType) {
	      if (fn) {
	        throw new _exception2['default']('Arg not supported with multiple helpers');
	      }
	      _utils.extend(this.helpers, name);
	    } else {
	      this.helpers[name] = fn;
	    }
	  },
	  unregisterHelper: function unregisterHelper(name) {
	    delete this.helpers[name];
	  },

	  registerPartial: function registerPartial(name, partial) {
	    if (_utils.toString.call(name) === objectType) {
	      _utils.extend(this.partials, name);
	    } else {
	      if (typeof partial === 'undefined') {
	        throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
	      }
	      this.partials[name] = partial;
	    }
	  },
	  unregisterPartial: function unregisterPartial(name) {
	    delete this.partials[name];
	  },

	  registerDecorator: function registerDecorator(name, fn) {
	    if (_utils.toString.call(name) === objectType) {
	      if (fn) {
	        throw new _exception2['default']('Arg not supported with multiple decorators');
	      }
	      _utils.extend(this.decorators, name);
	    } else {
	      this.decorators[name] = fn;
	    }
	  },
	  unregisterDecorator: function unregisterDecorator(name) {
	    delete this.decorators[name];
	  }
	};

	var log = _logger2['default'].log;

	exports.log = log;
	exports.createFrame = _utils.createFrame;
	exports.logger = _logger2['default'];

/***/ },
/* 5 */
/***/ function(module, exports) {

	'use strict';

	exports.__esModule = true;
	exports.extend = extend;
	exports.indexOf = indexOf;
	exports.escapeExpression = escapeExpression;
	exports.isEmpty = isEmpty;
	exports.createFrame = createFrame;
	exports.blockParams = blockParams;
	exports.appendContextPath = appendContextPath;
	var escape = {
	  '&': '&amp;',
	  '<': '&lt;',
	  '>': '&gt;',
	  '"': '&quot;',
	  "'": '&#x27;',
	  '`': '&#x60;',
	  '=': '&#x3D;'
	};

	var badChars = /[&<>"'`=]/g,
	    possible = /[&<>"'`=]/;

	function escapeChar(chr) {
	  return escape[chr];
	}

	function extend(obj /* , ...source */) {
	  for (var i = 1; i < arguments.length; i++) {
	    for (var key in arguments[i]) {
	      if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
	        obj[key] = arguments[i][key];
	      }
	    }
	  }

	  return obj;
	}

	var toString = Object.prototype.toString;

	exports.toString = toString;
	// Sourced from lodash
	// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
	/* eslint-disable func-style */
	var isFunction = function isFunction(value) {
	  return typeof value === 'function';
	};
	// fallback for older versions of Chrome and Safari
	/* istanbul ignore next */
	if (isFunction(/x/)) {
	  exports.isFunction = isFunction = function (value) {
	    return typeof value === 'function' && toString.call(value) === '[object Function]';
	  };
	}
	exports.isFunction = isFunction;

	/* eslint-enable func-style */

	/* istanbul ignore next */
	var isArray = Array.isArray || function (value) {
	  return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
	};

	exports.isArray = isArray;
	// Older IE versions do not directly support indexOf so we must implement our own, sadly.

	function indexOf(array, value) {
	  for (var i = 0, len = array.length; i < len; i++) {
	    if (array[i] === value) {
	      return i;
	    }
	  }
	  return -1;
	}

	function escapeExpression(string) {
	  if (typeof string !== 'string') {
	    // don't escape SafeStrings, since they're already safe
	    if (string && string.toHTML) {
	      return string.toHTML();
	    } else if (string == null) {
	      return '';
	    } else if (!string) {
	      return string + '';
	    }

	    // Force a string conversion as this will be done by the append regardless and
	    // the regex test will do this transparently behind the scenes, causing issues if
	    // an object's to string has escaped characters in it.
	    string = '' + string;
	  }

	  if (!possible.test(string)) {
	    return string;
	  }
	  return string.replace(badChars, escapeChar);
	}

	function isEmpty(value) {
	  if (!value && value !== 0) {
	    return true;
	  } else if (isArray(value) && value.length === 0) {
	    return true;
	  } else {
	    return false;
	  }
	}

	function createFrame(object) {
	  var frame = extend({}, object);
	  frame._parent = object;
	  return frame;
	}

	function blockParams(params, ids) {
	  params.path = ids;
	  return params;
	}

	function appendContextPath(contextPath, id) {
	  return (contextPath ? contextPath + '.' : '') + id;
	}

/***/ },
/* 6 */
/***/ function(module, exports) {

	'use strict';

	exports.__esModule = true;

	var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];

	function Exception(message, node) {
	  var loc = node && node.loc,
	      line = undefined,
	      column = undefined;
	  if (loc) {
	    line = loc.start.line;
	    column = loc.start.column;

	    message += ' - ' + line + ':' + column;
	  }

	  var tmp = Error.prototype.constructor.call(this, message);

	  // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
	  for (var idx = 0; idx < errorProps.length; idx++) {
	    this[errorProps[idx]] = tmp[errorProps[idx]];
	  }

	  /* istanbul ignore else */
	  if (Error.captureStackTrace) {
	    Error.captureStackTrace(this, Exception);
	  }

	  if (loc) {
	    this.lineNumber = line;
	    this.column = column;
	  }
	}

	Exception.prototype = new Error();

	exports['default'] = Exception;
	module.exports = exports['default'];

/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;
	exports.registerDefaultHelpers = registerDefaultHelpers;

	var _helpersBlockHelperMissing = __webpack_require__(8);

	var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);

	var _helpersEach = __webpack_require__(9);

	var _helpersEach2 = _interopRequireDefault(_helpersEach);

	var _helpersHelperMissing = __webpack_require__(10);

	var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);

	var _helpersIf = __webpack_require__(11);

	var _helpersIf2 = _interopRequireDefault(_helpersIf);

	var _helpersLog = __webpack_require__(12);

	var _helpersLog2 = _interopRequireDefault(_helpersLog);

	var _helpersLookup = __webpack_require__(13);

	var _helpersLookup2 = _interopRequireDefault(_helpersLookup);

	var _helpersWith = __webpack_require__(14);

	var _helpersWith2 = _interopRequireDefault(_helpersWith);

	function registerDefaultHelpers(instance) {
	  _helpersBlockHelperMissing2['default'](instance);
	  _helpersEach2['default'](instance);
	  _helpersHelperMissing2['default'](instance);
	  _helpersIf2['default'](instance);
	  _helpersLog2['default'](instance);
	  _helpersLookup2['default'](instance);
	  _helpersWith2['default'](instance);
	}

/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _utils = __webpack_require__(5);

	exports['default'] = function (instance) {
	  instance.registerHelper('blockHelperMissing', function (context, options) {
	    var inverse = options.inverse,
	        fn = options.fn;

	    if (context === true) {
	      return fn(this);
	    } else if (context === false || context == null) {
	      return inverse(this);
	    } else if (_utils.isArray(context)) {
	      if (context.length > 0) {
	        if (options.ids) {
	          options.ids = [options.name];
	        }

	        return instance.helpers.each(context, options);
	      } else {
	        return inverse(this);
	      }
	    } else {
	      if (options.data && options.ids) {
	        var data = _utils.createFrame(options.data);
	        data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
	        options = { data: data };
	      }

	      return fn(context, options);
	    }
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;

	var _utils = __webpack_require__(5);

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	exports['default'] = function (instance) {
	  instance.registerHelper('each', function (context, options) {
	    if (!options) {
	      throw new _exception2['default']('Must pass iterator to #each');
	    }

	    var fn = options.fn,
	        inverse = options.inverse,
	        i = 0,
	        ret = '',
	        data = undefined,
	        contextPath = undefined;

	    if (options.data && options.ids) {
	      contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
	    }

	    if (_utils.isFunction(context)) {
	      context = context.call(this);
	    }

	    if (options.data) {
	      data = _utils.createFrame(options.data);
	    }

	    function execIteration(field, index, last) {
	      if (data) {
	        data.key = field;
	        data.index = index;
	        data.first = index === 0;
	        data.last = !!last;

	        if (contextPath) {
	          data.contextPath = contextPath + field;
	        }
	      }

	      ret = ret + fn(context[field], {
	        data: data,
	        blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
	      });
	    }

	    if (context && typeof context === 'object') {
	      if (_utils.isArray(context)) {
	        for (var j = context.length; i < j; i++) {
	          if (i in context) {
	            execIteration(i, i, i === context.length - 1);
	          }
	        }
	      } else {
	        var priorKey = undefined;

	        for (var key in context) {
	          if (context.hasOwnProperty(key)) {
	            // We're running the iterations one step out of sync so we can detect
	            // the last iteration without have to scan the object twice and create
	            // an itermediate keys array.
	            if (priorKey !== undefined) {
	              execIteration(priorKey, i - 1);
	            }
	            priorKey = key;
	            i++;
	          }
	        }
	        if (priorKey !== undefined) {
	          execIteration(priorKey, i - 1, true);
	        }
	      }
	    }

	    if (i === 0) {
	      ret = inverse(this);
	    }

	    return ret;
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	exports['default'] = function (instance) {
	  instance.registerHelper('helperMissing', function () /* [args, ]options */{
	    if (arguments.length === 1) {
	      // A missing field in a {{foo}} construct.
	      return undefined;
	    } else {
	      // Someone is actually trying to call something, blow up.
	      throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
	    }
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _utils = __webpack_require__(5);

	exports['default'] = function (instance) {
	  instance.registerHelper('if', function (conditional, options) {
	    if (_utils.isFunction(conditional)) {
	      conditional = conditional.call(this);
	    }

	    // Default behavior is to render the positive path if the value is truthy and not empty.
	    // The `includeZero` option may be set to treat the condtional as purely not empty based on the
	    // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
	    if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
	      return options.inverse(this);
	    } else {
	      return options.fn(this);
	    }
	  });

	  instance.registerHelper('unless', function (conditional, options) {
	    return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 12 */
/***/ function(module, exports) {

	'use strict';

	exports.__esModule = true;

	exports['default'] = function (instance) {
	  instance.registerHelper('log', function () /* message, options */{
	    var args = [undefined],
	        options = arguments[arguments.length - 1];
	    for (var i = 0; i < arguments.length - 1; i++) {
	      args.push(arguments[i]);
	    }

	    var level = 1;
	    if (options.hash.level != null) {
	      level = options.hash.level;
	    } else if (options.data && options.data.level != null) {
	      level = options.data.level;
	    }
	    args[0] = level;

	    instance.log.apply(instance, args);
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 13 */
/***/ function(module, exports) {

	'use strict';

	exports.__esModule = true;

	exports['default'] = function (instance) {
	  instance.registerHelper('lookup', function (obj, field) {
	    return obj && obj[field];
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _utils = __webpack_require__(5);

	exports['default'] = function (instance) {
	  instance.registerHelper('with', function (context, options) {
	    if (_utils.isFunction(context)) {
	      context = context.call(this);
	    }

	    var fn = options.fn;

	    if (!_utils.isEmpty(context)) {
	      var data = options.data;
	      if (options.data && options.ids) {
	        data = _utils.createFrame(options.data);
	        data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
	      }

	      return fn(context, {
	        data: data,
	        blockParams: _utils.blockParams([context], [data && data.contextPath])
	      });
	    } else {
	      return options.inverse(this);
	    }
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;
	exports.registerDefaultDecorators = registerDefaultDecorators;

	var _decoratorsInline = __webpack_require__(16);

	var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);

	function registerDefaultDecorators(instance) {
	  _decoratorsInline2['default'](instance);
	}

/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _utils = __webpack_require__(5);

	exports['default'] = function (instance) {
	  instance.registerDecorator('inline', function (fn, props, container, options) {
	    var ret = fn;
	    if (!props.partials) {
	      props.partials = {};
	      ret = function (context, options) {
	        // Create a new partials stack frame prior to exec.
	        var original = container.partials;
	        container.partials = _utils.extend({}, original, props.partials);
	        var ret = fn(context, options);
	        container.partials = original;
	        return ret;
	      };
	    }

	    props.partials[options.args[0]] = options.fn;

	    return ret;
	  });
	};

	module.exports = exports['default'];

/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _utils = __webpack_require__(5);

	var logger = {
	  methodMap: ['debug', 'info', 'warn', 'error'],
	  level: 'info',

	  // Maps a given level value to the `methodMap` indexes above.
	  lookupLevel: function lookupLevel(level) {
	    if (typeof level === 'string') {
	      var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
	      if (levelMap >= 0) {
	        level = levelMap;
	      } else {
	        level = parseInt(level, 10);
	      }
	    }

	    return level;
	  },

	  // Can be overridden in the host environment
	  log: function log(level) {
	    level = logger.lookupLevel(level);

	    if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
	      var method = logger.methodMap[level];
	      if (!console[method]) {
	        // eslint-disable-line no-console
	        method = 'log';
	      }

	      for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
	        message[_key - 1] = arguments[_key];
	      }

	      console[method].apply(console, message); // eslint-disable-line no-console
	    }
	  }
	};

	exports['default'] = logger;
	module.exports = exports['default'];

/***/ },
/* 18 */
/***/ function(module, exports) {

	// Build out our basic SafeString type
	'use strict';

	exports.__esModule = true;
	function SafeString(string) {
	  this.string = string;
	}

	SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
	  return '' + this.string;
	};

	exports['default'] = SafeString;
	module.exports = exports['default'];

/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireWildcard = __webpack_require__(3)['default'];

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;
	exports.checkRevision = checkRevision;
	exports.template = template;
	exports.wrapProgram = wrapProgram;
	exports.resolvePartial = resolvePartial;
	exports.invokePartial = invokePartial;
	exports.noop = noop;

	var _utils = __webpack_require__(5);

	var Utils = _interopRequireWildcard(_utils);

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	var _base = __webpack_require__(4);

	function checkRevision(compilerInfo) {
	  var compilerRevision = compilerInfo && compilerInfo[0] || 1,
	      currentRevision = _base.COMPILER_REVISION;

	  if (compilerRevision !== currentRevision) {
	    if (compilerRevision < currentRevision) {
	      var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
	          compilerVersions = _base.REVISION_CHANGES[compilerRevision];
	      throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
	    } else {
	      // Use the embedded version info since the runtime doesn't know about this revision yet
	      throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
	    }
	  }
	}

	function template(templateSpec, env) {
	  /* istanbul ignore next */
	  if (!env) {
	    throw new _exception2['default']('No environment passed to template');
	  }
	  if (!templateSpec || !templateSpec.main) {
	    throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
	  }

	  templateSpec.main.decorator = templateSpec.main_d;

	  // Note: Using env.VM references rather than local var references throughout this section to allow
	  // for external users to override these as psuedo-supported APIs.
	  env.VM.checkRevision(templateSpec.compiler);

	  function invokePartialWrapper(partial, context, options) {
	    if (options.hash) {
	      context = Utils.extend({}, context, options.hash);
	      if (options.ids) {
	        options.ids[0] = true;
	      }
	    }

	    partial = env.VM.resolvePartial.call(this, partial, context, options);
	    var result = env.VM.invokePartial.call(this, partial, context, options);

	    if (result == null && env.compile) {
	      options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
	      result = options.partials[options.name](context, options);
	    }
	    if (result != null) {
	      if (options.indent) {
	        var lines = result.split('\n');
	        for (var i = 0, l = lines.length; i < l; i++) {
	          if (!lines[i] && i + 1 === l) {
	            break;
	          }

	          lines[i] = options.indent + lines[i];
	        }
	        result = lines.join('\n');
	      }
	      return result;
	    } else {
	      throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
	    }
	  }

	  // Just add water
	  var container = {
	    strict: function strict(obj, name) {
	      if (!(name in obj)) {
	        throw new _exception2['default']('"' + name + '" not defined in ' + obj);
	      }
	      return obj[name];
	    },
	    lookup: function lookup(depths, name) {
	      var len = depths.length;
	      for (var i = 0; i < len; i++) {
	        if (depths[i] && depths[i][name] != null) {
	          return depths[i][name];
	        }
	      }
	    },
	    lambda: function lambda(current, context) {
	      return typeof current === 'function' ? current.call(context) : current;
	    },

	    escapeExpression: Utils.escapeExpression,
	    invokePartial: invokePartialWrapper,

	    fn: function fn(i) {
	      var ret = templateSpec[i];
	      ret.decorator = templateSpec[i + '_d'];
	      return ret;
	    },

	    programs: [],
	    program: function program(i, data, declaredBlockParams, blockParams, depths) {
	      var programWrapper = this.programs[i],
	          fn = this.fn(i);
	      if (data || depths || blockParams || declaredBlockParams) {
	        programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
	      } else if (!programWrapper) {
	        programWrapper = this.programs[i] = wrapProgram(this, i, fn);
	      }
	      return programWrapper;
	    },

	    data: function data(value, depth) {
	      while (value && depth--) {
	        value = value._parent;
	      }
	      return value;
	    },
	    merge: function merge(param, common) {
	      var obj = param || common;

	      if (param && common && param !== common) {
	        obj = Utils.extend({}, common, param);
	      }

	      return obj;
	    },

	    noop: env.VM.noop,
	    compilerInfo: templateSpec.compiler
	  };

	  function ret(context) {
	    var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

	    var data = options.data;

	    ret._setup(options);
	    if (!options.partial && templateSpec.useData) {
	      data = initData(context, data);
	    }
	    var depths = undefined,
	        blockParams = templateSpec.useBlockParams ? [] : undefined;
	    if (templateSpec.useDepths) {
	      if (options.depths) {
	        depths = context !== options.depths[0] ? [context].concat(options.depths) : options.depths;
	      } else {
	        depths = [context];
	      }
	    }

	    function main(context /*, options*/) {
	      return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
	    }
	    main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
	    return main(context, options);
	  }
	  ret.isTop = true;

	  ret._setup = function (options) {
	    if (!options.partial) {
	      container.helpers = container.merge(options.helpers, env.helpers);

	      if (templateSpec.usePartial) {
	        container.partials = container.merge(options.partials, env.partials);
	      }
	      if (templateSpec.usePartial || templateSpec.useDecorators) {
	        container.decorators = container.merge(options.decorators, env.decorators);
	      }
	    } else {
	      container.helpers = options.helpers;
	      container.partials = options.partials;
	      container.decorators = options.decorators;
	    }
	  };

	  ret._child = function (i, data, blockParams, depths) {
	    if (templateSpec.useBlockParams && !blockParams) {
	      throw new _exception2['default']('must pass block params');
	    }
	    if (templateSpec.useDepths && !depths) {
	      throw new _exception2['default']('must pass parent depths');
	    }

	    return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
	  };
	  return ret;
	}

	function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
	  function prog(context) {
	    var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

	    var currentDepths = depths;
	    if (depths && context !== depths[0]) {
	      currentDepths = [context].concat(depths);
	    }

	    return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
	  }

	  prog = executeDecorators(fn, prog, container, depths, data, blockParams);

	  prog.program = i;
	  prog.depth = depths ? depths.length : 0;
	  prog.blockParams = declaredBlockParams || 0;
	  return prog;
	}

	function resolvePartial(partial, context, options) {
	  if (!partial) {
	    if (options.name === '@partial-block') {
	      partial = options.data['partial-block'];
	    } else {
	      partial = options.partials[options.name];
	    }
	  } else if (!partial.call && !options.name) {
	    // This is a dynamic partial that returned a string
	    options.name = partial;
	    partial = options.partials[partial];
	  }
	  return partial;
	}

	function invokePartial(partial, context, options) {
	  options.partial = true;
	  if (options.ids) {
	    options.data.contextPath = options.ids[0] || options.data.contextPath;
	  }

	  var partialBlock = undefined;
	  if (options.fn && options.fn !== noop) {
	    options.data = _base.createFrame(options.data);
	    partialBlock = options.data['partial-block'] = options.fn;

	    if (partialBlock.partials) {
	      options.partials = Utils.extend({}, options.partials, partialBlock.partials);
	    }
	  }

	  if (partial === undefined && partialBlock) {
	    partial = partialBlock;
	  }

	  if (partial === undefined) {
	    throw new _exception2['default']('The partial ' + options.name + ' could not be found');
	  } else if (partial instanceof Function) {
	    return partial(context, options);
	  }
	}

	function noop() {
	  return '';
	}

	function initData(context, data) {
	  if (!data || !('root' in data)) {
	    data = data ? _base.createFrame(data) : {};
	    data.root = context;
	  }
	  return data;
	}

	function executeDecorators(fn, prog, container, depths, data, blockParams) {
	  if (fn.decorator) {
	    var props = {};
	    prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
	    Utils.extend(prog, props);
	  }
	  return prog;
	}

/***/ },
/* 20 */
/***/ function(module, exports) {

	/* WEBPACK VAR INJECTION */(function(global) {/* global window */
	'use strict';

	exports.__esModule = true;

	exports['default'] = function (Handlebars) {
	  /* istanbul ignore next */
	  var root = typeof global !== 'undefined' ? global : window,
	      $Handlebars = root.Handlebars;
	  /* istanbul ignore next */
	  Handlebars.noConflict = function () {
	    if (root.Handlebars === Handlebars) {
	      root.Handlebars = $Handlebars;
	    }
	    return Handlebars;
	  };
	};

	module.exports = exports['default'];
	/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))

/***/ },
/* 21 */
/***/ function(module, exports) {

	'use strict';

	exports.__esModule = true;
	var AST = {
	  // Public API used to evaluate derived attributes regarding AST nodes
	  helpers: {
	    // a mustache is definitely a helper if:
	    // * it is an eligible helper, and
	    // * it has at least one parameter or hash segment
	    helperExpression: function helperExpression(node) {
	      return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
	    },

	    scopedId: function scopedId(path) {
	      return (/^\.|this\b/.test(path.original)
	      );
	    },

	    // an ID is simple if it only has one part, and that part is not
	    // `..` or `this`.
	    simpleId: function simpleId(path) {
	      return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
	    }
	  }
	};

	// Must be exported as an object rather than the root of the module as the jison lexer
	// must modify the object to operate properly.
	exports['default'] = AST;
	module.exports = exports['default'];

/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	var _interopRequireWildcard = __webpack_require__(3)['default'];

	exports.__esModule = true;
	exports.parse = parse;

	var _parser = __webpack_require__(23);

	var _parser2 = _interopRequireDefault(_parser);

	var _whitespaceControl = __webpack_require__(24);

	var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);

	var _helpers = __webpack_require__(26);

	var Helpers = _interopRequireWildcard(_helpers);

	var _utils = __webpack_require__(5);

	exports.parser = _parser2['default'];

	var yy = {};
	_utils.extend(yy, Helpers);

	function parse(input, options) {
	  // Just return if an already-compiled AST was passed in.
	  if (input.type === 'Program') {
	    return input;
	  }

	  _parser2['default'].yy = yy;

	  // Altering the shared object here, but this is ok as parser is a sync operation
	  yy.locInfo = function (locInfo) {
	    return new yy.SourceLocation(options && options.srcName, locInfo);
	  };

	  var strip = new _whitespaceControl2['default'](options);
	  return strip.accept(_parser2['default'].parse(input));
	}

/***/ },
/* 23 */
/***/ function(module, exports) {

	/* istanbul ignore next */
	/* Jison generated parser */
	"use strict";

	var handlebars = (function () {
	    var parser = { trace: function trace() {},
	        yy: {},
	        symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition_plus0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 },
	        terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" },
	        productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 1], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]],
	        performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
	        /**/) {

	            var $0 = $$.length - 1;
	            switch (yystate) {
	                case 1:
	                    return $$[$0 - 1];
	                    break;
	                case 2:
	                    this.$ = yy.prepareProgram($$[$0]);
	                    break;
	                case 3:
	                    this.$ = $$[$0];
	                    break;
	                case 4:
	                    this.$ = $$[$0];
	                    break;
	                case 5:
	                    this.$ = $$[$0];
	                    break;
	                case 6:
	                    this.$ = $$[$0];
	                    break;
	                case 7:
	                    this.$ = $$[$0];
	                    break;
	                case 8:
	                    this.$ = $$[$0];
	                    break;
	                case 9:
	                    this.$ = {
	                        type: 'CommentStatement',
	                        value: yy.stripComment($$[$0]),
	                        strip: yy.stripFlags($$[$0], $$[$0]),
	                        loc: yy.locInfo(this._$)
	                    };

	                    break;
	                case 10:
	                    this.$ = {
	                        type: 'ContentStatement',
	                        original: $$[$0],
	                        value: $$[$0],
	                        loc: yy.locInfo(this._$)
	                    };

	                    break;
	                case 11:
	                    this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
	                    break;
	                case 12:
	                    this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
	                    break;
	                case 13:
	                    this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
	                    break;
	                case 14:
	                    this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
	                    break;
	                case 15:
	                    this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
	                    break;
	                case 16:
	                    this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
	                    break;
	                case 17:
	                    this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
	                    break;
	                case 18:
	                    this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
	                    break;
	                case 19:
	                    var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
	                        program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
	                    program.chained = true;

	                    this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };

	                    break;
	                case 20:
	                    this.$ = $$[$0];
	                    break;
	                case 21:
	                    this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
	                    break;
	                case 22:
	                    this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
	                    break;
	                case 23:
	                    this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
	                    break;
	                case 24:
	                    this.$ = {
	                        type: 'PartialStatement',
	                        name: $$[$0 - 3],
	                        params: $$[$0 - 2],
	                        hash: $$[$0 - 1],
	                        indent: '',
	                        strip: yy.stripFlags($$[$0 - 4], $$[$0]),
	                        loc: yy.locInfo(this._$)
	                    };

	                    break;
	                case 25:
	                    this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
	                    break;
	                case 26:
	                    this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
	                    break;
	                case 27:
	                    this.$ = $$[$0];
	                    break;
	                case 28:
	                    this.$ = $$[$0];
	                    break;
	                case 29:
	                    this.$ = {
	                        type: 'SubExpression',
	                        path: $$[$0 - 3],
	                        params: $$[$0 - 2],
	                        hash: $$[$0 - 1],
	                        loc: yy.locInfo(this._$)
	                    };

	                    break;
	                case 30:
	                    this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
	                    break;
	                case 31:
	                    this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
	                    break;
	                case 32:
	                    this.$ = yy.id($$[$0 - 1]);
	                    break;
	                case 33:
	                    this.$ = $$[$0];
	                    break;
	                case 34:
	                    this.$ = $$[$0];
	                    break;
	                case 35:
	                    this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
	                    break;
	                case 36:
	                    this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
	                    break;
	                case 37:
	                    this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
	                    break;
	                case 38:
	                    this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
	                    break;
	                case 39:
	                    this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
	                    break;
	                case 40:
	                    this.$ = $$[$0];
	                    break;
	                case 41:
	                    this.$ = $$[$0];
	                    break;
	                case 42:
	                    this.$ = yy.preparePath(true, $$[$0], this._$);
	                    break;
	                case 43:
	                    this.$ = yy.preparePath(false, $$[$0], this._$);
	                    break;
	                case 44:
	                    $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
	                    break;
	                case 45:
	                    this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
	                    break;
	                case 46:
	                    this.$ = [];
	                    break;
	                case 47:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 48:
	                    this.$ = [$$[$0]];
	                    break;
	                case 49:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 50:
	                    this.$ = [];
	                    break;
	                case 51:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 58:
	                    this.$ = [];
	                    break;
	                case 59:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 64:
	                    this.$ = [];
	                    break;
	                case 65:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 70:
	                    this.$ = [];
	                    break;
	                case 71:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 78:
	                    this.$ = [];
	                    break;
	                case 79:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 82:
	                    this.$ = [];
	                    break;
	                case 83:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 86:
	                    this.$ = [];
	                    break;
	                case 87:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 90:
	                    this.$ = [];
	                    break;
	                case 91:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 94:
	                    this.$ = [];
	                    break;
	                case 95:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 98:
	                    this.$ = [$$[$0]];
	                    break;
	                case 99:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	                case 100:
	                    this.$ = [$$[$0]];
	                    break;
	                case 101:
	                    $$[$0 - 1].push($$[$0]);
	                    break;
	            }
	        },
	        table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 13: 40, 15: [1, 20], 17: 39 }, { 20: 42, 56: 41, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 45, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 48, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 42, 56: 49, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 50, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 51] }, { 72: [1, 35], 86: 52 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 53, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 54, 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 55, 47: [2, 54] }, { 28: 60, 43: 61, 44: [1, 59], 47: [2, 56] }, { 13: 63, 15: [1, 20], 18: [1, 62] }, { 15: [2, 48], 18: [2, 48] }, { 33: [2, 86], 57: 64, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 65, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 66, 47: [1, 67] }, { 30: 68, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 69, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 70, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 71, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 75, 33: [2, 80], 50: 72, 63: 73, 64: 76, 65: [1, 44], 69: 74, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 80] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 51] }, { 20: 75, 53: 81, 54: [2, 84], 63: 82, 64: 76, 65: [1, 44], 69: 83, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 84, 47: [1, 67] }, { 47: [2, 55] }, { 4: 85, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 86, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 87, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 88, 47: [1, 67] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 75, 33: [2, 88], 58: 89, 63: 90, 64: 76, 65: [1, 44], 69: 91, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 92, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 93, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 31: 94, 33: [2, 60], 63: 95, 64: 76, 65: [1, 44], 69: 96, 70: 77, 71: 78, 72: [1, 79], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 66], 36: 97, 63: 98, 64: 76, 65: [1, 44], 69: 99, 70: 77, 71: 78, 72: [1, 79], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 22: 100, 23: [2, 52], 63: 101, 64: 76, 65: [1, 44], 69: 102, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 92], 62: 103, 63: 104, 64: 76, 65: [1, 44], 69: 105, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 106] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 107, 72: [1, 108], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 109], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 110] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 112, 46: 111, 47: [2, 76] }, { 33: [2, 70], 40: 113, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 114] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 75, 63: 116, 64: 76, 65: [1, 44], 67: 115, 68: [2, 96], 69: 117, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 118] }, { 32: 119, 33: [2, 62], 74: 120, 75: [1, 121] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 122, 74: 123, 75: [1, 121] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 124] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 125] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 109] }, { 20: 75, 63: 126, 64: 76, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 75, 33: [2, 72], 41: 127, 63: 128, 64: 76, 65: [1, 44], 69: 129, 70: 77, 71: 78, 72: [1, 79], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 130] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 131] }, { 33: [2, 63] }, { 72: [1, 133], 76: 132 }, { 33: [1, 134] }, { 33: [2, 69] }, { 15: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 135, 74: 136, 75: [1, 121] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 138], 77: [1, 137] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 139] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }],
	        defaultActions: { 4: [2, 1], 55: [2, 55], 57: [2, 20], 61: [2, 57], 74: [2, 81], 83: [2, 85], 87: [2, 18], 91: [2, 89], 102: [2, 53], 105: [2, 93], 111: [2, 19], 112: [2, 77], 117: [2, 97], 120: [2, 63], 123: [2, 69], 124: [2, 12], 136: [2, 75], 137: [2, 32] },
	        parseError: function parseError(str, hash) {
	            throw new Error(str);
	        },
	        parse: function parse(input) {
	            var self = this,
	                stack = [0],
	                vstack = [null],
	                lstack = [],
	                table = this.table,
	                yytext = "",
	                yylineno = 0,
	                yyleng = 0,
	                recovering = 0,
	                TERROR = 2,
	                EOF = 1;
	            this.lexer.setInput(input);
	            this.lexer.yy = this.yy;
	            this.yy.lexer = this.lexer;
	            this.yy.parser = this;
	            if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
	            var yyloc = this.lexer.yylloc;
	            lstack.push(yyloc);
	            var ranges = this.lexer.options && this.lexer.options.ranges;
	            if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
	            function popStack(n) {
	                stack.length = stack.length - 2 * n;
	                vstack.length = vstack.length - n;
	                lstack.length = lstack.length - n;
	            }
	            function lex() {
	                var token;
	                token = self.lexer.lex() || 1;
	                if (typeof token !== "number") {
	                    token = self.symbols_[token] || token;
	                }
	                return token;
	            }
	            var symbol,
	                preErrorSymbol,
	                state,
	                action,
	                a,
	                r,
	                yyval = {},
	                p,
	                len,
	                newState,
	                expected;
	            while (true) {
	                state = stack[stack.length - 1];
	                if (this.defaultActions[state]) {
	                    action = this.defaultActions[state];
	                } else {
	                    if (symbol === null || typeof symbol == "undefined") {
	                        symbol = lex();
	                    }
	                    action = table[state] && table[state][symbol];
	                }
	                if (typeof action === "undefined" || !action.length || !action[0]) {
	                    var errStr = "";
	                    if (!recovering) {
	                        expected = [];
	                        for (p in table[state]) if (this.terminals_[p] && p > 2) {
	                            expected.push("'" + this.terminals_[p] + "'");
	                        }
	                        if (this.lexer.showPosition) {
	                            errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
	                        } else {
	                            errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
	                        }
	                        this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
	                    }
	                }
	                if (action[0] instanceof Array && action.length > 1) {
	                    throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
	                }
	                switch (action[0]) {
	                    case 1:
	                        stack.push(symbol);
	                        vstack.push(this.lexer.yytext);
	                        lstack.push(this.lexer.yylloc);
	                        stack.push(action[1]);
	                        symbol = null;
	                        if (!preErrorSymbol) {
	                            yyleng = this.lexer.yyleng;
	                            yytext = this.lexer.yytext;
	                            yylineno = this.lexer.yylineno;
	                            yyloc = this.lexer.yylloc;
	                            if (recovering > 0) recovering--;
	                        } else {
	                            symbol = preErrorSymbol;
	                            preErrorSymbol = null;
	                        }
	                        break;
	                    case 2:
	                        len = this.productions_[action[1]][1];
	                        yyval.$ = vstack[vstack.length - len];
	                        yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
	                        if (ranges) {
	                            yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
	                        }
	                        r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
	                        if (typeof r !== "undefined") {
	                            return r;
	                        }
	                        if (len) {
	                            stack = stack.slice(0, -1 * len * 2);
	                            vstack = vstack.slice(0, -1 * len);
	                            lstack = lstack.slice(0, -1 * len);
	                        }
	                        stack.push(this.productions_[action[1]][0]);
	                        vstack.push(yyval.$);
	                        lstack.push(yyval._$);
	                        newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
	                        stack.push(newState);
	                        break;
	                    case 3:
	                        return true;
	                }
	            }
	            return true;
	        }
	    };
	    /* Jison generated lexer */
	    var lexer = (function () {
	        var lexer = { EOF: 1,
	            parseError: function parseError(str, hash) {
	                if (this.yy.parser) {
	                    this.yy.parser.parseError(str, hash);
	                } else {
	                    throw new Error(str);
	                }
	            },
	            setInput: function setInput(input) {
	                this._input = input;
	                this._more = this._less = this.done = false;
	                this.yylineno = this.yyleng = 0;
	                this.yytext = this.matched = this.match = '';
	                this.conditionStack = ['INITIAL'];
	                this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
	                if (this.options.ranges) this.yylloc.range = [0, 0];
	                this.offset = 0;
	                return this;
	            },
	            input: function input() {
	                var ch = this._input[0];
	                this.yytext += ch;
	                this.yyleng++;
	                this.offset++;
	                this.match += ch;
	                this.matched += ch;
	                var lines = ch.match(/(?:\r\n?|\n).*/g);
	                if (lines) {
	                    this.yylineno++;
	                    this.yylloc.last_line++;
	                } else {
	                    this.yylloc.last_column++;
	                }
	                if (this.options.ranges) this.yylloc.range[1]++;

	                this._input = this._input.slice(1);
	                return ch;
	            },
	            unput: function unput(ch) {
	                var len = ch.length;
	                var lines = ch.split(/(?:\r\n?|\n)/g);

	                this._input = ch + this._input;
	                this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
	                //this.yyleng -= len;
	                this.offset -= len;
	                var oldLines = this.match.split(/(?:\r\n?|\n)/g);
	                this.match = this.match.substr(0, this.match.length - 1);
	                this.matched = this.matched.substr(0, this.matched.length - 1);

	                if (lines.length - 1) this.yylineno -= lines.length - 1;
	                var r = this.yylloc.range;

	                this.yylloc = { first_line: this.yylloc.first_line,
	                    last_line: this.yylineno + 1,
	                    first_column: this.yylloc.first_column,
	                    last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
	                };

	                if (this.options.ranges) {
	                    this.yylloc.range = [r[0], r[0] + this.yyleng - len];
	                }
	                return this;
	            },
	            more: function more() {
	                this._more = true;
	                return this;
	            },
	            less: function less(n) {
	                this.unput(this.match.slice(n));
	            },
	            pastInput: function pastInput() {
	                var past = this.matched.substr(0, this.matched.length - this.match.length);
	                return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
	            },
	            upcomingInput: function upcomingInput() {
	                var next = this.match;
	                if (next.length < 20) {
	                    next += this._input.substr(0, 20 - next.length);
	                }
	                return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
	            },
	            showPosition: function showPosition() {
	                var pre = this.pastInput();
	                var c = new Array(pre.length + 1).join("-");
	                return pre + this.upcomingInput() + "\n" + c + "^";
	            },
	            next: function next() {
	                if (this.done) {
	                    return this.EOF;
	                }
	                if (!this._input) this.done = true;

	                var token, match, tempMatch, index, col, lines;
	                if (!this._more) {
	                    this.yytext = '';
	                    this.match = '';
	                }
	                var rules = this._currentRules();
	                for (var i = 0; i < rules.length; i++) {
	                    tempMatch = this._input.match(this.rules[rules[i]]);
	                    if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
	                        match = tempMatch;
	                        index = i;
	                        if (!this.options.flex) break;
	                    }
	                }
	                if (match) {
	                    lines = match[0].match(/(?:\r\n?|\n).*/g);
	                    if (lines) this.yylineno += lines.length;
	                    this.yylloc = { first_line: this.yylloc.last_line,
	                        last_line: this.yylineno + 1,
	                        first_column: this.yylloc.last_column,
	                        last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
	                    this.yytext += match[0];
	                    this.match += match[0];
	                    this.matches = match;
	                    this.yyleng = this.yytext.length;
	                    if (this.options.ranges) {
	                        this.yylloc.range = [this.offset, this.offset += this.yyleng];
	                    }
	                    this._more = false;
	                    this._input = this._input.slice(match[0].length);
	                    this.matched += match[0];
	                    token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
	                    if (this.done && this._input) this.done = false;
	                    if (token) return token;else return;
	                }
	                if (this._input === "") {
	                    return this.EOF;
	                } else {
	                    return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
	                }
	            },
	            lex: function lex() {
	                var r = this.next();
	                if (typeof r !== 'undefined') {
	                    return r;
	                } else {
	                    return this.lex();
	                }
	            },
	            begin: function begin(condition) {
	                this.conditionStack.push(condition);
	            },
	            popState: function popState() {
	                return this.conditionStack.pop();
	            },
	            _currentRules: function _currentRules() {
	                return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
	            },
	            topState: function topState() {
	                return this.conditionStack[this.conditionStack.length - 2];
	            },
	            pushState: function begin(condition) {
	                this.begin(condition);
	            } };
	        lexer.options = {};
	        lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
	        /**/) {

	            function strip(start, end) {
	                return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
	            }

	            var YYSTATE = YY_START;
	            switch ($avoiding_name_collisions) {
	                case 0:
	                    if (yy_.yytext.slice(-2) === "\\\\") {
	                        strip(0, 1);
	                        this.begin("mu");
	                    } else if (yy_.yytext.slice(-1) === "\\") {
	                        strip(0, 1);
	                        this.begin("emu");
	                    } else {
	                        this.begin("mu");
	                    }
	                    if (yy_.yytext) return 15;

	                    break;
	                case 1:
	                    return 15;
	                    break;
	                case 2:
	                    this.popState();
	                    return 15;

	                    break;
	                case 3:
	                    this.begin('raw');return 15;
	                    break;
	                case 4:
	                    this.popState();
	                    // Should be using `this.topState()` below, but it currently
	                    // returns the second top instead of the first top. Opened an
	                    // issue about it at https://github.com/zaach/jison/issues/291
	                    if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
	                        return 15;
	                    } else {
	                        yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
	                        return 'END_RAW_BLOCK';
	                    }

	                    break;
	                case 5:
	                    return 15;
	                    break;
	                case 6:
	                    this.popState();
	                    return 14;

	                    break;
	                case 7:
	                    return 65;
	                    break;
	                case 8:
	                    return 68;
	                    break;
	                case 9:
	                    return 19;
	                    break;
	                case 10:
	                    this.popState();
	                    this.begin('raw');
	                    return 23;

	                    break;
	                case 11:
	                    return 55;
	                    break;
	                case 12:
	                    return 60;
	                    break;
	                case 13:
	                    return 29;
	                    break;
	                case 14:
	                    return 47;
	                    break;
	                case 15:
	                    this.popState();return 44;
	                    break;
	                case 16:
	                    this.popState();return 44;
	                    break;
	                case 17:
	                    return 34;
	                    break;
	                case 18:
	                    return 39;
	                    break;
	                case 19:
	                    return 51;
	                    break;
	                case 20:
	                    return 48;
	                    break;
	                case 21:
	                    this.unput(yy_.yytext);
	                    this.popState();
	                    this.begin('com');

	                    break;
	                case 22:
	                    this.popState();
	                    return 14;

	                    break;
	                case 23:
	                    return 48;
	                    break;
	                case 24:
	                    return 73;
	                    break;
	                case 25:
	                    return 72;
	                    break;
	                case 26:
	                    return 72;
	                    break;
	                case 27:
	                    return 87;
	                    break;
	                case 28:
	                    // ignore whitespace
	                    break;
	                case 29:
	                    this.popState();return 54;
	                    break;
	                case 30:
	                    this.popState();return 33;
	                    break;
	                case 31:
	                    yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
	                    break;
	                case 32:
	                    yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
	                    break;
	                case 33:
	                    return 85;
	                    break;
	                case 34:
	                    return 82;
	                    break;
	                case 35:
	                    return 82;
	                    break;
	                case 36:
	                    return 83;
	                    break;
	                case 37:
	                    return 84;
	                    break;
	                case 38:
	                    return 81;
	                    break;
	                case 39:
	                    return 75;
	                    break;
	                case 40:
	                    return 77;
	                    break;
	                case 41:
	                    return 72;
	                    break;
	                case 42:
	                    yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
	                    break;
	                case 43:
	                    return 'INVALID';
	                    break;
	                case 44:
	                    return 5;
	                    break;
	            }
	        };
	        lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
	        lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
	        return lexer;
	    })();
	    parser.lexer = lexer;
	    function Parser() {
	        this.yy = {};
	    }Parser.prototype = parser;parser.Parser = Parser;
	    return new Parser();
	})();exports.__esModule = true;
	exports['default'] = handlebars;

/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;

	var _visitor = __webpack_require__(25);

	var _visitor2 = _interopRequireDefault(_visitor);

	function WhitespaceControl() {
	  var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

	  this.options = options;
	}
	WhitespaceControl.prototype = new _visitor2['default']();

	WhitespaceControl.prototype.Program = function (program) {
	  var doStandalone = !this.options.ignoreStandalone;

	  var isRoot = !this.isRootSeen;
	  this.isRootSeen = true;

	  var body = program.body;
	  for (var i = 0, l = body.length; i < l; i++) {
	    var current = body[i],
	        strip = this.accept(current);

	    if (!strip) {
	      continue;
	    }

	    var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
	        _isNextWhitespace = isNextWhitespace(body, i, isRoot),
	        openStandalone = strip.openStandalone && _isPrevWhitespace,
	        closeStandalone = strip.closeStandalone && _isNextWhitespace,
	        inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;

	    if (strip.close) {
	      omitRight(body, i, true);
	    }
	    if (strip.open) {
	      omitLeft(body, i, true);
	    }

	    if (doStandalone && inlineStandalone) {
	      omitRight(body, i);

	      if (omitLeft(body, i)) {
	        // If we are on a standalone node, save the indent info for partials
	        if (current.type === 'PartialStatement') {
	          // Pull out the whitespace from the final line
	          current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
	        }
	      }
	    }
	    if (doStandalone && openStandalone) {
	      omitRight((current.program || current.inverse).body);

	      // Strip out the previous content node if it's whitespace only
	      omitLeft(body, i);
	    }
	    if (doStandalone && closeStandalone) {
	      // Always strip the next node
	      omitRight(body, i);

	      omitLeft((current.inverse || current.program).body);
	    }
	  }

	  return program;
	};

	WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
	  this.accept(block.program);
	  this.accept(block.inverse);

	  // Find the inverse program that is involed with whitespace stripping.
	  var program = block.program || block.inverse,
	      inverse = block.program && block.inverse,
	      firstInverse = inverse,
	      lastInverse = inverse;

	  if (inverse && inverse.chained) {
	    firstInverse = inverse.body[0].program;

	    // Walk the inverse chain to find the last inverse that is actually in the chain.
	    while (lastInverse.chained) {
	      lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
	    }
	  }

	  var strip = {
	    open: block.openStrip.open,
	    close: block.closeStrip.close,

	    // Determine the standalone candiacy. Basically flag our content as being possibly standalone
	    // so our parent can determine if we actually are standalone
	    openStandalone: isNextWhitespace(program.body),
	    closeStandalone: isPrevWhitespace((firstInverse || program).body)
	  };

	  if (block.openStrip.close) {
	    omitRight(program.body, null, true);
	  }

	  if (inverse) {
	    var inverseStrip = block.inverseStrip;

	    if (inverseStrip.open) {
	      omitLeft(program.body, null, true);
	    }

	    if (inverseStrip.close) {
	      omitRight(firstInverse.body, null, true);
	    }
	    if (block.closeStrip.open) {
	      omitLeft(lastInverse.body, null, true);
	    }

	    // Find standalone else statments
	    if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
	      omitLeft(program.body);
	      omitRight(firstInverse.body);
	    }
	  } else if (block.closeStrip.open) {
	    omitLeft(program.body, null, true);
	  }

	  return strip;
	};

	WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
	  return mustache.strip;
	};

	WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
	  /* istanbul ignore next */
	  var strip = node.strip || {};
	  return {
	    inlineStandalone: true,
	    open: strip.open,
	    close: strip.close
	  };
	};

	function isPrevWhitespace(body, i, isRoot) {
	  if (i === undefined) {
	    i = body.length;
	  }

	  // Nodes that end with newlines are considered whitespace (but are special
	  // cased for strip operations)
	  var prev = body[i - 1],
	      sibling = body[i - 2];
	  if (!prev) {
	    return isRoot;
	  }

	  if (prev.type === 'ContentStatement') {
	    return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
	  }
	}
	function isNextWhitespace(body, i, isRoot) {
	  if (i === undefined) {
	    i = -1;
	  }

	  var next = body[i + 1],
	      sibling = body[i + 2];
	  if (!next) {
	    return isRoot;
	  }

	  if (next.type === 'ContentStatement') {
	    return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
	  }
	}

	// Marks the node to the right of the position as omitted.
	// I.e. {{foo}}' ' will mark the ' ' node as omitted.
	//
	// If i is undefined, then the first child will be marked as such.
	//
	// If mulitple is truthy then all whitespace will be stripped out until non-whitespace
	// content is met.
	function omitRight(body, i, multiple) {
	  var current = body[i == null ? 0 : i + 1];
	  if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
	    return;
	  }

	  var original = current.value;
	  current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
	  current.rightStripped = current.value !== original;
	}

	// Marks the node to the left of the position as omitted.
	// I.e. ' '{{foo}} will mark the ' ' node as omitted.
	//
	// If i is undefined then the last child will be marked as such.
	//
	// If mulitple is truthy then all whitespace will be stripped out until non-whitespace
	// content is met.
	function omitLeft(body, i, multiple) {
	  var current = body[i == null ? body.length - 1 : i - 1];
	  if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
	    return;
	  }

	  // We omit the last node if it's whitespace only and not preceeded by a non-content node.
	  var original = current.value;
	  current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
	  current.leftStripped = current.value !== original;
	  return current.leftStripped;
	}

	exports['default'] = WhitespaceControl;
	module.exports = exports['default'];

/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	function Visitor() {
	  this.parents = [];
	}

	Visitor.prototype = {
	  constructor: Visitor,
	  mutating: false,

	  // Visits a given value. If mutating, will replace the value if necessary.
	  acceptKey: function acceptKey(node, name) {
	    var value = this.accept(node[name]);
	    if (this.mutating) {
	      // Hacky sanity check: This may have a few false positives for type for the helper
	      // methods but will generally do the right thing without a lot of overhead.
	      if (value && !Visitor.prototype[value.type]) {
	        throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
	      }
	      node[name] = value;
	    }
	  },

	  // Performs an accept operation with added sanity check to ensure
	  // required keys are not removed.
	  acceptRequired: function acceptRequired(node, name) {
	    this.acceptKey(node, name);

	    if (!node[name]) {
	      throw new _exception2['default'](node.type + ' requires ' + name);
	    }
	  },

	  // Traverses a given array. If mutating, empty respnses will be removed
	  // for child elements.
	  acceptArray: function acceptArray(array) {
	    for (var i = 0, l = array.length; i < l; i++) {
	      this.acceptKey(array, i);

	      if (!array[i]) {
	        array.splice(i, 1);
	        i--;
	        l--;
	      }
	    }
	  },

	  accept: function accept(object) {
	    if (!object) {
	      return;
	    }

	    /* istanbul ignore next: Sanity code */
	    if (!this[object.type]) {
	      throw new _exception2['default']('Unknown type: ' + object.type, object);
	    }

	    if (this.current) {
	      this.parents.unshift(this.current);
	    }
	    this.current = object;

	    var ret = this[object.type](object);

	    this.current = this.parents.shift();

	    if (!this.mutating || ret) {
	      return ret;
	    } else if (ret !== false) {
	      return object;
	    }
	  },

	  Program: function Program(program) {
	    this.acceptArray(program.body);
	  },

	  MustacheStatement: visitSubExpression,
	  Decorator: visitSubExpression,

	  BlockStatement: visitBlock,
	  DecoratorBlock: visitBlock,

	  PartialStatement: visitPartial,
	  PartialBlockStatement: function PartialBlockStatement(partial) {
	    visitPartial.call(this, partial);

	    this.acceptKey(partial, 'program');
	  },

	  ContentStatement: function ContentStatement() /* content */{},
	  CommentStatement: function CommentStatement() /* comment */{},

	  SubExpression: visitSubExpression,

	  PathExpression: function PathExpression() /* path */{},

	  StringLiteral: function StringLiteral() /* string */{},
	  NumberLiteral: function NumberLiteral() /* number */{},
	  BooleanLiteral: function BooleanLiteral() /* bool */{},
	  UndefinedLiteral: function UndefinedLiteral() /* literal */{},
	  NullLiteral: function NullLiteral() /* literal */{},

	  Hash: function Hash(hash) {
	    this.acceptArray(hash.pairs);
	  },
	  HashPair: function HashPair(pair) {
	    this.acceptRequired(pair, 'value');
	  }
	};

	function visitSubExpression(mustache) {
	  this.acceptRequired(mustache, 'path');
	  this.acceptArray(mustache.params);
	  this.acceptKey(mustache, 'hash');
	}
	function visitBlock(block) {
	  visitSubExpression.call(this, block);

	  this.acceptKey(block, 'program');
	  this.acceptKey(block, 'inverse');
	}
	function visitPartial(partial) {
	  this.acceptRequired(partial, 'name');
	  this.acceptArray(partial.params);
	  this.acceptKey(partial, 'hash');
	}

	exports['default'] = Visitor;
	module.exports = exports['default'];

/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;
	exports.SourceLocation = SourceLocation;
	exports.id = id;
	exports.stripFlags = stripFlags;
	exports.stripComment = stripComment;
	exports.preparePath = preparePath;
	exports.prepareMustache = prepareMustache;
	exports.prepareRawBlock = prepareRawBlock;
	exports.prepareBlock = prepareBlock;
	exports.prepareProgram = prepareProgram;
	exports.preparePartialBlock = preparePartialBlock;

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	function validateClose(open, close) {
	  close = close.path ? close.path.original : close;

	  if (open.path.original !== close) {
	    var errorNode = { loc: open.path.loc };

	    throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
	  }
	}

	function SourceLocation(source, locInfo) {
	  this.source = source;
	  this.start = {
	    line: locInfo.first_line,
	    column: locInfo.first_column
	  };
	  this.end = {
	    line: locInfo.last_line,
	    column: locInfo.last_column
	  };
	}

	function id(token) {
	  if (/^\[.*\]$/.test(token)) {
	    return token.substr(1, token.length - 2);
	  } else {
	    return token;
	  }
	}

	function stripFlags(open, close) {
	  return {
	    open: open.charAt(2) === '~',
	    close: close.charAt(close.length - 3) === '~'
	  };
	}

	function stripComment(comment) {
	  return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
	}

	function preparePath(data, parts, loc) {
	  loc = this.locInfo(loc);

	  var original = data ? '@' : '',
	      dig = [],
	      depth = 0,
	      depthString = '';

	  for (var i = 0, l = parts.length; i < l; i++) {
	    var part = parts[i].part,

	    // If we have [] syntax then we do not treat path references as operators,
	    // i.e. foo.[this] resolves to approximately context.foo['this']
	    isLiteral = parts[i].original !== part;
	    original += (parts[i].separator || '') + part;

	    if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
	      if (dig.length > 0) {
	        throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
	      } else if (part === '..') {
	        depth++;
	        depthString += '../';
	      }
	    } else {
	      dig.push(part);
	    }
	  }

	  return {
	    type: 'PathExpression',
	    data: data,
	    depth: depth,
	    parts: dig,
	    original: original,
	    loc: loc
	  };
	}

	function prepareMustache(path, params, hash, open, strip, locInfo) {
	  // Must use charAt to support IE pre-10
	  var escapeFlag = open.charAt(3) || open.charAt(2),
	      escaped = escapeFlag !== '{' && escapeFlag !== '&';

	  var decorator = /\*/.test(open);
	  return {
	    type: decorator ? 'Decorator' : 'MustacheStatement',
	    path: path,
	    params: params,
	    hash: hash,
	    escaped: escaped,
	    strip: strip,
	    loc: this.locInfo(locInfo)
	  };
	}

	function prepareRawBlock(openRawBlock, contents, close, locInfo) {
	  validateClose(openRawBlock, close);

	  locInfo = this.locInfo(locInfo);
	  var program = {
	    type: 'Program',
	    body: contents,
	    strip: {},
	    loc: locInfo
	  };

	  return {
	    type: 'BlockStatement',
	    path: openRawBlock.path,
	    params: openRawBlock.params,
	    hash: openRawBlock.hash,
	    program: program,
	    openStrip: {},
	    inverseStrip: {},
	    closeStrip: {},
	    loc: locInfo
	  };
	}

	function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
	  if (close && close.path) {
	    validateClose(openBlock, close);
	  }

	  var decorator = /\*/.test(openBlock.open);

	  program.blockParams = openBlock.blockParams;

	  var inverse = undefined,
	      inverseStrip = undefined;

	  if (inverseAndProgram) {
	    if (decorator) {
	      throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
	    }

	    if (inverseAndProgram.chain) {
	      inverseAndProgram.program.body[0].closeStrip = close.strip;
	    }

	    inverseStrip = inverseAndProgram.strip;
	    inverse = inverseAndProgram.program;
	  }

	  if (inverted) {
	    inverted = inverse;
	    inverse = program;
	    program = inverted;
	  }

	  return {
	    type: decorator ? 'DecoratorBlock' : 'BlockStatement',
	    path: openBlock.path,
	    params: openBlock.params,
	    hash: openBlock.hash,
	    program: program,
	    inverse: inverse,
	    openStrip: openBlock.strip,
	    inverseStrip: inverseStrip,
	    closeStrip: close && close.strip,
	    loc: this.locInfo(locInfo)
	  };
	}

	function prepareProgram(statements, loc) {
	  if (!loc && statements.length) {
	    var firstLoc = statements[0].loc,
	        lastLoc = statements[statements.length - 1].loc;

	    /* istanbul ignore else */
	    if (firstLoc && lastLoc) {
	      loc = {
	        source: firstLoc.source,
	        start: {
	          line: firstLoc.start.line,
	          column: firstLoc.start.column
	        },
	        end: {
	          line: lastLoc.end.line,
	          column: lastLoc.end.column
	        }
	      };
	    }
	  }

	  return {
	    type: 'Program',
	    body: statements,
	    strip: {},
	    loc: loc
	  };
	}

	function preparePartialBlock(open, program, close, locInfo) {
	  validateClose(open, close);

	  return {
	    type: 'PartialBlockStatement',
	    name: open.path,
	    params: open.params,
	    hash: open.hash,
	    program: program,
	    openStrip: open.strip,
	    closeStrip: close && close.strip,
	    loc: this.locInfo(locInfo)
	  };
	}

/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {

	/* eslint-disable new-cap */

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;
	exports.Compiler = Compiler;
	exports.precompile = precompile;
	exports.compile = compile;

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	var _utils = __webpack_require__(5);

	var _ast = __webpack_require__(21);

	var _ast2 = _interopRequireDefault(_ast);

	var slice = [].slice;

	function Compiler() {}

	// the foundHelper register will disambiguate helper lookup from finding a
	// function in a context. This is necessary for mustache compatibility, which
	// requires that context functions in blocks are evaluated by blockHelperMissing,
	// and then proceed as if the resulting value was provided to blockHelperMissing.

	Compiler.prototype = {
	  compiler: Compiler,

	  equals: function equals(other) {
	    var len = this.opcodes.length;
	    if (other.opcodes.length !== len) {
	      return false;
	    }

	    for (var i = 0; i < len; i++) {
	      var opcode = this.opcodes[i],
	          otherOpcode = other.opcodes[i];
	      if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
	        return false;
	      }
	    }

	    // We know that length is the same between the two arrays because they are directly tied
	    // to the opcode behavior above.
	    len = this.children.length;
	    for (var i = 0; i < len; i++) {
	      if (!this.children[i].equals(other.children[i])) {
	        return false;
	      }
	    }

	    return true;
	  },

	  guid: 0,

	  compile: function compile(program, options) {
	    this.sourceNode = [];
	    this.opcodes = [];
	    this.children = [];
	    this.options = options;
	    this.stringParams = options.stringParams;
	    this.trackIds = options.trackIds;

	    options.blockParams = options.blockParams || [];

	    // These changes will propagate to the other compiler components
	    var knownHelpers = options.knownHelpers;
	    options.knownHelpers = {
	      'helperMissing': true,
	      'blockHelperMissing': true,
	      'each': true,
	      'if': true,
	      'unless': true,
	      'with': true,
	      'log': true,
	      'lookup': true
	    };
	    if (knownHelpers) {
	      for (var _name in knownHelpers) {
	        /* istanbul ignore else */
	        if (_name in knownHelpers) {
	          options.knownHelpers[_name] = knownHelpers[_name];
	        }
	      }
	    }

	    return this.accept(program);
	  },

	  compileProgram: function compileProgram(program) {
	    var childCompiler = new this.compiler(),
	        // eslint-disable-line new-cap
	    result = childCompiler.compile(program, this.options),
	        guid = this.guid++;

	    this.usePartial = this.usePartial || result.usePartial;

	    this.children[guid] = result;
	    this.useDepths = this.useDepths || result.useDepths;

	    return guid;
	  },

	  accept: function accept(node) {
	    /* istanbul ignore next: Sanity code */
	    if (!this[node.type]) {
	      throw new _exception2['default']('Unknown type: ' + node.type, node);
	    }

	    this.sourceNode.unshift(node);
	    var ret = this[node.type](node);
	    this.sourceNode.shift();
	    return ret;
	  },

	  Program: function Program(program) {
	    this.options.blockParams.unshift(program.blockParams);

	    var body = program.body,
	        bodyLength = body.length;
	    for (var i = 0; i < bodyLength; i++) {
	      this.accept(body[i]);
	    }

	    this.options.blockParams.shift();

	    this.isSimple = bodyLength === 1;
	    this.blockParams = program.blockParams ? program.blockParams.length : 0;

	    return this;
	  },

	  BlockStatement: function BlockStatement(block) {
	    transformLiteralToPath(block);

	    var program = block.program,
	        inverse = block.inverse;

	    program = program && this.compileProgram(program);
	    inverse = inverse && this.compileProgram(inverse);

	    var type = this.classifySexpr(block);

	    if (type === 'helper') {
	      this.helperSexpr(block, program, inverse);
	    } else if (type === 'simple') {
	      this.simpleSexpr(block);

	      // now that the simple mustache is resolved, we need to
	      // evaluate it by executing `blockHelperMissing`
	      this.opcode('pushProgram', program);
	      this.opcode('pushProgram', inverse);
	      this.opcode('emptyHash');
	      this.opcode('blockValue', block.path.original);
	    } else {
	      this.ambiguousSexpr(block, program, inverse);

	      // now that the simple mustache is resolved, we need to
	      // evaluate it by executing `blockHelperMissing`
	      this.opcode('pushProgram', program);
	      this.opcode('pushProgram', inverse);
	      this.opcode('emptyHash');
	      this.opcode('ambiguousBlockValue');
	    }

	    this.opcode('append');
	  },

	  DecoratorBlock: function DecoratorBlock(decorator) {
	    var program = decorator.program && this.compileProgram(decorator.program);
	    var params = this.setupFullMustacheParams(decorator, program, undefined),
	        path = decorator.path;

	    this.useDecorators = true;
	    this.opcode('registerDecorator', params.length, path.original);
	  },

	  PartialStatement: function PartialStatement(partial) {
	    this.usePartial = true;

	    var program = partial.program;
	    if (program) {
	      program = this.compileProgram(partial.program);
	    }

	    var params = partial.params;
	    if (params.length > 1) {
	      throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
	    } else if (!params.length) {
	      if (this.options.explicitPartialContext) {
	        this.opcode('pushLiteral', 'undefined');
	      } else {
	        params.push({ type: 'PathExpression', parts: [], depth: 0 });
	      }
	    }

	    var partialName = partial.name.original,
	        isDynamic = partial.name.type === 'SubExpression';
	    if (isDynamic) {
	      this.accept(partial.name);
	    }

	    this.setupFullMustacheParams(partial, program, undefined, true);

	    var indent = partial.indent || '';
	    if (this.options.preventIndent && indent) {
	      this.opcode('appendContent', indent);
	      indent = '';
	    }

	    this.opcode('invokePartial', isDynamic, partialName, indent);
	    this.opcode('append');
	  },
	  PartialBlockStatement: function PartialBlockStatement(partialBlock) {
	    this.PartialStatement(partialBlock);
	  },

	  MustacheStatement: function MustacheStatement(mustache) {
	    this.SubExpression(mustache);

	    if (mustache.escaped && !this.options.noEscape) {
	      this.opcode('appendEscaped');
	    } else {
	      this.opcode('append');
	    }
	  },
	  Decorator: function Decorator(decorator) {
	    this.DecoratorBlock(decorator);
	  },

	  ContentStatement: function ContentStatement(content) {
	    if (content.value) {
	      this.opcode('appendContent', content.value);
	    }
	  },

	  CommentStatement: function CommentStatement() {},

	  SubExpression: function SubExpression(sexpr) {
	    transformLiteralToPath(sexpr);
	    var type = this.classifySexpr(sexpr);

	    if (type === 'simple') {
	      this.simpleSexpr(sexpr);
	    } else if (type === 'helper') {
	      this.helperSexpr(sexpr);
	    } else {
	      this.ambiguousSexpr(sexpr);
	    }
	  },
	  ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
	    var path = sexpr.path,
	        name = path.parts[0],
	        isBlock = program != null || inverse != null;

	    this.opcode('getContext', path.depth);

	    this.opcode('pushProgram', program);
	    this.opcode('pushProgram', inverse);

	    path.strict = true;
	    this.accept(path);

	    this.opcode('invokeAmbiguous', name, isBlock);
	  },

	  simpleSexpr: function simpleSexpr(sexpr) {
	    var path = sexpr.path;
	    path.strict = true;
	    this.accept(path);
	    this.opcode('resolvePossibleLambda');
	  },

	  helperSexpr: function helperSexpr(sexpr, program, inverse) {
	    var params = this.setupFullMustacheParams(sexpr, program, inverse),
	        path = sexpr.path,
	        name = path.parts[0];

	    if (this.options.knownHelpers[name]) {
	      this.opcode('invokeKnownHelper', params.length, name);
	    } else if (this.options.knownHelpersOnly) {
	      throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
	    } else {
	      path.strict = true;
	      path.falsy = true;

	      this.accept(path);
	      this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
	    }
	  },

	  PathExpression: function PathExpression(path) {
	    this.addDepth(path.depth);
	    this.opcode('getContext', path.depth);

	    var name = path.parts[0],
	        scoped = _ast2['default'].helpers.scopedId(path),
	        blockParamId = !path.depth && !scoped && this.blockParamIndex(name);

	    if (blockParamId) {
	      this.opcode('lookupBlockParam', blockParamId, path.parts);
	    } else if (!name) {
	      // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
	      this.opcode('pushContext');
	    } else if (path.data) {
	      this.options.data = true;
	      this.opcode('lookupData', path.depth, path.parts, path.strict);
	    } else {
	      this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
	    }
	  },

	  StringLiteral: function StringLiteral(string) {
	    this.opcode('pushString', string.value);
	  },

	  NumberLiteral: function NumberLiteral(number) {
	    this.opcode('pushLiteral', number.value);
	  },

	  BooleanLiteral: function BooleanLiteral(bool) {
	    this.opcode('pushLiteral', bool.value);
	  },

	  UndefinedLiteral: function UndefinedLiteral() {
	    this.opcode('pushLiteral', 'undefined');
	  },

	  NullLiteral: function NullLiteral() {
	    this.opcode('pushLiteral', 'null');
	  },

	  Hash: function Hash(hash) {
	    var pairs = hash.pairs,
	        i = 0,
	        l = pairs.length;

	    this.opcode('pushHash');

	    for (; i < l; i++) {
	      this.pushParam(pairs[i].value);
	    }
	    while (i--) {
	      this.opcode('assignToHash', pairs[i].key);
	    }
	    this.opcode('popHash');
	  },

	  // HELPERS
	  opcode: function opcode(name) {
	    this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
	  },

	  addDepth: function addDepth(depth) {
	    if (!depth) {
	      return;
	    }

	    this.useDepths = true;
	  },

	  classifySexpr: function classifySexpr(sexpr) {
	    var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);

	    var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);

	    // a mustache is an eligible helper if:
	    // * its id is simple (a single part, not `this` or `..`)
	    var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);

	    // if a mustache is an eligible helper but not a definite
	    // helper, it is ambiguous, and will be resolved in a later
	    // pass or at runtime.
	    var isEligible = !isBlockParam && (isHelper || isSimple);

	    // if ambiguous, we can possibly resolve the ambiguity now
	    // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
	    if (isEligible && !isHelper) {
	      var _name2 = sexpr.path.parts[0],
	          options = this.options;

	      if (options.knownHelpers[_name2]) {
	        isHelper = true;
	      } else if (options.knownHelpersOnly) {
	        isEligible = false;
	      }
	    }

	    if (isHelper) {
	      return 'helper';
	    } else if (isEligible) {
	      return 'ambiguous';
	    } else {
	      return 'simple';
	    }
	  },

	  pushParams: function pushParams(params) {
	    for (var i = 0, l = params.length; i < l; i++) {
	      this.pushParam(params[i]);
	    }
	  },

	  pushParam: function pushParam(val) {
	    var value = val.value != null ? val.value : val.original || '';

	    if (this.stringParams) {
	      if (value.replace) {
	        value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
	      }

	      if (val.depth) {
	        this.addDepth(val.depth);
	      }
	      this.opcode('getContext', val.depth || 0);
	      this.opcode('pushStringParam', value, val.type);

	      if (val.type === 'SubExpression') {
	        // SubExpressions get evaluated and passed in
	        // in string params mode.
	        this.accept(val);
	      }
	    } else {
	      if (this.trackIds) {
	        var blockParamIndex = undefined;
	        if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
	          blockParamIndex = this.blockParamIndex(val.parts[0]);
	        }
	        if (blockParamIndex) {
	          var blockParamChild = val.parts.slice(1).join('.');
	          this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
	        } else {
	          value = val.original || value;
	          if (value.replace) {
	            value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
	          }

	          this.opcode('pushId', val.type, value);
	        }
	      }
	      this.accept(val);
	    }
	  },

	  setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
	    var params = sexpr.params;
	    this.pushParams(params);

	    this.opcode('pushProgram', program);
	    this.opcode('pushProgram', inverse);

	    if (sexpr.hash) {
	      this.accept(sexpr.hash);
	    } else {
	      this.opcode('emptyHash', omitEmpty);
	    }

	    return params;
	  },

	  blockParamIndex: function blockParamIndex(name) {
	    for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
	      var blockParams = this.options.blockParams[depth],
	          param = blockParams && _utils.indexOf(blockParams, name);
	      if (blockParams && param >= 0) {
	        return [depth, param];
	      }
	    }
	  }
	};

	function precompile(input, options, env) {
	  if (input == null || typeof input !== 'string' && input.type !== 'Program') {
	    throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
	  }

	  options = options || {};
	  if (!('data' in options)) {
	    options.data = true;
	  }
	  if (options.compat) {
	    options.useDepths = true;
	  }

	  var ast = env.parse(input, options),
	      environment = new env.Compiler().compile(ast, options);
	  return new env.JavaScriptCompiler().compile(environment, options);
	}

	function compile(input, options, env) {
	  if (options === undefined) options = {};

	  if (input == null || typeof input !== 'string' && input.type !== 'Program') {
	    throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
	  }

	  if (!('data' in options)) {
	    options.data = true;
	  }
	  if (options.compat) {
	    options.useDepths = true;
	  }

	  var compiled = undefined;

	  function compileInput() {
	    var ast = env.parse(input, options),
	        environment = new env.Compiler().compile(ast, options),
	        templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
	    return env.template(templateSpec);
	  }

	  // Template is only compiled on first use and cached after that point.
	  function ret(context, execOptions) {
	    if (!compiled) {
	      compiled = compileInput();
	    }
	    return compiled.call(this, context, execOptions);
	  }
	  ret._setup = function (setupOptions) {
	    if (!compiled) {
	      compiled = compileInput();
	    }
	    return compiled._setup(setupOptions);
	  };
	  ret._child = function (i, data, blockParams, depths) {
	    if (!compiled) {
	      compiled = compileInput();
	    }
	    return compiled._child(i, data, blockParams, depths);
	  };
	  return ret;
	}

	function argEquals(a, b) {
	  if (a === b) {
	    return true;
	  }

	  if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
	    for (var i = 0; i < a.length; i++) {
	      if (!argEquals(a[i], b[i])) {
	        return false;
	      }
	    }
	    return true;
	  }
	}

	function transformLiteralToPath(sexpr) {
	  if (!sexpr.path.parts) {
	    var literal = sexpr.path;
	    // Casting to string here to make false and 0 literal values play nicely with the rest
	    // of the system.
	    sexpr.path = {
	      type: 'PathExpression',
	      data: false,
	      depth: 0,
	      parts: [literal.original + ''],
	      original: literal.original + '',
	      loc: literal.loc
	    };
	  }
	}

/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _interopRequireDefault = __webpack_require__(1)['default'];

	exports.__esModule = true;

	var _base = __webpack_require__(4);

	var _exception = __webpack_require__(6);

	var _exception2 = _interopRequireDefault(_exception);

	var _utils = __webpack_require__(5);

	var _codeGen = __webpack_require__(29);

	var _codeGen2 = _interopRequireDefault(_codeGen);

	function Literal(value) {
	  this.value = value;
	}

	function JavaScriptCompiler() {}

	JavaScriptCompiler.prototype = {
	  // PUBLIC API: You can override these methods in a subclass to provide
	  // alternative compiled forms for name lookup and buffering semantics
	  nameLookup: function nameLookup(parent, name /* , type*/) {
	    if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
	      return [parent, '.', name];
	    } else {
	      return [parent, '[', JSON.stringify(name), ']'];
	    }
	  },
	  depthedLookup: function depthedLookup(name) {
	    return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
	  },

	  compilerInfo: function compilerInfo() {
	    var revision = _base.COMPILER_REVISION,
	        versions = _base.REVISION_CHANGES[revision];
	    return [revision, versions];
	  },

	  appendToBuffer: function appendToBuffer(source, location, explicit) {
	    // Force a source as this simplifies the merge logic.
	    if (!_utils.isArray(source)) {
	      source = [source];
	    }
	    source = this.source.wrap(source, location);

	    if (this.environment.isSimple) {
	      return ['return ', source, ';'];
	    } else if (explicit) {
	      // This is a case where the buffer operation occurs as a child of another
	      // construct, generally braces. We have to explicitly output these buffer
	      // operations to ensure that the emitted code goes in the correct location.
	      return ['buffer += ', source, ';'];
	    } else {
	      source.appendToBuffer = true;
	      return source;
	    }
	  },

	  initializeBuffer: function initializeBuffer() {
	    return this.quotedString('');
	  },
	  // END PUBLIC API

	  compile: function compile(environment, options, context, asObject) {
	    this.environment = environment;
	    this.options = options;
	    this.stringParams = this.options.stringParams;
	    this.trackIds = this.options.trackIds;
	    this.precompile = !asObject;

	    this.name = this.environment.name;
	    this.isChild = !!context;
	    this.context = context || {
	      decorators: [],
	      programs: [],
	      environments: []
	    };

	    this.preamble();

	    this.stackSlot = 0;
	    this.stackVars = [];
	    this.aliases = {};
	    this.registers = { list: [] };
	    this.hashes = [];
	    this.compileStack = [];
	    this.inlineStack = [];
	    this.blockParams = [];

	    this.compileChildren(environment, options);

	    this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
	    this.useBlockParams = this.useBlockParams || environment.useBlockParams;

	    var opcodes = environment.opcodes,
	        opcode = undefined,
	        firstLoc = undefined,
	        i = undefined,
	        l = undefined;

	    for (i = 0, l = opcodes.length; i < l; i++) {
	      opcode = opcodes[i];

	      this.source.currentLocation = opcode.loc;
	      firstLoc = firstLoc || opcode.loc;
	      this[opcode.opcode].apply(this, opcode.args);
	    }

	    // Flush any trailing content that might be pending.
	    this.source.currentLocation = firstLoc;
	    this.pushSource('');

	    /* istanbul ignore next */
	    if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
	      throw new _exception2['default']('Compile completed with content left on stack');
	    }

	    if (!this.decorators.isEmpty()) {
	      this.useDecorators = true;

	      this.decorators.prepend('var decorators = container.decorators;\n');
	      this.decorators.push('return fn;');

	      if (asObject) {
	        this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
	      } else {
	        this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
	        this.decorators.push('}\n');
	        this.decorators = this.decorators.merge();
	      }
	    } else {
	      this.decorators = undefined;
	    }

	    var fn = this.createFunctionContext(asObject);
	    if (!this.isChild) {
	      var ret = {
	        compiler: this.compilerInfo(),
	        main: fn
	      };

	      if (this.decorators) {
	        ret.main_d = this.decorators; // eslint-disable-line camelcase
	        ret.useDecorators = true;
	      }

	      var _context = this.context;
	      var programs = _context.programs;
	      var decorators = _context.decorators;

	      for (i = 0, l = programs.length; i < l; i++) {
	        if (programs[i]) {
	          ret[i] = programs[i];
	          if (decorators[i]) {
	            ret[i + '_d'] = decorators[i];
	            ret.useDecorators = true;
	          }
	        }
	      }

	      if (this.environment.usePartial) {
	        ret.usePartial = true;
	      }
	      if (this.options.data) {
	        ret.useData = true;
	      }
	      if (this.useDepths) {
	        ret.useDepths = true;
	      }
	      if (this.useBlockParams) {
	        ret.useBlockParams = true;
	      }
	      if (this.options.compat) {
	        ret.compat = true;
	      }

	      if (!asObject) {
	        ret.compiler = JSON.stringify(ret.compiler);

	        this.source.currentLocation = { start: { line: 1, column: 0 } };
	        ret = this.objectLiteral(ret);

	        if (options.srcName) {
	          ret = ret.toStringWithSourceMap({ file: options.destName });
	          ret.map = ret.map && ret.map.toString();
	        } else {
	          ret = ret.toString();
	        }
	      } else {
	        ret.compilerOptions = this.options;
	      }

	      return ret;
	    } else {
	      return fn;
	    }
	  },

	  preamble: function preamble() {
	    // track the last context pushed into place to allow skipping the
	    // getContext opcode when it would be a noop
	    this.lastContext = 0;
	    this.source = new _codeGen2['default'](this.options.srcName);
	    this.decorators = new _codeGen2['default'](this.options.srcName);
	  },

	  createFunctionContext: function createFunctionContext(asObject) {
	    var varDeclarations = '';

	    var locals = this.stackVars.concat(this.registers.list);
	    if (locals.length > 0) {
	      varDeclarations += ', ' + locals.join(', ');
	    }

	    // Generate minimizer alias mappings
	    //
	    // When using true SourceNodes, this will update all references to the given alias
	    // as the source nodes are reused in situ. For the non-source node compilation mode,
	    // aliases will not be used, but this case is already being run on the client and
	    // we aren't concern about minimizing the template size.
	    var aliasCount = 0;
	    for (var alias in this.aliases) {
	      // eslint-disable-line guard-for-in
	      var node = this.aliases[alias];

	      if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
	        varDeclarations += ', alias' + ++aliasCount + '=' + alias;
	        node.children[0] = 'alias' + aliasCount;
	      }
	    }

	    var params = ['container', 'depth0', 'helpers', 'partials', 'data'];

	    if (this.useBlockParams || this.useDepths) {
	      params.push('blockParams');
	    }
	    if (this.useDepths) {
	      params.push('depths');
	    }

	    // Perform a second pass over the output to merge content when possible
	    var source = this.mergeSource(varDeclarations);

	    if (asObject) {
	      params.push(source);

	      return Function.apply(this, params);
	    } else {
	      return this.source.wrap(['function(', params.join(','), ') {\n  ', source, '}']);
	    }
	  },
	  mergeSource: function mergeSource(varDeclarations) {
	    var isSimple = this.environment.isSimple,
	        appendOnly = !this.forceBuffer,
	        appendFirst = undefined,
	        sourceSeen = undefined,
	        bufferStart = undefined,
	        bufferEnd = undefined;
	    this.source.each(function (line) {
	      if (line.appendToBuffer) {
	        if (bufferStart) {
	          line.prepend('  + ');
	        } else {
	          bufferStart = line;
	        }
	        bufferEnd = line;
	      } else {
	        if (bufferStart) {
	          if (!sourceSeen) {
	            appendFirst = true;
	          } else {
	            bufferStart.prepend('buffer += ');
	          }
	          bufferEnd.add(';');
	          bufferStart = bufferEnd = undefined;
	        }

	        sourceSeen = true;
	        if (!isSimple) {
	          appendOnly = false;
	        }
	      }
	    });

	    if (appendOnly) {
	      if (bufferStart) {
	        bufferStart.prepend('return ');
	        bufferEnd.add(';');
	      } else if (!sourceSeen) {
	        this.source.push('return "";');
	      }
	    } else {
	      varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());

	      if (bufferStart) {
	        bufferStart.prepend('return buffer + ');
	        bufferEnd.add(';');
	      } else {
	        this.source.push('return buffer;');
	      }
	    }

	    if (varDeclarations) {
	      this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
	    }

	    return this.source.merge();
	  },

	  // [blockValue]
	  //
	  // On stack, before: hash, inverse, program, value
	  // On stack, after: return value of blockHelperMissing
	  //
	  // The purpose of this opcode is to take a block of the form
	  // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
	  // replace it on the stack with the result of properly
	  // invoking blockHelperMissing.
	  blockValue: function blockValue(name) {
	    var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
	        params = [this.contextName(0)];
	    this.setupHelperArgs(name, 0, params);

	    var blockName = this.popStack();
	    params.splice(1, 0, blockName);

	    this.push(this.source.functionCall(blockHelperMissing, 'call', params));
	  },

	  // [ambiguousBlockValue]
	  //
	  // On stack, before: hash, inverse, program, value
	  // Compiler value, before: lastHelper=value of last found helper, if any
	  // On stack, after, if no lastHelper: same as [blockValue]
	  // On stack, after, if lastHelper: value
	  ambiguousBlockValue: function ambiguousBlockValue() {
	    // We're being a bit cheeky and reusing the options value from the prior exec
	    var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
	        params = [this.contextName(0)];
	    this.setupHelperArgs('', 0, params, true);

	    this.flushInline();

	    var current = this.topStack();
	    params.splice(1, 0, current);

	    this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
	  },

	  // [appendContent]
	  //
	  // On stack, before: ...
	  // On stack, after: ...
	  //
	  // Appends the string value of `content` to the current buffer
	  appendContent: function appendContent(content) {
	    if (this.pendingContent) {
	      content = this.pendingContent + content;
	    } else {
	      this.pendingLocation = this.source.currentLocation;
	    }

	    this.pendingContent = content;
	  },

	  // [append]
	  //
	  // On stack, before: value, ...
	  // On stack, after: ...
	  //
	  // Coerces `value` to a String and appends it to the current buffer.
	  //
	  // If `value` is truthy, or 0, it is coerced into a string and appended
	  // Otherwise, the empty string is appended
	  append: function append() {
	    if (this.isInline()) {
	      this.replaceStack(function (current) {
	        return [' != null ? ', current, ' : ""'];
	      });

	      this.pushSource(this.appendToBuffer(this.popStack()));
	    } else {
	      var local = this.popStack();
	      this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
	      if (this.environment.isSimple) {
	        this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
	      }
	    }
	  },

	  // [appendEscaped]
	  //
	  // On stack, before: value, ...
	  // On stack, after: ...
	  //
	  // Escape `value` and append it to the buffer
	  appendEscaped: function appendEscaped() {
	    this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
	  },

	  // [getContext]
	  //
	  // On stack, before: ...
	  // On stack, after: ...
	  // Compiler value, after: lastContext=depth
	  //
	  // Set the value of the `lastContext` compiler value to the depth
	  getContext: function getContext(depth) {
	    this.lastContext = depth;
	  },

	  // [pushContext]
	  //
	  // On stack, before: ...
	  // On stack, after: currentContext, ...
	  //
	  // Pushes the value of the current context onto the stack.
	  pushContext: function pushContext() {
	    this.pushStackLiteral(this.contextName(this.lastContext));
	  },

	  // [lookupOnContext]
	  //
	  // On stack, before: ...
	  // On stack, after: currentContext[name], ...
	  //
	  // Looks up the value of `name` on the current context and pushes
	  // it onto the stack.
	  lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
	    var i = 0;

	    if (!scoped && this.options.compat && !this.lastContext) {
	      // The depthed query is expected to handle the undefined logic for the root level that
	      // is implemented below, so we evaluate that directly in compat mode
	      this.push(this.depthedLookup(parts[i++]));
	    } else {
	      this.pushContext();
	    }

	    this.resolvePath('context', parts, i, falsy, strict);
	  },

	  // [lookupBlockParam]
	  //
	  // On stack, before: ...
	  // On stack, after: blockParam[name], ...
	  //
	  // Looks up the value of `parts` on the given block param and pushes
	  // it onto the stack.
	  lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
	    this.useBlockParams = true;

	    this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
	    this.resolvePath('context', parts, 1);
	  },

	  // [lookupData]
	  //
	  // On stack, before: ...
	  // On stack, after: data, ...
	  //
	  // Push the data lookup operator
	  lookupData: function lookupData(depth, parts, strict) {
	    if (!depth) {
	      this.pushStackLiteral('data');
	    } else {
	      this.pushStackLiteral('container.data(data, ' + depth + ')');
	    }

	    this.resolvePath('data', parts, 0, true, strict);
	  },

	  resolvePath: function resolvePath(type, parts, i, falsy, strict) {
	    // istanbul ignore next

	    var _this = this;

	    if (this.options.strict || this.options.assumeObjects) {
	      this.push(strictLookup(this.options.strict && strict, this, parts, type));
	      return;
	    }

	    var len = parts.length;
	    for (; i < len; i++) {
	      /* eslint-disable no-loop-func */
	      this.replaceStack(function (current) {
	        var lookup = _this.nameLookup(current, parts[i], type);
	        // We want to ensure that zero and false are handled properly if the context (falsy flag)
	        // needs to have the special handling for these values.
	        if (!falsy) {
	          return [' != null ? ', lookup, ' : ', current];
	        } else {
	          // Otherwise we can use generic falsy handling
	          return [' && ', lookup];
	        }
	      });
	      /* eslint-enable no-loop-func */
	    }
	  },

	  // [resolvePossibleLambda]
	  //
	  // On stack, before: value, ...
	  // On stack, after: resolved value, ...
	  //
	  // If the `value` is a lambda, replace it on the stack by
	  // the return value of the lambda
	  resolvePossibleLambda: function resolvePossibleLambda() {
	    this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
	  },

	  // [pushStringParam]
	  //
	  // On stack, before: ...
	  // On stack, after: string, currentContext, ...
	  //
	  // This opcode is designed for use in string mode, which
	  // provides the string value of a parameter along with its
	  // depth rather than resolving it immediately.
	  pushStringParam: function pushStringParam(string, type) {
	    this.pushContext();
	    this.pushString(type);

	    // If it's a subexpression, the string result
	    // will be pushed after this opcode.
	    if (type !== 'SubExpression') {
	      if (typeof string === 'string') {
	        this.pushString(string);
	      } else {
	        this.pushStackLiteral(string);
	      }
	    }
	  },

	  emptyHash: function emptyHash(omitEmpty) {
	    if (this.trackIds) {
	      this.push('{}'); // hashIds
	    }
	    if (this.stringParams) {
	      this.push('{}'); // hashContexts
	      this.push('{}'); // hashTypes
	    }
	    this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
	  },
	  pushHash: function pushHash() {
	    if (this.hash) {
	      this.hashes.push(this.hash);
	    }
	    this.hash = { values: [], types: [], contexts: [], ids: [] };
	  },
	  popHash: function popHash() {
	    var hash = this.hash;
	    this.hash = this.hashes.pop();

	    if (this.trackIds) {
	      this.push(this.objectLiteral(hash.ids));
	    }
	    if (this.stringParams) {
	      this.push(this.objectLiteral(hash.contexts));
	      this.push(this.objectLiteral(hash.types));
	    }

	    this.push(this.objectLiteral(hash.values));
	  },

	  // [pushString]
	  //
	  // On stack, before: ...
	  // On stack, after: quotedString(string), ...
	  //
	  // Push a quoted version of `string` onto the stack
	  pushString: function pushString(string) {
	    this.pushStackLiteral(this.quotedString(string));
	  },

	  // [pushLiteral]
	  //
	  // On stack, before: ...
	  // On stack, after: value, ...
	  //
	  // Pushes a value onto the stack. This operation prevents
	  // the compiler from creating a temporary variable to hold
	  // it.
	  pushLiteral: function pushLiteral(value) {
	    this.pushStackLiteral(value);
	  },

	  // [pushProgram]
	  //
	  // On stack, before: ...
	  // On stack, after: program(guid), ...
	  //
	  // Push a program expression onto the stack. This takes
	  // a compile-time guid and converts it into a runtime-accessible
	  // expression.
	  pushProgram: function pushProgram(guid) {
	    if (guid != null) {
	      this.pushStackLiteral(this.programExpression(guid));
	    } else {
	      this.pushStackLiteral(null);
	    }
	  },

	  // [registerDecorator]
	  //
	  // On stack, before: hash, program, params..., ...
	  // On stack, after: ...
	  //
	  // Pops off the decorator's parameters, invokes the decorator,
	  // and inserts the decorator into the decorators list.
	  registerDecorator: function registerDecorator(paramSize, name) {
	    var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
	        options = this.setupHelperArgs(name, paramSize);

	    this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
	  },

	  // [invokeHelper]
	  //
	  // On stack, before: hash, inverse, program, params..., ...
	  // On stack, after: result of helper invocation
	  //
	  // Pops off the helper's parameters, invokes the helper,
	  // and pushes the helper's return value onto the stack.
	  //
	  // If the helper is not found, `helperMissing` is called.
	  invokeHelper: function invokeHelper(paramSize, name, isSimple) {
	    var nonHelper = this.popStack(),
	        helper = this.setupHelper(paramSize, name),
	        simple = isSimple ? [helper.name, ' || '] : '';

	    var lookup = ['('].concat(simple, nonHelper);
	    if (!this.options.strict) {
	      lookup.push(' || ', this.aliasable('helpers.helperMissing'));
	    }
	    lookup.push(')');

	    this.push(this.source.functionCall(lookup, 'call', helper.callParams));
	  },

	  // [invokeKnownHelper]
	  //
	  // On stack, before: hash, inverse, program, params..., ...
	  // On stack, after: result of helper invocation
	  //
	  // This operation is used when the helper is known to exist,
	  // so a `helperMissing` fallback is not required.
	  invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
	    var helper = this.setupHelper(paramSize, name);
	    this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
	  },

	  // [invokeAmbiguous]
	  //
	  // On stack, before: hash, inverse, program, params..., ...
	  // On stack, after: result of disambiguation
	  //
	  // This operation is used when an expression like `{{foo}}`
	  // is provided, but we don't know at compile-time whether it
	  // is a helper or a path.
	  //
	  // This operation emits more code than the other options,
	  // and can be avoided by passing the `knownHelpers` and
	  // `knownHelpersOnly` flags at compile-time.
	  invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
	    this.useRegister('helper');

	    var nonHelper = this.popStack();

	    this.emptyHash();
	    var helper = this.setupHelper(0, name, helperCall);

	    var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');

	    var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
	    if (!this.options.strict) {
	      lookup[0] = '(helper = ';
	      lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
	    }

	    this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
	  },

	  // [invokePartial]
	  //
	  // On stack, before: context, ...
	  // On stack after: result of partial invocation
	  //
	  // This operation pops off a context, invokes a partial with that context,
	  // and pushes the result of the invocation back.
	  invokePartial: function invokePartial(isDynamic, name, indent) {
	    var params = [],
	        options = this.setupParams(name, 1, params);

	    if (isDynamic) {
	      name = this.popStack();
	      delete options.name;
	    }

	    if (indent) {
	      options.indent = JSON.stringify(indent);
	    }
	    options.helpers = 'helpers';
	    options.partials = 'partials';
	    options.decorators = 'container.decorators';

	    if (!isDynamic) {
	      params.unshift(this.nameLookup('partials', name, 'partial'));
	    } else {
	      params.unshift(name);
	    }

	    if (this.options.compat) {
	      options.depths = 'depths';
	    }
	    options = this.objectLiteral(options);
	    params.push(options);

	    this.push(this.source.functionCall('container.invokePartial', '', params));
	  },

	  // [assignToHash]
	  //
	  // On stack, before: value, ..., hash, ...
	  // On stack, after: ..., hash, ...
	  //
	  // Pops a value off the stack and assigns it to the current hash
	  assignToHash: function assignToHash(key) {
	    var value = this.popStack(),
	        context = undefined,
	        type = undefined,
	        id = undefined;

	    if (this.trackIds) {
	      id = this.popStack();
	    }
	    if (this.stringParams) {
	      type = this.popStack();
	      context = this.popStack();
	    }

	    var hash = this.hash;
	    if (context) {
	      hash.contexts[key] = context;
	    }
	    if (type) {
	      hash.types[key] = type;
	    }
	    if (id) {
	      hash.ids[key] = id;
	    }
	    hash.values[key] = value;
	  },

	  pushId: function pushId(type, name, child) {
	    if (type === 'BlockParam') {
	      this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
	    } else if (type === 'PathExpression') {
	      this.pushString(name);
	    } else if (type === 'SubExpression') {
	      this.pushStackLiteral('true');
	    } else {
	      this.pushStackLiteral('null');
	    }
	  },

	  // HELPERS

	  compiler: JavaScriptCompiler,

	  compileChildren: function compileChildren(environment, options) {
	    var children = environment.children,
	        child = undefined,
	        compiler = undefined;

	    for (var i = 0, l = children.length; i < l; i++) {
	      child = children[i];
	      compiler = new this.compiler(); // eslint-disable-line new-cap

	      var index = this.matchExistingProgram(child);

	      if (index == null) {
	        this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
	        index = this.context.programs.length;
	        child.index = index;
	        child.name = 'program' + index;
	        this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
	        this.context.decorators[index] = compiler.decorators;
	        this.context.environments[index] = child;

	        this.useDepths = this.useDepths || compiler.useDepths;
	        this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
	      } else {
	        child.index = index;
	        child.name = 'program' + index;

	        this.useDepths = this.useDepths || child.useDepths;
	        this.useBlockParams = this.useBlockParams || child.useBlockParams;
	      }
	    }
	  },
	  matchExistingProgram: function matchExistingProgram(child) {
	    for (var i = 0, len = this.context.environments.length; i < len; i++) {
	      var environment = this.context.environments[i];
	      if (environment && environment.equals(child)) {
	        return i;
	      }
	    }
	  },

	  programExpression: function programExpression(guid) {
	    var child = this.environment.children[guid],
	        programParams = [child.index, 'data', child.blockParams];

	    if (this.useBlockParams || this.useDepths) {
	      programParams.push('blockParams');
	    }
	    if (this.useDepths) {
	      programParams.push('depths');
	    }

	    return 'container.program(' + programParams.join(', ') + ')';
	  },

	  useRegister: function useRegister(name) {
	    if (!this.registers[name]) {
	      this.registers[name] = true;
	      this.registers.list.push(name);
	    }
	  },

	  push: function push(expr) {
	    if (!(expr instanceof Literal)) {
	      expr = this.source.wrap(expr);
	    }

	    this.inlineStack.push(expr);
	    return expr;
	  },

	  pushStackLiteral: function pushStackLiteral(item) {
	    this.push(new Literal(item));
	  },

	  pushSource: function pushSource(source) {
	    if (this.pendingContent) {
	      this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
	      this.pendingContent = undefined;
	    }

	    if (source) {
	      this.source.push(source);
	    }
	  },

	  replaceStack: function replaceStack(callback) {
	    var prefix = ['('],
	        stack = undefined,
	        createdStack = undefined,
	        usedLiteral = undefined;

	    /* istanbul ignore next */
	    if (!this.isInline()) {
	      throw new _exception2['default']('replaceStack on non-inline');
	    }

	    // We want to merge the inline statement into the replacement statement via ','
	    var top = this.popStack(true);

	    if (top instanceof Literal) {
	      // Literals do not need to be inlined
	      stack = [top.value];
	      prefix = ['(', stack];
	      usedLiteral = true;
	    } else {
	      // Get or create the current stack name for use by the inline
	      createdStack = true;
	      var _name = this.incrStack();

	      prefix = ['((', this.push(_name), ' = ', top, ')'];
	      stack = this.topStack();
	    }

	    var item = callback.call(this, stack);

	    if (!usedLiteral) {
	      this.popStack();
	    }
	    if (createdStack) {
	      this.stackSlot--;
	    }
	    this.push(prefix.concat(item, ')'));
	  },

	  incrStack: function incrStack() {
	    this.stackSlot++;
	    if (this.stackSlot > this.stackVars.length) {
	      this.stackVars.push('stack' + this.stackSlot);
	    }
	    return this.topStackName();
	  },
	  topStackName: function topStackName() {
	    return 'stack' + this.stackSlot;
	  },
	  flushInline: function flushInline() {
	    var inlineStack = this.inlineStack;
	    this.inlineStack = [];
	    for (var i = 0, len = inlineStack.length; i < len; i++) {
	      var entry = inlineStack[i];
	      /* istanbul ignore if */
	      if (entry instanceof Literal) {
	        this.compileStack.push(entry);
	      } else {
	        var stack = this.incrStack();
	        this.pushSource([stack, ' = ', entry, ';']);
	        this.compileStack.push(stack);
	      }
	    }
	  },
	  isInline: function isInline() {
	    return this.inlineStack.length;
	  },

	  popStack: function popStack(wrapped) {
	    var inline = this.isInline(),
	        item = (inline ? this.inlineStack : this.compileStack).pop();

	    if (!wrapped && item instanceof Literal) {
	      return item.value;
	    } else {
	      if (!inline) {
	        /* istanbul ignore next */
	        if (!this.stackSlot) {
	          throw new _exception2['default']('Invalid stack pop');
	        }
	        this.stackSlot--;
	      }
	      return item;
	    }
	  },

	  topStack: function topStack() {
	    var stack = this.isInline() ? this.inlineStack : this.compileStack,
	        item = stack[stack.length - 1];

	    /* istanbul ignore if */
	    if (item instanceof Literal) {
	      return item.value;
	    } else {
	      return item;
	    }
	  },

	  contextName: function contextName(context) {
	    if (this.useDepths && context) {
	      return 'depths[' + context + ']';
	    } else {
	      return 'depth' + context;
	    }
	  },

	  quotedString: function quotedString(str) {
	    return this.source.quotedString(str);
	  },

	  objectLiteral: function objectLiteral(obj) {
	    return this.source.objectLiteral(obj);
	  },

	  aliasable: function aliasable(name) {
	    var ret = this.aliases[name];
	    if (ret) {
	      ret.referenceCount++;
	      return ret;
	    }

	    ret = this.aliases[name] = this.source.wrap(name);
	    ret.aliasable = true;
	    ret.referenceCount = 1;

	    return ret;
	  },

	  setupHelper: function setupHelper(paramSize, name, blockHelper) {
	    var params = [],
	        paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
	    var foundHelper = this.nameLookup('helpers', name, 'helper'),
	        callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : {}');

	    return {
	      params: params,
	      paramsInit: paramsInit,
	      name: foundHelper,
	      callParams: [callContext].concat(params)
	    };
	  },

	  setupParams: function setupParams(helper, paramSize, params) {
	    var options = {},
	        contexts = [],
	        types = [],
	        ids = [],
	        objectArgs = !params,
	        param = undefined;

	    if (objectArgs) {
	      params = [];
	    }

	    options.name = this.quotedString(helper);
	    options.hash = this.popStack();

	    if (this.trackIds) {
	      options.hashIds = this.popStack();
	    }
	    if (this.stringParams) {
	      options.hashTypes = this.popStack();
	      options.hashContexts = this.popStack();
	    }

	    var inverse = this.popStack(),
	        program = this.popStack();

	    // Avoid setting fn and inverse if neither are set. This allows
	    // helpers to do a check for `if (options.fn)`
	    if (program || inverse) {
	      options.fn = program || 'container.noop';
	      options.inverse = inverse || 'container.noop';
	    }

	    // The parameters go on to the stack in order (making sure that they are evaluated in order)
	    // so we need to pop them off the stack in reverse order
	    var i = paramSize;
	    while (i--) {
	      param = this.popStack();
	      params[i] = param;

	      if (this.trackIds) {
	        ids[i] = this.popStack();
	      }
	      if (this.stringParams) {
	        types[i] = this.popStack();
	        contexts[i] = this.popStack();
	      }
	    }

	    if (objectArgs) {
	      options.args = this.source.generateArray(params);
	    }

	    if (this.trackIds) {
	      options.ids = this.source.generateArray(ids);
	    }
	    if (this.stringParams) {
	      options.types = this.source.generateArray(types);
	      options.contexts = this.source.generateArray(contexts);
	    }

	    if (this.options.data) {
	      options.data = 'data';
	    }
	    if (this.useBlockParams) {
	      options.blockParams = 'blockParams';
	    }
	    return options;
	  },

	  setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
	    var options = this.setupParams(helper, paramSize, params);
	    options = this.objectLiteral(options);
	    if (useRegister) {
	      this.useRegister('options');
	      params.push('options');
	      return ['options=', options];
	    } else if (params) {
	      params.push(options);
	      return '';
	    } else {
	      return options;
	    }
	  }
	};

	(function () {
	  var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' ');

	  var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};

	  for (var i = 0, l = reservedWords.length; i < l; i++) {
	    compilerWords[reservedWords[i]] = true;
	  }
	})();

	JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
	  return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
	};

	function strictLookup(requireTerminal, compiler, parts, type) {
	  var stack = compiler.popStack(),
	      i = 0,
	      len = parts.length;
	  if (requireTerminal) {
	    len--;
	  }

	  for (; i < len; i++) {
	    stack = compiler.nameLookup(stack, parts[i], type);
	  }

	  if (requireTerminal) {
	    return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
	  } else {
	    return stack;
	  }
	}

	exports['default'] = JavaScriptCompiler;
	module.exports = exports['default'];

/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {

	/* global define */
	'use strict';

	exports.__esModule = true;

	var _utils = __webpack_require__(5);

	var SourceNode = undefined;

	try {
	  /* istanbul ignore next */
	  if (false) {
	    // We don't support this in AMD environments. For these environments, we asusme that
	    // they are running on the browser and thus have no need for the source-map library.
	    var SourceMap = require('source-map');
	    SourceNode = SourceMap.SourceNode;
	  }
	} catch (err) {}
	/* NOP */

	/* istanbul ignore if: tested but not covered in istanbul due to dist build  */
	if (!SourceNode) {
	  SourceNode = function (line, column, srcFile, chunks) {
	    this.src = '';
	    if (chunks) {
	      this.add(chunks);
	    }
	  };
	  /* istanbul ignore next */
	  SourceNode.prototype = {
	    add: function add(chunks) {
	      if (_utils.isArray(chunks)) {
	        chunks = chunks.join('');
	      }
	      this.src += chunks;
	    },
	    prepend: function prepend(chunks) {
	      if (_utils.isArray(chunks)) {
	        chunks = chunks.join('');
	      }
	      this.src = chunks + this.src;
	    },
	    toStringWithSourceMap: function toStringWithSourceMap() {
	      return { code: this.toString() };
	    },
	    toString: function toString() {
	      return this.src;
	    }
	  };
	}

	function castChunk(chunk, codeGen, loc) {
	  if (_utils.isArray(chunk)) {
	    var ret = [];

	    for (var i = 0, len = chunk.length; i < len; i++) {
	      ret.push(codeGen.wrap(chunk[i], loc));
	    }
	    return ret;
	  } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
	    // Handle primitives that the SourceNode will throw up on
	    return chunk + '';
	  }
	  return chunk;
	}

	function CodeGen(srcFile) {
	  this.srcFile = srcFile;
	  this.source = [];
	}

	CodeGen.prototype = {
	  isEmpty: function isEmpty() {
	    return !this.source.length;
	  },
	  prepend: function prepend(source, loc) {
	    this.source.unshift(this.wrap(source, loc));
	  },
	  push: function push(source, loc) {
	    this.source.push(this.wrap(source, loc));
	  },

	  merge: function merge() {
	    var source = this.empty();
	    this.each(function (line) {
	      source.add(['  ', line, '\n']);
	    });
	    return source;
	  },

	  each: function each(iter) {
	    for (var i = 0, len = this.source.length; i < len; i++) {
	      iter(this.source[i]);
	    }
	  },

	  empty: function empty() {
	    var loc = this.currentLocation || { start: {} };
	    return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
	  },
	  wrap: function wrap(chunk) {
	    var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];

	    if (chunk instanceof SourceNode) {
	      return chunk;
	    }

	    chunk = castChunk(chunk, this, loc);

	    return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
	  },

	  functionCall: function functionCall(fn, type, params) {
	    params = this.generateList(params);
	    return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
	  },

	  quotedString: function quotedString(str) {
	    return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
	    .replace(/\u2029/g, '\\u2029') + '"';
	  },

	  objectLiteral: function objectLiteral(obj) {
	    var pairs = [];

	    for (var key in obj) {
	      if (obj.hasOwnProperty(key)) {
	        var value = castChunk(obj[key], this);
	        if (value !== 'undefined') {
	          pairs.push([this.quotedString(key), ':', value]);
	        }
	      }
	    }

	    var ret = this.generateList(pairs);
	    ret.prepend('{');
	    ret.add('}');
	    return ret;
	  },

	  generateList: function generateList(entries) {
	    var ret = this.empty();

	    for (var i = 0, len = entries.length; i < len; i++) {
	      if (i) {
	        ret.add(',');
	      }

	      ret.add(castChunk(entries[i], this));
	    }

	    return ret;
	  },

	  generateArray: function generateArray(entries) {
	    var ret = this.generateList(entries);
	    ret.prepend('[');
	    ret.add(']');

	    return ret;
	  }
	};

	exports['default'] = CodeGen;
	module.exports = exports['default'];

/***/ }
/******/ ])
});
;;
var Home = {
    init: function () {
        Home.bind.giftCardBalance();
        Home.bind.quickView();
        $("#breadcrumb-content").css("display", "none");
        Home.bind.makeSliderlItemClickable();
    },
    bind: {
        // Get balance of provided gift card number
        giftCardBalance: function () {
            $("#giftcard-balance-form").on("submit", function (e) {
                e.preventDefault();
                var form = $(this);
                var gcInput = $("#giftcard_number");
                // Call API for response
                Api.getGiftCardBalance(gcInput.val(), function (response) {
                    if (response.success) {
                        // Generate markup from inline template (within view)
                        var template = $("#tmpl-giftcardbalance").html();
                        var html = Mustache.render(template, response.data);
                        $("#giftcard-balance-result").html(html);
                        gcInput.val("");
                    } else {
                        form.find(".form-error").html('<div class="field-validation-error">' + response.message + '</div>');
                    }

                });
            });
        },
        quickView: function () {
            $(".btn-quick-view").on("click", function () {
                var productId = $(this).attr("data-value");
                var reviewStateId = $(this).attr("data-review-state-id");
                var productIsActive = $(this).attr("data-product-is-active");
                if ((reviewStateId !=undefined && reviewStateId != "20") || (productIsActive != undefined && productIsActive=="False")) {
                    return false;
                } else {
                Api.getQuickView(productId, function (responce) {
                    $("#quick-view-content").html(responce);
                    Product.data.isQuickView = true;
                    Product.init();
                    Product.local.updateProductVariations("#dynamic-product-variations", $("#dynamic-product-variations .quantity").val())
                });
                var ipad = navigator.userAgent.match(/iPad/i) != null;
                if (ipad) {
                    $('body').css('overflow', 'hidden');
                    $('body').css('position', 'fixed');
                }
                }
            });
        },
        menuHandler: function () {
            var agent = navigator.userAgent.toLowerCase();
            if (agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0) {
                var node = $("#navbar-collapse-nav li");
                for (var i = 0; i < node.length ; i++) {
                    var item = node[i];
                    if (item.childElementCount > 1) {
                        var link = item.children[0];
                        //var catgId = link.innerText.toLowerCase() + i;
                        var catgId = link.dataset.category + i;
                        var href = link.href;
                        link.id = catgId;
                        link.className = "_expandchildmenu";
                        link.href = "javascript:void(0);";
                        $('#' + catgId).attr("data-href", href);
                    }
                }
                Home.bind.HandleParentCategory();
            }
        },
        HandleParentCategory: function () {
            // Determine if we on iPhone or iPad
            var isiOS = false;
            var agent = navigator.userAgent.toLowerCase();
            if (agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0) {
                isiOS = true;
            }

            $.fn.doubletap = function (onDoubleTapCallback, onTapCallback, delay) {
                var eventName, action;
                delay = delay == null ? 500 : delay;
                eventName = isiOS == true ? 'touchend' : 'click';

                $(this).bind(eventName, function (event) {
                    var now = new Date().getTime();
                    var lastTouch = $(this).data('lastTouch') || now + 1 /** the first time this will make delta a negative number */;
                    var delta = now - lastTouch;
                    clearTimeout(action);
                    if (delta < 500 && delta > 0) {
                        if (onDoubleTapCallback != null && typeof onDoubleTapCallback == 'function') {
                            onDoubleTapCallback(event);
                        }
                    } else {
                        $(this).data('lastTouch', now);
                        action = setTimeout(function (evt) {
                            if (onTapCallback != null && typeof onTapCallback == 'function') {
                                onTapCallback(evt);
                            }
                            clearTimeout(action);   // clear the timeout
                        }, delay, [event]);
                    }
                    $(this).data('lastTouch', now);
                });
            };

            /** doubletap-dblclick delay (default is 500 ms) */
            var categories = $("#navbar-collapse-nav li ._expandchildmenu");
            for (var i = 0; i < categories.length ; i++) {
                var category = categories[i];
                var categoryId = category.id;
                var actualUrl = $("#" + categoryId).data("href");
                $("#" + categoryId).doubletap(
                   /** doubletap-dblclick callback */
                   function (event) {
                       if (actualUrl != undefined) {
                           window.location = actualUrl;
                       }
                   },
                   /** touch-click callback (touch) */
                   function (event) {
                       /** singletap-dblclick callback */
                   });
            }
        },
        makeSliderlItemClickable: function () {
            const topSlider = document.querySelector('#top-slider');

            if (topSlider === null) {
                return;
            }

            const goToUrlHandler = (event) => {
                const target = event.target;

                if (target === null) {
                    return;
                }

                const goToUrlElement = target.closest('[data-action="goToUrl"]');

                if (goToUrlElement === null) {
                    return;
                }

                const sliderLink = goToUrlElement.closest('.item').querySelector('a');

                window.location.assign(sliderLink.href);
            };

            topSlider.addEventListener('click', goToUrlHandler);
        }
    }
}
;
var Cart = {


    // INIT	
    init: function () {
        _debug("cart.init()");
        Cart.bind.formatCartQuantity();
        Cart.bind.removeCartItem();
        Cart.bind.updateQuantity();
        Cart.bind.updateShipTo();
        Cart.bind.promoCode();

        //Removes all item from cart - Start 
        Cart.bind.removeAllCartItem();
        //Removes all item from cart - End 

        Cart.bind.submitMultipleShipping();
        Cart.bind.calculateShipping();
        Cart.bind.viewMultiAddressCart();
        Cart.bind.cardQuantityKeyPress();
        Cart.bind.shippingToValidation();
        Cart.bind.multipleShipQuantityKeyPressEvent();
        Cart.bind.removeCouponCode();
    },


    // BINDINGS
    bind: {
        // Removes item from cart
        formatCartQuantity: function () {
            _debug("bind.formatCartQuantity()");
            var cartQty = "";
            if ($(".cartQuantity").html() == undefined)
            {
                cartQty = $(".shipQuantity");
            }
            else
            {
                cartQty = $(".cartQuantity");
            }
            
            for (var i = 0; i < cartQty.length; i++) {
                var cartQuantityFormat = parseFloat(cartQty[i].value);
                if ((cartQuantityFormat % 1) == 0) {
                    cartQty[i].value = (parseInt(cartQuantityFormat));
                }
            }
        },

        // Removes item from cart
        removeCartItem: function () {
            _debug("bind.removeCartItem()");
            $("#layout-cart .cart-item-remove").on("click", function (e) {
                e.preventDefault();
                $(this).closest("form").submit();
            });
        },

        // Updates quantity of item 
        updateQuantity: function () {
            _debug("bind.updateQuantity()");
            $("#layout-cart .cart-item-total select.shipTo").on("change", function (ev) {
                $(this).closest("form").submit();
            });
        },

        // Updates quantity of item 
        updateShipTo: function () {
            $("#layout-cart .cart-item-quantity .cartQuantity").on("blur", function (ev) {
                var selectedQty = $(this).val();
                var productid = $(this).attr("data-cart-productid")
                if (selectedQty.split(".")[1] != undefined) {
                    var validQty = selectedQty.split(".")[1].length;
                    if (!validQty) {
                        $(this).val('');
                        $("#quantity_error_msg_" + productid).text('Please enter valid quantity');
                        $("#checkOut-link").attr('href', 'javascript:void(0);');
                        return false;
                    }
                }
                var matches = selectedQty.match(/^-?[\d.]+(?:e-?\d+)?$/);
                if (matches == null) {
                    $(this).val('');
                    $("#quantity_error_msg_" + productid).text('Please enter numeric value');
                    $("#checkOut-link").attr('href', 'javascript:void(0);');
                    return false;
                }
                else {
                    $("#checkOut-link").attr('href', '/Checkout');
                }

                if (parseFloat(selectedQty) < parseFloat($(this).attr("data-product-minqty"))) {
                    $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                    $("#checkOut-link").attr('href', 'javascript:void(0);');
                    return false;
                }

                if (parseFloat(selectedQty) > parseFloat($(this).attr("data-product-maxqty"))) {
                    $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                    $("#checkOut-link").attr('href', 'javascript:void(0);');
                    return false;
                }
                if ($(this).attr("data-cart-uom") != "2" && $(this).attr("data-cart-uom") != "4") {
                    $(this).val(selectedQty.replace(/[^\d].+/, ""));
                    if ((ev.which < 48 || ev.which > 57)) {
                        $(this).val(parseInt(selectedQty));
                    }
                }
$(this).val(parseFloat($(this).val()));
                $(this).closest("form").submit();
            });
        },

        cardQuantityKeyPress: function () {
            $('#layout-cart .cart-item-quantity .cartQuantity').keypress(function (e) {
                var key = e.which;
                if (key == 13)  // the enter key code
                {
                    var selectedQty = $(this).val();
                    var productid = $(this).attr("data-cart-productid");
                    var matches = selectedQty.match(/^-?[\d.]+(?:e-?\d+)?$/);
                    if (matches == null) {
                        $(this).val('');
                        $("#quantity_error_msg_" + productid).text('Please enter numeric value');
                        $("#checkOut-link").attr('href', 'javascript:void(0);');
                        return false;
                    }
                    else {
                        $("#checkOut-link").attr('href', '/Checkout');
                    }

                    if (parseFloat(selectedQty) < parseFloat($(this).attr("data-product-minqty"))) {
                        $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                        $("#checkOut-link").attr('href', 'javascript:void(0);');
                        return false;
                    }

                    if (parseFloat(selectedQty) > parseFloat($(this).attr("data-product-maxqty"))) {
                        $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                        $("#checkOut-link").attr('href', 'javascript:void(0);');
                        return false;
                    }
                    if ($(this).attr("data-cart-uom") != "2" && $(this).attr("data-cart-uom") != "4") {
                        $(this).val(selectedQty.replace(/[^\d].+/, ""));
                        if ((ev.which < 48 || ev.which > 57)) {
                            $(this).val(parseInt(selectedQty));
                        }
                    }
                }
            });
        },

        multipleShipQuantityKeyPressEvent: function () {
            $('#layout-cart .cart-item-quantity .shipQuantity').keypress(function (e) {
                var key = e.which;
                if (key == 13)  // the enter key code
                {
                    var selectedQty = $(this).val();
                    var productid = $(this).attr("data-cart-productid")
                    if (selectedQty == null || selectedQty == "") {
                        $(this).next().text('Please enter valid quantity');
                        $("#submitMultipleShipping").attr("disabled", "disabled");
                        return false;
                    }
                    if (selectedQty.split(".")[1] != undefined) {
                        var validQty = selectedQty.split(".")[1].length;
                        if (!validQty) {
                            $(this).val('');
                            $(this).next().text('Please enter valid quantity');
                            $("#submitMultipleShipping").attr("disabled", "disabled");
                            return false;
                        }
                    }
                    var matches = selectedQty.match(/^-?[\d.]+(?:e-?\d+)?$/);
                    if (matches == null) {
                        $(this).val('');
                        $(this).next().text('Please enter numeric value');
                        $("#submitMultipleShipping").attr("disabled", "disabled");
                        return false;
                    }


                    if (parseFloat(selectedQty) < parseFloat($(this).attr("data-cart-minqty"))) {
                        $(this).next().text("Selected quantity should be in between " + parseFloat($(this).attr("data-cart-minqty")) + " to " + parseFloat($(this).attr("data-cart-maxqty")) + "");
                        $("#submitMultipleShipping").attr("disabled", "disabled");
                        return false;
                    }

                    if (parseFloat(selectedQty) > parseFloat($(this).attr("data-cart-maxqty"))) {
                        $(this).next().text("Selected quantity should be in between " + parseFloat($(this).attr("data-cart-minqty")) + " to " + parseFloat($(this).attr("data-cart-maxqty")) + "");
                        $("#submitMultipleShipping").attr("disabled", "disabled");
                        return false;
                    }
                    if ($(this).attr("data-cart-uom") != "2" && $(this).attr("data-cart-uom") != "4") {
                        $(this).val(selectedQty.replace(/[^\d].+/, ""));
                        if ((ev.which < 48 || ev.which > 57)) {
                            $(this).val(parseInt(selectedQty));
                        }
                    }

                $(this).closest("form").submit();
                }
            });
        },

        shippingToValidation: function () {
            $("#layout-cart .cart-item-quantity .shipQuantity").on("focusout", function (ev) {
                var selectedQty = $(this).val();
                var productid = $(this).attr("data-cart-productid")
                if (selectedQty == null || selectedQty == "") {
                    $(this).next().text('Please enter valid quantity');
                    $("#submitMultipleShipping").attr("disabled", "disabled");
                    return false;
                }
                if (selectedQty.split(".")[1] != undefined) {
                    var validQty = selectedQty.split(".")[1].length;
                    if (!validQty) {
                        $(this).val('');
                        $(this).next().text('Please enter valid quantity');
                        $("#submitMultipleShipping").attr("disabled", "disabled");
                        return false;
                    }
                }
                var matches = selectedQty.match(/^-?[\d.]+(?:e-?\d+)?$/);
                if (matches == null) {
                    $(this).val('');
                    $(this).next().text('Please enter numeric value');
                    $("#submitMultipleShipping").attr("disabled", "disabled");
                    return false;
                }


                if (parseFloat(selectedQty) < parseFloat($(this).attr("data-cart-minqty"))) {
                    $(this).next().text("Selected quantity should be in between " + parseFloat($(this).attr("data-cart-minqty")) + " to " + parseFloat($(this).attr("data-cart-maxqty")) + "");
                    $("#submitMultipleShipping").attr("disabled", "disabled");
                    return false;
                }

                if (parseFloat(selectedQty) > parseFloat($(this).attr("data-cart-maxqty"))) {
                    $(this).next().text("Selected quantity should be in between " + parseFloat($(this).attr("data-cart-minqty")) + " to " + parseFloat($(this).attr("data-cart-maxqty")) + "");
                    $("#submitMultipleShipping").attr("disabled", "disabled");
                    return false;
                }
                if ($(this).attr("data-cart-uom") != "2" && $(this).attr("data-cart-uom") != "4") {
                    $(this).val(selectedQty.replace(/[^\d].+/, ""));
                    if ((ev.which < 48 || ev.which > 57)) {
                        $(this).val(parseInt(selectedQty));
                    }
                }

                $(this).closest("form").submit();
            });
        },
        // Updates quantity of item 
        submitMultipleShipping: function () {
            $("#layout-cart #submitMultipleShipping").on("click", function (ev) {
                var DataList = new Array;
                $("#layout-cart select.shipTo option:selected").each(function (e) {
                    DataList.push({
                        addressid: $(this).val(),
                        productid: $(this).parent().next().next().val(),
                        quantity: $(this).closest('td').prev('td').children().find('input').val(),
                        SKU: $(this).parent().next().next().next().val(),
                        AddOnValueIds: $(this).parent().next().next().next().next().next().val(),
                        AddOnValuesCustomText: $(this).parent().next().next().next().next().next().next().val()
                    });
                });

                var jArray = JSON.stringify(DataList);
                overlayforwaitblock();
                $.ajax({
                    url: "/Checkout/ContinueCheckout/",
                    type: "get",
                    dataType: "json",
                    data: {
                        "multipleAddress": jArray
                    },
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        overlayforwaitnone();
                        if (data == 'true') {
                            window.location.href = "/Checkout/ShippingMethods?returnUrl='multipleshipto'";
                        }
                        else {
                            $('#status-message').remove();
                            $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">Customer shipping address is not a valid address. Please enter valid address to continue.</div>');
                            return false;
                        }
                    },
                    error: function (msg) {
                        window.location.href = "/Checkout/ShippingMethods?returnUrl='multipleshipto'";
                    }
                });

            });
        },

        // Updates quantity of item 
        calculateShipping: function () {
            //shippingOptionList
            $(".multipleShippingOption").on("change", function (ev) {
                $(this).closest("form").submit();
            });
        },

        viewMultiAddressCart: function () {
            //shippingOptionList
            $(".view-multi-address-cart").on("click", function (ev) {
                $(this).closest("form").submit();
            });
        },

        promoCode: function () {
            _debug("bind.promoCode()");
            var couponCode = Cart.bind.getQueryString("coupon");
            if (couponCode != null && couponCode != undefined && couponCode != "") {
                Api.isCouponUrlEnabled(couponCode, function (response) {
                    if (response.couponUrlIsEnabled) {
                        Cart.bind.applyPromoCode(couponCode);
                    }
                });
            }
            else if ($("#cart-promocode-container p.error-msg").length > 0) {
                $("#cart-promocode-container p.error-msg").remove();
            }
            $("#cart-promocode-container").on("submit", function (e) {
                e.preventDefault();
                Cart.bind.applyPromoCode($("#promocode").val());
            });
        },

        applyPromoCode: function (couponCode) {
            var template = $("#tmpl-promocodes").html();

            Api.useCouponCode(couponCode, function (response) {
                var html = "";
                if (!response.isMultipleCoupon) {
                    if (response.success) {
                        response.data.class = "success-msg";
                        response.data.coupon = response.data.promoCode[0].Coupon;
                        response.data.message = response.data.promoCode[0].CouponMessage;
                    }
                    else {
                        $("#cart-promocode-container p.error-msg").remove();
                        response.data.class = "error-msg";
                        response.data.coupon = couponCode;
                        response.data.message = (response.data.coupon === "") ? response.data.promoCode[response.data.promoCode.length - 1].CouponMessage : "Invalid coupon code ";
                    }
                    html = Mustache.render(template, response.data);

                    if (response.success) {
                        $(".cart-promocode-status .success-msg").css("text-decoration", "line-through");
                        $(".cart-promocode-status").prepend(html);
                        $("#cart-promocode-container input").val("");
                        $("#dynamic-discount-amount").html(response.data.discountamount);
                        $("#dynamic-order-total").find("h2").html(response.data.ordertotal);
                        $("#dynamic-tax-amount").html(response.data.taxamount);
                        $("#dynamic-order-subtotal").html(response.data.subtotal);
                        $("#dynamic-cart-order-total").html(response.data.ordertotal);
                    } else {
                        $(".cart-promocode-status").prepend(html);
                    }

                }
                else {
                    for (var dataIndex = 0; dataIndex < response.data.promoCode.length; dataIndex++) {
                        response.data.message = response.data.promoCode[dataIndex].CouponMessage;
                        if (response.data.promoCode[dataIndex].CouponValid === true) {
                            response.data.class = "success-msg";
                        }
                        else {
                            response.data.class = "error-msg";
                        }
                        response.data.coupon = response.data.promoCode[dataIndex].Coupon;
                        html = html + Mustache.render(template, response.data);
                    }
                    $(".cart-promocode-status").text("");
                    $(".cart-promocode-status").prepend(html);
                    $("#cart-promocode-container input").val("");
                    $("#dynamic-discount-amount").html(response.data.discountamount);
                    $("#dynamic-order-total").find("h2").html(response.data.ordertotal);
                    $("#dynamic-tax-amount").html(response.data.taxamount);
                    $("#dynamic-order-subtotal").html(response.data.subtotal);
                    $("#dynamic-cart-order-total").html(response.data.ordertotal);
                }
            });
        },

        removeAllCartItem: function () {
            _debug("bind.removeAllCartItem()");
            $("#layout-cart .cart-item-remove-all").on("click", function (e) {
                e.preventDefault();
                $(this).closest("form").submit();
            });
            localStorage.removeItem("bundleCartAddOnDetails");
        },

        getQueryString: function (field) {
            var href = window.location.href;
            var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
            var string = reg.exec(href);
            return string ? string[1] : null;
        },

        removeCouponCode: function (couponCode) {
            var template = $("#tmpl-promocodes").html();
            Api.removeCouponCode(couponCode, function (response) {
                var html = "";
                for (var dataIndex = 0; dataIndex < response.data.promoCode.length; dataIndex++) {
                    response.data.message = response.data.promoCode[dataIndex].CouponMessage;
                    if (response.data.promoCode[dataIndex].CouponValid === true) {
                        response.data.class = "success-msg";
                    }
                    else {
                        response.data.class = "error-msg";
                    }
                    response.data.coupon = response.data.promoCode[dataIndex].Coupon;
                    html = html + Mustache.render(template, response.data);
                }
                $(".cart-promocode-status").text("");
                $(".cart-promocode-status").prepend(html);
                $("#cart-promocode-container input").val("");
                $("#dynamic-discount-amount").html(response.data.discountamount);
                $("#dynamic-order-total").find("h2").html(response.data.ordertotal);
                $("#dynamic-tax-amount").html(response.data.taxamount);
                $("#dynamic-order-subtotal").html(response.data.subtotal);
                $("#dynamic-cart-order-total").html(response.data.ordertotal);
            });
        }
    },
    multiShippingCart: function () {
        $.ajax({
            url: "/Checkout/SetSelectedIndex/",
            type: "get",
            dataType: "json",
            data: {
            },
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                if (data != null) {
                    var jsonData = data;
                    for (var i = 0; i < jsonData.length; i++) {
                        if ($("#layout-cart select.shipTo:eq(" + i + ")").next().next().val() === jsonData[i].productid) {
                            $("#layout-cart select.shipTo:eq(" + i + ")").val(jsonData[i].addressid);
                        }
                    }
                }
            },
            error: function (msg) {
                alert("error");
            }
        });
    }
};

// END module;
var Product = {
    init: function () {
        _debug("writeReviewForm.init");
        Product.bind.writeReviewStars();
        if (!Product.data.isQuickView) {
            // Pull in Lightbox library for image zooming
            $.getScript("/Scripts/lib/lightbox-2.6.min.js");

            $('#demo-1 .simpleLens-thumbnails-container img').simpleGallery({ loading_image: '/Images/lightbox/loading.gif' });
            $('#demo-1 .simpleLens-big-image').simpleLens({ loading_image: '/Images/lightbox/loading.gif' });
        }

        // Bindings

        //Product.setProductBreadCrumb();
        Product.bind.productAttributes();
        Product.bind.productAddOns();
        Product.bind.productQuantity();
        $("#dynamic-product-variations .quantity").trigger("blur");
        Product.bind.addToWishlist();
        Product.bind.readReviews();
        Product.bind.ChangeMainImage();
        // get recent  product grids
        Product.getRecentProductList(function (res) {
            if (res === true) {
                loadSlider();
            }
        });
        Product.getRelatedProducts();
        Product.bind.jumpToReviews();
        // Product.bind.getProductDetails();
        // Disable addTocart button on renavigation when quantity reach to max quantity
        Product.quantityVerifieronRenavigation();
        Product.bind.writeReviewStars();
        Product.bind.bundleAttributes();
        Product.viewCompareProduct();
        Product.bind.productDetailSendMailPopup();
        Product.bind.addToCartProductDetails();
        Product.mobileImageCarousel();
    },
    // Module variables. Use for local tracking
    data: {
        productId: 0,
        lastSelectedAttributeId: 0,
        //Show reviews on product listing pages.-Starts
        productContent: "scrollReview",
        //Show reviews on product listing pages.-Ends
        isQuickView: false
    },

    getRelatedProducts: function () {
        _debug("getRelatedProducts()");
        global.local.lazyLoadContent("#layout-product", function (el, params, renderAction) {
            Api.getRelatedProducts(params.ids, params.accountid, function (response) {
                renderAction(response);
                global.local.lazyLoadImages("#" + el.id); // Lazy load images in the incoming markup
            });

        });
    },

    // get recent  product grids
    getRecentProductList: function (fun_res) {
        var productId = Product.local.setProductId();
        Api.getRecentProducts(productId, 4, function (response) {
            var title = $("#recently-viewed-header").html();
            $("#layout-product .recent-view-items").html("<h4>" + title + "</h4>" + response.data.html);
            fun_res(true);
        });
    },



    // Disable addTocart button on renavigation when quantity reach to max quantity
    quantityVerifieronRenavigation: function () {
        $("#Quantity").change();
    },

    // Updates total price element
    refreshPrice: function (amount) {
        $("#product_Detail_Price_Div").show();
        $("#layout-product .dynamic-product-price").html(amount);
    },

    // Updates paypal pay in 4 widget on pdp for non-custom products
    paypalWidget: function (amount) {
        PayPalSDK
            .Messages({
                amount: amount,
                placement: "product",
                style: {
                    layout: "text",
                    logo: {
                        type: "inline",
                    },
                },
            })
            .render('.pp-message');
    },
    refreshMainProductImage: function (data) {
        if (typeof data.imagePath === 'string' && data.imagePath.trim().length === 0) {
            return;
        }

        const galleryItem = document.querySelector('.splide__slide.is-active.is-visible');

        if (galleryItem === null) {
            return;
        }

        const link = galleryItem.querySelector('a');

        link.href = data.imagePath;

        const image = link.querySelector('img');

        image.src = data.imagePath;
        image.dataset.splideLazy = data.imagePath;

        const selectAttribute = document.querySelector('#AttributeId');

        if (selectAttribute === null) {
            if (typeof image.alt === 'string' && image.alt.trim().length > 0) {
                return;
            }

            const productNameHeader = document.querySelector('#productNameHeader');

            if (productNameHeader === null) {
                image.alt = document.title;
                return;
            }

            image.alt = productNameHeader.textContent;

            return;
        }

        const selectedAttribute = selectAttribute.options[selectAttribute.selectedIndex];

        image.alt = selectedAttribute.textContent;
    },
    inventoryStatus: function (response) {
        if (response.success) {
            // In stock
            $("#dynamic-inventory").hide();
            $("#button-addtocart").removeAttr("disabled");
        } else {
            // Out of stock
            $("#button-addtocart").attr("disabled", "disabled");
            $("#dynamic-inventory").show().html(response.message);
        }
    },

    updateProductValues: function (response, quantity) {
        var selectedAddOnIds = Product.local.getAddOnIds();
        // Set form values for submit
        $("#dynamic-productid").val(Product.data.productId);
        $("#dynamic-sku").val(response.data.sku);
        $(".quantity").val(quantity);
        $("#dynamic-addons").val(selectedAddOnIds);
        $("input[name='AddOnValueIds']").val(selectedAddOnIds);
        $("#dynamic-productName").val(Product.data.ProductName);
        if (response.data.addOnId != undefined && response.data.addOnMessage != undefined && response.data.isOutOfStock != undefined) {
            for (var index = 0; index < response.data.addOnId.length; index++) {
                if (response.data.isOutOfStock[index]) {
                    $("#dynamic-addOninventory_" + response.data.addOnId[index]).show();
                    $("#dynamic-addOninventory_" + response.data.addOnId[index]).html(response.data.addOnMessage[index]);
                }
                else {
                    $("#dynamic-addOninventory_" + response.data.addOnId[index]).hide();
                    $("#dynamic-addOninventory_" + response.data.addOnId[index]).html("");
                }
            }
        }
    },

    mobileImageCarousel: function () {
        $('.mobile-carousel').owlCarousel({
            items: 1,
            loop: true
        });
    },

    viewCompareProduct: function () {
        _debug("viewCompareProduct.init()");

        $(".remove-compare").on("click", function () {
            Product.bind.removeProduct($(this).attr("data-productid"));
        });

        $("#lnkSendMail").on("click", function () {
            Product.bind.sendMailPopup();
        });
    },
    // LOCAL ACTIONS, various views
    local: {

        setProductId: function () {
            Product.data.productId = $(".product-meta").data("id");

            return (Product.data.productId);
        },

        addToWishList: function (el) {
            var productId = Product.local.setProductId();
            var sku = $("#dynamic-sku").val();
            var clicked = $(el);
            Api.addProductToWishList(productId, sku, function (response) {

                $(".wishlist-status").remove(); // Clears any existing message
                $("#SuccessMessage").empty();

                response.data.message = response.message; // Adds response message to data object for template

                // Build status message template
                var template = $("#tmpl-wishliststatus").html();
                var html = Mustache.render(template, response.data);

                if (response.success) {
                    // Added to list
                    clicked.after(html);
                } else {
                    if (response.data.redirect) {
                        // Login needed
                        global.local.setAlertMessage(response.message, "info");
                        document.location = response.data.redirect;
                    } else {
                        // Catchall error
                        clicked.after(html);
                    }
                }
            });

        },

        updateProductVariations: function (htmlContainer, quantity, callback) {
            var selectedAddOnIds = "";
            var selectedIds = Product.local.getAttributeIds();

            if (localStorage.getItem("cartAddOnDetails") != null)
                cartAddOnDetails = Product.getAddOnIdsFromStorage();
            else {
                selectedAddOnIds = Product.local.getAddOnIds();
            }
            if (Product.data.lastSelectedAttributeId <= 0) {
                Product.data.lastSelectedAttributeId = selectedIds;
            }
            //if (localStorage.getItem('isSelectedProducRedirected') != undefined && localStorage.getItem('isSelectedProducRedirected') != null && localStorage.getItem('isSelectedProducRedirected') == "true") {
            //    Product.data.lastSelectedAttributeId = selectedIds.split(',')[0];
            //}
            var params = "attributeId=" + Product.data.lastSelectedAttributeId + "&selectedIds=" + selectedIds + "&quantity=" + quantity + "&selectedAddOnIds=" + selectedAddOnIds;

            Api.getProductAttributes(Product.local.setProductId(), params, function (response) {
                if (response.data.addOnId != undefined && response.data.addOnMessage != undefined && response.data.isOutOfStock != undefined) {
                    for (var index = 0; index < response.data.addOnId.length; index++) {
                        if (response.data.isOutOfStock[index]) {
                            $("#dynamic-addOninventory_" + response.data.addOnId[index]).show();
                            $("#dynamic-addOninventory_" + response.data.addOnId[index]).html(response.data.addOnMessage[index]);
                        }
                        else {
                            $("#dynamic-addOninventory_" + response.data.addOnId[index]).hide();
                            $("#dynamic-addOninventory_" + response.data.addOnId[index]).html("");
                        }
                    }
                }
                if (htmlContainer) {
                    $(htmlContainer).html(response.data.html);
                }

                if (callback) {
                    callback(response);
                }
            });
        },

        updateBundleVariations: function (htmlContainer, bundleProductId, callback) {
            var selectedIds = Product.local.getAttributeIds("#bundle-item-" + bundleProductId);
            var selectedAddOnIds = Product.local.getAddOnIds("#bundle-item-" + bundleProductId);
            if (Product.data.lastSelectedAttributeId <= 0) {
                Product.data.lastSelectedAttributeId = selectedIds;
            }

            var params = "attributeId=" + Product.data.lastSelectedAttributeId + "&selectedIds=" + selectedIds + "&quantity=1&selectedAddOnIds=" + selectedAddOnIds;

            Api.getProductAttributes(bundleProductId, params, function (response) {
                if (htmlContainer) {
                    $(htmlContainer).html(response.data.html);
                }

                if (callback) {
                    callback(response);
                }
            });
        },

        getAttributeIds: function (parentSelector) {
            var selectedIds = [];
            if (typeof parentSelector == "undefined") { parentSelector = ""; }

            $(parentSelector + " select.attribute").each(function () {
                selectedIds.push($(this).val());
            });

            return (selectedIds.join());
        },

        getAddOnIds: function (parentSelector) {
            var selectedAddOnIds = [];
            var addOnsCustomText = [];
            if (typeof parentSelector == "undefined") { parentSelector = ""; }
            $(parentSelector + " select.AddOn").each(function () {
                selectedAddOnIds.push($(this).val());
            });

            $(parentSelector + " input.AddOn:checked").each(function () {
                selectedAddOnIds.push($(this).val());
            });

            $(parentSelector + ".AddOnValues").each(function () {
                var optional = $(this).data("isoptional");
                var displayType = $(this).data("addondisplaytype");
                if (displayType == "TextBox" && optional == "False") {
                    selectedAddOnIds.push($(this).data("addonvalueid"));
                    addOnsCustomText.push($(this).val());
                }
                else if (displayType == "TextBox" && optional == "True" && $(this).val() != "") {
                    selectedIds.push($(this).data("addonvalueid"));
                    addOnsCustomText.push($(this).val());
                }
            });
            return (selectedAddOnIds.join());
        },

        GetDetails: function () {
            var selectedIds = [];
            var addOnsCustomText = [];
            var addOnValueIds = [];
            var addToCart = false;
            var checkBoxaAddOnCart = true;
            var textBoxAddOn = true;
            var cartDetails = [];
            var cartAddOnValues = "";
            if (typeof parentSelector == "undefined") { parentSelector = ""; }

            //for dropdown
            $(parentSelector + " select.AddOn").each(function () {
                selectedIds.push($(this).val());
                cartAddOnValues += $(this).val();
                addOnsCustomText.push("undefined");
            });
            cartDetails.push($(parentSelector + " select.AddOn").attr("id") + ':' + cartAddOnValues);
            cartAddOnValues = "";

            $(parentSelector + " input.AddOn:checked").each(function () {
                selectedIds.push($(this).val());
                addOnsCustomText.push("undefined");
            });

            $(parentSelector + 'input[type=radio].AddOn:checked').each(function () {
                var id = $(this).attr("id");
                var val = $(this).val();
                cartDetails.push(id + ':' + val);
            });

            $(parentSelector + 'input[type=checkbox].AddOn:checked').each(function () {
                var id = $(this).attr("id");
                var val = $(this).val();
                cartDetails.push(id + ':' + val);
            });



            //for checkbox   
            $(".chk-product-addons").each(function () {
                var optional = $(this).data("isoptional");
                var id = $(this).attr("id");
                var addOnId = $(this).data("addonid");
                if (optional == "True") {
                    checkBoxaAddOnCart = true;
                }
                else {
                    var isError = true;
                    $('#' + id).find(':checkbox').each(function () {
                        if ($(this).is(':checked')) {
                            isError = false;
                        }
                    });
                    if (!isError) {
                        $("#paraComment-" + addOnId).css("display", "none");
                    }
                    else {
                        $("#paraComment-" + addOnId).removeAttr("style");
                        checkBoxaAddOnCart = false;
                    }
                }
            });

            //for textbox
            $(".AddOnValues").each(function () {
                var optional = $(this).data("isoptional");
                var displayType = $(this).data("addondisplaytype");
                var id = $(this).attr("id");
                var number = id.split('-');
                if (displayType == "TextBox" && optional == "False") {
                    if ($("#" + id).val() == "") {
                        $("#paraComment-" + number[1]).removeAttr("style");
                        textBoxAddOn = false;
                        cartDetails.push($("#" + id).attr("id") + ':' + $("#" + id).val());
                    }
                    else {
                        selectedIds.push($(this).data("addonvalueid"));
                        addOnValueIds.push($(this).data("addonvalueid"));
                        addOnsCustomText.push($(this).val());
                        $("#paraComment-" + number[1]).css("display", "none");
                        textBoxAddOn = true;
                        cartDetails.push($("#" + id).attr("id") + ':' + $("#" + id).val());
                    }
                }
                else if (displayType == "TextBox" && optional == "True" && $(this).val() != "") {
                    selectedIds.push($(this).data("addonvalueid"));
                    addOnsCustomText.push($(this).val());
                    textBoxAddOn = true;
                }
                $("#dynamic-addons").val(selectedIds);
                $("input[name='AddOnValueIds']").val(selectedIds);
                $("#dynamic-addonvaluecustomtext").val(addOnsCustomText);
            });
            if (textBoxAddOn && checkBoxaAddOnCart) {
                addToCart = true;
            }

            localStorage.setItem("bundleCartAddOnDetails", cartDetails);
            $("#CartAddOnDetails").val(cartDetails);
            return addToCart;
        },
    },

    SendMail: function (isCompare) {
        var senderMailId = $("#txtSenderEmail").val();
        var recieverMailId = $("#txtReceiverEmail").val();
        var productId = $("#dynamic-productId").val();
        var url = "";
        if (isCompare === "True") {
            url = "/Product/SendComparedProductMail";
        }
        else {

            url = "/Product/SendMailToFriend";
        }
        Api.getSenMailNOtification(url, productId, senderMailId, recieverMailId, function (response) {
            $('#status-message').remove();
            $(".ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close").trigger("click");
            $("#divSendMail").dialog("close");
            if (response.success) {
                $("#SuccessMessage").append('<div id="status-message" class="alert alert-success text-center">' + "Email send successfully" + '</div>')
            }
            else {
                $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + "Email was not sent" + '</div>')
            }
        });
    },

    ProductSendMail: function () {
        var productId = $("#dynamic-productId").val();
        var productName = $("#dynamic-seoPageName").val();
        Api.getProductSendMailDetails(productId, productName, function (response) {
            $("#divSendMail").html(response);
            $("#btnSendMail").on("click", function () {
                if (!Product.bind.EmailValidation()) {
                    return false;
                }
                else {
                    var isCompare = $("#dynamic-iscompare").val();
                    Product.SendMail(isCompare);
                }
            });
            $("#divSendMail").dialog({
                title: "Email a Friend",
                resizable: false,
                modal: true,
                width: 400,
                height: 280,
                create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup send-mail-popup"); }
            });
        });
    },

    // BINDINGS
    // Keep all bindings in this object and call as needed from view init()	
    bind: {
        // Change to attributes on bundle options view; view does not include quantity option
        bundleAttributes: function () {
            _debug("bind.bundleAttributes()");
            $("#layout-bundlesettings .bundle-item-details").on("change", ".attribute, .AddOn", function (ev) {

                /*
				| !! - Need to find ajax-based solution rather than full POST on each change
				*/
                var form = $(this).closest("form");
                $("#dynamic-bundle-attributeId").val($(this).val());
                $("#dynamic-bundle-ProductId").val($(this).closest(".bundle-item").data("id"));
                form.attr('action', '/Product/UpdateBundles');
                form.submit();
            });

            $("#layout-bundlesettings .bundle-item-details").on("change", ".AddOn", function (ev) {
                $("#dynamic-addons").val($(this).val());
                $("input[name='AddOnValueIds']").val($(this).val());
            });
        },

        // When attribute dropdown is changed, update region with new HTML
        productAttributes: function () {
            _debug("bind.productAttributes()");

            const dynamicProductVariations = $("#dynamic-product-variations");

            if (dynamicProductVariations.length > 0) {
                dynamicProductVariations.on("change", "select.attribute", function (ev) {
                    //localStorage.removeItem('isSelectedProducRedirected');
                    Product.data.lastSelectedAttributeId = $(this).val();

                    let quantity = $("#Quantity").val();

                    Product.local.updateProductVariations("#dynamic-product-variations", quantity, function (response) {
                        quantity = response.quantity;
                        Product.updateProductValues(response, quantity);
    
                        // Update display
                        var retailPrice = response.data.price;
                        Product.refreshPrice(retailPrice.substr(0, retailPrice.indexOf('.') + 3));
                        Product.inventoryStatus(response);
    
                        //CCCChange
                        GetEstimateShippingText(response.data.sku);

                        //Paypal pay in 4
                        Product.paypalWidget(response.data.finalProductPrice);

                        //Populate the sku selected SKU from the DDL, or default to product page, if there is no choices
                        $("#CurrentProductSku").html(response.data.sku);
    
                        Product.refreshMainProductImage(response.data);
                        dynamicProductVariations.html(response.data.html);
                        $(".quantity").blur();
                    });
                });

                return;
            }

            // Note: this covers Discontinued scenario
            const quantity = 0;

            Product.local.updateProductVariations("#dynamic-product-variations", quantity, (response) => {
                $("#CurrentProductSku").html(response.data.sku);
            });
        },

        // When add-on input control is changed, update region with new HTML
        productAddOns: function () {
            _debug("bind.productAddOns()");
            $("#dynamic-product-addons").on("change", ".AddOn", function (ev) {
                var quantity = $('#product-details-quantity #Quantity').val();
                Product.local.updateProductVariations(false, quantity, function (response) {
                    Product.updateProductValues(response, quantity);
                    var retailPrice = response.data.price;
                    Product.refreshPrice(retailPrice.substr(0, retailPrice.indexOf('.') + 3));
                    Product.inventoryStatus(response);

                    //CCCChange
                    GetEstimateShippingText(response.data.sku);

                    //Populate the sku selected SKU from the DDL, or default to product page, if there is no choices
                    $("#CurrentProductSku").html(response.data.sku);
                });
            });
        },


        // When quantity is changed, update region with new HTML
        productQuantity: function () {
            _debug("bind.productQuantity()");

            $("#dynamic-product-variations").on("focusout", ".quantity", function (ev) {
               
                $("#quantity-error-msg").text('')
                $("#dynamic-inventory").text('');
                var productQty = $(this).val();
                if (productQty.split(".")[1] != undefined) {
                    var validQty = productQty.split(".")[1].length;
                    if (!validQty) {
                        $(this).val('');
                        $("#quantity-error-msg").text('Please enter valid quantity');
                        $("#button-addtocart").attr("disabled", "disabled");
                        return false;
                    }
                }
                if (parseFloat(productQty) == "0") {
                    $("#button-addtocart").attr("disabled", "disabled");
                    return false;
                }
                if (parseFloat(productQty) == "" || parseFloat(productQty) == "0") {
                    $("#button-addtocart").attr("disabled", "disabled");
                    $("#quantity-error-msg").text('Please enter numeric value');
                    return false;
                }
                var matches = $(this).val().match(/^-?[\d.]+(?:e-?\d+)?$/);
                if (matches == null) {
                    $(this).val('');
                    $("#quantity-error-msg").text('Please enter numeric value');
                    $("#button-addtocart").attr("disabled", "disabled");
                    return false;
                }

                if ($("#hdnUOM").val() != "2" && $("#hdnUOM").val() != "4") {
                    $(this).val($(this).val().replace(/[^\d].+/, ""));
                    if ((ev.which < 48 || ev.which > 57)) {
                        $(this).val(parseInt($(this).val()));
                        if ($(this).val() == "0") {
                            $("#button-addtocart").attr("disabled", "disabled");
                            return false;
                        }
                    }
                }
                var quantity = parseFloat($(this).val());
                Product.local.updateProductVariations(false, quantity, function (response) {
                    var retailPrice = response.data.price;
                    Product.updateProductValues(response, quantity);
                    Product.refreshPrice(retailPrice);
                    Product.inventoryStatus(response);
                    Product.refreshMainProductImage(response.data);

                    //CCCChange
                    GetEstimateShippingText(response.data.sku);

                    //Paypal pay in 4
                    Product.paypalWidget(response.data.finalProductPrice);

                    //Populate the sku selected SKU from the DDL, or default to product page, if there is no choices
                    $("#CurrentProductSku").html(response.data.sku);
                });
            });
        },


        // Click for Add to Wishlist button
        addToWishlist: function () {
            _debug("bind.addToWishlist()");

            $("#layout-product .button-wishlist").on("click", function (e) {
                Product.local.addToWishList(this);
            });
        },

        // Click for "read reviews" link at top of product; jump and toggle
        readReviews: function () {

            _debug("bind.readReviews()");

            $("#jumpto-readreviews").on("click", function (ev) {
                ev.preventDefault();
                $("#tab-reviews").trigger("click");
                scrollToTop(300, "#scrollReview");
            });
        },

        jumpToReviews: function () {
            var url = document.URL.toString();
            var name = '';
            if (!(url.indexOf('#') === -1)) {
                var urlParts = url.split("#");
                name = urlParts[1];
            }
            if (name == Product.data.productContent.toString()) {
                $("#tab-reviews").trigger("click");
                scrollToTop(300, "#scrollReview");
            }
        },

        // Click for write review form stars
        writeReviewStars: function () {
            _debug("bind.writeReviewStars()");

            $("#layout-writereview .setrating label").on("click", function () {
                $("#layout-writereview .setrating label").removeClass("full").addClass("empty"); // Reset all to empty

                var stars = $(this).data("stars");

                for (a = 1; a <= stars; a += 1) {
                    $(".star" + a).removeClass("empty").addClass("full");
                }
            });
        },

        //Change the Main image in Product Details on click of Swatch(Color) Images. - Start 
        ChangeMainImage: function () {
            _debug("bind.ChangeMainImage()");
            $(".SwatchImage").on("click", function () {
                $("#product-image").attr('src', $(this).attr("data-mediumsrc"));
                $("#product-image").attr('data-src', $(this).attr("data-mediumsrc"));
                $("#product-lens-image").attr('data-lens-image', $(this).attr("data-largesrc"));
            });
        },
        //Change the Main image in Product Details on click of Swatch(Color) Images. - End 

        removeProduct: function (productId) {
            _debug("bind.removeProduct()");
            var url = window.location.href.toString().split('/')
            var control = url[3];
            Api.removeProduct(productId, control, function (response) {
                if (response.count == 0) {
                    window.location.href = "/Home/Index";
                }
                if (response.count == 1) {
                    $(".compare-print").html("");
                }

                $("#divRemoveProduct").html("");
                $("#divRemoveProduct").html(response.data.html);
                if (response.message != "" && response.count == 1) {
                    $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + response.message + '</div>')
                }
                $(".remove-compare").unbind("click");
                $(".remove-compare").on("click", function () {
                    Product.bind.removeProduct($(this).attr("data-productid"));
                });
                return true;
            });
        },

        sendMailPopup: function () {
            _debug("bind.sendMailPopup()")
            Api.getComparedProductSendMailDetails(function (response) {
                $("#divSendMail").html(response);
                $("#btnSendMail").on("click", function () {
                    if (!Product.bind.EmailValidation()) {
                        return false;
                    }
                    else {
                        var isCompare = $("#dynamic-iscompare").val();
                        Product.SendMail(isCompare);
                    }
                });
                $("#divSendMail").dialog({
                    title: "Product Compare",
                    resizable: false,
                    modal: true,
                    width: 400,
                    height: 280,
                    create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup send-mail-popup"); }
                });
            });
        },

        EmailValidation: function () {
            _debug("bind.EmailValidation()");
            $("#valSenderEmail").text('').removeClass("field-validation-error").hide();
            $("#valReceiverEmail").text('').removeClass("field-validation-error").hide();
            var senderEmail = $("#txtSenderEmail").val();
            var receiverEmail = $("#txtReceiverEmail").val();
            var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
            if (senderEmail.length < 1 && receiverEmail.length < 1) {
                $("#valSenderEmail").text('').text('Enter email address').addClass("field-validation-error").show();
                $("#valReceiverEmail").text('').text('Enter email address').addClass("field-validation-error").show();
                return false;
            }
            else if (!pattern.test(senderEmail) && receiverEmail.length < 1) {
                $("#valSenderEmail").text('').text('Enter valid email address').addClass("field-validation-error").show();
                $("#valReceiverEmail").text('').text('Enter email address').addClass("field-validation-error").show();
                return false;
            }
            else if (!Product.bind.validateEmail(receiverEmail, pattern) && senderEmail.length < 1) {
                $("#valReceiverEmail").text('').text('Enter valid email address').addClass("field-validation-error").show();
                $("#valSenderEmail").text('').text('Enter email address').addClass("field-validation-error").show();
                return false;
            }
            else if (!pattern.test(senderEmail) && !Product.bind.validateEmail(receiverEmail, pattern)) {
                $("#valSenderEmail").text('').text('Enter valid email address').addClass("field-validation-error").show();
                $("#valReceiverEmail").text('').text('Enter valid email address').addClass("field-validation-error").show();
                return false;
            }
            else if (!pattern.test(senderEmail)) {
                $("#valSenderEmail").text('').text('Enter valid email address').addClass("field-validation-error").show();
                return false;
            }
            else if (senderEmail.length < 1) {
                $("#valSenderEmail").text('').text('Enter email address').addClass("field-validation-error").show();
                return false;
            }
            else if (receiverEmail.length < 1) {
                $("#valReceiverEmail").text('').text('Enter email address').addClass("field-validation-error").show();
                return false;
            }
            else if (!Product.bind.validateEmail(receiverEmail, pattern)) {
                $("#valReceiverEmail").text('').text('Enter valid email address').addClass("field-validation-error").show();
                return false;
            }
            return true;
        },

        validateEmail: function (mailId, pattern) {
            var email = mailId.split(',');
            for (var i = 0; i < email.length; i++) {
                if (email[i].length < 1) {
                    return false;
                }
                else if (!pattern.test(email[i])) {
                    return false;
                }
            }
            return true;
        },

        productDetailSendMailPopup: function () {
            $("#email-a-friend > li").find('a').on("click", function (e) {
                e.preventDefault();
                Product.ProductSendMail();
            });
        },
        addToCartProductDetails: function () {
            $("#button-addtocart").on("click", function () {
                var selectedAddOnIds = Product.local.getAddOnIds();
                $("#dynamic-addons").val(selectedAddOnIds);
                $("input[name='AddOnValueIds']").val(selectedAddOnIds);
                return true;
            });
        },
        getProductDetails: function () {
            $("#button-addtocart").on("click", function () {
                var addToCart = Product.local.GetDetails()
                if (addToCart) {
                    return true;
                }
                else {
                    return false
                }
            });
        },
    },

    setProductBreadCrumb: function () {
        _debug("bind.setProductBreadCrumb()")
        var isQuickView = $("#hdnQuickView").val();
        var productName = $(".product-name").html();
        Api.getProductBreadCrumb(Product.local.setProductId(), productName, isQuickView, function (response) {
            if (response != undefined && response != null && response.data != undefined && response.data != null && response.data.ProductBreadCrumb != undefined && response.data.ProductBreadCrumb != null && response.data.ProductBreadCrumb != "") {
                $("#breadcrumb-content").html(response.data.ProductBreadCrumb);
                $("#categoryLink").attr("href", response.data.CategoryUrl);
                $("#categoryName").html(response.data.CategoryName);
            }
        });
    },
    GetProductOutOfStockDetails: function (control, e) {
        e.preventDefault();
        var productId = $(control).attr("data-value");
        Api.getProductOutOfStockDetails(productId, function (response) {
            if (response === "True") {
                $(control).closest("form").submit();
            }
            else {
                $(control).attr("disabled", "disabled")
                return false;
            }
        });
    },

    setAddOnValues: function (cartAddOnDetails) {
        localStorage.setItem("cartAddOnDetails", cartAddOnDetails);
    },

    setBundleAddOnValues: function () {
        var cartAddOnDetails = localStorage.getItem("bundleCartAddOnDetails");
        $("#CartAddOnDetails").val(cartAddOnDetails);
    },

    getAddOnIdsFromStorage: function () {
        var cartAddOnDetails = localStorage.getItem("cartAddOnDetails");
        cartAddOnDetails = cartAddOnDetails.split(",");

        localStorage.removeItem("cartAddOnDetails");

        $('input[type=checkbox].AddOn').removeAttr('checked');


        for (var i = 0; i < cartAddOnDetails.length; i++) {
            var idVal = cartAddOnDetails[i].split(':');

            if ($("#" + idVal[0]).is("input") && $("#" + idVal[0]).attr('type') == "checkbox" && $("#" + idVal[0]).val() == idVal[1]) {
                $("#" + idVal[0]).attr("checked", true);
            }
            else if ($("#" + idVal[0]).is("input") && $("#" + idVal[0]).attr('type') == "radio") {
                if ($("#" + idVal[0]).val() == idVal[1]) {
                    $("#" + idVal[0]).attr("checked", true);
                }
                else { $("#" + idVal[0]).attr("checked", false); }
            }
            else if ($("#" + idVal[0]).is("input") && $("#" + idVal[0]).attr('type') == "text") {
                $("#" + idVal[0]).val(idVal[1]);
            }
            else {
                $("#" + idVal[0]).val(idVal[1]);
            }
        }
        return cartAddOnDetails;
    }
}


GetEstimateShippingText = function (sku) {
    $.ajax({
        url: "/api/ccc/GetBackOrderDate?sku=" + sku,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            $("#EstimateShippingText").html(result);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (Globals.LogErrors)
                console.log("[Error] XHR Status: " + xhr.status + ", Error: " + thrownError);
        }
    });
};function SetPaymentUrl() {
  var payment_Url = PaymentApplicationUrl;
  return payment_Url;
}
function SetStoreUrl() {
  var store_Url = StoreUrl;
  return store_Url;
}

var correctCaptcha = function (response) {
  Api.GetCurbstoneRecaptchaResult(response, function(result) {
      if (result.isHuman) {
          $("#ccCheckoutButton").show();
          $("#curbCheckoutButton").show();
          $("#gRecaptchaContainer").hide();
          $(".g-recaptcha").hide();
      }
  });
};

var GloabalVariables = {
  ScriptPaymentUrl: SetPaymentUrl() + "/script/znodeapijs",
  PaymentApplicationUrl: SetPaymentUrl() + "/",
  PaymentApplicationJSCall: SetPaymentUrl() + "/script/znodeapijs?gateway={0}&profileId={1}&twoCoUrl={2}&customerGUID={3}",
  PymentApplicationPaypalCall: SetPaymentUrl() + "/payment/paypal?callback=?",
  ZnodeMVCDemoUrl: SetStoreUrl(),
  ZnodeDemoPaymentCancelUrl: SetStoreUrl() + "/checkout",
  ZnodeDemoPaymentTwoCoUrl: SetStoreUrl() + "/checkout/twoco?paymentOptionId={0}",
  ZnodeDemoPaymentSuccessUrl: SetStoreUrl() + "/checkout/Custom?paymentOptionId={0}",
  CurbstoneInitForm: SetStoreUrl() + "/checkout/curbstoneinit"
}

String.format = function () {
  var theString = arguments[0];

  for (var i = 1; i < arguments.length; i++) {
      var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
      theString = theString.replace(regEx, arguments[i]);
  }

  return theString;
}
var Checkout = {
  init: function () {
      $("#payment-methods a").on("click", function () {
          Checkout.viewPayments.togglePaymentMethod(this);
      });

      Checkout.viewSinglePageCheckout.init();
      $("#payment-methods li a:eq(0)").trigger("click");
  },
  GloabalVariables: {
      ScriptPaymentUrl: SetPaymentUrl() + "/script/znodeapijs",
      PaymentApplicationUrl: SetPaymentUrl() + "/",
      PaymentApplicationJSCall: SetPaymentUrl() + "/script/znodeapijs?gateway={0}&profileId={1}&twoCoUrl={2}&customerGUID={3}",
      PymentApplicationPaypalCall: SetPaymentUrl() + "/payment/paypal?callback=?",
      ZnodeMVCDemoUrl: SetStoreUrl(),
      ZnodeDemoPaymentCancelUrl: SetStoreUrl() + "/checkout",
      ZnodeDemoPaymentTwoCoUrl: SetStoreUrl() + "/checkout/twoco?paymentOptionId={0}",
      ZnodeDemoPaymentSuccessUrl: SetStoreUrl() + "/checkout/Custom?paymentOptionId={0}",
  },

  // PAYMENT VIEW
  viewPayments: {

      // Toggle payment option tabs
      togglePaymentMethod: function (el) {
          var clicked = $(el).parent(),
              content = clicked.data("toggle");

          _debug("payment method: " + content);
          $("#payment-methods li").removeClass("active");

          clicked.addClass("active");
          $(".payment-method").hide();
          $("#" + content).show();

          $("#divPaymentOptions").show();
      }
  },

  viewSinglePageCheckout: {
      init: function () {
          Checkout.bind.setStateByCountry();
          var addressBillingZip = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"]').val();
          var addressBillingCity = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').val();
          var addressShippingCity = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').val();
          var addressShippingZip = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').val();

          var multiAddressShippingCity = $('input[name="ShippingAddressModel.City"]').val();
          var multiAddressShippingZip = $('input[name="ShippingAddressModel.PostalCode"]').val();
          var multiAddressBillingCity = $('input[name="BillingAddressModel.City"]').val();
          var multiAddressBillingZip = $('input[name="BillingAddressModel.PostalCode"]').val();

          $(".address_country").trigger("change");

          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"]').val(addressBillingZip);
          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').val(addressBillingCity);
          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').val(addressShippingCity);
          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').val(addressShippingZip);

          $('input[name="ShippingAddressModel.City"]').val(multiAddressShippingCity);
          $('input[name="ShippingAddressModel.PostalCode"]').val(multiAddressShippingZip);
          $('input[name="BillingAddressModel.City"]').val(multiAddressBillingCity);
          $('input[name="BillingAddressModel.PostalCode"]').val(multiAddressBillingZip);

          _debug("checkout.singlecheckout.init()");
          Checkout.bind.singleCheckout();
          Checkout.bind.billingAddress();
          Checkout.bind.BillingSameAsShippingHandler();
          Checkout.bind.setDefaultState();
          Checkout.bind.callAddressChange(0);
          Checkout.bind.OnStateChange();
          Checkout.bind.payment();
          Checkout.bind.giftCard();
          Checkout.bind.ShowAppliedPromotion();
          Checkout.bind.RemoveDuplicateMessage();
          Checkout.bind.SelectAddress();
          Checkout.bind.ResetReviewIndex();

          /**Safari fix**/
          $("#billingSameAsShippingAddress").on("click", function () {

              if ($("#billingSameAsShippingAddress").is(':checked')) {
                  $("#billingaddressform").hide();
              } else {
                  $("#billingaddressform").show();
              }
          });            
      },

  },


  //NEW ADDRESS 
  viewAddnewaddress: {
      init: function () {
          _debug("checkout.addnewaddress.init()");
          Checkout.bind.setStateByCountryById();
          Checkout.bind.setDefaultStateById();
          Checkout.bind.OnStateChangeForAddNewAddress();
      }
  },

  // BINDINGS
  bind: {
      // Payment option toggling
      payment: function () {
          _debug("checkout.bind.payment()");

          if ($('#defaultpayment').length > 0) {
              _debug("default payment:" + $('#defaultpayment').val());
              Checkout.viewPayments.togglePaymentMethod('a[data-toggle=' + $('#defaultpayment').val() + ']');
          }

          // COD confirm to continue
          $("#pick-cod").on("change", function (e) {
              $("#payment-cod .button").toggleDisabled();
              if ($('#pick-cod').is(':checked')) {
                  $("#payment-cod .button").removeClass('grey').addClass('red');
              }
              else {
                  $("#payment-cod .button").removeClass('red').addClass('grey');
              }
          });

          // Purchase Order click
          $("#btn-payment-po").on("click", function () {
              var form = $(this).closest(".form");
              form.find(".form-error").html('');
              if ($("#txt-po-number").val().trim().length < 1) {
                  form.find(".form-error").html('<div class="field-validation-error">Please enter purchase order number.</div>');
                  return false;
              }
              else {
                  $("#hdnPurchaseOrderNumber").val($("#txt-po-number").val().trim());
              }
          });

          $("#curbCheckoutButton").on("click",
              function (e) {
                  e.preventDefault();
                  if ($("#ajaxBusy").html() == undefined) {
                      $('body').append('<div id="ajaxBusy"><p id="ajaxBusyMsg">Please wait while we load the payment screen. Do not close this window.</p></div>');
                  }

                  $("#ajaxBusy").html('');
                  $("#ajaxBusy").html('Please wait while we load the payment screen. Do not close this window.');
                  $("#ajaxBusy").dialog({
                      title: 'Payment Application',
                      resizable: false,
                      modal: true,
                      open: function (event, ui) {
                          $("#ajaxBusy").parent().find(" .ui-dialog-titlebar-close").hide();
                      }
                  });

                  Api.LoadCurbstoneIframe(function (response) {
                      if (response.success) {
                          $("#paymentResult-data").html(response.mfsess);
                          $("#ajaxBusy").dialog('close');
                          $("#ajaxBusy").html('');
                          $("#curbpopUp .ErrorMessage").html('');
                          $("#curbpopUp").show();
                      }
                      else {
                          $("#curbpopUp .ErrorMessage").html('');
                          $("#curbpopUp .Tab-container").html('');
                          $("#ajaxBusy").html('Could not proceed with payment as no payment gateway available with this selection.');
                      }
                  });
              });

          $("#ccCheckoutButton").on("click", function (e) {
              e.preventDefault();
              $("#hdnGatwayName").val('');
              $("#hdnCustomerGUID").val('');
              $('#paymentProviders').html('');
              $('#chkAddCCDetails').attr('checked', false)
              if ($("#CCPaymentOptionId").val().length > 0) {

                  if ($("#ajaxBusy").html() == undefined) {
                      $('body').append('<div id="ajaxBusy"><p id="ajaxBusyMsg">Please wait while we load the payment screen. Do not close this window.</p></div>');
                  }

                  $("#ajaxBusy").html('');
                  $("#ajaxBusy").html('Please wait while we load the payment screen. Do not close this window.');
                  $("#ajaxBusy").dialog({
                      title: 'Payment Application',
                      resizable: false,
                      modal: true,
                      open: function (event, ui) {
                          $("#ajaxBusy").parent().find(" .ui-dialog-titlebar-close").hide();
                      }
                  });
                  Api.GetPaymentGatwayName($("#CCPaymentOptionId").val(), function (response) {

                      $('#Save-credit-card').show();
                      if (response.success) {
                          $("#hdnGatwayName").val(response.name);
                          $("#paymentProfileId").val(response.profileId);
                          $("#hdnCustomerGUID").val(response.customerGuid);
                          if (response.name == "TwoCheckout" || response.name == "PayFlow") {
                              $('#Save-credit-card').hide();
                          }
                          var gatewayName = $("#hdnGatwayName").val();
                          if (gatewayName != undefined && gatewayName.length > 0) {
                              var paymentAppGatewayName = gatewayName.toLowerCase();

                              if (gatewayName.toLowerCase() == 'authorize.net') {
                                  paymentAppGatewayName = 'authorizenet';
                              }

                              if (gatewayName.toLowerCase() == 'paymentech orbital') {
                                  paymentAppGatewayName = 'paymenttech';
                              }
                              if (gatewayName.toLowerCase() == 'payflow') {
                                  Checkout.bind.SetEncryptedTotalAmount(response.total);
                              }

                              var paymentUrl = Checkout.GloabalVariables.PaymentApplicationJSCall;
                              var twoCOUrl = String.format(Checkout.GloabalVariables.ZnodeDemoPaymentTwoCoUrl, $("#CCPaymentOptionId").val());
                              paymentUrl = String.format(paymentUrl, paymentAppGatewayName, $("#paymentProfileId").val(), twoCOUrl, $("#hdnCustomerGUID").val());


                              var gateway = paymentAppGatewayName;
                              var profileId = $("#paymentProfileId").val();
                              var twoCoUrl = twoCOUrl;
                              var customerGUID = $("#hdnCustomerGUID").val();

                              var paymentCreditCardModel = {
                                  gateway: gateway,
                                  profileId: profileId,
                                  twoCoUrl: twoCoUrl,
                                  customerGUID: customerGUID
                              };

                              $.ajax({
                                  type: "POST",
                                  url: Checkout.GloabalVariables.ScriptPaymentUrl,
                                  data: paymentCreditCardModel,
                                  success: function (response) {
                                      $("#ajaxBusy").dialog('close');
                                      Checkout.bind.SetCreditCardValidations();
                                      if (enabledPaymentProviders != '') {
                                          var payProvidersHtml = '';
                                          var toSplittedPayProviders = enabledPaymentProviders.split(",");
                                          for (var iPayProviders = 0; iPayProviders < toSplittedPayProviders.length; iPayProviders++) {
                                              payProvidersHtml += "<div  class='col-xs-12 col-sm-3 nopadding styled-input'><input id=radioPaymentProviders" + iPayProviders + " type=radio name=PaymentProviders value=" + toSplittedPayProviders[iPayProviders] + " /><label for=radioPaymentProviders" + iPayProviders + "><img src=../Images/" + toSplittedPayProviders[iPayProviders] + ".png class='img-responsive' /></label></div>";
                                          }

                                          $('#paymentProviders').append("<ul style='padding:0px;'>" + payProvidersHtml + "</ul>");
                                          $('input[name="PaymentProviders"]')[0].checked = true;
                                      }
                                      if (savedUserCCDetails != '') {
                                          $('#radioCCList').show();
                                          $('#radioCCList').html('');
                                          var iCCOrder = 0;
                                          var creditCardHtml = ""
                                          $.each(JSON.parse(savedUserCCDetails), function () {
                                              creditCardHtml += "<div  class='col-xs-12 nopadding styled-input'><input id=radioSavedCreditCard" + iCCOrder + " type=radio name=CCdetails value=" + this['PaymentGUID'] + " /><label for=radioSavedCreditCard" + iCCOrder + ">" + this['CreditCardLastFourDigit'] + "</label></div>";
                                              iCCOrder++;
                                          });
                                          $('#radioCCList').append("<div class='col-xs-12 nopadding'>" + creditCardHtml + "</div>");
                                          $('input[name="CCdetails"]')[0].checked = true;
                                          $('#divAddNewCCDetails').show();
                                      }
                                      else {
                                          jQuery('#creditCardTab').hide()
                                          jQuery('#savedCreditCard-panel').removeClass('active')
                                          jQuery('#addNewCreditCard-panel').addClass('in active')
                                      }
                                      $("#ccpopUp").show();
                                  },
                                  error: function () {
                                      $("#ajaxBusy").dialog('close');
                                      $("#ccpopUp .ErrorMessage").html('');
                                      $("#ccpopUp .ErrorMessage").html('Unable to contact payment application.');
                                  }
                              });

                          } else {
                              $("#ajaxBusy").html('');
                              $("#ajaxBusy").html('Could not proceed with payment as no payment gateway available with this selection.');
                          }
                          return false;
                      } else {
                          $("#ccpopUp .ErrorMessage").html('');
                          $("#ajaxBusy").html('Could not proceed with payment as no payment gateway available with this selection.');
                      }
                  });
              }
              return false;
          });

          $("#singlepage-paypal-express-checkout").on("click", function (e) {
              if (!$("#div-paypal-express-checkout").is(':visible')) {
                  return false;
              }
              var Total = 0;
              var finalPrice = Number($('#dynamic-order-total').text().replace(/[^0-9\.]+/g, ""));
              Total = parseFloat(finalPrice).toFixed(2);

              if (Total <= 0) {
                  $.ajax({
                      url: "SubmitSingleCheckout",
                      type: 'post',
                      data: $("#checkoutform").serialize(),
                      success: function (data) {
                          if (!data.HasError) {
                              var form = $('<form action="CheckoutReceipt" method="post">' +
                                  '<input type="hidden" name="EmailId" value="' + data.EmailId + '" />' +
                                  '<input type="hidden" name="OrderId" value="' + data.OrderId + '" />' +
                                  '</form>');
                              $('body').append(form);
                              $(form).submit();
                          }
                          else {

                              if (data.ErrorMessage == "Logout") {
                                  window.location.href = "/cart/index";
                              }
                              $("#ajaxProcessPayment").dialog('close');
                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                          }
                      },
                      error: function (xhr, ajaxOptions, thrownError) {
                          $("#ajaxProcessPayment").dialog('close');
                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                      },
                  });
                  return false;
              }
              var isValid = true;
              overlayforwaitblock();
              e.preventDefault();
              if ($("#ddlPaymentTypes option:selected").text().toLowerCase() == 'select payment') {
                  isValid = false;
                  $("#ddlPaymentTypes").css({
                      "border": "1px solid red",
                      "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
                  });
              }
              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.EmailAddress"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').each(function () {
                  if ($.trim($(this).val()) == '') {
                      isValid = false;
                      $(this).css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $(this).css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              });

              var country = $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"] option:selected').val();
              if (country == "0" || country == "") {
                  isValid = false;
                  $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }

              if ($('#CreateLogin').is(":checked")) {
                  $('input[name="ShippingBillingAddressViewModel.LoginViewModel.Username"],input[name="ShippingBillingAddressViewModel.LoginViewModel.Password"]').each(function () {
                      if ($.trim($(this).val()) == '') {
                          isValid = false;
                          $(this).css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }
                      else {
                          $(this).css({
                              "border": "1px solid #C3C3C3",
                              "background": ""
                          });
                      }
                  });
              }

              if ($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val() == "" || !Checkout.bind.ValidateEmail($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val())) {
                  isValid = false;
                  $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }

              if (!($('#billingSameAsShippingAddress').is(":checked"))) {
                  $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').each(function () {
                      if ($.trim($(this).val()) == '') {
                          isValid = false;
                          $(this).css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }
                      else {
                          $(this).css({
                              "border": "1px solid #C3C3C3",
                              "background": ""
                          });
                      }
                  });

                  var country = $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"] option:selected').val();
                  if (country == "0" || country == "") {
                      isValid = false;
                      $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              }
              if ($('#CreateLogin').is(":checked")) {
                  var pattern = new RegExp(/^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/);
                  if (!pattern.test($('#login_password').val())) {
                      isValid = false;
                      $("#valPassword").text('Password must be at least 8 alphanumeric characters and contain at least one number');
                  }
              }
              if ($('#CreateLogin').is(":checked") && $("#valPassword").text() != "") {
                  isValid = false;
              }
              if (isValid) {
                  $.ajax({
                      url: "CreateCustomerPaypalAccount",
                      type: 'post',
                      data: $("#checkoutform").serialize(),
                      success: function (data) {
                          $('#status-message').remove();
                          if (data.HasError) {
                              overlayforwaitnone();
                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                              isValid = false;
                              if (data.ErrorMessage != undefined && data.ErrorMessage != "" && data.ErrorMessage != null) {
                                  if (data.ErrorMessage.trim() == "Your Shipping Address is not a valid address. Please enter valid address to continue.") {
                                      window.location = "/Checkout/SingleCheckout?message=" + data.ErrorMessage;
                                  }
                              }
                              $("#ajaxProcessPayment").dialog('close');
                              $(window).scrollTop(0);
                              return isValid;
                          }
                          else {
                              $('#status-message').remove();
                              overlayforwaitnone();
                              Checkout.bind.PayPalPaymentProcess();
                          }
                      }
                  })
              }
              else {
                  overlayforwaitnone();
                  return false;
              }

          });

          $("#paypal-express-checkout").on("click", function (e) {
              var Total = 0;
              var finalPrice = Number($('#dynamic-total').text().replace(/[^0-9\.]+/g, ""));
              if ($('#OrderTotalGiftCard').val() == "" || $('#OrderTotalGiftCard').val() == undefined) {
                  Total = parseFloat(finalPrice).toFixed(2);
              } else {
                  Total = parseFloat($('#OrderTotalGiftCard').val()).toFixed(2);
              }

              if (Checkout.bind.IsOrderTotalGreaterThanZero(Total)) {
                  $("#ErrorMessage").html('');
                  $("#ajaxProcessPayment").html('');
                  if ($("#ajaxProcessPayment").html() == undefined) {
                      $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p></div>');
                  }

                  $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p>');
                  $("#ajaxProcessPayment").dialog({
                      title: 'Payment Application',
                      resizable: false,
                      modal: true,
                      create: function () {
                          $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top");
                      },
                      closeOnEscape: false,
                      open: function (event, ui) {
                          $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
                      }
                  });
                  var paymentSettingId = $('#PaymentPaypalOptionId').val();
                  var ReturnUrl = String.format(GloabalVariables.ZnodeDemoPaymentSuccessUrl, paymentSettingId);
                  var CancelUrl = GloabalVariables.ZnodeDemoPaymentCancelUrl;
                  Api.ProcessPayPalPayment(paymentSettingId, ReturnUrl, CancelUrl, function (response) {
                      var message = response;
                      $("#SuccessMessage").html('');
                      $("#status-message").html();
                      if (message != undefined && message.indexOf('Message=') >= 0) {
                          var errorMessage = message.substr(message.indexOf('=') + 1);
                          $("#ajaxBusy").dialog('close');
                          $('#SuccessMessage').show();
                          $("#ajaxProcessPayment").dialog('close');
                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                      } else if (message.indexOf("http") != -1) {
                          $("#ajaxBusy").dialog('close');
                          window.location = response;
                      }
                      else {
                          $("#ajaxBusy").dialog('close');
                          $("#ajaxProcessPayment").dialog('close');
                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + message + '</div>');
                          $(window).scrollTop(0);
                      }
                  });
                  return false;
              }
              else {
                  $("#payment-cod").submit();
                  return false;
              }
          });

          $("#paypalCccCheckout").on("click", function (e) {
              console.log("HERE ON PP");
              Api.PayPalCreateOrder(function (response) {
                  console.log(response);
                  if (response.success) {
                      location.href = response.payPalLink;
                  }
                  else {
                      $("#payPalpopUp .ErrorMessage").html('');
                      $("#payPalpopUp .Tab-container").html('');
                      $("#ajaxBusy").html('Error connecting to PayPal.');
                  }
              });
          });


          $("#ccpopUp #submitPayment").on("click", function (e) {

              var Total = 0;
              var finalPrice = Number($('#dynamic-total').text().replace(/[^0-9\.]+/g, ""));
              if ($('#OrderTotalGiftCard').val() == "" || $('#OrderTotalGiftCard').val() == undefined) {
                  Total = parseFloat(finalPrice).toFixed(2);
              } else {
                  Total = parseFloat($('#OrderTotalGiftCard').val()).toFixed(2);
              }
              //alert("here1");
              if (Checkout.bind.IsOrderTotalGreaterThanZero(Total)) {
                  var isValid = true;
                  if (!$("#radioCCList").is(':visible')) {
                      $('input[data-payment="number"],input[data-payment="exp-month"] option:selected,input[data-payment="exp-year"] option:selected,input[data-payment="cvc"]').each(function () {
                          if ($.trim($(this).val()) == '') {
                              isValid = false;
                              $(this).css({
                                  "border": "1px solid red",
                                  "background": "#FFCECE"
                              });
                          }
                          else {
                              $(this).css({
                                  "border": "1px solid #C3C3C3",
                                  "background": ""
                              });
                          }
                      });

                      if (!Checkout.bind.Mod10($('input[data-payment="number"]').val())) {
                          isValid = false;
                          $('#errornumber').show();
                          $('input[data-payment="number"]').css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }

                      if ($('input[data-payment="exp-month"] option:selected').val() > 12 || $('input[data-payment="exp-month"] option:selected').val() < 1) {
                          isValid = false;
                          $('#errormonth').show();
                          $('input[data-payment="exp-month"]').css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }

                      var currentYear = (new Date).getFullYear();
                      var currentMonth = (new Date).getMonth() + 1;

                      if ($('input[data-payment="exp-year"] option:selected').val() < currentYear) {
                          isValid = false;
                          $('#erroryear').show();
                          $('input[data-payment="exp-year"]').css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }

                      if ($('input[data-payment="exp-year"] option:selected').val() == currentYear && $('input[data-payment="exp-month"]').val() < currentMonth) {
                          isValid = false;
                          $('#errormonth').show();
                          $('input[data-payment="exp-month"]').css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                          $('#erroryear').show();
                          $('input[data-payment="exp-year"]').css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }
                      if ($('input[data-payment="cvc"]').val().length < 3) {
                          isValid = false;
                          $('#errorcardnumber').show();
                          $('input[data-payment="cvc"]').css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }
                  }

                  if (isValid == false) {
                      e.preventDefault();
                  }

                  if (isValid) {

                      $("#ajaxProcessPayment").html('');
                      if ($("#ajaxProcessPayment").html() == undefined) {
                          $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p></div>');
                      }

                      $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p>');
                      $("#ajaxProcessPayment").dialog({
                          title: 'Payment Application',
                          resizable: false,
                          modal: true,
                          create: function () { $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top"); },
                          closeOnEscape: false,
                          open: function (event, ui) {
                              $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
                          }
                      });

                      if ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) {
                          var cardNumber = $("#ccpopUp [data-payment='number']").val();
                          var cardCvcNum = $("#ccpopUp [data-payment='cvc']").val();
                          var cardExpMonth = $("#ccpopUp [data-payment='exp-month'] option:selected").val();
                          var cardExpYear = $("#ccpopUp [data-payment='exp-year'] option:selected").val();
                          console.log(cardExpMonth);
                          console.log(cardExpYear);
                      }

                      var PaymentToken = ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) ? "" : $("input[name='CCdetails']:checked").val();
                      var IsAnonymousUser = $(".username").text().length > 0 ? false : true;
                      var IsSaveCreditCard = ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) ? $("#SaveCart").is(':checked') : false;
                      var CardHolderName = $('#CCHolderName').val();
                      var CustomerGUID = $("#hdnCustomerGUID").val();

                      var guid = $('#GUID').val();

                      var discount = parseFloat($('#Discount').val()).toFixed(2);
                      var ShippingCost = parseFloat($('#ShippingCost').val()).toFixed(2);
                      var TaxCost = parseFloat($('#TaxCost').val()).toFixed(2);
                      var SubTotal = parseFloat($('#SubTotal').val()).toFixed(2);

                      var cardType = Checkout.bind.detectCardType(cardNumber);

                      if ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) {
                          if (cardType.toLowerCase() != $("input[name='PaymentProviders']:checked").val().toLowerCase()) {
                              $('#ajaxProcessPayment').dialog('close');
                              var message = "The selected card type is of " + $("input[name='PaymentProviders']:checked").val().toLowerCase() + ".  Please check the credit card number and the card type.";

                              if ($("#ajaxProcessPaymentError").html() == undefined) {
                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">' + message + '</p></div>');
                              } else {
                                  $("#ajaxProcessPaymentError").html(message);
                              }

                              if ($('#ajaxProcessPaymentError').html() != undefined) {
                                  $('#ajaxProcessPaymentError').dialog({
                                      title: 'Payment Application',
                                      resizable: false,
                                      modal: true,
                                      create: function () {
                                          $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                      },
                                      buttons: {
                                          Ok: function () {
                                              $(this).dialog('close');
                                          }
                                      },
                                      closeOnEscape: false,
                                      open: function (event, ui) {
                                          $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                      }
                                  });
                              }
                              return false;
                          }
                      }

                      var OrderId = 1;

                      var BillingFirstName = $('#BillingFirstName').val();
                      var BillingLastName = $('#BillingLastName').val();
                      var BillingName = $('#BillingName').val();
                      var BillingStreetAddress1 = $('#BillingStreetAddress1').val();
                      var BillingStreetAddress2 = $('#BillingStreetAddress2').val();
                      var BillingCity = $('#BillingCity').val();
                      var BillingStateCode = $('#BillingStateCode').val();
                      var BillingCountryCode = $('#BillingCountryCode').val();
                      var BillingPhoneNumber = $('#BillingPhoneNumber').val();
                      var BillingPostalCode = $('#BillingPostalCode').val();
                      var BillingEmailId = $('#BillingEmailId').val();

                      var paymentSettingId = $('#CCPaymentOptionId').val();

                      var GatewayLoginName = $('#GatewayLoginName').val();
                      var GatewayLoginPassword = $('#GatewayLoginPassword').val();
                      var GatewayTestMode = $('#GatewayTestMode').val();
                      var GatewayCustom1 = $('#GatewayCustom1').val();
                      var GatewayPreAuthorize = $('#GatewayPreAuthorize').val();
                      var GatewayTransactionKey = $('#GatewayTransactionKey').val();
                      var GatewayCurrencyCode = $('#GatewayCurrencyCode').val();
                      var Gateway = $('#GatewayType').val();

                      var ReturnUrl = String.format(Checkout.GloabalVariables.ZnodeDemoPaymentSuccessUrl, $("#CCPaymentOptionId").val());
                      var CancelUrl = Checkout.GloabalVariables.ZnodeDemoPaymentCancelUrl;

                      var CustomerPaymentProfileId = $('#CustomerPaymentProfileId').val();
                      var CustomerProfileId = $('#CustomerProfileId').val();
                      var CardDataToken = $('#CardDataToken').val();

                      var Subscriptions = new Array();

                      if ($('#RecurringBillingFrequency').val() != undefined) {
                          var loopCount = $('#RecurringBillingFrequency').length;
                          for (var iCount = 0; iCount < loopCount; iCount++) {

                              if ($($('#RecurringBillingInd')[iCount]).val() != "False") {

                                  var period = $($('#RecurringBillingFrequency')[iCount]).val();
                                  var billingInd = $($('#RecurringBillingInd')[iCount]).val();
                                  var billingIndinInt = 0;

                                  if (billingInd == 'True') {
                                      billingIndinInt = 1;
                                  }

                                  var item = {
                                      Amount: $($('#RecurringBillingInitialAmount')[iCount]).val(),
                                      Frequency: period,
                                      GUID: "",
                                      InitialAmount: $($('#RecurringBillingInitialAmount')[iCount]).val(),
                                      InstallmentInd: billingIndinInt,
                                      InvoiceNo: 1,
                                      Period: "DAY",
                                      TotalCycles: 1,
                                      ProfileName: $($('#RecurringProfileName')[iCount]).val()
                                  }

                                  Subscriptions.push(item);
                              }
                          }
                      }
                      var gatewayName = $("#hdnGatwayName").val();
                      var paymentAppGatewayName = gatewayName;
                      if (gatewayName != undefined && gatewayName.length > 0) {
                          var paymentAppGatewayName = gatewayName.toLowerCase();

                          if (gatewayName.toLowerCase() == 'authorize.net') {
                              paymentAppGatewayName = 'authorizenet';
                          }
                          else if (gatewayName.toLowerCase() == 'paymentech orbital') {
                              paymentAppGatewayName = 'paymenttech';
                          }
                          else if (gatewayName.toLowerCase() == 'payflow') {
                              if ($("#hdnEncryptedTotalAmount").val() != undefined && $("#hdnEncryptedTotalAmount").val() != null) {
                                  Total = $("#hdnEncryptedTotalAmount").val();
                              }
                          }
                      }
                      var payment = {
                          "GUID": guid,
                          "GatewayLoginName": GatewayLoginName,
                          "GatewayLoginPassword": GatewayLoginPassword,
                          "GatewayTestMode": GatewayTestMode,
                          "GatewayCustom1": GatewayCustom1,
                          "GatewayPreAuthorize": GatewayPreAuthorize,
                          "GatewayTransactionKey": GatewayTransactionKey,
                          "GatewayType": paymentAppGatewayName,
                          "GatewayCurrencyCode": GatewayCurrencyCode,
                          "OrderId": OrderId,
                          "BillingCity": BillingCity,
                          "BillingCountryCode": BillingCountryCode,
                          "BillingFirstName": BillingFirstName,
                          "BillingLastName": BillingLastName,
                          "BillingName": BillingName,
                          "BillingPhoneNumber": BillingPhoneNumber,
                          "BillingPostalCode": BillingPostalCode,
                          "BillingStateCode": BillingStateCode,
                          "BillingStreetAddress1": BillingStreetAddress1,
                          "BillingStreetAddress2": BillingStreetAddress2,
                          "BillingEmailId": BillingEmailId,
                          "ShippingCost": ShippingCost,
                          "SubTotal": SubTotal,
                          "TaxCost": TaxCost,
                          "Total": Total,
                          "Discount": discount,
                          "CardSecurityCode": cardCvcNum,
                          "CardNumber": cardNumber,
                          "CardExpirationMonth": cardExpMonth,
                          "CardExpirationYear": cardExpYear,
                          "CancelUrl": CancelUrl,
                          "ReturnUrl": ReturnUrl,
                          "CustomerPaymentProfileId": CustomerPaymentProfileId,
                          "CustomerProfileId": CustomerProfileId,
                          "CardDataToken": CardDataToken,
                          "CardType": cardType,
                          "PaymentSettingId": paymentSettingId,
                          "Subscriptions": Subscriptions,

                          "IsAnonymousUser": IsAnonymousUser,
                          "IsSaveCreditCard": IsSaveCreditCard,
                          "CardHolderName": CardHolderName,
                          "CustomerGUID": CustomerGUID,
                          "PaymentToken": PaymentToken
                      };
                      //alert(JSON.stringify(payment));
                      $("#ccpopUp").hide();

                      submitCard(payment, function (response) {
                          if (response.Data == undefined) {
                              if (response.indexOf("Unauthorized") > 0) {

                                  $("#ajaxProcessPayment").html('');
                                  $("#ccpopUp [data-payment='number']").val('');
                                  $("#ccpopUp [data-payment='cvc']").val('');
                                  $("#ccpopUp [data-payment='exp-month']").val('');
                                  $("#ccpopUp [data-payment='exp-year']").val('');
                                  $("#ajaxProcessPayment").dialog('close');

                                  message = response;

                                  if ($("#ajaxProcessPaymentError").html() == undefined) {
                                      $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                  } else {
                                      $("#ajaxProcessPaymentError").html('We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.');
                                  }

                                  if ($('#ajaxProcessPaymentError').html() != undefined) {
                                      $('#ajaxProcessPaymentError').dialog({
                                          title: 'Payment Application',
                                          resizable: false,
                                          modal: true,
                                          create: function () {
                                              $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                          },
                                          buttons: {
                                              Ok: function () {
                                                  $(this).dialog('close');
                                              }
                                          },
                                          closeOnEscape: false,
                                          open: function (event, ui) {
                                              $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                          }
                                      });
                                  }

                                  return false;
                              }
                          } else {
                              var isSuccess = response.Data.IsSuccess;
                              if (isSuccess) {
                                  var customerProfileId = response.Data.CustomerProfileId;
                                  var customerPaymentId = response.Data.CustomerPaymentProfileId;
                                  var customerGuid = response.Data.CustomerGUID;
                                  var paymentSettingId = $("#CCPaymentOptionId").val();
                                  var paymentToken = $("input[name='CCdetails']:checked").val();
                                  var guid = response.Data.GUID;

                                  var paymentModel = {
                                      PaymentSettingId: paymentSettingId,
                                      CustomerProfileId: customerProfileId,
                                      CustomerPaymentId: customerPaymentId,
                                      CustomerGuid: customerGuid,
                                      PaymentToken: paymentToken,
                                      GUID: guid
                                  };

                                  $.ajax({
                                      type: "POST",
                                      url: "/checkout/submitpayment",
                                      data: paymentModel,
                                      success: function (response) {
                                          var newLocation = response.Data;
                                          if (newLocation != undefined && newLocation.toLowerCase().indexOf('missing card data') >= 0) {
                                              $('#ajaxProcessPayment').html('');
                                              $('#ccpopUp [data-payment="number"]').val('');
                                              $('#ccpopUp [data-payment="cvc"]').val('');
                                              $('#ccpopUp [data-payment="exp-month"]').val('');
                                              $('#ccpopUp [data-payment="exp-year"]').val('');
                                              $('#ajaxProcessPayment').dialog('close');
                                              if ($('#ajaxProcessPaymentError').html() == undefined) {
                                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">Error occurred during processing an order. Order could not be placed as card data is missing.</p></div>');
                                              } else {
                                                  $('#ajaxProcessPaymentError').html('Error occurred during processing an order. Order could not be placed as card data is missing.');
                                              }
                                          } else if (newLocation != undefined && newLocation.indexOf('Message=') >= 0) {
                                              var message = newLocation.substr(newLocation.indexOf('=') + 1);
                                              $('#ajaxProcessPayment').html('');
                                              $('#ccpopUp [data-payment="number"]').val('');
                                              $('#ccpopUp [data-payment="cvc"]').val('');
                                              $('#ccpopUp [data-payment="exp-month"]').val('');
                                              $('#ccpopUp [data-payment="exp-year"]').val('');
                                              $('#ajaxProcessPayment').dialog('close');

                                              if ($('#ajaxProcessPaymentError').html() == undefined) {
                                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                              } else {
                                                  $('#ajaxProcessPaymentError').html('We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.');
                                              }
                                          } else if (newLocation != undefined) {
                                              $('#ajaxProcessPaymentError').remove();
                                              window.location = newLocation;
                                          } else {
                                              $('#ccpopUp .ErrorMessage').html('');
                                              $('#ccpopUp [data-payment="number"]').val('');
                                              $('#ccpopUp [data-payment="cvc"]').val('');
                                              //$('#ccpopUp [data-payment="exp-month"]').val('');
                                              //$('#ccpopUp [data-payment="exp-year"]').val('');
                                              $('#ajaxProcessPayment').dialog('close');
                                              if ($('#ajaxProcessPaymentError').html() == undefined) {
                                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">Error occurred during processing an order. Order could not be placed.</p></div>');
                                              } else {
                                                  $('#ajaxProcessPaymentError').html('Error occurred during processing an order. Order could not be placed.');
                                              }
                                          }

                                          if ($('#ajaxProcessPaymentError').html() != undefined) {
                                              $('#ajaxProcessPaymentError').dialog({
                                                  title: 'Payment Application',
                                                  resizable: false,
                                                  modal: true,
                                                  create: function () {
                                                      $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                                  },
                                                  buttons: {
                                                      Ok: function () {
                                                          $(this).dialog('close');
                                                      }
                                                  },
                                                  closeOnEscape: false,
                                                  open: function (event, ui) {
                                                      $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                                  }
                                              });
                                          }

                                          return false;
                                      },
                                      error: function () {
                                          ajax.errorOut("API Endpoint not available: " + url);
                                      }
                                  });
                              }
                              else {
                                  var message = response.Data.ResponseText;
                                  if (message == undefined) {
                                      message = response.Data.GatewayResponseData;
                                      if (message == undefined) {
                                          message = response.Data;
                                      }
                                  }
                                  $("#ajaxProcessPayment").html('');
                                  $("#ccpopUp [data-payment='number']").val('');
                                  $("#ccpopUp [data-payment='cvc']").val('');
                                  $("#ccpopUp [data-payment='exp-month']").val('');
                                  $("#ccpopUp [data-payment='exp-year']").val('');
                                  $("#ajaxProcessPayment").dialog('close');
                                  if (message.length > 0 && message != null) {
                                      if ($("#ajaxProcessPaymentError").html() == undefined) {
                                          $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                      } else {
                                          $("#ajaxProcessPaymentError").html('We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.');
                                      }
                                  }
                                  else {
                                      if ($("#ajaxProcessPaymentError").html() == undefined) {
                                          $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                      } else {
                                          $("#ajaxProcessPaymentError").html('We were unable to process your credit card payment. <br /><br /><br />If the problem persists, contact us to complete your order.');
                                      }
                                  }
                                  if ($('#ajaxProcessPaymentError').html() != undefined) {
                                      $('#ajaxProcessPaymentError').dialog({
                                          title: 'Payment Application',
                                          resizable: false,
                                          modal: true,
                                          create: function () {
                                              $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                          },
                                          buttons: {
                                              Ok: function () {
                                                  $(this).dialog('close');
                                              }
                                          },
                                          closeOnEscape: false,
                                          open: function (event, ui) {
                                              $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                          }
                                      });
                                  }
                              }
                          }
                      });
                      return false;
                  }
                  return false;
              }
          });


      },
      SetEncryptedTotalAmount: function (total) {

          if ($("#hdnEncryptedTotalAmount").val() != undefined && $("#hdnEncryptedTotalAmount").val() != null) {
              $("#hdnEncryptedTotalAmount").val(total);
          }
          else {
              $('body').append('<input type="hidden" id="hdnEncryptedTotalAmount" value="' + total + '">');
          }
      },
      IsOrderTotalGreaterThanZero: function (total) {
          if (total > 0.00) {
              return true;
          } else {
              var paymentURL = String.format(Checkout.GloabalVariables.ZnodeDemoPaymentSuccessUrl, 0);
              paymentURL = paymentURL + "&token=null";
              window.location = paymentURL;
          }
      },
      SetCreditCardValidations: function () {
          $('input[data-payment="exp-month"]').on("keypress", function (e) {
              if (e.which != 8 && e.which != 0 && (e.wchich < 48 || e.which > 57)) {
                  return false;
              }
          });

          $('input[data-payment="exp-month"]').on("focusout", function (e) {
              var monthVal = $('input[data-payment="exp-month"]').val();
              if (monthVal.length == 1 && (monthVal >= 1 || monthVal <= 9)) {
                  monthVal = 0 + monthVal;
                  $('input[data-payment="exp-month"]').val(monthVal);
              }
          });

          $('input[data-payment="exp-year"]').on("keypress", function (e) {
              if (e.which != 8 && e.which != 0 && (e.wchich < 48 || e.which > 57)) {
                  return false;
              }
          });

          $('input[data-payment="cvc"]').on("keypress", function (e) {
              if (e.which != 8 && e.which != 0 && (e.wchich < 48 || e.which > 57)) {
                  return false;
              }
          });
      },
      Mod10: function (ccNum) {
          var valid = "0123456789";  // Valid digits in a credit card number
          var len = ccNum.length;  // The length of the submitted cc number
          var iCCN = parseInt(ccNum);  // integer of ccNum
          var sCCN = ccNum.toString();  // string of ccNum

          sCCN = sCCN.replace(/^\s+|\s+$/g, '');  // strip spaces

          var iTotal = 0;  // integer total set at zero
          var bNum = true;  // by default assume it is a number
          var bResult = false;  // by default assume it is NOT a valid cc
          var temp;  // temp variable for parsing string
          var calc;  // used for calculation of each digit

          // Determine if the ccNum is in fact all numbers
          for (var j = 0; j < len; j++) {
              temp = "" + sCCN.substring(j, j + 1);
              if (valid.indexOf(temp) == "-1") {
                  bNum = false;
              }
          }

          // if it is NOT a number, you can either alert to the fact, or just pass a failure
          if (!bNum) {
              bResult = false;
          }

          // Determine if it is the proper length
          if ((len == 0) && (bResult)) {  // nothing, field is blank AND passed above # check
              bResult = false;
          } else {  // ccNum is a number and the proper length - let's see if it is a valid card number
              if (len >= 15) {  // 15 or 16 for Amex or V/MC
                  for (var i = len; i > 0; i--) {  // LOOP throught the digits of the card
                      calc = parseInt(iCCN) % 10;  // right most digit
                      calc = parseInt(calc);  // assure it is an integer
                      iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
                      i--;  // decrement the count - move to the next digit in the card
                      iCCN = iCCN / 10;                               // subtracts right most digit from ccNum
                      calc = parseInt(iCCN) % 10;    // NEXT right most digit
                      calc = calc * 2;                                 // multiply the digit by two
                      // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
                      // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
                      switch (calc) {
                      case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
                      case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
                      case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
                      case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
                      case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
                      default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
                      }
                      iCCN = iCCN / 10;  // subtracts right most digit from ccNum
                      iTotal += calc;  // running total of the card number as we loop
                  }  // END OF LOOP
                  if ((iTotal % 10) == 0) {  // check to see if the sum Mod 10 is zero
                      bResult = true;  // This IS (or could be) a valid credit card number.
                  } else {
                      bResult = false;  // This could NOT be a valid credit card number
                  }
              }
          }
          return bResult; // Return the results
      },

      IsMatchRegularExpressionString: function (str, regax) {
          if (str.match(regax)) {
              return true;
          }
          else {
              return false;
          }
      },

      detectCardType: function (number) {

          var re = {
              electron: /^(4026|417500|4405|4508|4844|4913|4917)\d+$/,
              maestro: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\d+$/,
              dankort: /^(5019)\d+$/,
              interpayment: /^(636)\d+$/,
              unionpay: /^(62|88)\d+$/,
              visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
              mastercard: /^5[1-5]\d{14}$|^2(?:2(?:2[1-9]|[3-9]\d)|[3-6]\d\d|7(?:[01]\d|20))\d{12}$/,
              amex: /^3[47][0-9]{13}$/,
              diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
              discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,
              jcb: /^(?:2131|1800|35\d{3})\d{11}$/
          };
          if (re.electron.test(number)) {
              return 'ELECTRON';
          } else if (re.maestro.test(number)) {
              return 'MAESTRO';
          } else if (re.dankort.test(number)) {
              return 'DANKORT';
          } else if (re.interpayment.test(number)) {
              return 'INTERPAYMENT';
          } else if (re.unionpay.test(number)) {
              return 'UNIONPAY';
          } else if (re.visa.test(number)) {
              return 'VISA';
          } else if (re.mastercard.test(number)) {
              return 'MASTERCARD';
          } else if (re.amex.test(number)) {
              return 'AMEX';
          } else if (re.diners.test(number)) {
              return 'DINERS';
          } else if (re.discover.test(number)) {
              return 'DISCOVER';
          } else if (re.jcb.test(number)) {
              return 'JCB';
          } else {
              return undefined;
          }
      },
      giftCard: function () {
          _debug("bind.giftcard()");

          // Close gift card after application
          $("#giftcard-action").on("click", ".close-giftcard", function (e) {
              e.preventDefault();
              $("#layout-checkout-payment .payment-method").hide();
              var defaultPayment = "#" + $("#payment-methods li").first().data("toggle");
              $(defaultPayment).show();

              $("#payment-methods li").removeClass("active").show();

              $("#payment-methods li a:eq(0)").trigger("click");
              scrollToTop(300, "#payment-container");
          });



          // Apply gift card, handles invalid and valid codes
          $("#payment-giftcard").on("click", ".giftcard-apply", function () {
              // Gets nearest gift card number
              // Need this because there are two gift card inputs after the first submit
              var form = $(this).closest(".form");
              var giftCardNumber = $("input[name='giftcard']").val();

              if (giftCardNumber == "" || giftCardNumber == null) {
                  isValid = false;
                  $("input[name='giftcard']").css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $("input[name='giftcard']").css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });

                  // Apply card and get back new total details
                  Api.useGiftCard(giftCardNumber, function (response) {

                      // Is it a valid number?
                      if (response.success) {
                          $("#giftcard-initial").hide();

                          $("#GiftCardAmount").val(response.data.giftcardamount);

                          // If the gift card covers order total then offer button, else link to close results
                          if (response.data.paid) {
                              var template = $("#tmpl-giftcard-finish").html();
                          } else {
                              var template = $("#tmpl-giftcard-continue").html();
                          }


                          $("#dynamic-total").html(response.data.total);
                          var html = Mustache.render(template, response.data);

                          $("#giftcard-action").html(html);
                      } else {


                          $("form #error-giftCard").html(response.message);
                      }
                  });
              }
          });


      },
      // Toggle for billing address same-as
      billingAddress: function () {
          if ($("#UseSameAsShippingAddress").attr("checked") == "checked") {
              $("#billingaddressform .edit-address-form").toggle();
          }

          $("#UseSameAsShippingAddress").on("click", function () {
              $("#billingaddressform .edit-address-form").toggle();
          });
      },
      BillingSameAsShippingHandler: function () {

          if ($("#billingSameAsShippingAddress").is(':checked')) {
              $("#billingaddressform").hide();
          }

          $("#billingSameAsShippingAddress").on("click", function () {

              if ($("#billingSameAsShippingAddress").is(':checked')) {
                  $("#billingaddressform").hide();
              } else {
                  $("#billingaddressform").show();
              }
          });

      },

      AddNewCCDetailsHandler: function () {

          if ($("#chkAddCCDetails").is(':checked')) {
              $("#credit-card-div").show();
              $('#Save-credit-card').hide();
          } else {
              $("#credit-card-div").hide();
              $('#Save-credit-card').show();
          }
      },
      // Get State by country
      setStateByCountry: function () {

          $(".address_country").on("change", function (e) {
              var shipToCallingDropDown = $($(this).parent().parent().parent().parent()).attr("Id");
              var countryId = $(this).attr('id');

              var shippingAddressStateCode = "";
              var billingAddressStateCode = "";

              if (countryId == "ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode") {
                  shippingAddressStateCode = $("#ShippingBillingAddressViewModel_ShippingAddressModel_StateCode").val();
              }

              if (countryId == "ShippingBillingAddressViewModel_BillingAddressModel_CountryCode") {
                  billingAddressStateCode = $("#ShippingBillingAddressViewModel_BillingAddressModel_StateCode").val();
              }

              if (countryId == "ShippingAddressModel_CountryCode") {
                  shippingAddressStateCode = $("#ShippingAddressModel_StateCode").val();
              }
              if (countryId == "BillingAddressModel_CountryCode") {
                  billingAddressStateCode = $("#BillingAddressModel_StateCode").val();
              }

              if (countryId.indexOf("ShippingAddressModel") > -1) {
                  Checkout.bind.ResetCityAndZipCodeShipping();
              }
              else {
                  Checkout.bind.ResetCityAndZipCodeBilling();
              }
              var stateId = countryId.replace("CountryCode", "StateCode");
              var countryCode = $(this).val();
              Api.getStateByCountryCode(countryCode, function (response) {
                  $('#' + stateId).empty();
                  for (var i = 0; i < response.length; i++) {
                      $("#" + stateId).append("<option value='" + response[i].Code + "'>" + response[i].Name + "</option>");
                  }
                  if (response.length < 1) {
                      $("#" + stateId).append("<option value=''>Please Select</option>");
                  }

                  if (countryId == "ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode") {
                      if (response.length > 1) {
                          if (shippingAddressStateCode != "" && shippingAddressStateCode != null) {
                              $("#ShippingBillingAddressViewModel_ShippingAddressModel_StateCode").val(shippingAddressStateCode);
                          }
                      }
                  }
                  if (countryId == "ShippingBillingAddressViewModel_BillingAddressModel_CountryCode") {
                      if (response.length > 1) {
                          if (billingAddressStateCode != "" && billingAddressStateCode != null) {
                              $("#ShippingBillingAddressViewModel_BillingAddressModel_StateCode").val(billingAddressStateCode);
                          }
                      }
                  }

                  if (countryId == "ShippingAddressModel_CountryCode") {
                      if (response.length > 1) {
                          if (shippingAddressStateCode != "" && shippingAddressStateCode != null) {
                              $("#ShippingAddressModel_StateCode").val(shippingAddressStateCode);
                          }
                      }
                  }
                  if (countryId == "BillingAddressModel_CountryCode") {
                      if (response.length > 1) {
                          if (billingAddressStateCode != "" && billingAddressStateCode != null) {
                              $("#BillingAddressModel_StateCode").val(billingAddressStateCode);
                          }
                      }
                  }
              });
              if (shipToCallingDropDown == "divShipping") {
                  if ($("#checkoutform").length > 0) {
                      if (countryCode) {
                          overlayforwaitblock();
                          $.ajax({
                              url: "/Checkout/GetShippingMethodsByCountryCode?isCountryStateTax=true&countryShippingCode=true",
                              data: $("#checkoutform").serialize(),
                              type: 'POST',
                              success: function (data) {
                                  overlayforwaitnone();
                                  var cartData = $.parseHTML(data.data.cartView);
                                  var shippingMethods = $.parseHTML(data.data.shippingMethodsView);
                                  $(".cart-summary").html($(cartData).find('.cart-summary').html());
                                  $("#singlepage-checkout-shipping-content").html(data.data.shippingMethodsView);
                                  $('input[name="ShippingOptions"]')[0].checked = true;

                              }
                          });
                      }
                  }
              }
          });
          if ($(".address_country").val() == "") {
              $('#ShippingAddressModel_StateCode').append("<option value=''>Please Select</option>");
          }
      },
      setDefaultState: function () {
          this.callAddressChange(0);
          this.callAddressChange(1);
      },
      callAddressChange: function (addressCnt) {
          var state = $($(".hdn_StateCode")[addressCnt]).val();
          if (state != undefined && state != null && state.length < 1) {
              $($(".address_country")[addressCnt]).change();
          }
      },
      // Get State by country
      setStateByCountryById: function () {
          $("#address_country").on("change", function (e) {
              var stateCode = $(this).val();
              Checkout.bind.ResetCityAndZipCode();
              Api.getStateByCountryCode(stateCode, function (response) {
                  $('#address_state').empty();
                  for (var i = 0; i < response.length; i++) {
                      $("#address_state").append("<option value='" + response[i].Code + "'>" + response[i].Name + "</option>");
                  }
                  if (response.length < 1) {
                      $("#address_state").append("<option value=''>Please Select</option>");
                  }
              });
          });
      },
      setDefaultStateById: function () {
          var state = $("#hdn_StateCode").val();
          if (state.length < 1) {
              $("#address_country").change();
          }
      },
      OnStateChange: function () {
          $(".address_state").on("change", function (e) {
              var stateId = $(this).attr('id');
              var state = $(".address_state").val();
              if (stateId.indexOf("ShippingAddressModel") > -1) {
                  Checkout.bind.ResetCityAndZipCodeShipping();

                  if ($("#checkoutform").length > 0) {
                      if (state) {
                          overlayforwaitblock();
                          $.ajax({
                              url: "/Checkout/GetUpdatedCart?isCountryStateTax=true",
                              data: $("#checkoutform").serialize(),
                              type: 'POST',
                              success: function (data) {
                                  overlayforwaitnone();
                                  var cartData = $.parseHTML(data)
                                  $(".cart-summary").html($(cartData).find('.cart-summary').html())

                              }
                          });
                      }
                  }
              }
              else {
                  Checkout.bind.ResetCityAndZipCodeBilling();
              }
          });
      },

      OnStateChangeForAddNewAddress: function () {
          $("#address_state").on("change", function (e) {
              Checkout.bind.ResetCityAndZipCode();
          });
      },
      ResetCityAndZipCodeBilling: function () {
          $('[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').val("");
          $('[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"]').val("");
          $('[name="BillingAddressModel.City"]').val("");
          $('[name="BillingAddressModel.PostalCode"]').val("");
          $("#ErrorMessage").html("");
      },
      ResetCityAndZipCodeShipping: function () {
          $('[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').val("");
          $('[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').val("");
          $('[name="ShippingAddressModel.City"]').val("");
          $('[name="ShippingAddressModel.PostalCode"]').val("");
          $("#ErrorMessage").html("");
          $('#address_city').val('');
          $('#address_zipcode').val('');
      },
      ResetCityAndZipCode: function () {
          $("#address_city").val("");
          $("#address_zipcode").val("");
      },
      ValidateEmail: function (email) {
          var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
          return expr.test(email);
      },

      SetCreditCardValidation: function () {
          var isValid = true;
          $('input[data-payment="number"],input[data-payment="exp-month"],input[data-payment="exp-year"],input[data-payment="cvc"]').each(function () {
              if ($.trim($(this).val()) == '') {
                  isValid = false;
                  $(this).css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $(this).css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
          });
          if (!Checkout.bind.Mod10($('input[data-payment="number"]').val())) {
              isValid = false;
              $('#errornumber').show();
              $('input[data-payment="number"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }

          if ($('input[data-payment="exp-month"]').val() > 12 || $('input[data-payment="exp-month"]').val() < 1) {
              isValid = false;
              $('#errormonth').show();
              $('input[data-payment="exp-month"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }

          var currentYear = (new Date).getFullYear();
          var currentMonth = (new Date).getMonth() + 1;

          if ($('input[data-payment="exp-year"]').val() < currentYear) {
              isValid = false;
              $('#erroryear').show();
              $('input[data-payment="exp-year"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }

          if ($('input[data-payment="exp-year"]').val() == currentYear && $('input[data-payment="exp-month"]').val() < currentMonth) {
              isValid = false;
              $('#errormonth').show();
              $('input[data-payment="exp-month"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
              $('#erroryear').show();
              $('input[data-payment="exp-year"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }

          if ($('input[data-payment="cvc"]').val().length < 3) {
              isValid = false;
              $('#errorcardnumber').show();
              $('input[data-payment="cvc"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }
          return isValid;
      },
      bindStatesForSelectedCountry: function (countryId, response) {
          var stateId = countryId.replace("CountryCode", "StateCode");
          states = response.States;
          $('#' + stateId).empty();
          for (var i = 0; i < states.length; i++) {
              $("#" + stateId).append("<option value='" + states[i].Code + "'>" + states[i].Name + "</option>");
          }
          if (states.length < 1) {
              $("#" + stateId).append("<option value=''>Please Select</option>");
          }
      },
      GetShippingMethods: function (event) {
          $('#status-message').remove();
          var value = $("input[name='ShippingOptions']:checked").val();
          var isValidAddress = true;
          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').each(function () {
              if ($.trim($(this).val()) == '') {
                  isValidAddress = false;
                  $(this).css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $(this).css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
          });

          var country = $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"] option:selected').val();
          if (country == "0" || country == "") {
              isValidAddress = false;
              $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }
          else {
              $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                  "border": "1px solid #c3c3c3",
                  "background": ""
              });
          }
          if (isValidAddress == false) {
              return false;
          }
          else {
              overlayforwaitblock();
              $("#SuccessMessage").show();
              $.ajax({
                  url: "/Checkout/GetUpdatedCart",
                  data: $("#checkoutform").serialize(),
                  type: 'POST',
                  success: function (data) {
                      overlayforwaitnone();
                      var cartData = $.parseHTML(data)
                      $(".cart-summary").html($(cartData).find('.cart-summary').html())
                      var errorMessage = $(cartData).find('#status-message').html();
                      if (errorMessage != undefined && errorMessage != "") {
                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                          $(cartData).find('#status-message').html('');
                      }
                      else {
                          if (errorMessage == undefined) {
                              $("#SuccessMessage").hide();
                              $("#SuccessMessage").html('');

                              var orderTotal = $("#dynamic-order-total").text() != null && $("#dynamic-order-total").text() != "" && typeof $("#dynamic-order-total").text() != "undefined" ? $("#dynamic-order-total").text().trim() : $("#dynamic-order-total").text();
                              var yourstring = $("#dynamic-order-total").text().trim();

                              if ($("#dynamic-order-total").text() != null && $("#dynamic-order-total").text() != "" && typeof $("#dynamic-order-total").text() != "undefined" && $("#UserAccessId").val() == 3) {
                                  orderTotal = parseFloat(orderTotal.substring(1));
                                  $(".singlecheckoutsubmitpayment").remove();
                                  $(".singlecheckoutsubmitquote").remove();
                                  if (orderTotal > parseFloat($("#MaxBudget").val())) {
                                      $("#paymentSection").hide();
                                      $('.quotebutton').append("<button type='submit' id='singleCheckoutSubmitQuote' name='singleCheckoutSubmitQuote' class='btn-text-icon red singlecheckoutsubmitquote' onclick='Checkout.bind.SubmitQuoteForSingleCheckout(event)'>Submit For Approval</button>");
                                  }
                                  else {
                                      $("#paymentSection").show();
                                      if ($("#singleCheckoutSubmitPayment").html() == undefined) {
                                          $('.quotebutton').append("<button type='submit' id='singleCheckoutSubmitPayment' name='singleCheckoutSubmitPayment' class='btn-text-icon red pull-right singlecheckoutsubmitpayment' onclick='Checkout.bind.SubmitSinglePageCheckout(event)'><i class='zf-checkout'></i> Complete Purchase</button>");
                                      }
                                  }
                                  Checkout.bind.ResetReviewIndex();
                              }
                          }
                      }
                  }
              });
          }
      },

      CalculateShippingMethods: function () {
          $('#status-message').remove();
          var value = $("input[name='ShippingOptions']:checked").val();
          var isValidAddress = true;
          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').each(function () {
              if ($.trim($(this).val()) == '') {
                  isValidAddress = false;
              }
          });

          var country = $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"] option:selected').val();
          if (country == "0" || country == "") {
              isValidAddress = false;
          }
          if (isValidAddress == false) {
              return false;
          }
          else {
              overlayforwaitblock();
              $("#SuccessMessage").show();
              $.ajax({
                  url: "/Checkout/GetUpdatedCart",
                  data: $("#checkoutform").serialize(),
                  type: 'POST',
                  success: function (data) {
                      overlayforwaitnone();
                      var cartData = $.parseHTML(data)
                      $(".cart-summary").html($(cartData).find('.cart-summary').html())
                      var errorMessage = $(cartData).find('#status-message').html();
                      if (errorMessage != undefined && errorMessage != "") {
                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                          $(cartData).find('#status-message').html('');
                      }
                      else {
                          if (errorMessage == undefined) {
                              $("#SuccessMessage").hide();
                              $("#SuccessMessage").html('');
                          }
                      }
                      Checkout.bind.ResetReviewIndex();
                  }
              });
          }
      },

      PaymentProcess: function () {
          isValid = true;
          $('#status-message').remove();
          $("#ajaxProcessPayment").html('');
          if ($("#ajaxProcessPayment").html() == undefined) {
              $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p></div>');
          }

          $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p>');
          $("#ajaxProcessPayment").dialog({
              title: 'Payment Application',
              resizable: false,
              modal: true,
              create: function () {
                  $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top");
              },
              closeOnEscape: false,
              open: function (event, ui) {
                  $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
              }
          });

          $.ajax({
              url: "ValidateSinglePageCheckout",
              type: 'post',
              data: $("#checkoutform").serialize(),
              success: function (data) {
                  if (!data.HasError) {
                      if ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) {

                          var cardNumber = $("#ccpopUp [data-payment='number']").val();
                          var cardCvcNum = $("#ccpopUp [data-payment='cvc']").val();
                          var cardExpMonth = $("#ccpopUp [data-payment='exp-month'] option:selected").val();
                          var cardExpYear = $("#ccpopUp [data-payment='exp-year'] option:selected").val();
                          console.log(cardExpMonth);
                          console.log(cardExpYear);
                      }

                      var PaymentToken = ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) ? "" : $("input[name='CCdetails']:checked").val();
                      var IsAnonymousUser = $(".username").text().length > 0 ? false : true;
                      var IsSaveCreditCard = ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) ? $("#SaveCart").is(':checked') : false;
                      var CardHolderName = $('#CCHolderName').val();
                      var CustomerGUID = $("#hdnCustomerGUID").val();

                      var guid = $('#GUID').val();

                      var discount = parseFloat($('#Discount').val()).toFixed(2);
                      var ShippingCost = parseFloat($('#ShippingCost').val()).toFixed(2);
                      var TaxCost = parseFloat($('#TaxCost').val()).toFixed(2);
                      var SubTotal = parseFloat($('#SubTotal').val()).toFixed(2);
                      var Total = parseFloat($('#Total').val()).toFixed(2);

                      var cardType = Checkout.bind.detectCardType(cardNumber);

                      if ($("#addNewCreditCard-panel").attr("class").indexOf("active") != -1) {
                          if (cardType.toLowerCase() != $("input[name='PaymentProviders']:checked").val().toLowerCase()) {
                              $('#ajaxProcessPayment').dialog('close');
                              var message = "The selected card type is of " + $("input[name='PaymentProviders']:checked").val().toLowerCase() + ".  Please check the credit card number and the card type.";

                              if ($("#ajaxProcessPaymentError").html() == undefined) {
                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">' + message + '</p></div>');
                              } else {
                                  $("#ajaxProcessPaymentError").html(message);
                              }

                              if ($('#ajaxProcessPaymentError').html() != undefined) {
                                  $('#ajaxProcessPaymentError').dialog({
                                      title: 'Payment Application',
                                      resizable: false,
                                      modal: true,
                                      create: function () {
                                          $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                      },
                                      buttons: {
                                          Ok: function () {
                                              $(this).dialog('close');
                                          }
                                      },
                                      closeOnEscape: false,
                                      open: function (event, ui) {
                                          $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                      }
                                  });
                              }
                              return false;
                          }
                      }

                      var OrderId = 1;
                      var BillingFirstName = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"]').val();
                      var BillingLastName = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"]').val();
                      var BillingName = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.Name"]').val();
                      var BillingStreetAddress1 = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"]').val();
                      var BillingStreetAddress2 = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress2"]').val();
                      var BillingCity = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').val();
                      var BillingStateCode = $("#ShippingBillingAddressViewModel_ShippingAddressModel_StateCode option:selected").val();
                      var BillingCountryCode = $("#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode option:selected").val();
                      var BillingPhoneNumber = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PhoneNumber"]').val();
                      var BillingPostalCode = $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"]').val();
                      var BillingEmailId = $('input[name="ShippingBillingAddressViewModel.EmailAddress"]').val();

                      if ($('#billingSameAsShippingAddress').is(":checked")) {
                          BillingFirstName = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"]').val();
                          BillingLastName = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"]').val();
                          BillingName = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.Name"]').val();
                          BillingStreetAddress1 = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"]').val();
                          BillingStreetAddress2 = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress2"]').val();
                          BillingCity = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').val();
                          BillingStateCode = $("#ShippingBillingAddressViewModel_ShippingAddressModel_StateCode option:selected").val();
                          BillingCountryCode = $("#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode option:selected").val();
                          BillingPhoneNumber = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').val();
                          BillingPostalCode = $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').val();
                      }

                      var GatewayCurrencyCode = $('#GatewayCurrencyCode').val();
                      var Gateway = $('#GatewayType').val();

                      var ReturnUrl = String.format(Checkout.GloabalVariables.ZnodeDemoPaymentSuccessUrl, $("#CCPaymentOptionId").val());
                      var CancelUrl = location.protocol + "//" + location.host + "/checkout/SingleCheckout?";

                      var gatewayName = $("#hdnGatwayName").val();
                      var paymentAppGatewayName = gatewayName;
                      if (gatewayName != undefined && gatewayName.length > 0) {
                          var paymentAppGatewayName = gatewayName.toLowerCase();

                          if (gatewayName.toLowerCase() == 'authorize.net') {
                              paymentAppGatewayName = 'authorizenet';
                          }

                          else if (gatewayName.toLowerCase() == 'paymentech orbital') {
                              paymentAppGatewayName = 'paymenttech';
                          }
                          else if (gatewayName.toLowerCase() == 'payflow') {
                              if ($("#hdnEncryptedTotalAmount").val() != undefined && $("#hdnEncryptedTotalAmount").val() != null) {
                                  Total = $("#hdnEncryptedTotalAmount").val();
                              }
                          }
                      }

                      var payment = {
                          "GUID": guid,
                          "GatewayType": paymentAppGatewayName,
                          "GatewayCurrencyCode": GatewayCurrencyCode,
                          "OrderId": OrderId,
                          "BillingCity": BillingCity,
                          "BillingCountryCode": BillingCountryCode,
                          "BillingFirstName": BillingFirstName,
                          "BillingLastName": BillingLastName,
                          "BillingName": BillingName,
                          "BillingPhoneNumber": BillingPhoneNumber,
                          "BillingPostalCode": BillingPostalCode,
                          "BillingStateCode": BillingStateCode,
                          "BillingStreetAddress1": BillingStreetAddress1,
                          "BillingStreetAddress2": BillingStreetAddress2,
                          "BillingEmailId": BillingEmailId,
                          "ShippingCost": ShippingCost,
                          "SubTotal": SubTotal,
                          "TaxCost": TaxCost,
                          "Total": Total,
                          "Discount": discount,
                          "CardSecurityCode": cardCvcNum,
                          "CardNumber": cardNumber,
                          "CardExpirationMonth": cardExpMonth,
                          "CardExpirationYear": cardExpYear,
                          "CancelUrl": CancelUrl,
                          "ReturnUrl": ReturnUrl,
                          "CardType": cardType,
                          "PaymentSettingId": $("#CCPaymentOptionId").val(),

                          "IsAnonymousUser": IsAnonymousUser,
                          "IsSaveCreditCard": IsSaveCreditCard,
                          "CardHolderName": CardHolderName,
                          "CustomerGUID": CustomerGUID,
                          "PaymentToken": PaymentToken
                      };

                      $("#ccpopUp").hide();

                      submitCard(payment, function (response) {
                          if (response.Data == undefined) {
                              if (response.indexOf("Unauthorized") > 0) {

                                  $("#ajaxProcessPayment").html('');
                                  $("#ccpopUp [data-payment='number']").val('');
                                  $("#ccpopUp [data-payment='cvc']").val('');
                                  $("#ccpopUp [data-payment='exp-month']").val('');
                                  $("#ccpopUp [data-payment='exp-year']").val('');
                                  $("#ajaxProcessPayment").dialog('close');
                                  overlayforwaitnone();
                                  $('#ddlPaymentTypes').prop('selectedIndex', 0);
                                  message = response;

                                  if ($("#ajaxProcessPaymentError").html() == undefined) {
                                      $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                  } else {
                                      $("#ajaxProcessPaymentError").html('We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.');
                                  }

                                  if ($('#ajaxProcessPaymentError').html() != undefined) {
                                      $('#ajaxProcessPaymentError').dialog({
                                          title: 'Payment Application',
                                          resizable: false,
                                          modal: true,
                                          create: function () {
                                              $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                          },
                                          buttons: {
                                              Ok: function () {
                                                  $(this).dialog('close');
                                              }
                                          },
                                          closeOnEscape: false,
                                          open: function (event, ui) {
                                              $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                          }
                                      });
                                  }

                                  return false;
                              }
                          } else {
                              var isSuccess = response.Data.IsSuccess;
                              if (isSuccess) {
                                  var customerProfileId = response.Data.CustomerProfileId;
                                  var customerPaymentId = response.Data.CustomerPaymentProfileId;
                                  var customerGuid = response.Data.CustomerGUID;
                                  var paymentSettingId = $("#CCPaymentOptionId").val();
                                  var paymentToken = $("input[name='CCdetails']:checked").val();

                                  var paymentModel = {
                                      PaymentSettingId: paymentSettingId,
                                      CustomerProfileId: customerProfileId,
                                      CustomerPaymentId: customerPaymentId,
                                      CustomerGuid: customerGuid,
                                      PaymentToken: paymentToken
                                  };

                                  $.ajax({
                                      type: "POST",
                                      url: "/checkout/submitpayment",
                                      data: paymentModel,
                                      success: function (response) {
                                          var newLocation = response.Data;
                                          if (newLocation != undefined && newLocation.toLowerCase().indexOf('missing card data') >= 0) {
                                              $('#ajaxProcessPayment').html('');
                                              $('#ccpopUp [data-payment="number"]').val('');
                                              $('#ccpopUp [data-payment="cvc"]').val('');
                                              $('#ccpopUp [data-payment="exp-month"]').val('');
                                              $('#ccpopUp [data-payment="exp-year"]').val('');
                                              $('#ajaxProcessPayment').dialog('close');
                                              overlayforwaitnone();
                                              $('#ddlPaymentTypes').prop('selectedIndex', 0);
                                              if ($('#ajaxProcessPaymentError').html() == undefined) {
                                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">Error occurred during processing an order. Order could not be placed as card data is missing.</p></div>');
                                              }
                                              else {
                                                  $('#ajaxProcessPaymentError').html('Error occurred during processing an order. Order could not be placed as card data is missing.');
                                              }
                                          } else if (newLocation != undefined && newLocation.indexOf('Message=') >= 0) {
                                              var message = newLocation.substr(newLocation.indexOf('=') + 1);
                                              $('#ajaxProcessPayment').html('');
                                              $('#ccpopUp [data-payment="number"]').val('');
                                              $('#ccpopUp [data-payment="cvc"]').val('');
                                              $('#ccpopUp [data-payment="exp-month"]').val('');
                                              $('#ccpopUp [data-payment="exp-year"]').val('');
                                              $('#ajaxProcessPayment').dialog('close');
                                              overlayforwaitnone();
                                              $('#ddlPaymentTypes').prop('selectedIndex', 0);
                                              if ($('#ajaxProcessPaymentError').html() == undefined) {
                                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                              } else {
                                                  $('#ajaxProcessPaymentError').html('We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.');
                                              }
                                          }
                                          else if (newLocation == "Customer shipping address is not a valid address. Please enter valid address to continue.") {
                                              $("#ajaxProcessPayment").dialog('close');
                                              $("#SuccessMessage").show();
                                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + newLocation + '</div>');
                                              $('#ddlPaymentTypes').prop('selectedIndex', 0);
                                              $(window).scrollTop(0);
                                          }
                                          else if (newLocation != undefined) {
                                              $('#ajaxProcessPaymentError').remove();
                                              window.location = newLocation;
                                          } else {
                                              $('#ccpopUp .ErrorMessage').html('');
                                              $('#ccpopUp [data-payment="number"]').val('');
                                              $('#ccpopUp [data-payment="cvc"]').val('');
                                              $('#ccpopUp [data-payment="exp-month"]').val('');
                                              $('#ccpopUp [data-payment="exp-year"]').val('');
                                              $('#ajaxProcessPayment').dialog('close');
                                              overlayforwaitnone();
                                              $('#ddlPaymentTypes').prop('selectedIndex', 0);
                                              if ($('#ajaxProcessPaymentError').html() == undefined) {
                                                  $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">Error occurred during processing an order. Order could not be placed.</p></div>');
                                              } else {
                                                  $('#ajaxProcessPaymentError').html('Error occurred during processing an order. Order could not be placed.');
                                              }
                                          }

                                          if ($('#ajaxProcessPaymentError').html() != undefined) {
                                              $('#ajaxProcessPaymentError').dialog({
                                                  title: 'Payment Application',
                                                  resizable: false,
                                                  modal: true,
                                                  create: function () {
                                                      $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                                  },
                                                  buttons: {
                                                      Ok: function () {
                                                          $(this).dialog('close');
                                                      }
                                                  },
                                                  closeOnEscape: false,
                                                  open: function (event, ui) {
                                                      $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                                  }
                                              });
                                          }

                                          return false;
                                      },
                                      error: function () {
                                          ajax.errorOut("API Endpoint not available: " + url);
                                      }
                                  });
                              }
                              else {
                                  var message = response.Data.ResponseText;
                                  if (message == undefined) {
                                      message = response.Data.GatewayResponseData;
                                      if (message == undefined) {
                                          message = response.Data;
                                      }
                                  }
                                  $("#ajaxProcessPayment").html('');
                                  $("#ccpopUp [data-payment='number']").val('');
                                  $("#ccpopUp [data-payment='cvc']").val('');
                                  $("#ccpopUp [data-payment='exp-month']").val('');
                                  $("#ccpopUp [data-payment='exp-year']").val('');
                                  $("#ajaxProcessPayment").dialog('close');
                                  overlayforwaitnone();
                                  $('#ddlPaymentTypes').prop('selectedIndex', 0);
                                  if (message.length > 0 && message != null) {
                                      if ($("#ajaxProcessPaymentError").html() == undefined) {
                                          $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                      } else {
                                          $("#ajaxProcessPaymentError").html('We were unable to process your credit card payment. <br /><br />Reason:<br />' + message + '<br /><br />If the problem persists, contact us to complete your order.');
                                      }
                                  }
                                  else {
                                      if ($("#ajaxProcessPaymentError").html() == undefined) {
                                          $('body').append('<div id="ajaxProcessPaymentError"><p id="ajaxProcessPaymentErrorMsg">We were unable to process your credit card payment. <br /><br /><br />If the problem persists, contact us to complete your order.</p></div>');
                                      } else {
                                          $("#ajaxProcessPaymentError").html('We were unable to process your credit card payment. <br /><br /><br />If the problem persists, contact us to complete your order.');
                                      }
                                  }
                                  if ($('#ajaxProcessPaymentError').html() != undefined) {
                                      $('#ajaxProcessPaymentError').dialog({
                                          title: 'Payment Application',
                                          resizable: false,
                                          modal: true,
                                          create: function () {
                                              $(this).closest('.ui-dialog').addClass('ui-md-popup ui-popup-top');
                                          },
                                          buttons: {
                                              Ok: function () {
                                                  $(this).dialog('close');
                                              }
                                          },
                                          closeOnEscape: false,
                                          open: function (event, ui) {
                                              $('#ajaxProcessPaymentError').parent().find(' .ui-dialog-titlebar-close').hide();
                                          }
                                      });
                                  }
                              }
                              return false;
                          }
                      });
                  }
                  else {
                      if (data.ErrorMessage == "Logout") {
                          window.location.href = "/cart/index";
                      }
                      $("#ErrorMessage").html(data.ErrorMessage);
                      $("#ajaxBusy").dialog('close');
                  }
              },

              error: function (jqXHR, textStatus, errorThrown) {

              }

          });
      },

      PayPalPaymentProcess: function () {
          $("#ddlPaymentTypes").val(0);
          isValid = true;
          $('#status-message').remove();
          $("#ErrorMessage").html('');
          $("#ajaxProcessPayment").html('');
          if ($("#ajaxProcessPayment").html() == undefined) {
              $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p></div>');
          }

          $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Your payment is processing. Please wait and do not close this window</p>');
          $("#ajaxProcessPayment").dialog({
              title: 'Payment Application',
              resizable: false,
              modal: true,
              create: function () {
                  $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top");
              },
              closeOnEscape: false,
              open: function (event, ui) {
                  $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
              }
          });

          var paymentSettingId = $('#PaymentsViewModel_PaymentPaypalOptionId').val();
          var ReturnUrl = String.format(Checkout.GloabalVariables.ZnodeDemoPaymentSuccessUrl, paymentSettingId);
          var CancelUrl = location.protocol + "//" + location.host + "/checkout/SingleCheckout?";
          Api.ProcessPayPalPayment(paymentSettingId, ReturnUrl, CancelUrl, function (response) {
              var message = response;
              if (message != undefined && message.indexOf('Message=') >= 0) {
                  var errorMessage = message.substr(message.indexOf('=') + 1);
                  $("#ajaxBusy").dialog('close');
                  $('#SuccessMessage').show();
                  $("#ajaxProcessPayment").dialog('close');
                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
              } else if (message.indexOf("http") != -1) {
                  $("#ajaxBusy").dialog('close');
                  window.location = response;
              }
              else {
                  $("#ajaxBusy").dialog('close');
                  $('#SuccessMessage').show();
                  $("#ajaxProcessPayment").dialog('close');
                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + message + '</div>');
              }
          });
      },

      singleCheckout: function () {

          $("#giftcard_number").keypress(function (event) {
              if (event.which == 13) {
                  event.preventDefault();
                  $(".singlecheckout-giftcard-apply").focus();
              }
          });
          $('#login_password').on("blur", function (e) {

              var password = $('#login_password').val();
              var regex = $('#login_password').attr('data-val-regex-pattern');
              if (password.trim().length > 0) {
                  $("#valPassword").text('').removeClass("field-validation-error");
                  $("#valPassword").hide();
                  if (Checkout.bind.IsMatchRegularExpressionString(password, regex) == false) {
                      $("#valPassword").text("Password must be at least 8 alphanumeric characters and contain at least one number").addClass("error-msg");
                      $("#valPassword").show();
                      return false;
                  }
              }
              return true;
          });

          if (window.location.href.toLowerCase().indexOf("singlecheckout") > -1) {
              Checkout.bind.CalculateShippingMethods();
          }

          $('[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').on("focusout", function (e) {
              if ($('[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').val() != "") {
                  overlayforwaitblock();
                  $.ajax({
                      url: "/Checkout/GetUpdatedCart?isCountryStateTax=true",
                      data: $("#checkoutform").serialize(),
                      type: 'POST',
                      success: function (data) {
                          overlayforwaitnone();
                          var cartData = $.parseHTML(data)
                          $(".cart-summary").html($(cartData).find('.cart-summary').html())

                      }
                  });
              }
          });


          $('[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').on("focusout", function (e) {
              if ($('[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').val() != "") {
                  overlayforwaitblock();
                  $.ajax({
                      url: "/Checkout/GetUpdatedCart?isCountryStateTax=true",
                      data: $("#checkoutform").serialize(),
                      type: 'POST',
                      success: function (data) {
                          overlayforwaitnone();
                          $('#status-message').remove();
                          var cartData = $.parseHTML(data)
                          $(".cart-summary").html($(cartData).find('.cart-summary').html())
                          var errorMessage = $(cartData).find('#status-message').html();
                          if (errorMessage != undefined && errorMessage != "") {
                              $("#SuccessMessage").show();

                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                          }
                          else {
                              $('#status-message').remove();
                          }
                      }
                  });
              }
          });

          $('#ccpopUp').hide();

          $('#ddlPaymentTypes').change(function () {

              var paymentType = $("#ddlPaymentTypes option:selected").text();
              var paymentTypeId = $('#ddlPaymentTypes').val()
              $('#radioCCList').hide();
              $("#singleCheckoutSubmitPayment").show();
              $('#purchase-order-number').hide();
              $("#div-paypal-express-checkout").hide();
              $('#paymentProviders').html('');
              if (paymentType.toLowerCase() != 'select payment') {
                  $("#ddlPaymentTypes").css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
              if (paymentType.toLowerCase() == 'credit card') {
                  $("#hdnGatwayName").val('');
                  $("#hdnCustomerGUID").val('');
                  if ($("#CCPaymentOptionId").val().length > 0) {

                      $("#ajaxProcessPayment").html('');
                      if ($("#ajaxProcessPayment").html() == undefined) {
                          $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Please wait while we load the payment screen. Do not close this window.</p></div>');
                      }

                      $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Please wait while we load the payment screen. Do not close this window.</p>');
                      $("#ajaxProcessPayment").dialog({
                          title: 'Payment Application',
                          resizable: false,
                          modal: true,
                          create: function () {
                              $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top");
                          },
                          closeOnEscape: false,
                          open: function (event, ui) {
                              $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
                          }
                      });

                      Api.GetPaymentGatwayName($("#CCPaymentOptionId").val(), function (response) {

                          $('#Save-credit-card').show();
                          $('#radioCCList').hide();
                          $('#paymentProviders').html('');
                          if (response.success) {
                              $("#hdnGatwayName").val(response.name);
                              $("#hdnCustomerGUID").val(response.customerGuid);
                              if (response.name == "TwoCheckout" || response.name == "PayFlow") {
                                  $('#Save-credit-card').hide();
                              }

                              $("#paymentProfileId").val(response.profileId);

                              var gatewayName = $("#hdnGatwayName").val();
                              if (gatewayName != undefined && gatewayName.length > 0) {
                                  var paymentAppGatewayName = gatewayName.toLowerCase();

                                  if (gatewayName.toLowerCase() == 'authorize.net') {
                                      paymentAppGatewayName = 'authorizenet';
                                  }

                                  if (gatewayName.toLowerCase() == 'paymentech orbital') {
                                      paymentAppGatewayName = 'paymenttech';
                                  }
                                  if (gatewayName.toLowerCase() == 'payflow') {
                                      Checkout.bind.SetEncryptedTotalAmount(response.total);
                                  }

                                  var paymentUrl = Checkout.GloabalVariables.PaymentApplicationJSCall;
                                  var twoCOUrl = String.format(Checkout.GloabalVariables.ZnodeDemoPaymentTwoCoUrl, $("#CCPaymentOptionId").val());

                                  var gateway = paymentAppGatewayName;
                                  var profileId = $("#paymentProfileId").val();
                                  var twoCoUrl = twoCOUrl;
                                  var customerGUID = $("#hdnCustomerGUID").val();

                                  var paymentCreditCardModel = {
                                      gateway: gateway,
                                      profileId: profileId,
                                      twoCoUrl: twoCoUrl,
                                      customerGUID: customerGUID
                                  };

                                  $.ajax({
                                      type: "POST",
                                      url: Checkout.GloabalVariables.ScriptPaymentUrl,
                                      data: paymentCreditCardModel,
                                      success: function (response) {
                                          $("#ajaxProcessPayment").dialog('close');
                                          Checkout.bind.SetCreditCardValidations();
                                          if (enabledPaymentProviders != '') {
                                              var payProvidersHtml = '';
                                              var toSplittedPayProviders = enabledPaymentProviders.split(",");
                                              for (var iPayProviders = 0; iPayProviders < toSplittedPayProviders.length; iPayProviders++) {
                                                  payProvidersHtml += "<div  class='col-xs-12 col-sm-3 nopadding styled-input'><input id=radioPaymentProviders" + iPayProviders + " type=radio name=PaymentProviders value=" + toSplittedPayProviders[iPayProviders] + " /><label for=radioPaymentProviders" + iPayProviders + "><img src=../Images/" + toSplittedPayProviders[iPayProviders] + ".png class='img-responsive' /></label></div>";
                                              }

                                              $('#paymentProviders').append("<ul>" + payProvidersHtml + "</ul>");
                                              $('input[name="PaymentProviders"]')[0].checked = true;
                                          }
                                          if (savedUserCCDetails != '') {
                                              $('#radioCCList').show();
                                              $('#radioCCList').html('');
                                              var iCCOrder = 0;
                                              var creditCardHtml = "";
                                              $.each(JSON.parse(savedUserCCDetails), function () {
                                                  creditCardHtml += "<div  class='col-xs-12 nopadding styled-input'><input id=radioSavedCreditCard" + iCCOrder + " type=radio name=CCdetails value=" + this['PaymentGUID'] + " /><label for=radioSavedCreditCard" + iCCOrder + ">" + this['CreditCardLastFourDigit'] + "</label></div>";
                                                  iCCOrder++;
                                              });
                                              $('#radioCCList').append("<ul>" + creditCardHtml + "</ul>");
                                              $('input[name="CCdetails"]')[0].checked = true;
                                              $('#divAddNewCCDetails').show();
                                          }
                                          else {
                                              jQuery('#creditCardTab').hide()
                                              jQuery('#savedCreditCard-panel').removeClass('active')
                                              jQuery('#addNewCreditCard-panel').addClass('in active')
                                          }
                                          $("#ccpopUp").show();
                                          $("#ccpopUp [data-payment='number']").focus();
                                      },
                                      error: function () {
                                          $("#ajaxProcessPayment").dialog('close');
                                          $("#ccpopUp .ErrorMessage").html('');
                                          $("#ccpopUp .ErrorMessage").html('Unable to contact payment application.');
                                      }
                                  });

                              } else {
                                  $("#ajaxProcessPayment").html('');
                                  $("#ajaxProcessPayment").html('Could not procced with payment as no payment gateway available with this selection.');
                              }
                              return false;
                          } else {
                              $("#ccpopUp .ErrorMessage").html('');
                              $("#ajaxProcessPayment").html('Could not procced with payment as no payment gateway available with this selection.');
                          }
                      });
                  }
              } else if (paymentTypeId == '2') {
                  $('#ccpopUp').hide();
                  $('#purchase-order-number').show();
              }
              else if (paymentTypeId == '3') {
                  $('#ccpopUp').hide();
                  $("#singleCheckoutSubmitPayment").hide();
                  $('#div-paypal-express-checkout').show();
              }
              else {
                  $('#ccpopUp').hide();
                  $('#radioCCList').hide();
                  $('#chkAddCCDetails').attr('checked', false)
              }
          });

          $("#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode").change(function () {
              if ($("#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode").val().trim().length > 0) {
                  $.ajax({
                      url: "/Checkout/GetUpdatedCart?isCountryStateTax=true",
                      data: $("#checkoutform").serialize(),
                      type: 'POST',
                      success: function (data) {
                          $("#SingleCheckoutCartItem").html(data);
                      }
                  });
              }
          });

          $("#singlepage-checkout-shipping-content [name=ShippingOptions]").unbind("change");

          $("#singlepage-checkout-shipping-content [name=ShippingOptions]").on('change', Checkout.bind.GetShippingMethods);

          $("#btnApplyCoupon").on('click', function () {
              var couponCode = $("input[name='Coupon']").val();
              var url = "/Checkout/ApplyDiscount";
              Checkout.bind.ApplyPromotion(couponCode, url);
          });

          $(".singlecheckout-giftcard-apply").on('click', function () {
              var value = $("input[name='giftcard']").val();
              if (value == "" || value == null) {
                  isValid = false;
                  $("input[name='giftcard']").css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $("input[name='giftcard']").css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });

                  $.ajax({
                      url: "/Checkout/ApplyGiftCard",
                      data: {
                          "number": value
                      },
                      type: 'GET',
                      success: function (response) {
                          if (response.success) {
                              $('#errorgiftcard').hide();
                              $("#giftcard-initial").hide();
                              $("#GiftCardAmount").val(response.data.giftcardamount);
                              // If the gift card covers order total then offer button, else link to close results
                              if (response.data.paid) {
                                  var template = $("#tmpl-giftcard-finish").html();
                              } else {
                                  var template = $("#tmpl-giftcard-continue").html();
                              }


                              $("#dynamic-order-total").find("h2").html(response.data.total);
                              var html = Mustache.render(template, response.data);

                              $("#giftcard-action").html(html);
                              if (response.data.total == "$0.00") {
                                  $("#TotalAmount").val(response.data.total)
                              }

                          } else {
                              isValid = false;
                              $('#errorgiftcard').show();
                              $("#errorgiftcard").html('<div class="field-validation-error">' + response.message + '</div>').addClass("error-msg");
                          }
                      }
                  });
              }

          });

          $('#singleCheckoutSubmitPayment').on("click", function (e) {
              $('#status-message').remove()
              var isValid = true;
              e.preventDefault();
              if ($("#ddlPaymentTypes option:selected").text().toLowerCase() == 'select payment') {
                  isValid = false;
                  $("#ddlPaymentTypes").css({
                      "border": "1px solid red",
                      "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
                  });
              }
              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.EmailAddress"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').each(function () {
                  if ($.trim($(this).val()) == '') {
                      isValid = false;
                      $(this).css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $(this).css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              });

              var country = $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"] option:selected').val();
              if (country == "0" || country == "") {
                  isValid = false;
                  $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                      "border": "1px solid red",
                      "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
                  });
              }
              else {
                  $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }

              if ($('#CreateLogin').is(":checked")) {
                  $('input[name="ShippingBillingAddressViewModel.LoginViewModel.Username"],input[name="ShippingBillingAddressViewModel.LoginViewModel.Password"]').each(function () {
                      if ($.trim($(this).val()) == '') {
                          isValid = false;
                          $(this).css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }
                      else {
                          $(this).css({
                              "border": "1px solid #C3C3C3",
                              "background": ""
                          });
                      }
                  });
              }

              if ($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val() == "" || !Checkout.bind.ValidateEmail($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val())) {
                  isValid = false;
                  $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }

              if (!($('#billingSameAsShippingAddress').is(":checked"))) {
                  $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').each(function () {
                      if ($.trim($(this).val()) == '') {
                          isValid = false;
                          $(this).css({
                              "border": "1px solid red",
                              "background": "#FFCECE"
                          });
                      }
                      else {
                          $(this).css({
                              "border": "1px solid #C3C3C3",
                              "background": ""
                          });
                      }
                  });

                  var country = $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"] option:selected').val();
                  if (country == "0" || country == "") {
                      isValid = false;
                      $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                          "border": "1px solid red",
                          "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
                      });
                  }
                  else {
                      $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              }

              if ($('#ddlPaymentTypes').val() == "2") {
                  var purchaseOrderNumber = $('#txtPurchaseOrderNumber').val().trim();
                  if (purchaseOrderNumber.length < 1) {
                      isValid = false;
                      $('#errorpurchaseorder').show();
                      $('#txtPurchaseOrderNumber').css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $('#txtPurchaseOrderNumber').css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              }

              if ($('#ddlPaymentTypes').val() != "1" || ($("#TotalAmount").val() == "$0.00")) {
                  if (isValid) {
                      $('#status-message').remove();
                      if ($("#ajaxProcessPayment").html() == undefined) {
                          $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Please wait while processing and do not close this window</p></div>');
                      }

                      $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Please wait while processing and do not close this window</p>');
                      $("#ajaxProcessPayment").dialog({
                          title: 'Order Processing',
                          resizable: false,
                          modal: true,
                          create: function () {
                              $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top");
                          },
                          closeOnEscape: false,
                          open: function (event, ui) {
                              $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
                          }
                      });
                      if ($('#CreateLogin').is(":checked")) {
                          $.ajax({
                              url: "CreateSingleCheckoutAccount",
                              type: 'post',
                              data: $("#checkoutform").serialize(),
                              success: function (data) {
                                  if (data.HasError) {
                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                      isValid = false;
                                      $("#ajaxProcessPayment").dialog('close');
                                      $(window).scrollTop(0);
                                      return isValid;
                                  }
                                  else {
                                      $('#status-message').remove();
                                      $.ajax({
                                          url: "SubmitSingleCheckout",
                                          type: 'post',
                                          data: $("#checkoutform").serialize(),
                                          success: function (data) {
                                              if (!data.HasError) {
                                                  var form = $('<form action="CheckoutReceipt" method="post">' +
                                                      '<input type="hidden" name="EmailId" value="' + data.EmailId + '" />' +
                                                      '<input type="hidden" name="OrderId" value="' + data.OrderId + '" />' +
                                                      '</form>');
                                                  $('body').append(form);
                                                  $(form).submit();
                                              }
                                              else {
                                                  var isError = data.ErrorMessage;
                                                  if (data.ErrorMessage == "Logout") {
                                                      window.location.href = "/cart/index";
                                                  }
                                                  if (isError != "" && isError != null) {
                                                      window.location = "/Checkout/SingleCheckout?message=" + data.ErrorMessage;
                                                  }

                                                  $("#ajaxProcessPayment").dialog('close');
                                              }
                                          },
                                          error: function (xhr, ajaxOptions, thrownError) {
                                              $("#ajaxProcessPayment").dialog('close');
                                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                          },
                                      });
                                  }
                              }
                          })
                      }
                      else {
                          if (!$('#CreateLogin').is(":checked") && !$("#divnewLogin").is(':visible')) {
                              $('#status-message').remove();
                              $.ajax({
                                  url: "IsValidGuestUser",
                                  type: 'post',
                                  data: $("#checkoutform").serialize(),
                                  success: function (data) {
                                      if (data.HasError) {
                                          isValid = false;
                                          $("#ajaxProcessPayment").dialog('close');
                                          $("#SuccessMessage").show();
                                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                          $(window).scrollTop(0);
                                      }
                                      else {
                                          isValid = true;
                                          $.ajax({
                                              url: "SubmitSingleCheckout",
                                              type: 'post',
                                              data: $("#checkoutform").serialize(),
                                              success: function (data) {
                                                  if (!data.HasError) {
                                                      var form = $('<form action="CheckoutReceipt" method="post">' +
                                                          '<input type="hidden" name="EmailId" value="' + data.EmailId + '" />' +
                                                          '<input type="hidden" name="OrderId" value="' + data.OrderId + '" />' +
                                                          '</form>');
                                                      $('body').append(form);
                                                      $(form).submit();
                                                  }
                                                  else {

                                                      if (data.ErrorMessage == "Logout") {
                                                          window.location.href = "/cart/index";
                                                      }
                                                      $("#ajaxProcessPayment").dialog('close');
                                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                                      $(window).scrollTop(0);
                                                  }
                                              },
                                              error: function (xhr, ajaxOptions, thrownError) {
                                                  $("#ajaxProcessPayment").dialog('close');
                                                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                              },
                                          });
                                      }
                                  },
                              });
                          }
                          else {
                              $('#status-message').remove();
                              $.ajax({
                                  url: "SubmitSingleCheckout",
                                  type: 'post',
                                  data: $("#checkoutform").serialize(),
                                  success: function (data) {
                                      if (!data.HasError) {
                                          var form = $('<form action="CheckoutReceipt" method="post">' +
                                              '<input type="hidden" name="EmailId" value="' + data.EmailId + '" />' +
                                              '<input type="hidden" name="OrderId" value="' + data.OrderId + '" />' +
                                              '</form>');
                                          $('body').append(form);
                                          $(form).submit();
                                      }
                                      else {

                                          if (data.ErrorMessage == "Logout") {
                                              window.location.href = "/cart/index";
                                          }
                                          $("#ajaxProcessPayment").dialog('close');
                                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                      }
                                  },
                                  error: function (xhr, ajaxOptions, thrownError) {
                                      $("#ajaxProcessPayment").dialog('close');
                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                  },
                              });
                          }
                      }
                  }
              }
              else {
                  $('#status-message').remove()
                  if (isValid == false) {
                      e.preventDefault();
                  }
                  else {

                      if ($("#radioCCList").is(':visible')) {
                          return Checkout.bind.PaymentProcess();
                      }
                      else {
                          isValid = Checkout.bind.SetCreditCardValidation();
                      }
                  }
                  if (isValid) {
                      overlayforwaitblock();
                      $('#status-message').remove();
                      if ($('#CreateLogin').is(":checked")) {
                          $.ajax({
                              url: "CreateCreditCardUserAccount",
                              type: 'post',
                              data: $("#checkoutform").serialize(),
                              success: function (data) {
                                  overlayforwaitnone();
                                  if (data.HasError) {
                                      if (data.ErrorMessage != undefined && data.ErrorMessage != "" && data.ErrorMessage != null) {
                                          window.location = "/Checkout/SingleCheckout?message=" + data.ErrorMessage;
                                      }
                                      isValid = false;
                                      return isValid;
                                  }
                                  else {
                                      $.ajax({
                                          url: "/Checkout/GetUpdatedCart",
                                          data: $("#checkoutform").serialize(),
                                          type: 'POST',
                                          success: function (data) {
                                              overlayforwaitnone();
                                              var cartData = $.parseHTML(data)
                                              $(".cart-summary").html($(cartData).find('.cart-summary').html())
                                              var errorMessage = $(cartData).find('#status-message').html();
                                              if (errorMessage != undefined && errorMessage != "") {
                                                  $("#ajaxProcessPayment").dialog('close');
                                                  isValid = false;
                                                  e.preventDefault();
                                                  $("#SuccessMessage").show();
                                                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                                                  if (errorMessage != undefined && errorMessage != "" && errorMessage != null) {
                                                      window.location = "/Checkout/SingleCheckout?message=" + errorMessage;
                                                  }
                                                  $(window).scrollTop(0);
                                              }
                                              else {
                                                  Checkout.bind.PaymentProcess();
                                              }
                                          }
                                      });
                                  }
                              }
                          })
                      }
                      else {
                          if (!$('#CreateLogin').is(":checked") && !$("#divnewLogin").is(':visible')) {
                              $.ajax({
                                  url: "IsValidGuestUser",
                                  type: 'post',
                                  data: $("#checkoutform").serialize(),
                                  success: function (data) {
                                      overlayforwaitnone();
                                      if (data.HasError) {
                                          isValid = false;
                                          $("#ajaxProcessPayment").dialog('close');
                                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                          $(window).scrollTop(0);
                                      }
                                      else {
                                          isValid = true;
                                          if ($('#ddlPaymentTypes').val() == "1") {
                                              $.ajax({
                                                  url: "/Checkout/GetUpdatedCart",
                                                  data: $("#checkoutform").serialize(),
                                                  type: 'POST',
                                                  success: function (data) {
                                                      overlayforwaitblock();
                                                      var cartData = $.parseHTML(data)
                                                      $(".cart-summary").html($(cartData).find('.cart-summary').html())
                                                      var errorMessage = $(cartData).find('#status-message').html();
                                                      if (errorMessage != undefined && errorMessage != "") {
                                                          $("#ajaxProcessPayment").dialog('close');
                                                          isValid = false;
                                                          e.preventDefault();
                                                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                                                          $(window).scrollTop(0);
                                                      }
                                                      else {
                                                          overlayforwaitnone();
                                                          Checkout.bind.PaymentProcess();
                                                      }
                                                  }
                                              });
                                          }
                                      }
                                  },
                              });
                          }
                      }
                  }
              }
          });

          $('#singleCheckoutSubmitQuote').on("click", function (e) {
              $("#hdnIsSaveDraft").val(false);
              if ($("#promocode").val().trim() != "" || $("#giftcard_number").val().trim() != "") {
                  Checkout.ShowQuoteConfirm('Confirm?', 'Coupon or Gift Card will get applied at the time of Order Purchase.', e, "");
                  return false;
              }
              else {
                  Checkout.bind.SubmitQuote(e);
              }

          });

          $("#btnSaveDraft").on("click", function (e) {
              $("#hdnIsSaveDraft").val(true);

              if ($("#promocode").val().trim() != "" || $("#giftcard_number").val().trim() != "") {
                  Checkout.ShowQuoteConfirm('Confirm?', 'Coupon or Gift Card will get applied at the time of Order Purchase.', e, "");
                  return false;
              }
              else {
                  Checkout.bind.SubmitQuote(e);
              }

          });

          $("#btnSubmitQuoteNormalPageCheckout").on("click", function (e) {
              if ($("#ppromocode").text().trim() != "") {
                  e.preventDefault();
                  var urlAddress = "/checkout/SubmitQuoteNormalPageCheckout?saveDraft=false&quoteId=" + $("#QuoteId").val() + "&draftStateId=" + $("#QuoteStateId").val() + "";
                  Checkout.ShowQuoteConfirm('Confirm?', 'Coupon or Gift Card will get applied at the time of Order Purchase.', e, urlAddress);
                  return false;
              }
          });

          $("#btnDraft").on("click", function (e) {
              if ($("#ppromocode").text().trim() != "") {
                  e.preventDefault();
                  var urlAddress = "/checkout/SubmitQuoteNormalPageCheckout?saveDraft=true&quoteId=" + $("#QuoteId").val() + "&draftStateId=" + $("#QuoteStateId").val() + "";
                  Checkout.ShowQuoteConfirm('Confirm?', 'Coupon or Gift Card will get applied at the time of Order Purchase.', e, urlAddress);
                  return false;
              }
          });

      },

      ApplyPromotion: function (couponCode, url) {
          Api.applyDiscount(url, couponCode, function (response) {
              $('#layout-cart').html("");
              $('#layout-cart').html(response.html);

              var coupons = response.data;
              htmlString = "<div class='col-xs-12 nopadding'>";
              for (var couponIndex = 0; couponIndex < coupons.length; couponIndex++) {
                  var style = coupons[couponIndex].CouponApplied ? "success-msg padding-top" : "error-msg";
                  var message = coupons[couponIndex].CouponMessage;
                  var couponCode = coupons[couponIndex].Coupon;
                  htmlString = htmlString + "<p class='" + style + "'>" + "<i class='zf-close' style='cursor:pointer;color:#cc0000;padding-right:3px;' onclick='Checkout.bind.RemoveCoupon(&#39;" + couponCode + "&#39;)'></i>" + "<b>" + couponCode + "</b>" + " - " + message + "</p>";
              }
              htmlString = htmlString + "</div>";

              $("#couponMessageContainer").html("");
              $("#couponMessageContainer").html(htmlString);
          });
      },

      RemoveCoupon: function (coupon) {
          Api.removeCoupon(coupon, function (response) {
              $('#layout-cart').html("");
              $('#layout-cart').html(response.html);
              var coupons = response.data;
              htmlString = "<div class='col-xs-12 nopadding'>";
              for (var couponIndex = 0; couponIndex < coupons.length; couponIndex++) {
                  var style = coupons[couponIndex].CouponApplied ? "success-msg padding-top" : "error-msg";
                  var message = coupons[couponIndex].CouponMessage;
                  var couponCode = coupons[couponIndex].Coupon;
                  htmlString = htmlString + "<p class='" + style + "'>" + "<i class='zf-close' style='cursor:pointer;color:#cc0000;padding-right:3px;' onclick='Checkout.bind.RemoveCoupon(&#39;" + couponCode + "&#39;)'></i>" + "<b>" + couponCode + "</b>" + " - " + message + "</p>";
              }
              htmlString = htmlString + "</div>";

              $("#couponMessageContainer").html("");
              $("#couponMessageContainer").html(htmlString);
              $("#promocode").val("");
          });
      },

      ShowAppliedPromotion: function () {
          var couponCode = $("input[name='Coupon']").val();
          var url = "/Checkout/ApplyDiscount";
          if (couponCode != null && couponCode != "") {
              Checkout.bind.ApplyPromotion(couponCode, url);
          }
      },

      RemoveDuplicateMessage: function () {
          var errorMessageDiv = $("#ErrorMessage").html();
          var statusMessageDiv = $("#status-message").html();
          if (typeof statusMessageDiv != 'undefined' && typeof errorMessageDiv != 'undefined') {
              if ((errorMessageDiv != null && errorMessageDiv != "") && (statusMessageDiv != null && statusMessageDiv != "")) {
                  $("#ErrorMessage").hide();
              }
          }
      },
      ResetReviewIndex: function () {
          var orderTotal = $("#dynamic-order-total").text() != null && $("#dynamic-order-total").text() != "" && typeof $("#dynamic-order-total").text() != "undefined" ? $("#dynamic-order-total").text().trim() : $("#dynamic-order-total").text();
          if ($("#dynamic-order-total").text() != null && $("#dynamic-order-total").text() != "" && typeof $("#dynamic-order-total").text() != "undefined" && $("#UserAccessId").val() == 3) {
              orderTotal = parseFloat(orderTotal.substring(1));
              if (orderTotal > parseFloat($("#MaxBudget").val()) && $("#CartViewModel_QuoteStateId").val() != "60") {
                  $("#paymentSection").hide();
                  $("#spnReviewYourOrder").text(3);
              }
              else {
                  $("#paymentSection").show();
                  $("#spnReviewYourOrder").text(4);
              }
          }
          if (!$("#paymentsection").is(':visible')) {
              $("#spnReviewYourOrder").text(3);
          }
          else {
              $("#spnReviewYourOrder").text(4);
          }
      },

      SelectAddress: function () {
          $(".shipTo").change(function () {
              var firstDropVal = $(this, '.shipTo').val();
              var shipToCallingDropDown = $($(this).parent().parent().parent().parent()).attr("Id");
              $.ajax({
                  url: "/Checkout/GetAddressById",
                  data: {
                      "addressId": firstDropVal
                  },
                  type: 'GET',
                  success: function (response) {
                      if (response.AddressId > 0) {
                          var isBillingSameAsShipping = $("input#billingSameAsShippingAddress").is(":checked");
                          if (shipToCallingDropDown == "divShipping" && isBillingSameAsShipping) {
                              $('#CheckoutAddressId').val(response.AddressId);
                              $('#ShippingBillingAddressViewModel_ShippingAddressId').val(response.AddressId);
                              $('#ShippingBillingAddressViewModel_BillingAddressId').val(response.AddressId);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.Name"]').val(response.Name);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"]').val(response.FirstName);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"]').val(response.LastName);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.CompanyName"]').val(response.CompanyName);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"]').val(response.StreetAddress1)
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress2"]').val(response.StreetAddress2)
                              $('input[name="ShippingBillingAddressViewModel.EmailAddress"]').val(response.Email)
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').val(response.PostalCode);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').val(response.City);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').val(response.PhoneNumber);

                              $('#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode').val(response.CountryCode).attr("selected", "selected");
                              Checkout.bind.bindStatesForSelectedCountry('ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode', response);
                              $('#ShippingBillingAddressViewModel_ShippingAddressModel_StateCode').val(response.StateCode).attr("selected", "selected");

                              $($('.shipTo')[1]).val(response.AddressId);
                              $('#ShippingBillingAddressViewModel_BillingAddressId').val(response.AddressId);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.Name"]').val(response.Name);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"]').val(response.FirstName);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"]').val(response.LastName);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.CompanyName"]').val(response.CompanyName);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"]').val(response.StreetAddress1)
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress2"]').val(response.StreetAddress2)
                              $('input[name="ShippingBillingAddressViewModel.EmailAddress"]').val(response.Email)
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"]').val(response.PostalCode);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').val(response.City);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PhoneNumber"]').val(response.PhoneNumber);

                              $('#ShippingBillingAddressViewModel_BillingAddressModel_CountryCode').val(response.CountryCode).attr("selected", "selected");
                              Checkout.bind.bindStatesForSelectedCountry('ShippingBillingAddressViewModel_BillingAddressModel_CountryCode', response);
                              $('#ShippingBillingAddressViewModel_BillingAddressModel_StateCode').val(response.StateCode).attr("selected", "selected");

                              $('.alert-danger').remove();
                              Checkout.bind.GetShippingMethods();
                          } else if (shipToCallingDropDown == "divShipping") {
                              $('#CheckoutAddressId').val(response.AddressId);
                              $('#ShippingBillingAddressViewModel_ShippingAddressId').val(response.AddressId);
                              $('#ShippingBillingAddressViewModel_BillingAddressId').val(response.AddressId);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.Name"]').val(response.Name);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"]').val(response.FirstName);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"]').val(response.LastName);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.CompanyName"]').val(response.CompanyName);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"]').val(response.StreetAddress1)
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress2"]').val(response.StreetAddress2)

                              $('#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode').val(response.CountryCode).attr("selected", "selected");
                              Checkout.bind.bindStatesForSelectedCountry('ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode', response);
                              $('#ShippingBillingAddressViewModel_ShippingAddressModel_StateCode').val(response.StateCode).attr("selected", "selected");

                              $('input[name="ShippingBillingAddressViewModel.EmailAddress"]').val(response.Email)
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"]').val(response.PostalCode);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"]').val(response.City);
                              $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').val(response.PhoneNumber);
                              $('.alert-danger').remove();
                              Checkout.bind.GetShippingMethods();
                          } else if (shipToCallingDropDown == 'divBilling') {
                              $('#CheckoutAddressId').val(response.AddressId);
                              $('#ShippingBillingAddressViewModel_BillingAddressId').val(response.AddressId);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.Name"]').val(response.Name);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"]').val(response.FirstName);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"]').val(response.LastName);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.CompanyName"]').val(response.CompanyName);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"]').val(response.StreetAddress1)
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress2"]').val(response.StreetAddress2)

                              $('#ShippingBillingAddressViewModel_BillingAddressModel_CountryCode').val(response.CountryCode).attr("selected", "selected");
                              Checkout.bind.bindStatesForSelectedCountry('ShippingBillingAddressViewModel_BillingAddressModel_CountryCode', response);
                              $('#ShippingBillingAddressViewModel_BillingAddressModel_StateCode').val(response.StateCode).attr("selected", "selected");

                              $('input[name="ShippingBillingAddressViewModel.EmailAddress"]').val(response.Email)
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"]').val(response.PostalCode);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').val(response.City);
                              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PhoneNumber"]').val(response.PhoneNumber);
                          }
                      } else if (firstDropVal == 'addNewAddress' && shipToCallingDropDown == "divShipping") {
                          $("select#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode").prop('selectedIndex', 0);
                          $("select#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode").change();
                          $('#ShippingBillingAddressViewModel_ShippingAddressModel_CountryCode').change();
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.AddressId"]').val(0);
                          $('#ShippingBillingAddressViewModel_ShippingAddressId').val(0);
                          $('#ShippingBillingAddressViewModel_ShippingAddressId').val(0);
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.Name"]').val('');
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"]').val('');
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"]').val('');
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.CompanyName"]').val('');
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"]').val('');
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress2"]').val('');
                          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').val('');
                      } else if (firstDropVal == 'addNewAddress' && shipToCallingDropDown == "divBilling") {
                          $("select#ShippingBillingAddressViewModel_BillingAddressModel_CountryCode").prop('selectedIndex', 0);
                          $("select#ShippingBillingAddressViewModel_BillingAddressModel_CountryCode").change();
                          $('#ShippingBillingAddressViewModel_BillingAddressModel_CountryCode').change();
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.AddressId"]').val(response.AddressId);
                          $('#ShippingBillingAddressViewModel_ShippingAddressId').val(response.AddressId);
                          $('#ShippingBillingAddressViewModel_BillingAddressId').val(response.AddressId);
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.Name"]').val(response.Name);
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"]').val(response.FirstName);
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"]').val(response.LastName);
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.CompanyName"]').val(response.CompanyName);
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"]').val(response.StreetAddress1)
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress2"]').val(response.StreetAddress2)
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PhoneNumber"]').val(response.PhoneNumber);
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"]').val(response.PostalCode);
                          $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').val(response.City);
                      }
                  }
              });
          });
      },
      SubmitQuote: function (e) {
          var quotemessage = quotesentforapproval;
          if ($("#hdnIsSaveDraft").val()) {
              quotemessage = draftmessage;
          }
          $('#status-message').remove()
          var isValid = true;
          e.preventDefault();

          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.EmailAddress"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').each(function () {
              if ($.trim($(this).val()) == '') {
                  isValid = false;
                  $(this).css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $(this).css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
          });

          var country = $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"] option:selected').val();
          if (country == "0" || country == "") {
              isValid = false;
              $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
              });
          }
          else {
              $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                  "border": "1px solid #C3C3C3",
                  "background": ""
              });
          }

          if ($('#CreateLogin').is(":checked")) {
              $('input[name="ShippingBillingAddressViewModel.LoginViewModel.Username"],input[name="ShippingBillingAddressViewModel.LoginViewModel.Password"]').each(function () {
                  if ($.trim($(this).val()) == '') {
                      isValid = false;
                      $(this).css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $(this).css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              });
          }

          if ($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val() == "" || !Checkout.bind.ValidateEmail($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val())) {
              isValid = false;
              $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }
          else {
              $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                  "border": "1px solid #C3C3C3",
                  "background": ""
              });
          }

          if (!($('#billingSameAsShippingAddress').is(":checked"))) {
              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').each(function () {
                  if ($.trim($(this).val()) == '') {
                      isValid = false;
                      $(this).css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $(this).css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              });

              var country = $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"] option:selected').val();
              if (country == "0" || country == "") {
                  isValid = false;
                  $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                      "border": "1px solid red",
                      "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
                  });
              }
              else {
                  $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
          }


          if (isValid) {
              $('#status-message').remove();
              if ($("#ajaxProcessPayment").html() == undefined) {
                  $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Please wait while processing and do not close this window</p></div>');
              }

              $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Please wait while processing and do not close this window</p>');
              $("#ajaxProcessPayment").dialog({
                  title: 'Quote Processing',
                  resizable: false,
                  modal: true,
                  create: function () {
                      $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top");
                  },
                  closeOnEscape: false,
                  open: function (event, ui) {
                      $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
                  }
              });
              if ($('#CreateLogin').is(":checked")) {
                  $.ajax({
                      url: "CreateSingleCheckoutAccount",
                      type: 'post',
                      data: $("#checkoutform").serialize(),
                      success: function (data) {
                          if (data.HasError) {
                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                              isValid = false;
                              $("#ajaxProcessPayment").dialog('close');
                              $(window).scrollTop(0);
                              return isValid;
                          }
                          else {
                              $('#status-message').remove();
                              $.ajax({
                                  url: "SubmitQuoteSinglePageCheckout",
                                  type: 'post',
                                  data: $("#checkoutform").serialize(),
                                  success: function (data) {
                                      if (!data.HasError) {
                                          if (data.QuoteStateId == 90) {
                                              window.location.href = "/quote/history";
                                          }
                                          else {
                                              Checkout.RedirectToQuoteCheckoutReceipt(data.EmailId, data.OrderId);
                                          }
                                      }
                                      else {
                                          var isError = data.ErrorMessage;
                                          if (data.ErrorMessage == "Logout") {
                                              window.location.href = "/cart/index";
                                          }
                                          if (isError != "" && isError != null) {
                                              window.location = "/Checkout/SingleCheckout?message=" + data.ErrorMessage;
                                          }

                                          $("#ajaxProcessPayment").dialog('close');
                                      }
                                  },
                                  error: function (xhr, ajaxOptions, thrownError) {
                                      $("#ajaxProcessPayment").dialog('close');
                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                  },
                              });
                          }
                      }
                  })
              }
              else {
                  if (!$('#CreateLogin').is(":checked") && !$("#divnewLogin").is(':visible')) {
                      $('#status-message').remove();
                      $.ajax({
                          url: "IsValidGuestUser",
                          type: 'post',
                          data: $("#checkoutform").serialize(),
                          success: function (data) {
                              if (data.HasError) {
                                  isValid = false;
                                  $("#ajaxProcessPayment").dialog('close');
                                  $("#SuccessMessage").show();
                                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                  $(window).scrollTop(0);
                              }
                              else {
                                  isValid = true;
                                  $.ajax({
                                      url: "SubmitQuoteSinglePageCheckout",
                                      type: 'post',
                                      data: $("#checkoutform").serialize(),
                                      success: function (data) {
                                          if (!data.HasError) {
                                              if (data.QuoteStateId == 90) {
                                                  window.location.href = "/quote/history";
                                              }
                                              else {
                                                  Checkout.RedirectToQuoteCheckoutReceipt(data.EmailId, data.OrderId);
                                              }
                                          }
                                          else {

                                              if (data.ErrorMessage == "Logout") {
                                                  window.location.href = "/cart/index";
                                              }
                                              $("#ajaxProcessPayment").dialog('close');
                                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                              $(window).scrollTop(0);
                                          }
                                      },
                                      error: function (xhr, ajaxOptions, thrownError) {
                                          $("#ajaxProcessPayment").dialog('close');
                                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                      },
                                  });
                              }
                          },
                      });
                  }
                  else {
                      $('#status-message').remove();
                      $.ajax({
                          url: "SubmitQuoteSinglePageCheckout",
                          type: 'post',
                          data: $("#checkoutform").serialize(),
                          success: function (data) {
                              if (!data.HasError) {

                                  if (data.QuoteStateId == 90) {
                                      window.location.href = "/quote/history";
                                  }
                                  else {
                                      Checkout.RedirectToQuoteCheckoutReceipt(data.EmailId, data.OrderId);
                                  }
                              }
                              else {

                                  if (data.ErrorMessage == "Logout") {
                                      window.location.href = "/cart/index";
                                  }
                                  $("#ajaxProcessPayment").dialog('close');
                                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                              }
                          },
                          error: function (xhr, ajaxOptions, thrownError) {
                              $("#ajaxProcessPayment").dialog('close');
                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                          },
                      });
                  }
              }
          }
      },

      SubmitQuoteForSingleCheckout: function (event) {

          $("#hdnIsSaveDraft").val(false);
          if ($("#promocode").val().trim() != "" || $("#giftcard_number").val().trim() != "") {
              Checkout.ShowQuoteConfirm('Confirm?', 'Coupon or Gift Card will get applied at the time of Order Purchase.', event, "");
              return false;
          }
          else {
              Checkout.bind.SubmitQuote(event);
          }
      },
      SubmitSinglePageCheckout: function (event) {

          $('#status-message').remove()
          var isValid = true;
          event.preventDefault();
          if ($("#ddlPaymentTypes option:selected").text().toLowerCase() == 'select payment') {
              isValid = false;
              $("#ddlPaymentTypes").css({
                  "border": "1px solid red",
                  "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
              });
          }
          $('input[name="ShippingBillingAddressViewModel.ShippingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.EmailAddress"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.City"],input[name="ShippingBillingAddressViewModel.ShippingAddressModel.PhoneNumber"]').each(function () {
              if ($.trim($(this).val()) == '') {
                  isValid = false;
                  $(this).css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $(this).css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
          });

          var country = $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"] option:selected').val();
          if (country == "0" || country == "") {
              isValid = false;
              $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
              });
          }
          else {
              $('select[name="ShippingBillingAddressViewModel.ShippingAddressModel.CountryCode"]').css({
                  "border": "1px solid #C3C3C3",
                  "background": ""
              });
          }

          if ($('#CreateLogin').is(":checked")) {
              $('input[name="ShippingBillingAddressViewModel.LoginViewModel.Username"],input[name="ShippingBillingAddressViewModel.LoginViewModel.Password"]').each(function () {
                  if ($.trim($(this).val()) == '') {
                      isValid = false;
                      $(this).css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $(this).css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              });
          }

          if ($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val() == "" || !Checkout.bind.ValidateEmail($('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').val())) {
              isValid = false;
              $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                  "border": "1px solid red",
                  "background": "#FFCECE"
              });
          }
          else {
              $('input[name = "ShippingBillingAddressViewModel.EmailAddress"]').css({
                  "border": "1px solid #C3C3C3",
                  "background": ""
              });
          }

          if (!($('#billingSameAsShippingAddress').is(":checked"))) {
              $('input[name="ShippingBillingAddressViewModel.BillingAddressModel.FirstName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.LastName"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.StreetAddress1"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.PostalCode"],input[name="ShippingBillingAddressViewModel.BillingAddressModel.City"]').each(function () {
                  if ($.trim($(this).val()) == '') {
                      isValid = false;
                      $(this).css({
                          "border": "1px solid red",
                          "background": "#FFCECE"
                      });
                  }
                  else {
                      $(this).css({
                          "border": "1px solid #C3C3C3",
                          "background": ""
                      });
                  }
              });

              var country = $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"] option:selected').val();
              if (country == "0" || country == "") {
                  isValid = false;
                  $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                      "border": "1px solid red",
                      "background": "#FFCECE url('../../../Images/drop-arrow.png') no-repeat 98% center"
                  });
              }
              else {
                  $('select[name="ShippingBillingAddressViewModel.BillingAddressModel.CountryCode"]').css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
          }

          if ($('#ddlPaymentTypes').val() == "2") {
              var purchaseOrderNumber = $('#txtPurchaseOrderNumber').val().trim();
              if (purchaseOrderNumber.length < 1) {
                  isValid = false;
                  $('#errorpurchaseorder').show();
                  $('#txtPurchaseOrderNumber').css({
                      "border": "1px solid red",
                      "background": "#FFCECE"
                  });
              }
              else {
                  $('#txtPurchaseOrderNumber').css({
                      "border": "1px solid #C3C3C3",
                      "background": ""
                  });
              }
          }

          if ($('#ddlPaymentTypes').val() != "1" || ($("#TotalAmount").val() == "$0.00")) {
              if (isValid) {
                  $('#status-message').remove();
                  if ($("#ajaxProcessPayment").html() == undefined) {
                      $('body').append('<div id="ajaxProcessPayment"><p id="ajaxProcessPaymentMsg">Please wait while processing and do not close this window</p></div>');
                  }

                  $("#ajaxProcessPayment").html('<p id="ajaxProcessPaymentMsg">Please wait while processing and do not close this window</p>');
                  $("#ajaxProcessPayment").dialog({
                      title: 'Order Processing',
                      resizable: false,
                      modal: true,
                      create: function () {
                          $(this).closest(".ui-dialog").addClass("ui-md-popup ui-popup-top");
                      },
                      closeOnEscape: false,
                      open: function (event, ui) {
                          $("#ajaxProcessPayment").parent().find(" .ui-dialog-titlebar-close").hide();
                      }
                  });
                  if ($('#CreateLogin').is(":checked")) {
                      $.ajax({
                          url: "CreateSingleCheckoutAccount",
                          type: 'post',
                          data: $("#checkoutform").serialize(),
                          success: function (data) {
                              if (data.HasError) {
                                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                  isValid = false;
                                  $("#ajaxProcessPayment").dialog('close');
                                  $(window).scrollTop(0);
                                  return isValid;
                              }
                              else {
                                  $('#status-message').remove();
                                  $.ajax({
                                      url: "SubmitSingleCheckout",
                                      type: 'post',
                                      data: $("#checkoutform").serialize(),
                                      success: function (data) {
                                          if (!data.HasError) {
                                              var form = $('<form action="CheckoutReceipt" method="post">' +
                                                  '<input type="hidden" name="EmailId" value="' + data.EmailId + '" />' +
                                                  '<input type="hidden" name="OrderId" value="' + data.OrderId + '" />' +
                                                  '</form>');
                                              $('body').append(form);
                                              $(form).submit();
                                          }
                                          else {
                                              var isError = data.ErrorMessage;
                                              if (data.ErrorMessage == "Logout") {
                                                  window.location.href = "/cart/index";
                                              }
                                              if (isError != "" && isError != null) {
                                                  window.location = "/Checkout/SingleCheckout?message=" + data.ErrorMessage;
                                              }

                                              $("#ajaxProcessPayment").dialog('close');
                                          }
                                      },
                                      error: function (xhr, ajaxOptions, thrownError) {
                                          $("#ajaxProcessPayment").dialog('close');
                                          $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                      },
                                  });
                              }
                          }
                      })
                  }
                  else {
                      if (!$('#CreateLogin').is(":checked") && !$("#divnewLogin").is(':visible')) {
                          $('#status-message').remove();
                          $.ajax({
                              url: "IsValidGuestUser",
                              type: 'post',
                              data: $("#checkoutform").serialize(),
                              success: function (data) {
                                  if (data.HasError) {
                                      isValid = false;
                                      $("#ajaxProcessPayment").dialog('close');
                                      $("#SuccessMessage").show();
                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                      $(window).scrollTop(0);
                                  }
                                  else {
                                      isValid = true;
                                      $.ajax({
                                          url: "SubmitSingleCheckout",
                                          type: 'post',
                                          data: $("#checkoutform").serialize(),
                                          success: function (data) {
                                              if (!data.HasError) {
                                                  var form = $('<form action="CheckoutReceipt" method="post">' +
                                                      '<input type="hidden" name="EmailId" value="' + data.EmailId + '" />' +
                                                      '<input type="hidden" name="OrderId" value="' + data.OrderId + '" />' +
                                                      '</form>');
                                                  $('body').append(form);
                                                  $(form).submit();
                                              }
                                              else {

                                                  if (data.ErrorMessage == "Logout") {
                                                      window.location.href = "/cart/index";
                                                  }
                                                  $("#ajaxProcessPayment").dialog('close');
                                                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                                  $(window).scrollTop(0);
                                              }
                                          },
                                          error: function (xhr, ajaxOptions, thrownError) {
                                              $("#ajaxProcessPayment").dialog('close');
                                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                          },
                                      });
                                  }
                              },
                          });
                      }
                      else {
                          $('#status-message').remove();
                          $.ajax({
                              url: "SubmitSingleCheckout",
                              type: 'post',
                              data: $("#checkoutform").serialize(),
                              success: function (data) {
                                  if (!data.HasError) {
                                      var form = $('<form action="CheckoutReceipt" method="post">' +
                                          '<input type="hidden" name="EmailId" value="' + data.EmailId + '" />' +
                                          '<input type="hidden" name="OrderId" value="' + data.OrderId + '" />' +
                                          '</form>');
                                      $('body').append(form);
                                      $(form).submit();
                                  }
                                  else {

                                      if (data.ErrorMessage == "Logout") {
                                          window.location.href = "/cart/index";
                                      }
                                      $("#ajaxProcessPayment").dialog('close');
                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                  }
                              },
                              error: function (xhr, ajaxOptions, thrownError) {
                                  $("#ajaxProcessPayment").dialog('close');
                                  $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                              },
                          });
                      }
                  }
              }
          }
          else {
              $('#status-message').remove()
              if (isValid == false) {
                  event.preventDefault();
              }
              else {

                  if ($("#radioCCList").is(':visible')) {
                      return Checkout.bind.PaymentProcess();
                  }
                  else {
                      isValid = Checkout.bind.SetCreditCardValidation();
                  }
              }
              if (isValid) {
                  overlayforwaitblock();
                  $('#status-message').remove();
                  if ($('#CreateLogin').is(":checked")) {
                      $.ajax({
                          url: "CreateCreditCardUserAccount",
                          type: 'post',
                          data: $("#checkoutform").serialize(),
                          success: function (data) {
                              overlayforwaitnone();
                              if (data.HasError) {
                                  if (data.ErrorMessage != undefined && data.ErrorMessage != "" && data.ErrorMessage != null) {
                                      window.location = "/Checkout/SingleCheckout?message=" + data.ErrorMessage;
                                  }
                                  isValid = false;
                                  return isValid;
                              }
                              else {
                                  $.ajax({
                                      url: "/Checkout/GetUpdatedCart",
                                      data: $("#checkoutform").serialize(),
                                      type: 'POST',
                                      success: function (data) {
                                          overlayforwaitnone();
                                          var cartData = $.parseHTML(data)
                                          $(".cart-summary").html($(cartData).find('.cart-summary').html())
                                          var errorMessage = $(cartData).find('#status-message').html();
                                          if (errorMessage != undefined && errorMessage != "") {
                                              $("#ajaxProcessPayment").dialog('close');
                                              isValid = false;
                                              event.preventDefault();
                                              $("#SuccessMessage").show();
                                              $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                                              if (errorMessage != undefined && errorMessage != "" && errorMessage != null) {
                                                  window.location = "/Checkout/SingleCheckout?message=" + errorMessage;
                                              }
                                              $(window).scrollTop(0);
                                          }
                                          else {
                                              Checkout.bind.PaymentProcess();
                                          }
                                      }
                                  });
                              }
                          }
                      })
                  }
                  else {
                      if (!$('#CreateLogin').is(":checked") && !$("#divnewLogin").is(':visible')) {
                          $.ajax({
                              url: "IsValidGuestUser",
                              type: 'post',
                              data: $("#checkoutform").serialize(),
                              success: function (data) {
                                  overlayforwaitnone();
                                  if (data.HasError) {
                                      isValid = false;
                                      $("#ajaxProcessPayment").dialog('close');
                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + data.ErrorMessage + '</div>');
                                      $(window).scrollTop(0);
                                  }
                                  else {
                                      isValid = true;
                                      if ($('#ddlPaymentTypes').val() == "1") {
                                          $.ajax({
                                              url: "/Checkout/GetUpdatedCart",
                                              data: $("#checkoutform").serialize(),
                                              type: 'POST',
                                              success: function (data) {
                                                  overlayforwaitblock();
                                                  var cartData = $.parseHTML(data)
                                                  $(".cart-summary").html($(cartData).find('.cart-summary').html())
                                                  var errorMessage = $(cartData).find('#status-message').html();
                                                  if (errorMessage != undefined && errorMessage != "") {
                                                      $("#ajaxProcessPayment").dialog('close');
                                                      isValid = false;
                                                      event.preventDefault();
                                                      $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + errorMessage + '</div>');
                                                      $(window).scrollTop(0);
                                                  }
                                                  else {
                                                      overlayforwaitnone();
                                                      Checkout.bind.PaymentProcess();
                                                  }
                                              }
                                          });
                                      }
                                  }
                              },
                          });
                      }
                  }
              }
          }
      }
  },
  RedirectToQuoteCheckoutReceipt: function (emailId, orderId) {
      var form = $('<form action="QuoteReceipt" method="post">' +
          '<input type="hidden" name="EmailId" value="' + emailId + '" />' +
          '<input type="hidden" name="OrderId" value="' + orderId + '" />' +
          '<input type="hidden" name="IsQuote" value="true" />' +
          '</form>');
      $('body').append(form);
      $(form).submit();
  },
  ShowQuoteConfirm: function (title, message, e, urlAddress) {
      var toggleMessage, toggleTitle, RefreshLocationOndelete = false;
      if ($("BODY").find("div#popup_container").length == 0) {
          CreatePopUp(title);
      }

      $("#popup_title").html(title);
      if (toggleMessage === undefined || toggleMessage === '') {
          $("#popup_message").html(message);
      }
      else {
          $("#popup_message").html(toggleMessage);
      }

      $("#popup_container").dialog({
          resizable: true,
          title: title,
          modal: true,
          stack: true,
          width: 400,
          buttons: {
              "OK": function () {
                  $(this).dialog("close");

                  if (urlAddress != "" && typeof urlAddress != 'undefined') {
                      window.location.href = urlAddress;
                  }
                  else {
                      Checkout.bind.SubmitQuote(e);
                  }
              },
              Cancel: function () {
                  $(this).dialog("close");
              }
          }
      });
  }
}
;
var Search = {

    // INIT
    init: function () {
        $.getScript("/Scripts/lib/purl.js");
        Search.bind.hideControl();
        Search.bind.searchSort();

        Search.bind.changeSearchProductViewDisplay();
        Search.bind.setProductViewDisplay();
        Search.bind.SetSwatchImage();
        Search.bind.recentProductList(function (res) {
            if (res === true) { loadSlider(); }
        });
        Search.bind.addToCompare();
        Search.bind.compareProductList();
        Home.bind.quickView();
    },

    // BINDINGS
    bind: {
        // Redirects to new search results page when the sorting dropdown is changed
        // Uses purl library
        searchSort: function () {
            _debug("bind.searchSort()");

            $(".layout-search .search-sorting select").on("change", function () {
                $(".layout-search .search-results").html('<div class="search-results-wait">...</div>');

                var url = purl(),
					query = url.param();

                query.sort = $(this).val();
                query.pagenumber = 1;
                window.location.href = url.attr("path") + "?" + $.param(query) + "#product-grid";
            });
            Search.bind.searchPaging();
        },

        searchPaging: function () {
            _debug("bind.searchPaging()");

            $(".layout-paging .search-paging select").on("change", function () {
                $(".layout-search .search-results").html('<div class="search-results-wait">...</div>');

                var url = purl(),
					query = url.param();

                query.pageSize = $(this).val();
                query.pagenumber = 1;

                window.location.href = url.attr("path") + "?" + $.param(query) + "#product-grid";
            });
        },

        // get recent  product grids
        recentProductList: function (fun_res) {
            var productId = null;
            var htmlContainer = "#category-recent-product .recent-view-items";
            Api.getRecentProducts(productId, 3, function (response) {
                if (htmlContainer) {
                    $(htmlContainer).html(response.data.html);
                }
                if (response.data.html == undefined || response.data.html.length < 1) {
                    $("#category-recent-product").hide();
                }
                else {
                    $("#category-recent-product").show();
                }
                fun_res(true);
            });
        },

        //Display products which are added for comparison.
        compareProductList: function () {
            var htmlContainer = "#compareProductList";
            Api.getCompareProducts(function (response) {
                if (htmlContainer) {
                    $(htmlContainer).html(response.data.html);
                    if (response.count > 0) {
                        $("#compareProductBox").removeAttr("style");
                    }
                    $(".remove-compare").unbind("click");
                    $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
                }
                if (response.data.html == undefined || response.data.html.length < 1) {
                    $("#compareProductList").hide();
                }
                else {
                    $("#compareProductList").show();
                }
                return true;
            });
        },

        changeSearchProductViewDisplay: function () {
            $(".productview").on("click", function () {
                var previousClass = $("#view-option").attr('class').split(' ')[1];
                var newClass = $(this).attr('title').toLowerCase().replace(" ", "-");

                $(".productview").each(function () {
                    if ($(this).attr("class").indexOf('-active') >= 0) {
                        var baseClass = $(this).attr('class').replace('-active', '');
                        $(this).removeClass($(this).attr('class'));
                        $(this).addClass(baseClass);
                    }
                });

                var activeclass = $(this).attr('class') + '-active';
                $(this).removeClass($(this).attr('class'));
                $(this).addClass(activeclass);

                if (previousClass != undefined && previousClass.length > 0) {
                    $("#view-option").removeClass(previousClass).addClass(newClass)
                } else {
                    $("#view-option").addClass(newClass)
                }
                if (navigator.userAgent.toLowerCase().indexOf("iphone") >= 0) {
                    Search.bind.setCookie("currentDisplayType", newClass, 1);
                }
                else {
                    localStorage["currentDisplayType"] = newClass;
                }
            });
        },

        setProductViewDisplay: function () {
            if (navigator.userAgent.toLowerCase().indexOf("iphone") >= 0) {
                var displayType = Category.getCookie("currentDisplayType");
            }
            else {
                var displayType = localStorage["currentDisplayType"];
            }
            var previousClass = $("#view-option").attr('class').split(' ')[1];

            $(".productview").each(function () {
                if ($(this).attr("class").indexOf('-active') >= 0) {
                    var baseClass = $(this).attr('class').replace('-active', '');
                    $(this).removeClass($(this).attr('class'));
                    $(this).addClass(baseClass);
                }
            });

            $(".productview").each(function () {
                if (!displayType) {
                    if ($(this).attr("class").indexOf("grid-view") >= 0) {
                        var firstClass = $(this).attr('class');
                        $(this).removeClass(firstClass);
                        $(this).addClass(firstClass + "-active");
                    }
                }
                else {
                    if ($(this).attr("class").indexOf(displayType) >= 0) {
                        var activeclass = $(this).attr('class') + '-active';
                        $(this).removeClass($(this).attr('class'));
                        $(this).addClass(activeclass);
                    }
                }
            });
            if (!displayType) {
                $("#view-option").removeClass(previousClass).addClass("grid-view");
            }
            else {
                $("#view-option").removeClass(previousClass).addClass(displayType);
            }
            $(".view-opt").show();
        },

        setCookie: function (name, value, days) {
            var expires;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            else {
                expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },

        getCookie: function (c_name) {
            if (document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=");
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    c_end = document.cookie.indexOf(";", c_start);
                    if (c_end == -1) {
                        c_end = document.cookie.length;
                    }
                    return unescape(document.cookie.substring(c_start, c_end));
                }
            }
            return "";
        },

        SetSwatchImage: function () {
            _debug("bind.SetSwatchImage()");
            $(".SwatchImage").on("click", function () {
                var productImageId = $(this).attr("data-imgid");
                if (productImageId != null && productImageId > 0) {
                    $("#" + productImageId).attr('src', $(this).attr("data-mediumsrc"));
                    $("#" + productImageId).attr('data-src', $(this).attr("data-mediumsrc"));
                }
            });
        },
        hideControl: function () {
            $("#category-recent-product").hide();
            $(".view-opt").hide();
        },

        //add product in comparison list and display on category page
        addToCompare: function () {
            _debug("bind.addToCompare()");
            $(".button-compare").on("click", function () {
                var productId = $(this).attr("data-productid");
                var categoryId = $(this).attr("data-categoryid");
                var htmlContainer = "#compareProductList";
                Api.globalAddToCompare(productId, categoryId, function (response) {
                    if (response.success == true) {
                        $(htmlContainer).html(response.data.html);
                        $("#compareProductBox").removeAttr("style");
                        $(".remove-compare").unbind("click");
                        $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
                        $("[data-products-comparison]").text(response.message)
                        $("[data-products-comparison]").dialog({
                            title: "Product Compare",
                            resizable: false,
                            modal: true,
                            width: 400,
                            height: 170,
                            buttons: {
                                "Add  More": function () {
                                    var htmlContainer = "#compareProductList";
                                    $(".ui-dialog-titlebar-close").trigger("click");
                                },
                                "View  Comparison": function () {
                                    Api.getProductComparison(function (response) {
                                        if (response.status == true) {
                                            $(".ui-dialog-titlebar-close").trigger("click");
                                            $("[data-products-comparison]").text(response.message)
                                            $("[data-products-comparison]").dialog({
                                                title: "Product Compare",
                                                resizable: false,
                                                modal: true,
                                                width: 400,
                                                height: 170,
                                                buttons: {
                                                    "Add More": function () {
                                                        $(".ui-dialog-titlebar-close").trigger("click");
                                                    }
                                                },
                                                create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                                            });
                                        }
                                        else {
                                            window.location.href = "/Product/ViewComparison";
                                        }
                                    });
                                }
                            },
                            create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                        });
                    }
                    else if (response.errorCode == 1) {
                        $("[data-products-comparison]").text(response.message)
                        $("[data-products-comparison]").dialog({
                            title: "Product Compare",
                            resizable: false,
                            modal: true,
                            buttons: {
                                "OK": function () {
                                    Api.categoryAddToCompare(productId, categoryId, function (response) {
                                        if (response.success == true) {
                                            $(htmlContainer).html(response.data.html);
                                            $("#compareProductBox").removeAttr("style");
                                            $(".remove-compare").off("click");
                                            $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
                                            $(".ui-dialog-titlebar-close").trigger("click");
                                            $("[data-products-comparison]").text(response.message)
                                            $("[data-products-comparison]").dialog({
                                                title: "Product Compare",
                                                resizable: false,
                                                modal: true,
                                                width: 400,
                                                height: 170,
                                                buttons: {
                                                    "Add  More": function () {
                                                        var htmlContainer = "#compareProductList";
                                                        $(".ui-dialog-titlebar-close").trigger("click");
                                                        return true;
                                                    },
                                                    "View  Comparison": function () {
                                                        Api.getProductComparison(function (response) {
                                                            if (response.status == true) {
                                                                $(".ui-dialog-titlebar-close").trigger("click");
                                                                $("[data-products-comparison]").text(response.message)
                                                                $("[data-products-comparison]").dialog({
                                                                    title: "Product Compare",
                                                                    resizable: false,
                                                                    modal: true,
                                                                    width: 400,
                                                                    height: 170,
                                                                    buttons: {
                                                                        addMore: function () {
                                                                            $(".ui-dialog-titlebar-close").trigger("click");
                                                                        }
                                                                    },
                                                                    create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                                                                });
                                                            }
                                                            else {
                                                                window.location.href = "/Product/ViewComparison";
                                                            }
                                                        });
                                                    }
                                                },
                                                create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                                            });
                                        }
                                    });
                                },
                                "Cancel": function () {
                                    $(".ui-dialog-titlebar-close").trigger("click");
                                }
                            },
                        });
                    }
                    else if (response.errorCode == 2) {
                        $("[data-products-comparison]").text(response.message)
                        $("[data-products-comparison]").dialog({
                            title: "Product Compare",
                            resizable: false,
                            modal: true,
                            width: 400,
                            height: 170,
                            buttons: {
                                "OK": function () {
                                    $(".ui-dialog-titlebar-close").trigger("click");
                                    return true;
                                }
                            },
                            create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                        });
                    }
                    else if (response.errorCode == 3) {
                        $("[data-products-comparison]").text(response.message)
                        $("[data-products-comparison]").dialog({
                            title: "Product Compare",
                            resizable: false,
                            modal: true,
                            width: 400,
                            height: 170,
                            buttons: {
                                "OK": function () {
                                    $(".ui-dialog-titlebar-close").trigger("click");
                                    return true;
                                }
                            },
                            create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                        });
                    }
                    if (response.data.html == undefined || response.data.html.length < 1) {
                        $("#compareProductList").hide();
                    }
                    else {
                        $("#compareProductList").show();
                    }
                });
            });
        },

        removeProduct: function (productId) {
            _debug("bind.removeProduct()");
            var htmlContainer = "#compareProductList";
            var url = window.location.href.toString().split('/')
            var control = url[3];
            Api.removeProduct(productId, control, function (response) {
                if (htmlContainer) {
                    $(htmlContainer).html(response.data.html);
                    if (response.count > 0) {
                        $("#compareProductBox").removeAttr("style");
                    }
                    $(".remove-compare").unbind("click");
                    $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
                }
                if (response.data.html == undefined || response.data.html.length < 1) {
                    $("#compareProductList").hide();
                }
                else {
                    $("#compareProductList").show();
                }
                return true;
            });
        }
    }
}
;
var addressId = 0;
var Account = {
    // FORGOT PASSWORD VIEW
    init: function () {
        Account.bind.setSelectedTab();
        _debug("Account.ForgotPassword.init()");
        Account.bind.buttonContinue();
        Account.bind.setStateByCountry();
        Account.bind.removeIcon();
        Account.bind.setDefaultState();
        Account.bind.OnStateChange();
        $("#breadcrumb-content").css("display", "none");
        var addressCity = $("#address_city").val();
        var addressZipcode = $("#address_zipcode").val();
        $(".address_country").trigger("change");
        var addressCity = $("#address_city").val(addressCity);
        var addressZipcode = $("#address_zipcode").val(addressZipcode);
    },
    // Passes user credentials and returns security question if valid
    // Final action is handled by POST submit
    toggleSecurityQuestion: function () {
        Api.getUserSecurityQuestion($("#forgot_username").val(), $("#forgot_email").val(), function (response) {
            if (response.success) {
                global.clearAlertMessage();
                $("#display-securityquestion").html(response.data.question);
                $("#dynamic-userid").val(response.data.userid);

                $("#reset-securityquestion").show();
                $("#toggle-securityquestion").hide();
            } else {
                global.setAlertMessage(response.message, "error");
                global.displayAlertMessage();
                scrollToTop();
            }

        });
    },

    ResetCityAndZipCode: function () {
        $("#address_city").val("");
        $("#address_zipcode").val("");
    },
    // Removes item from account wish list
    removeWishlistItem: function (el) {
        var clicked = $(el);
        var wishlistId = clicked.data("id");
        var wishListCount = parseInt($("#wishlistcount").text());

        Api.removeProductFromWishList(wishlistId, function (response) {
            if (response.success) {
                clicked.closest(".wishlist-item").remove();

                $("#wishlistcount").html(response.data.total);
            } else {
                global.setAlertMessage(response.message, "error");
                global.displayAlertMessage();
                scrollToTop();
            }
        });
    },
    bind: {
        // Continue button to submit username/mail for security question
        buttonContinue: function () {
            _debug("bind.buttonContinue()");

            $("#toggle-securityquestion button").on("click", function () {
                Account.toggleSecurityQuestion();
            });
        },
        // Get State by country
        setStateByCountry: function () {
            $(".address_country").on("change", function (e) {
                var stateNameCode = $(".address_state").val();
                Account.ResetCityAndZipCode();
                var stateCode = $(this).val();
                Api.getStateByCountryCode(stateCode, function (response) {
                    $('#ShippingAddressModel_StateCode').empty();
                    for (var i = 0; i < response.length; i++) {
                        $("#ShippingAddressModel_StateCode").append("<option value='" + response[i].Code + "'>" + response[i].Name + "</option>");
                    }
                    if (response.length < 1) {
                        $("#ShippingAddressModel_StateCode").append("<option value=''>Please Select</option>");
                    }
                    if (response.length > 1) {
                        if (stateNameCode != "" && stateNameCode != null) {
                            $(".address_state").val(stateNameCode);
                        }
                    }
                });
            });
            if ($(".address_country").val() == "") {
                $('#ShippingAddressModel_StateCode').append("<option value=''>Please Select</option>");
            }
        },

        setDefaultState: function () {
            var state = $("#hdn_StateCode").val();
            if (state.length < 1) {
                $("#address_country").change();
            }
        },

        OnStateChange: function () {
            $("#ShippingAddressModel_StateCode").on("change", function (e) {
                Account.ResetCityAndZipCode();
            });
        },
        removeIcon: function () {
            _debug("bind.removeIcon()");

            $("#layout-account-wishlist .wishlist-item-remove a").on("click", function (ev) {
                ev.preventDefault();
                Account.removeWishlistItem(this);
            });
        },
        setSelectedTab: function () {
            var selectedTabhref = "/" + $("body").attr("id") + "/" + $("body").attr("class");
            $(".account-dashboard .account-menu a").each(function () {           
                var arrValue = $.trim($(this).attr("add-value")).split(',');  
                var isSelected = false;
                if ($.trim($(this).attr("href")).toLowerCase() === $.trim(selectedTabhref).toLowerCase()) {
                    $(this).addClass("selected");
                    isSelected = true;
                }

                if (isSelected === false) {
                    for (var i = 0; i < arrValue.length; i++) {                    
                        if (arrValue[i].toLowerCase() === $.trim(selectedTabhref).toLowerCase()) {
                            $(this).addClass("selected");
                            break;
                        }
                    }
                }            
            });           
        }
    }
}

;
var count
var Category = {
    // INIT	
    init: function () {
        _debug("category.init()");
        //bind.recentProductList();
        Category.setSelectedCategory();
        Category.changeProductViewDisplay();
        Category.setProductViewDisplay();
        Category.SetSwatchImage();
        Category.addToCompare();
        Category.recentProductList(function (res) {
            if (res === true) { loadSlider(); }
        });
        Category.compareProductList();
        Home.bind.quickView();
        $.getScript("/Scripts/lib/purl.js");
        Search.bind.searchSort();
    },
    // get recent  product grids
    recentProductList: function (fun_res) {
        var productId = null;
        var htmlContainer = "#category-recent-product .recent-view-items";
        Api.getRecentProducts(productId, 3, function (response) {
            if (htmlContainer) {
                $(htmlContainer).html(response.data.html);
            }
            if (response.data.html == undefined || response.data.html.length < 1) {
                $("#category-recent-product").hide();
                $("#category-recent-product-header").hide();
            }
            else {
                $("#category-recent-product").show();
                $("#category-recent-product-header").show();
            }
            fun_res(true);
        });
    },

    //Display products which are added for comparison.
    compareProductList: function () {
        var htmlContainer = "#compareProductList";
        Api.getCompareProducts(function (response) {
            if (htmlContainer) {
                $(htmlContainer).html(response.data.html);
                if (response.count > 0) {
                    $("#compareProductBox").removeAttr("style");
                }
                $(".remove-compare").unbind("click");
                $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
            }
            if (response.data.html == undefined || response.data.html.length < 1) {
                $("#compareProductList").hide();
            }
            else {
                $("#compareProductList").show();
            }
            return true;
        });
    },

    changeProductViewDisplay: function () {
        $(".productview").on("click", function () {
            var previousClass = $("#view-option").attr('class').split(' ')[1];
            var newClass = $(this).attr('title').toLowerCase().replace(" ", "-");

            $(".productview").each(function () {
                if ($(this).attr("class").indexOf('-active') >= 0) {
                    var baseClass = $(this).attr('class').replace('-active', '');
                    $(this).removeClass($(this).attr('class'));
                    $(this).addClass(baseClass);
                }
            });

            var activeclass = $(this).attr('class') + '-active';
            $(this).removeClass($(this).attr('class'));
            $(this).addClass(activeclass);

            if (previousClass != undefined && previousClass.length > 0) {
                $("#view-option").removeClass(previousClass).addClass(newClass)
            } else {
                $("#view-option").addClass(newClass)
            }

            if (navigator.userAgent.toLowerCase().indexOf("iphone") >= 0) {
                Category.setCookie("currentDisplayType", newClass, 1);
            }
            else {
                localStorage["currentDisplayType"] = newClass;
            }
        });
    },

    setProductViewDisplay: function () {
        if (navigator.userAgent.toLowerCase().indexOf("iphone") >= 0) {
            var displayType = Category.getCookie("currentDisplayType");
        }
        else {
            var displayType = localStorage["currentDisplayType"];
        }

        if ($("#view-option").html() != undefined) {
            var previousClass = $("#view-option").attr('class').split(' ')[1];

            $(".productview").each(function () {
                if ($(this).attr("class").indexOf('-active') >= 0) {
                    var baseClass = $(this).attr('class').replace('-active', '');
                    $(this).removeClass($(this).attr('class'))
                    $(this).addClass(baseClass);
                }
            });

            $(".productview").each(function () {
                if (!displayType) {
                    if ($(this).attr("class").indexOf("grid-view") >= 0) {
                        var firstClass = $(this).attr('class');
                        $(this).removeClass(firstClass);
                        $(this).addClass(firstClass + "-active");
                    }
                }
                else {
                    if ($(this).attr("class").indexOf(displayType) >= 0) {
                        var activeclass = $(this).attr('class') + '-active';
                        $(this).removeClass($(this).attr('class'));
                        $(this).addClass(activeclass);
                    }
                }
            });
            if (!displayType) {
                $("#view-option").removeClass(previousClass).addClass("grid-view");
            }
            else {
                $("#view-option").removeClass(previousClass).addClass(displayType);
            }
        }
    },

    setCookie: function (name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else {
            expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    getCookie: function (c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) {
                    c_end = document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    },

    //Change the Product image in Category view, on click of Swatch(Color) Images. - Start 
    SetSwatchImage: function () {
        _debug("bind.SetSwatchImage()");
        $(".SwatchImage").on("click", function () {
            var productImageId = $(this).attr("data-imgid");
            if (productImageId != null && productImageId > 0) {
                $("#" + productImageId).attr('src', $(this).attr("data-mediumsrc"));
                $("#" + productImageId).attr('data-src', $(this).attr("data-mediumsrc"));
            }
        });
    },
    //Change the Product image in Category view, on click of Swatch(Color) Images. - End 

    //add product in comparison list and display on category page
    addToCompare: function () {
        _debug("bind.addToCompare()");
        $(".button-compare").on("click", function () {
            var productId = $(this).attr("data-productid");
            var categoryId = $(this).attr("data-categoryid");
            var htmlContainer = "#compareProductList";
            Api.globalAddToCompare(productId, categoryId, function (response) {
                if (response.success == true) {
                    $(htmlContainer).html(response.data.html);
                    $("#compareProductBox").removeAttr("style");
                    $(".remove-compare").unbind("click");
                    $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
                    $("[data-products-comparison]").text(response.message)
                    $("[data-products-comparison]").dialog({
                        title: "Product Compare",
                        resizable: false,
                        modal: true,
                        width: 400,
                        height: 170,
                        buttons: {
                            "Add  More": function () {
                                var htmlContainer = "#compareProductList";
                                $(".ui-dialog-titlebar-close").trigger("click");
                            },
                            "View  Comparison": function () {
                                Api.getProductComparison(function (response) {
                                    if (response.status == true) {
                                        $(".ui-dialog-titlebar-close").trigger("click");
                                        $("[data-products-comparison]").text(response.message)
                                        $("[data-products-comparison]").dialog({
                                            title: "Product Compare",
                                            resizable: false,
                                            modal: true,
                                            width: 400,
                                            height: 170,
                                            buttons: {
                                                "Add More": function () {
                                                    $(".ui-dialog-titlebar-close").trigger("click");
                                                }
                                            },
                                            create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup"); }
                                        });
                                    }
                                    else {
                                        window.location.href = "/Product/ViewComparison";
                                    }
                                });
                            }
                        },
                        create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                    });
                }
                else if (response.errorCode == 1) {
                    $("[data-products-comparison]").text(response.message)
                    $("[data-products-comparison]").dialog({
                        title: "Product Compare",
                        resizable: false,
                        modal: true,
                        buttons: {
                            "OK": function () {
                                Api.categoryAddToCompare(productId, categoryId, function (response) {
                                    if (response.success == true) {
                                        $(htmlContainer).html(response.data.html);
                                        $("#compareProductBox").removeAttr("style");
                                        $(".remove-compare").unbind("click");
                                        $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
                                        $(".ui-dialog-titlebar-close").trigger("click");
                                        $("[data-products-comparison]").text(response.message)
                                        $("[data-products-comparison]").dialog({
                                            title: "Product Compare",
                                            resizable: false,
                                            modal: true,
                                            width: 400,
                                            height: 170,
                                            buttons: {
                                                "Add  More": function () {
                                                    var htmlContainer = "#compareProductList";
                                                    $(".ui-dialog-titlebar-close").trigger("click");
                                                    return true;
                                                },
                                                "View  Comparison": function () {
                                                    Api.getProductComparison(function (response) {
                                                        if (response.status == true) {
                                                            $(".ui-dialog-titlebar-close").trigger("click");
                                                            $("[data-products-comparison]").text(response.message)
                                                            $("[data-products-comparison]").dialog({
                                                                title: "Product Compare",
                                                                resizable: false,
                                                                modal: true,
                                                                width: 400,
                                                                height: 170,
                                                                buttons: {
                                                                    "Add  More": function () {
                                                                        $(".ui-dialog-titlebar-close").trigger("click");
                                                                    }
                                                                },
                                                                create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                                                            });
                                                        }
                                                        else {
                                                            window.location.href = "/Product/ViewComparison";
                                                        }
                                                    });
                                                }
                                            },
                                            create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                                        });
                                    }
                                });
                            },
                            "Cancel": function () {
                                $(".ui-dialog-titlebar-close").trigger("click");
                            }
                        },
                    });
                }
                else if (response.errorCode == 2) {
                    $("[data-products-comparison]").text(response.message)
                    $("[data-products-comparison]").dialog({
                        title: "Product Compare",
                        resizable: false,
                        modal: true,
                        width: 400,
                        height: 170,
                        buttons: {
                            "OK": function () {
                                $(".ui-dialog-titlebar-close").trigger("click");
                                return true;
                            }
                        },
                        create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                    });

                }
                else if (response.errorCode == 3) {
                    $("[data-products-comparison]").text(response.message)
                    $("[data-products-comparison]").dialog({
                        title: "Product Compare",
                        resizable: false,
                        modal: true,
                        width: 400,
                        height: 170,
                        buttons: {
                            "OK": function () {
                                $(".ui-dialog-titlebar-close").trigger("click");
                                return true;
                            }
                        },
                        create: function () { $(this).closest(".ui-dialog").addClass("ui-sm-popup compare-popup-option"); }
                    });
                }
                if (response.data.html == undefined || response.data.html.length < 1) {
                    $("#compareProductList").hide();
                }
                else {
                    $("#compareProductList").show();
                }
            });
        });
    },

    removeProduct: function (productId) {
        _debug("bind.removeProduct()");
        var htmlContainer = "#compareProductList";
        var url = window.location.href.toString().split('/')
        var control = url[3];
        Api.removeProduct(productId, control, function (response) {
            if (htmlContainer) {
                $(htmlContainer).html(response.data.html);
                if (response.count > 0) {
                    $("#compareProductBox").removeAttr("style");
                }
                $(".remove-compare").unbind("click");
                $(".remove-compare").on("click", function () { Category.removeProduct($(this).attr("data-productid")); });
            }
            if (response.data.html == undefined || response.data.html.length < 1) {
                $("#compareProductList").hide();
            }
            else {
                $("#compareProductList").show();
            }
            return true;
        });
    },
    setSelectedCategory: function () {
        if ($('#hdnCategoryName').length && $('#hdnCategoryId').length) {
            Api.setProductCategory($("#hdnCategoryId").val(), $("#hdnCategoryName").val(), function (response) {
            });
        }
    }
}
;
;(function ($) {
    $.fn.flexisel = function (options) {

        var defaults = $.extend({
            visibleItems: 4,
            animationSpeed: 200,
            autoPlay: false,
            autoPlaySpeed: 3000,
            pauseOnHover: true,
            setMaxWidthAndHeight: false,
            enableResponsiveBreakpoints: true,
            clone: true,
            responsiveBreakpoints: {
                portrait: {
                    changePoint: 480,
                    visibleItems: 1
                },
                landscape: {
                    changePoint: 640,
                    visibleItems: 2
                },
                tablet: {
                    changePoint: 768,
                    visibleItems: 3
                }
            }
        }, options);

        /******************************
        Private Variables
         *******************************/

        var object = $(this);
        var settings = $.extend(defaults, options);
        var itemsWidth; // Declare the global width of each item in carousel
        var canNavigate = true;
        var itemsVisible = settings.visibleItems; // Get visible items
        var totalItems = object.children().length; // Get number of elements
        var responsivePoints = [];

        /******************************
        Public Methods
        *******************************/
        var methods = {
            init: function () {
                return this.each(function () {
                    methods.appendHTML();
                    methods.setEventHandlers();
                    methods.initializeItems();
                });
            },

            /******************************
            Initialize Items
            Fully initialize everything. Plugin is loaded and ready after finishing execution
	    *******************************/
            initializeItems: function () {

                var listParent = object.parent();
                var innerHeight = listParent.height();
                var childSet = object.children();
                methods.sortResponsiveObject(settings.responsiveBreakpoints);

                var innerWidth = listParent.width(); // Set widths
                itemsWidth = (innerWidth) / itemsVisible;
                childSet.width(itemsWidth);
                if (settings.clone) {
                    childSet.last().insertBefore(childSet.first());
                    childSet.last().insertBefore(childSet.first());
                    object.css({
                        'left': -itemsWidth
                    });
                }

                object.fadeIn();
                $(window).trigger("resize"); // needed to position arrows correctly

            },

            /******************************
                Append HTML
                Add additional markup needed by plugin to the DOM
            *******************************/
            appendHTML: function () {
                object.addClass("nbs-flexisel-ul");
                object.wrap("<div class='nbs-flexisel-container'><div class='nbs-flexisel-inner'></div></div>");
                object.find("li").addClass("nbs-flexisel-item");

                var flexiselInner = object.parent(); // flexisel-inner

                if (settings.setMaxWidthAndHeight) {
                    var baseWidth = $(".nbs-flexisel-item img").width();
                    var baseHeight = $(".nbs-flexisel-item img").height();
                    $(".nbs-flexisel-item img").css("max-width", baseWidth);
                    $(".nbs-flexisel-item img").css("max-height", baseHeight);
                }
                $("<div class='nbs-flexisel-nav-left'></div><div class='nbs-flexisel-nav-right'></div>").insertAfter(flexiselInner);
                if (settings.clone) {
                    var cloneContent = object.children().clone();
                    object.append(cloneContent);
                }
            },
            /******************************
            Set Event Handlers
	    Set events: click, resize, etc
            *******************************/
            setEventHandlers: function () {

                var listParent = object.parent();
                var flexiselInner = listParent.parent();
                var childSet = object.children();
                var leftArrow = flexiselInner.find(".nbs-flexisel-nav-left");
                var rightArrow = flexiselInner.find(".nbs-flexisel-nav-right");

                $(window).on("resize", function (event) {

                    methods.setResponsiveEvents();

                    var innerWidth = $(listParent).width();
                    var innerHeight = $(listParent).height();

                    itemsWidth = (innerWidth) / itemsVisible;

                    childSet.width(itemsWidth);
                    if (settings.clone) {
                        object.css({
                            'left': -itemsWidth
                        });
                    } else {
                        object.css({
                            'left': 0
                        });
                    }

                    // Hide the arrows if the elements are the same of the visible       !settings.clone &&              
                    if (totalItems <= itemsVisible) {
                        leftArrow.add(rightArrow).css('display', 'none');
                    }
                    else {
                        leftArrow.add(rightArrow).css('display', 'block');

                        var halfArrowHeight = (leftArrow.height()) / 2;
                        var arrowMargin = (innerHeight / 2) - halfArrowHeight;
                        leftArrow.css("top", arrowMargin + "px");
                        rightArrow.css("top", arrowMargin + "px");
                    }

                });
                $(leftArrow).on("click", function (event) {
                    methods.scrollLeft();
                });
                $(rightArrow).on("click", function (event) {
                    methods.scrollRight();
                });
                if (settings.pauseOnHover == true) {
                    $(".nbs-flexisel-item").on({
                        mouseenter: function () {
                            canNavigate = false;
                        },
                        mouseleave: function () {
                            canNavigate = true;
                        }
                    });
                }
                if (settings.autoPlay == true) {

                    setInterval(function () {
                        if (canNavigate == true)
                            methods.scrollRight();
                    }, settings.autoPlaySpeed);
                }

            },
            /******************************
            Set Responsive Events
            Set breakpoints depending on responsiveBreakpoints
            *******************************/

            setResponsiveEvents: function () {
                var contentWidth = $('html').width();

                if (settings.enableResponsiveBreakpoints) {

                    var largestCustom = responsivePoints[responsivePoints.length - 1].changePoint; // sorted array 

                    for (var i in responsivePoints) {

                        if (contentWidth >= largestCustom) { // set to default if width greater than largest custom responsiveBreakpoint 
                            itemsVisible = settings.visibleItems;
                            break;
                        }
                        else { // determine custom responsiveBreakpoint to use

                            if (contentWidth < responsivePoints[i].changePoint) {
                                itemsVisible = responsivePoints[i].visibleItems;
                                break;
                            }
                            else
                                continue;
                        }
                    }
                }
            },

            /******************************
            Sort Responsive Object
            Gets all the settings in resposiveBreakpoints and sorts them into an array
            *******************************/

            sortResponsiveObject: function (obj) {

                var responsiveObjects = [];

                for (var i in obj) {
                    responsiveObjects.push(obj[i]);
                }

                responsiveObjects.sort(function (a, b) {
                    return a.changePoint - b.changePoint;
                });

                responsivePoints = responsiveObjects;
            },

            /******************************
            Scroll Left
            *******************************/
            scrollLeft: function () {
                if (object.position().left < 0) {
                    if (canNavigate == true) {
                        canNavigate = false;

                        var listParent = object.parent();
                        var innerWidth = listParent.width();

                        itemsWidth = (innerWidth) / itemsVisible;

                        var childSet = object.children();

                        object.animate({
                            'left': "+=" + itemsWidth
                        }, {
                            queue: false,
                            duration: settings.animationSpeed,
                            easing: "linear",
                            complete: function () {
                                if (settings.clone) {
                                    childSet.last().insertBefore(
                                            childSet.first()); // Get the first list item and put it after the last list item (that's how the infinite effects is made)                                   
                                }
                                methods.adjustScroll();
                                canNavigate = true;
                            }
                        });
                    }
                }
            },
            /******************************
            Scroll Right
            *******************************/
            scrollRight: function () {
                var listParent = object.parent();
                var innerWidth = listParent.width();

                itemsWidth = (innerWidth) / itemsVisible;

                var difObject = (itemsWidth - innerWidth);
                var objPosition = (object.position().left + ((totalItems - itemsVisible) * itemsWidth) - innerWidth);

                if ((difObject <= Math.ceil(objPosition)) && (!settings.clone)) {
                    if (canNavigate == true) {
                        canNavigate = false;

                        object.animate({
                            'left': "-=" + itemsWidth
                        }, {
                            queue: false,
                            duration: settings.animationSpeed,
                            easing: "linear",
                            complete: function () {
                                methods.adjustScroll();
                                canNavigate = true;
                            }
                        });
                    }
                } else if (settings.clone) {
                    if (canNavigate == true) {
                        canNavigate = false;

                        var childSet = object.children();

                        object.animate({
                            'left': "-=" + itemsWidth
                        }, {
                            queue: false,
                            duration: settings.animationSpeed,
                            easing: "linear",
                            complete: function () {
                                childSet.first().insertAfter(childSet.last()); // Get the first list item and put it after the last list item (that's how the infinite effects is made)                                
                                methods.adjustScroll();
                                canNavigate = true;
                            }
                        });
                    }
                };
            },
            /******************************
            Adjust Scroll 
             *******************************/
            adjustScroll: function () {
                var listParent = object.parent();
                var childSet = object.children();

                var innerWidth = listParent.width();
                itemsWidth = (innerWidth) / itemsVisible;
                childSet.width(itemsWidth);
                if (settings.clone) {
                    object.css({
                        'left': -itemsWidth
                    });
                }
            }
        };
        if (methods[options]) { // $("#element").pluginName('methodName', 'arg1', 'arg2');
            return methods[options].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof options === 'object' || !options) { // $("#element").pluginName({ option: 1, option:2 });
            return methods.init.apply(this);
        } else {
            $.error('Method "' + method + '" does not exist in flexisel plugin!');
        }
    };
})(jQuery);

var index = 0;

function slider(cloneVal, visibleItems, index) {    
    $(".flexisel-product-slider:eq(" + index + ")").flexisel({
        visibleItems: visibleItems,
        animationSpeed: 500,
        autoPlay: false,
        autoPlaySpeed: 3000,
        enableResponsiveBreakpoints: true,
        clone: cloneVal,
        responsiveBreakpoints: {
            portrait: {
                changePoint: 480,
                visibleItems: 2
            },
            landscape: {
                changePoint: 640,
                visibleItems: 3
            },
            tablet: {
                changePoint: 769,
                visibleItems: 3
            }
        }
    });
}

function loadSlider() {    
    var count = $(".flexisel-product-slider").length;
    for (var i = 0; i <= count; i++) {
        startSlider(i);
    }
}

function startSlider(index) {    
    var url = window.location.href.toLowerCase();
    var winWidth = $(window).width();
    var cloneValue;
    var visibleItms;

    if (!(url.indexOf('search') === -1)) {
        visibleItms = 4;
    } else {
        visibleItms = 5;
    }
    
    if (winWidth <= 320) {
        visibleItms = 2;
    } else if (winWidth <= 640) {
        visibleItms = 3;
    } else if (winWidth <= 769) {
        visibleItms = 5;
    }
        
    if ($(".flexisel-product-slider:eq(" + index + ") li").length <= visibleItms) {
        cloneValue = false;
    } else {
        cloneValue = true;
    }

    this.slider(cloneValue, visibleItms, index);
};
(function ($) {
    "use strict";

    var ver = 'simpleGallery-1.0.1';

    function debug(message) {
        if (window.console) {
            console.log(message);
        }
    }

    $.fn.simpleGallery = function (options) {
        var opts = $.extend({}, $.fn.simpleGallery.defaults, options);

        if (this.length <= 0) {
            debug('There are no thumbnails in the gallery');
            return false;
        }

        this.each(function () {
            var img = $('<img>');
            img.src = $(this).attr('rel');
        });

        var init = function () {
            var parent_anchor =  $(this).parents(opts.thumbnail_anchor),
                src = parent_anchor.attr(opts.big_image_attr),
                lens_image = parent_anchor.attr(opts.lens_image_attr);
            var image_container = $(this).parents(opts.gallery_container).find(opts.big_image_container);

            var loading_image = $('<img>', {'src': opts.loading_image});
            image_container.html(loading_image);

            var a = $('<a>').attr('data-lens-image', lens_image).addClass(opts.parent_anchor_class);
            var img = $('<img>').load(function(){
                img.appendTo(a);
                image_container.html(a);
            }).attr('src', src).addClass(opts.big_image_class);

        };

        $(this).on(opts.show_event, init);

        return this;
    };

    $.fn.simpleGallery.ver = function () { return ver; };

    $.fn.simpleGallery.defaults = {
        thumbnail_anchor: '.simpleLens-thumbnail-wrapper',
        big_image_class: 'simpleLens-big-image',
        lens_image_attr: 'data-lens-image',
        big_image_attr: 'data-big-image',
        parent_anchor_class: 'simpleLens-lens-image',
        gallery_container: '.simpleLens-gallery-container',
        big_image_container: '.simpleLens-big-image-container',
        loading_image: 'images/loading.gif',
        show_event: 'mouseenter'
    };

})( jQuery );;
(function ($) {
    "use strict";

    var ver = 'simpleLens-1.0.1';

    function debug(message) {
        if (window.console) {
            console.log(message);
        }
    }

    $.fn.simpleLens = function (options) {
        var opts = $.extend({}, $.fn.simpleLens.defaults, options);

        var big_image = {
            init: function (image) {
                this.height = image.height();
                this.width = image.width();
                this.offset = image.offset();
                this.position = image.position();

                this.calc_image_limits();
            },
            calc_image_limits: function(){
                this.limits = {
                    x_left : (this.position.left),
                    x_right : (this.position.left + this.width),
                    y_top : (this.position.top),
                    y_bottom : (this.position.top + this.height)
                }
            },
            calc_view_position: function (e) {
                return {
                    org_x: (e.pageX - this.offset.left),
                    org_y: (e.pageY - this.offset.top)
                }
            }
        };

        var cursor = {
            init: function(parent_anchor, lens_container, ratio, position){
                this.parent_anchor = parent_anchor;
                this.lens_container = lens_container;
                this.ratio = ratio;

                this.cursor_position = {
                    'top': 0,
                    'left': 0
                };

                this.calc_cursor_size();
                this.insert_cursor(position.org_x, position.org_y);
            },
            destroy: function(){
                $('.' + opts.cursor_class).remove();
            },
            calc_cursor_size: function () {
                this.cursor_height = this.lens_container.height() / this.ratio.x;
                this.cursor_width = this.lens_container.width() / this.ratio.y;
                this.height_center = (this.cursor_height / 2);
                this.width_center = (this.cursor_width / 2);
            },
            update_cursor_position: function (x, y) {
                var new_y = (y - this.height_center);
                var new_bottom_y = (y + this.height_center);
                var new_x = (x - this.width_center);
                var new_right_x = (x + this.width_center);

                var limits = big_image.limits;
                if (parseFloat(limits.y_top) > parseFloat(new_y)) {
                    new_y = limits.y_top;
                } else if (parseFloat(new_bottom_y) > parseFloat(limits.y_bottom)) {
                    new_y = limits.y_bottom - this.cursor_height;
                }

                if (parseFloat(limits.x_left) > parseFloat(new_x)) {
                    new_x = limits.x_left;
                } else if (parseFloat(new_right_x) > parseFloat(limits.x_right)) {
                    new_x = limits.x_right - this.cursor_width;
                }

                this.cursor_position = {
                    'top': new_y,
                    'left': new_x,
                    'center_top': new_y + this.height_center,
                    'center_left': new_x + this.width_center
                };

                if (this.cursor !== undefined) {
                    this.cursor.css(this.cursor_position);
                }
            },
            insert_cursor: function (x, y) {
                this.cursor = $('<div>', {'class': opts.cursor_class});
                this.cursor.css({
                    'height': this.cursor_height + 'px',
                    'width': this.cursor_width + 'px'
                });

                this.cursor.appendTo(this.parent_anchor);
                return this.update_cursor_position(x, y);
            }
        };

        var lens = {
            init: function(parent_anchor){
                this.parent_anchor = parent_anchor;
                this.parent_div = parent_anchor.parent(opts.parent_class);
                this.lens_image_url = parent_anchor.attr(opts.lens_image_attr);
                this.lens_container = $('<div>', {'class': opts.lens_class});
                this.lens_image = $('<img>');
                big_image.init(parent_anchor.find(opts.big_image_class));

                if (this.lens_image_url === undefined) {
                    debug('Cannot find lens image. URL: ' + this.lens_image_url);
                    debug(that);
                    debug(parent_anchor);
                    debug(lens_image_url);
                }
            },
            update_lens_position: function (position) {
                this.lens_image.css({
                    'top': position.top,
                    'left': position.left
                });
            },
            calc_lens_position: function(cursor_position){
                return {
                    left: (cursor_position.center_left * this.ratio.x - this.container.width) * -1,
                    top: (cursor_position.center_top * this.ratio.y - this.container.height) * -1
                }
            },
            lens_event_bind: function () {
                var that = this;
                var mouse_callback = function (mouse) {
                    var position = big_image.calc_view_position(mouse);
                    cursor.update_cursor_position(position.org_x, position.org_y);
                    that.update_lens_position(that.calc_lens_position(cursor.cursor_position, that.ratio, that.container));
                };

                this.parent_anchor.mousemove(mouse_callback);
            },
            lens_event_unbind: function(){
                if(this.parent_anchor !== undefined){
                    this.parent_anchor.unbind('mousemove');
                }
            },
            destroy: function(){
                cursor.destroy();

                if(this.lens_container !== undefined && this.lens_container.length > 0){
                    $('.' + opts.lens_class).remove();
                    this.lens_event_unbind();
                }
            },
            load: function(e){
                var that = this;

                this.lens_container.appendTo(this.parent_div);

                var margin_top = (this.lens_container.height() / 2) - 25,
                    loading_image = $('<img>', {'src': opts.loading_image})
                        .css("margin-top", margin_top);
                this.lens_container.html(loading_image);

                this.lens_image.load(function () {
                    that.lens_container.html(that.lens_image);

                    that.container = {
                        width: that.lens_container.width() / 2,
                        height: that.lens_container.height() / 2
                    };

                    that.img_size = {
                        width: that.lens_image.width(),
                        height: that.lens_image.height()
                    };

                    that.ratio = {
                        y: that.lens_image.height() / big_image.height,
                        x: that.lens_image.width() / big_image.width
                    };

                    var position = big_image.calc_view_position(e);
                    cursor.init(that.parent_anchor, that.lens_container, that.ratio, position);
                    that.update_lens_position(that.calc_lens_position(cursor.cursor_position));

                    that.lens_event_bind();
                }).attr('src', this.lens_image_url);
            }
        };

        var init = function (e) {
            var parent_anchor =  $(this);

            lens.init(parent_anchor);
            lens.load(e);
        };

        var destroy = function () {
            lens.destroy();
        };

        $(this).parents(opts.parent_class).on(opts.open_lens_event, opts.anchor_parent_class, init);
        $(this).parents(opts.parent_class).on('mouseleave', opts.anchor_parent_class, destroy);

    };

    $.fn.simpleLens.ver = function () { return ver; };

    $.fn.simpleLens.defaults = {
        anchor_parent_class: '.simpleLens-lens-image',
        lens_image_attr: 'data-lens-image',
        big_image_class: '.simpleLens-big-image',
        parent_class: '.simpleLens-big-image-container',
        lens_class: 'simpleLens-lens-element',
        cursor_class: 'simpleLens-mouse-cursor',
        loading_image: 'images/loading.gif',
        open_lens_event: 'mouseenter'
    };

})( jQuery );;
var QuickOrder = {
    Initialization: function () {
        QuickOrder.CloseQuickOrderpopup();
        QuickOrder.SetProperties();
        QuickOrder.Validation();
        QuickOrder.ValidationTemplate();
        QuickOrder.ShowHideQuickOrderPopUp();
        QuickOrder.SetQuantity();
        var agent = navigator.userAgent.toLowerCase();
        if (agent.indexOf('ipad') >= 0) {
            QuickOrder.AutocompleteSkuForDevice();
            QuickOrder.AutocompleteTemplateSkuForDevice();
        }
        else {
            QuickOrder.AutocompleteSku();
            QuickOrder.AutocompleteTemplateSku();
        }
        QuickOrder.RemoveValidationMessage();
        Home.bind.menuHandler();
    },
    ShowHideQuickOrderPopUp: function () {
        var ipad = navigator.userAgent.match(/iPad/i) != null;
        if (ipad) {
            $(".quickordercontainer").on('mouseenter touch', function () {
                $(".ui-autocomplete").css('display');
                $(".divQuickOrder").show();
            });
            $(".quickordercontainer").on('mouseleave touch', function () {
                if ((!$(".txtQuickOrderSku").is(":focus")) && (!$(".txtQuickOrderQuantity").is(":focus")) && ($(".txtQuickOrderSku").val() == "")) {
                    $(".divQuickOrder").hide();
                }
            });
        }
        else {
            var mq = window.matchMedia("(min-width: 768px)");
            if (mq.matches) {
                $(".quickordercontainer").on('mouseenter touch', function () {
                    $(".ui-autocomplete").css('display');
                    $(".divQuickOrder").show();
                });
                $(".quickordercontainer").on('mouseleave touch', function () {
                    if ((!$(".txtQuickOrderSku").is(":focus")) && (!$(".txtQuickOrderQuantity").is(":focus")) && ($(".txtQuickOrderSku").val() == "")) {
                        $(".divQuickOrder").hide();
                    }
                });
            }
            else {
                $(".quickordercontainer").on('mouseenter touch', function () {
                    $(".divQuickOrder").hide();
                });
                $(".quickordercontainer").on('mouseleave touch', function () {
                    if ((!$(".txtQuickOrderSku").is(":focus")) && (!$(".txtQuickOrderQuantity").is(":focus")) && ($(".txtQuickOrderSku").val() == "")) {
                        $(".divQuickOrder").hide();
                    }
                });
            }
        }
    },
    Validation: function () {
        $(".quickOrderAddToCart").on("click", function () {
            var quantity = parseFloat($('.txtQuickOrderQuantity').val());
            var track_inventory = $('#hdnQuickOrderTrackInventoryInd').val();
            var back_order = $('#hdnQuickOrderAllowBackOrder').val();

            if ($('.txtQuickOrderSku').val() != $('#hdnQuickOrderSku').val()) {
                $('#inventorymsg').html("Please enter valid sku.");
                return false;
            }

            if (parseInt($('.txtQuickOrderQuantity').val() % 1) != 0 || parseInt($('.txtQuickOrderQuantity').val()) <= 0) {
                $('#inventorymsg').html("Enter Valid Quantity");
                return false;
            }

            if (isNaN($('.txtQuickOrderQuantity').val()) || $('.txtQuickOrderQuantity').val() == "") {
                $('#inventorymsg').html("Enter Whole Number");
                return false;
            }

            if ($('#hdnQuickOrderCallForPricing').val() == "true") {
                $('#inventorymsg').html("Call for pricing");
                return false;
            }

            if ((track_inventory == "true" && back_order == "false")) {
                if (parseFloat($("#hdnQuickOrderQuantityOnHand").val()) <= 0) {
                    $('#inventorymsg').html($('#hdnQuickOrderOutOfStockMessage').val());
                    return false;
                }
            }

            if (parseFloat($('#hdnQuickOrderMaxQty').val()) < quantity + parseFloat($("#hdnQuickOrderCartQuantity").val())) {
                $('#inventorymsg').html('Selected quantity exceeds product maximum given current Shopping Cart quantities.');
                return false;
            }

            if (parseFloat($('#hdnQuickOrderMinQty').val()) > quantity) {
                $('#inventorymsg').html('Selected quantity is less than minimum specified quantity.');
                return false;
            }

            if ((track_inventory == "true" && back_order == "false")) {
                if (parseFloat($('#hdnQuickOrderQuantityOnHand').val()) == parseFloat($("#hdnQuickOrderCartQuantity").val())) {
                    $('#inventorymsg').html($('#hdnQuickOrderOutOfStockMessage').val());
                    return false;
                }
            }

            if ((track_inventory == "true" && back_order == "false")) {
                if (quantity + parseFloat($("#hdnQuickOrderCartQuantity").val()) > parseFloat($('#hdnQuickOrderQuantityOnHand').val())) {
                    $('#inventorymsg').html("Only " + (parseFloat($('#hdnQuickOrderQuantityOnHand').val()) - parseFloat($("#hdnQuickOrderCartQuantity").val())) + " quantities are available for Add to cart/Shipping");
                    return false;
                }
            }

            if (QuickOrder.CheckInventory($('#hdnQuickOrderAddOnQuantityOnHand').val(), quantity + parseFloat($("#hdnQuickOrderCartQuantity").val()))) {
                $('#inventorymsg').html("Add-On is out of stock");
                return false;
            }

            if (QuickOrder.CheckInventoryForBundle($('#hdnQuickOrderBundleQuantityOnHand').val(), quantity, $("#hdnQuickOrderBundleTrackInventoryInd").val(), $("#hdnQuickOrderBundleAllowBackOrder").val())) {
                $('#inventorymsg').html("Bundle product is out of stock");
                return false;
            }

            return true;
        })
    },
    AutocompleteSkuForDevice: function () {
        $(".txtQuickOrderSku").on("keyup", function (e) {
            $("#ui-id-1").show();
            var txt = $(".txtQuickOrderSku").val();
            Api.GetProductListBySKU(txt, function (data) {
                if ($("#ui-id-1").length < 1) {
                    $(".txtQuickOrderSku").addClass("ui-autocomplete-input");
                    $(".txtQuickOrderSku").attr("autocomplete", "off");
                    $("body").append('<ul class="ui-autocomplete ui-autocomplete-ipad-top ui-front scroll-default ui-menu ui-widget ui-widget-content quick-order-autocomplete" id="ui-id-1" tabindex="0" style="display: block; overflow: hidden; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); -webkit-touch-callout: none; outline: none; cursor: -webkit-grab; width: 283px; top: 150px; left: 419.625px;"></ul>');
                } else {
                    $(".ui-autocomplete").addClass("ui-autocomplete-ipad-top");
                }
                $("#ui-id-1").html('');
                var productContaits = "";
                for (var i = 0; i < data.length; i++) {
                    var index = 2 + parseInt(i);
                    var id = "ui-id-" + index;
                    var hdnDetails = QuickOrder.BindHinddenData(data[i], index);
                    if (i == 0) {
                        productContaits = '<li class="ui-menu-item" id=' + id + ' tabindex="-1" onclick="QuickOrder.SelectSku(this);">' + hdnDetails + data[i].AutoCompleteLabel + '</li>';
                    }
                    else {
                        productContaits += '<li class="ui-menu-item" id=' + id + ' tabindex="-1" onclick="QuickOrder.SelectSku(this);">' + hdnDetails + data[i].AutoCompleteLabel + '</li>';
                    }
                }

                $("#ui-id-1").append(productContaits);
                $('.ui-autocomplete').off('menufocus hover mouseover mouseenter');
            });
        });
    },
    BindHinddenData: function (data, index) {
        var details = '<input type="hidden" value="' + data.Sku + '" id="hdnqosku' + index + '" class="hdnqosku">';
        details += '<input type="hidden" value=' + data.ProductId + ' id="hdnqoProductId' + index + '"  class="hdnqoProductId">';
        details += '<input type="hidden" value=' + data.BundleItemIds + ' id="hdnqoBundleItemsIds' + index + '" class="hdnqoBundleItemsIds">';
        details += '<input type="hidden" value="' + data.Price + '" id="hdnqoPrice' + index + '" class="hdnqoPrice">';
        details += '<input type="hidden" value=' + data.AddonValueIds + ' id="hdnqoAddOnValueIds' + index + '" class="hdnqoAddOnValueIds">';
        details += '<input type="hidden" value="' + data.ProductName + '" id="hdnqoProductName' + index + '" class="hdnqoProductName">';
        details += '<input type="hidden" value="' + data.Quantity + '" id="hdnqoQuantity' + index + '" class="hdnqoQuantity">';
        details += '<input type="hidden" value="' + data.QuantityOnHand + '" id="hdnqoQuantityOnHand' + index + '" class="hdnqoQuantityOnHand">';
        details += '<input type="hidden" value="' + data.InventoryMessage + '" id="hdnqoInventoryMessage' + index + '" class="hdnqoInventoryMessage">';
        details += '<input type="hidden" value="' + data.InStockMessage + '" id="hdnqoInStockMessage' + index + '" class="hdnqoInStockMessage">';
        details += '<input type="hidden" value="' + data.OutOfStockMessage + '" id="hdnqoOutOfStockMessage' + index + '" class="hdnqoOutOfStockMessage">';
        details += '<input type="hidden" value="' + data.MinQty + '" id="hdnqoMinQty' + index + '" class="hdnqoMinQty">';
        details += '<input type="hidden" value="' + data.MaxQty + '" id="hdnqoMaxQty' + index + '" class="hdnqoMaxQty">';
        details += '<input type="hidden" value="' + data.CallForPricing + '" id="hdnqoCallForPricing' + index + '" class="hdnqoCallForPricing">';
        details += '<input type="hidden" value="' + data.BundleQuantityOnHand + '" id="hdnqoBundleQuantityOnHand' + index + '" class="hdnqoBundleQuantityOnHand">';
        details += '<input type="hidden" value="' + data.AddOnQuantityOnHand + '" id="hdnqoAddOnQuantityOnHand' + index + '" class="hdnqoAddOnQuantityOnHand">';
        details += '<input type="hidden" value="' + data.AllowBackOrder + '" id="hdnqoAllowBackOrder' + index + '" class="hdnqoAllowBackOrder">';
        details += '<input type="hidden" value="' + data.TrackInventoryInd + '" id="hdnqoTrackInventoryInd' + index + '" class="hdnqoTrackInventoryInd">';
        details += '<input type="hidden" value="' + data.BundleAllowBackOrder + '" id="hdnqoBundleAllowBackOrder' + index + '" class="hdnqoBundleAllowBackOrder">';
        details += '<input type="hidden" value="' + data.BundleTrackInventoryInd + '" id="hdnqoBundleTrackInventoryInd' + index + '" class="hdnqoBundleTrackInventoryInd">';
        details += '<input type="hidden" value="' + data.SeoPageName + '" id="hdnqoOrderSeoPageName' + index + '" class="hdnqoOrderSeoPageName">';
        return details;
    },
    SelectSku: function (obj) {
        var li = obj.id;
        var sku = $("#" + li + " .hdnqosku").val();// $("#" + li + " input").val();
        $('.txtQuickOrderSku').val(sku);
        $("#ui-id-1").hide();
        $('#inventorymsg').html("");
        $('.quickOrderAddToCart').removeAttr('disabled');
        var productId = $("#" + li + " .hdnqoProductId").val();
        var bundleId = $("#" + li + " .hdnqoBundleItemsIds").val();
        if (bundleId == "null") {
            bundleId = null;
        }
        var price = $("#" + li + " .hdnqoPrice").val();
        var addonId = $("#" + li + " .hdnqoAddOnValueIds").val();
        if (addonId == "null") {
            addonId = null;
        }
        var productname = $("#" + li + " .hdnqoProductName").val();
        var qty = $("#" + li + " .hdnqoQuantity").val()
        var qtyonhand = $("#" + li + " .hdnqoQuantityOnHand").val();
        var inventorymsg = $("#" + li + " .hdnqoInventoryMessage").val();
        var instock = $("#" + li + " .hdnqoInStockMessage").val();
        var outofstock = $("#" + li + " .hdnqoOutOfStockMessage").val();
        var minqty = $("#" + li + " .hdnqoMinQty").val();
        var maxqty = $("#" + li + " .hdnqoMaxQty").val();
        var callforprice = $("#" + li + " .hdnqoCallForPricing").val();
        var bundleqty = $("#" + li + " .hdnqoBundleQuantityOnHand").val();
        var addonqty = $("#" + li + " .hdnqoAddOnQuantityOnHand").val();
        var allowbackorder = $("#" + li + " .hdnqoAllowBackOrder").val();
        var trackinv = $("#" + li + " .hdnqoTrackInventoryInd").val();
        var bundleallowbackorder = $("#" + li + " .hdnqoBundleAllowBackOrder").val();
        var bundletrackinventoryind = $("#" + li + " .hdnqoBundleTrackInventoryInd").val();
        var orderseopagename = $("#" + li + " .hdnqoOrderSeoPageName").val();
        if (bundleqty = "null") {
            bundleqty = null;
        }
        if (addonqty = "null") {
            addonqty = null;
        }
        if (bundleallowbackorder = "null") {
            bundleallowbackorder = null;
        }
        if (bundletrackinventoryind = "null") {
            bundletrackinventoryind = null;
        }
        $('#hdnQuickOrderProductId').val(productId);
        $("#hdnQuickOrderBundleItemsIds").val(bundleId);
        $('#hdnQuickOrderPrice').val(price);
        $("#hdnQuickOrderAddOnValueIds").val(addonId);
        $('#hdnQuickOrderSku').val(sku);
        $('#hdnQuickOrderProductName').val(productname);
        $('#hdnQuickOrderCartQuantity').val(qty);
        $('#hdnQuickOrderQuantityOnHand').val(qtyonhand);
        $('#hdnQuickOrderInventoryMessage').val(inventorymsg);
        $('#hdnQuickOrderInStockMessage').val(instock);
        $('#hdnQuickOrderOutOfStockMessage').val(outofstock);
        $('#hdnQuickOrderMinQty').val(minqty);
        $('#hdnQuickOrderMaxQty').val(maxqty);
        $('#hdnQuickOrderCallForPricing').val(callforprice);
        $('#hdnQuickOrderBundleQuantityOnHand').val(bundleqty);
        $('#hdnQuickOrderAddOnQuantityOnHand').val(addonqty);
        $('#hdnQuickOrderAllowBackOrder').val(allowbackorder);
        $('#hdnQuickOrderTrackInventoryInd').val(trackinv);
        $('#hdnQuickOrderBundleAllowBackOrder').val(bundleallowbackorder);
        $('#hdnQuickOrderBundleTrackInventoryInd').val(bundletrackinventoryind);
        $('#hdnQuickOrderSeoPageName').val(orderseopagename);
        $('#inventorymsg').html("");
        $('.quickOrderAddToCart').removeAttr('disabled');
        return false;
    },
    AutocompleteSku: function () {
        $(".txtQuickOrderSku").autocomplete({
            source: function (request, response) {
                try {
                    Api.GetProductListBySKU(request.term, function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.AutoCompleteLabel,
                                value: item.Sku,
                                productId: item.ProductId,
                                price: item.Price,
                                addonValueIds: item.AddonValueIds,
                                bundleItemsIds: item.BundleItemIds,
                                sku: item.Sku,
                                productName: item.ProductName,
                                cartQuantity: item.CartQuantity,
                                quantityOnHand: item.QuantityOnHand,
                                inStockMessage: item.InStockMessage,
                                outOfStockMessage: item.OutOfStockMessage,
                                inventoryMessage: item.InventoryMessage,
                                callForPricing: item.CallForPricing,
                                minQty: item.MinQty,
                                maxQty: item.MaxQty,
                                bundleQuantityOnHand: item.BundleQuantityOnHand,
                                addOnQuantityOnHand: item.AddOnQuantityOnHand,
                                allowBackOrder: item.AllowBackOrder,
                                trackInventoryInd: item.TrackInventoryInd,
                                bundleAllowBackOrder: item.BundleAllowBackOrder,
                                bundleTrackInventoryInd: item.BundleTrackInventoryInd,
                                SeoPageName: item.SeoPageName,
                                UOM: item.UOM,
                                UOMText: item.UOMText
                            }
                        }));
                    });
                } catch (err) {
                }
            },

            select: function (event, ui) {
                $('.txtQuickOrderSku').val(ui.item.sku);
                $('#hdnQuickOrderProductId').val(ui.item.productId);
                $("#hdnQuickOrderBundleItemsIds").val(ui.item.bundleItemsIds);
                $('#hdnQuickOrderPrice').val(ui.item.price);
                $("#hdnQuickOrderAddOnValueIds").val(ui.item.addonValueIds);
                $('#hdnQuickOrderSku').val(ui.item.sku);
                $('#hdnQuickOrderProductName').val(ui.item.productName);
                $('#hdnQuickOrderCartQuantity').val(ui.item.cartQuantity);
                $('#hdnQuickOrderQuantityOnHand').val(ui.item.quantityOnHand);
                $('#hdnQuickOrderInventoryMessage').val(ui.item.inventoryMessage);
                $('#hdnQuickOrderInStockMessage').val(ui.item.inStockMessage);
                $('#hdnQuickOrderOutOfStockMessage').val(ui.item.outOfStockMessage);
                $('#hdnQuickOrderMinQty').val(ui.item.minQty);
                $('#hdnQuickOrderMaxQty').val(ui.item.maxQty);
                $('#hdnQuickOrderCallForPricing').val(ui.item.callForPricing);
                $('#hdnQuickOrderBundleQuantityOnHand').val(ui.item.bundleQuantityOnHand);
                $('#hdnQuickOrderAddOnQuantityOnHand').val(ui.item.addOnQuantityOnHand);
                $('#hdnQuickOrderAllowBackOrder').val(ui.item.allowBackOrder);
                $('#hdnQuickOrderTrackInventoryInd').val(ui.item.trackInventoryInd);
                $('#hdnQuickOrderBundleAllowBackOrder').val(ui.item.bundleAllowBackOrder);
                $('#hdnQuickOrderBundleTrackInventoryInd').val(ui.item.bundleTrackInventoryInd);
                $('#hdnQuickOrderSeoPageName').val(ui.item.SeoPageName);
                $('#inventorymsg').html("");
                $('#hdnQuickOrderUOM').val(ui.item.UOM);
                $('.quickOrderAddToCart').removeAttr('disabled');
                return false;
            },
            open: function () {
                $(this).data("ui-autocomplete").menu.element.addClass("quick-order-autocomplete");
            }
        });
    },
    SetProperties: function () {
        $('.quickOrderAddToCart').attr('disabled', 'disabled');
        $('.quickOrderAddToTemplate').attr('disabled', 'disabled');
        $('#txtQuickOrderQuantity').attr('Value', 1);
        $('#txtTemplateQuickOrderQuantity').attr('Value', 1);
    },
    CloseQuickOrderpopup: function () {
        $('.close-quick-order-popup').bind('click', function () {
            $(".divQuickOrder").hide();
            $('.quickOrderAddToCart').attr('disabled', 'disabled');
            $('.txtQuickOrderSku').val("");
            $('.txtQuickOrderQuantity').val("1");
            $('#inventorymsg').html("");

            $(".divTemplateQuickOrder").hide();
            $('.quickOrderAddToTemplate').attr('disabled', 'disabled');
            $('.txtTemplateQuickOrderQuantity').val("");
            $('.txtTemplateQuickOrderQuantity').val("1");
            $('#templateInventorymsg').html("");
        });
    },
    CheckInventory: function (quantitiesOnHand, quantity) {
        if (quantitiesOnHand != undefined && quantitiesOnHand != null && quantitiesOnHand.length > 0) {
            var quantityArray = quantitiesOnHand.split(',');
            for (var quantityIndex = 0; quantityIndex < quantityArray.length; quantityIndex++) {
                if ((quantityArray[quantityIndex] != "") && (parseInt(quantityArray[quantityIndex]) < quantity)) {
                    return true;
                }
            }
        }
        return false;
    },
    CheckInventoryForBundle: function (quantitiesOnHand, quantity, track_inventory_bundle, allow_back_order) {
        if (quantitiesOnHand != undefined && quantitiesOnHand != null && quantitiesOnHand.length > 0) {
            var quantityArray = quantitiesOnHand.split(',');
            var track_inventory_bundle_array = (track_inventory_bundle != undefined && track_inventory_bundle != null && track_inventory_bundle.length > 0) ? track_inventory_bundle.split(',') : [];
            var allow_back_order_array = (allow_back_order != undefined && allow_back_order != null && allow_back_order.length > 0) ? allow_back_order.split(',') : [];
            for (var quantityIndex = 0; quantityIndex < quantityArray.length; quantityIndex++) {
                if (track_inventory_bundle_array[quantityIndex] == "1" && allow_back_order_array[quantityIndex] == "0") {
                    if ((quantityArray[quantityIndex] != "") && (parseInt(quantityArray[quantityIndex]) < quantity)) {
                        return true;
                    }
                }
            }
        }
        return false;
    },
    RemoveValidationMessage: function () {
        $(".txtQuickOrderSku").on("focusout", function () {
            $('#txtQuickOrderQuantity').val('1');
            $('#inventorymsg').text('');
            if ($(".txtQuickOrderSku").val() == "") {
                $('#inventorymsg').html("");
                $('.quickOrderAddToCart').attr('disabled', 'disabled');
                $('.txtQuickOrderQuantity').val("1");
            }
        });

        $("#txtQuickOrderQuantity").on("focusout", function () { $('#inventorymsg').text(''); });

        $(".txtTemplateQuickOrderSku").on("focusout", function () {
            if ($(".txtTemplateQuickOrderSku").val() == "") {
                $('#templateInventorymsg').html("");
                $('.quickOrderAddToTemplate').attr('disabled', 'disabled');
                $('.txtTemplateQuickOrderQuantity').val("1");
            }
        });
    },

    ValidationTemplate: function () {

        $(".quickOrderAddToTemplate").on("click", function () {
            var quantity = parseFloat($('.txtTemplateQuickOrderQuantity').val());
            var track_inventory = $('#hdnTemplateQuickOrderTrackInventoryInd').val();
            var back_order = $('#hdnTemplateQuickOrderAllowBackOrder').val();
            if ($('.txtTemplateQuickOrderSku').val() != $('#hdnTemplateQuickOrderSku').val()) {
                $('#templateInventorymsg').html("Please enter valid sku.");
                return false;
            }
            if (parseInt($('.txtTemplateQuickOrderQuantity').val() % 1) != 0 || parseInt($('.txtTemplateQuickOrderQuantity').val()) <= 0) {
                $('#templateInventorymsg').html("Enter Valid Quantity");
                return false;
            }
            if (isNaN($('.txtTemplateQuickOrderQuantity').val()) || $('.txtTemplateQuickOrderQuantity').val() == "") {
                $('#templateInventorymsg').html("Enter Whole Number");
                return false;
            }
            if ($('#hdnTemplateQuickOrderCallForPricing').val() == "true") {
                $('#templateInventorymsg').html("Call for pricing");
                return false;
            }
            if ((track_inventory == "true" && back_order == "false")) {
                if (parseFloat($("#hdnTemplateQuickOrderQuantityOnHand").val()) <= 0) {
                    $('#templateInventorymsg').html($('#hdnTemplateQuickOrderOutOfStockMessage').val());
                    return false;
                }
            }
            if (parseFloat($('#hdnTemplateQuickOrderMaxQty').val()) < quantity + parseFloat($("#hdnTemplateQuickOrderCartQuantity").val())) {
                $('#templateInventorymsg').html('Selected quantity exceeds product maximum given current Shopping Cart quantities.');
                return false;
            }
            if (parseFloat($('#hdnTemplateQuickOrderMinQty').val()) > quantity) {
                $('#templateInventorymsg').html('Selected quantity is less than minimum specified quantity.');
                return false;
            }
            if ((track_inventory == "true" && back_order == "false")) {
                if (parseFloat($('#hdnTemplateQuickOrderQuantityOnHand').val()) == parseFloat($("#hdnTemplateQuickOrderCartQuantity").val())) {
                    $('#templateInventorymsg').html($('#hdnTemplateQuickOrderOutOfStockMessage').val());
                    return false;
                }
            }
            if ((track_inventory == "true" && back_order == "false")) {
                if (quantity + parseFloat($("#hdnTemplateQuickOrderCartQuantity").val()) > parseFloat($('#hdnTemplateQuickOrderQuantityOnHand').val())) {
                    $('#templateInventorymsg').html("Only " + (parseFloat($('#hdnTemplateQuickOrderQuantityOnHand').val()) - parseFloat($("#hdnTemplateQuickOrderCartQuantity").val())) + " quantities are available for Add to cart/Shipping");
                    return false;
                }
            }
            if (QuickOrder.CheckInventory($('#hdnTemplateQuickOrderAddOnQuantityOnHand').val(), quantity + parseFloat($("#hdnTemplateQuickOrderCartQuantity").val()))) {
                $('#templateInventorymsg').html("Add-On is out of stock");
                return false;
            }
            if (QuickOrder.CheckInventoryForBundle($('#hdnTemplateQuickOrderBundleQuantityOnHand').val(), quantity, $("#hdnTemplateQuickOrderBundleTrackInventoryInd").val(), $("#hdnTemplateQuickOrderBundleAllowBackOrder").val())) {
                $('#templateInventorymsg').html("Bundle product is out of stock");
                return false;
            }
            QuickOrder.AddToTemplate();
            return true;
        })
    },
    AutocompleteTemplateSku: function () {
        $(".txtTemplateQuickOrderSku").autocomplete({
            source: function (request, response) {
                try {                    
                    Api.GetProductListBySKU(request.term, function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.AutoCompleteLabel,
                                value: item.Sku,
                                productId: item.ProductId,
                                price: item.Price,
                                addonValueIds: item.AddonValueIds,
                                bundleItemsIds: item.BundleItemIds,
                                sku: item.Sku,
                                productName: item.ProductName,
                                cartQuantity: item.CartQuantity,
                                quantityOnHand: item.QuantityOnHand,
                                inStockMessage: item.InStockMessage,
                                outOfStockMessage: item.OutOfStockMessage,
                                inventoryMessage: item.InventoryMessage,
                                callForPricing: item.CallForPricing,
                                minQty: item.MinQty,
                                maxQty: item.MaxQty,
                                bundleQuantityOnHand: item.BundleQuantityOnHand,
                                addOnQuantityOnHand: item.AddOnQuantityOnHand,
                                allowBackOrder: item.AllowBackOrder,
                                trackInventoryInd: item.TrackInventoryInd,
                                bundleAllowBackOrder: item.BundleAllowBackOrder,
                                bundleTrackInventoryInd: item.BundleTrackInventoryInd,
                                SeoPageName: item.SeoPageName,
                                skuId: item.SkuId,
                            }
                        }));
                    });
                } catch (err) {
                }
            },
            select: function (event, ui) {
                $('.txtTemplateQuickOrderSku').val(ui.item.sku);
                $('#hdnTemplateQuickOrderProductId').val(ui.item.productId);
                $("#hdnTemplateQuickOrderBundleItemsIds").val(ui.item.bundleItemsIds);
                $('#hdnTemplateQuickOrderPrice').val(ui.item.price);
                $("#hdnTemplateQuickOrderAddOnValueIds").val(ui.item.addonValueIds);
                $('#hdnTemplateQuickOrderSku').val(ui.item.sku);
                $('#hdnTemplateQuickOrderSkuId').val(ui.item.skuId);
                $('#hdnTemplateQuickOrderProductName').val(ui.item.productName);
                $('#hdnTemplateQuickOrderCartQuantity').val(ui.item.cartQuantity);
                $('#hdnTemplateQuickOrderQuantityOnHand').val(ui.item.quantityOnHand);
                $('#hdnTemplateQuickOrderInventoryMessage').val(ui.item.inventoryMessage);
                $('#hdnTemplateQuickOrderInStockMessage').val(ui.item.inStockMessage);
                $('#hdnTemplateQuickOrderOutOfStockMessage').val(ui.item.outOfStockMessage);
                $('#hdnTemplateQuickOrderMinQty').val(ui.item.minQty);
                $('#hdnTemplateQuickOrderMaxQty').val(ui.item.maxQty);
                $('#hdnTemplateQuickOrderCallForPricing').val(ui.item.callForPricing);
                $('#hdnTemplateQuickOrderBundleQuantityOnHand').val(ui.item.bundleQuantityOnHand);
                $('#hdnTemplateQuickOrderAddOnQuantityOnHand').val(ui.item.addOnQuantityOnHand);
                $('#hdnTemplateQuickOrderAllowBackOrder').val(ui.item.allowBackOrder);
                $('#hdnTemplateQuickOrderTrackInventoryInd').val(ui.item.trackInventoryInd);
                $('#hdnTemplateQuickOrderBundleAllowBackOrder').val(ui.item.bundleAllowBackOrder);
                $('#hdnTemplateQuickOrderBundleTrackInventoryInd').val(ui.item.bundleTrackInventoryInd);
                $('#hdnTemplateQuickOrderSeoPageName').val(ui.item.SeoPageName);
                $('#templateInventorymsg').html("");
                $('.quickOrderAddToTemplate').removeAttr('disabled');
                return false;
            },
            open: function () {
                $(this).data("ui-autocomplete").menu.element.addClass("quick-order-autocomplete");
            }
        });
    },
    AutocompleteTemplateSkuForDevice: function () {
        $(".txtTemplateQuickOrderSku").on("keyup", function (e) {           
            $("#ui-id-1").show();
            var txt = $(".txtTemplateQuickOrderSku").val();
            Api.GetProductListBySKU(txt, function (data) {
                if ($("#ui-id-1").length < 1) {
                    $(".txtTemplateQuickOrderSku").addClass("ui-autocomplete-input");
                    $(".txtTemplateQuickOrderSku").attr("autocomplete", "off");
                    $("body").append('<ul class="ui-autocomplete ui-autocomplete-ipad-template ui-front scroll-default ui-menu ui-widget ui-widget-content quick-order-autocomplete" id="ui-id-1" tabindex="0" style="display: block; overflow: hidden; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); -webkit-touch-callout: none; outline: none; cursor: -webkit-grab; width: 283px; top: 150px; left: 419.625px;"></ul>');
                } else {
                    $(".ui-autocomplete").addClass("ui-autocomplete-ipad-template");
                }
                $("#ui-id-1").html('');
                var productContaits = "";
                for (var i = 0; i < data.length; i++) {
                    var index = 2 + parseInt(i);
                    var id = "ui-id-" + index;
                    var hdnDetails = QuickOrder.BindTemplateHinddenData(data[i], index);
                    if (i == 0) {
                        productContaits = '<li class="ui-menu-item" id=' + id + ' tabindex="-1" onclick="QuickOrder.SelectTemplateSku(this);">' + hdnDetails + data[i].AutoCompleteLabel + '</li>';
                    }
                    else {
                        productContaits += '<li class="ui-menu-item" id=' + id + ' tabindex="-1" onclick="QuickOrder.SelectTemplateSku(this);">' + hdnDetails + data[i].AutoCompleteLabel + '</li>';
                    }
                }

                $("#ui-id-1").append(productContaits);
                $('.ui-autocomplete').off('menufocus hover mouseover mouseenter');
            });
        });
    },
    BindTemplateHinddenData: function (data, index) {
       var details = '<input type="hidden" value="' + data.Sku + '" id="hdnqoTemplatesku' + index + '" class="hdnqoTemplatesku">';
        details += '<input type="hidden" value=' + data.ProductId + ' id="hdnqoTemplateProductId' + index + '"  class="hdnqoTemplateProductId">';
        details += '<input type="hidden" value=' + data.BundleItemIds + ' id="hdnqoTemplateBundleItemsIds' + index + '" class="hdnqoTemplateBundleItemsIds">';
        details += '<input type="hidden" value="' + data.Price + '" id="hdnqoTemplatePrice' + index + '" class="hdnqoTemplatePrice">';
        details += '<input type="hidden" value=' + data.AddonValueIds + ' id="hdnqoTemplateAddOnValueIds' + index + '" class="hdnqoTemplateAddOnValueIds">';
        details += '<input type="hidden" value="' + data.ProductName + '" id="hdnqoTemplateProductName' + index + '" class="hdnqoTemplateProductName">';
        details += '<input type="hidden" value="' + data.Quantity + '" id="hdnqoTemplateQuantity' + index + '" class="hdnqoTemplateQuantity">';
        details += '<input type="hidden" value="' + data.QuantityOnHand + '" id="hdnqoTemplateQuantityOnHand' + index + '" class="hdnqoTemplateQuantityOnHand">';
        details += '<input type="hidden" value="' + data.InventoryMessage + '" id="hdnqoTemplateInventoryMessage' + index + '" class="hdnqoTemplateInventoryMessage">';
        details += '<input type="hidden" value="' + data.InStockMessage + '" id="hdnqoTemplateInStockMessage' + index + '" class="hdnqoTemplateInStockMessage">';
        details += '<input type="hidden" value="' + data.OutOfStockMessage + '" id="hdnqoTemplateOutOfStockMessage' + index + '" class="hdnqoTemplateOutOfStockMessage">';
        details += '<input type="hidden" value="' + data.MinQty + '" id="hdnqoTemplateMinQty' + index + '" class="hdnqoTemplateMinQty">';
        details += '<input type="hidden" value="' + data.MaxQty + '" id="hdnqoTemplateMaxQty' + index + '" class="hdnqoTemplateMaxQty">';
        details += '<input type="hidden" value="' + data.CallForPricing + '" id="hdnqoTemplateCallForPricing' + index + '" class="hdnqoTemplateCallForPricing">';
        details += '<input type="hidden" value="' + data.BundleQuantityOnHand + '" id="hdnqoTemplateBundleQuantityOnHand' + index + '" class="hdnqoTemplateBundleQuantityOnHand">';
        details += '<input type="hidden" value="' + data.AddOnQuantityOnHand + '" id="hdnqoTemplateAddOnQuantityOnHand' + index + '" class="hdnqoTemplateAddOnQuantityOnHand">';
        details += '<input type="hidden" value="' + data.AllowBackOrder + '" id="hdnqoTemplateAllowBackOrder' + index + '" class="hdnqoTemplateAllowBackOrder">';
        details += '<input type="hidden" value="' + data.TrackInventoryInd + '" id="hdnqoTemplateTrackInventoryInd' + index + '" class="hdnqoTemplateTrackInventoryInd">';
        details += '<input type="hidden" value="' + data.BundleAllowBackOrder + '" id="hdnqoTemplateBundleAllowBackOrder' + index + '" class="hdnqoTemplateBundleAllowBackOrder">';
        details += '<input type="hidden" value="' + data.BundleTrackInventoryInd + '" id="hdnqoTemplateBundleTrackInventoryInd' + index + '" class="hdnqoTemplateBundleTrackInventoryInd">';
        details += '<input type="hidden" value="' + data.SeoPageName + '" id="hdnqoTemplateOrderSeoPageName' + index + '" class="hdnqoTemplateOrderSeoPageName">';
        return details;
    },
    SelectTemplateSku: function (obj) {       
        var li = obj.id;
        var sku = $("#" + li + " .hdnqoTemplatesku").val();// $("#" + li + " input").val();      
        $('.txtTemplateQuickOrderSku').val(sku);      
        $("#ui-id-1").hide();
        $('#templateInventorymsg').html("");
        $('.quickOrderAddToTemplate').removeAttr('disabled');
        var productId = $("#" + li + " .hdnqoTemplateProductId").val();
        var bundleId = $("#" + li + " .hdnqoTemplateBundleItemsIds").val();
        if (bundleId == "null") {
            bundleId = null;
        }
        var price = $("#" + li + " .hdnqoTemplatePrice").val();
        var addonId = $("#" + li + " .hdnqoTemplateAddOnValueIds").val();
        if (addonId == "null") {
            addonId = null;
        }
        var productname = $("#" + li + " .hdnqoTemplateProductName").val();
        var skuId = $("#" + li + " .hdnTemplateQuickOrderSkuId").val();
        var qty = $("#" + li + " .hdnqoTemplateQuantity").val()
        var qtyonhand = $("#" + li + " .hdnqoTemplateQuantityOnHand").val();
        var inventorymsg = $("#" + li + " .hdnqoTemplateInventoryMessage").val();
        var instock = $("#" + li + " .hdnqoTemplateInStockMessage").val();
        var outofstock = $("#" + li + " .hdnqoTemplateOutOfStockMessage").val();
        var minqty = $("#" + li + " .hdnqoTemplateMinQty").val();
        var maxqty = $("#" + li + " .hdnqoTemplateMaxQty").val();
        var callforprice = $("#" + li + " .hdnqoTemplateCallForPricing").val();
        var bundleqty = $("#" + li + " .hdnqoTemplateBundleQuantityOnHand").val();
        var addonqty = $("#" + li + " .hdnqoTemplateAddOnQuantityOnHand").val();
        var allowbackorder = $("#" + li + " .hdnqoTemplateAllowBackOrder").val();
        var trackinv = $("#" + li + " .hdnqoTemplateTrackInventoryInd").val();
        var bundleallowbackorder = $("#" + li + " .hdnqoTemplateBundleAllowBackOrder").val();
        var bundletrackinventoryind = $("#" + li + " .hdnqoTemplateBundleTrackInventoryInd").val();
        var orderseopagename = $("#" + li + " .hdnqoTemplateOrderSeoPageName").val();
        if (bundleqty = "null") {
            bundleqty = null;
        }
        if (addonqty = "null") {
            addonqty = null;
        }
        if (bundleallowbackorder = "null") {
            bundleallowbackorder = null;
        }
        if (bundletrackinventoryind = "null") {
            bundletrackinventoryind = null;
        }
        $('#hdnTemplateQuickOrderProductId').val(productId);
        $("#hdnTemplateQuickOrderBundleItemsIds").val(bundleId);
        $('#hdnTemplateQuickOrderPrice').val(price);
        $("#hdnTemplateQuickOrderAddOnValueIds").val(addonId);
        $('#hdnTemplateQuickOrderSku').val(sku);
        $('#hdnTemplateQuickOrderSkuId').val(skuId);
        $('#hdnTemplateQuickOrderProductName').val(productname);
        $('#hdnTemplateQuickOrderCartQuantity').val(qty);
        $('#hdnTemplateQuickOrderQuantityOnHand').val(qtyonhand);
        $('#hdnTemplateQuickOrderInventoryMessage').val(inventorymsg);
        $('#hdnTemplateQuickOrderInStockMessage').val(instock);
        $('#hdnTemplateQuickOrderOutOfStockMessage').val(outofstock);
        $('#hdnTemplateQuickOrderMinQty').val(minqty);
        $('#hdnTemplateQuickOrderMaxQty').val(maxqty);
        $('#hdnTemplateQuickOrderCallForPricing').val(callforprice);
        $('#hdnTemplateQuickOrderBundleQuantityOnHand').val(bundleqty);
        $('#hdnTemplateQuickOrderAddOnQuantityOnHand').val(addonqty);
        $('#hdnTemplateQuickOrderAllowBackOrder').val(allowbackorder);
        $('#hdnTemplateQuickOrderTrackInventoryInd').val(trackinv);
        $('#hdnTemplateQuickOrderBundleAllowBackOrder').val(bundleallowbackorder);
        $('#hdnTemplateQuickOrderBundleTrackInventoryInd').val(bundletrackinventoryind);
        $('#hdnTemplateQuickOrderSeoPageName').val(orderseopagename);
        $('#templateInventorymsg').html("");
        $('.quickOrderAddToTemplate').removeAttr('disabled');
        return false;
    },
    AddToTemplate: function () {
        $(".divTemplateQuickOrder").hide();
        $("#templateView").show();
        $("#SuccessMessage").html("");
        var skuId = $("#hdnTemplateQuickOrderSkuId").val();
        if (QuickOrder.IsDuplicateItem(skuId)) {
            DisplayNotificationMessagesHelper("Product already added to template.", "error", false, 5000);
            return false;
        }
        var product = {
            "ProductId": $("#hdnTemplateQuickOrderProductId").val(),
            "ProductName": $("#hdnTemplateQuickOrderProductName").val(),
            "Sku": $("#hdnTemplateQuickOrderSku").val(),
            "SkuId": $("#hdnTemplateQuickOrderSkuId").val(),
            "AddOnValueIds": $("#hdnTemplateQuickOrderAddOnValueIds").val(),
            "BundleItemsIds": $("#hdnTemplateQuickOrderBundleItemsIds").val(),
            "CartQuantity": $("#hdnTemplateQuickOrderCartQuantity").val(),
            "QuantityOnHand": $("#hdnTemplateQuickOrderQuantityOnHand").val(),
            "InStockMessage": $("#hdnTemplateQuickOrderInStockMessage").val(),
            "OutOfStockMessage": $("#hdnTemplateQuickOrderOutOfStockMessage").val(),
            "InventoryMessage": $("#hdnTemplateQuickOrderInventoryMessage").val(),
            "MinQty": $("#hdnTemplateQuickOrderMinQty").val(),
            "MaxQty": $("#hdnTemplateQuickOrderMaxQty").val(),
            "CallForPricing": $("#hdnTemplateQuickOrderCallForPricing").val(),
            "BundleQuantityOnHand": $("#hdnTemplateQuickOrderBundleQuantityOnHand").val(),
            "AddOnQuantityOnHand": $("#hdnTemplateQuickOrderAddOnQuantityOnHand").val(),
            "AllowBackOrder": $("#hdnTemplateQuickOrderAllowBackOrder").val(),
            "TrackInventoryInd": $("#hdnTemplateQuickOrderTrackInventoryInd").val(),
            "BundleAllowBackOrder": $("#hdnTemplateQuickOrderBundleAllowBackOrder").val(),
            "BundleTrackInventoryInd": $("#hdnTemplateQuickOrderBundleTrackInventoryInd").val(),
            "SeoPageName": $("#hdnTemplateQuickOrderSeoPageName").val(),
            "Quantity": $(".txtTemplateQuickOrderQuantity").val()
        };

        $.ajax({
            url: "/Order/AddTemplate/",
            type: "post",
            dataType: "json",
            data: { "product": product },
            success: function (response) {
                $("#templateViewRow").append(response.data.templateView);
                Order.ShowHideControls();
            },
            error: function (msg) {
                DisplayNotificationMessagesHelper(msg, "error", false, 5000);
            }
        });

    },
    IsDuplicateItem: function (sku) {
        var checkedValues = $('#templateView .templateChk').map(function () {
            return this.value;
        }).get();
        for (i = 0; i < checkedValues.length; i++) {
            if (parseInt(checkedValues[i]) == parseInt(sku)) {
                return true;
            }
        }
        return false;
    },
    SetQuantity: function () {
        $("#txtQuickOrderQuantity").on("focusout", function (ev) {
            var uom = $("#hdnQuickOrderUOM").val();
            if ($(this).val() != "") {
                if (uom != "2" && uom != "4") {
                    $(this).val($(this).val().replace(/[^\d].+/, ""));
                    if ((ev.which < 48 || ev.which > 57)) {
                        $(this).val(parseInt($(this).val()));
                    }
                }
            }
        });
    }
}
;var Order = {
    // INIT	
    init: function () {
        Account.bind.setSelectedTab();
        _debug("order.init()");
        Order.ShowHideControls();
        Order.LoadTemplate();
        Order.GenerateInvoice();
        Order.HideInvoiceButton();
    },
    LoadTemplate: function () {
        $(".show-quickorder-popup").on('click', function () {
            $("#templateChkAll").prop("checked", false);
            Order.ShowQuickOrder();
        });
        $("#btnDeleteTemplateItems").on('click', function () {
            Order.DeleteTemplateItems();
        });
        $("#btnSaveTemplate").on('click', function () {
            Order.SaveTemplate();
        });
    },
    ChechUncheckTemplate: function () {
        if ($("#templateChkAll").is(':checked')) {
            $(".templateChk").prop("checked", true);

        } else {
            $(".templateChk").prop("checked", false);
        }
    },
    SaveTemplate: function () {
        $("#SuccessMessage").html("");
        if ($("#txtTemplateName").val().trim().length < 1) {
            Order.ShowMessage("Please enter template name.");
            return false;
        }
        var templateId = $("#TemplateId").val();
        if (parseInt(templateId) == 0) {
            var outofStockItems = $('#templateView .status-outofstock');
            for (var i = 0; i < outofStockItems.length; i++) {
                var item = outofStockItems[i];
                if (item.innerHTML.length > 0) {
                    Order.ShowMessage("Fail to save template.");
                    return false;
                }
            }
        }
        var checkedValues = $('#templateView .templateChk').map(function () {
            return this.value;
        }).get();
        var items = new Array();
        for (var i = 0; i < checkedValues.length; i++) {
            var item = {
                ProductId: $("#trTemplateItem_" + checkedValues[i] + " .templateProductId").val(),
                Sku: $("#trTemplateItem_" + checkedValues[i] + " .templateSku").val(),
                Quantity: $("#trTemplateItem_" + checkedValues[i] + " .cartQuantity").val(),
                AddOnValueIds: $("#trTemplateItem_" + checkedValues[i] + " .templateAddOnValueIds").val(),
                BundleItemsIds: $("#trTemplateItem_" + checkedValues[i] + " .templateBundleItemsIds").val(),
                ProductName: $("#trTemplateItem_" + checkedValues[i] + " .templateProductName").val()
            }
            items.push(item);
        }
        var template = {
            "TemplateId": templateId,
            "TemplateName": $("#txtTemplateName").val(),
            "Items": items
        };
        $.ajax({
            url: "/Order/SaveTemplate/",
            type: "post",
            dataType: "json",
            data: { "template": template },
            success: function (response) {
                if (response.sucess) {
                    $("#SuccessMessage").append('<div id="status-message" class="alert alert-success text-center">Template saved successfully..</div>');
                    window.location.href = "/Order/Templates";
                }
                else {
                    Order.ShowMessage(response.message);
                }
            },
            error: function (msg) {
                Order.ShowMessage(msg);
            }
        });
    },
    DeleteTemplate: function () {
        $("#SuccessMessage").html("");
        var selectedItems = $("input:checkbox[name=TemplateId]:checked");
        if (selectedItems.length > 0) {
            Order.ShowDeleteConfirm('Confirm Delete?', 'Are you sure, you want to delete this record?');

        }
        else {
            Order.ShowMessage("Please select template to delete.");
            return false;
        }
    },
    DeleteTemplateItems: function () {
        $("#SuccessMessage").html("");
        if ($("#templateView .templateChk:checked").length < 1) {
            Order.ShowMessage("Please select item to delete.");
            return false;
        }
        var selectedItems = $(".templateChk");
        for (var i = 0; i < selectedItems.length; i++) {
            var ctrl = selectedItems[i].id;
            if ($("#" + ctrl).is(':checked')) {
                var id = selectedItems[i].value;
                $('table#templateView tr#trTemplateItem_' + id).remove();
                $("#SuccessMessage").html("");
                $("#SuccessMessage").append('<div id="status-message" class="alert alert-success text-center">Item deleted successfully.</div>');
            }
        }
        Order.ShowHideControls();
    },
    ShowQuickOrder: function () {
        $("#SuccessMessage").html("");
        $(".txtTemplateQuickOrderSku").val("");
        $("#txtTemplateQuickOrderQuantity").val("1");
        $(".divTemplateQuickOrder").show();
        $("#btnTemplateMultipleSku").on('click', function () {
            Order.MultipleSKUHandler();
        });
    },
    ShowHideControls: function () {
        var templateItems = $(".templateChk");
        if (templateItems.length > 0) {
            $(".template-controls").show();
            Order.UpdateTemplateQuantity();
        }
        else {
            $(".template-controls").hide();
        }
    },
    CheckUncheckAll: function () {
        var templateItems = $(".templateChk");
        var checkedValues = $('#templateView .templateChk:checked').map(function () {
            return this.value;
        }).get();
        if (templateItems.length != checkedValues.length) {
            $("#templateChkAll").prop("checked", false);
        }
        else {
            $("#templateChkAll").prop("checked", true);
        }
    },
    ShowMessage: function (msg) {
        $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + msg + '</div>');
    },
    MultipleSKUHandler: function () {
        $(".divTemplateQuickOrder").hide();
        $('#divTemplateMultipleItems').load('/order/QuickOrderPad', function () {
            $(this).dialog({
                title: "Order Template",
                resizable: false,
                modal: true,
                create: function () { $(this).closest(".ui-dialog").addClass("ui-md-popup"); }
            });
        });
    },
    ManageTemplateGridHeader: function () {
        $("#grid .grid-header").find("th").each(function () {
            var txt = $(this).text();
            if ($.trim(txt) === "Select") {
                $(this).html('<div class="grid-checkbox-all styled-input"><input type="checkbox" id="chktemplates" name="chktemplates" class="chktemplates" onclick="Order.ToggleTemplates()" /><label for="chktemplates"></label></div>');
            }
        });
        $("input:checkbox[name=TemplateId]").on("click", function () {
            Order.CheckUncheckTemplates();
        });
        if (useraccounttypename.toLowerCase() == "manager" || useraccounttypename.toLowerCase() == "user") {
            $("#Dynamic_Grid #grid thead tr").find('th:eq(0)').hide();
            $("#Dynamic_Grid #grid tbody tr").find('td:eq(0)').each(function () {
                $(this).hide();
                if ($(this).html() != undefined && $(this).html().trim() == "") {
                    $(this).parent().find('.zf-Enable').hide();
                }

            });
            $("#Dynamic_Grid #grid thead tr").find('th:eq(5)').hide();
            $("#Dynamic_Grid #grid tbody tr").find('td:eq(5)').each(function () {
                $(this).hide();
                if ($(this).html() != undefined && $(this).html().trim() == "") {
                    $(this).parent().find('.zf-Enable').hide();
                }

            });
        }
        if ($("#Dynamic_Grid #grid thead tr").length > 0) {
            $("#btnDeleteTemplate").show();
        }
        else {
            $("#btnDeleteTemplate").hide();
        }
    },

    OrderListGridHeader: function () {
        $("#grid .grid-header").find("th").each(function () {
            var txt = $(this).text().trim();
            if ($.trim(txt) === "Select") {
                $(this).html('<div class="grid-checkbox-all styled-input"><input type="checkbox" id="chkorders" name="chkorders" class="chkorders" onclick="Order.ToggleOrders()" /><label for="chkorders"></label></div>');
            }
        });
        $("input:checkbox[name=OrderId]").on("click", function () {
            Order.CheckUncheckOrders();
        });
        if (useraccounttypename.toLowerCase() != "manager" && useraccounttypename.toLowerCase() != "admin") {
            $("#Dynamic_Grid #grid thead tr").find('th:eq(0)').hide();
            $("#Dynamic_Grid #grid tbody tr").find('td:eq(0)').each(function () {
                $(this).hide();
                if ($(this).html() != undefined && $(this).html().trim() == "") {
                    $(this).parent().find('.zf-Enable').hide();
                }
            });
            if ($("#Dynamic_Grid #grid > tbody > tr").length < 1) {
                $("#btnGenerateInvoice").hide();
            }
        }

        if (usertypeid.toLowerCase() != "1" && usertypeid.toLowerCase() != "2") {
            var filter = $("#layout-account-orderhistory #filterComponent .product-group");
            var userDiv = filter[1];
            userDiv.id = "dvUserName";
            $("#dvUserName").hide();

            $("#Dynamic_Grid #grid thead tr").find('th:eq(2)').hide();
            $("#Dynamic_Grid #grid tbody tr").find('td:eq(2)').each(function () {
                $(this).hide();
            });
        }
    },
    ToggleTemplates: function () {
        $("input:checkbox[name=TemplateId]").prop("checked", $("#chktemplates").is(':checked'));
        Order.ToggleDeleteTemplate();
    },
    CheckUncheckTemplates: function () {
        var templateItems = $("input:checkbox[name=TemplateId]");
        var checkedValues = $('input:checkbox[name=TemplateId]:checked').map(function () {
            return this.value;
        }).get();
        if (templateItems.length != checkedValues.length) {
            $("#chktemplates").prop("checked", false);
        }
        else {
            $("#chktemplates").prop("checked", true);
        }
        Order.ToggleDeleteTemplate();
    },
    ShowDeleteConfirm: function (title, message) {
        var toggleMessage, toggleTitle, RefreshLocationOndelete = false;
        if ($("BODY").find("div#popup_container").length == 0) {
            CreatePopUp(title);
        }

        $("#popup_title").html(title);
        if (toggleMessage === undefined || toggleMessage === '') {
            $("#popup_message").html(message);
        }
        else {
            $("#popup_message").html(toggleMessage);
        }

        $("#popup_container").dialog({
            resizable: true,
            title: title,
            modal: true,
            stack: true,
            width: 400,
            buttons: {
                "OK": function () {
                    $(this).dialog("close");
                    var arrIds = $('input:checkbox[name=TemplateId]:checked').map(function () {
                        var id = this.id;
                        var index = id.indexOf('_');
                        return id.substring(index + 1);
                    }).get();

                    $.ajax({
                        url: "/Order/DeleteTemplate/",
                        type: "post",
                        dataType: "json",
                        data: { "templateIds": arrIds },
                        success: function (response) {
                            if (response.sucess) {
                                Order.ShowMessage("Template deleted successfully..");
                                window.location.href = "/Order/Templates";
                            }
                            else {
                                Order.ShowMessage(response.message);
                            }
                        },
                        error: function (msg) {
                            Order.ShowMessage(msg);
                        }
                    });
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    },
    UpdateTemplateQuantity: function () {
        $("#layout-add-template .template-item-quantity .cartQuantity").on("blur", function (ev) {
            var selectedQty = $(this).val();
            var productid = $(this).attr("data-cart-productid")
            if (selectedQty.split(".")[1] != undefined) {
                var validQty = selectedQty.split(".")[1].length;
                if (!validQty) {
                    $(this).val('');
                    $("#quantity_error_msg_" + productid).text('Please enter valid quantity');
                    $("#checkOut-link").attr('href', 'javascript:void(0);');
                    return false;
                }
            }

            $("#quantity_error_msg_" + productid).text('');

            var matches = selectedQty.match(/^-?[\d.]+(?:e-?\d+)?$/);
            if (matches == null) {
                $(this).val('');
                $("#quantity_error_msg_" + productid).text('Please enter numeric value');
                $("#checkOut-link").attr('href', 'javascript:void(0);');
                return false;
            }
            else {
                $("#checkOut-link").attr('href', '/Checkout');
            }

            if (parseFloat(selectedQty) < parseFloat($(this).attr("data-product-minqty"))) {
                $("#quantity_error_msg_" + productid).text()
                $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                $("#checkOut-link").attr('href', 'javascript:void(0);');
                return false;
            }

            if (parseFloat(selectedQty) > parseFloat($(this).attr("data-product-maxqty"))) {
                $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                $("#checkOut-link").attr('href', 'javascript:void(0);');
                return false;
            }
            if ($(this).attr("data-cart-uom") != "2" && $(this).attr("data-cart-uom") != "4") {
                $(this).val(selectedQty.replace(/[^\d].+/, ""));
                if ((ev.which < 48 || ev.which > 57)) {
                    $(this).val(parseInt(selectedQty));
                }
            }

            var attributeId = "";
            var selectedIds = "";
            var quantity = parseFloat(selectedQty);
            var selectedAddOnIds = $(this).closest("tr").find(".templateAddOnValueIds").val();
            var skuval = $(this).closest("tr").find(".templateSku").val();
            var skuid = $(this).closest("tr").find(".templateSkuId").val();
            var productId = productid;
            var params = "attributeId=" + attributeId + "&selectedIds=" + selectedIds + "&quantity=" + quantity + "&selectedAddOnIds=" + selectedAddOnIds + "&isTemplateItem=true";
            $(this).val(parseFloat($(this).val()));
            Api.getProductAttributes(parseInt(productId), params, function (response) {
                if (response.success) {
                    $("#dynamic_templateinventory_" + productId).hide();
                    $("#dynamic_templateinventory_" + productId).html("");
                    $("#SuccessMessage").html("");
                    $("#SuccessMessage").append('<div id="status-message" class="alert alert-success text-center">Quantity updated successfully..</div>');
                }
                else {
                    $("#dynamic_templateinventory_" + productId).show();
                    $("#dynamic_templateinventory_" + productId).html(response.message);
                }

                $("#trTemplateItem_" + skuid + " .template-item-total").text(response.data.price);
                $("#templateinventoryMessage" + productId).hide();
                $("#templateinventoryMessage" + productId).html("");
            });
        });
    },
    ToggleDeleteTemplate: function () {
        var checkedValues = $('input:checkbox[name=TemplateId]:checked').map(function () {
            return this.value;
        }).get();
        if (checkedValues.length > 0) {
            $('#btnDeleteTemplate').removeAttr('disabled');
            $('#btnDeleteTemplate').removeClass().addClass("btn-text red");
        }
        else {
            $('#btnDeleteTemplate').attr('disabled', 'disabled');
            $('#btnDeleteTemplate').removeClass().addClass("btn-text grey");
        }
    },
    CheckUncheckOrders: function () {
        var orderItems = $("input:checkbox[name=OrderId]");
        var checkedValues = $('input:checkbox[name=OrderId]:checked').map(function () {
            return this.value;
        }).get();
        if (orderItems.length != checkedValues.length) {
            $("#chkorders").prop("checked", false);
        }
        else {
            $("#chkorders").prop("checked", true);
        }
    },
    ToggleOrders: function () {
        $("input:checkbox[name=OrderId]").prop("checked", $("#chkorders").is(':checked'));
    },
    GenerateInvoice: function () {
        $("#btnGenerateInvoice").on('click', function () {
            var arrIds = $('input:checkbox[name=OrderId]:checked').map(function () {
                var id = this.id;
                var index = id.indexOf('_');
                return id.substring(index + 1);
            }).get().join(",");

            if (arrIds != "") {
                $("#orderIds").val(arrIds);
                return true;
            }
            else {
                $("#SuccessMessage").html("");
                Order.ShowMessage("At least one order should be selected.");
                return false;
            }
        });
    },
    HideInvoiceButton: function () {
        if ($("#grid").length == 0) {
            $("#divInvoice").hide();
        }
    }
}
;var Quote = {
    // INIT	
    init: function () {
        Account.bind.setSelectedTab();
        _debug("quote.init()");
        Quote.updateQuoteShipTo();
        Quote.HideQuoteStatusButton();
    },
    LoadQuote: function () {
        Account.bind.setSelectedTab();
        $("#btnProcessQuote").on('click', function () {

            var cartItemcount = $("#cartitemcount").val();
            var msg = quoteConfirm.replace('{0}', cartItemcount);
            if (parseInt(cartItemcount) > 0) {
                Quote.ShowQuoteConfirm('Confirm Quote?', msg);
            }
            else {
                Quote.ProcessQuote("", "checkout");
            }
        });
        $("#btnBottomProcessQuote").on('click', function () {
            var cartItemcount = $("#cartitemcount").val();
            var msg = quoteConfirm.replace('{0}', cartItemcount);
            if (parseInt(cartItemcount) > 0) {
                Quote.ShowQuoteConfirm('Confirm Quote?', msg);
            }
            else {
                Quote.ProcessQuote("", "checkout");
            }
        });

        $('#quoteView').on('click', '.btnRemover', function (e) {
            e.preventDefault();
            var removeQuoteItemId = $(this).closest("tr").find('.quoteorderlineid').text();
            Quote.ProcessQuote(removeQuoteItemId, "remove");
        });

        $('#quoteView').on('change', '.quoteQuantity', function () {
            var removeQuoteItemId = $(this).closest("tr").find('.quoteorderlineid').text();
            var quoteQuantity = $(this).closest("tr").find('.quoteQuantity option:selected').val();
            Quote.ProcessQuote(removeQuoteItemId, "updatequantity", quoteQuantity);
        });

        $("#btnReview").on('click', function () {
            $("#QuoteStateId").val('80');
        });

        $("#btnApprove").on('click', function () {
            $("#QuoteStateId").val('60');
        });

        $("#btnReject").on('click', function () {
            $("#QuoteStateId").val('70');
        });

        $("#btnBottomReview").on('click', function () {
            $("#QuoteStateId").val('80');
        });

        $("#btnBottomApprove").on('click', function () {
            $("#QuoteStateId").val('60');
        });

        $("#btnBottomReject").on('click', function () {
            $("#QuoteStateId").val('70');
        });

        Quote.OutOfStock();
    },
    ShowQuoteConfirm: function (title, message, quoteOrderLineItemId) {
        var toggleMessage, toggleTitle, RefreshLocationOndelete = false;
        if ($("BODY").find("div#popup_container").length == 0) {
            CreatePopUp(title);
        }

        $("#popup_title").html(title);
        if (toggleMessage === undefined || toggleMessage === '') {
            $("#popup_message").html(message);
        }
        else {
            $("#popup_message").html(toggleMessage);
        }

        $("#popup_container").dialog({
            resizable: true,
            title: title,
            modal: true,
            stack: true,
            create: function () {
                $(this).closest('.ui-dialog').addClass('ui-sm-popup');
            },
            buttons: {
                "OK": function () {
                    $(this).dialog("close");
                    var arrIds = $('input:checkbox[name=TemplateId]:checked').map(function () {
                        var id = this.id;
                        var index = id.indexOf('_');
                        return id.substring(index + 1);
                    }).get();
                    if ($("#QuoteStateId").val().trim() == "90" && typeof quoteOrderLineItemId != "undefined") {
                        Quote.ProcessQuote(quoteOrderLineItemId, "remove", "", true);
                    }
                    else {
                        Quote.ProcessQuote("", "checkout");
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    },
    ProcessQuote: function (quoteItemId, process, quantity, deletedraft) {

        var quoteItems = $('#quoteViewRow .quoteProductId');
        var items = new Array();
        var quoteQuantity = "0";
        var inStock = false;

        if (process == "updatequantity") {
            $('#quoteView tr').each(function (i, row) {
                if (i != 0) {
                    var $row = $(row);

                    var quantityoutofstock = $row.find('.status-outofstock').text().trim();
                    if (quantityoutofstock != "") {
                        $("#btnProcessQuote").addClass("grey");
                        $("#btnBottomProcessQuote").addClass("grey");
                        $("#btnProcessQuote").prop('disabled', true);
                        $("#btnBottomProcessQuote").prop('disabled', true);
                        if ($('#btnApprove').is(':visible') || $('#btnBottomApprove').is(':visible')) {

                            $("#btnApprove").addClass("grey");
                            $("#btnBottomApprove").addClass("grey");

                            $("#btnApprove").prop('disabled', true);
                            $("#btnBottomApprove").prop('disabled', true);
                        }

                        quantity = "1";
                        inStock = true;
                    }
                }
            });
        }
        var quoteOrderLineItemId = quoteItemId != "" && typeof quoteItemId != 'undefined' ? quoteItemId : 0;
        var userType = $("#AccountTypeName").val();
        if (quoteOrderLineItemId == 0 && process == "checkout") {

            var itemQuantity = 0;
            var lineIds = "";
            $('#quoteView tr').each(function (i, row) {
                var $row = $(row);
                lineIds = "," + $row.find('.quoteorderlineid').text().trim() + lineIds;
            });

            $('#quoteView tr').each(function (i, row) {

                if (i != 0) {
                    var $row = $(row);
                    if (userType == "Admin" || userType == "Manager" || (userType == "User" && $("#QuoteStateId").val().trim() == "70") || (userType == "User" && $("#QuoteStateId").val().trim() == "90")) {
                        itemQuantity = parseFloat($row.find('.cartQuantity').val().trim());
                    } else if (userType == "User") {
                        itemQuantity = $row.find('span').text().trim()
                    }

                    var item = {
                        ProductId: $row.find('.productid').text().trim(),
                        Sku: $row.find('.sku').text().trim(),
                        Quantity: itemQuantity,
                        AddOnValueIds: $row.find('.addonvalueids').text().trim(),
                        BundleItemsIds: $row.find('.bundleitemsids').text().trim()
                    }
                    items.push(item);
                }
            });
        }
        else if (process == "updatequantity") {
            quoteQuantity = quantity != "" && typeof quantity != 'undefined' ? quantity : 1;

            $('#quoteView tr').each(function (i, row) {

                if (i != 0) {
                    var $row = $(row);

                    var selectedQty = $row.find('.cartQuantity').val();
                    if ($row.find('.cartQuantity').attr("data-cart-uom") != "2" && $row.find('.cartQuantity').attr("data-cart-uom") != "4") {
                        $row.find('.cartQuantity').val(selectedQty.replace(/[^\d].+/, ""));
                        selectedQty = parseInt(selectedQty);
                    }
                    else {
                        selectedQty = parseFloat(selectedQty);
                    }

                    var item = {
                        ProductId: $row.find('.productid').text().trim(),
                        Sku: $row.find('.sku').text().trim(),
                        Quantity: inStock ? quoteQuantity : selectedQty,
                        AddOnValueIds: $row.find('.addonvalueids').text().trim(),
                        BundleItemsIds: $row.find('.bundleitemsids').text().trim()
                    }
                    items.push(item);
                }
            });
        }
        else if (process == "remove" || deletedraft) {
            var rowCount = $('#quoteView tr').not(':first').length;
            if (rowCount == 1 && (deletedraft == "" || typeof deletedraft == "undefined")) {
                if ($("#QuoteStateId").val().trim() == "90") {
                    Quote.ShowQuoteConfirm("Warning", "If you delete the product from draft then draft will be discard.", quoteOrderLineItemId);
                    return false;
                }
                else {
                    $("#SuccessMessage").html("");
                    $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">Unable to delete. At least one product should remain in the Quote.</div>');
                    return false;
                }
            }
            else {
                $('#quoteView tr').each(function (i, row) {
                    var $row = $(row);
                    if (i != 0) {
                        if (quoteItemId != $row.find('.quoteorderlineid').text().trim() || deletedraft) {

                            var itemQuantity = 0;
                            if (userType == "Admin" || userType == "Manager" || (userType == "User" && $("#QuoteStateId").val().trim() == "70") || (userType == "User" && $("#QuoteStateId").val().trim() == "90")) {
                                itemQuantity = parseFloat($row.find('.cartQuantity').val().trim());
                            } else if (userType == "User") {
                                itemQuantity = $row.find('span').text().trim()
                            }
                            var item = {
                                ProductId: $row.find('.productid').text().trim(),
                                Sku: $row.find('.sku').text().trim(),
                                Quantity: parseFloat(itemQuantity),
                                AddOnValueIds: $row.find('.addonvalueids').text().trim(),
                                BundleItemsIds: $row.find('.bundleitemsids').text().trim()
                            }
                            items.push(item);
                        }
                    }
                });
            }
        }

        var addressURL = quoteOrderLineItemId == 0 && process == "checkout" ? "/Quote/ProcessQuote/" : "/Quote/DeleteUpdateQuote/";

        var quote = {
            "QuoteId": $("#QuoteId").val().trim(),
            "QuoteStateId": $("#QuoteStateId").val().trim(),
            "QuoteItemLineId": quoteOrderLineItemId,
            "QuoteQuantity": quoteQuantity,
            "ShippingId": $("#ShippingId").val().trim(),
            "Items": items,
            "QuoteLineIds": lineIds != "" && typeof lineIds != "undefined" ? lineIds.replace(/^,|,$/g, '') : "",
            "IsInStock": inStock
        };
        $.ajax({
            url: addressURL,
            type: "post",
            dataType: "json",
            data: { "quote": quote },
            async: false,
            success: function (response) {

                if (response.isdeletedraft == true) {
                    window.location = "/Quote/History";
                }
                if (response.sucess) {

                    if (response.sucessmessage != "" && typeof response.sucessmessage != 'undefined') {
                        window.location = window.location.href;

                    } else if (response.errormessage != "" && typeof response.errormessage != 'undefined') {

                        window.location = window.location.href;
                    }
                    else {
                        window.location = "/checkout/index";
                    }
                }
                else {
                    if (typeof response.message != "undefined" && response.message != "" && response.message != null) {
                        Quote.ShowMessage(response.message);
                    }
                }
            },
            error: function (msg) {
                Quote.ShowMessage(msg);
            }
        });
    },
    ShowMessage: function (msg) {
        $("#SuccessMessage").append('<div id="status-message" class="alert alert-danger text-center">' + msg + '</div>');
    },
    ManageQuoteGridHeader: function () {
        if (isUser.toLocaleLowerCase() == "false") {
            $("#grid .grid-header").find("th").each(function () {
                var txt = $(this).text().trim();
                if ($.trim(txt) === "Select") {
                    $(this).html('<div class="grid-checkbox-all styled-input"><input type="checkbox" id="chkquotes" name="chkquotes" class="chkquotes" onclick="Quote.ToggleQuotes()" /><label for="chkquotes"></label></div>');
                }
            });
        }
        $("input:checkbox[name=QuoteId]").on("click", function () {
            Quote.CheckUncheckQuotes();
        });
        if (isUser.toLocaleLowerCase() == "true") {
            $("#Dynamic_Grid #grid thead tr").find('th:eq(0)').hide();
            $("#Dynamic_Grid #grid tbody tr").find('td:eq(0)').each(function () {
                $(this).hide();
                if ($(this).html() != undefined && $(this).html().trim() == "") {
                    $(this).parent().find('.zf-Enable').hide();
                }

            });
            $("#Dynamic_Grid #grid thead tr").find('th:eq(2)').hide();
            $("#Dynamic_Grid #grid tbody tr").find('td:eq(2)').each(function () {
                $(this).hide();
                if ($(this).html() != undefined && $(this).html().trim() == "") {
                    $(this).parent().find('.zf-Enable').hide();
                }

            });
            var filter = $("#layout-account-quotehistory #filterComponent .product-group");
            var userDiv = filter[1];
            userDiv.id = "dvUserName";
            $("#dvUserName").hide();
        }
    },
    LoadQuoteHistory: function () {
        if ($("#layout-account-quotehistory #Dynamic_Grid #grid > tbody > tr").length > 0) {
            $("#btnUpdateStatus").show();
        }
        else {
            $("#btnUpdateStatus").hide();
        }

        $("#btnUpdateStatus").on('click', function () {
            $("#SuccessMessage").html("");
            var orderState = $("#OrderState").val();

            var exceptDraftIDs = new Array();
            var exceptOrderIDs = new Array();

            $('#grid tr').each(function (i, row) {
                var $row = $(row);

                if (i >= 1) {

                    var id = $row.find("td").eq(1).find('a').html();
                    var state = $row.find("td").eq(5).html();

                    if (state == "DRAFT" && state != typeof 'undefined' && state != "") {
                        exceptDraftIDs.push(id);
                    }
                    else if (state == "ORDERED" && state != typeof 'undefined' && state != "") {
                        exceptOrderIDs.push(id);
                    }

                }
            });

            var arrIds = new Array();

            var checkedIds = $('input:checkbox[name=QuoteId]:checked').map(function () {
                var id = this.id;
                var index = id.indexOf('_');
                return id.substring(index + 1);
            }).get();


            arrIds = Quote.RemoveQuoteIds(exceptDraftIDs, checkedIds);
            arrIds = Quote.RemoveQuoteIds(exceptOrderIDs, checkedIds);


            var resultarray = arrIds.join();

            if (resultarray != "") {
                if (orderState < 0 || orderState == "") {
                    Quote.ShowMessage("Please select quote status.");
                    return false;
                }

                $("#QuoteIds").val(resultarray);
                $("#QuoteStateId").val(orderState);
                return true;

            }
            else {
                if (orderState > 0 && (exceptDraftIDs.length > 0 || exceptOrderIDs > 0)) {
                    Quote.ShowMessage("Draft or Ordered quote status can not be change.");
                } else {
                    Quote.ShowMessage("At least one quote should be selected.");
                }
                return false;
            }
        });

    },
    ToggleQuotes: function () {
        $("input:checkbox[name=QuoteId]").prop("checked", $("#chkquotes").is(':checked'));
    },
    CheckUncheckQuotes: function () {
        var templateItems = $("input:checkbox[name=QuoteId]");
        var checkedValues = $('input:checkbox[name=QuoteId]:checked').map(function () {
            return this.value;
        }).get();
        if (templateItems.length != checkedValues.length) {
            $("#chkquotes").prop("checked", false);
        }
        else {
            $("#chkquotes").prop("checked", true);
        }
    },
    OutOfStock: function () {
        var stockstatus = true;
        var itemQuantity = 1;
        var userType = $("#AccountTypeName").val();
        $('#quoteView tr').each(function (i, row) {
            if (i != 0) {
                var $row = $(row);
                if (userType == "Admin" || userType == "Manager" || (userType == "User" && $("#QuoteStateId").val().trim() == "70") || (userType == "User" && $("#QuoteStateId").val().trim() == "90")) {
                    itemQuantity = parseFloat($row.find('.cartQuantity').val().trim());
                } else if (userType == "User") {
                    itemQuantity = $row.find('span').text().trim()
                }
                var quantityoutofstock = $row.find('.status-outofstock').text().trim();
                if (quantityoutofstock != "" && itemQuantity != 1) {
                    $("#btnProcessQuote").addClass("grey");
                    $("#btnBottomProcessQuote").addClass("grey");
                    $("#btnProcessQuote").prop('disabled', true);
                    $("#btnBottomProcessQuote").prop('disabled', true);
                    if ($('#btnApprove').is(':visible') || $('#btnBottomApprove').is(':visible')) {

                        $("#btnApprove").addClass("grey");
                        $("#btnBottomApprove").addClass("grey");

                        $("#btnApprove").prop('disabled', true);
                        $("#btnBottomApprove").prop('disabled', true);
                    }

                    var removeQuoteItemId = $row.find('.quoteorderlineid').text();

                    Quote.ProcessQuote(removeQuoteItemId, "updatequantity", 1);
                    
                }
            }
        });

        return stockstatus;
    },
    updateQuoteShipTo: function () {
        $("#layout-quote-details .quote-item-quantity .cartQuantity").on("blur", function (ev) {
            var quoteQuantity = "";
            var selectedQty = $(this).val();
            var productid = $(this).attr("data-cart-productid")
            if (selectedQty.split(".")[1] != undefined) {
                var validQty = selectedQty.split(".")[1].length;
                if (!validQty) {
                    $(this).val('');
                    $("#quantity_error_msg_" + productid).text('Please enter valid quantity');
                    $("#checkOut-link").attr('href', 'javascript:void(0);');
                    return false;
                }
            }

            $("#quantity_error_msg_" + productid).text('');

            var matches = selectedQty.match(/^-?[\d.]+(?:e-?\d+)?$/);
            if (matches == null) {
                $(this).val('');
                $("#quantity_error_msg_" + productid).text('Please enter numeric value');
                $("#checkOut-link").attr('href', 'javascript:void(0);');
                return false;
            }
            else {
                $("#checkOut-link").attr('href', '/Checkout');
            }

            if (parseFloat(selectedQty) < parseFloat($(this).attr("data-product-minqty"))) {
                $("#quantity_error_msg_" + productid).text()
                $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                $("#checkOut-link").attr('href', 'javascript:void(0);');
                return false;
            }

            if (parseFloat(selectedQty) > parseFloat($(this).attr("data-product-maxqty"))) {
                $("#quantity_error_msg_" + productid).text("Selected quantity should be in between " + parseFloat($(this).attr("data-product-minqty")) + " to " + parseFloat($(this).attr("data-product-maxqty")) + "");
                $("#checkOut-link").attr('href', 'javascript:void(0);');
                return false;
            }
            if ($(this).attr("data-cart-uom") != "2" && $(this).attr("data-cart-uom") != "4") {
                $(this).val(selectedQty.replace(/[^\d].+/, ""));
                if ((ev.which < 48 || ev.which > 57)) {
                    $(this).val(parseInt(selectedQty));
                    quoteQuantity = parseInt(selectedQty);
                }
            }
            else {
                quoteQuantity = parseFloat(selectedQty);
            }

            var removeQuoteItemId = $(this).closest("tr").find('.quoteorderlineid').text();

            Quote.ProcessQuote(removeQuoteItemId, "updatequantity", quoteQuantity);
        });
    },
    HideQuoteStatusButton: function () {
        if ($("#grid").length == 0) {
            $("#dicQuoteStatus").hide();
        }
    },
    RemoveQuoteIds: function (exceptIDs, checkedIds) {

        $.each(exceptIDs, function (key, approvevalue) {

            $.each(checkedIds, function (key, value) {
                if (approvevalue == value) {
                    checkedIds.splice($.inArray(approvevalue, checkedIds), 1);
                }
            });
        });
        return checkedIds;
    },
    ViewQuoteOrderLink: function () {
        $('#grid tr').each(function (i, row) {
            var $row = $(row);

            if (i >= 1) {
                var id = $row.find("td").eq(1).find('a').html();
                var state = $row.find("td").eq(5).html();
                if (state == "ORDERED" && state != typeof 'undefined' && state != "") {
                    $row.find("td").eq(6).find('a').attr("href", "/Account/OrderReceipt/" + id + "");
                    $row.find("td").eq(1).find('a').attr("href", "/Account/OrderReceipt/" + id + "");
                }
            }
        });
    }
};
var CaseRequest = {
    init: function () {
        CaseRequest.ValidationForContactUsForm();
        CaseRequest.ValidationForCustomerFeedbackForm();
    },
    ValidationForContactUsForm: function () {
        $("#contact-us").on("click", function () {
            var flag = true;
            var firstName = $("#valFirstName").val();
            if (firstName.length < 1) {
                $("#valFirstNameErr").html("First name is required.");
                flag = false;
            }
            else {
                $("#valFirstNameErr").html("");
            }

            var lastName = $("#valLastName").val();
            if (lastName.length < 1) {
                $("#valLastNameErr").html("Last name is required.");
                flag = false;
            }
            else {
                $("#valLastNameErr").html("");
            }

            var phoneNum = $("#valPhoneNum").val();
            var regexPhoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
            if(!(phoneNum.match(regexPhoneNum)) &&(!phoneNum.length<1))
            {
                $("#valPhoneNumErr").html("Enter valid phone number.");
                flag = false;
            }
            else {
                $("#valPhoneNumErr").html("");
            }

            var email = $("#valEmail").val();
            if (email.length < 1) {
                $("#valEmailErr").html("Email ID is required.");
                flag = false;
            }
            else {
                $("#valEmailErr").html("");
                var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                if (!regex.test(email)) {
                    $("#valEmailErr").html("Enter valid email address");
                    flag = false;
                }
            }
            if (flag)
                return true;
            else
                return false;
        });
    },

    ValidationForCustomerFeedbackForm: function () {
        $("#customer-feedback").on("click", function () {
            var flag = true;
            var email = $("#valEmailAddress").val();
            if (email.length < 1) {
                $("#valEmailAddressErr").html("Email ID is required.");
                flag = false;
            }
            else {
                $("#valEmailAddressErr").html("");
                var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                if (!regex.test(email)) {
                    $("#valEmailAddressErr").html("Enter valid Email ID");
                    flag = false;
                }
            }
            if (flag)
                return true;
            else
                return false;
        });
    }
}
;

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

    var version = '2.8.1',

    Modernizr = {},

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

    docElement = document.documentElement,

   
    mod = 'modernizr',
    modElem = document.createElement(mod),
    mStyle = modElem.style,

   
    inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/,

   
    smile = ':)',
  

    toString = {}.toString,

  
    prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
   
    omPrefixes = 'Webkit Moz O ms',

    cssomPrefixes = omPrefixes.split(' '),

    domPrefixes = omPrefixes.toLowerCase().split(' '),
   
    ns = { 'svg': 'http://www.w3.org/2000/svg' },
   

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

    classes = [],

    slice = classes.slice,

    featureName, // used in testing loop


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

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

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

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

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

        return !!ret;

    },
   

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

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

        var bool;

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

        return bool;

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

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

        function isEventSupported(eventName, element) {

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

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

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

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

            element = null;
            return isSupported;
        }
        return isEventSupported;
    })(),
   

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

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

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

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

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

            var target = this;

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

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

                    if (this instanceof bound) {

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

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

                    } else {

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

                    }

                };

            return bound;
        };
    }

   
    function setCss(str) {
        mStyle.cssText = str;
    }

   
    function setCssAll(str1, str2) {
        return setCss(prefixes.join(str1 + ';') + (str2 || ''));
    }

    
    function is(obj, type) {
        return typeof obj === type;
    }

    function contains(str, substr) {
        return !!~('' + str).indexOf(substr);
    }

   

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

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

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

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

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

    // TODO :: add testDOMProps
   
    function testDOMProps(props, obj, elem) {
        for (var i in props) {
            var item = obj[props[i]];
            if (item !== undefined) {

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

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

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

    
    function testPropsAll(prop, prefixed, elem) {

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

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

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

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

   

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

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

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

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

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

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

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

    

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

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

        return bool;
    };


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

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


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


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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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



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

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

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


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

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

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

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


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

        setCssAll('opacity:.55');

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


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


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


    tests['cssgradients'] = function () {
       

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

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

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


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


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


    tests['csstransforms3d'] = function () {

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

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

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


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


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

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

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

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

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

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

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

        return bool;
    };



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

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

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

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

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

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

        } catch (e) { }

        return bool;
    };

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

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

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

        return bool;
    };


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

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

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

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

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

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

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


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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        docElement.removeChild(inputElem);

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

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

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

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

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


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



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

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

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


    Modernizr.addTest = function (feature, test) {
        if (typeof feature == 'object') {
            for (var key in feature) {
                if (hasOwnProp(feature, key)) {
                    Modernizr.addTest(key, feature[key]);
                }
            }
        } else {

            feature = feature.toLowerCase();

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

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

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

        }

        return Modernizr; // allow chaining.
    };


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

   
    ; (function (window, document) {
        
        var version = '3.7.0';

      
        var options = window.html5 || {};

      
        var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;

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

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

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

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

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

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

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

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

        }());

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

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

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

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

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

     
        function createElement(nodeName, ownerDocument, data) {
            if (!ownerDocument) {
                ownerDocument = document;
            }
            if (supportsUnknownElements) {
                return ownerDocument.createElement(nodeName);
            }
            if (!data) {
                data = getExpandoData(ownerDocument);
            }
            var node;

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

            return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
        }

      
        function createDocumentFragment(ownerDocument, data) {
            if (!ownerDocument) {
                ownerDocument = document;
            }
            if (supportsUnknownElements) {
                return ownerDocument.createDocumentFragment();
            }
            data = data || getExpandoData(ownerDocument);
            var clone = data.frag.cloneNode(),
            i = 0,
            elems = getElements(),
            l = elems.length;
            for (; i < l; i++) {
                clone.createElement(elems[i]);
            }
            return clone;
        }

     
        function shivMethods(ownerDocument, data) {
            if (!data.cache) {
                data.cache = {};
                data.createElem = ownerDocument.createElement;
                data.createFrag = ownerDocument.createDocumentFragment;
                data.frag = data.createFrag();
            }


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

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

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

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

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

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

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

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

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

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

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

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

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

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

            //creates a shived element
            createElement: createElement,

            //creates a shived documentFragment
            createDocumentFragment: createDocumentFragment
        };

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

        // expose html5
        window.html5 = html5;

        // shiv the document
        shivDocument(document);

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

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

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

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

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

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

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


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


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

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

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

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


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

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

    return Modernizr;

})(this, this.document);
;
;(function($,window,document,undefined)
{
	
	var animateSlider	=	function(element,options)
	{
		this.element	=	element;
		this.$element	=	$(element);
		this.options	=	options;
	};

	animateSlider.prototype = 
	{
		/**
		 * [Initialize the plugin]
		 */
		init		:	function()
		{
			//Use Modernizr
			this.cssAnimations  =	Modernizr.cssanimations;
			this.cssTransitions =	Modernizr.csstransitions;
			if (!this.cssAnimations || !this.cssTransitions)
			{
				throw new Error("Your broswer does not support CSS3 Animations or Transitions");
			}
			
			this.config			=	$.extend({},this.defaults,this.options);
			this.slides			=	this.$element.children(".anim-slide");
			this.slidesCount	=	this.slides.length;
			this.interval		=	[];//Ovveride config.interval 
			this.current		=	0; //first slide	
	
			var $dots	=	$("<div class=\"anim-dots\"></div>");
			var temp	=	this.slidesCount;
			while ( temp --)
			{
				$dots.append("<span></span>");
			}
			$dots.appendTo(this.$element);
			this.slides.eq(this.current).addClass("anim-slide-this");

			this.$dots			=	this.$element.find(".anim-dots>span");
			this.$navNext		=	this.$element.find(".anim-arrows-next");
			this.$navPrev		=	this.$element.find(".anim-arrows-prev");
			
			this.loadEvents();
			this.navigate(this.current);
			this.updateDots();
			this.autoplay();
		},
		/**
		 * [Go to current slide and set the proper classes to animate the elements]
		 * @param  {number} page [current slide]
		 */
		navigate	:	function(page)
		{
			//Classes created from animate.css, you can add your own here.
			var classes		=	'bounce flash pulse rubberBand shake swing tada wobble bounceIn bounceInDown bounceInRight bounceInUp bounceOut bounceOutDown bounceOutLeft bounceOutRight bounceOutUp fadeIn fadeInDown fadeInDownBig fadeInLeft fadeInLeftBig fadeInRight fadeInRightBig fadeInUp fadeInUpBig fadeOut fadeOutDown fadeOutDownBig fadeOutLeft fadeOutLeftBig fadeOutRight fadeOutRightBig fadeOutUp fadeOutUpBig animated.flip flipInX flipInY flipOutX flipOutY lightSpeedIn lightSpeedOut rotateIn rotateInDownLeft rotateInDownRight rotateInUpLeft rotateInUpRight rotateOut rotateOutDownLeft rotateOutDownRight rotateOutUpLeft rotateOutUpRight slideInDown slideInLeft slideInRight slideOutLeft slideOutRight slideOutUp slideInUp slideOutDown hinge rollIn rollOut';
			var classShow,classHide,delayShow,$next,$current,currentAnimate,nextAnimate;

			$current		=	this.slides.eq(this.current);
			currentAnimate	=	this.elemAnimate(this.current,this.config);
			this.current	=	page;
			$next			=	this.slides.eq(this.current);
			nextAnimate		=	this.elemAnimate(this.current,this.config);

				/*=========================================*/
				$current.removeClass(" anim-slide-this "+classes);
				$current.find("*").removeClass(classes);

					//Iterate through a javascript plain object of current and next Slide
					$.each(currentAnimate,function(index)
					{
						if ( index == $current.prop("tagName").toLowerCase() )
						{
							classHide	=	$current.data("classHide");
							delayShow	=	$current.data("delayShow");
							$current.removeClass(delayShow);
							$current.addClass(classHide+" animated");
							return false;
						}
						else
						{
							classHide	=	$current.find(index).data("classHide");
							delayShow	=	$current.find(index).data("delayShow"); 
							$current.find(index).removeClass(delayShow);
							$current.find(index).addClass(classHide+" animated");
						}
					});
					$.each(nextAnimate,function(index)
						{
							if ( index == $current.prop("tagName").toLowerCase() )
							{
								classShow	=	$next.data("classShow") ;
								delayShow	=	$next.data("delayShow");
								$next.removeClass(classes);
								$next.addClass(classShow+" "+delayShow+" animated");
								return false;
							}
							else
							{
								classShow	=	$next.find(index).data("classShow");
								delayShow	=	$next.find(index).data("delayShow"); 
								$next.find(index).removeClass(classes);
								$next.find(index).addClass(classShow+" "+delayShow+" animated ");
							}
						});

				$next.addClass(" anim-slide-this");
			    /*=========================================*/ 
			this.updateDots();
		},
		/**
		 * [Update the dots to the current slide]
		 */
		updateDots	:	function() 
		{
			this.$dots.removeClass("anim-dots-this");
			this.$dots.eq(this.current).addClass("anim-dots-this");
		},
		/**
		 * [If the dots are clicked the autoplay procedure stops
		 * and you navigate to the current slide]
		 * @param  {number} page [current slide]
		 */
		dots		:	function(page)
		{
			if ( page >= this.slidesCount || page < 0)
			{
				return false;
			}
			if (this.config.autoplay)
			{
				clearTimeout(this.autoplay);
				this.config.autoplay	=	false;
			}
			this.navigate(page);
		},
		/**
		 * [Get the configuration object for each slide element and attach it to elements with $.data]
		 * @param  {number} page   [current slide]
		 * @param  {object} config [configuration object]
		 */
		elemAnimate	:	function(page,config)
		{
			if ( typeof config.animations == "object" )
			{
				if ( this.slidesCount !== Object.keys(config.animations).length )
				{
					throw new SyntaxError("Slides length and animation Object length must be equal.");
				}
				//Get the selected Slide configuration object
				var animations		=	config.animations[page];
				var $current		=	this.slides.eq(page);
				return $.each(animations,function(index,value)
					{
						
						if ( index	==	$current.prop("tagName").toLowerCase() )
						{
							if ( $current.data("classShow")	== null )
							{
								if ( typeof value.show		===	"string" )	{	$current.data("classShow",value.show);		}	else	{	$current.data("classShow","");	}
								if ( typeof value.hide		===	"string" )	{	$current.data("classHide",value.hide);		}	else	{	$current.data("classHide","");	}	
								if ( typeof	value.delayShow	===	"string" )	{	$current.data("delayShow",value.delayShow);	}	else	{	$current.data("delayShow"," ");	}	
							}
							return false;
						}
						else
						{
							if ( !$current.find(index)[0] )
							{
								throw new TypeError("The element \'"+index+"\' does not exist.");
							}

							if ( $current.find(index).data("classShow") == null )
							{
								if( typeof value.show		===	"string" ) {	$current.find(index).data("classShow",value.show);		} else	{	$current.find(index).data("classShow"," ");	}
								if( typeof value.hide		===	"string" ) {	$current.find(index).data("classHide",value.hide);		} else	{	$current.find(index).data("classHide"," ");	}
								if( typeof value.delayShow	===	"string" ) {	$current.find(index).data("delayShow",value.delayShow);	} else	{	$current.find(index).data("delayShow"," ");	}
							}
						}
					});
			}
		},
		/**
		 * [Call the animDuration for each slide and if the animation time of current slide is bigger than 
         * config.interval replace it with this.inteval, else leave config.interval with the default value]
		 */
		autoplay	:	function() 
		{
			if (this.config.autoplay)
			{
				var page				=	this.current;
				var that				=	this;
				var loop				=	function()
				{
					page	=	( page >= that.slidesCount -1 || page < 0 )	? 0 : page + 1;
					that.navigate(page);
					that.autoplay();
				};

				if ( this.interval.length === this.slidesCount )
				{
					this.autoplayTime	=	setTimeout(loop,this.interval[page]);
					return;
				}

				this.animDuration(page).done(function(animationTime)
				{
					if( animationTime >= that.config.interval )
					{
						that.interval[page]	=	animationTime;
						that.autoplayTime	=	setTimeout(loop,0);	
					}				
					else if( animationTime < that.config.interval	)
					{
						that.interval[page]	=	that.config.interval;
						that.autoplayTime	=	setTimeout(loop,that.config.interval-animationTime);
					}
				});
			}
		},
		/**
		 * [Find the total animation time for the current slide]
		 * @param  {number} page	[current slide]
		 * @return {object} promise [jQuery's Promises to make asynchronous call]
		 */
		animDuration:	function(page) 
		{
			var $slideAnimations			=	this.slides.eq(page);
			var slideAnimationsCount		=	$slideAnimations.children("*.animated").length;
			var animationStart				=	+new Date();
			var	promise						=	new $.Deferred();
			var	animationTime,count			=	0;
			$slideAnimations.on("animationend webkitAnimationEnd oanimationend MSAnimationEnd",function()
				{
					var animationEnd	=	+new Date();
					animationTime		=	Math.ceil((animationEnd -animationStart)/1000)*1000;
					count++;
					if (count == slideAnimationsCount)
					{
						promise.resolve(animationTime);
					}
				});	
			return promise;
		},
		/**
		 * [Attach events handlers to specific tasks]
		 */
		loadEvents	:	function()
		{
			var that = this;
			this.$navNext.on("click.slide",function(event)
				{
					if (that.config.autoplay)
					{
						clearTimeout(that.autoplay);
						that.config.autoplay	=	false;
					}
					var page	=	(that.current >= that.slidesCount - 1 ) ?  0 : that.current + 1 ;
					that.navigate(page,"next");
					event.preventDefault();
				});
			this.$navPrev.on("click.slide",function(event)
				{
					if (that.config.autoplay)
					{
						clearTimeout(that.autoplay);
						that.config.autoplay	=	false;
					}
					var page	=	( that.current === 0 )? that.slidesCount - 1 : that.current - 1;
					that.navigate(page,"prev");
					event.preventDefault(); 
				});
			this.$dots.on("click.slide",function(event)
				{
					var page	=	$(this).index();
					that.dots(page);
					event.preventDefault();
				});
		},
		defaults	:
		{
			autoplay	: true,
			interval	: 5000
		}
	};

	/**
	 * [Attach the plugin to jQuery's prototype]
	 * @param  {object} options [plugin's configuration object]
	 * @return {object} this    [the jQuery wrapper]
	 */
	$.fn.animateSlider	=	function(options)
	{
		return this.each(function()
			{
				var instance	=	$.data(this,"animateSlider");
				if (!instance)
				{
					$.data(this,"animateSlider",new animateSlider(this,options).init());
				}
			});
	};
})(jQuery);;/**
 * Owl Carousel
 * Copyright 2013-2018 David Deutsch
 * Licensed under: SEE LICENSE IN https://github.com/OwlCarousel2/OwlCarousel2/blob/master/LICENSE
 */
"function"!=typeof Object.create&&(Object.create=function(t){function e(){}return e.prototype=t,new e}),function(t,e,o){var i={init:function(e,o){var i=this;i.$elem=t(o),i.options=t.extend({},t.fn.owlCarousel.options,i.$elem.data(),e),i.userOptions=e,i.loadContent()},loadContent:function(){var e,o=this;"function"==typeof o.options.beforeInit&&o.options.beforeInit.apply(this,[o.$elem]),"string"==typeof o.options.jsonPath?(e=o.options.jsonPath,t.getJSON(e,(function(t){var e,i="";if("function"==typeof o.options.jsonSuccess)o.options.jsonSuccess.apply(this,[t]);else{for(e in t.owl)t.owl.hasOwnProperty(e)&&(i+=t.owl[e].item);o.$elem.html(i)}o.logIn()}))):o.logIn()},logIn:function(){var t=this;t.$elem.data({"owl-originalStyles":t.$elem.attr("style"),"owl-originalClasses":t.$elem.attr("class")}),t.$elem.css({opacity:0}),t.orignalItems=t.options.items,t.checkBrowser(),t.wrapperWidth=0,t.checkVisible=null,t.setVars()},setVars:function(){var t=this;if(0===t.$elem.children().length)return!1;t.baseClass(),t.eventTypes(),t.$userItems=t.$elem.children(),t.itemsAmount=t.$userItems.length,t.wrapItems(),t.$owlItems=t.$elem.find(".owl-item"),t.$owlWrapper=t.$elem.find(".owl-wrapper"),t.playDirection="next",t.prevItem=0,t.prevArr=[0],t.currentItem=0,t.customEvents(),t.onStartup()},onStartup:function(){var t=this;t.updateItems(),t.calculateAll(),t.buildControls(),t.updateControls(),t.response(),t.moveEvents(),t.stopOnHover(),t.owlStatus(),!1!==t.options.transitionStyle&&t.transitionTypes(t.options.transitionStyle),!0===t.options.autoPlay&&(t.options.autoPlay=5e3),t.play(),t.$elem.find(".owl-wrapper").css("display","block"),t.$elem.is(":visible")?t.$elem.css("opacity",1):t.watchVisibility(),t.onstartup=!1,t.eachMoveUpdate(),"function"==typeof t.options.afterInit&&t.options.afterInit.apply(this,[t.$elem])},eachMoveUpdate:function(){var t=this;!0===t.options.lazyLoad&&t.lazyLoad(),!0===t.options.autoHeight&&t.autoHeight(),t.onVisibleItems(),"function"==typeof t.options.afterAction&&t.options.afterAction.apply(this,[t.$elem])},updateVars:function(){var t=this;"function"==typeof t.options.beforeUpdate&&t.options.beforeUpdate.apply(this,[t.$elem]),t.watchVisibility(),t.updateItems(),t.calculateAll(),t.updatePosition(),t.updateControls(),t.eachMoveUpdate(),"function"==typeof t.options.afterUpdate&&t.options.afterUpdate.apply(this,[t.$elem])},reload:function(){var t=this;e.setTimeout((function(){t.updateVars()}),0)},watchVisibility:function(){var t=this;if(!1!==t.$elem.is(":visible"))return!1;t.$elem.css({opacity:0}),e.clearInterval(t.autoPlayInterval),e.clearInterval(t.checkVisible),t.checkVisible=e.setInterval((function(){t.$elem.is(":visible")&&(t.reload(),t.$elem.animate({opacity:1},200),e.clearInterval(t.checkVisible))}),500)},wrapItems:function(){var t=this;t.$userItems.wrapAll('<div class="owl-wrapper">').wrap('<div class="owl-item"></div>'),t.$elem.find(".owl-wrapper").wrap('<div class="owl-wrapper-outer">'),t.wrapperOuter=t.$elem.find(".owl-wrapper-outer"),t.$elem.css("display","block")},baseClass:function(){var t=this,e=t.$elem.hasClass(t.options.baseClass),o=t.$elem.hasClass(t.options.theme);e||t.$elem.addClass(t.options.baseClass),o||t.$elem.addClass(t.options.theme)},updateItems:function(){var e,o,i=this;if(!1===i.options.responsive)return!1;if(!0===i.options.singleItem)return i.options.items=i.orignalItems=1,i.options.itemsCustom=!1,i.options.itemsDesktop=!1,i.options.itemsDesktopSmall=!1,i.options.itemsTablet=!1,i.options.itemsTabletSmall=!1,i.options.itemsMobile=!1,!1;if((e=t(i.options.responsiveBaseWidth).width())>(i.options.itemsDesktop[0]||i.orignalItems)&&(i.options.items=i.orignalItems),!1!==i.options.itemsCustom)for(i.options.itemsCustom.sort((function(t,e){return t[0]-e[0]})),o=0;o<i.options.itemsCustom.length;o+=1)i.options.itemsCustom[o][0]<=e&&(i.options.items=i.options.itemsCustom[o][1]);else e<=i.options.itemsDesktop[0]&&!1!==i.options.itemsDesktop&&(i.options.items=i.options.itemsDesktop[1]),e<=i.options.itemsDesktopSmall[0]&&!1!==i.options.itemsDesktopSmall&&(i.options.items=i.options.itemsDesktopSmall[1]),e<=i.options.itemsTablet[0]&&!1!==i.options.itemsTablet&&(i.options.items=i.options.itemsTablet[1]),e<=i.options.itemsTabletSmall[0]&&!1!==i.options.itemsTabletSmall&&(i.options.items=i.options.itemsTabletSmall[1]),e<=i.options.itemsMobile[0]&&!1!==i.options.itemsMobile&&(i.options.items=i.options.itemsMobile[1]);i.options.items>i.itemsAmount&&!0===i.options.itemsScaleUp&&(i.options.items=i.itemsAmount)},response:function(){var o,i,s=this;if(!0!==s.options.responsive)return!1;i=t(e).width(),s.resizer=function(){t(e).width()!==i&&(!1!==s.options.autoPlay&&e.clearInterval(s.autoPlayInterval),e.clearTimeout(o),o=e.setTimeout((function(){i=t(e).width(),s.updateVars()}),s.options.responsiveRefreshRate))},t(e).resize(s.resizer)},updatePosition:function(){var t=this;t.jumpTo(t.currentItem),!1!==t.options.autoPlay&&t.checkAp()},appendItemsSizes:function(){var e=this,o=0,i=e.itemsAmount-e.options.items;e.$owlItems.each((function(s){var n=t(this);n.css({width:e.itemWidth}).data("owl-item",Number(s)),s%e.options.items!=0&&s!==i||s>i||(o+=1),n.data("owl-roundPages",o)}))},appendWrapperSizes:function(){var t=this,e=t.$owlItems.length*t.itemWidth;t.$owlWrapper.css({width:2*e,left:0}),t.appendItemsSizes()},calculateAll:function(){var t=this;t.calculateWidth(),t.appendWrapperSizes(),t.loops(),t.max()},calculateWidth:function(){var t=this;t.itemWidth=Math.round(t.$elem.width()/t.options.items)},max:function(){var t=this,e=-1*(t.itemsAmount*t.itemWidth-t.options.items*t.itemWidth);return t.options.items>t.itemsAmount?(t.maximumItem=0,e=0,t.maximumPixels=0):(t.maximumItem=t.itemsAmount-t.options.items,t.maximumPixels=e),e},min:function(){return 0},loops:function(){var e,o,i=this,s=0,n=0;for(i.positionsInArray=[0],i.pagesInArray=[],e=0;e<i.itemsAmount;e+=1)n+=i.itemWidth,i.positionsInArray.push(-n),!0===i.options.scrollPerPage&&(o=t(i.$owlItems[e]).data("owl-roundPages"))!==s&&(i.pagesInArray[s]=i.positionsInArray[e],s=o)},buildControls:function(){var e=this;!0!==e.options.navigation&&!0!==e.options.pagination||(e.owlControls=t('<div class="owl-controls"/>').toggleClass("clickable",!e.browser.isTouch).appendTo(e.$elem)),!0===e.options.pagination&&e.buildPagination(),!0===e.options.navigation&&e.buildButtons()},buildButtons:function(){var e=this,o=t('<div class="owl-buttons pull-right"/>');e.owlControls.append(o),e.buttonPrev=t("<div/>",{class:"owl-prev",title:"Prev",html:e.options.navigationText[0]||""}),e.buttonNext=t("<div/>",{class:"owl-next",title:"Next",html:e.options.navigationText[1]||""}),o.append(e.buttonPrev).append(e.buttonNext),o.on("touchstart.owlControls mousedown.owlControls",'div[class^="owl"]',(function(t){t.preventDefault()})),o.on("touchend.owlControls mouseup.owlControls",'div[class^="owl"]',(function(o){o.preventDefault(),t(this).hasClass("owl-next")?e.next():e.prev()}))},buildPagination:function(){var e=this;e.paginationWrapper=t('<div class="owl-pagination"/>'),e.owlControls.append(e.paginationWrapper),e.paginationWrapper.on("touchend.owlControls mouseup.owlControls",".owl-page",(function(o){o.preventDefault(),Number(t(this).data("owl-page"))!==e.currentItem&&e.goTo(Number(t(this).data("owl-page")),!0)}))},updatePagination:function(){var e,o,i,s,n,a,r=this;if(!1===r.options.pagination)return!1;for(r.paginationWrapper.html(""),e=0,o=r.itemsAmount-r.itemsAmount%r.options.items,s=0;s<r.itemsAmount;s+=1)s%r.options.items==0&&(e+=1,o===s&&(i=r.itemsAmount-r.options.items),n=t("<div/>",{class:"owl-page"}),a=t("<span></span>",{text:!0===r.options.paginationNumbers?e:"",class:!0===r.options.paginationNumbers?"owl-numbers":""}),n.append(a),n.data("owl-page",o===s?i:s),n.data("owl-roundPages",e),r.paginationWrapper.append(n));r.checkPagination()},checkPagination:function(){var e=this;if(!1===e.options.pagination)return!1;e.paginationWrapper.find(".owl-page").each((function(){t(this).data("owl-roundPages")===t(e.$owlItems[e.currentItem]).data("owl-roundPages")&&(e.paginationWrapper.find(".owl-page").removeClass("active"),t(this).addClass("active"))}))},checkNavigation:function(){var t=this;if(!1===t.options.navigation)return!1;!1===t.options.rewindNav&&(0===t.currentItem&&0===t.maximumItem?(t.buttonPrev.addClass("disabled"),t.buttonNext.addClass("disabled")):0===t.currentItem&&0!==t.maximumItem?(t.buttonPrev.addClass("disabled"),t.buttonNext.removeClass("disabled")):t.currentItem===t.maximumItem?(t.buttonPrev.removeClass("disabled"),t.buttonNext.addClass("disabled")):0!==t.currentItem&&t.currentItem!==t.maximumItem&&(t.buttonPrev.removeClass("disabled"),t.buttonNext.removeClass("disabled")))},updateControls:function(){var t=this;t.updatePagination(),t.checkNavigation(),t.owlControls&&(t.options.items>=t.itemsAmount?t.owlControls.hide():t.owlControls.show())},destroyControls:function(){this.owlControls&&this.owlControls.remove()},next:function(t){var e=this;if(e.isTransition)return!1;if(e.currentItem+=!0===e.options.scrollPerPage?e.options.items:1,e.currentItem>e.maximumItem+(!0===e.options.scrollPerPage?e.options.items-1:0)){if(!0!==e.options.rewindNav)return e.currentItem=e.maximumItem,!1;e.currentItem=0,t="rewind"}e.goTo(e.currentItem,t)},prev:function(t){var e=this;if(e.isTransition)return!1;if(!0===e.options.scrollPerPage&&e.currentItem>0&&e.currentItem<e.options.items?e.currentItem=0:e.currentItem-=!0===e.options.scrollPerPage?e.options.items:1,e.currentItem<0){if(!0!==e.options.rewindNav)return e.currentItem=0,!1;e.currentItem=e.maximumItem,t="rewind"}e.goTo(e.currentItem,t)},goTo:function(t,o,i){var s,n=this;return!n.isTransition&&("function"==typeof n.options.beforeMove&&n.options.beforeMove.apply(this,[n.$elem]),t>=n.maximumItem?t=n.maximumItem:t<=0&&(t=0),n.currentItem=n.owl.currentItem=t,!1!==n.options.transitionStyle&&"drag"!==i&&1===n.options.items&&!0===n.browser.support3d?(n.swapSpeed(0),!0===n.browser.support3d?n.transition3d(n.positionsInArray[t]):n.css2slide(n.positionsInArray[t],1),n.afterGo(),n.singleItemTransition(),!1):(s=n.positionsInArray[t],!0===n.browser.support3d?(n.isCss3Finish=!1,!0===o?(n.swapSpeed("paginationSpeed"),e.setTimeout((function(){n.isCss3Finish=!0}),n.options.paginationSpeed)):"rewind"===o?(n.swapSpeed(n.options.rewindSpeed),e.setTimeout((function(){n.isCss3Finish=!0}),n.options.rewindSpeed)):(n.swapSpeed("slideSpeed"),e.setTimeout((function(){n.isCss3Finish=!0}),n.options.slideSpeed)),n.transition3d(s)):!0===o?n.css2slide(s,n.options.paginationSpeed):"rewind"===o?n.css2slide(s,n.options.rewindSpeed):n.css2slide(s,n.options.slideSpeed),void n.afterGo()))},jumpTo:function(t){var e=this;"function"==typeof e.options.beforeMove&&e.options.beforeMove.apply(this,[e.$elem]),t>=e.maximumItem||-1===t?t=e.maximumItem:t<=0&&(t=0),e.swapSpeed(0),!0===e.browser.support3d?e.transition3d(e.positionsInArray[t]):e.css2slide(e.positionsInArray[t],1),e.currentItem=e.owl.currentItem=t,e.afterGo()},afterGo:function(){var t=this;t.prevArr.push(t.currentItem),t.prevItem=t.owl.prevItem=t.prevArr[t.prevArr.length-2],t.prevArr.shift(0),t.prevItem!==t.currentItem&&(t.checkPagination(),t.checkNavigation(),t.eachMoveUpdate(),!1!==t.options.autoPlay&&t.checkAp()),"function"==typeof t.options.afterMove&&t.prevItem!==t.currentItem&&t.options.afterMove.apply(this,[t.$elem])},stop:function(){this.apStatus="stop",e.clearInterval(this.autoPlayInterval)},checkAp:function(){"stop"!==this.apStatus&&this.play()},play:function(){var t=this;if(t.apStatus="play",!1===t.options.autoPlay)return!1;e.clearInterval(t.autoPlayInterval),t.autoPlayInterval=e.setInterval((function(){t.next(!0)}),t.options.autoPlay)},swapSpeed:function(t){var e=this;"slideSpeed"===t?e.$owlWrapper.css(e.addCssSpeed(e.options.slideSpeed)):"paginationSpeed"===t?e.$owlWrapper.css(e.addCssSpeed(e.options.paginationSpeed)):"string"!=typeof t&&e.$owlWrapper.css(e.addCssSpeed(t))},addCssSpeed:function(t){return{"-webkit-transition":"all "+t+"ms ease","-moz-transition":"all "+t+"ms ease","-o-transition":"all "+t+"ms ease",transition:"all "+t+"ms ease"}},removeTransition:function(){return{"-webkit-transition":"","-moz-transition":"","-o-transition":"",transition:""}},doTranslate:function(t){return{"-webkit-transform":"translate3d("+t+"px, 0px, 0px)","-moz-transform":"translate3d("+t+"px, 0px, 0px)","-o-transform":"translate3d("+t+"px, 0px, 0px)","-ms-transform":"translate3d("+t+"px, 0px, 0px)",transform:"translate3d("+t+"px, 0px,0px)"}},transition3d:function(t){this.$owlWrapper.css(this.doTranslate(t))},css2move:function(t){this.$owlWrapper.css({left:t})},css2slide:function(t,e){var o=this;o.isCssFinish=!1,o.$owlWrapper.stop(!0,!0).animate({left:t},{duration:e||o.options.slideSpeed,complete:function(){o.isCssFinish=!0}})},checkBrowser:function(){var t,i,s,n,a="translate3d(0px, 0px, 0px)",r=o.createElement("div");r.style.cssText="  -moz-transform:"+a+"; -ms-transform:"+a+"; -o-transform:"+a+"; -webkit-transform:"+a+"; transform:"+a,t=/translate3d\(0px, 0px, 0px\)/g,s=null!==(i=r.style.cssText.match(t))&&1===i.length,n="ontouchstart"in e||e.navigator.msMaxTouchPoints,this.browser={support3d:s,isTouch:n}},moveEvents:function(){var t=this;!1===t.options.mouseDrag&&!1===t.options.touchDrag||(t.gestures(),t.disabledEvents())},eventTypes:function(){var t=this,e=["s","e","x"];t.ev_types={},!0===t.options.mouseDrag&&!0===t.options.touchDrag?e=["touchstart.owl mousedown.owl","touchmove.owl mousemove.owl","touchend.owl touchcancel.owl mouseup.owl"]:!1===t.options.mouseDrag&&!0===t.options.touchDrag?e=["touchstart.owl","touchmove.owl","touchend.owl touchcancel.owl"]:!0===t.options.mouseDrag&&!1===t.options.touchDrag&&(e=["mousedown.owl","mousemove.owl","mouseup.owl"]),t.ev_types.start=e[0],t.ev_types.move=e[1],t.ev_types.end=e[2]},disabledEvents:function(){this.$elem.on("dragstart.owl",(function(t){t.preventDefault()})),this.$elem.on("mousedown.disableTextSelect",(function(e){return t(e.target).is("input, textarea, select, option")}))},gestures:function(){var i=this,s={offsetX:0,offsetY:0,baseElWidth:0,relativePos:0,position:null,minSwipe:null,maxSwipe:null,sliding:null,dargging:null,targetElement:null};function n(t){if(void 0!==t.touches)return{x:t.touches[0].pageX,y:t.touches[0].pageY};if(void 0===t.touches){if(void 0!==t.pageX)return{x:t.pageX,y:t.pageY};if(void 0===t.pageX)return{x:t.clientX,y:t.clientY}}}function a(e){"on"===e?(t(o).on(i.ev_types.move,r),t(o).on(i.ev_types.end,l)):"off"===e&&(t(o).off(i.ev_types.move),t(o).off(i.ev_types.end))}function r(a){var r,l,p=a.originalEvent||a||e.event;i.newPosX=n(p).x-s.offsetX,i.newPosY=n(p).y-s.offsetY,i.newRelativeX=i.newPosX-s.relativePos,"function"==typeof i.options.startDragging&&!0!==s.dragging&&0!==i.newRelativeX&&(s.dragging=!0,i.options.startDragging.apply(i,[i.$elem])),(i.newRelativeX>8||i.newRelativeX<-8)&&!0===i.browser.isTouch&&(void 0!==p.preventDefault?p.preventDefault():p.returnValue=!1,s.sliding=!0),(i.newPosY>10||i.newPosY<-10)&&!1===s.sliding&&t(o).off("touchmove.owl"),r=function(){return i.newRelativeX/5},l=function(){return i.maximumPixels+i.newRelativeX/5},i.newPosX=Math.max(Math.min(i.newPosX,r()),l()),!0===i.browser.support3d?i.transition3d(i.newPosX):i.css2move(i.newPosX)}function l(o){var n,r,l,p=o.originalEvent||o||e.event;p.target=p.target||p.srcElement,s.dragging=!1,!0!==i.browser.isTouch&&i.$owlWrapper.removeClass("grabbing"),i.newRelativeX<0?i.dragDirection=i.owl.dragDirection="left":i.dragDirection=i.owl.dragDirection="right",0!==i.newRelativeX&&(n=i.getNewPosition(),i.goTo(n,!1,"drag"),s.targetElement===p.target&&!0!==i.browser.isTouch&&(t(p.target).on("click.disable",(function(e){e.stopImmediatePropagation(),e.stopPropagation(),e.preventDefault(),t(e.target).off("click.disable")})),l=(r=t._data(p.target,"events").click).pop(),r.splice(0,0,l))),a("off")}i.isCssFinish=!0,i.$elem.on(i.ev_types.start,".owl-wrapper",(function(o){var r,l=o.originalEvent||o||e.event;if(3===l.which)return!1;if(!(i.itemsAmount<=i.options.items)){if(!1===i.isCssFinish&&!i.options.dragBeforeAnimFinish)return!1;if(!1===i.isCss3Finish&&!i.options.dragBeforeAnimFinish)return!1;!1!==i.options.autoPlay&&e.clearInterval(i.autoPlayInterval),!0===i.browser.isTouch||i.$owlWrapper.hasClass("grabbing")||i.$owlWrapper.addClass("grabbing"),i.newPosX=0,i.newRelativeX=0,t(this).css(i.removeTransition()),r=t(this).position(),s.relativePos=r.left,s.offsetX=n(l).x-r.left,s.offsetY=n(l).y-r.top,a("on"),s.sliding=!1,s.targetElement=l.target||l.srcElement}}))},getNewPosition:function(){var t=this,e=t.closestItem();return e>t.maximumItem?(t.currentItem=t.maximumItem,e=t.maximumItem):t.newPosX>=0&&(e=0,t.currentItem=0),e},closestItem:function(){var e=this,o=!0===e.options.scrollPerPage?e.pagesInArray:e.positionsInArray,i=e.newPosX,s=null;return t.each(o,(function(n,a){i-e.itemWidth/20>o[n+1]&&i-e.itemWidth/20<a&&"left"===e.moveDirection()?(s=a,!0===e.options.scrollPerPage?e.currentItem=t.inArray(s,e.positionsInArray):e.currentItem=n):i+e.itemWidth/20<a&&i+e.itemWidth/20>(o[n+1]||o[n]-e.itemWidth)&&"right"===e.moveDirection()&&(!0===e.options.scrollPerPage?(s=o[n+1]||o[o.length-1],e.currentItem=t.inArray(s,e.positionsInArray)):(s=o[n+1],e.currentItem=n+1))})),e.currentItem},moveDirection:function(){var t,e=this;return e.newRelativeX<0?(t="right",e.playDirection="next"):(t="left",e.playDirection="prev"),t},customEvents:function(){var t=this;t.$elem.on("owl.next",(function(){t.next()})),t.$elem.on("owl.prev",(function(){t.prev()})),t.$elem.on("owl.play",(function(e,o){t.options.autoPlay=o,t.play(),t.hoverStatus="play"})),t.$elem.on("owl.stop",(function(){t.stop(),t.hoverStatus="stop"})),t.$elem.on("owl.goTo",(function(e,o){t.goTo(o)})),t.$elem.on("owl.jumpTo",(function(e,o){t.jumpTo(o)}))},stopOnHover:function(){var t=this;!0===t.options.stopOnHover&&!0!==t.browser.isTouch&&!1!==t.options.autoPlay&&(t.$elem.on("mouseover",(function(){t.stop()})),t.$elem.on("mouseout",(function(){"stop"!==t.hoverStatus&&t.play()})))},lazyLoad:function(){var e,o,i,s,n=this;if(!1===n.options.lazyLoad)return!1;for(e=0;e<n.itemsAmount;e+=1)"loaded"!==(o=t(n.$owlItems[e])).data("owl-loaded")&&(i=o.data("owl-item"),"string"==typeof(s=o.find(".lazyOwl")).data("src")?(void 0===o.data("owl-loaded")&&(s.hide(),o.addClass("loading").data("owl-loaded","checked")),(!0!==n.options.lazyFollow||i>=n.currentItem)&&i<n.currentItem+n.options.items&&s.length&&s.each((function(){n.lazyPreload(o,t(this))}))):o.data("owl-loaded","loaded"))},lazyPreload:function(t,o){var i,s=this,n=0;function a(){t.data("owl-loaded","loaded").removeClass("loading"),o.removeAttr("data-src"),"fade"===s.options.lazyEffect?o.fadeIn(400):o.show(),"function"==typeof s.options.afterLazyLoad&&s.options.afterLazyLoad.apply(this,[s.$elem])}"DIV"===o.prop("tagName")?(o.css("background-image","url("+o.data("src")+")"),i=!0):o[0].src=o.data("src"),function t(){n+=1,s.completeImg(o.get(0))||!0===i?a():n<=100?e.setTimeout(t,100):a()}()},autoHeight:function(){var o,i=this,s=t(i.$owlItems[i.currentItem]).find("img");function n(){var o=t(i.$owlItems[i.currentItem]).height();i.wrapperOuter.css("height",o+"px"),i.wrapperOuter.hasClass("autoHeight")||e.setTimeout((function(){i.wrapperOuter.addClass("autoHeight")}),0)}void 0!==s.get(0)?(o=0,function t(){o+=1,i.completeImg(s.get(0))?n():o<=100?e.setTimeout(t,100):i.wrapperOuter.css("height","")}()):n()},completeImg:function(t){return!!t.complete&&("undefined"===typeof t.naturalWidth||0!==t.naturalWidth)},onVisibleItems:function(){var e,o=this;for(!0===o.options.addClassActive&&o.$owlItems.removeClass("active"),o.visibleItems=[],e=o.currentItem;e<o.currentItem+o.options.items;e+=1)o.visibleItems.push(e),!0===o.options.addClassActive&&t(o.$owlItems[e]).addClass("active");o.owl.visibleItems=o.visibleItems},transitionTypes:function(t){this.outClass="owl-"+t+"-out",this.inClass="owl-"+t+"-in"},singleItemTransition:function(){var t=this,e=t.outClass,o=t.inClass,i=t.$owlItems.eq(t.currentItem),s=t.$owlItems.eq(t.prevItem),n=Math.abs(t.positionsInArray[t.currentItem])+t.positionsInArray[t.prevItem],a=Math.abs(t.positionsInArray[t.currentItem])+t.itemWidth/2,r="webkitAnimationEnd oAnimationEnd MSAnimationEnd animationend";t.isTransition=!0,t.$owlWrapper.addClass("owl-origin").css({"-webkit-transform-origin":a+"px","-moz-perspective-origin":a+"px","perspective-origin":a+"px"}),s.css(function(t){return{position:"relative",left:t+"px"}}(n)).addClass(e).on(r,(function(){t.endPrev=!0,s.off(r),t.clearTransStyle(s,e)})),i.addClass(o).on(r,(function(){t.endCurrent=!0,i.off(r),t.clearTransStyle(i,o)}))},clearTransStyle:function(t,e){var o=this;t.css({position:"",left:""}).removeClass(e),o.endPrev&&o.endCurrent&&(o.$owlWrapper.removeClass("owl-origin"),o.endPrev=!1,o.endCurrent=!1,o.isTransition=!1)},owlStatus:function(){var t=this;t.owl={userOptions:t.userOptions,baseElement:t.$elem,userItems:t.$userItems,owlItems:t.$owlItems,currentItem:t.currentItem,prevItem:t.prevItem,visibleItems:t.visibleItems,isTouch:t.browser.isTouch,browser:t.browser,dragDirection:t.dragDirection}},clearEvents:function(){this.$elem.off(".owl owl mousedown.disableTextSelect"),t(o).off(".owl owl"),t(e).off("resize",this.resizer)},unWrap:function(){var t=this;0!==t.$elem.children().length&&(t.$owlWrapper.unwrap(),t.$userItems.unwrap().unwrap(),t.owlControls&&t.owlControls.remove()),t.clearEvents(),t.$elem.attr({style:t.$elem.data("owl-originalStyles")||"",class:t.$elem.data("owl-originalClasses")})},destroy:function(){var t=this;t.stop(),e.clearInterval(t.checkVisible),t.unWrap(),t.$elem.removeData()},reinit:function(e){var o=this,i=t.extend({},o.userOptions,e);o.unWrap(),o.init(i,o.$elem)},addItem:function(t,e){var o,i=this;return!!t&&(0===i.$elem.children().length?(i.$elem.append(t),i.setVars(),!1):(i.unWrap(),(o=void 0===e||-1===e?-1:e)>=i.$userItems.length||-1===o?i.$userItems.eq(-1).after(t):i.$userItems.eq(o).before(t),void i.setVars()))},removeItem:function(t){var e,o=this;if(0===o.$elem.children().length)return!1;e=void 0===t||-1===t?-1:t,o.unWrap(),o.$userItems.eq(e).remove(),o.setVars()}};t.fn.owlCarousel=function(e){return this.each((function(){if(!0===t(this).data("owl-init"))return!1;t(this).data("owl-init",!0);var o=Object.create(i);o.init(e,this),t.data(this,"owlCarousel",o)}))},t.fn.owlCarousel.options={items:5,itemsCustom:!1,itemsDesktop:[1199,4],itemsDesktopSmall:[979,3],itemsTablet:[768,2],itemsTabletSmall:!1,itemsMobile:[479,1],singleItem:!1,itemsScaleUp:!1,slideSpeed:200,paginationSpeed:800,rewindSpeed:1e3,autoPlay:!1,stopOnHover:!1,navigation:!1,navigationText:["prev","next"],rewindNav:!0,scrollPerPage:!1,pagination:!0,paginationNumbers:!1,responsive:!0,responsiveRefreshRate:200,responsiveBaseWidth:e,baseClass:"owl-carousel",theme:"owl-theme",lazyLoad:!1,lazyFollow:!0,lazyEffect:"fade",autoHeight:!1,jsonPath:!1,jsonSuccess:!1,dragBeforeAnimFinish:!0,mouseDrag:!0,touchDrag:!0,addClassActive:!1,transitionStyle:!1,beforeUpdate:!1,afterUpdate:!1,beforeInit:!1,afterInit:!1,beforeMove:!1,afterMove:!1,afterAction:!1,startDragging:!1,afterLazyLoad:!1}}(jQuery,window,document);;/*!
 * Fotorama 4.6.4 | http://fotorama.io/license/
 */
fotoramaVersion="4.6.4",function(a,b,c,d,e){"use strict";function f(a){var b="bez_"+d.makeArray(arguments).join("_").replace(".","p");if("function"!=typeof d.easing[b]){var c=function(a,b){var c=[null,null],d=[null,null],e=[null,null],f=function(f,g){return e[g]=3*a[g],d[g]=3*(b[g]-a[g])-e[g],c[g]=1-e[g]-d[g],f*(e[g]+f*(d[g]+f*c[g]))},g=function(a){return e[0]+a*(2*d[0]+3*c[0]*a)},h=function(a){for(var b,c=a,d=0;++d<14&&(b=f(c,0)-a,!(Math.abs(b)<.001));)c-=b/g(c);return c};return function(a){return f(h(a),1)}};d.easing[b]=function(b,d,e,f,g){return f*c([a[0],a[1]],[a[2],a[3]])(d/g)+e}}return b}function g(){}function h(a,b,c){return Math.max(isNaN(b)?-1/0:b,Math.min(isNaN(c)?1/0:c,a))}function i(a){return a.match(/ma/)&&a.match(/-?\d+(?!d)/g)[a.match(/3d/)?12:4]}function j(a){return Ic?+i(a.css("transform")):+a.css("left").replace("px","")}function k(a){var b={};return Ic?b.transform="translate3d("+a+"px,0,0)":b.left=a,b}function l(a){return{"transition-duration":a+"ms"}}function m(a,b){return isNaN(a)?b:a}function n(a,b){return m(+String(a).replace(b||"px",""))}function o(a){return/%$/.test(a)?n(a,"%"):e}function p(a,b){return m(o(a)/100*b,n(a))}function q(a){return(!isNaN(n(a))||!isNaN(n(a,"%")))&&a}function r(a,b,c,d){return(a-(d||0))*(b+(c||0))}function s(a,b,c,d){return-Math.round(a/(b+(c||0))-(d||0))}function t(a){var b=a.data();if(!b.tEnd){var c=a[0],d={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",msTransition:"MSTransitionEnd",transition:"transitionend"};T(c,d[uc.prefixed("transition")],function(a){b.tProp&&a.propertyName.match(b.tProp)&&b.onEndFn()}),b.tEnd=!0}}function u(a,b,c,d){var e,f=a.data();f&&(f.onEndFn=function(){e||(e=!0,clearTimeout(f.tT),c())},f.tProp=b,clearTimeout(f.tT),f.tT=setTimeout(function(){f.onEndFn()},1.5*d),t(a))}function v(a,b){if(a.length){var c=a.data();Ic?(a.css(l(0)),c.onEndFn=g,clearTimeout(c.tT)):a.stop();var d=w(b,function(){return j(a)});return a.css(k(d)),d}}function w(){for(var a,b=0,c=arguments.length;c>b&&(a=b?arguments[b]():arguments[b],"number"!=typeof a);b++);return a}function x(a,b){return Math.round(a+(b-a)/1.5)}function y(){return y.p=y.p||("https:"===c.protocol?"https://":"http://"),y.p}function z(a){var c=b.createElement("a");return c.href=a,c}function A(a,b){if("string"!=typeof a)return a;a=z(a);var c,d;if(a.host.match(/youtube\.com/)&&a.search){if(c=a.search.split("v=")[1]){var e=c.indexOf("&");-1!==e&&(c=c.substring(0,e)),d="youtube"}}else a.host.match(/youtube\.com|youtu\.be/)?(c=a.pathname.replace(/^\/(embed\/|v\/)?/,"").replace(/\/.*/,""),d="youtube"):a.host.match(/vimeo\.com/)&&(d="vimeo",c=a.pathname.replace(/^\/(video\/)?/,"").replace(/\/.*/,""));return c&&d||!b||(c=a.href,d="custom"),c?{id:c,type:d,s:a.search.replace(/^\?/,""),p:y()}:!1}function B(a,b,c){var e,f,g=a.video;return"youtube"===g.type?(f=y()+"img.youtube.com/vi/"+g.id+"/default.jpg",e=f.replace(/\/default.jpg$/,"/hqdefault.jpg"),a.thumbsReady=!0):"vimeo"===g.type?d.ajax({url:y()+"vimeo.com/api/v2/video/"+g.id+".json",dataType:"jsonp",success:function(d){a.thumbsReady=!0,C(b,{img:d[0].thumbnail_large,thumb:d[0].thumbnail_small},a.i,c)}}):a.thumbsReady=!0,{img:e,thumb:f}}function C(a,b,c,e){for(var f=0,g=a.length;g>f;f++){var h=a[f];if(h.i===c&&h.thumbsReady){var i={videoReady:!0};i[Xc]=i[Zc]=i[Yc]=!1,e.splice(f,1,d.extend({},h,i,b));break}}}function D(a){function b(a,b,e){var f=a.children("img").eq(0),g=a.attr("href"),h=a.attr("src"),i=f.attr("src"),j=b.video,k=e?A(g,j===!0):!1;k?g=!1:k=j,c(a,f,d.extend(b,{video:k,img:b.img||g||h||i,thumb:b.thumb||i||h||g}))}function c(a,b,c){var e=c.thumb&&c.img!==c.thumb,f=n(c.width||a.attr("width")),g=n(c.height||a.attr("height"));d.extend(c,{width:f,height:g,thumbratio:S(c.thumbratio||n(c.thumbwidth||b&&b.attr("width")||e||f)/n(c.thumbheight||b&&b.attr("height")||e||g))})}var e=[];return a.children().each(function(){var a=d(this),f=R(d.extend(a.data(),{id:a.attr("id")}));if(a.is("a, img"))b(a,f,!0);else{if(a.is(":empty"))return;c(a,null,d.extend(f,{html:this,_html:a.html()}))}e.push(f)}),e}function E(a){return 0===a.offsetWidth&&0===a.offsetHeight}function F(a){return!d.contains(b.documentElement,a)}function G(a,b,c,d){return G.i||(G.i=1,G.ii=[!0]),d=d||G.i,"undefined"==typeof G.ii[d]&&(G.ii[d]=!0),a()?b():G.ii[d]&&setTimeout(function(){G.ii[d]&&G(a,b,c,d)},c||100),G.i++}function H(a){c.replace(c.protocol+"//"+c.host+c.pathname.replace(/^\/?/,"/")+c.search+"#"+a)}function I(a,b,c,d){var e=a.data(),f=e.measures;if(f&&(!e.l||e.l.W!==f.width||e.l.H!==f.height||e.l.r!==f.ratio||e.l.w!==b.w||e.l.h!==b.h||e.l.m!==c||e.l.p!==d)){var g=f.width,i=f.height,j=b.w/b.h,k=f.ratio>=j,l="scaledown"===c,m="contain"===c,n="cover"===c,o=$(d);k&&(l||m)||!k&&n?(g=h(b.w,0,l?g:1/0),i=g/f.ratio):(k&&n||!k&&(l||m))&&(i=h(b.h,0,l?i:1/0),g=i*f.ratio),a.css({width:g,height:i,left:p(o.x,b.w-g),top:p(o.y,b.h-i)}),e.l={W:f.width,H:f.height,r:f.ratio,w:b.w,h:b.h,m:c,p:d}}return!0}function J(a,b){var c=a[0];c.styleSheet?c.styleSheet.cssText=b:a.html(b)}function K(a,b,c){return b===c?!1:b>=a?"left":a>=c?"right":"left right"}function L(a,b,c,d){if(!c)return!1;if(!isNaN(a))return a-(d?0:1);for(var e,f=0,g=b.length;g>f;f++){var h=b[f];if(h.id===a){e=f;break}}return e}function M(a,b,c){c=c||{},a.each(function(){var a,e=d(this),f=e.data();f.clickOn||(f.clickOn=!0,d.extend(cb(e,{onStart:function(b){a=b,(c.onStart||g).call(this,b)},onMove:c.onMove||g,onTouchEnd:c.onTouchEnd||g,onEnd:function(c){c.moved||b.call(this,a)}}),{noMove:!0}))})}function N(a,b){return'<div class="'+a+'">'+(b||"")+"</div>"}function O(a){for(var b=a.length;b;){var c=Math.floor(Math.random()*b--),d=a[b];a[b]=a[c],a[c]=d}return a}function P(a){return"[object Array]"==Object.prototype.toString.call(a)&&d.map(a,function(a){return d.extend({},a)})}function Q(a,b,c){a.scrollLeft(b||0).scrollTop(c||0)}function R(a){if(a){var b={};return d.each(a,function(a,c){b[a.toLowerCase()]=c}),b}}function S(a){if(a){var b=+a;return isNaN(b)?(b=a.split("/"),+b[0]/+b[1]||e):b}}function T(a,b,c,d){b&&(a.addEventListener?a.addEventListener(b,c,!!d):a.attachEvent("on"+b,c))}function U(a){return!!a.getAttribute("disabled")}function V(a){return{tabindex:-1*a+"",disabled:a}}function W(a,b){T(a,"keyup",function(c){U(a)||13==c.keyCode&&b.call(a,c)})}function X(a,b){T(a,"focus",a.onfocusin=function(c){b.call(a,c)},!0)}function Y(a,b){a.preventDefault?a.preventDefault():a.returnValue=!1,b&&a.stopPropagation&&a.stopPropagation()}function Z(a){return a?">":"<"}function $(a){return a=(a+"").split(/\s+/),{x:q(a[0])||bd,y:q(a[1])||bd}}function _(a,b){var c=a.data(),e=Math.round(b.pos),f=function(){c.sliding=!1,(b.onEnd||g)()};"undefined"!=typeof b.overPos&&b.overPos!==b.pos&&(e=b.overPos,f=function(){_(a,d.extend({},b,{overPos:b.pos,time:Math.max(Qc,b.time/2)}))});var h=d.extend(k(e),b.width&&{width:b.width});c.sliding=!0,Ic?(a.css(d.extend(l(b.time),h)),b.time>10?u(a,"transform",f,b.time):f()):a.stop().animate(h,b.time,_c,f)}function ab(a,b,c,e,f,h){var i="undefined"!=typeof h;if(i||(f.push(arguments),Array.prototype.push.call(arguments,f.length),!(f.length>1))){a=a||d(a),b=b||d(b);var j=a[0],k=b[0],l="crossfade"===e.method,m=function(){if(!m.done){m.done=!0;var a=(i||f.shift())&&f.shift();a&&ab.apply(this,a),(e.onEnd||g)(!!a)}},n=e.time/(h||1);c.removeClass(Rb+" "+Qb),a.stop().addClass(Rb),b.stop().addClass(Qb),l&&k&&a.fadeTo(0,0),a.fadeTo(l?n:0,1,l&&m),b.fadeTo(n,0,m),j&&l||k||m()}}function bb(a){var b=(a.touches||[])[0]||a;a._x=b.pageX,a._y=b.clientY,a._now=d.now()}function cb(a,c){function e(a){return m=d(a.target),u.checked=p=q=s=!1,k||u.flow||a.touches&&a.touches.length>1||a.which>1||ed&&ed.type!==a.type&&gd||(p=c.select&&m.is(c.select,t))?p:(o="touchstart"===a.type,q=m.is("a, a *",t),n=u.control,r=u.noMove||u.noSwipe||n?16:u.snap?0:4,bb(a),l=ed=a,fd=a.type.replace(/down|start/,"move").replace(/Down/,"Move"),(c.onStart||g).call(t,a,{control:n,$target:m}),k=u.flow=!0,void((!o||u.go)&&Y(a)))}function f(a){if(a.touches&&a.touches.length>1||Nc&&!a.isPrimary||fd!==a.type||!k)return k&&h(),void(c.onTouchEnd||g)();bb(a);var b=Math.abs(a._x-l._x),d=Math.abs(a._y-l._y),e=b-d,f=(u.go||u.x||e>=0)&&!u.noSwipe,i=0>e;o&&!u.checked?(k=f)&&Y(a):(Y(a),(c.onMove||g).call(t,a,{touch:o})),!s&&Math.sqrt(Math.pow(b,2)+Math.pow(d,2))>r&&(s=!0),u.checked=u.checked||f||i}function h(a){(c.onTouchEnd||g)();var b=k;u.control=k=!1,b&&(u.flow=!1),!b||q&&!u.checked||(a&&Y(a),gd=!0,clearTimeout(hd),hd=setTimeout(function(){gd=!1},1e3),(c.onEnd||g).call(t,{moved:s,$target:m,control:n,touch:o,startEvent:l,aborted:!a||"MSPointerCancel"===a.type}))}function i(){u.flow||setTimeout(function(){u.flow=!0},10)}function j(){u.flow&&setTimeout(function(){u.flow=!1},Pc)}var k,l,m,n,o,p,q,r,s,t=a[0],u={};return Nc?(T(t,"MSPointerDown",e),T(b,"MSPointerMove",f),T(b,"MSPointerCancel",h),T(b,"MSPointerUp",h)):(T(t,"touchstart",e),T(t,"touchmove",f),T(t,"touchend",h),T(b,"touchstart",i),T(b,"touchend",j),T(b,"touchcancel",j),Ec.on("scroll",j),a.on("mousedown",e),Fc.on("mousemove",f).on("mouseup",h)),a.on("click","a",function(a){u.checked&&Y(a)}),u}function db(a,b){function c(c,d){A=!0,j=l=c._x,q=c._now,p=[[q,j]],m=n=D.noMove||d?0:v(a,(b.getPos||g)()),(b.onStart||g).call(B,c)}function e(a,b){s=D.min,t=D.max,u=D.snap,w=a.altKey,A=z=!1,y=b.control,y||C.sliding||c(a)}function f(d,e){D.noSwipe||(A||c(d),l=d._x,p.push([d._now,l]),n=m-(j-l),o=K(n,s,t),s>=n?n=x(n,s):n>=t&&(n=x(n,t)),D.noMove||(a.css(k(n)),z||(z=!0,e.touch||Nc||a.addClass(ec)),(b.onMove||g).call(B,d,{pos:n,edge:o})))}function i(e){if(!D.noSwipe||!e.moved){A||c(e.startEvent,!0),e.touch||Nc||a.removeClass(ec),r=d.now();for(var f,i,j,k,o,q,v,x,y,z=r-Pc,C=null,E=Qc,F=b.friction,G=p.length-1;G>=0;G--){if(f=p[G][0],i=Math.abs(f-z),null===C||j>i)C=f,k=p[G][1];else if(C===z||i>j)break;j=i}v=h(n,s,t);var H=k-l,I=H>=0,J=r-C,K=J>Pc,L=!K&&n!==m&&v===n;u&&(v=h(Math[L?I?"floor":"ceil":"round"](n/u)*u,s,t),s=t=v),L&&(u||v===n)&&(y=-(H/J),E*=h(Math.abs(y),b.timeLow,b.timeHigh),o=Math.round(n+y*E/F),u||(v=o),(!I&&o>t||I&&s>o)&&(q=I?s:t,x=o-q,u||(v=q),x=h(v+.03*x,q-50,q+50),E=Math.abs((n-x)/(y/F)))),E*=w?10:1,(b.onEnd||g).call(B,d.extend(e,{moved:e.moved||K&&u,pos:n,newPos:v,overPos:x,time:E}))}}var j,l,m,n,o,p,q,r,s,t,u,w,y,z,A,B=a[0],C=a.data(),D={};return D=d.extend(cb(b.$wrap,d.extend({},b,{onStart:e,onMove:f,onEnd:i})),D)}function eb(a,b){var c,e,f,h=a[0],i={prevent:{}};return T(h,Oc,function(a){var h=a.wheelDeltaY||-1*a.deltaY||0,j=a.wheelDeltaX||-1*a.deltaX||0,k=Math.abs(j)&&!Math.abs(h),l=Z(0>j),m=e===l,n=d.now(),o=Pc>n-f;e=l,f=n,k&&i.ok&&(!i.prevent[l]||c)&&(Y(a,!0),c&&m&&o||(b.shift&&(c=!0,clearTimeout(i.t),i.t=setTimeout(function(){c=!1},Rc)),(b.onEnd||g)(a,b.shift?l:j)))}),i}function fb(){d.each(d.Fotorama.instances,function(a,b){b.index=a})}function gb(a){d.Fotorama.instances.push(a),fb()}function hb(a){d.Fotorama.instances.splice(a.index,1),fb()}var ib="fotorama",jb="fullscreen",kb=ib+"__wrap",lb=kb+"--css2",mb=kb+"--css3",nb=kb+"--video",ob=kb+"--fade",pb=kb+"--slide",qb=kb+"--no-controls",rb=kb+"--no-shadows",sb=kb+"--pan-y",tb=kb+"--rtl",ub=kb+"--only-active",vb=kb+"--no-captions",wb=kb+"--toggle-arrows",xb=ib+"__stage",yb=xb+"__frame",zb=yb+"--video",Ab=xb+"__shaft",Bb=ib+"__grab",Cb=ib+"__pointer",Db=ib+"__arr",Eb=Db+"--disabled",Fb=Db+"--prev",Gb=Db+"--next",Hb=ib+"__nav",Ib=Hb+"-wrap",Jb=Hb+"__shaft",Kb=Hb+"--dots",Lb=Hb+"--thumbs",Mb=Hb+"__frame",Nb=Mb+"--dot",Ob=Mb+"--thumb",Pb=ib+"__fade",Qb=Pb+"-front",Rb=Pb+"-rear",Sb=ib+"__shadow",Tb=Sb+"s",Ub=Tb+"--left",Vb=Tb+"--right",Wb=ib+"__active",Xb=ib+"__select",Yb=ib+"--hidden",Zb=ib+"--fullscreen",$b=ib+"__fullscreen-icon",_b=ib+"__error",ac=ib+"__loading",bc=ib+"__loaded",cc=bc+"--full",dc=bc+"--img",ec=ib+"__grabbing",fc=ib+"__img",gc=fc+"--full",hc=ib+"__dot",ic=ib+"__thumb",jc=ic+"-border",kc=ib+"__html",lc=ib+"__video",mc=lc+"-play",nc=lc+"-close",oc=ib+"__caption",pc=ib+"__caption__wrap",qc=ib+"__spinner",rc='" tabindex="0" role="button',sc=d&&d.fn.jquery.split(".");if(!sc||sc[0]<1||1==sc[0]&&sc[1]<8)throw"Fotorama requires jQuery 1.8 or later and will not run without it.";var tc={},uc=function(a,b,c){function d(a){r.cssText=a}function e(a,b){return typeof a===b}function f(a,b){return!!~(""+a).indexOf(b)}function g(a,b){for(var d in a){var e=a[d];if(!f(e,"-")&&r[e]!==c)return"pfx"==b?e:!0}return!1}function h(a,b,d){for(var f in a){var g=b[a[f]];if(g!==c)return d===!1?a[f]:e(g,"function")?g.bind(d||b):g}return!1}function i(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),f=(a+" "+u.join(d+" ")+d).split(" ");return e(b,"string")||e(b,"undefined")?g(f,b):(f=(a+" "+v.join(d+" ")+d).split(" "),h(f,b,c))}var j,k,l,m="2.6.2",n={},o=b.documentElement,p="modernizr",q=b.createElement(p),r=q.style,s=({}.toString," -webkit- -moz- -o- -ms- ".split(" ")),t="Webkit Moz O ms",u=t.split(" "),v=t.toLowerCase().split(" "),w={},x=[],y=x.slice,z=function(a,c,d,e){var f,g,h,i,j=b.createElement("div"),k=b.body,l=k||b.createElement("body");if(parseInt(d,10))for(;d--;)h=b.createElement("div"),h.id=e?e[d]:p+(d+1),j.appendChild(h);return f=["&#173;",'<style id="s',p,'">',a,"</style>"].join(""),j.id=p,(k?j:l).innerHTML+=f,l.appendChild(j),k||(l.style.background="",l.style.overflow="hidden",i=o.style.overflow,o.style.overflow="hidden",o.appendChild(l)),g=c(j,a),k?j.parentNode.removeChild(j):(l.parentNode.removeChild(l),o.style.overflow=i),!!g},A={}.hasOwnProperty;l=e(A,"undefined")||e(A.call,"undefined")?function(a,b){return b in a&&e(a.constructor.prototype[b],"undefined")}:function(a,b){return A.call(a,b)},Function.prototype.bind||(Function.prototype.bind=function(a){var b=this;if("function"!=typeof b)throw new TypeError;var c=y.call(arguments,1),d=function(){if(this instanceof d){var e=function(){};e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(y.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(y.call(arguments)))};return d}),w.csstransforms3d=function(){var a=!!i("perspective");return a};for(var B in w)l(w,B)&&(k=B.toLowerCase(),n[k]=w[B](),x.push((n[k]?"":"no-")+k));return n.addTest=function(a,b){if("object"==typeof a)for(var d in a)l(a,d)&&n.addTest(d,a[d]);else{if(a=a.toLowerCase(),n[a]!==c)return n;b="function"==typeof b?b():b,"undefined"!=typeof enableClasses&&enableClasses&&(o.className+=" "+(b?"":"no-")+a),n[a]=b}return n},d(""),q=j=null,n._version=m,n._prefixes=s,n._domPrefixes=v,n._cssomPrefixes=u,n.testProp=function(a){return g([a])},n.testAllProps=i,n.testStyles=z,n.prefixed=function(a,b,c){return b?i(a,b,c):i(a,"pfx")},n}(a,b),vc={ok:!1,is:function(){return!1},request:function(){},cancel:function(){},event:"",prefix:""},wc="webkit moz o ms khtml".split(" ");if("undefined"!=typeof b.cancelFullScreen)vc.ok=!0;else for(var xc=0,yc=wc.length;yc>xc;xc++)if(vc.prefix=wc[xc],"undefined"!=typeof b[vc.prefix+"CancelFullScreen"]){vc.ok=!0;break}vc.ok&&(vc.event=vc.prefix+"fullscreenchange",vc.is=function(){switch(this.prefix){case"":return b.fullScreen;case"webkit":return b.webkitIsFullScreen;default:return b[this.prefix+"FullScreen"]}},vc.request=function(a){return""===this.prefix?a.requestFullScreen():a[this.prefix+"RequestFullScreen"]()},vc.cancel=function(){return""===this.prefix?b.cancelFullScreen():b[this.prefix+"CancelFullScreen"]()});var zc,Ac={lines:12,length:5,width:2,radius:7,corners:1,rotate:15,color:"rgba(128, 128, 128, .75)",hwaccel:!0},Bc={top:"auto",left:"auto",className:""};!function(a,b){zc=b()}(this,function(){function a(a,c){var d,e=b.createElement(a||"div");for(d in c)e[d]=c[d];return e}function c(a){for(var b=1,c=arguments.length;c>b;b++)a.appendChild(arguments[b]);return a}function d(a,b,c,d){var e=["opacity",b,~~(100*a),c,d].join("-"),f=.01+c/d*100,g=Math.max(1-(1-a)/b*(100-f),a),h=m.substring(0,m.indexOf("Animation")).toLowerCase(),i=h&&"-"+h+"-"||"";return o[e]||(p.insertRule("@"+i+"keyframes "+e+"{0%{opacity:"+g+"}"+f+"%{opacity:"+a+"}"+(f+.01)+"%{opacity:1}"+(f+b)%100+"%{opacity:"+a+"}100%{opacity:"+g+"}}",p.cssRules.length),o[e]=1),e}function f(a,b){var c,d,f=a.style;for(b=b.charAt(0).toUpperCase()+b.slice(1),d=0;d<n.length;d++)if(c=n[d]+b,f[c]!==e)return c;return f[b]!==e?b:void 0}function g(a,b){for(var c in b)a.style[f(a,c)||c]=b[c];return a}function h(a){for(var b=1;b<arguments.length;b++){var c=arguments[b];for(var d in c)a[d]===e&&(a[d]=c[d])}return a}function i(a){for(var b={x:a.offsetLeft,y:a.offsetTop};a=a.offsetParent;)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}function j(a,b){return"string"==typeof a?a:a[b%a.length]}function k(a){return"undefined"==typeof this?new k(a):void(this.opts=h(a||{},k.defaults,q))}function l(){function b(b,c){return a("<"+b+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',c)}p.addRule(".spin-vml","behavior:url(#default#VML)"),k.prototype.lines=function(a,d){function e(){return g(b("group",{coordsize:k+" "+k,coordorigin:-i+" "+-i}),{width:k,height:k})}function f(a,f,h){c(m,c(g(e(),{rotation:360/d.lines*a+"deg",left:~~f}),c(g(b("roundrect",{arcsize:d.corners}),{width:i,height:d.width,left:d.radius,top:-d.width>>1,filter:h}),b("fill",{color:j(d.color,a),opacity:d.opacity}),b("stroke",{opacity:0}))))}var h,i=d.length+d.width,k=2*i,l=2*-(d.width+d.length)+"px",m=g(e(),{position:"absolute",top:l,left:l});if(d.shadow)for(h=1;h<=d.lines;h++)f(h,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(h=1;h<=d.lines;h++)f(h);return c(a,m)},k.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}}var m,n=["webkit","Moz","ms","O"],o={},p=function(){var d=a("style",{type:"text/css"});return c(b.getElementsByTagName("head")[0],d),d.sheet||d.styleSheet}(),q={lines:12,length:7,width:5,radius:10,rotate:0,corners:1,color:"#000",direction:1,speed:1,trail:100,opacity:.25,fps:20,zIndex:2e9,className:"spinner",top:"auto",left:"auto",position:"relative"};k.defaults={},h(k.prototype,{spin:function(b){this.stop();var c,d,e=this,f=e.opts,h=e.el=g(a(0,{className:f.className}),{position:f.position,width:0,zIndex:f.zIndex}),j=f.radius+f.length+f.width;if(b&&(b.insertBefore(h,b.firstChild||null),d=i(b),c=i(h),g(h,{left:("auto"==f.left?d.x-c.x+(b.offsetWidth>>1):parseInt(f.left,10)+j)+"px",top:("auto"==f.top?d.y-c.y+(b.offsetHeight>>1):parseInt(f.top,10)+j)+"px"})),h.setAttribute("role","progressbar"),e.lines(h,e.opts),!m){var k,l=0,n=(f.lines-1)*(1-f.direction)/2,o=f.fps,p=o/f.speed,q=(1-f.opacity)/(p*f.trail/100),r=p/f.lines;!function s(){l++;for(var a=0;a<f.lines;a++)k=Math.max(1-(l+(f.lines-a)*r)%p*q,f.opacity),e.opacity(h,a*f.direction+n,k,f);e.timeout=e.el&&setTimeout(s,~~(1e3/o))}()}return e},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=e),this},lines:function(b,e){function f(b,c){return g(a(),{position:"absolute",width:e.length+e.width+"px",height:e.width+"px",background:b,boxShadow:c,transformOrigin:"left",transform:"rotate("+~~(360/e.lines*i+e.rotate)+"deg) translate("+e.radius+"px,0)",borderRadius:(e.corners*e.width>>1)+"px"})}for(var h,i=0,k=(e.lines-1)*(1-e.direction)/2;i<e.lines;i++)h=g(a(),{position:"absolute",top:1+~(e.width/2)+"px",transform:e.hwaccel?"translate3d(0,0,0)":"",opacity:e.opacity,animation:m&&d(e.opacity,e.trail,k+i*e.direction,e.lines)+" "+1/e.speed+"s linear infinite"}),e.shadow&&c(h,g(f("#000","0 0 4px #000"),{top:"2px"})),c(b,c(h,f(j(e.color,i),"0 0 1px rgba(0,0,0,.1)")));return b},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}});var r=g(a("group"),{behavior:"url(#default#VML)"});return!f(r,"transform")&&r.adj?l():m=f(r,"animation"),k});var Cc,Dc,Ec=d(a),Fc=d(b),Gc="quirks"===c.hash.replace("#",""),Hc=uc.csstransforms3d,Ic=Hc&&!Gc,Jc=Hc||"CSS1Compat"===b.compatMode,Kc=vc.ok,Lc=navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i),Mc=!Ic||Lc,Nc=navigator.msPointerEnabled,Oc="onwheel"in b.createElement("div")?"wheel":b.onmousewheel!==e?"mousewheel":"DOMMouseScroll",Pc=250,Qc=300,Rc=1400,Sc=5e3,Tc=2,Uc=64,Vc=500,Wc=333,Xc="$stageFrame",Yc="$navDotFrame",Zc="$navThumbFrame",$c="auto",_c=f([.1,0,.25,1]),ad=99999,bd="50%",cd={width:null,minwidth:null,maxwidth:"100%",height:null,minheight:null,maxheight:null,ratio:null,margin:Tc,glimpse:0,fit:"contain",position:bd,thumbposition:bd,nav:"dots",navposition:"bottom",navwidth:null,thumbwidth:Uc,thumbheight:Uc,thumbmargin:Tc,thumbborderwidth:Tc,thumbfit:"cover",allowfullscreen:!1,transition:"slide",clicktransition:null,transitionduration:Qc,captions:!0,hash:!1,startindex:0,loop:!1,autoplay:!1,stopautoplayontouch:!0,keyboard:!1,arrows:!0,click:!0,swipe:!0,trackpad:!1,enableifsingleframe:!1,controlsonstart:!0,shuffle:!1,direction:"ltr",shadows:!0,spinner:null},dd={left:!0,right:!0,down:!1,up:!1,space:!1,home:!1,end:!1};G.stop=function(a){G.ii[a]=!1};var ed,fd,gd,hd;jQuery.Fotorama=function(a,e){function f(){d.each(yd,function(a,b){if(!b.i){b.i=me++;var c=A(b.video,!0);if(c){var d={};b.video=c,b.img||b.thumb?b.thumbsReady=!0:d=B(b,yd,ie),C(yd,{img:d.img,thumb:d.thumb},b.i,ie)}}})}function g(a){return Zd[a]||ie.fullScreen}function i(a){var b="keydown."+ib,c=ib+je,d="keydown."+c,f="resize."+c+" orientationchange."+c;a?(Fc.on(d,function(a){var b,c;Cd&&27===a.keyCode?(b=!0,md(Cd,!0,!0)):(ie.fullScreen||e.keyboard&&!ie.index)&&(27===a.keyCode?(b=!0,ie.cancelFullScreen()):a.shiftKey&&32===a.keyCode&&g("space")||37===a.keyCode&&g("left")||38===a.keyCode&&g("up")?c="<":32===a.keyCode&&g("space")||39===a.keyCode&&g("right")||40===a.keyCode&&g("down")?c=">":36===a.keyCode&&g("home")?c="<<":35===a.keyCode&&g("end")&&(c=">>")),(b||c)&&Y(a),c&&ie.show({index:c,slow:a.altKey,user:!0})}),ie.index||Fc.off(b).on(b,"textarea, input, select",function(a){!Dc.hasClass(jb)&&a.stopPropagation()}),Ec.on(f,ie.resize)):(Fc.off(d),Ec.off(f))}function j(b){b!==j.f&&(b?(a.html("").addClass(ib+" "+ke).append(qe).before(oe).before(pe),gb(ie)):(qe.detach(),oe.detach(),pe.detach(),a.html(ne.urtext).removeClass(ke),hb(ie)),i(b),j.f=b)}function m(){yd=ie.data=yd||P(e.data)||D(a),zd=ie.size=yd.length,!xd.ok&&e.shuffle&&O(yd),f(),Je=y(Je),zd&&j(!0)}function o(){var a=2>zd&&!e.enableifsingleframe||Cd;Me.noMove=a||Sd,Me.noSwipe=a||!e.swipe,!Wd&&se.toggleClass(Bb,!e.click&&!Me.noMove&&!Me.noSwipe),Nc&&qe.toggleClass(sb,!Me.noSwipe)}function t(a){a===!0&&(a=""),e.autoplay=Math.max(+a||Sc,1.5*Vd)}function u(){function a(a,c){b[a?"add":"remove"].push(c)}ie.options=e=R(e),Sd="crossfade"===e.transition||"dissolve"===e.transition,Md=e.loop&&(zd>2||Sd&&(!Wd||"slide"!==Wd)),Vd=+e.transitionduration||Qc,Yd="rtl"===e.direction,Zd=d.extend({},e.keyboard&&dd,e.keyboard);var b={add:[],remove:[]};zd>1||e.enableifsingleframe?(Nd=e.nav,Pd="top"===e.navposition,b.remove.push(Xb),we.toggle(!!e.arrows)):(Nd=!1,we.hide()),Rb(),Bd=new zc(d.extend(Ac,e.spinner,Bc,{direction:Yd?-1:1})),Gc(),Hc(),e.autoplay&&t(e.autoplay),Td=n(e.thumbwidth)||Uc,Ud=n(e.thumbheight)||Uc,Ne.ok=Pe.ok=e.trackpad&&!Mc,o(),ed(e,[Le]),Od="thumbs"===Nd,Od?(lc(zd,"navThumb"),Ad=Be,he=Zc,J(oe,d.Fotorama.jst.style({w:Td,h:Ud,b:e.thumbborderwidth,m:e.thumbmargin,s:je,q:!Jc})),ye.addClass(Lb).removeClass(Kb)):"dots"===Nd?(lc(zd,"navDot"),Ad=Ae,he=Yc,ye.addClass(Kb).removeClass(Lb)):(Nd=!1,ye.removeClass(Lb+" "+Kb)),Nd&&(Pd?xe.insertBefore(re):xe.insertAfter(re),wc.nav=!1,wc(Ad,ze,"nav")),Qd=e.allowfullscreen,Qd?(De.prependTo(re),Rd=Kc&&"native"===Qd):(De.detach(),Rd=!1),a(Sd,ob),a(!Sd,pb),a(!e.captions,vb),a(Yd,tb),a("always"!==e.arrows,wb),Xd=e.shadows&&!Mc,a(!Xd,rb),qe.addClass(b.add.join(" ")).removeClass(b.remove.join(" ")),Ke=d.extend({},e)}function x(a){return 0>a?(zd+a%zd)%zd:a>=zd?a%zd:a}function y(a){return h(a,0,zd-1)}function z(a){return Md?x(a):y(a)}function E(a){return a>0||Md?a-1:!1}function U(a){return zd-1>a||Md?a+1:!1}function $(){Me.min=Md?-1/0:-r(zd-1,Le.w,e.margin,Fd),Me.max=Md?1/0:-r(0,Le.w,e.margin,Fd),Me.snap=Le.w+e.margin}function bb(){Oe.min=Math.min(0,Le.nw-ze.width()),Oe.max=0,ze.toggleClass(Bb,!(Oe.noMove=Oe.min===Oe.max))}function cb(a,b,c){if("number"==typeof a){a=new Array(a);var e=!0}return d.each(a,function(a,d){if(e&&(d=a),"number"==typeof d){var f=yd[x(d)];if(f){var g="$"+b+"Frame",h=f[g];c.call(this,a,d,f,h,g,h&&h.data())}}})}function fb(a,b,c,d){(!$d||"*"===$d&&d===Ld)&&(a=q(e.width)||q(a)||Vc,b=q(e.height)||q(b)||Wc,ie.resize({width:a,ratio:e.ratio||c||a/b},0,d!==Ld&&"*"))}function Pb(a,b,c,f,g,h){cb(a,b,function(a,i,j,k,l,m){function n(a){var b=x(i);fd(a,{index:b,src:w,frame:yd[b]})}function o(){t.remove(),d.Fotorama.cache[w]="error",j.html&&"stage"===b||!y||y===w?(!w||j.html||r?"stage"===b&&(k.trigger("f:load").removeClass(ac+" "+_b).addClass(bc),n("load"),fb()):(k.trigger("f:error").removeClass(ac).addClass(_b),n("error")),m.state="error",!(zd>1&&yd[i]===j)||j.html||j.deleted||j.video||r||(j.deleted=!0,ie.splice(i,1))):(j[v]=w=y,Pb([i],b,c,f,g,!0))}function p(){d.Fotorama.measures[w]=u.measures=d.Fotorama.measures[w]||{width:s.width,height:s.height,ratio:s.width/s.height},fb(u.measures.width,u.measures.height,u.measures.ratio,i),t.off("load error").addClass(fc+(r?" "+gc:"")).prependTo(k),I(t,(d.isFunction(c)?c():c)||Le,f||j.fit||e.fit,g||j.position||e.position),d.Fotorama.cache[w]=m.state="loaded",setTimeout(function(){k.trigger("f:load").removeClass(ac+" "+_b).addClass(bc+" "+(r?cc:dc)),"stage"===b?n("load"):(j.thumbratio===$c||!j.thumbratio&&e.thumbratio===$c)&&(j.thumbratio=u.measures.ratio,vd())},0)}function q(){var a=10;G(function(){return!fe||!a--&&!Mc},function(){p()})}if(k){var r=ie.fullScreen&&j.full&&j.full!==j.img&&!m.$full&&"stage"===b;if(!m.$img||h||r){var s=new Image,t=d(s),u=t.data();m[r?"$full":"$img"]=t;var v="stage"===b?r?"full":"img":"thumb",w=j[v],y=r?null:j["stage"===b?"thumb":"img"];if("navThumb"===b&&(k=m.$wrap),!w)return void o();d.Fotorama.cache[w]?!function z(){"error"===d.Fotorama.cache[w]?o():"loaded"===d.Fotorama.cache[w]?setTimeout(q,0):setTimeout(z,100)}():(d.Fotorama.cache[w]="*",t.on("load",q).on("error",o)),m.state="",s.src=w}}})}function Qb(a){Ie.append(Bd.spin().el).appendTo(a)}function Rb(){Ie.detach(),Bd&&Bd.stop()}function Sb(){var a=Dd[Xc];a&&!a.data().state&&(Qb(a),a.on("f:load f:error",function(){a.off("f:load f:error"),Rb()}))}function ec(a){W(a,sd),X(a,function(){setTimeout(function(){Q(ye)},0),Rc({time:Vd,guessIndex:d(this).data().eq,minMax:Oe})})}function lc(a,b){cb(a,b,function(a,c,e,f,g,h){if(!f){f=e[g]=qe[g].clone(),h=f.data(),h.data=e;var i=f[0];"stage"===b?(e.html&&d('<div class="'+kc+'"></div>').append(e._html?d(e.html).removeAttr("id").html(e._html):e.html).appendTo(f),e.caption&&d(N(oc,N(pc,e.caption))).appendTo(f),e.video&&f.addClass(zb).append(Fe.clone()),X(i,function(){setTimeout(function(){Q(re)},0),pd({index:h.eq,user:!0})}),te=te.add(f)):"navDot"===b?(ec(i),Ae=Ae.add(f)):"navThumb"===b&&(ec(i),h.$wrap=f.children(":first"),Be=Be.add(f),e.video&&h.$wrap.append(Fe.clone()))}})}function sc(a,b,c,d){return a&&a.length&&I(a,b,c,d)}function tc(a){cb(a,"stage",function(a,b,c,f,g,h){if(f){var i=x(b),j=c.fit||e.fit,k=c.position||e.position;h.eq=i,Re[Xc][i]=f.css(d.extend({left:Sd?0:r(b,Le.w,e.margin,Fd)},Sd&&l(0))),F(f[0])&&(f.appendTo(se),md(c.$video)),sc(h.$img,Le,j,k),sc(h.$full,Le,j,k)}})}function uc(a,b){if("thumbs"===Nd&&!isNaN(a)){var c=-a,f=-a+Le.nw;Be.each(function(){var a=d(this),g=a.data(),h=g.eq,i=function(){return{h:Ud,w:g.w}},j=i(),k=yd[h]||{},l=k.thumbfit||e.thumbfit,m=k.thumbposition||e.thumbposition;j.w=g.w,g.l+g.w<c||g.l>f||sc(g.$img,j,l,m)||b&&Pb([h],"navThumb",i,l,m)})}}function wc(a,b,c){if(!wc[c]){var f="nav"===c&&Od,g=0;b.append(a.filter(function(){for(var a,b=d(this),c=b.data(),e=0,f=yd.length;f>e;e++)if(c.data===yd[e]){a=!0,c.eq=e;break}return a||b.remove()&&!1}).sort(function(a,b){return d(a).data().eq-d(b).data().eq}).each(function(){if(f){var a=d(this),b=a.data(),c=Math.round(Ud*b.data.thumbratio)||Td;b.l=g,b.w=c,a.css({width:c}),g+=c+e.thumbmargin}})),wc[c]=!0}}function xc(a){return a-Se>Le.w/3}function yc(a){return!(Md||Je+a&&Je-zd+a||Cd)}function Gc(){var a=yc(0),b=yc(1);ue.toggleClass(Eb,a).attr(V(a)),ve.toggleClass(Eb,b).attr(V(b))}function Hc(){Ne.ok&&(Ne.prevent={"<":yc(0),">":yc(1)})}function Lc(a){var b,c,d=a.data();return Od?(b=d.l,c=d.w):(b=a.position().left,c=a.width()),{c:b+c/2,min:-b+10*e.thumbmargin,max:-b+Le.w-c-10*e.thumbmargin}}function Oc(a){var b=Dd[he].data();_(Ce,{time:1.2*a,pos:b.l,width:b.w-2*e.thumbborderwidth})}function Rc(a){var b=yd[a.guessIndex][he];if(b){var c=Oe.min!==Oe.max,d=a.minMax||c&&Lc(Dd[he]),e=c&&(a.keep&&Rc.l?Rc.l:h((a.coo||Le.nw/2)-Lc(b).c,d.min,d.max)),f=c&&h(e,Oe.min,Oe.max),g=1.1*a.time;_(ze,{time:g,pos:f||0,onEnd:function(){uc(f,!0)}}),ld(ye,K(f,Oe.min,Oe.max)),Rc.l=e}}function Tc(){_c(he),Qe[he].push(Dd[he].addClass(Wb))}function _c(a){for(var b=Qe[a];b.length;)b.shift().removeClass(Wb)}function bd(a){var b=Re[a];d.each(Ed,function(a,c){delete b[x(c)]}),d.each(b,function(a,c){delete b[a],c.detach()})}function cd(a){Fd=Gd=Je;var b=Dd[Xc];b&&(_c(Xc),Qe[Xc].push(b.addClass(Wb)),a||ie.show.onEnd(!0),v(se,0,!0),bd(Xc),tc(Ed),$(),bb())}function ed(a,b){a&&d.each(b,function(b,c){c&&d.extend(c,{width:a.width||c.width,height:a.height,minwidth:a.minwidth,maxwidth:a.maxwidth,minheight:a.minheight,maxheight:a.maxheight,ratio:S(a.ratio)})})}function fd(b,c){a.trigger(ib+":"+b,[ie,c])}function gd(){clearTimeout(hd.t),fe=1,e.stopautoplayontouch?ie.stopAutoplay():ce=!0}function hd(){fe&&(e.stopautoplayontouch||(id(),jd()),hd.t=setTimeout(function(){fe=0},Qc+Pc))}function id(){ce=!(!Cd&&!de)}function jd(){if(clearTimeout(jd.t),G.stop(jd.w),!e.autoplay||ce)return void(ie.autoplay&&(ie.autoplay=!1,fd("stopautoplay")));ie.autoplay||(ie.autoplay=!0,fd("startautoplay"));var a=Je,b=Dd[Xc].data();jd.w=G(function(){return b.state||a!==Je},function(){jd.t=setTimeout(function(){if(!ce&&a===Je){var b=Kd,c=yd[b][Xc].data();jd.w=G(function(){return c.state||b!==Kd},function(){ce||b!==Kd||ie.show(Md?Z(!Yd):Kd)})}},e.autoplay)})}function kd(){ie.fullScreen&&(ie.fullScreen=!1,Kc&&vc.cancel(le),Dc.removeClass(jb),Cc.removeClass(jb),a.removeClass(Zb).insertAfter(pe),Le=d.extend({},ee),md(Cd,!0,!0),rd("x",!1),ie.resize(),Pb(Ed,"stage"),Q(Ec,ae,_d),fd("fullscreenexit"))}function ld(a,b){Xd&&(a.removeClass(Ub+" "+Vb),b&&!Cd&&a.addClass(b.replace(/^|\s/g," "+Tb+"--")))}function md(a,b,c){b&&(qe.removeClass(nb),Cd=!1,o()),a&&a!==Cd&&(a.remove(),fd("unloadvideo")),c&&(id(),jd())}function nd(a){qe.toggleClass(qb,a)}function od(a){if(!Me.flow){var b=a?a.pageX:od.x,c=b&&!yc(xc(b))&&e.click;od.p!==c&&re.toggleClass(Cb,c)&&(od.p=c,od.x=b)}}function pd(a){clearTimeout(pd.t),e.clicktransition&&e.clicktransition!==e.transition?setTimeout(function(){var b=e.transition;ie.setOptions({transition:e.clicktransition}),Wd=b,pd.t=setTimeout(function(){ie.show(a)},10)},0):ie.show(a)}function qd(a,b){var c=a.target,f=d(c);f.hasClass(mc)?ie.playVideo():c===Ee?ie.toggleFullScreen():Cd?c===He&&md(Cd,!0,!0):b?nd():e.click&&pd({index:a.shiftKey||Z(xc(a._x)),slow:a.altKey,user:!0})}function rd(a,b){Me[a]=Oe[a]=b}function sd(a){var b=d(this).data().eq;pd({index:b,slow:a.altKey,user:!0,coo:a._x-ye.offset().left})}function td(a){pd({index:we.index(this)?">":"<",slow:a.altKey,user:!0})}function ud(a){X(a,function(){setTimeout(function(){Q(re)},0),nd(!1)})}function vd(){if(m(),u(),!vd.i){vd.i=!0;var a=e.startindex;(a||e.hash&&c.hash)&&(Ld=L(a||c.hash.replace(/^#/,""),yd,0===ie.index||a,a)),Je=Fd=Gd=Hd=Ld=z(Ld)||0}if(zd){if(wd())return;Cd&&md(Cd,!0),Ed=[],bd(Xc),vd.ok=!0,ie.show({index:Je,time:0}),ie.resize()}else ie.destroy()}function wd(){return!wd.f===Yd?(wd.f=Yd,Je=zd-1-Je,ie.reverse(),!0):void 0}function xd(){xd.ok||(xd.ok=!0,fd("ready"))}Cc=d("html"),Dc=d("body");var yd,zd,Ad,Bd,Cd,Dd,Ed,Fd,Gd,Hd,Id,Jd,Kd,Ld,Md,Nd,Od,Pd,Qd,Rd,Sd,Td,Ud,Vd,Wd,Xd,Yd,Zd,$d,_d,ae,be,ce,de,ee,fe,ge,he,ie=this,je=d.now(),ke=ib+je,le=a[0],me=1,ne=a.data(),oe=d("<style></style>"),pe=d(N(Yb)),qe=d(N(kb)),re=d(N(xb)).appendTo(qe),se=(re[0],d(N(Ab)).appendTo(re)),te=d(),ue=d(N(Db+" "+Fb+rc)),ve=d(N(Db+" "+Gb+rc)),we=ue.add(ve).appendTo(re),xe=d(N(Ib)),ye=d(N(Hb)).appendTo(xe),ze=d(N(Jb)).appendTo(ye),Ae=d(),Be=d(),Ce=(se.data(),ze.data(),d(N(jc)).appendTo(ze)),De=d(N($b+rc)),Ee=De[0],Fe=d(N(mc)),Ge=d(N(nc)).appendTo(re),He=Ge[0],Ie=d(N(qc)),Je=!1,Ke={},Le={},Me={},Ne={},Oe={},Pe={},Qe={},Re={},Se=0,Te=[];
qe[Xc]=d(N(yb)),qe[Zc]=d(N(Mb+" "+Ob+rc,N(ic))),qe[Yc]=d(N(Mb+" "+Nb+rc,N(hc))),Qe[Xc]=[],Qe[Zc]=[],Qe[Yc]=[],Re[Xc]={},qe.addClass(Ic?mb:lb).toggleClass(qb,!e.controlsonstart),ne.fotorama=this,ie.startAutoplay=function(a){return ie.autoplay?this:(ce=de=!1,t(a||e.autoplay),jd(),this)},ie.stopAutoplay=function(){return ie.autoplay&&(ce=de=!0,jd()),this},ie.show=function(a){var b;"object"!=typeof a?(b=a,a={}):b=a.index,b=">"===b?Gd+1:"<"===b?Gd-1:"<<"===b?0:">>"===b?zd-1:b,b=isNaN(b)?L(b,yd,!0):b,b="undefined"==typeof b?Je||0:b,ie.activeIndex=Je=z(b),Id=E(Je),Jd=U(Je),Kd=x(Je+(Yd?-1:1)),Ed=[Je,Id,Jd],Gd=Md?b:Je;var c=Math.abs(Hd-Gd),d=w(a.time,function(){return Math.min(Vd*(1+(c-1)/12),2*Vd)}),f=a.overPos;a.slow&&(d*=10);var g=Dd;ie.activeFrame=Dd=yd[Je];var i=g===Dd&&!a.user;md(Cd,Dd.i!==yd[x(Fd)].i),lc(Ed,"stage"),tc(Mc?[Gd]:[Gd,E(Gd),U(Gd)]),rd("go",!0),i||fd("show",{user:a.user,time:d}),ce=!0;var j=ie.show.onEnd=function(b){if(!j.ok){if(j.ok=!0,b||cd(!0),i||fd("showend",{user:a.user}),!b&&Wd&&Wd!==e.transition)return ie.setOptions({transition:Wd}),void(Wd=!1);Sb(),Pb(Ed,"stage"),rd("go",!1),Hc(),od(),id(),jd()}};if(Sd){var k=Dd[Xc],l=Je!==Hd?yd[Hd][Xc]:null;ab(k,l,te,{time:d,method:e.transition,onEnd:j},Te)}else _(se,{pos:-r(Gd,Le.w,e.margin,Fd),overPos:f,time:d,onEnd:j});if(Gc(),Nd){Tc();var m=y(Je+h(Gd-Hd,-1,1));Rc({time:d,coo:m!==Je&&a.coo,guessIndex:"undefined"!=typeof a.coo?m:Je,keep:i}),Od&&Oc(d)}return be="undefined"!=typeof Hd&&Hd!==Je,Hd=Je,e.hash&&be&&!ie.eq&&H(Dd.id||Je+1),this},ie.requestFullScreen=function(){return Qd&&!ie.fullScreen&&(_d=Ec.scrollTop(),ae=Ec.scrollLeft(),Q(Ec),rd("x",!0),ee=d.extend({},Le),a.addClass(Zb).appendTo(Dc.addClass(jb)),Cc.addClass(jb),md(Cd,!0,!0),ie.fullScreen=!0,Rd&&vc.request(le),ie.resize(),Pb(Ed,"stage"),Sb(),fd("fullscreenenter")),this},ie.cancelFullScreen=function(){return Rd&&vc.is()?vc.cancel(b):kd(),this},ie.toggleFullScreen=function(){return ie[(ie.fullScreen?"cancel":"request")+"FullScreen"]()},T(b,vc.event,function(){!yd||vc.is()||Cd||kd()}),ie.resize=function(a){if(!yd)return this;var b=arguments[1]||0,c=arguments[2];ed(ie.fullScreen?{width:"100%",maxwidth:null,minwidth:null,height:"100%",maxheight:null,minheight:null}:R(a),[Le,c||ie.fullScreen||e]);var d=Le.width,f=Le.height,g=Le.ratio,i=Ec.height()-(Nd?ye.height():0);return q(d)&&(qe.addClass(ub).css({width:d,minWidth:Le.minwidth||0,maxWidth:Le.maxwidth||ad}),d=Le.W=Le.w=qe.width(),Le.nw=Nd&&p(e.navwidth,d)||d,e.glimpse&&(Le.w-=Math.round(2*(p(e.glimpse,d)||0))),se.css({width:Le.w,marginLeft:(Le.W-Le.w)/2}),f=p(f,i),f=f||g&&d/g,f&&(d=Math.round(d),f=Le.h=Math.round(h(f,p(Le.minheight,i),p(Le.maxheight,i))),re.stop().animate({width:d,height:f},b,function(){qe.removeClass(ub)}),cd(),Nd&&(ye.stop().animate({width:Le.nw},b),Rc({guessIndex:Je,time:b,keep:!0}),Od&&wc.nav&&Oc(b)),$d=c||!0,xd())),Se=re.offset().left,this},ie.setOptions=function(a){return d.extend(e,a),vd(),this},ie.shuffle=function(){return yd&&O(yd)&&vd(),this},ie.destroy=function(){return ie.cancelFullScreen(),ie.stopAutoplay(),yd=ie.data=null,j(),Ed=[],bd(Xc),vd.ok=!1,this},ie.playVideo=function(){var a=Dd,b=a.video,c=Je;return"object"==typeof b&&a.videoReady&&(Rd&&ie.fullScreen&&ie.cancelFullScreen(),G(function(){return!vc.is()||c!==Je},function(){c===Je&&(a.$video=a.$video||d(d.Fotorama.jst.video(b)),a.$video.appendTo(a[Xc]),qe.addClass(nb),Cd=a.$video,o(),we.blur(),De.blur(),fd("loadvideo"))})),this},ie.stopVideo=function(){return md(Cd,!0,!0),this},re.on("mousemove",od),Me=db(se,{onStart:gd,onMove:function(a,b){ld(re,b.edge)},onTouchEnd:hd,onEnd:function(a){ld(re);var b=(Nc&&!ge||a.touch)&&e.arrows&&"always"!==e.arrows;if(a.moved||b&&a.pos!==a.newPos&&!a.control){var c=s(a.newPos,Le.w,e.margin,Fd);ie.show({index:c,time:Sd?Vd:a.time,overPos:a.overPos,user:!0})}else a.aborted||a.control||qd(a.startEvent,b)},timeLow:1,timeHigh:1,friction:2,select:"."+Xb+", ."+Xb+" *",$wrap:re}),Oe=db(ze,{onStart:gd,onMove:function(a,b){ld(ye,b.edge)},onTouchEnd:hd,onEnd:function(a){function b(){Rc.l=a.newPos,id(),jd(),uc(a.newPos,!0)}if(a.moved)a.pos!==a.newPos?(ce=!0,_(ze,{time:a.time,pos:a.newPos,overPos:a.overPos,onEnd:b}),uc(a.newPos),Xd&&ld(ye,K(a.newPos,Oe.min,Oe.max))):b();else{var c=a.$target.closest("."+Mb,ze)[0];c&&sd.call(c,a.startEvent)}},timeLow:.5,timeHigh:2,friction:5,$wrap:ye}),Ne=eb(re,{shift:!0,onEnd:function(a,b){gd(),hd(),ie.show({index:b,slow:a.altKey})}}),Pe=eb(ye,{onEnd:function(a,b){gd(),hd();var c=v(ze)+.25*b;ze.css(k(h(c,Oe.min,Oe.max))),Xd&&ld(ye,K(c,Oe.min,Oe.max)),Pe.prevent={"<":c>=Oe.max,">":c<=Oe.min},clearTimeout(Pe.t),Pe.t=setTimeout(function(){Rc.l=c,uc(c,!0)},Pc),uc(c)}}),qe.hover(function(){setTimeout(function(){fe||nd(!(ge=!0))},0)},function(){ge&&nd(!(ge=!1))}),M(we,function(a){Y(a),td.call(this,a)},{onStart:function(){gd(),Me.control=!0},onTouchEnd:hd}),we.each(function(){W(this,function(a){td.call(this,a)}),ud(this)}),W(Ee,ie.toggleFullScreen),ud(Ee),d.each("load push pop shift unshift reverse sort splice".split(" "),function(a,b){ie[b]=function(){return yd=yd||[],"load"!==b?Array.prototype[b].apply(yd,arguments):arguments[0]&&"object"==typeof arguments[0]&&arguments[0].length&&(yd=P(arguments[0])),vd(),ie}}),vd()},d.fn.fotorama=function(b){return this.each(function(){var c=this,e=d(this),f=e.data(),g=f.fotorama;g?g.setOptions(b,!0):G(function(){return!E(c)},function(){f.urtext=e.html(),new d.Fotorama(e,d.extend({},cd,a.fotoramaDefaults,b,f))})})},d.Fotorama.instances=[],d.Fotorama.cache={},d.Fotorama.measures={},d=d||{},d.Fotorama=d.Fotorama||{},d.Fotorama.jst=d.Fotorama.jst||{},d.Fotorama.jst.style=function(a){{var b,c="";tc.escape}return c+=".fotorama"+(null==(b=a.s)?"":b)+" .fotorama__nav--thumbs .fotorama__nav__frame{\npadding:"+(null==(b=a.m)?"":b)+"px;\nheight:"+(null==(b=a.h)?"":b)+"px}\n.fotorama"+(null==(b=a.s)?"":b)+" .fotorama__thumb-border{\nheight:"+(null==(b=a.h-a.b*(a.q?0:2))?"":b)+"px;\nborder-width:"+(null==(b=a.b)?"":b)+"px;\nmargin-top:"+(null==(b=a.m)?"":b)+"px}"},d.Fotorama.jst.video=function(a){function b(){c+=d.call(arguments,"")}var c="",d=(tc.escape,Array.prototype.join);return c+='<div class="fotorama__video"><iframe src="',b(("youtube"==a.type?a.p+"youtube.com/embed/"+a.id+"?autoplay=1":"vimeo"==a.type?a.p+"player.vimeo.com/video/"+a.id+"?autoplay=1&badge=0":a.id)+(a.s&&"custom"!=a.type?"&"+a.s:"")),c+='" frameborder="0" allowfullscreen></iframe></div>\n'},d(function(){d("."+ib+':not([data-auto="false"])').fotorama()})}(window,document,location,"undefined"!=typeof jQuery&&jQuery);;