/*!

 handlebars v3.0.3

Copyright (C) 2011-2014 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(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(8)["default"];b.__esModule=!0;var f=c(1),g=e(f),h=c(2),i=e(h),j=c(3),k=c(4),l=c(5),m=e(l),n=c(6),o=e(n),p=c(7),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=new g.HandlebarsEnvironment;return m.extend(a,g),a.SafeString=i["default"],a.Exception=k["default"],a.Utils=m,a.escapeExpression=m.escapeExpression,a.VM=o,a.template=function(b){return o.template(b,a)},a}var e=c(8)["default"];b.__esModule=!0;var f=c(9),g=e(f),h=c(10),i=e(h),j=c(11),k=e(j),l=c(12),m=e(l),n=c(13),o=e(n),p=c(7),q=e(p),r=d();r.create=d,q["default"](r),r["default"]=r,b["default"]=r,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c={Program:function(a,b,c,d){this.loc=d,this.type="Program",this.body=a,this.blockParams=b,this.strip=c},MustacheStatement:function(a,b,c,d,e,f){this.loc=f,this.type="MustacheStatement",this.path=a,this.params=b||[],this.hash=c,this.escaped=d,this.strip=e},BlockStatement:function(a,b,c,d,e,f,g,h,i){this.loc=i,this.type="BlockStatement",this.path=a,this.params=b||[],this.hash=c,this.program=d,this.inverse=e,this.openStrip=f,this.inverseStrip=g,this.closeStrip=h},PartialStatement:function(a,b,c,d,e){this.loc=e,this.type="PartialStatement",this.name=a,this.params=b||[],this.hash=c,this.indent="",this.strip=d},ContentStatement:function(a,b){this.loc=b,this.type="ContentStatement",this.original=this.value=a},CommentStatement:function(a,b,c){this.loc=c,this.type="CommentStatement",this.value=a,this.strip=b},SubExpression:function(a,b,c,d){this.loc=d,this.type="SubExpression",this.path=a,this.params=b||[],this.hash=c},PathExpression:function(a,b,c,d,e){this.loc=e,this.type="PathExpression",this.data=a,this.original=d,this.parts=c,this.depth=b},StringLiteral:function(a,b){this.loc=b,this.type="StringLiteral",this.original=this.value=a},NumberLiteral:function(a,b){this.loc=b,this.type="NumberLiteral",this.original=this.value=Number(a)},BooleanLiteral:function(a,b){this.loc=b,this.type="BooleanLiteral",this.original=this.value="true"===a},UndefinedLiteral:function(a){this.loc=a,this.type="UndefinedLiteral",this.original=this.value=void 0},NullLiteral:function(a){this.loc=a,this.type="NullLiteral",this.original=this.value=null},Hash:function(a,b){this.loc=b,this.type="Hash",this.pairs=a},HashPair:function(a,b,c){this.loc=c,this.type="HashPair",this.key=a,this.value=b},helpers:{helperExpression:function(a){return!("SubExpression"!==a.type&&!a.params.length&&!a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;g["default"].yy=o,o.locInfo=function(a){return new o.SourceLocation(b&&b.srcName,a)};var c=new k["default"];return c.accept(g["default"].parse(a))}var e=c(8)["default"];b.__esModule=!0,b.parse=d;var f=c(14),g=e(f),h=c(2),i=e(h),j=c(15),k=e(j),l=c(16),m=e(l),n=c(12);b.parser=g["default"];var o={};n.extend(o,m,i["default"])},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var b=c.parse(a,f),d=(new c.Compiler).compile(b,f),e=(new c.JavaScriptCompiler).compile(d,f,void 0,!0);return c.template(e)}function e(a,b){return g||(g=d()),g.call(this,a,b)}var f=void 0===arguments[1]?{}:arguments[1];if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);"data"in f||(f.data=!0),f.compat&&(f.useDepths=!0);var g=void 0;return e._setup=function(a){return g||(g=d()),g._setup(a)},e._child=function(a,b,c,e){return g||(g=d()),g._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path=new n["default"].PathExpression(!1,0,[b.original+""],b.original+"",b.loc)}}var i=c(8)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(11),k=i(j),l=c(12),m=c(2),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;b>c;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;b>c;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(b.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;c>d;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},PartialStatement:function(a){this.usePartial=!0;var b=a.params;if(b.length>1)throw new k["default"]("Unsupported number of partial arguments: "+b.length,a);b.length||b.push({type:"PathExpression",parts:[],depth:0});var c=a.name.original,d="SubExpression"===a.name.type;d&&this.accept(a.name),this.setupFullMustacheParams(a,void 0,void 0,!0);var e=a.indent||"";this.options.preventIndent&&e&&(this.opcode("appendContent",e),e=""),this.opcode("invokePartial",d,c,e),this.opcode("append")},MustacheStatement:function(a){this.SubExpression(a),this.opcode(a.escaped&&!this.options.noEscape?"appendEscaped":"append")},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){this.accept(a.path),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts)):this.opcode("lookupOnContext",a.parts,a.falsy,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");d>c;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;c>b;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^\.\//g,"").replace(/^\.$/g,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;c>b;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;g>f;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("this.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(8)["default"];b.__esModule=!0;var h=c(9),i=c(11),j=g(i),k=c(12),l=c(17),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"['",b,"']"]},depthedLookup:function(a){return[this.aliasable("this.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;i>h;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k},m=this.context.programs;for(h=0,i=m.length;i>h;h++)m[h]&&(l[h]=m[h]);return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n  ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend("  + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("this.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c){var d=0;c||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[d++])),this.resolvePath("context",a,d,b)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b){this.pushStackLiteral(a?"this.data(data, "+a+")":"data"),this.resolvePath("data",b,0,!0)},resolvePath:function(a,b,c,d){var e=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict,this,b,a));for(var g=b.length;g>c;c++)this.replaceStack(function(f){var g=e.nameLookup(f,b[c],a);return d?[" && ",g]:[" != null ? ",g," : ",f]})},resolvePossibleLambda:function(){this.push([this.aliasable("this.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){this.pushStackLiteral(null!=a?this.programExpression(a):null)},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d,!1);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",d.unshift(a?b:this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("this.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):this.pushStackLiteral("SubExpression"===a?"true":"null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;g>f;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);null==h?(this.context.programs.push(""),h=this.context.programs.length,d.index=h,d.name="program"+h,this.context.programs[h]=e.compile(d,b,this.context,!this.precompile),this.context.environments[h]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams):(d.index=h,d.name="program"+h,this.useDepths=this.useDepths||d.useDepths,this.useBlockParams=this.useBlockParams||d.useBlockParams)}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;c>b;b++){var d=this.context.environments[b];if(d&&d.equals(a))return b}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"this.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;c>b;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper");return{params:d,paramsInit:e,name:f,callParams:[this.contextName(0)].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=void 0;d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var i=this.popStack(),j=this.popStack();(j||i)&&(d.fn=j||"this.noop",d.inverse=i||"this.noop");for(var k=b;k--;)h=this.popStack(),c[k]=h,this.trackIds&&(g[k]=this.popStack()),this.stringParams&&(f[k]=this.popStack(),e[k]=this.popStack());return this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c,!0);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):(c.push(e),"")}},function(){for(var a="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(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;d>c;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}var e=c(8)["default"];b.__esModule=!0;var f=c(11),g=e(f),h=c(2),i=e(h);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&(!c.type||!i["default"][c.type]))throw new g["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new g["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;c>b;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:function(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")},BlockStatement:function(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash"),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")},PartialStatement:function(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:function(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")},PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){b.Handlebars===a&&(b.Handlebars=d)}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b){this.helpers=a||{},this.partials=b||{},e(this)}function e(a){a.registerHelper("helperMissing",function(){if(1===arguments.length)return void 0;throw new k["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')}),a.registerHelper("blockHelperMissing",function(b,c){var d=c.inverse,e=c.fn;if(b===!0)return e(this);if(b===!1||null==b)return d(this);if(o(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):d(this);if(c.data&&c.ids){var g=f(c.data);g.contextPath=i.appendContextPath(c.data.contextPath,c.name),c={data:g}}return e(b,c)}),a.registerHelper("each",function(a,b){function c(b,c,e){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!e,l&&(j.contextPath=l+b)),h+=d(a[b],{data:j,blockParams:i.blockParams([a[b],b],[l+b,null])})}if(!b)throw new k["default"]("Must pass iterator to #each");var d=b.fn,e=b.inverse,g=0,h="",j=void 0,l=void 0;if(b.data&&b.ids&&(l=i.appendContextPath(b.data.contextPath,b.ids[0])+"."),p(a)&&(a=a.call(this)),b.data&&(j=f(b.data)),a&&"object"==typeof a)if(o(a))for(var m=a.length;m>g;g++)c(g,g,g===a.length-1);else{var n=void 0;for(var q in a)a.hasOwnProperty(q)&&(n&&c(n,g-1),n=q,g++);n&&c(n,g-1,!0)}return 0===g&&(h=e(this)),h}),a.registerHelper("if",function(a,b){return p(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||i.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){p(a)&&(a=a.call(this));var c=b.fn;if(i.isEmpty(a))return b.inverse(this);if(b.data&&b.ids){var d=f(b.data);d.contextPath=i.appendContextPath(b.data.contextPath,b.ids[0]),b={data:d}}return c(a,b)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)}),a.registerHelper("lookup",function(a,b){return a&&a[b]})}function f(a){var b=i.extend({},a);return b._parent=a,b}var g=c(8)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d,b.createFrame=f;var h=c(12),i=g(h),j=c(11),k=g(j),l="3.0.1";b.VERSION=l;var m=6;b.COMPILER_REVISION=m;var n={1:"<= 1.0.rc.2",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"};b.REVISION_CHANGES=n;var o=i.isArray,p=i.isFunction,q=i.toString,r="[object Object]";d.prototype={constructor:d,logger:s,log:t,registerHelper:function(a,b){if(q.call(a)===r){if(b)throw new k["default"]("Arg not supported with multiple helpers");i.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(q.call(a)===r)i.extend(this.partials,a);else{if("undefined"==typeof b)throw new k["default"]("Attempting to register a partial as undefined");this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]}};var s={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:1,log:function(a,b){if("undefined"!=typeof console&&s.level<=a){var c=s.methodMap[a];(console[c]||console.log).call(console,b)}}};b.logger=s;var t=s.log;b.log=t},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b){"use strict";function c(a,b){var e=b&&b.loc,f=void 0,g=void 0;e&&(f=e.start.line,g=e.start.column,a+=" - "+f+":"+g);for(var h=Error.prototype.constructor.call(this,a),i=0;i<d.length;i++)this[d[i]]=h[d[i]];Error.captureStackTrace&&Error.captureStackTrace(this,c),e&&(this.lineNumber=f,this.column=g)}b.__esModule=!0;var d=["description","fileName","lineNumber","message","name","number","stack"];c.prototype=new Error,b["default"]=c,a.exports=b["default"]},function(a,b){"use strict";function c(a){return j[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return l.test(a)?a.replace(k,c):a}function g(a){return a||0===a?o(a)&&0===a.length?!0:!1:!0}function h(a,b){return a.path=b,a}function i(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.blockParams=h,b.appendContextPath=i;var j={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},k=/[&<>"'`]/g,l=/[&<>"'`]/,m=Object.prototype.toString;b.toString=m;var n=function(a){return"function"==typeof a};n(/x/)&&(b.isFunction=n=function(a){return"function"==typeof a&&"[object Function]"===m.call(a)});var n;b.isFunction=n;var o=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===m.call(a):!1};b.isArray=o},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=p.COMPILER_REVISION;if(b!==c){if(c>b){var d=p.REVISION_CHANGES[c],e=p.REVISION_CHANGES[b];throw new o["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new o["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=m.extend({},d,e.hash)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;i>h&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new o["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){var c=void 0===arguments[1]?{}:arguments[1],f=c.data;
d._setup(c),!c.partial&&a.useData&&(f=j(b,f));var g=void 0,h=a.useBlockParams?[]:void 0;return a.useDepths&&(g=c.depths?[b].concat(c.depths):[b]),a.main.call(e,b,e.helpers,e.partials,f,h,g)}if(!b)throw new o["default"]("No environment passed to template");if(!a||!a.main)throw new o["default"]("Unknown template object: "+typeof a);b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new o["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;c>d;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:m.escapeExpression,invokePartial:c,fn:function(b){return a[b]},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=m.extend({},b,a)),c},noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new o["default"]("must pass block params");if(a.useDepths&&!g)throw new o["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=void 0===arguments[1]?{}:arguments[1];return c.call(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),g&&[b].concat(g))}return h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a=c.partials[c.name],a}function h(a,b,c){if(c.partial=!0,void 0===a)throw new o["default"]("The partial "+c.name+" could not be found");return a instanceof Function?a(b,c):void 0}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?p.createFrame(b):{},b.root=a),b}var k=c(8)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var l=c(12),m=k(l),n=c(11),o=k(n),p=c(9)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,content:12,COMMENT:13,CONTENT:14,openRawBlock:15,END_RAW_BLOCK:16,OPEN_RAW_BLOCK:17,helperName:18,openRawBlock_repetition0:19,openRawBlock_option0:20,CLOSE_RAW_BLOCK:21,openBlock:22,block_option0:23,closeBlock:24,openInverse:25,block_option1:26,OPEN_BLOCK:27,openBlock_repetition0:28,openBlock_option0:29,openBlock_option1:30,CLOSE:31,OPEN_INVERSE:32,openInverse_repetition0:33,openInverse_option0:34,openInverse_option1:35,openInverseChain:36,OPEN_INVERSE_CHAIN:37,openInverseChain_repetition0:38,openInverseChain_option0:39,openInverseChain_option1:40,inverseAndProgram:41,INVERSE:42,inverseChain:43,inverseChain_option0:44,OPEN_ENDBLOCK:45,OPEN:46,mustache_repetition0:47,mustache_option0:48,OPEN_UNESCAPED:49,mustache_repetition1:50,mustache_option1:51,CLOSE_UNESCAPED:52,OPEN_PARTIAL:53,partialName:54,partial_repetition0:55,partial_option0:56,param:57,sexpr:58,OPEN_SEXPR:59,sexpr_repetition0:60,sexpr_option0:61,CLOSE_SEXPR:62,hash:63,hash_repetition_plus0:64,hashSegment:65,ID:66,EQUALS:67,blockParams:68,OPEN_BLOCK_PARAMS:69,blockParams_repetition_plus0:70,CLOSE_BLOCK_PARAMS:71,path:72,dataName:73,STRING:74,NUMBER:75,BOOLEAN:76,UNDEFINED:77,NULL:78,DATA:79,pathSegments:80,SEP:81,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",13:"COMMENT",14:"CONTENT",16:"END_RAW_BLOCK",17:"OPEN_RAW_BLOCK",21:"CLOSE_RAW_BLOCK",27:"OPEN_BLOCK",31:"CLOSE",32:"OPEN_INVERSE",37:"OPEN_INVERSE_CHAIN",42:"INVERSE",45:"OPEN_ENDBLOCK",46:"OPEN",49:"OPEN_UNESCAPED",52:"CLOSE_UNESCAPED",53:"OPEN_PARTIAL",59:"OPEN_SEXPR",62:"CLOSE_SEXPR",66:"ID",67:"EQUALS",69:"OPEN_BLOCK_PARAMS",71:"CLOSE_BLOCK_PARAMS",74:"STRING",75:"NUMBER",76:"BOOLEAN",77:"UNDEFINED",78:"NULL",79:"DATA",81:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[12,1],[10,3],[15,5],[9,4],[9,4],[22,6],[25,6],[36,6],[41,2],[43,3],[43,1],[24,3],[8,5],[8,5],[11,5],[57,1],[57,1],[58,5],[63,1],[65,3],[68,3],[18,1],[18,1],[18,1],[18,1],[18,1],[18,1],[18,1],[54,1],[54,1],[73,2],[72,1],[80,3],[80,1],[6,0],[6,2],[19,0],[19,2],[20,0],[20,1],[23,0],[23,1],[26,0],[26,1],[28,0],[28,2],[29,0],[29,1],[30,0],[30,1],[33,0],[33,2],[34,0],[34,1],[35,0],[35,1],[38,0],[38,2],[39,0],[39,1],[40,0],[40,1],[44,0],[44,1],[47,0],[47,2],[48,0],[48,1],[50,0],[50,2],[51,0],[51,1],[55,0],[55,2],[56,0],[56,1],[60,0],[60,2],[61,0],[61,1],[64,1],[64,2],[70,1],[70,2]],performAction:function(a,b,c,d,e,f){var g=f.length-1;switch(e){case 1:return f[g-1];case 2:this.$=new d.Program(f[g],null,{},d.locInfo(this._$));break;case 3:this.$=f[g];break;case 4:this.$=f[g];break;case 5:this.$=f[g];break;case 6:this.$=f[g];break;case 7:this.$=f[g];break;case 8:this.$=new d.CommentStatement(d.stripComment(f[g]),d.stripFlags(f[g],f[g]),d.locInfo(this._$));break;case 9:this.$=new d.ContentStatement(f[g],d.locInfo(this._$));break;case 10:this.$=d.prepareRawBlock(f[g-2],f[g-1],f[g],this._$);break;case 11:this.$={path:f[g-3],params:f[g-2],hash:f[g-1]};break;case 12:this.$=d.prepareBlock(f[g-3],f[g-2],f[g-1],f[g],!1,this._$);break;case 13:this.$=d.prepareBlock(f[g-3],f[g-2],f[g-1],f[g],!0,this._$);break;case 14:this.$={path:f[g-4],params:f[g-3],hash:f[g-2],blockParams:f[g-1],strip:d.stripFlags(f[g-5],f[g])};break;case 15:this.$={path:f[g-4],params:f[g-3],hash:f[g-2],blockParams:f[g-1],strip:d.stripFlags(f[g-5],f[g])};break;case 16:this.$={path:f[g-4],params:f[g-3],hash:f[g-2],blockParams:f[g-1],strip:d.stripFlags(f[g-5],f[g])};break;case 17:this.$={strip:d.stripFlags(f[g-1],f[g-1]),program:f[g]};break;case 18:var h=d.prepareBlock(f[g-2],f[g-1],f[g],f[g],!1,this._$),i=new d.Program([h],null,{},d.locInfo(this._$));i.chained=!0,this.$={strip:f[g-2].strip,program:i,chain:!0};break;case 19:this.$=f[g];break;case 20:this.$={path:f[g-1],strip:d.stripFlags(f[g-2],f[g])};break;case 21:this.$=d.prepareMustache(f[g-3],f[g-2],f[g-1],f[g-4],d.stripFlags(f[g-4],f[g]),this._$);break;case 22:this.$=d.prepareMustache(f[g-3],f[g-2],f[g-1],f[g-4],d.stripFlags(f[g-4],f[g]),this._$);break;case 23:this.$=new d.PartialStatement(f[g-3],f[g-2],f[g-1],d.stripFlags(f[g-4],f[g]),d.locInfo(this._$));break;case 24:this.$=f[g];break;case 25:this.$=f[g];break;case 26:this.$=new d.SubExpression(f[g-3],f[g-2],f[g-1],d.locInfo(this._$));break;case 27:this.$=new d.Hash(f[g],d.locInfo(this._$));break;case 28:this.$=new d.HashPair(d.id(f[g-2]),f[g],d.locInfo(this._$));break;case 29:this.$=d.id(f[g-1]);break;case 30:this.$=f[g];break;case 31:this.$=f[g];break;case 32:this.$=new d.StringLiteral(f[g],d.locInfo(this._$));break;case 33:this.$=new d.NumberLiteral(f[g],d.locInfo(this._$));break;case 34:this.$=new d.BooleanLiteral(f[g],d.locInfo(this._$));break;case 35:this.$=new d.UndefinedLiteral(d.locInfo(this._$));break;case 36:this.$=new d.NullLiteral(d.locInfo(this._$));break;case 37:this.$=f[g];break;case 38:this.$=f[g];break;case 39:this.$=d.preparePath(!0,f[g],this._$);break;case 40:this.$=d.preparePath(!1,f[g],this._$);break;case 41:f[g-2].push({part:d.id(f[g]),original:f[g],separator:f[g-1]}),this.$=f[g-2];break;case 42:this.$=[{part:d.id(f[g]),original:f[g]}];break;case 43:this.$=[];break;case 44:f[g-1].push(f[g]);break;case 45:this.$=[];break;case 46:f[g-1].push(f[g]);break;case 53:this.$=[];break;case 54:f[g-1].push(f[g]);break;case 59:this.$=[];break;case 60:f[g-1].push(f[g]);break;case 65:this.$=[];break;case 66:f[g-1].push(f[g]);break;case 73:this.$=[];break;case 74:f[g-1].push(f[g]);break;case 77:this.$=[];break;case 78:f[g-1].push(f[g]);break;case 81:this.$=[];break;case 82:f[g-1].push(f[g]);break;case 85:this.$=[];break;case 86:f[g-1].push(f[g]);break;case 89:this.$=[f[g]];break;case 90:f[g-1].push(f[g]);break;case 91:this.$=[f[g]];break;case 92:f[g-1].push(f[g])}},table:[{3:1,4:2,5:[2,43],6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],46:[2,43],49:[2,43],53:[2,43]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:[1,11],14:[1,18],15:16,17:[1,21],22:14,25:15,27:[1,19],32:[1,20],37:[2,2],42:[2,2],45:[2,2],46:[1,12],49:[1,13],53:[1,17]},{1:[2,1]},{5:[2,44],13:[2,44],14:[2,44],17:[2,44],27:[2,44],32:[2,44],37:[2,44],42:[2,44],45:[2,44],46:[2,44],49:[2,44],53:[2,44]},{5:[2,3],13:[2,3],14:[2,3],17:[2,3],27:[2,3],32:[2,3],37:[2,3],42:[2,3],45:[2,3],46:[2,3],49:[2,3],53:[2,3]},{5:[2,4],13:[2,4],14:[2,4],17:[2,4],27:[2,4],32:[2,4],37:[2,4],42:[2,4],45:[2,4],46:[2,4],49:[2,4],53:[2,4]},{5:[2,5],13:[2,5],14:[2,5],17:[2,5],27:[2,5],32:[2,5],37:[2,5],42:[2,5],45:[2,5],46:[2,5],49:[2,5],53:[2,5]},{5:[2,6],13:[2,6],14:[2,6],17:[2,6],27:[2,6],32:[2,6],37:[2,6],42:[2,6],45:[2,6],46:[2,6],49:[2,6],53:[2,6]},{5:[2,7],13:[2,7],14:[2,7],17:[2,7],27:[2,7],32:[2,7],37:[2,7],42:[2,7],45:[2,7],46:[2,7],49:[2,7],53:[2,7]},{5:[2,8],13:[2,8],14:[2,8],17:[2,8],27:[2,8],32:[2,8],37:[2,8],42:[2,8],45:[2,8],46:[2,8],49:[2,8],53:[2,8]},{18:22,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:33,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{4:34,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],37:[2,43],42:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{4:35,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],42:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{12:36,14:[1,18]},{18:38,54:37,58:39,59:[1,40],66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{5:[2,9],13:[2,9],14:[2,9],16:[2,9],17:[2,9],27:[2,9],32:[2,9],37:[2,9],42:[2,9],45:[2,9],46:[2,9],49:[2,9],53:[2,9]},{18:41,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:42,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:43,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{31:[2,73],47:44,59:[2,73],66:[2,73],74:[2,73],75:[2,73],76:[2,73],77:[2,73],78:[2,73],79:[2,73]},{21:[2,30],31:[2,30],52:[2,30],59:[2,30],62:[2,30],66:[2,30],69:[2,30],74:[2,30],75:[2,30],76:[2,30],77:[2,30],78:[2,30],79:[2,30]},{21:[2,31],31:[2,31],52:[2,31],59:[2,31],62:[2,31],66:[2,31],69:[2,31],74:[2,31],75:[2,31],76:[2,31],77:[2,31],78:[2,31],79:[2,31]},{21:[2,32],31:[2,32],52:[2,32],59:[2,32],62:[2,32],66:[2,32],69:[2,32],74:[2,32],75:[2,32],76:[2,32],77:[2,32],78:[2,32],79:[2,32]},{21:[2,33],31:[2,33],52:[2,33],59:[2,33],62:[2,33],66:[2,33],69:[2,33],74:[2,33],75:[2,33],76:[2,33],77:[2,33],78:[2,33],79:[2,33]},{21:[2,34],31:[2,34],52:[2,34],59:[2,34],62:[2,34],66:[2,34],69:[2,34],74:[2,34],75:[2,34],76:[2,34],77:[2,34],78:[2,34],79:[2,34]},{21:[2,35],31:[2,35],52:[2,35],59:[2,35],62:[2,35],66:[2,35],69:[2,35],74:[2,35],75:[2,35],76:[2,35],77:[2,35],78:[2,35],79:[2,35]},{21:[2,36],31:[2,36],52:[2,36],59:[2,36],62:[2,36],66:[2,36],69:[2,36],74:[2,36],75:[2,36],76:[2,36],77:[2,36],78:[2,36],79:[2,36]},{21:[2,40],31:[2,40],52:[2,40],59:[2,40],62:[2,40],66:[2,40],69:[2,40],74:[2,40],75:[2,40],76:[2,40],77:[2,40],78:[2,40],79:[2,40],81:[1,45]},{66:[1,32],80:46},{21:[2,42],31:[2,42],52:[2,42],59:[2,42],62:[2,42],66:[2,42],69:[2,42],74:[2,42],75:[2,42],76:[2,42],77:[2,42],78:[2,42],79:[2,42],81:[2,42]},{50:47,52:[2,77],59:[2,77],66:[2,77],74:[2,77],75:[2,77],76:[2,77],77:[2,77],78:[2,77],79:[2,77]},{23:48,36:50,37:[1,52],41:51,42:[1,53],43:49,45:[2,49]},{26:54,41:55,42:[1,53],45:[2,51]},{16:[1,56]},{31:[2,81],55:57,59:[2,81],66:[2,81],74:[2,81],75:[2,81],76:[2,81],77:[2,81],78:[2,81],79:[2,81]},{31:[2,37],59:[2,37],66:[2,37],74:[2,37],75:[2,37],76:[2,37],77:[2,37],78:[2,37],79:[2,37]},{31:[2,38],59:[2,38],66:[2,38],74:[2,38],75:[2,38],76:[2,38],77:[2,38],78:[2,38],79:[2,38]},{18:58,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{28:59,31:[2,53],59:[2,53],66:[2,53],69:[2,53],74:[2,53],75:[2,53],76:[2,53],77:[2,53],78:[2,53],79:[2,53]},{31:[2,59],33:60,59:[2,59],66:[2,59],69:[2,59],74:[2,59],75:[2,59],76:[2,59],77:[2,59],78:[2,59],79:[2,59]},{19:61,21:[2,45],59:[2,45],66:[2,45],74:[2,45],75:[2,45],76:[2,45],77:[2,45],78:[2,45],79:[2,45]},{18:65,31:[2,75],48:62,57:63,58:66,59:[1,40],63:64,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{66:[1,70]},{21:[2,39],31:[2,39],52:[2,39],59:[2,39],62:[2,39],66:[2,39],69:[2,39],74:[2,39],75:[2,39],76:[2,39],77:[2,39],78:[2,39],79:[2,39],81:[1,45]},{18:65,51:71,52:[2,79],57:72,58:66,59:[1,40],63:73,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{24:74,45:[1,75]},{45:[2,50]},{4:76,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],37:[2,43],42:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{45:[2,19]},{18:77,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{4:78,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{24:79,45:[1,75]},{45:[2,52]},{5:[2,10],13:[2,10],14:[2,10],17:[2,10],27:[2,10],32:[2,10],37:[2,10],42:[2,10],45:[2,10],46:[2,10],49:[2,10],53:[2,10]},{18:65,31:[2,83],56:80,57:81,58:66,59:[1,40],63:82,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{59:[2,85],60:83,62:[2,85],66:[2,85],74:[2,85],75:[2,85],76:[2,85],77:[2,85],78:[2,85],79:[2,85]},{18:65,29:84,31:[2,55],57:85,58:66,59:[1,40],63:86,64:67,65:68,66:[1,69],69:[2,55],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:65,31:[2,61],34:87,57:88,58:66,59:[1,40],63:89,64:67,65:68,66:[1,69],69:[2,61],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:65,20:90,21:[2,47],57:91,58:66,59:[1,40],63:92,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{31:[1,93]},{31:[2,74],59:[2,74],66:[2,74],74:[2,74],75:[2,74],76:[2,74],77:[2,74],78:[2,74],79:[2,74]},{31:[2,76]},{21:[2,24],31:[2,24],52:[2,24],59:[2,24],62:[2,24],66:[2,24],69:[2,24],74:[2,24],75:[2,24],76:[2,24],77:[2,24],78:[2,24],79:[2,24]},{21:[2,25],31:[2,25],52:[2,25],59:[2,25],62:[2,25],66:[2,25],69:[2,25],74:[2,25],75:[2,25],76:[2,25],77:[2,25],78:[2,25],79:[2,25]},{21:[2,27],31:[2,27],52:[2,27],62:[2,27],65:94,66:[1,95],69:[2,27]},{21:[2,89],31:[2,89],52:[2,89],62:[2,89],66:[2,89],69:[2,89]},{21:[2,42],31:[2,42],52:[2,42],59:[2,42],62:[2,42],66:[2,42],67:[1,96],69:[2,42],74:[2,42],75:[2,42],76:[2,42],77:[2,42],78:[2,42],79:[2,42],81:[2,42]},{21:[2,41],31:[2,41],52:[2,41],59:[2,41],62:[2,41],66:[2,41],69:[2,41],74:[2,41],75:[2,41],76:[2,41],77:[2,41],78:[2,41],79:[2,41],81:[2,41]},{52:[1,97]},{52:[2,78],59:[2,78],66:[2,78],74:[2,78],75:[2,78],76:[2,78],77:[2,78],78:[2,78],79:[2,78]},{52:[2,80]},{5:[2,12],13:[2,12],14:[2,12],17:[2,12],27:[2,12],32:[2,12],37:[2,12],42:[2,12],45:[2,12],46:[2,12],49:[2,12],53:[2,12]},{18:98,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{36:50,37:[1,52],41:51,42:[1,53],43:100,44:99,45:[2,71]},{31:[2,65],38:101,59:[2,65],66:[2,65],69:[2,65],74:[2,65],75:[2,65],76:[2,65],77:[2,65],78:[2,65],79:[2,65]},{45:[2,17]},{5:[2,13],13:[2,13],14:[2,13],17:[2,13],27:[2,13],32:[2,13],37:[2,13],42:[2,13],45:[2,13],46:[2,13],49:[2,13],53:[2,13]},{31:[1,102]},{31:[2,82],59:[2,82],66:[2,82],74:[2,82],75:[2,82],76:[2,82],77:[2,82],78:[2,82],79:[2,82]},{31:[2,84]},{18:65,57:104,58:66,59:[1,40],61:103,62:[2,87],63:105,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{30:106,31:[2,57],68:107,69:[1,108]},{31:[2,54],59:[2,54],66:[2,54],69:[2,54],74:[2,54],75:[2,54],76:[2,54],77:[2,54],78:[2,54],79:[2,54]},{31:[2,56],69:[2,56]},{31:[2,63],35:109,68:110,69:[1,108]},{31:[2,60],59:[2,60],66:[2,60],69:[2,60],74:[2,60],75:[2,60],76:[2,60],77:[2,60],78:[2,60],79:[2,60]},{31:[2,62],69:[2,62]},{21:[1,111]},{21:[2,46],59:[2,46],66:[2,46],74:[2,46],75:[2,46],76:[2,46],77:[2,46],78:[2,46],79:[2,46]},{21:[2,48]},{5:[2,21],13:[2,21],14:[2,21],17:[2,21],27:[2,21],32:[2,21],37:[2,21],42:[2,21],45:[2,21],46:[2,21],49:[2,21],53:[2,21]},{21:[2,90],31:[2,90],52:[2,90],62:[2,90],66:[2,90],69:[2,90]},{67:[1,96]},{18:65,57:112,58:66,59:[1,40],66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{5:[2,22],13:[2,22],14:[2,22],17:[2,22],27:[2,22],32:[2,22],37:[2,22],42:[2,22],45:[2,22],46:[2,22],49:[2,22],53:[2,22]},{31:[1,113]},{45:[2,18]},{45:[2,72]},{18:65,31:[2,67],39:114,57:115,58:66,59:[1,40],63:116,64:67,65:68,66:[1,69],69:[2,67],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{5:[2,23],13:[2,23],14:[2,23],17:[2,23],27:[2,23],32:[2,23],37:[2,23],42:[2,23],45:[2,23],46:[2,23],49:[2,23],53:[2,23]},{62:[1,117]},{59:[2,86],62:[2,86],66:[2,86],74:[2,86],75:[2,86],76:[2,86],77:[2,86],78:[2,86],79:[2,86]},{62:[2,88]},{31:[1,118]},{31:[2,58]},{66:[1,120],70:119},{31:[1,121]},{31:[2,64]},{14:[2,11]},{21:[2,28],31:[2,28],52:[2,28],62:[2,28],66:[2,28],69:[2,28]},{5:[2,20],13:[2,20],14:[2,20],17:[2,20],27:[2,20],32:[2,20],37:[2,20],42:[2,20],45:[2,20],46:[2,20],49:[2,20],53:[2,20]},{31:[2,69],40:122,68:123,69:[1,108]},{31:[2,66],59:[2,66],66:[2,66],69:[2,66],74:[2,66],75:[2,66],76:[2,66],77:[2,66],78:[2,66],79:[2,66]},{31:[2,68],69:[2,68]},{21:[2,26],31:[2,26],52:[2,26],59:[2,26],62:[2,26],66:[2,26],69:[2,26],74:[2,26],75:[2,26],76:[2,26],77:[2,26],78:[2,26],79:[2,26]},{13:[2,14],14:[2,14],17:[2,14],27:[2,14],32:[2,14],37:[2,14],42:[2,14],45:[2,14],46:[2,14],49:[2,14],53:[2,14]},{66:[1,125],71:[1,124]},{66:[2,91],71:[2,91]},{13:[2,15],14:[2,15],17:[2,15],27:[2,15],32:[2,15],42:[2,15],45:[2,15],46:[2,15],49:[2,15],53:[2,15]},{31:[1,126]},{31:[2,70]},{31:[2,29]},{66:[2,92],71:[2,92]},{13:[2,16],14:[2,16],17:[2,16],27:[2,16],32:[2,16],37:[2,16],42:[2,16],45:[2,16],46:[2,16],49:[2,16],53:[2,16]}],defaultActions:{4:[2,1],49:[2,50],51:[2,19],55:[2,52],64:[2,76],73:[2,80],78:[2,17],82:[2,84],92:[2,48],99:[2,18],100:[2,72],105:[2,88],107:[2,58],110:[2,64],111:[2,11],123:[2,70],124:[2,29]},parseError:function(a){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:((null===n||"undefined"==typeof n)&&(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=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),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 14;break;case 1:return 14;case 2:return this.popState(),14;case 3:return b.yytext=b.yytext.substr(5,b.yyleng-9),this.popState(),16;case 4:return 14;case 5:return this.popState(),13;case 6:return 59;case 7:return 62;case 8:return 17;case 9:return this.popState(),this.begin("raw"),21;case 10:return 53;case 11:return 27;case 12:return 45;case 13:return this.popState(),42;case 14:return this.popState(),42;case 15:return 32;case 16:return 37;case 17:return 49;case 18:return 46;case 19:this.unput(b.yytext),this.popState(),this.begin("com");break;case 20:return this.popState(),13;case 21:return 46;case 22:return 67;case 23:return 66;case 24:return 66;case 25:return 81;case 26:break;case 27:return this.popState(),52;case 28:return this.popState(),31;case 29:return b.yytext=e(1,2).replace(/\\"/g,'"'),74;case 30:return b.yytext=e(1,2).replace(/\\'/g,"'"),74;case 31:return 79;case 32:return 76;case 33:return 76;case 34:return 77;case 35:return 78;case 36:return 75;case 37:return 69;case 38:return 71;case 39:return 66;case 40:return 66;case 41:return"INVALID";case 42:return 5}},a.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\/.)|]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[6,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],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[5],inclusive:!1},raw:{rules:[3,4],inclusive:!1},INITIAL:{rules:[0,1,42],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(8)["default"];b.__esModule=!0;var j=c(6),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.isRootSeen;this.isRootSeen=!0;for(var c=a.body,d=0,i=c.length;i>d;d++){var j=c[d],k=this.accept(j);if(k){var l=e(c,d,b),m=f(c,d,b),n=k.openStandalone&&l,o=k.closeStandalone&&m,p=k.inlineStandalone&&l&&m;k.close&&g(c,d,!0),k.open&&h(c,d,!0),p&&(g(c,d),h(c,d)&&"PartialStatement"===j.type&&(j.indent=/([ \t]+$)/.exec(c[d-1].original)[1])),n&&(g((j.program||j.inverse).body),h(c,d)),o&&(g(c,d),h((j.inverse||j.program).body))}}return a},d.prototype.BlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function e(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function f(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function g(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function h(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;i>h;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new n["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return new this.PathExpression(a,f,e,d,c)}function i(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g;return new this.MustacheStatement(a,b,c,h,e,this.locInfo(f))}function j(a,b,c,d){if(a.path.original!==c){var e={loc:a.path.loc};throw new n["default"](a.path.original+" doesn't match "+c,e)}d=this.locInfo(d);var f=new this.Program([b],null,{},d);return new this.BlockStatement(a.path,a.params,a.hash,f,void 0,{},{},{},d)}function k(a,b,c,d,e,f){if(d&&d.path&&a.path.original!==d.path.original){var g={loc:a.path.loc};throw new n["default"](a.path.original+" doesn't match "+d.path.original,g)}b.blockParams=a.blockParams;var h=void 0,i=void 0;return c&&(c.chain&&(c.program.body[0].closeStrip=d.strip),i=c.strip,h=c.program),e&&(e=h,h=b,b=e),new this.BlockStatement(a.path,a.params,a.hash,b,h,a.strip,i,d&&d.strip,this.locInfo(f))}var l=c(8)["default"];b.__esModule=!0,b.SourceLocation=d,b.id=e,b.stripFlags=f,b.stripComment=g,b.preparePath=h,b.prepareMustache=i,b.prepareRawBlock=j,b.prepareBlock=k;var m=c(11),n=l(m)},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;g>e;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(12),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add(["  ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;c>b;b++)a(this.source[b])},empty:function(){var a=void 0===arguments[0]?this.currentLocation||{start:{}}:arguments[0];return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])
}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a,b){for(var c=this.empty(b),e=0,f=a.length;f>e;e++)e&&c.add(","),c.add(d(a[e],this,b));return c},generateArray:function(a,b){var c=this.generateList(a,b);return c.prepend("["),c.add("]"),c}},b["default"]=e,a.exports=b["default"]}])});
/*!
 * Spinners 3.0.0
 * (c) 2010-2012 Nick Stakenburg - http://www.nickstakenburg.com
 *
 * Spinners is freely distributable under the terms of an MIT-style license.
 *
 * GitHub: http://github.com/staaky/spinners
 */
; var Spinners = { version: "3.0.0" }; (function (a) { function b(a) { return a * Math.PI / 180 } function c(a) { this.element = a } function d(b, c) { b && (this.element = b, h.remove(b), h.removeDetached(), this._position = 0, this._state = "stopped", this.setOptions(a.extend({ color: "#000", dashes: 12, radius: 5, height: 5, width: 1.8, opacity: 1, padding: 3, rotation: 700 }, c || {})), this.drawPosition(0), h.add(this)) } var e = { scroll: function (a, b) { if (!b) return a; var c = a.slice(0, b); return a.slice(b, a.length).concat(c) }, isElement: function (a) { return a && 1 == a.nodeType }, element: { isAttached: function () { return function (a) { for (; a && a.parentNode;) a = a.parentNode; return !!a && !!a.body } }() } }, f = { drawRoundedRectangle: function (c, d) { var e = a.extend({ top: 0, left: 0, width: 0, height: 0, radius: 0 }, d || {}), f = e.left, g = e.top, h = e.width, i = e.height, e = e.radius; c.beginPath(), c.moveTo(f + e, g), c.arc(f + h - e, g + e, e, b(-90), b(0), !1), c.arc(f + h - e, g + i - e, e, b(0), b(90), !1), c.arc(f + e, g + i - e, e, b(90), b(180), !1), c.arc(f + e, g + e, e, b(-180), b(-90), !1), c.closePath(), c.fill() } }, g = function () { function a(a) { var c = []; 0 == a.indexOf("#") && (a = a.substring(1)), a = a.toLowerCase(); if ("" != a.replace(b, "")) return null; 3 == a.length ? (c[0] = a.charAt(0) + a.charAt(0), c[1] = a.charAt(1) + a.charAt(1), c[2] = a.charAt(2) + a.charAt(2)) : (c[0] = a.substring(0, 2), c[1] = a.substring(2, 4), c[2] = a.substring(4)); for (a = 0; a < c.length; a++) c[a] = parseInt(c[a], 16); return c.red = c[0], c.green = c[1], c.blue = c[2], c } var b = RegExp("[0123456789abcdef]", "g"), c = function () { function a(a, b, c) { return a = a.toString(c || 10), Array(b - a.length).join("0") + a } return function (b, c, d) { return "#" + a(b, 2, 16) + a(c, 2, 16) + a(d, 2, 16) } }(); return { hex2rgb: a, hex2fill: function (b, c) { "undefined" == typeof c && (c = 1); var d = c, e = a(b); return e[3] = d, e.opacity = d, "rgba(" + e.join() + ")" }, rgb2hex: c } }(); a.extend(Spinners, { enabled: !1, support: { canvas: function () { var b = a("<canvas>")[0]; return !!b.getContext && !!b.getContext("2d") }() }, init: function () { if (this.support.canvas || window.G_vmlCanvasManager && window.attachEvent && -1 === navigator.userAgent.indexOf("Opera")) window.G_vmlCanvasManager && window.G_vmlCanvasManager.init_(document), this.enabled = !0 }, create: function (a, b) { return c.create(a, b), this.get(a) }, get: function (a) { return new c(a) }, play: function (a) { return this.get(a).play(), this }, pause: function (a) { return this.get(a).pause(), this }, toggle: function (a) { return this.get(a).toggle(), this }, stop: function (a) { return this.get(a).stop(), this }, remove: function (a) { return this.get(a).remove(), this }, removeDetached: function () { return h.removeDetached(), this }, center: function (a) { return this.get(a).center(), this }, setOptions: function (a, b) { return this.get(a).setOptions(b), this }, getDimensions: function (a) { return a = 2 * h.get(a)[0].getLayout().workspace.radius, { width: a, height: a } } }); var h = { spinners: [], get: function (b) { if (b) { var c = []; return a.each(this.spinners, function (d, f) { f && (e.isElement(b) ? f.element == b : a(f.element).is(b)) && c.push(f) }), c } }, add: function (a) { this.spinners.push(a) }, remove: function (b) { a(a.map(this.spinners, function (c) { if (e.isElement(b) ? c.element == b : a(c.element).is(b)) return c.element })).each(a.proxy(function (a, b) { this.removeByElement(b) }, this)) }, removeByElement: function (b) { var c = this.get(b)[0]; c && (c.remove(), this.spinners = a.grep(this.spinners, function (a) { return a.element != b })) }, removeDetached: function () { a.each(this.spinners, a.proxy(function (a, b) { b && b.element && !e.element.isAttached(b.element) && this.remove(b.element) }, this)) } }; a.extend(c, { create: function (b, c) { if (b) { var f = c || {}, g = []; return e.isElement(b) ? g.push(new d(b, f)) : a(b).each(function (a, b) { g.push(new d(b, f)) }), g } } }), a.extend(c.prototype, { items: function () { return h.get(this.element) }, play: function () { return a.each(this.items(), function (a, b) { b.play() }), this }, stop: function () { return a.each(this.items(), function (a, b) { b.stop() }), this }, pause: function () { return a.each(this.items(), function (a, b) { b.pause() }), this }, toggle: function () { return a.each(this.items(), function (a, b) { b.toggle() }), this }, center: function () { return a.each(this.items(), function (a, b) { b.center() }), this }, setOptions: function (b) { return a.each(this.items(), function (a, c) { c.setOptions(b) }), this }, remove: function () { return h.remove(this.element), this } }), a.extend(d.prototype, { setOptions: function (b) { this.options = a.extend({}, this.options, b || {}), this.options.radii && (b = this.options.radii, this.options.radius = Math.min(b[0], b[1]), this.options.height = Math.max(b[0], b[1]) - this.options.radius), this.options.dashWidth && (this.options.width = this.options.dashWidth), this.options.speed && (this.options.duration = 1e3 * this.options.speed); var b = this._state, c = this._position; this._layout = null, this.build(), c && c >= this.options.dashes - 1 && (this._position = this.options.dashes - 1); switch (b) { case "playing": this.play(); break; case "paused": case "stopped": this.drawPosition(this._position) } this._centered && this.center() }, remove: function () { this.canvas && (this.pause(), a(this.canvas).remove(), this.ctx = this.canvas = null) }, build: function () { this.remove(); var b = this.getLayout().workspace.radius; return a(document.body).append(this.canvas = a("<canvas>").attr({ width: 2 * b, height: 2 * b }).css({ zoom: 1 })), window.G_vmlCanvasManager && G_vmlCanvasManager.initElement(this.canvas[0]), this.ctx = this.canvas[0].getContext("2d"), this.ctx.globalAlpha = this.options.opacity, a(this.element).append(this.canvas), this.ctx.translate(b, b), this }, drawPosition: function (a) { var c = this.getLayout().workspace, a = e.scroll(c.opacities, -1 * a), d = c.radius, c = this.options.dashes, f = b(360 / c); this.ctx.clearRect(-1 * d, -1 * d, 2 * d, 2 * d); for (d = 0; d < c; d++) this.drawDash(a[d], this.options.color), this.ctx.rotate(f) }, drawDash: function (a, b) { this.ctx.fillStyle = g.hex2fill(b, a); var c = this.getLayout(), d = c.workspace.radius, e = c.dash.position, c = c.dash.dimensions; f.drawRoundedRectangle(this.ctx, { top: e.top - d, left: e.left - d, width: c.width, height: c.height, radius: Math.min(c.height, c.width) / 2 }) }, _nextPosition: function () { var b = this.options.rotation / this.options.dashes; this.nextPosition(), this._playTimer = window.setTimeout(a.proxy(this._nextPosition, this), b) }, nextPosition: function () { this._position == this.options.dashes - 1 && (this._position = -1), this._position++, this.drawPosition(this._position) }, play: function () { if ("playing" != this._state) { this._state = "playing"; var b = this.options.rotation / this.options.dashes; return this._playTimer = window.setTimeout(a.proxy(this._nextPosition, this), b), this } }, pause: function () { if ("paused" != this._state) return this._pause(), this._state = "paused", this }, _pause: function () { this._playTimer && (window.clearTimeout(this._playTimer), this._playTimer = null) }, stop: function () { if ("stopped" != this._state) return this._pause(), this._position = 0, this.drawPosition(0), this._state = "stopped", this }, toggle: function () { return this["playing" == this._state ? "pause" : "play"](), this }, getLayout: function () { if (this._layout) return this._layout; for (var a = this.options, b = a.dashes, c = a.width, d = a.radius, e = a.radius + a.height, f = Math.max(c, e), f = Math.ceil(Math.max(f, Math.sqrt(e * e + c / 2 * (c / 2)))), a = f += a.padding, g = 1 / b, h = [], i = 0; i < b; i++) h.push((i + 1) * g); return this._layout = b = { workspace: { radius: a, opacities: h }, dash: { position: { top: f - e, left: f - c / 2 }, dimensions: { width: c, height: e - d } } } }, center: function () { var b = 2 * this.getLayout().workspace.radius; a(this.element.parentNode).css({ position: "relative" }), a(this.element).css({ position: "absolute", height: b + "px", width: b + "px", top: "50%", left: "50%", marginLeft: -0.5 * b + "px", marginTop: -0.5 * b + "px" }), this._centered = !0 } }), Spinners.init(), Spinners.enabled || (c.create = function () { return [] }) })(jQuery);


/*!
 * Tipped - The jQuery Tooltip - v2.5.5
 * (c) 2010-2012 Nick Stakenburg
 *
 * http://projects.nickstakenburg.com/tipped
 *
 * License: http://projects.nickstakenburg.com/tipped/license
 */
;var Tipped = { version: '2.5.5' };

Tipped.Skins = {
  // base skin, don't modify! (create custom skins in a seperate file)
  'base': {
    afterUpdate: false,
    ajax: {
      cache: true,
      type: 'get'
    },
    background: {
      color: '#f2f2f2',
      opacity: 1
    },
    border: {
      size: 1,
      color: '#000',
      opacity: 1
    },
    closeButtonSkin: 'default',
    containment: {
      selector: 'viewport'
    },
    fadeIn: 180,
    fadeOut: 220,
    showDelay: 75,
    hideDelay: 25,
    radius: {
      size: 3,
      position: 'background'
    },
    hideAfter: false,
    hideOn: {
      element: 'self',
      event: 'mouseleave'
    },
    hideOthers: false,
    hook: 'topleft',
    inline: false,
    offset: {
      x: 0, y: 0,
      mouse: { x: -12, y: -12 } // only defined in the base class
    },
    onHide: false,
    onShow: false,
    shadow: {
      blur: 2,
      color: '#000',
      offset: { x: 0, y: 0 },
      opacity: .15
    },
    showOn: 'mousemove',
    spinner: true,
    stem: {
      height: 6,
      width: 11,
      offset: { x: 5, y: 5 },
      spacing: 2
    },
    target: 'self'
  },
  
  // Every other skin inherits from this one
  'reset': {
    ajax: false,
    closeButton: false,
    hideOn: [{
      element: 'self',
      event: 'mouseleave'
    }, {
      element: 'tooltip',
      event: 'mouseleave'
    }],
    hook: 'topmiddle',
    stem: true
  },

  // Custom skins start here
  'black': {
     background: { color: '#232323', opacity: .9 },
     border: { size: 1, color: "#232323" },
     spinner: { color: '#fff' }
  },

  'cloud': {
    border: {
      size: 1,
      color: [
        { position: 0, color: '#bec6d5'},
        { position: 1, color: '#b1c2e3' }
      ]
    },
    closeButtonSkin: 'light',
    background: {
      color: [
        { position: 0, color: '#f6fbfd'},
        { position: 0.1, color: '#fff' },
        { position: .48, color: '#fff'},
        { position: .5, color: '#fefffe'},
        { position: .52, color: '#f7fbf9'},
        { position: .8, color: '#edeff0' },
        { position: 1, color: '#e2edf4' }
      ]
    },
    shadow: { opacity: .1 }
  },

  'dark': {
    border: { size: 1, color: '#1f1f1f', opacity: .95 },
    background: {
      color: [
        { position: .0, color: '#686766' },
        { position: .48, color: '#3a3939' },
        { position: .52, color: '#2e2d2d' },
        { position: .54, color: '#2c2b2b' },
        { position: 0.95, color: '#222' },
        { position: 1, color: '#202020' }
      ],
      opacity: .9
    },
    radius: { size: 4 },
    shadow: { offset: { x: 0, y: 1 } },
    spinner: { color: '#ffffff' }
  },

  'facebook': {
    background: { color: '#282828' },
    border: 0,
    fadeIn: 0,
    fadeOut: 0,
    radius: 0,
    stem: {
      width: 7,
      height: 4,
      offset: { x: 6, y: 6 }
    },
    shadow: false
  },

  'lavender': {
    background: {
      color: [
        { position: .0, color: '#b2b6c5' },
        { position: .5, color: '#9da2b4' },
        { position: 1, color: '#7f85a0' }
      ]
    },
    border: {
      color: [
        { position: 0, color: '#a2a9be' },
        { position: 1, color: '#6b7290' }
      ],
      size: 1
    },
    radius: 1,
    shadow: { opacity: .1 }
  },

  'light': {
    border: { size: 0, color: '#afafaf' },
    background: {
      color: [
        { position: 0, color: '#fefefe' },
        { position: 1, color: '#f7f7f7' }
      ]
    },
    closeButtonSkin: 'light',
    radius: 1,
    stem: {
      height: 7,
      width: 13,
      offset: { x: 7, y: 7 }
    },
    shadow: { opacity: .32, blur: 2 }
  },

  'lime': {
    border: {
      size: 1,
      color: [
        { position: 0,   color: '#5a785f' },
        { position: .05, color: '#0c7908' },
        { position: 1, color: '#587d3c' }
      ]
    },
    background: {
      color: [
        { position: 0,   color: '#a5e07f' },
        { position: .02, color: '#cef8be' },
        { position: .09, color: '#7bc83f' },
        { position: .35, color: '#77d228' },
        { position: .65, color: '#85d219' },
        { position: .8,  color: '#abe041' },
        { position: 1,   color: '#c4f087' }
      ]
    }
  },

  'liquid' : {
    border: {
      size: 1,
      color: [
        { position: 0, color: '#454545' },
        { position: 1, color: '#101010' }
      ]
    },
    background: {
      color: [
        { position: 0, color: '#515562'},
        { position: .3, color: '#252e43'},
        { position: .48, color: '#111c34'},
        { position: .52, color: '#161e32'},
        { position: .54, color: '#0c162e'},
        { position: 1, color: '#010c28'}
      ],
      opacity: .8
    },
    radius: { size: 4 },
    shadow: { offset: { x: 0, y: 1 } },
    spinner: { color: '#ffffff' }
  },

  'blue': {
    border: {
      color: [
        { position: 0, color: '#113d71'},
        { position: 1, color: '#1e5290' }
      ]
    },
    background: {
      color: [
        { position: 0, color: '#3a7ab8'},
        { position: .48, color: '#346daa'},
        { position: .52, color: '#326aa6'},
        { position: 1, color: '#2d609b' }
      ]
    },
    spinner: { color: '#f2f6f9' },
    shadow: { opacity: .2 }
  },

  'salmon' : {
    background: {
      color: [
        { position: 0, color: '#fbd0b7' },
        { position: .5, color: '#fab993' },
        { position: 1, color: '#f8b38b' }
      ]
    },
    border: {
      color: [
        { position: 0, color: '#eda67b' },
        { position: 1, color: '#df946f' }
      ],
      size: 1
    },
    radius: 1,
    shadow: { opacity: .1 }
  },

  'yellow': {
    border: { size: 1, color: '#f7c735' },
    background: '#ffffaa',
    radius: 1,
    shadow: { opacity: .1 }
  }
};

Tipped.Skins.CloseButtons = {
  'base': {
    diameter: 17,
    border: 2,
    x: { diameter: 10, size: 2, opacity: 1 },
    states: {
      'default': {
        background: {
          color: [
            { position: 0, color: '#1a1a1a' },
            { position: 0.46, color: '#171717' },
            { position: 0.53, color: '#121212' },
            { position: 0.54, color: '#101010' },
            { position: 1, color: '#000' }
          ],
          opacity: 1
        },
        x: { color: '#fafafa', opacity: 1 },
        border: { color: '#fff', opacity: 1 }
      },
      'hover': {
        background: {
          color: '#333',
          opacity: 1
        },
        x: { color: '#e6e6e6', opacity: 1 },
        border: { color: '#fff', opacity: 1 }
      }
    },
    shadow: {
      blur: 2,
      color: '#000',
      offset: { x: 0, y: 0 },
      opacity: .3
    }
  },

  'reset': {},

  'default': {},

  'light': {
    diameter: 17,
    border: 2,
    x: { diameter: 10, size: 2, opacity: 1 },
    states: {
      'default': {
        background: {
          color: [
            { position: 0, color: '#797979' },
            { position: 0.48, color: '#717171' },
            { position: 0.52, color: '#666' },
            { position: 1, color: '#666' }
          ],
          opacity: 1
        },
        x: { color: '#fff', opacity: .95 },
        border: { color: '#676767', opacity: 1 }
      },
      'hover': {
        background: {
          color: [
            { position: 0, color: '#868686' },
            { position: 0.48, color: '#7f7f7f' },
            { position: 0.52, color: '#757575' },
            { position: 1, color: '#757575' }
          ],
          opacity: 1
        },
        x: { color: '#fff', opacity: 1 },
        border: { color: '#767676', opacity: 1 }
      }
    }
  }
};

eval(function (p, a, c, k, e, r) { e = function (c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) r[e(c)] = k[c] || e(c); k = [function (e) { return r[e] }]; e = function () { return '\\w+' }; c = 1 }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p }('(C(a){C b(a,b){I c=[a,b];J c.E=a,c.G=b,c}C c(a){z.Q=a}C d(a){I b={},c;1E(c 5S a)b[c]=a[c]+"22";J b}C e(a){J 2f*a/K.2A}C f(a){J a*K.2A/2f}C g(b){O(b){z.Q=b,u.1e(b);I c=z.1N();z.F=a.U({},c.F),z.23=1,z.W={},z.1t=a(b).1x("1X-1t"),u.2B(z),z.1F=z.F.X.17,z.7A=z.F.V&&z.1F,z.1p()}}C h(b,c,d){(z.Q=b)&&c&&(z.F=a.U({2C:3,1f:{x:0,y:0},1q:"#41",1m:.5,2m:1},d||{}),z.23=z.F.2m,z.W={},z.1t=a(b).1x("1X-1t"),v.2B(z),z.1p())}C i(b,c){O(z.Q=b)z.F=a.U({2C:5,1f:{x:0,y:0},1q:"#41",1m:.5,2m:1},c||{}),z.23=z.F.2m,z.1t=a(b).1x("1X-1t"),w.2B(z),z.1p()}C j(b,c){1E(I d 5S c)c[d]&&c[d].3c&&c[d].3c===4U?(b[d]=a.U({},b[d])||{},j(b[d],c[d])):b[d]=c[d];J b}C k(b,c,d){O(z.Q=b){I e=a(b).1x("1X-1t");e&&x.1e(b),e=p(),a(b).1x("1X-1t",e),z.1t=e,"7B"==a.12(c)&&!m.1T(c)?(d=c,c=1d):d=d||{},z.F=x.5T(d),d=b.5U("4V"),c||((e=b.5U("1x-1X"))?c=e:d&&(c=d)),d&&(a(b).1x("4W",d),b.7C("4V","")),z.2n=c,z.1S=z.F.1S||+x.F.42,z.W={2L:{D:1,H:1},4X:[],2M:[],1Y:{43:!1,24:!1,1k:!1,2W:!1,1p:!1,44:!1,4Y:!1,3d:!1},4Z:""},b=z.F.1g,z.1g="2o"==b?"2o":"46"==b||!b?z.Q:b&&19.5V(b)||z.Q,z.5W(),x.2B(z)}}I l=5X.3e.7D,m={7E:C(b,c){J C(){I d=[a.15(b,z)].5Y(l.2X(47));J c.52(z,d)}},"1a":{},5Z:C(a,b){1E(I c=0,d=a.1y;c<d;c++)b(a[c])},1b:C(a,b,c){I d=0;53{z.5Z(a,C(a){b.2X(c,a,d++)})}54(e){O(e!=m["1a"])7F e}},48:C(a,b,c){I d=!1;J m.1b(a||[],C(a,e){O(d|=b.2X(c,a,e))J m["1a"]}),!!d},60:C(a,b){I c=!1;J m.48(a||[],C(a){O(c=a===b)J!0}),c},56:C(a,b,c){I d=[];J m.1b(a||[],C(a,e){b.2X(c,a,e)&&(d[d.1y]=a)}),d},7G:C(a){I b=l.2X(47,1);J m.56(a,C(a){J!m.60(b,a)})},1T:C(a){J a&&1==a.7H},57:C(a,b){I c=l.2X(47,2);J 49(C(){J a.52(a,c)},b)},58:C(a){J m.57.52(z,[a,1].5Y(l.2X(47,1)))},4a:C(a){J{x:a.61,y:a.7I}},3f:C(b,c){I d=b.1g;J c?a(d).4b(c)[0]:d},Q:{4c:C(a){I c=0,d=0;7J c+=a.4d||0,d+=a.4e||0,a=a.4f;7K(a);J b(d,c)},4g:C(c){I d=a(c).1f(),c=m.Q.4c(c),e=a(1r).4d(),f=a(1r).4e();J d.E+=c.E-f,d.G+=c.G-e,b(d.E,d.G)},59:C(){J C(a){1E(;a&&a.4f;)a=a.4f;J!!a&&!!a.2N}}()}},n=C(a){C b(b){J(b=62(b+"([\\\\d.]+)").7L(a))?63(b[1]):!0}J{3y:!!1r.7M&&-1===a.2Y("5a")&&b("7N "),5a:-1<a.2Y("5a")&&(!!1r.5b&&5b.5c&&63(5b.5c())||7.55),7O:-1<a.2Y("64/")&&b("64/"),65:-1<a.2Y("65")&&-1===a.2Y("7P")&&b("7Q:"),7R:!!a.2O(/7S.*7T.*7U/),5d:-1<a.2Y("5d")&&b("5d/")}}(7V.7W),o={2D:{2Z:{4h:"3.0.0",4i:1r.2Z&&(2Z.5c||2Z.7X)},3z:{4h:"1.4.4",4i:1r.3z&&3z.7Y.7Z}},66:C(){C a(a){1E(I c=(a=a.2O(b))&&a[1]&&a[1].2p(".")||[],d=0,e=0,f=c.1y;e<f;e++)d+=2q(c[e]*K.4j(10,6-2*e));J a&&a[3]?d-1:d}I b=/^(\\d+(\\.?\\d+){0,3})([A-67-80-]+[A-67-81-9]+)?/;J C(b){!z.2D[b].68&&(z.2D[b].68=!0,!z.2D[b].4i||a(z.2D[b].4i)<a(z.2D[b].4h)&&!z.2D[b].69)&&((z.2D[b].69=!0,b="1z 6a "+b+" >= "+z.2D[b].4h,1r.5e)?5e[5e.6b?"6b":"82"](b):6c(b))}}()},p=C(){I a=0;J C(b){b=b||"83";1E(a++;19.5V(b+a);)a++;J b+a}}();a.U(1z,C(){I b=C(){I a=19.1G("2P");J!!a.3g&&!!a.3g("2d")}(),d;53{d=!!19.6d("84")}54(e){d=!1}J{2Q:{2P:b,5f:d,3A:C(){I b=!1;J a.1b(["85","86","87"],C(a,c){53{19.6d(c),b=!0}54(d){}}),b}()},30:C(){O(!z.2Q.2P&&!1r.3B){O(!n.3y)J;6c("1z 6a 88 (89.8a)")}o.66("3z"),a(19).6e(C(){x.6f()})},4k:C(a,b,d){J c.4k(a,b,d),z.14(a)},14:C(a){J 31 c(a)},3f:C(a){J x.3f(a)},1u:C(a){J z.14(a).1u(),z},1l:C(a){J z.14(a).1l(),z},2E:C(a){J z.14(a).2E(),z},2r:C(a){J z.14(a).2r(),z},1e:C(a){J z.14(a).1e(),z},4l:C(){J x.4l(),z},5g:C(a){J x.5g(a),z},5h:C(a){J x.5h(a),z},1k:C(b){O(m.1T(b))J x.5i(b);O("5j"!=a.12(b)){I b=a(b),c=0;J a.1b(b,C(a,b){x.5i(b)&&c++}),c}J x.3h().1y}}}()),a.U(c,{4k:C(b,c,d){O(b){I e=d||{},f=[];J x.6g(),m.1T(b)?f.2s(31 k(b,c,e)):a(b).1b(C(a,b){f.2s(31 k(b,c,e))}),f}}}),a.U(c.3e,{3C:C(){J x.26.4m={x:0,y:0},x.14(z.Q)},1u:C(){J a.1b(z.3C(),C(a,b){b.1u()}),z},1l:C(){J a.1b(z.3C(),C(a,b){b.1l()}),z},2E:C(){J a.1b(z.3C(),C(a,b){b.2E()}),z},2r:C(){J a.1b(z.3C(),C(a,b){b.2r()}),z},1e:C(){J x.1e(z.Q),z}});I q={30:C(){J 1r.3B&&!1z.2Q.2P&&n.3y?C(a){3B.8b(a)}:C(){}}(),6h:C(b,c){I d=a.U({G:0,E:0,D:0,H:0,Y:0},c||{}),e=d.E,g=d.G,h=d.D,i=d.H;(d=d.Y)?(b.1O(),b.32(e+d,g),b.1L(e+h-d,g+d,d,f(-90),f(0),!1),b.1L(e+h-d,g+i-d,d,f(0),f(90),!1),b.1L(e+d,g+i-d,d,f(90),f(2f),!1),b.1L(e+d,g+d,d,f(-2f),f(-90),!1),b.1P(),b.2F()):b.6i(e,g,h,i)},8c:C(b,c,d){1E(I d=a.U({x:0,y:0,1q:"#41"},d||{}),e=0,f=c.1y;e<f;e++)1E(I g=0,h=c[e].1y;g<h;g++){I i=2q(c[e].33(g))*(1/9);b.2t=t.2u(d.1q,i),i&&b.6i(d.x+g,d.y+e,1,1)}},3D:C(b,c,d){I e;J"1Z"==a.12(c)?e=t.2u(c):"1Z"==a.12(c.1q)?e=t.2u(c.1q,"27"==a.12(c.1m)?c.1m:1):a.6j(c.1q)&&(d=a.U({3i:0,3j:0,3k:0,3l:0},d||{}),e=q.6k.6l(b.8d(d.3i,d.3j,d.3k,d.3l),c.1q,c.1m)),e},6k:{6l:C(b,c,d){1E(I d="27"==a.12(d)?d:1,e=0,f=c.1y;e<f;e++){I g=c[e];O("5j"==a.12(g.1m)||"27"!=a.12(g.1m))g.1m=1;b.8e(g.L,t.2u(g.1q,g.1m*d))}J b}}},r={3E:"3m 3F 3n 3o 3G 3H 3I 3J 3K 3L 3M 3p".2p(" "),3N:{6m:/^(G|E|1A|1B)(G|E|1A|1B|2v|2w)$/,1v:/^(G|1A)/,2G:/(2v|2w)/,6n:/^(G|1A|E|1B)/},6o:C(){I a={G:"H",E:"D",1A:"H",1B:"D"};J C(b){J a[b]}}(),2G:C(a){J!!a.34().2O(z.3N.2G)},6p:C(a){J!z.2G(a)},2g:C(a){J a.34().2O(z.3N.1v)?"1v":"2h"},5k:C(a){I b=1d;J(a=a.34().2O(z.3N.6n))&&a[1]&&(b=a[1]),b},2p:C(a){J a.34().2O(z.3N.6m)}},s={5l:C(a){J a=a.F.V,{D:a.D,H:a.H}},3O:C(b,c,d){J d=a.U({3q:"1i"},d||{}),b=b.F.V,c=z.4n(b.D,b.H,c),d.3q&&(c.D=K[d.3q](c.D),c.H=K[d.3q](c.H)),{D:c.D,H:c.H}},4n:C(a,b,c){I d=2f-e(K.6q(.5*(b/a))),c=K.4o(f(d-90))*c,c=a+2*c;J{D:c,H:c*b/a}},3r:C(a,b){I c=z.3O(a,b),d=z.5l(a);r.2G(a.1F);I e=K.1i(c.H+b);J{2R:{N:{D:K.1i(c.D),H:K.1i(e)}},R:{N:c},V:{N:{D:d.D,H:d.H}}}},5m:C(b,c,d){I e={G:0,E:0},f={G:0,E:0},g=a.U({},c),h=b.R,i=i||z.3r(b,b.R),j=i.2R.N;d&&(j.H=d,h=0);O(b.F.V){I k=r.5k(b.1F);"G"==k?e.G=j.H-h:"E"==k&&(e.E=j.H-h);I d=r.2p(b.1F),l=r.2g(b.1F);O("1v"==l){1s(d[2]){P"2v":P"2w":f.E=.5*g.D;1a;P"1B":f.E=g.D}"1A"==d[1]&&(f.G=g.H-h+j.H)}1H{1s(d[2]){P"2v":P"2w":f.G=.5*g.H;1a;P"1A":f.G=g.H}"1B"==d[1]&&(f.E=g.D-h+j.H)}g[r.6o(k)]+=j.H-h}1H O(d=r.2p(b.1F),l=r.2g(b.1F),"1v"==l){1s(d[2]){P"2v":P"2w":f.E=.5*g.D;1a;P"1B":f.E=g.D}"1A"==d[1]&&(f.G=g.H)}1H{1s(d[2]){P"2v":P"2w":f.G=.5*g.H;1a;P"1A":f.G=g.H}"1B"==d[1]&&(f.E=g.D)}I m=b.F.Y&&b.F.Y.28||0,h=b.F.R&&b.F.R.28||0;O(b.F.V){I n=b.F.V&&b.F.V.1f||{x:0,y:0},k=m&&"T"==b.F.Y.L?m:0,m=m&&"R"==b.F.Y.L?m:m+h,o=h+k+.5*i.V.N.D-.5*i.R.N.D,i=K.1i(h+k+.5*i.V.N.D+(m>o?m-o:0));O("1v"==l)1s(d[2]){P"E":f.E+=i;1a;P"1B":f.E-=i}1H 1s(d[2]){P"G":f.G+=i;1a;P"1A":f.G-=i}}O(b.F.V&&(n=b.F.V.1f))O("1v"==l)1s(d[2]){P"E":f.E+=n.x;1a;P"1B":f.E-=n.x}1H 1s(d[2]){P"G":f.G+=n.y;1a;P"1A":f.G-=n.y}I p;O(b.F.V&&(p=b.F.V.8f))O("1v"==l)1s(d[1]){P"G":f.G-=p;1a;P"1A":f.G+=p}1H 1s(d[1]){P"E":f.E-=p;1a;P"1B":f.E+=p}J{N:g,L:{G:0,E:0},T:{L:e,N:c},V:{N:j},1U:f}}},t=C(){C b(a){J a.6r=a[0],a.6s=a[1],a.6t=a[2],a}C c(a){I c=5X(3);0==a.2Y("#")&&(a=a.4p(1)),a=a.34();O(""!=a.8g(d,""))J 1d;3==a.1y?(c[0]=a.33(0)+a.33(0),c[1]=a.33(1)+a.33(1),c[2]=a.33(2)+a.33(2)):(c[0]=a.4p(0,2),c[1]=a.4p(2,4),c[2]=a.4p(4));1E(a=0;a<c.1y;a++)c[a]=2q(c[a],16);J b(c)}I d=62("[8h]","g");J{8i:c,2u:C(b,d){"5j"==a.12(d)&&(d=1);I e=d,f=c(b);J f[3]=e,f.1m=e,"8j("+f.8k()+")"},8l:C(a){I a=c(a),a=b(a),d=a.6r,e=a.6s,f=a.6t,g,h=d>e?d:e;f>h&&(h=f);I i=d<e?d:e;f<i&&(i=f),g=h/8m,a=0!=h?(h-i)/h:0;O(0==a)d=0;1H{I j=(h-d)/(h-i),k=(h-e)/(h-i),f=(h-f)/(h-i),d=(d==h?f-k:e==h?2+j-f:4+k-j)/6;0>d&&(d+=1)}J d=K.1I(6u*d),a=K.1I(5n*a),g=K.1I(5n*g),e=[],e[0]=d,e[1]=a,e[2]=g,e.8n=d,e.8o=a,e.8p=g,"#"+(50<e[2]?"41":"8q")}}}(),u={4q:{},14:C(b){O(!b)J 1d;I c=1d;J(b=a(b).1x("1X-1t"))&&(c=z.4q[b]),c},2B:C(a){z.4q[a.1t]=a},1e:C(a){O(a=z.14(a))3P z.4q[a.1t],a.1e()}};a.U(g.3e,C(){J{4r:C(){I a=z.1N();z.2L=a.W.2L,a=a.F,z.Y=a.Y&&a.Y.28||0,z.R=a.R&&a.R.28||0,z.1V=a.1V,a=K.5o(z.2L.H,z.2L.D),z.Y>a/2&&(z.Y=K.5p(a/2)),"R"==z.F.Y.L&&z.Y>z.R&&(z.R=z.Y),z.W={F:{Y:z.Y,R:z.R,1V:z.1V}}},6v:C(){z.W.X={};I b=z.1F;a.1b(r.3E,a.15(C(a,b){I c;z.W.X[b]={},z.1F=b,c=z.1W(),z.W.X[b].1U=c.1U,z.W.X[b].1h={N:c.1h.N,L:{G:c.1h.L.G,E:c.1h.L.E}},z.W.X[b].17={N:c.1J.N},z.13&&(c=z.13.1W(),z.W.X[b].1U=c.1U,z.W.X[b].1h.L.G+=c.1J.L.G,z.W.X[b].1h.L.E+=c.1J.L.E,z.W.X[b].17.N=c.17.N)},z)),z.1F=b},1p:C(){z.2H(),1r.3B&&1r.3B.8r(19);I b=z.1N(),c=z.F;z.1h=a("<1Q>").2I("8s")[0],a(b.4s).1C(z.1h),z.4r(),z.6w(b),c.1c&&(z.6x(b),c.1c.13&&(z.2x?(z.2x.F=c.1c.13,z.2x.1p()):z.2x=31 i(z.Q,a.U({2m:z.23},c.1c.13)))),n.3y&&7>n.3y&&a(b.S).5q(z.2y=a("<8t>").2I("8u").1w({8v:0,3Q:"8w:\'\';"})),z.4t(),c.13&&(z.13?(z.13.F=c.13,z.13.1p()):z.13=31 h(z.Q,z,a.U({2m:z.23},c.13))),z.6v()},1e:C(){z.2H(),z.F.13&&(v.1e(z.Q),z.F.1c&&z.F.1c.13&&w.1e(z.Q)),z.2y&&(z.2y.1e(),z.2y=1d),z.S&&(a(z.S).1e(),z.S=1d)},2H:C(){z.1h&&(z.1c&&(a(z.1c).1e(),z.5r=z.5s=z.1c=1d),a(z.1h).1e(),z.1h=z.T=z.V=1d,z.W={})},1N:C(){J x.14(z.Q)[0]},2r:C(){I b=z.1N(),c=a(b.S),d=a(b.S).5t(".6y").6z()[0];O(d){a(d).Z({D:"5u",H:"5u"});I e=2q(c.Z("G")),f=2q(c.Z("E")),g=2q(c.Z("D"));c.Z({E:"-6A",G:"-6A",D:"8x",H:"5u"}),b.1j("1k")||a(b.S).1u();I h=x.4u.5v(d);b.F.2S&&"27"==a.12(b.F.2S)&&h.D>b.F.2S&&(a(d).Z({D:b.F.2S+"22"}),h=x.4u.5v(d)),b.1j("1k")||a(b.S).1l(),b.W.2L=h,c.Z({E:f+"22",G:e+"22",D:g+"22"}),z.1p()}},3R:C(a){z.1F!=a&&(z.1F=a,z.1p())},6x:C(b){I c=b.F.1c,c={D:c.35+2*c.R,H:c.35+2*c.R};a(b.S).1C(a(z.1c=19.1G("1Q")).1w({"29":"6B"}).Z(d(c)).1C(a(z.6C=19.1G("1Q")).1w({"29":"8y"}).Z(d(c)))),z.5w(b,"5x"),z.5w(b,"5y"),a(z.1c).36("3S",a.15(z.6D,z)).36("4v",a.15(z.6E,z))},5w:C(b,c){I e=b.F.1c,g=e.35,h=e.R||0,i=e.x.35,j=e.x.28,k=e.1Y[c||"5x"],l={D:g+2*h,H:g+2*h};i>=g&&(i=g-2);I m;a(z.6C).1C(a(z[c+"6F"]=19.1G("1Q")).1w({"29":"8z"}).Z(a.U(d(l),{E:("5y"==c?l.D:0)+"22"}))),a(19.2N).1C(a(m=19.1G("2P")).1w(l)),q.30(m),e=m.3g("2d"),e.2m=z.23,a(z[c+"6F"]).1C(m),e.8A(l.D/2,l.H/2),e.2t=q.3D(e,k.T,{3i:0,3j:0-g/2,3k:0,3l:0+g/2}),e.1O(),e.1L(0,0,g/2,0,2*K.2A,!0),e.1P(),e.2F(),h&&(e.2t=q.3D(e,k.R,{3i:0,3j:0-g/2-h,3k:0,3l:0+g/2+h}),e.1O(),e.1L(0,0,g/2,K.2A,0,!1),e.M((g+h)/2,0),e.1L(0,0,g/2+h,0,K.2A,!0),e.1L(0,0,g/2+h,K.2A,0,!0),e.M(g/2,0),e.1L(0,0,g/2,0,K.2A,!1),e.1P(),e.2F()),g=i/2,j/=2,j>g&&(h=j,j=g,g=h),e.2t=t.2u(k.x.1q||k.x,k.x.1m||1),e.4w(f(45)),e.1O(),e.32(0,0),e.M(0,g);1E(k=0;4>k;k++)e.M(0,g),e.M(j,g),e.M(j,g-(g-j)),e.M(g,j),e.M(g,0),e.4w(f(90));e.1P(),e.2F()},6w:C(b){I c=z.1W(),d=z.F.V&&z.3T(),e=z.1F&&z.1F.34(),f=z.Y,g=z.R,b=b.F.V&&b.F.V.1f||{x:0,y:0},h=0,i=0;f&&(h="T"==z.F.Y.L?f:0,i="R"==z.F.Y.L?f:h+g),a(19.2N).1C(z.2J=19.1G("2P")),a(z.2J).1w(c.1h.N),q.30(z.2J),f=z.2J.3g("2d"),f.2m=z.23,a(z.1h).1C(z.2J),f.2t=q.3D(f,z.F.T,{3i:0,3j:c.T.L.G+g,3k:0,3l:c.T.L.G+c.T.N.H-g}),f.8B=0,z.5z(f,{1O:!0,1P:!0,R:g,Y:h,4x:i,37:c,38:d,V:z.F.V,39:e,3a:b}),f.2F();O(g){I j=q.3D(f,z.F.R,{3i:0,3j:c.T.L.G,3k:0,3l:c.T.L.G+c.T.N.H});f.2t=j,z.5z(f,{1O:!0,1P:!1,R:g,Y:h,4x:i,37:c,38:d,V:z.F.V,39:e,3a:b}),z.6G(f,{1O:!1,1P:!0,R:g,6H:h,Y:{28:i,L:z.F.Y.L},37:c,38:d,V:z.F.V,39:e,3a:b}),f.2F()}},5z:C(b,c){I d=a.U({V:!1,39:1d,1O:!1,1P:!1,37:1d,38:1d,Y:0,R:0,4x:0,3a:{x:0,y:0}},c||{}),e=d.37,g=d.38,h=d.3a,i=d.R,j=d.Y,k=d.39,l=e.T.L,e=e.T.N,m,n,o;g&&(m=g.V.N,n=g.2R.N,o=d.4x,g=i+j+.5*m.D-.5*g.R.N.D,o=K.1i(o>g?o-g:0));I p,g=j?l.E+i+j:l.E+i;p=l.G+i,h&&h.x&&/^(3m|3p)$/.4y(k)&&(g+=h.x),d.1O&&b.1O(),b.32(g,p);O(d.V)1s(k){P"3m":g=l.E+i,j&&(g+=j),g+=K.1o(o,h.x||0),b.M(g,p),p-=m.H,g+=.5*m.D,b.M(g,p),p+=m.H,g+=.5*m.D,b.M(g,p);1a;P"3F":P"4z":g=l.E+.5*e.D-.5*m.D,b.M(g,p),p-=m.H,g+=.5*m.D,b.M(g,p),p+=m.H,g+=.5*m.D,b.M(g,p),g=l.E+.5*e.D-.5*n.D,b.M(g,p);1a;P"3n":g=l.E+e.D-i-m.D,j&&(g-=j),g-=K.1o(o,h.x||0),b.M(g,p),p-=m.H,g+=.5*m.D,b.M(g,p),p+=m.H,g+=.5*m.D,b.M(g,p)}j?j&&(b.1L(l.E+e.D-i-j,l.G+i+j,j,f(-90),f(0),!1),g=l.E+e.D-i,p=l.G+i+j):(g=l.E+e.D-i,p=l.G+i,b.M(g,p));O(d.V)1s(k){P"3o":p=l.G+i,j&&(p+=j),p+=K.1o(o,h.y||0),b.M(g,p),g+=m.H,p+=.5*m.D,b.M(g,p),g-=m.H,p+=.5*m.D,b.M(g,p);1a;P"3G":P"4A":p=l.G+.5*e.H-.5*m.D,b.M(g,p),g+=m.H,p+=.5*m.D,b.M(g,p),g-=m.H,p+=.5*m.D,b.M(g,p);1a;P"3H":p=l.G+e.H-i,j&&(p-=j),p-=m.D,p-=K.1o(o,h.y||0),b.M(g,p),g+=m.H,p+=.5*m.D,b.M(g,p),g-=m.H,p+=.5*m.D,b.M(g,p)}j?j&&(b.1L(l.E+e.D-i-j,l.G+e.H-i-j,j,f(0),f(90),!1),g=l.E+e.D-i-j,p=l.G+e.H-i):(g=l.E+e.D-i,p=l.G+e.H-i,b.M(g,p));O(d.V)1s(k){P"3I":g=l.E+e.D-i,j&&(g-=j),g-=K.1o(o,h.x||0),b.M(g,p),g-=.5*m.D,p+=m.H,b.M(g,p),g-=.5*m.D,p-=m.H,b.M(g,p);1a;P"3J":P"4B":g=l.E+.5*e.D+.5*m.D,b.M(g,p),g-=.5*m.D,p+=m.H,b.M(g,p),g-=.5*m.D,p-=m.H,b.M(g,p);1a;P"3K":g=l.E+i+m.D,j&&(g+=j),g+=K.1o(o,h.x||0),b.M(g,p),g-=.5*m.D,p+=m.H,b.M(g,p),g-=.5*m.D,p-=m.H,b.M(g,p)}j?j&&(b.1L(l.E+i+j,l.G+e.H-i-j,j,f(90),f(2f),!1),g=l.E+i,p=l.G+e.H-i-j):(g=l.E+i,p=l.G+e.H-i,b.M(g,p));O(d.V)1s(k){P"3L":p=l.G+e.H-i,j&&(p-=j),p-=K.1o(o,h.y||0),b.M(g,p),g-=m.H,p-=.5*m.D,b.M(g,p),g+=m.H,p-=.5*m.D,b.M(g,p);1a;P"3M":P"4C":p=l.G+.5*e.H+.5*m.D,b.M(g,p),g-=m.H,p-=.5*m.D,b.M(g,p),g+=m.H,p-=.5*m.D,b.M(g,p);1a;P"3p":p=l.G+i+m.D,j&&(p+=j),p+=K.1o(o,h.y||0),b.M(g,p),g-=m.H,p-=.5*m.D,b.M(g,p),g+=m.H,p-=.5*m.D,b.M(g,p)}J j?j&&(b.1L(l.E+i+j,l.G+i+j,j,f(-2f),f(-90),!1),g=l.E+i+j,p=l.G+i,g+=1,b.M(g,p)):(g=l.E+i,p=l.G+i,b.M(g,p)),d.1P&&b.1P(),{x:g,y:p}},6G:C(b,c){I d=a.U({V:!1,39:1d,1O:!1,1P:!1,37:1d,38:1d,Y:0,R:0,8C:0,3a:{x:0,y:0}},c||{}),e=d.37,g=d.38,h=d.3a,i=d.R,j=d.Y&&d.Y.28||0,k=d.6H,l=d.39,m=e.T.L,e=e.T.N,n,o,p;g&&(n=g.V.N,o=g.R.N,p=i+k+.5*n.D-.5*o.D,p=K.1i(j>p?j-p:0));I g=m.E+i+k,q=m.G+i;k&&(g+=1),a.U({},{x:g,y:q}),d.1O&&b.1O();I r=a.U({},{x:g,y:q}),q=q-i;b.M(g,q),j?j&&(b.1L(m.E+j,m.G+j,j,f(-90),f(-2f),!0),g=m.E,q=m.G+j):(g=m.E,q=m.G,b.M(g,q));O(d.V)1s(l){P"3p":q=m.G+i,k&&(q+=k),q-=.5*o.D,q+=.5*n.D,q+=K.1o(p,h.y||0),b.M(g,q),g-=o.H,q+=.5*o.D,b.M(g,q),g+=o.H,q+=.5*o.D,b.M(g,q);1a;P"3M":P"4C":q=m.G+.5*e.H-.5*o.D,b.M(g,q),g-=o.H,q+=.5*o.D,b.M(g,q),g+=o.H,q+=.5*o.D,b.M(g,q);1a;P"3L":q=m.G+e.H-i-o.D,k&&(q-=k),q+=.5*o.D,q-=.5*n.D,q-=K.1o(p,h.y||0),b.M(g,q),g-=o.H,q+=.5*o.D,b.M(g,q),g+=o.H,q+=.5*o.D,b.M(g,q)}j?j&&(b.1L(m.E+j,m.G+e.H-j,j,f(-2f),f(-8D),!0),g=m.E+j,q=m.G+e.H):(g=m.E,q=m.G+e.H,b.M(g,q));O(d.V)1s(l){P"3K":g=m.E+i,k&&(g+=k),g-=.5*o.D,g+=.5*n.D,g+=K.1o(p,h.x||0),b.M(g,q),q+=o.H,g+=.5*o.D,b.M(g,q),q-=o.H,g+=.5*o.D,b.M(g,q);1a;P"3J":P"4B":g=m.E+.5*e.D-.5*o.D,b.M(g,q),q+=o.H,g+=.5*o.D,b.M(g,q),q-=o.H,g+=.5*o.D,b.M(g,q),g=m.E+.5*e.D+o.D,b.M(g,q);1a;P"3I":g=m.E+e.D-i-o.D,k&&(g-=k),g+=.5*o.D,g-=.5*n.D,g-=K.1o(p,h.x||0),b.M(g,q),q+=o.H,g+=.5*o.D,b.M(g,q),q-=o.H,g+=.5*o.D,b.M(g,q)}j?j&&(b.1L(m.E+e.D-j,m.G+e.H-j,j,f(90),f(0),!0),g=m.E+e.D,q=m.G+e.D+j):(g=m.E+e.D,q=m.G+e.H,b.M(g,q));O(d.V)1s(l){P"3H":q=m.G+e.H-i,q+=.5*o.D,q-=.5*n.D,k&&(q-=k),q-=K.1o(p,h.y||0),b.M(g,q),g+=o.H,q-=.5*o.D,b.M(g,q),g-=o.H,q-=.5*o.D,b.M(g,q);1a;P"3G":P"4A":q=m.G+.5*e.H+.5*o.D,b.M(g,q),g+=o.H,q-=.5*o.D,b.M(g,q),g-=o.H,q-=.5*o.D,b.M(g,q);1a;P"3o":q=m.G+i,k&&(q+=k),q+=o.D,q-=.5*o.D-.5*n.D,q+=K.1o(p,h.y||0),b.M(g,q),g+=o.H,q-=.5*o.D,b.M(g,q),g-=o.H,q-=.5*o.D,b.M(g,q)}j?j&&(b.1L(m.E+e.D-j,m.G+j,j,f(0),f(-90),!0),q=m.G):(g=m.E+e.D,q=m.G,b.M(g,q));O(d.V)1s(l){P"3n":g=m.E+e.D-i,g+=.5*o.D-.5*n.D,k&&(g-=k),g-=K.1o(p,h.x||0),b.M(g,q),q-=o.H,g-=.5*o.D,b.M(g,q),q+=o.H,g-=.5*o.D,b.M(g,q);1a;P"3F":P"4z":g=m.E+.5*e.D+.5*o.D,b.M(g,q),q-=o.H,g-=.5*o.D,b.M(g,q),q+=o.H,g-=.5*o.D,b.M(g,q),g=m.E+.5*e.D-o.D,b.M(g,q),b.M(g,q);1a;P"3m":g=m.E+i+o.D,g-=.5*o.D,g+=.5*n.D,k&&(g+=k),g+=K.1o(p,h.x||0),b.M(g,q),q-=o.H,g-=.5*o.D,b.M(g,q),q+=o.H,g-=.5*o.D,b.M(g,q)}b.M(r.x,r.y-i),b.M(r.x,r.y),d.1P&&b.1P()},6D:C(){I b=z.1N().F.1c,b=b.35+2*b.R;a(z.5s).Z({E:-1*b+"22"}),a(z.5r).Z({E:0})},6E:C(){I b=z.1N().F.1c,b=b.35+2*b.R;a(z.5s).Z({E:0}),a(z.5r).Z({E:b+"22"})},3T:C(){J s.3r(z,z.R)},1W:C(){I a,b,c,d,e,g,h=z.2L,i=z.1N().F,j=z.Y,k=z.R,l=z.1V,h={D:2*k+2*l+h.D,H:2*k+2*l+h.H};z.F.V&&z.3T();I m=s.5m(z,h),l=m.N,n=m.L,h=m.T.N,o=m.T.L,p=0,q=0,r=l.D,t=l.H;J i.1c&&(e=j,"T"==i.Y.L&&(e+=k),p=e-K.8E(f(45))*e,k="1B",z.1F.34().2O(/^(3n|3o)$/)&&(k="E"),g=e=i=i.1c.35+2*i.1c.R,q=o.E-i/2+("E"==k?p:h.D-p),p=o.G-i/2+p,"E"==k?0>q&&(i=K.2a(q),r+=i,n.E+=i,q=0):(i=q+i-r,0<i&&(r+=i)),0>p&&(i=K.2a(p),t+=i,n.G+=i,p=0),z.F.1c.13)&&(a=z.F.1c.13,b=a.2C,i=a.1f,c=e+2*b,d=g+2*b,a=p-b+i.y,b=q-b+i.x,"E"==k?0>b&&(i=K.2a(b),r+=i,n.E+=i,q+=i,b=0):(i=b+c-r,0<i&&(r+=i)),0>a)&&(i=K.2a(a),t+=i,n.G+=i,p+=i,a=0),m=m.1U,m.G+=n.G,m.E+=n.E,k={E:K.1i(n.E+o.E+z.R+z.F.1V),G:K.1i(n.G+o.G+z.R+z.F.1V)},h={17:{N:{D:K.1i(r),H:K.1i(t)}},1J:{N:{D:K.1i(r),H:K.1i(t)}},1h:{N:l,L:{G:K.1I(n.G),E:K.1I(n.E)}},T:{N:{D:K.1i(h.D),H:K.1i(h.H)},L:{G:K.1I(o.G),E:K.1I(o.E)}},1U:{G:K.1I(m.G),E:K.1I(m.E)},2n:{L:k}},z.F.1c&&(h.1c={N:{D:K.1i(e),H:K.1i(g)},L:{G:K.1I(p),E:K.1I(q)}},z.F.1c.13&&(h.2x={N:{D:K.1i(c),H:K.1i(d)},L:{G:K.1I(a),E:K.1I(b)}})),h},4t:C(){I b=z.1W(),c=z.1N();a(c.S).Z(d(b.17.N)),a(c.4s).Z(d(b.1J.N)),z.2y&&z.2y.Z(d(b.17.N)),a(z.1h).Z(a.U(d(b.1h.N),d(b.1h.L))),z.1c&&(a(z.1c).Z(d(b.1c.L)),b.2x&&a(z.2x.S).Z(d(b.2x.L))),a(c.2T).Z(d(b.2n.L))},6I:C(a){z.23=a||0,z.13&&(z.13.23=z.23)},8F:C(a){z.6I(a),z.1p()}}}());I v={2U:{},14:C(b){O(!b)J 1d;I c=1d;J(b=a(b).1x("1X-1t"))&&(c=z.2U[b]),c},2B:C(a){z.2U[a.1t]=a},1e:C(a){O(a=z.14(a))3P z.2U[a.1t],a.1e()},3U:C(a){J K.2A/2-K.4j(a,K.4o(a)*K.2A)},3V:{3O:C(a,b){I c=u.14(a.Q).3T().R.N,c=z.4n(c.D,c.H,b,{3q:!1});J{D:c.D,H:c.H}},8G:C(a,b,c){I d=.5*a,g=2f-e(K.8H(d/K.6J(d*d+b*b)))-90,g=f(g),c=1/K.4o(g)*c,d=2*(d+c);J{D:d,H:d/a*b}},4n:C(a,b,c){I d=2f-e(K.6q(.5*(b/a))),c=K.4o(f(d-90))*c,c=a+2*c;J{D:c,H:c*b/a}},3r:C(b){I c=u.14(b.Q),d=b.F.2C,e=r.6p(c.1F);r.2g(c.1F),c=v.3V.3O(b,d),c={2R:{N:{D:K.1i(c.D),H:K.1i(c.H)},L:{G:0,E:0}}};O(d){c.2z=[];1E(I f=0;f<=d;f++){I g=v.3V.3O(b,f,{3q:!1});c.2z.2s({L:{G:c.2R.N.H-g.H,E:e?d-f:(c.2R.N.D-g.D)/2},N:g})}}1H c.2z=[a.U({},c.2R)];J c},4w:C(a,b,c){s.4w(a,b.2V(),c)}}};a.U(h.3e,C(){J{4r:C(){},1e:C(){z.2H()},2H:C(){z.S&&(a(z.S).1e(),z.S=z.1h=z.T=z.V=1d,z.W={})},1p:C(){z.2H(),z.4r();I b=z.1N(),c=z.2V();z.S=a("<1Q>").2I("8I")[0],a(b.S).5q(z.S),c.2y&&a(b.S).5q(c.2y),c.1W(),a(z.S).Z({G:0,E:0}),z.6K(),z.4t()},1N:C(){J x.14(z.Q)[0]},2V:C(){J u.14(z.Q)},1W:C(){I b=z.2V(),c=b.1W();z.1N();I d=z.F.2C,e=a.U({},c.T.N);e.D+=2*d,e.H+=2*d;I f;b.F.V&&(f=v.3V.3r(z).2R.N,f=f.H);I g=s.5m(b,e,f);f=g.N;I h=g.L,e=g.T.N,g=g.T.L,i=c.1h.L,j=c.T.L,d={G:i.G+j.G-(g.G+d)+z.F.1f.y,E:i.E+j.E-(g.E+d)+z.F.1f.x},i=c.1U,j=c.1J.N,k={G:0,E:0};O(0>d.G){I l=K.2a(d.G);k.G+=l,d.G=0,i.G+=l}J 0>d.E&&(l=K.2a(d.E),k.E+=l,d.E=0,i.E+=l),l={H:K.1o(f.H+d.G,j.H+k.G),D:K.1o(f.D+d.E,j.D+k.E)},b={E:K.1i(k.E+c.1h.L.E+c.T.L.E+b.R+b.1V),G:K.1i(k.G+c.1h.L.G+c.T.L.G+b.R+b.1V)},{17:{N:l},1J:{N:j,L:k},S:{N:f,L:d},1h:{N:f,L:{G:K.1I(h.G),E:K.1I(h.E)}},T:{N:{D:K.1i(e.D),H:K.1i(e.H)},L:{G:K.1I(g.G),E:K.1I(g.E)}},1U:i,2n:{L:b}}},6L:C(){J z.F.1m/(z.F.2C+1)},6K:C(){I b=z.2V(),c=b.1W(),e=z.1N(),f=z.1W(),g=z.F.2C,h=v.3V.3r(z),i=b.1F,j=r.5k(i),k=g,l=g;O(e.F.V){I m=h.2z[h.2z.1y-1];"E"==j&&(l+=K.1i(m.N.H)),"G"==j&&(k+=K.1i(m.N.H))}I n=b.W.F,m=n.Y,n=n.R;"T"==e.F.Y.L&&m&&(m+=n),a(z.S).1C(a(z.1h=19.1G("1Q")).1w({"29":"8J"}).Z(d(f.1h.N))).Z(d(f.1h.N)),a(19.2N).1C(a(z.2J=19.1G("2P")).1w(f.1h.N)),q.30(z.2J),e=z.2J.3g("2d"),e.2m=z.23,a(z.1h).1C(z.2J);1E(I f=g+1,o=0;o<=g;o++)e.2t=t.2u(z.F.1q,v.3U(o*(1/f))*(z.F.1m/f)),q.6h(e,{D:c.T.N.D+2*o,H:c.T.N.H+2*o,G:k-o,E:l-o,Y:m+o});O(b.F.V){I o=h.2z[0].N,p=b.F.V,g=n+.5*p.D,s=b.F.Y&&"T"==b.F.Y.L?b.F.Y.28||0:0;s&&(g+=s),n=n+s+.5*p.D-.5*o.D,m=K.1i(m>n?m-n:0),g+=K.1o(m,b.F.V.1f&&b.F.V.1f[j&&/^(E|1B)$/.4y(j)?"y":"x"]||0);O("G"==j||"1A"==j){1s(i){P"3m":P"3K":l+=g;1a;P"3F":P"4z":P"3J":P"4B":l+=.5*c.T.N.D;1a;P"3n":P"3I":l+=c.T.N.D-g}"1A"==j&&(k+=c.T.N.H),o=0;1E(b=h.2z.1y;o<b;o++)e.2t=t.2u(z.F.1q,v.3U(o*(1/f))*(z.F.1m/f)),g=h.2z[o],e.1O(),"G"==j?(e.32(l,k-o),e.M(l-.5*g.N.D,k-o),e.M(l,k-o-g.N.H),e.M(l+.5*g.N.D,k-o)):(e.32(l,k+o),e.M(l-.5*g.N.D,k+o),e.M(l,k+o+g.N.H),e.M(l+.5*g.N.D,k+o)),e.1P(),e.2F()}1H{1s(i){P"3p":P"3o":k+=g;1a;P"3M":P"4C":P"3G":P"4A":k+=.5*c.T.N.H;1a;P"3L":P"3H":k+=c.T.N.H-g}"1B"==j&&(l+=c.T.N.D),o=0;1E(b=h.2z.1y;o<b;o++)e.2t=t.2u(z.F.1q,v.3U(o*(1/f))*(z.F.1m/f)),g=h.2z[o],e.1O(),"E"==j?(e.32(l-o,k),e.M(l-o,k-.5*g.N.D),e.M(l-o-g.N.H,k),e.M(l-o,k+.5*g.N.D)):(e.32(l+o,k),e.M(l+o,k-.5*g.N.D),e.M(l+o+g.N.H,k),e.M(l+o,k+.5*g.N.D)),e.1P(),e.2F()}}},4t:C(){I b=z.1W(),c=z.2V(),e=z.1N();a(e.S).Z(d(b.17.N)),a(e.4s).Z(a.U(d(b.1J.L),d(b.1J.N))),c.2y&&c.2y.Z(d(b.17.N));O(e.F.1c){I f=c.1W(),g=b.1J.L,h=f.1c.L;a(c.1c).Z(d({G:g.G+h.G,E:g.E+h.E})),e.F.1c.13&&(f=f.2x.L,a(c.2x.S).Z(d({G:g.G+f.G,E:g.E+f.E})))}a(z.S).Z(a.U(d(b.S.N),d(b.S.L))),a(z.1h).Z(d(b.1h.N)),a(e.2T).Z(d(b.2n.L))}}}());I w={2U:{},14:C(b){J b?(b=a(b).1x("1X-1t"))?z.2U[b]:1d:1d},2B:C(a){z.2U[a.1t]=a},1e:C(a){O(a=z.14(a))3P z.2U[a.1t],a.1e()}};a.U(i.3e,C(){J{1p:C(){z.2H(),z.1N();I b=z.2V(),c=b.1W().1c.N,d=a.U({},c),e=z.F.2C;d.D+=2*e,d.H+=2*e,a(b.1c).5A(a(z.S=19.1G("1Q")).1w({"29":"8K"})),a(19.2N).1C(a(z.4D=19.1G("2P")).1w(d)),q.30(z.4D),b=z.4D.3g("2d"),b.2m=z.23,a(z.S).1C(z.4D);1E(I g=d.D/2,d=d.H/2,c=c.H/2,h=e+1,i=0;i<=e;i++)b.2t=t.2u(z.F.1q,v.3U(i*(1/h))*(z.F.1m/h)),b.1O(),b.1L(g,d,c+i,f(0),f(6u),!0),b.1P(),b.2F()},1e:C(){z.2H()},2H:C(){z.S&&(a(z.S).1e(),z.S=1d)},1N:C(){J x.14(z.Q)[0]},2V:C(){J u.14(z.Q)},6L:C(){J z.F.1m/(z.F.2C+1)}}}());I x={2b:{},F:{3s:"5B",42:8L},6f:C(){J C(){I b=["2c"];1z.2Q.5f&&(b.2s("8M"),a(19.2N).36("2c",C(){})),a.1b(b,C(b,c){a(19.6M).36(c,C(b){I c=m.3f(b,".3b .6B, .3b .8N-17");c&&(b.8O(),b.8P(),x.5C(a(c).4b(".3b")[0]).1l())})}),a(1r).36("8Q",a.15(z.6N,z))}}(),6N:C(){z.5D&&(1r.5E(z.5D),z.5D=1d),1r.49(a.15(C(){I b=z.3h();a.1b(b,C(a,b){b.L()})},z),8R)},4E:C(b){I c=a(b).1x("1X-1t"),d;c||(b=z.5C(a(b).4b(".3b")[0]))&&b.Q&&(c=a(b.Q).1x("1X-1t"));O(c&&(d=z.2b[c]))J d},3f:C(a){I b;J m.1T(a)&&(b=z.4E(a)),b&&b.Q},14:C(b){I c=[];O(m.1T(b)){I d=z.4E(b);d&&(c=[d])}1H a.1b(z.2b,C(d,e){e.Q&&a(e.Q).6O(b)&&c.2s(e)});J c},5C:C(b){O(!b)J 1d;I c=1d;J a.1b(z.2b,C(a,d){d.1j("1p")&&d.S===b&&(c=d)}),c},8S:C(b){I c=[];J a.1b(z.2b,C(d,e){e.Q&&a(e.Q).6O(b)&&c.2s(e)}),c},1u:C(b){m.1T(b)?(b=z.14(b)[0])&&b.1u():a(b).1b(a.15(C(a,b){I c=z.14(b)[0];c&&c.1u()},z))},1l:C(b){m.1T(b)?(b=z.14(b)[0])&&b.1l():a(b).1b(a.15(C(a,b){I c=z.14(b)[0];c&&c.1l()},z))},2E:C(b){m.1T(b)?(b=z.14(b)[0])&&b.2E():a(b).1b(a.15(C(a,b){I c=z.14(b)[0];c&&c.2E()},z))},4l:C(){a.1b(z.3h(),C(a,b){b.1l()})},2r:C(b){m.1T(b)?(b=z.14(b)[0])&&b.2r():a(b).1b(a.15(C(a,b){I c=z.14(b)[0];c&&c.2r()},z))},3h:C(){I b=[];J a.1b(z.2b,C(a,c){c.1k()&&b.2s(c)}),b},5i:C(a){J m.1T(a)?m.48(z.3h()||[],C(b){J b.Q==a}):!1},1k:C(){J m.56(z.2b,C(a){J a.1k()})},6P:C(){I b=0,c;J a.1b(z.2b,C(a,d){d.1S>b&&(b=d.1S,c=d)}),c},6Q:C(){1>=z.3h().1y&&a.1b(z.2b,C(b,c){c.1j("1p")&&!c.F.1S&&a(c.S).Z({1S:c.1S=+x.F.42})})},2B:C(a){z.2b[a.1t]=a},4F:C(b){O(b=z.4E(b))3P z.2b[a(b.Q).1x("1X-1t")],b.1l(),b.1e()},1e:C(b){m.1T(b)?z.4F(b):a(b).1b(a.15(C(a,b){z.4F(b)},z))},6g:C(){a.1b(z.2b,a.15(C(a,b){b.Q&&!m.Q.59(b.Q)&&z.4F(b.Q)},z))},5g:C(a){z.F.3s=a||"5B"},5h:C(a){z.F.42=a||0},5T:C(){C b(b){J"1Z"==a.12(b)?{Q:f.1K&&f.1K.Q||e.1K.Q,20:b}:j(a.U({},e.1K),b)}C c(b){J e=1z.2i.6R,f=j(a.U({},e),1z.2i.5F),g=1z.2i.5G.6R,h=j(a.U({},g),1z.2i.5G.5F),c=d,d(b)}C d(c){c.1J=c.1J||(1z.2i[x.F.3s]?x.F.3s:"5B");I d=c.1J?a.U({},1z.2i[c.1J]||1z.2i[x.F.3s]):{},d=j(a.U({},f),d),d=j(a.U({},d),c);d.1D&&("3W"==a.12(d.1D)&&(d.1D={3X:f.1D&&f.1D.3X||e.1D.3X,12:f.1D&&f.1D.12||e.1D.12}),d.1D=j(a.U({},e.1D),d.1D)),d.T&&"1Z"==a.12(d.T)&&(d.T={1q:d.T,1m:1});O(d.R){I i;i="27"==a.12(d.R)?{28:d.R,1q:f.R&&f.R.1q||e.R.1q,1m:f.R&&f.R.1m||e.R.1m}:j(a.U({},e.R),d.R),d.R=0===i.28?!1:i}d.Y&&(i="27"==a.12(d.Y)?{28:d.Y,L:f.Y&&f.Y.L||e.Y.L}:j(a.U({},e.Y),d.Y),d.Y=0===i.28?!1:i),i=i=d.X&&d.X.1g||"1Z"==a.12(d.X)&&d.X||f.X&&f.X.1g||"1Z"==a.12(f.X)&&f.X||e.X&&e.X.1g||e.X;I k=d.X&&d.X.17||f.X&&f.X.17||e.X&&e.X.17||x.26.6S(i);O(d.X){O("1Z"==a.12(d.X))i={1g:d.X,17:x.26.6T(d.X)};1H O(i={17:k,1g:i},d.X.17&&(i.17=d.X.17),d.X.1g)i.1g=d.X.1g}1H i={17:k,1g:i};d.X=i,"2o"==d.1g?(k=a.U({},e.1f.2o),a.U(k,1z.2i.5F.1f||{}),c.1J&&a.U(k,(1z.2i[c.1J]||1z.2i[x.F.3s]).1f||{}),k=x.26.6U(e.1f.2o,e.X,i.1g),c.1f&&(k=a.U(k,c.1f||{})),d.3t=0):k={x:d.1f.x,y:d.1f.y},d.1f=k;O(d.1c&&d.6V){I c=a.U({},1z.2i.5G[d.6V]),l=j(a.U({},h),c);l.1Y&&a.1b(["5x","5y"],C(b,c){I d=l.1Y[c],e=h.1Y&&h.1Y[c];O(d.T){I f=e&&e.T;a.12(d.T)=="27"?d.T={1q:f&&f.1q||g.1Y[c].T.1q,1m:d.T}:a.12(d.T)=="1Z"?(f=f&&a.12(f.1m)=="27"&&f.1m||g.1Y[c].T.1m,d.T={1q:d.T,1m:f}):d.T=j(a.U({},g.1Y[c].T),d.T)}d.R&&(e=e&&e.R,d.R=a.12(d.R)=="27"?{1q:e&&e.1q||g.1Y[c].R.1q,1m:d.R}:j(a.U({},g.1Y[c].R),d.R))}),l.13&&(c=h.13&&h.13.3c&&h.13.3c==4U?h.13:g.13,l.13.3c&&l.13.3c==4U&&(c=j(c,l.13)),l.13=c),d.1c=l}d.13&&(c="3W"==a.12(d.13)?f.13&&"3W"==a.12(f.13)?e.13:f.13?f.13:e.13:j(a.U({},e.13),d.13||{}),"27"==a.12(c.1f)&&(c.1f={x:c.1f,y:c.1f}),d.13=c),d.V&&(c={},c="3W"==a.12(d.V)?j({},e.V):j(j({},e.V),a.U({},d.V)),"27"==a.12(c.1f)&&(c.1f={x:c.1f,y:c.1f}),d.V=c),d.21&&("1Z"==a.12(d.21)?d.21={4G:d.21,6W:!0}:"3W"==a.12(d.21)&&(d.21=d.21?{4G:"6X",6W:!0}:!1)),d.1K&&"2c-8T"==d.1K&&(d.6Y=!0,d.1K=!1);O(d.1K)O(a.6j(d.1K)){I m=[];a.1b(d.1K,C(a,c){m.2s(b(c))}),d.1K=m}1H d.1K=[b(d.1K)];J d.2j&&"1Z"==a.12(d.2j)&&(d.2j=[""+d.2j]),d.1V=0,d.1n&&!1r.2Z&&(d.1n=!1),d}I e,f,g,h;J c}()};x.26=C(){C b(b,c){I d=r.2p(b),e=d[1],d=d[2],f=r.2g(b),g=a.U({1v:!0,2h:!0},c||{});J"1v"==f?(g.2h&&(e=k[e]),g.1v&&(d=k[d])):(g.2h&&(d=k[d]),g.1v&&(e=k[e])),e+d}C c(b,c){O(b.F.21){I d=c,e=j(b),f=e.N,e=e.L,g=u.14(b.Q).W.X[d.X.17].17.N,h=d.L;e.E>h.E&&(d.L.E=e.E),e.G>h.G&&(d.L.G=e.G),e.E+f.D<h.E+g.D&&(d.L.E=e.E+f.D-g.D),e.G+f.H<h.G+g.H&&(d.L.G=e.G+f.H-g.H),c=d}b.3R(c.X.17),d=c.L,a(b.S).Z({G:d.G+"22",E:d.E+"22"})}C d(a){J a&&(/^2o|2c|5f$/.4y("1Z"==6Z a.12&&a.12||"")||0<=a.61)}C e(a,b,c,d){I e=a>=c&&a<=d,f=b>=c&&b<=d;J e&&f?b-a:e&&!f?d-a:!e&&f?b-c:(e=c>=a&&c<=b,f=d>=a&&d<=b,e&&f?d-c:e&&!f?b-c:!e&&f?d-a:0)}C f(a,b){I c=a.N.D*a.N.H;J c?e(a.L.E,a.L.E+a.N.D,b.L.E,b.L.E+b.N.D)*e(a.L.G,a.L.G+a.N.H,b.L.G,b.L.G+b.N.H)/c:0}C g(a,b){I c=r.2p(b),d={E:0,G:0};O("1v"==r.2g(b)){1s(c[2]){P"2v":P"2w":d.E=.5*a.D;1a;P"1B":d.E=a.D}"1A"==c[1]&&(d.G=a.H)}1H{1s(c[2]){P"2v":P"2w":d.G=.5*a.H;1a;P"1A":d.G=a.H}"1B"==c[1]&&(d.E=a.D)}J d}C h(b){I c=m.Q.4g(b),b=m.Q.4c(b),d=a(1r).4d(),e=a(1r).4e();J c.E+=-1*(b.E-e),c.G+=-1*(b.G-d),c}C i(c,e,i,k){I n,o,p=u.14(c.Q),q=p.F.1f,s=d(i);s||!i?(o={D:1,H:1},s?(n=m.4a(i),n={G:n.y,E:n.x}):(n=c.W.20,n={G:n?n.y:0,E:n?n.x:0}),c.W.20={x:n.E,y:n.G}):(n=h(i),o={D:a(i).70(),H:a(i).71()});O(p.F.V&&"2o"!=p.F.1g){I i=r.2p(k),t=r.2p(e),w=r.2g(k),x=p.W.F,y=p.3T().R.N,A=x.Y,x=x.R,B=A&&"T"==p.F.Y.L?A:0,A=A&&"R"==p.F.Y.L?A:A+x,y=x+B+.5*p.F.V.D-.5*y.D,y=K.1i(x+B+.5*p.F.V.D+(A>y?A-y:0)+p.F.V.1f["1v"==w?"x":"y"]);O("1v"==w&&"E"==i[2]&&"E"==t[2]||"1B"==i[2]&&"1B"==t[2])o.D-=2*y,n.E+=y;1H O("2h"==w&&"G"==i[2]&&"G"==t[2]||"1A"==i[2]&&"1A"==t[2])o.H-=2*y,n.G+=y}i=a.U({},n),p=s?b(p.F.X.17):p.F.X.1g,g(o,p),s=g(o,k),n={E:n.E+s.E,G:n.G+s.G},q=a.U({},q),q=l(q,p,k),n.G+=q.y,n.E+=q.x,p=u.14(c.Q),q=p.W.X,s=a.U({},q[e]),n={G:n.G-s.1U.G,E:n.E-s.1U.E},s.17.L=n,s={1v:!0,2h:!0};O(c.F.21){O(t=j(c),c=(c.F.13?v.14(c.Q):p).1W().17.N,s.2k=f({N:c,L:n},t),1>s.2k){O(n.E<t.L.E||n.E+c.D>t.L.E+t.N.D)s.1v=!1;O(n.G<t.L.G||n.G+c.H>t.L.G+t.N.H)s.2h=!1}}1H s.2k=1;J c=q[e].1h,o=f({N:o,L:i},{N:c.N,L:{G:n.G+c.L.G,E:n.E+c.L.E}}),{L:n,2k:{1g:o},3u:s,X:{17:e,1g:k}}}C j(b){I c={G:a(1r).4d(),E:a(1r).4e()},d=b.F.1g;O("2o"==d||"46"==d)d=b.Q;d=a(d).4b(b.F.21.4G).6z()[0];O(!d||"6X"==b.F.21.4G)J{N:{D:a(1r).D(),H:a(1r).H()},L:c};I b=m.Q.4g(d),e=m.Q.4c(d);J b.E+=-1*(e.E-c.E),b.G+=-1*(e.G-c.G),{N:{D:a(d).72(),H:a(d).73()},L:b}}I k={E:"1B",1B:"E",G:"1A",1A:"G",2v:"2v",2w:"2w"},l=C(){I a=[[-1,-1],[0,-1],[1,-1],[-1,0],[0,0],[1,0],[-1,1],[0,1],[1,1]],b={3p:0,3m:0,3F:1,4z:1,3n:2,3o:2,3G:5,4A:5,3H:8,3I:8,3J:7,4B:7,3K:6,3L:6,3M:3,4C:3};J C(c,d,e){I f=a[b[d]],g=a[b[e]],f=[K.5p(.5*K.2a(f[0]-g[0]))?-1:1,K.5p(.5*K.2a(f[1]-g[1]))?-1:1];J!r.2G(d)&&r.2G(e)&&("1v"==r.2g(e)?f[0]=0:f[1]=0),{x:f[0]*c.x,y:f[1]*c.y}}}();J{14:i,74:C(a,d,e,g){I h=i(a,d,e,g);/8U$/.4y(e&&"1Z"==6Z e.12?e.12:"");O(1===h.3u.2k)c(a,h);1H{I j=d,k=g,k={1v:!h.3u.1v,2h:!h.3u.2h};O(!r.2G(d))J j=b(d,k),k=b(g,k),h=i(a,j,e,k),c(a,h),h;O("1v"==r.2g(d)&&k.2h||"2h"==r.2g(d)&&k.1v)O(j=b(d,k),k=b(g,k),h=i(a,j,e,k),1===h.3u.2k)J c(a,h),h;d=[],g=r.3E,j=0;1E(k=g.1y;j<k;j++)1E(I l=g[j],m=0,n=r.3E.1y;m<n;m++)d.2s(i(a,r.3E[m],e,l));1E(I e=h,o=u.14(a.Q).W.X,j=o[e.X.17],g=0,p=e.L.E+j.1U.E,q=e.L.G+j.1U.G,s=0,t=1,v={N:j.17.N,L:e.L},w=0,j=1,l=k=0,m=d.1y;l<m;l++){n=d[l],n.2l={},n.2l.21=n.3u.2k;I x=o[n.X.17].1U,x=K.6J(K.4j(K.2a(n.L.E+x.E-p),2)+K.4j(K.2a(n.L.G+x.G-q),2)),g=K.1o(g,x);n.2l.75=x,x=n.2k.1g,t=K.5o(t,x),s=K.1o(s,x),n.2l.76=x,x=f(v,{N:o[n.X.17].17.N,L:n.L}),j=K.5o(j,x),w=K.1o(w,x),n.2l.77=x,x="1v"==r.2g(e.X.1g)?"G":"E",x=K.2a(e.L[x]-n.L[x]),k=K.1o(k,x),n.2l.78=x}1E(I o=0,y,s=K.1o(e.2k.1g-t,s-e.2k.1g),t=w-j,l=0,m=d.1y;l<m;l++)n=d[l],w=51*n.2l.21,w+=18*(1-n.2l.75/g)||9,p=K.2a(e.2k.1g-n.2l.76)||0,w+=4*(1-(p/s||1)),w+=11*((n.2l.77-j)/t||0),w+=r.2G(n.X.17)?0:25*(1-n.2l.78/(k||1)),o=K.1o(o,w),w==o&&(y=l);c(a,d[y])}J h},6S:b,6T:C(a){J a=r.2p(a),b(a[1]+k[a[2]])},79:h,6U:l,5H:d}}(),x.26.4m={x:0,y:0},a(19).6e(C(){a(19).36("4H",C(a){x.26.4m=m.4a(a)})}),x.4u=C(){C b(b){J{D:a(b).72(),H:a(b).73()}}C c(c){I d=b(c),e=c.4f;J e&&a(e).Z({D:d.D+"22"})&&b(c).H>d.H&&d.D++,a(e).Z({D:"5n%"}),d}J{1p:C(){a(19.2N).1C(a(19.1G("1Q")).1w({"29":"8V"}).1C(a(19.1G("1Q")).1w({"29":"3b"}).1C(a(z.S=19.1G("1Q")).1w({"29":"7a"}))))},3v:C(b,c,d,e){z.S||z.1p(),e=a.U({1n:!1},e||{}),(b.F.7b||m.1T(c))&&!a(c).1x("7c")&&(b.F.7b&&"1Z"==a.12(c)&&(b.2K=a("#"+c)[0],c=b.2K),!b.3w&&c&&m.Q.59(c))&&(a(b.2K).1x("7d",a(b.2K).Z("7e")),b.3w=19.1G("1Q"),a(b.2K).5A(a(b.3w).1l()));I f=19.1G("1Q");a(z.S).1C(a(f).1w({"29":"6y 8W"}).1C(c)),m.1T(c)&&a(c).1u(),b.F.1J&&a(f).2I("8X"+b.F.1J);I g=a(f).5t("7f[3Q]").8Y(C(){J!a(z).1w("H")||!a(z).1w("D")});O(0<g.1y&&!b.1j("3d")){b.1M("3d",!0),b.F.1n&&(!e.1n&&!b.1n&&(b.1n=b.5I(b.F.1n)),b.1j("1k")&&(b.L(),a(b.S).1u()),b.1n.5J());I h=0,c=K.1o(8Z,91*(g.1y||0));b.1R("3d"),b.3x("3d",a.15(C(){g.1b(C(){z.5K=C(){}}),h>=g.1y||(z.4I(b,f),d&&d())},z),c),a.1b(g,a.15(C(c,e){I i=31 92;i.5K=a.15(C(){i.5K=C(){};I c=i.D,j=i.H,k=a(e).1w("D"),l=a(e).1w("H");O(!k||!l)!k&&l?(c=K.1I(l*c/j),j=l):!l&&k&&(j=K.1I(k*j/c),c=k),a(e).1w({D:c,H:j}),h++;h==g.1y&&(b.1R("3d"),b.1n&&(b.1n.1e(),b.1n=1d),b.1j("1k")&&a(b.S).1l(),z.4I(b,f),d&&d())},z),i.3Q=e.3Q},z))}1H z.4I(b,f),d&&d()},4I:C(b,d){I e=c(d),f=e.D-(2q(a(d).Z("1V-E"))||0)-(2q(a(d).Z("1V-1B"))||0);2q(a(d).Z("1V-G")),2q(a(d).Z("1V-1A")),b.F.2S&&"27"==a.12(b.F.2S)&&f>b.F.2S&&(a(d).Z({D:b.F.2S+"22"}),e=c(d)),b.W.2L=e,a(b.2T).7g(d)},5v:c}}(),a.U(k.3e,C(){J{1p:C(){z.1j("1p")||(a(19.2N).1C(a(z.S).Z({E:"-4J",G:"-4J",1S:z.1S}).1C(a(z.4s=19.1G("1Q")).1w({"29":"93"})).1C(a(z.2T=19.1G("1Q")).1w({"29":"7a"}))),a(z.S).2I("94"+z.F.1J),z.F.6Y&&(a(z.Q).2I("7h"),z.2e(19.6M,"2c",a.15(C(a){z.1k()&&(a=m.3f(a,".3b, .7h"),(!a||a&&a!=z.S&&a!=z.Q)&&z.1l())},z))),1z.2Q.3A&&(z.F.3Y||z.F.3t)&&(z.4K(z.F.3Y),a(z.S).2I("5L")),z.7i(),z.1M("1p",!0),x.2B(z))},5W:C(){a(z.S=19.1G("1Q")).1w({"29":"3b"}),z.7j()},7k:C(){z.1p();I a=u.14(z.Q);a?a.1p():(31 g(z.Q),z.1M("44",!0))},7j:C(){z.2e(z.Q,"3S",z.4L),z.2e(z.Q,"4v",a.15(C(a){z.5M(a)},z)),z.F.2j&&a.1b(z.F.2j,a.15(C(b,c){I d=!1;"2c"==c&&(d=z.F.1K&&m.48(z.F.1K,C(a){J"46"==a.Q&&"2c"==a.20}),z.1M("4Y",d)),z.2e(z.Q,c,"2c"==c?d?z.2E:z.1u:a.15(C(){z.7l()},z))},z)),z.F.1K?a.1b(z.F.1K,a.15(C(b,c){I d;1s(c.Q){P"46":O(z.1j("4Y")&&"2c"==c.20)J;d=z.Q;1a;P"1g":d=z.1g}d&&z.2e(d,c.20,"2c"==c.20?z.1l:a.15(C(){z.5N()},z))},z)):z.F.7m&&z.F.2j&&-1<!a.5O("2c",z.F.2j)&&z.2e(z.Q,"4v",a.15(C(){z.1R("1u")},z));I b=!1;!z.F.95&&z.F.2j&&((b=-1<a.5O("4H",z.F.2j))||-1<a.5O("7n",z.F.2j))&&"2o"==z.1g&&z.2e(z.Q,b?"4H":"7n",C(a){z.1j("44")&&z.L(a)})},7i:C(){z.2e(z.S,"3S",z.4L),z.2e(z.S,"4v",z.5M),z.2e(z.S,"3S",a.15(C(){z.4M("3Z")||z.1u()},z)),z.F.1K&&a.1b(z.F.1K,a.15(C(b,c){I d;1s(c.Q){P"17":d=z.S}d&&z.2e(d,c.20,c.20.2O(/^(2c|4H|3S)$/)?z.1l:a.15(C(){z.5N()},z))},z))},1u:C(b){z.1R("1l"),z.1R("3Z");O(!z.1k()){O("C"==a.12(z.2n)||"C"==a.12(z.W.4N)){"C"!=a.12(z.W.4N)&&(z.W.4N=z.2n);I c=z.W.4N(z.Q)||!1;c!=z.W.4Z&&(z.W.4Z=c,z.1M("2W",!1),z.5P()),z.2n=c;O(!c)J}z.F.96&&x.4l(),z.1M("1k",!0),z.F.1D?z.7o(b):z.1j("2W")||z.3v(z.2n),z.1j("44")&&z.L(b),z.4O(),z.F.4P&&m.58(a.15(C(){z.4L()},z)),"C"==a.12(z.F.4Q)&&(!z.F.1D||z.F.1D&&z.F.1D.3X&&z.1j("2W"))&&z.F.4Q(z.2T.4R,z.Q),1z.2Q.3A&&(z.F.3Y||z.F.3t)&&(z.4K(z.F.3Y),a(z.S).2I("7p").7q("5L")),a(z.S).1u()}},1l:C(){z.1R("1u"),z.1j("1k")&&(z.1M("1k",!1),1z.2Q.3A&&(z.F.3Y||z.F.3t)?(z.4K(z.F.3t),a(z.S).7q("7p").2I("5L"),z.3x("3Z",a.15(z.5Q,z),z.F.3t)):z.5Q(),z.W.24)&&(z.W.24.7r(),z.W.24=1d,z.1M("24",!1))},5Q:C(){z.1j("1p")&&(a(z.S).Z({E:"-4J",G:"-4J"}),x.6Q(),z.7s(),"C"==a.12(z.F.7t)&&!z.1n)&&z.F.7t(z.2T.4R,z.Q)},2E:C(a){z[z.1k()?"1l":"1u"](a)},1k:C(){J z.1j("1k")},7l:C(b){z.1R("1l"),z.1R("3Z"),!z.1j("1k")&&!z.4M("1u")&&z.3x("1u",a.15(C(){z.1R("1u"),z.1u(b)},z),z.F.7m||1)},5N:C(){z.1R("1u"),!z.4M("1l")&&z.1j("1k")&&z.3x("1l",a.15(C(){z.1R("1l"),z.1R("3Z"),z.1l()},z),z.F.97||1)},4K:C(a){O(1z.2Q.3A){I a=a||0,b=z.S.98;b.99=a+"4S",b.9a=a+"4S",b.9b=a+"4S",b.9c=a+"4S"}},1M:C(a,b){z.W.1Y[a]=b},1j:C(a){J z.W.1Y[a]},4L:C(){z.1M("43",!0),z.1j("1k")&&z.4O(),z.F.4P&&z.1R("5R")},5M:C(){z.1M("43",!1),z.F.4P&&z.3x("5R",a.15(C(){z.1R("5R"),z.1j("43")||z.1l()},z),z.F.4P)},4M:C(a){J z.W.2M[a]},3x:C(a,b,c){z.W.2M[a]=m.57(b,c)},1R:C(a){z.W.2M[a]&&(1r.5E(z.W.2M[a]),3P z.W.2M[a])},7u:C(){a.1b(z.W.2M,C(a,b){1r.5E(b)}),z.W.2M=[]},2e:C(b,c,d,e){d=a.15(d,e||z),z.W.4X.2s({Q:b,7v:c,7w:d}),a(b).36(c,d)},7x:C(){a.1b(z.W.4X,C(b,c){a(c.Q).7y(c.7v,c.7w)})},3R:C(a){I b=u.14(z.Q);b&&b.3R(a)},7s:C(){z.3R(z.F.X.17)},2r:C(){I a=u.14(z.Q);a&&(a.2r(),z.1k()&&z.L())},3v:C(b,c){I d=a.U({40:z.F.40,1n:!1},c||{});z.1p(),z.1j("1k")&&a(z.S).1l(),x.4u.3v(z,b,a.15(C(){I b=z.1j("1k");b||z.1M("1k",!0),z.7k(),b||z.1M("1k",!1),z.1j("1k")&&(a(z.S).1l(),z.L(),z.4O(),a(z.S).1u()),z.1M("2W",!0),d.40&&d.40(z.2T.4R,z.Q),d.4T&&d.4T()},z),{1n:d.1n})},7o:C(b){z.1j("24")||z.F.1D.3X&&z.1j("2W")||(z.1M("24",!0),z.F.1n&&(z.1n?z.1n.5J():(z.1n=z.5I(z.F.1n),z.1M("2W",!1)),z.L(b)),z.W.24&&(z.W.24.7r(),z.W.24=1d),z.W.24=a.1D({9d:z.2n,12:z.F.1D.12,1x:z.F.1D.1x||{},7z:z.F.1D.7z||"7g",9e:a.15(C(b,c,d){d.9f!==0&&z.3v(d.9g,{1n:z.F.1n&&z.1n,4T:a.15(C(){z.1M("24",!1),z.1j("1k")&&z.F.4Q&&z.F.4Q(z.2T.4R,z.Q),z.1n&&(z.1n.1e(),z.1n=1d)},z)})},z)}))},5I:C(b){I c=19.1G("1Q");a(c).1x("7c",!0);I e=2Z.4k(c,a.U({},b||{})),b=2Z.5l(c);J a(c).Z(d(b)),z.3v(c,{40:!1,4T:C(){e.5J()}}),e},L:C(b){O(z.1k()){I c;O("2o"==z.F.1g){c=x.26.5H(b);I d=x.26.4m;c?d.x||d.y?(z.W.20={x:d.x,y:d.y},c=1d):c=b:(d.x||d.y?z.W.20={x:d.x,y:d.y}:z.W.20||(c=x.26.79(z.Q),z.W.20={x:c.E,y:c.G}),c=1d)}1H c=z.1g;x.26.74(z,z.F.X.17,c,z.F.X.1g);O(b&&x.26.5H(b)){I d=a(z.S).70(),e=a(z.S).71(),b=m.4a(b);c=m.Q.4g(z.S),b.x>=c.E&&b.x<=c.E+d&&b.y>=c.G&&b.y<=c.G+e&&m.58(a.15(C(){z.1R("1l")},z))}}},4O:C(){O(z.1j("1p")&&!z.F.1S){I b=x.6P();b&&b!=z&&z.1S<=b.1S&&a(z.S).Z({1S:z.1S=b.1S+1})}},5P:C(){I b;z.3w&&z.2K&&((b=a(z.2K).1x("7d"))&&a(z.2K).Z({7e:b}),a(z.3w).5A(z.2K).1e(),z.3w=1d)},1e:C(){1r.49(a.15(C(){z.7x()},z),1),z.7u(),z.5P(),1r.49(a.15(C(){a(z.S).5t("7f[3Q]").7y("9h")},z),1),u.1e(z.Q),z.1j("1p")&&z.S&&(a(z.S).1e(),z.S=1d);I b=a(z.Q).1x("4W");b&&(a(z.Q).1w("4V",b),a(z.Q).1x("4W",1d)),a(z.Q).9i("1X-1t")}}}()),1z.30()})(3z)', 62, 577, '|||||||||||||||||||||||||||||||||||this|||function|width|left|options|top|height|var|return|Math|position|lineTo|dimensions|if|case|element|border|container|background|extend|stem|_cache|hook|radius|css|||type|shadow|get|proxy||tooltip||document|break|each|closeButton|null|remove|offset|target|bubble|ceil|getState|visible|hide|opacity|spinner|max|build|color|window|switch|uid|show|horizontal|attr|data|length|Tipped|bottom|right|append|ajax|for|_hookPosition|createElement|else|round|skin|hideOn|arc|setState|getTooltip|beginPath|closePath|div|clearTimer|zIndex|isElement|anchor|padding|getOrderLayout|tipped|states|string|event|containment|px|_globalAlpha|xhr||Position|number|size|class|abs|tooltips|click||setEvent|180|getOrientation|vertical|Skins|showOn|overlap|score|globalAlpha|content|mouse|split|parseInt|refresh|push|fillStyle|hex2fill|middle|center|closeButtonShadow|iframeShim|blurs|PI|add|blur|scripts|toggle|fill|isCenter|cleanup|addClass|bubbleCanvas|inlineContent|contentDimensions|timers|body|match|canvas|support|box|maxWidth|contentElement|shadows|getSkin|updated|call|indexOf|Spinners|init|new|moveTo|charAt|toLowerCase|diameter|bind|layout|stemLayout|hookPosition|cornerOffset|t_Tooltip|constructor|preloading_images|prototype|findElement|getContext|getVisible|x1|y1|x2|y2|topleft|topright|righttop|lefttop|math|getLayout|defaultSkin|fadeOut|contained|update|inlineMarker|setTimer|IE|jQuery|cssTransitions|G_vmlCanvasManager|items|createFillStyle|positions|topmiddle|rightmiddle|rightbottom|bottomright|bottommiddle|bottomleft|leftbottom|leftmiddle|regex|getBorderDimensions|delete|src|setHookPosition|mouseenter|getStemLayout|transition|Stem|boolean|cache|fadeIn|fadeTransition|afterUpdate|000|startingZIndex|active|skinned||self|arguments|any|setTimeout|pointer|closest|cumulativeScrollOffset|scrollTop|scrollLeft|parentNode|cumulativeOffset|required|available|pow|create|hideAll|mouseBuffer|getCenterBorderDimensions|cos|substring|skins|prepare|skinElement|order|UpdateQueue|mouseleave|rotate|borderRadius|test|topcenter|rightcenter|bottomcenter|leftcenter|closeButtonCanvas|_getTooltip|_remove|selector|mousemove|_updateTooltip|10000px|setFadeDuration|setActive|getTimer|contentFunction|raise|hideAfter|onShow|firstChild|ms|callback|Object|title|tipped_restore_title|events|toggles|fnCallContent|||apply|try|catch||select|delay|defer|isAttached|Opera|opera|version|Chrome|console|touch|setDefaultSkin|setStartingZIndex|isVisibleByElement|undefined|getSide|getDimensions|getBubbleLayout|100|min|floor|prepend|hoverCloseButton|defaultCloseButton|find|auto|getMeasureElementDimensions|drawCloseButtonState|default|hover|_drawBackgroundPath|before|black|getByTooltipElement|_resizeTimer|clearTimeout|reset|CloseButtons|isPointerEvent|insertSpinner|play|onload|t_hidden|setIdle|hideDelayed|inArray|_restoreInlineContent|_hide|idle|in|createOptions|getAttribute|getElementById|_preBuild|Array|concat|_each|member|pageX|RegExp|parseFloat|AppleWebKit|Gecko|check|Za|checked|notified|requires|warn|alert|createEvent|ready|startDelegating|removeDetached|drawRoundedRectangle|fillRect|isArray|Gradient|addColorStops|toOrientation|side|toDimension|isCorner|atan|red|green|blue|360|createHookCache|drawBubble|drawCloseButton|t_ContentContainer|first|25000px|t_Close|closeButtonShift|closeButtonMouseover|closeButtonMouseout|CloseButton|_drawBorderPath|backgroundRadius|setGlobalAlpha|sqrt|drawBackground|getBlurOpacity|documentElement|onWindowResize|is|getHighestTooltip|resetZ|base|getInversedPosition|getTooltipPositionFromTarget|adjustOffsetBasedOnHooks|closeButtonSkin|flip|viewport|hideOnClickOutside|typeof|outerWidth|outerHeight|innerWidth|innerHeight|set|distance|targetOverlap|tooltipOverlap|orientationOffset|getAbsoluteOffset|t_Content|inline|isSpinner|tipped_restore_inline_display|display|img|html|t_hideOnClickOutside|createPostBuildObservers|createPreBuildObservers|_buildSkin|showDelayed|showDelay|touchmove|ajaxUpdate|t_visible|removeClass|abort|resetHookPosition|onHide|clearTimers|eventName|handler|clearEvents|unbind|dataType|_stemPosition|object|setAttribute|slice|wrap|throw|without|nodeType|pageY|do|while|exec|attachEvent|MSIE|WebKit|KHTML|rv|MobileSafari|Apple|Mobile|Safari|navigator|userAgent|Version|fn|jquery|z_|z0|log|_t_uid_|TouchEvent|WebKitTransitionEvent|TransitionEvent|OTransitionEvent|ExplorerCanvas|excanvas|js|initElement|drawPixelArray|createLinearGradient|addColorStop|spacing|replace|0123456789abcdef|hex2rgb|rgba|join|getSaturatedBW|255|hue|saturation|brightness|fff|init_|t_Bubble|iframe|t_iframeShim|frameBorder|javascript|15000px|t_CloseButtonShift|t_CloseState|translate|lineWidth|stemOffset|270|sin|setOpacity|getCenterBorderDimensions2|acos|t_Shadow|t_ShadowBubble|t_CloseButtonShadow|999999|touchstart|close|preventDefault|stopPropagation|resize|200|getBySelector|outside|move|t_UpdateQueue|t_clearfix|t_Content_|filter|8e3||750|Image|t_Skin|t_Tooltip_|fixed|hideOthers|hideDelay|style|MozTransitionDuration|webkitTransitionDuration|OTransitionDuration|transitionDuration|url|success|status|responseText|load|removeData'.split('|'), 0, {}));
var GEO_LOCATION={watchID:null,callback:null};GEO_LOCATION.mySpot=function(position){var lat=(position.coords)?new String(position.coords.latitude):position.x;var lon=(position.coords)?new String(position.coords.longitude):position.y;return GEO_LOCATION.callback(lat,lon);}
GEO_LOCATION.getLocation=function(func,timeout){GEO_LOCATION.callback=func;if(navigator.geolocation){this.requestCurrentPosition(this.mySpot,this.errorCallback,this.timeoutCallback,timeout,{maximumAge:10000,timeout:timeout,enableHighAccuracy:true});}else{setTimeout(this.errorCallback,3000);}}
GEO_LOCATION.requestCurrentPosition=function(successCB,errorCB,timeoutCB,timeoutThreshold,options){var successHandler=successCB;var errorHandler=errorCB;window.geolocationTimeoutHandler=function(){timeoutCB();}
if(typeof(geolocationRequestTimeoutHandler)!='undefined'){clearTimeout(window['geolocationRequestTimeoutHandler']);}
var timeout=timeoutThreshold||30000;window['geolocationRequestTimeoutHandler']=setTimeout('geolocationTimeoutHandler()',timeout);GEO_LOCATION.watchID=navigator.geolocation.watchPosition(function(position){successHandler(position);clearTimeout(window['geolocationRequestTimeoutHandler']);},function(error){if(!GEO_LOCATION.room){clearTimeout(window['geolocationRequestTimeoutHandler']);alert("Something went wrong. Trying to locate your position using your IP address instead. Please wait...");setTimeout(errorHandler,3000);}},options);};GEO_LOCATION.errorCallback=function(){var url='http://freegeoip.net/json/?callback=?';$.getJSON(url,function(data){if(data){var position={};position.x=data.latitude;position.y=data.longitude;GEO_LOCATION.mySpot(position);}
if(GEO_LOCATION.watchID){navigator.geolocation.clearWatch(GEO_LOCATION.watchID);}});}
if (typeof(GEO_LOCATION.timeoutCallback)!='undefined') {GEO_LOCATION.timeoutCallback=function(){vartext="Hi there! we are trying to locate you but you have not answered the security question yet.\n\nPlease choose 'Share My Location' to enable us to find you.";alert(text);}}
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
    (i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
    m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

// was... (using cookies)
//ga('create', 'UA-3163228-10', 'auto');
//ga('send', 'pageview');

// now... (using localStorage)
var GA_LOCAL_STORAGE_KEY = 'ga_clientId';

if (window.localStorage) {
    ga( 'create', 'UA-3163228-10', {
        'storage': 'none',
        'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY)
    });
    ga(function (tracker) {
        localStorage.setItem(GA_LOCAL_STORAGE_KEY, tracker.get('clientId'));
    });
}
else {
    ga('create', 'UA-3163228-10', 'auto');
}

ga('send', 'pageview');
/***************************
*   Account JavaScript     *
****************************/

/** Bind Global Helpers */
var bindGlobalHelpers = function () {

    // String Format
    if (!String.prototype.format) {
        String.prototype.format = function () {
            var str = this.toString();
            if (!arguments.length)
                return str;
            var args = typeof arguments[0],
                args = (("string" == args || "number" == args) ? arguments : arguments[0]);
            for (arg in args)
                str = str.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
            return str;
        }
    }
};
/** /Bind Global Helpers */

/** Init */
bindGlobalHelpers();

/** Validate Email */
function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}
//-->

/** Validate Letter */
function validateLetter(text) {
    var re = /^[a-zA-Z]+$/;
    return re.test(text);
}
//-->

/** Validate Number */
function validateNumber(number) {
    var re = /^[0-9]+$/;
    return re.test(number);
}
//-->

/** Validate Alpha-Numeric */
function validateAlphaNumeric(text) {
    var re = /^[a-zA-Z0-9 ]+$/;
    return re.test(text);
}
//-->

/** Validate Passport Card */
function validatePassportCard(preCard, cardNum1, cardNum2) {

    var errorText = "";
    if (($(preCard).val() == "") || ($(cardNum1).val() == "") || ($(cardNum2).val() == "") ||
        ($(preCard).val() == $(preCard).attr("placeholder")) || ($(cardNum1).val() == $(cardNum1).attr("placeholder")) || ($(cardNum2).val() == $(cardNum2).attr("placeholder"))) {
        errorText = "Please enter card number first.";
    }
    else {
        if (!validateLetter($(preCard).val())) {
            errorText = "Card prefix must be letters.";
        }
        else if ($(preCard).val().length != 3) {
            errorText = "Card prefix must contain 3 letters.";
        }
        else {
            if (!validateNumber($(cardNum1).val()) || !validateNumber($(cardNum2).val())) {
                errorText = "Card digits must be numbers.";
            }
            else if ($(cardNum1).val().length != 2) {
                errorText = "Card first set of digits must contain 2 numbers.";
            }
            else if ($(cardNum2).val().length != 4) {
                errorText = "Card second set of digits must contain 4 numbers.";
            }
        }
    }
    return errorText;
}
/** /Validate Passport Card */

/** Redirect To Login */
function redirectToLogin() {
    window.location.replace(window.location.protocol + '//' + window.location.host + '/Account/Login');
}
//-->

/** Login Spinner */
function createLoadingSpinner(buttonID) {
    $(buttonID).addClass("loading");
    $(buttonID).append(" <i class='fa fa-circle-o-notch fa-spin fa-fw'></i>");
}

function destroyLoadingSpinner(buttonID) {
    $(buttonID).removeClass("loading");
    $(buttonID).children(".fa-circle-o-notch").remove();
}
//-->

jQuery.fn.reverse = function () {
    return this.pushStack(this.get().reverse(), arguments);
};

function GetEntityByProperty(collection, propertyName, propertyValue) {
    var len = collection.getLength(), entity;

    for (var i = 0; i < len; i++) {
        entity = collection.get(i);

        if (entity[propertyName] && entity[propertyName] == propertyValue) {
            return entity;
        } else if (entity.getLength) {
            //Entity collections have this property and we want to look inside these collections
            var layer = GetEntityByProperty(entity, propertyName, propertyValue);

            if (layer != null) {
                return layer;
            }
        }
    }

    return null;
}

/** On Hot Deal Click */
function onHotdealClick(url) {
    window.open(url, "_blank");
}
//-->

/** get query string value */
function getQuerystring(key) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === key) {
            return pair[1];
        }
    }
    return null;
}
//-->
/**************************
*   Main - JavaScript     *
***************************/

/** Global / Member Var */
var loadingInProgress = false;
var keepAlive = null;
var windowWidth = $(window).width();

// This closes a navigation dropdown menu when resizing the screen
$(window).resize(() => {
    $('.dropdown-toggle.show').dropdown('toggle');
});
/** Doc Ready! */
$(function () {

    if (queryModel !== null) {
        FilterBar.Init();
        LocationView.init();
        SearchView.init();
    }
    else {
        $("#search-column").hide(); //disable Search
        $("#location-column").hide(); //disable Location
    }

    //Image slider elements
    var owlLayerslider = $("#layerslider");
    var sliderClickProxy = $('<a id="sliderClickProxy" tabindex="204" target="_blank">&nbsp;</a>');
    var initSlider = function() {
        owlLayerslider.append(sliderClickProxy);
    };
    var bindSliderDots = function() {
        owlLayerslider.find('.owl-dot').each(function (i) {
            var label = ('carousel item ' + (i + 1) + ' of ' + owlLayerslider.find('.owl-dot').length);
            var title = label += ' button'
            if ($(this).hasClass('active')) {
                label += ' selected';
            }
            $(this).attr({
                'aria-label': label,
                'title': title,
                'role': 'button'
            });
        });
    }
    var setActiveSlideAccessibility = function () {
        setTimeout(function () {
            var activeLabel = owlLayerslider.find('.owl-item.active .item img').attr('alt');
            var activeHref = owlLayerslider.find('.owl-item.active .item a').attr('href');
            var activeOnClick = owlLayerslider.find('.owl-item.active .item a').attr('onclick');
            var activeTarget = owlLayerslider.find('.owl-item.active .item a').attr('target');
            sliderClickProxy.attr('aria-label', activeLabel);
            sliderClickProxy.attr('href', activeHref);
            sliderClickProxy.attr('onclick', activeOnClick);
            sliderClickProxy.attr('target', activeTarget);
            bindSliderDots();
        }, 100);
    }
    owlLayerslider.owlCarousel({
        items: 1,
        dots: true,
        lazyLoad: true,
        autoplay: true,
        autoplayTimeout: 8000,
        autoplayHoverPause: true,
        loop: true,
        rewind: false,
        nav: true,
        navText: ["<i class='fa fa-lg fa-chevron-left' tabindex='203' aria-label='previous item' title='previous item button' role='button'></i>", "<i class='fa fa-lg fa-chevron-right' tabindex='205' aria-label='next item' title='next item button' role='button'></i>"],
        onInitialized: function () {
            initSlider();
            setActiveSlideAccessibility();
        },
        onChanged: function () {
            setActiveSlideAccessibility();
        }
    });

    //$('.carousel-item').on('focus', function () {
    //    $('#carouselExampleControls').css('outline', '3px solid #48bde4 !important');
    //})

    //$('.carousel-item').on('blur', function () {
    //    $('#carouselExampleControls').css('outline', 'none');
    //})
                    
    $('#carouselExampleControls').carousel({ pause: false, interval: 6000 })

    $('#bs-carousel-pause-btn').on('click', function () {
        $('#carouselExampleControls').carousel('pause');
        $(this).hide(0);
        $('#bs-carousel-play-btn').show(0, function () {
            $(this).focus();
        })
        $('#bs-playpause-state-announcement').html('paused, activate again to play')
    })

    $('#bs-carousel-play-btn').on('click', function () {
        $('#carouselExampleControls').carousel('cycle');
        $(this).hide(0);
        $('#bs-carousel-pause-btn').show(0, function () {
            $(this).focus();
        })
        $('#bs-playpause-state-announcement').html('playing, activate again to pause')
    })

    $('.carousel-item').on('focus', function () {
        $('#carouselExampleControls').carousel('pause');
        $('#bs-carousel-pause-btn').hide();
        $('#bs-carousel-play-btn').show();
    })

    $('.carousel-item').on('blur', function () {
        $('#carouselExampleControls').carousel('cycle');
        $('#bs-carousel-pause-btn').show();
        $('#bs-carousel-play-btn').hide();
    })

    //$('#carouselExampleControls').on('slide.bs.carousel', function (e) {
    //    $('#playpause-state-announcement').html('playing, activate again to pause')

    //})

    //WCAG: due to the append adding the sliderClickProxy aobve, the owl-dots HTML must be re-ordered so that the tooltip/title of each dot is visible on mouseover
    var owlDotsHtml = $('.owl-dots').html();
    $('.owl-dots').remove();
    owlLayerslider.append("<div class='owl-dots'>" + owlDotsHtml + "</div><div class='owl-playpause'><div class='owl-play play' style='display:none;' tabindex='202' aria-label='play carousel items' title='play button' role='button'><div class='fa fa-play'></div></div><div class='owl-play pause active' style='display:none;' tabindex='202' aria-label='pause carousel items' title='pause button' role='button'><div class='fa fa-pause'></div></div>");

    $(".owl-play.play", owlLayerslider).on('click', function () {
        owlLayerslider.trigger('play.owl.autoplay');
        $(".owl-play.pause", owlLayerslider).toggleClass('active');
        $(".owl-play.play", owlLayerslider).toggleClass('active');
        $('#playpause-state-announcement').html('playing, activate again to pause')
        $(".owl-play.pause").focus();
    });
    $(".owl-play.pause", owlLayerslider).on('click', function () {
        owlLayerslider.trigger('stop.owl.autoplay');
        $(".owl-play.pause", owlLayerslider).toggleClass('active');
        $(".owl-play.play", owlLayerslider).toggleClass('active');
        $('#playpause-state-announcement').html('paused, activate again to play')
        $(".owl-play.play").focus();
    });

    

    //Add tabindex for keyboard navigation.
    keyboardHelper.init();

    //WCAG: aria-hide all cloned list items to ensure correct list count announcement by screen readers
    $('.owl-item.cloned').attr('aria-hidden', true);

    //Add event trigger for change aria on filter bar expand collapse buttons and panels.
    $('#headingOfferType a').on('click', function () {
        if ($('#collapseFilter').hasClass('in')) // Expanded
        {
            $('#collapseFilter').attr('aria-hidden', true);
            $('#collapseFilterText').attr('aria-hidden', false);
            $(this).attr('aria-expanded', false);
            $('#headingOfferType').attr('aria-label', 'click to expand offer type');
        }
        else {
            $('#collapseFilter').attr('aria-hidden', false);
            $('#collapseFilterText').attr('aria-hidden', true);
            $(this).attr('aria-expanded', true);
            $('#headingOfferType').attr('aria-label', 'click to collapse offer type');
        }
    });
    $('#L1FilterCategoryHeaderBtn a').on('click', function () {
        if ($('#collapseCategory').hasClass('in')) // Expanded
        {
            $('#collapseCategory').attr('aria-hidden', true);
            $('#collapseCategoryText').attr('aria-hidden', false);
            $(this).attr('aria-expanded', false);
            $('#L1FilterCategoryHeaderBtn').attr('aria-label', 'click to expand category filter');
        }
        else {
            $('#collapseCategory').attr('aria-hidden', false);
            $('#collapseCategoryText').attr('aria-hidden', true);
            $(this).attr('aria-expanded', true);
            $('#L1FilterCategoryHeaderBtn').attr('aria-label', 'click to collapse category filter');
        }
    });
    $('#headingMileBound a').on('click', function () {
        if ($('#collapseMileBound').hasClass('in')) // Expanded
        {
            $('#collapseMileBound').attr('aria-hidden', true);
            $('#collapseMileBoundText').attr('aria-hidden', false);
            $(this).attr('aria-expanded', false);
            $('#headingMileBound').attr('aria-label', 'click to expand search radius');
        }
        else {
            $('#collapseMileBound').attr('aria-hidden', false);
            $('#collapseMileBoundText').attr('aria-hidden', true);
            $(this).attr('aria-expanded', true);
            $('#headingMileBound').attr('aria-label', 'click to expand search radius');
        }
    });
    $('#headingMealtime a').on('click', function () {
        if ($('#collapseMeal').hasClass('in')) // Expanded
        {
            $('#collapseMeal').attr('aria-hidden', true);
            $('#collapseMealText').attr('aria-hidden', false);
            $(this).attr('aria-expanded', false);
            $('#headingMealtime').attr('aria-label', 'click to expand mealtime type');
        }
        else {
            $('#collapseMeal').attr('aria-hidden', false);
            $('#collapseMealText').attr('aria-hidden', true);
            $(this).attr('aria-expanded', true);
            $('#headingMealtime').attr('aria-label', 'click to collapse mealtime type');
        }
    });
    $('#headingMealPrice a').on('click', function () {
        if ($('#collapsePrice').hasClass('in')) // Expanded
        {
            $('#collapsePrice').attr('aria-hidden', true);
            $('#collapsePriceText').attr('aria-hidden', false);
            $(this).attr('aria-expanded', false);
            $('#headingMealPrice').attr('aria-label', 'click to expand price range');
        }
        else {
            $('#collapsePrice').attr('aria-hidden', false);
            $('#collapsePriceText').attr('aria-hidden', true);
            $(this).attr('aria-expanded', true);
            $('#headingMealPrice').attr('aria-label', 'click to collapse price range');
        }
    });
    $('#headingSortBy a').on('click', function () {
        if ($('#collapseSort').hasClass('in')) // Expanded
        {
            $('#collapseSort').attr('aria-hidden', true);
            $('#collapseSortText').attr('aria-hidden', false);
            $(this).attr('aria-expanded', false);
            $('#headingSortBy').attr('aria-label', 'click to expand sort criteria');
        }
        else {
            $('#collapseSort').attr('aria-hidden', false);
            $('#collapseSortText').attr('aria-hidden', true);
            $(this).attr('aria-expanded', true);
            $('#headingSortBy').attr('aria-label', 'click to collapse sort criteria');
        }
    });


    keepAlive = setInterval(KeepAlive, 15 * 60 * 1000);
  //  var
    $win = $(window);
  //$filter = $('.navbar-header'),
  //$search = $('.search-location-bar')
  //$filterSpacer = $('<div />', {
  //    "class": "filter-drop-spacer",
  //    "height": $filter.outerHeight()
  //});
    if ($win.scrollTop() > 0) {
        $(".navbar-wrapper").toggleClass("darken", true);
        $(".navbar-shadow").toggleClass("darken", true);
    }
    else {
        $(".navbar-wrapper").toggleClass("darken", false);
        $(".navbar-shadow").toggleClass("darken", false);
    }


    //search-location-bar-fixed-top
    $win.scroll(function () {

        if ($win.scrollTop() > 0) {
            $(".navbar-wrapper").toggleClass("darken", true);
            $(".navbar-shadow").toggleClass("darken", true);
        }
        else {
            $(".navbar-wrapper").toggleClass("darken", false);
            $(".navbar-shadow").toggleClass("darken", false);
        }

        if ($('#PreLogin').length) {
            if ($('#PreLogin').offset().top + $('#PreLogin').height()
                >= $('footer').offset().top - 10) {
                //
                $('#PreLogin').removeClass("navbar-fixed-bottom");
                //$('footer').css("margin-top", "-1px");
            }
            if ($(document).scrollTop() + window.innerHeight < $('footer').offset().top) {
                //if !has class closed
                $('#PreLogin').addClass("navbar-fixed-bottom");
                //$('footer').css("margin-top", $('#PreLogin').height());
            }
        }


    //    if (!$filter.hasClass('navbar-fixed-top') && $win.scrollTop() > $filter.offset().top) {
    //        $filter.before($filterSpacer);
    //        $filter.addClass("navbar-fixed-top");
    //        //$search.addClass("search-location-bar-fixed-top");
    //    } else if ($filter.hasClass('navbar-fixed-top') && $win.scrollTop() < $filterSpacer.offset().top) {
    //        //$search.removeClass("search-location-bar-fixed-top");
    //        $filter.removeClass("navbar-fixed-top");
    //        $filterSpacer.remove();
    //    }
    });

    Tipped.create($("a[target='_blank']"), 'Opens a new window', { hideOthers: true, showOn: 'focus mouseover', hideOn: 'blur mouseout' });
    Tipped.create($(".showTipped[title]"), { hideOthers: true, showOn: 'focus mouseover', hideOn: 'blur mouseout' });

    bindSkipNavLinks();
    bindHotDealDotDotDot();
    bindOfferDotDotDot();

    // Track basic JavaScript errors
    window.addEventListener('error', function (e) {

        ga('send', 'event', '_trackEvent', 'JavaScript Error', e.message, e.filename + ':  ' + e.lineno);
    });

    // Track AJAX errors (jQuery API)
    $(document).ajaxError(function (e, request, settings) {
        ga('send', 'event', '_trackEvent', 'Ajax Error', settings.url, e.result);
    });


    // Collapse filters on small screens
    $('#fitler-menu-expand').on('click', function () {

        $('.filter-collapse').toggle().toggleClass('expanded');

        var expanded = $('.filter-collapse').hasClass('expanded');
        var iconClass = expanded ? 'fal fa-times-circle' : 'far fa-filter';
        var icon = $(this).find('i');

        if (expanded) {
            icon.removeClass('far fa-filter').addClass('fal fa-times-circle');
        } else {
            icon.removeClass('fal fa-times-circle').addClass('far fa-filter');
        }
    })

    $(window).on('scroll', function () {
        if (window.scrollY == 0) {
            $('#responsive-header').removeClass('bg-dark');

        } else {
            $('#responsive-header').addClass('bg-dark');
        }
    })

    $('#navbarSupportedContent .dropdown-toggle').on('keyup', function (e) {
        if (e.code == "Space") {
           $(this).dropdown('toggle');
        }
    })



    // NOTES:
    // 1. WCAG failure when hidden.bs.dropdown(menu collapse) event occurs..focus is moved to next element but scroll position is retained as if menu was still expanded
    // 2. WCAG failure if onKeyUp event scrolls view to (0,0) each time since that moves element w/focus off-screen at higher zoom levels


    //NOTES: Adding a filter to jQuery to see if an element is offscreen
    $.expr.filters.offscreen = function (el) {
        var rect = el.getBoundingClientRect();
        return (
            (rect.x + rect.width) < 0
            || (rect.y + rect.height) < 0
            || (rect.x > window.innerWidth || rect.y > window.innerHeight)
        );
    };

    
    $('#navbarSupportedContent .nav-link').each(function (e) {

        $(this).on('hidden.bs.dropdown', function (e) {

            if ($(this).parent().next().find('.nav-link')) {
                if ($(this).is(':offscreen')) {
                   $(this)[0].scrollIntoView();
                }
            }
            else {
                if ($(this).is(':offscreen')) {
                    $('.carousel-item.active')[0][0].scrollIntoView();
                }
            }
        })
    })    
});

function clearLocalStorage() {
    window.localStorage.removeItem('sso');
}

/** Load Hot Deal */
function bindHotDealDotDotDot(currItemObj) {

    if (currItemObj == null) {

        $('.hotdeal-vendor-name').dotdotdot({
            wrap: 'word',
            watch: true,
            height: 26
        });

            $('.hotdeal-detail').dotdotdot({
                wrap: 'word',
                watch: true,
                height: 109
            });
        
    }
    else {
        if ($('.hotdeal-vendor-name', $(currItemObj)).length) {
            $('.hotdeal-vendor-name', $(currItemObj)).dotdotdot({
                wrap: 'word',
                watch: true,
                height: 26
            });
        }
        if ($('.hotdeal-detail', $(currItemObj)).length) {
            $('.hotdeal-detail', $(currItemObj)).dotdotdot({
                wrap: 'word',
                watch: true,
                height: 109
            });
        }
    }


}

function bindGridDotDotDot(currItemObj) {

    if ($('.vendor-offer-preview', $(currItemObj)).length) {
        $('.vendor-offer-preview', $(currItemObj)).dotdotdot({
            wrap: 'word',
            watch: true,
            height: 44
        });
    }
    //if ($('.featured-offer-caption', $(currItemObj)).length) {
    //    $('.featured-offer-caption', $(currItemObj)).dotdotdot({
    //        wrap: 'word',
    //        watch: true,
    //        height: 60
    //    });
    //}
}

/** Load Offer */
function bindOfferDotDotDot(currItemObj) {

    if (currItemObj == null)
    {
        if ($('.featured-offer-title').length) {
            $('.featured-offer-title').dotdotdot({
                wrap: 'word',
                watch: true,
                height: 25
            });
        }
        if ($('.featured-offer-caption').length) {
            $('.featured-offer-caption').dotdotdot({
                wrap: 'word',
                watch: true,
                height: 60
            });
        }
    }
    else {
        if ($('.featured-offer-title', $(currItemObj)).length) {
            $('.featured-offer-title', $(currItemObj)).dotdotdot({
                wrap: 'word',
                watch: true,
                height: 25
            });
        }
        if ($('.featured-offer-caption', $(currItemObj)).length) {
            $('.featured-offer-caption', $(currItemObj)).dotdotdot({
                wrap: 'word',
                watch: true,
                height: 60
            });
        }
    }
}

//function bindOwlCarousel(currItemObj, currSelector, itemPerPage, slideBy, padding)
//{
//    var owl1 = $(currSelector, $(currItemObj));
//    owl1.owlCarousel({
//        items: itemPerPage,
//        dots: false,
//        nav: true,
//        autoHeight: false,
//        slideBy: slideBy,
//        stagePadding: padding,
//        navText: ["<i class='fa fa-lg fa-chevron-left' aria-hidden='true'></i>", "<i class='fa fa-lg fa-chevron-right' aria-hidden='true'></i>"],
//        onTranslate: function (e)
//        {
//            if ($(e.target).find('.owl-next').hasClass('disabled'))
//            {
//                $(e.target).find('.owl-stage').addClass("right");
//            }
//            else {
//                $(e.target).find('.owl-stage').removeClass("right");
//            }
//        },
//      responsive: {
//            1160: {
//                items: itemPerPage
//            },
//            960: {
//                items: (itemPerPage - 1)
//            },
//            768: {
//                items: (itemPerPage - 2)
//            },
//            0: {
//                items: (itemPerPage - 2)
//            }
//        }
//    });    
//    $('.owl-item.cloned').find('img').attr('aria-hidden', true);
//}


// This is in charge of setting active status on L1Category elements
$(document).ready(function () {
    const pathname = window.location.pathname.toLowerCase();

    if (pathname === "/") {
        $('.nav-link#home').addClass('active');
    } else if (pathname === "/all" || pathname === "/all/") {
            $('.nav-link#alloffers').addClass('active');
    } else if (pathname === "/dine") {
        $('.nav-link#dine').addClass('active');
    } else if (pathname === "/shop") {
        $('.nav-link#shop').addClass('active');
    } else if (pathname === "/travel") {
        $('.nav-link#travel').addClass('active');
    } else if (pathname === "/online"
            || pathname === "/portal-01"
            || pathname === "/portal-02"
            || pathname === "/portal-03"
            || pathname === "/portal-04"
            || pathname === "/portal-05"
            || pathname === "/portal-06") {
        $('.nav-link#portal').addClass('active');
    } else if (pathname === "/xtradeals") {
        $('.nav-link#xtradeals').addClass('active');
    } else {
        $('.nav-link#account').addClass('active');
    }


    // This makes sure that the dropdown will open when a mouse is hovered over.
    $('.navbar .nav-item').on('mouseover', function () {

        if ($(this).hasClass('dropdown')) {
            var toggle = $(this).find('.dropdown-toggle');
            var menu = $(this).find('.dropdown-menu');
            var windowX = $(window).width();

            if (windowX > 992) {
                toggle.addClass('show').prop('aria-expanded', true);
                menu.addClass('show').prop('data-bs-popper', true);
            }
        } else {
            $(this).focus();
        }

    });

    // This closes the dropdown menu on mouse exit
    $('.navbar .nav-item').on('mouseout', function () {

        if ($(this).hasClass('dropdown')) {
            var toggle = $(this).find('.dropdown-toggle');
            var menu = $(this).find('.dropdown-menu');
            var windowX = $(window).width();

            if (windowX > 992) {
                toggle.removeClass('show').prop('aria-expanded', false);
                menu.removeClass('show').removeProp('data-bs-popper');
            }
        }
    })

})



function bindOwlCarousel(currItemObj, currSelector, responsive) {
    var owl1 = $(currSelector, $(currItemObj));
    owl1.owlCarousel({
        dots: false,
        nav: true,
        autoHeight: false,
        navText: ["<i class='fa fa-lg fa-chevron-left' aria-hidden='true'></i>", "<i class='fa fa-lg fa-chevron-right' aria-hidden='true'></i>"],
        onTranslate: function (e) {
            //if ($(e.target).find('.owl-prev').hasClass('disabled')) {
            //    $(e.target).find('.owl-prev').attr('tabindex', -1);
            //}
            //else {
            //    $(e.target).find('.owl-prev').attr('tabindex', 501);
            //}
            if ($(e.target).find('.owl-next').hasClass('disabled')) {
                $(e.target).find('.owl-stage').addClass('right');
            //    $(e.target).find('.owl-next').attr('tabindex', -1);
            }
            else {
                $(e.target).find('.owl-stage').removeClass('right');
            //    $(e.target).find('.owl-next').attr('tabindex', 501);
            }
        },
        responsive: responsive
    });
    //onBind: default state...
    $('.owl-item.cloned').find('img').attr('aria-hidden', true);
    //$('.owl-next').attr('tabindex', 501);
    //$('.owl-prev').attr('tabindex', -1);
}

function LinkHomeCatChange(e, t) {
    e.preventDefault();

    const id = $(t).attr('id');

    $.ajax({
        url: "/Main/ChangeRootCategory",
        type: "POST",
        async: true,
        data: { cat_id: -1 },
        dataType: "json"
    }).
        // Success!
        done(function (result) {
            if (result.Authorized != null && result.Authorized == false) {
                redirectToLogin();
            }
            if (result.Authorized) {
                //Redirect

                if (id === 'all-btn') {
                    window.location = '/all';
                } else if (id === 'map-btn') {
                    window.location = '/all/map';
                } else {
                    window.location = $(t).attr('href');
                }
            }
        });
}

//function toggleL1Cat(L1anchor) {
//    $(L1anchor).toggleClass("open");
//}

function selectL1Cat(event, L1anchor) {
    $('a.dropdown-item').removeClass('active'); //un-set active state on all L2 items
    $('.navbar-nav a.nav-link dropdown-menu').removeClass('show') //hide any expanded dropdown-menus
    $('.navbar-nav a.nav-link').removeClass('active'); //un-set active state on all L1 items
    $(L1anchor).addClass('active'); //make the selected L1anchor active

    if ($(L1anchor).attr('href').length)
        $.ajax({
            url: "/Main/ChangeRootCategory",
            type: "POST",
            async: true,
            data: AddAntiForgeryToken({ cat_id: -1 }),
            dataType: "json"
        }).
            // Success!
            done(function (result) {
                if (result.Authorized != null && result.Authorized == false) {
                    redirectToLogin();
                }
                if (result.Authorized) {
                    //Redirect
                    window.location = $(L1anchor).attr('href');
                }
            });
}
function selectXtraDealCat(L1anchor) {
    $('a.dropdown-item').removeClass('active'); //un-set active state on all L2 items
    $('.navbar-nav a.nav-link dropdown-menu').removeClass('show') //hide any expanded dropdown-menus
    $('.navbar-nav a.nav-link').removeClass('active'); //un-set active state on all L1 items
    $(L1anchor).addClass('active'); //make the selected L1anchor active
}

//This function is only needed if we want to make a L1 nav item active prior to page reload
function setSelectedL1Category(categoryName) {
    var navbarLinks = $('.navbar-nav a.nav-link')
    navbarLinks.removeClass('active');
    for (let link of navbarLinks) {
        if ($(link).attr('id') === categoryName) {
            $(link).addClass('active');
        }
    }
}

function selectL2Cat(ev, L1parentID, CategoryID, L2anchor) {
    ev.preventDefault();

    var currentTabSelected = $('.navbar-nav').find('.active').attr('id');
    var isRedirectNeed = !$(L2anchor).hasClass(currentTabSelected);
    var isEcommerce = false;
    var isTravel = L1parentID == 3;
    var rootLink = '';

    if (L1parentID == 1) {
        rootLink = '/dine';
    } else if (L1parentID == 2) {
        rootLink = '/shop';
    } else if (L1parentID == 3) {
        rootLink = '/travel';
    } 

    $('.dropdown-item').removeClass('active'); //un-set active state on any other L2 items
    $(L2anchor).addClass('active'); //make the anchor active

    if (isRedirectNeed) {
    $.ajax({
        url: "/Main/ChangeRootCategory",
        type: "POST",
        async: true,
        data: AddAntiForgeryToken({ cat_id: CategoryID, is_ecommerce: isEcommerce, is_travel: isTravel }),
        dataType: "json"
    }).
        // Success!
        done(function (result) {
            if (result.Authorized != null && result.Authorized == false) {
                redirectToLogin();
            }
            if (result.Authorized) {
                //Redirect
                window.location = rootLink;
            }
        });
    } else {
        queryModel.CurrentCategoryID = CategoryID;
        queryModel.Category = null;

        if (queryModel.HiddenLocation != null) {
            queryModel.HiddenLocation = null;
            queryModel.HiddenLatitude = null;
            queryModel.HiddenLongitude = null;
            LocationView.UpdateApplied(queryModel.Location);
        }

        queryModel.PageIndex = 1;

        queryModel.IsMapNeedData = true;
        queryModel.IsListNeedData = true;
        queryModel.IsFilterApply = true;
        queryModel.IsEcommerce = isEcommerce;
        queryModel.IsFilterUpdate = true;

        $('#location-container').removeClass("disabled");
        if (queryModel.IsListView) {
            ListView.Clear();
            ListView.GetVendors();
        }
        else {
            MapView.Clear();
            MapView.loadBingMapData();
        }

        autoScrollup();
    }
    
}

function toggleLocationFlyout(show) {
    if (show == 1) {
        $('#location-container').attr('aria-expanded', true);
        $('#locationFlyout').attr('aria-hidden', false);
        $('#locationFlyout').addClass("visible");
        $("div.L1callout-box").hide(); //if this is shown then hide it to avoid UX conflicts
    }
    else {
        LocationView.lockFlyout = false;
        $('#locationFlyout').removeClass("visible");
        $('#location-container').attr('aria-expanded', false);
        $('#locationFlyout').attr('aria-hidden', true);
    };
}

function toggleSearchHints(show) {
    if (show == 1) {
        $("div.search-flyout").addClass("visible");
    }
    else {
        $("div.search-flyout").removeClass("visible");
        $(".search-aria-live-region").html(""); //unset the text in the live region
    };
}

function toggleCallout(show) {
    if (show == 1) {
        toggleOptinCallout(0); //hide the other callout
        $("div.dine-shop-travel-callout").addClass("show-callout");
    }
    else {
        $("div.dine-shop-travel-callout").removeClass("show-callout");
    };
}

function toggleOptinCallout(show) {
    if (show == 1) {
        toggleCallout(0); //hide the other callout
        $("div.optin-callout").addClass("show-callout");
    }
    else {
        $("div.optin-callout").removeClass("show-callout");
    };
}

function requestOptin(e)
{

    createLoadingSpinner(e);

    $.ajax({
        url: "/Account/SendOptinEmailConfirm",
        type: "POST",
        async: true,
        dataType: "json"
    })
        .done(function (result) {
            destroyLoadingSpinner(e);

            if (result) {
                toastr.info("Thank you for opting in.")
                $('.optin-badge').hide();
                $('#MyProfile').prop("onmouseenter", null).attr("onmouseenter", null);
                $('#MyProfile').prop("onmouseleave", null).attr("onmouseleave", null);
                $('#MyProfile').prop("onfocus", null).attr("onfocus", null);
                toggleOptinCallout(0);
            }
            else {
                toastr.error("Sorry we could not opt you in at this time.")
            }
        });
}

function filterRefreshCategory(categoryID, L1parentID)
{
    queryModel.CurrentCategoryID = categoryID;
    queryModel.PageIndex = 1;

    queryModel.CurrentCategoryID = categoryID;
    //queryModel.IsEcommerce = isEcommerce;
    queryModel.IsMapNeedData = true;
    queryModel.IsListNeedData = true;
    queryModel.IsFilterApply = true;
    queryModel.IsFilterUpdate = true;
        
    ListView.GetVendors();

    //FilterBar._resetCategory(categoryID);
    autoScrollup();
    
}

function autoScrollup(immediate, isScrollup) {
    if (isScrollup == null) {
        isScrollup = false;
    }

    if (immediate != null && immediate) {
        $('html, body').scrollTop(0);
    } else {
        setTimeout(function () {
            $('html, body').animate({ scrollTop: 0 }, 2000);
        }, 200);
    }
}

function RadionButtonSelectedValueSet(name, SelectedValue) {
    $('input[type=radio][name="' + name + '"]').val([SelectedValue]);
    $('input[type=radio][name="' + name + '"][value="' + SelectedValue + '"]').trigger('update');
}

function CheckboxButtonSelectedValueSet(name, SelectedValue) {
    
    $.each(SelectedValue, function () {
        $('input[type=checkbox][name="' + name + '"][value="' + this + '"]').prop("checked", true);
        $('input[type=checkbox][name="' + name + '"][value="' + this + '"]').parents('.filters-checkbox').attr("aria-checked", true);
    });
    if (!SelectedValue.length) {
        $('input[type=checkbox][name="' + name + '"]').prop("checked", false).trigger('updatecheck');
        $('input[type=checkbox][name="' + name + '"]').parents('.filters-checkbox').attr("aria-checked", false);
    }
    $('#filterPanel input[type=checkbox][name="' + name + '"]:first').trigger('updatecheck');
}
Array.prototype.unique = function () {
    return this.filter(function (value, index, self) {
        return self.indexOf(value) === index;
    });
};

/** Map Near By Location event */
function recommendVendor(event, actionId, uniqueOfferNameUrl) {
    event.stopPropagation();
    var objRecommend;
    objRecommend = $('#action-' + actionId);

    $.ajax({
        url: "/Main/UpdateRecommendation",
        type: "POST",
        data: AddAntiForgeryToken({ name: uniqueOfferNameUrl, sIsUpdate: $(objRecommend).find('i').hasClass('fa-heart-o') }),
        async: true,
        traditional: true})
        //
        // Success!
        .done(function (result) {
            if (result.Authorized != null && result.Authorized == false) {
                redirectToLogin();
            }
            else {

                if ($(objRecommend).length > 0) {
                    var strTitle = '';

                    if ($(objRecommend).find('i').hasClass('fa-heart')) {
                        
                        $(objRecommend).find('i').removeClass('fa-heart');
                        $(objRecommend).find('i').addClass('fa-heart-o');
                        $(objRecommend).prop('title', 'Add to My Favorites');
                        $(objRecommend).prop('alt', 'Add to My Favorites');
                    }
                    else if ($(objRecommend).find('i').hasClass('fa-heart-o')) {
     
                        $(objRecommend).find('i').removeClass('fa-heart-o');
                        $(objRecommend).find('i').addClass('fa-heart');
                        $(objRecommend).prop('title', 'Remove from My Favorites');
                        $(objRecommend).prop('alt', 'Remove from My Favorites');
                    }
                }
            }
        })
        //
        // Error!
            .fail(function (result) {
                // TODO: handle!
            });
}
//-->

function redirectQuery(x) {
        ListView.xhr = $.ajax({
            url: "/Main/Redirect",
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            async: true,
            dataType: "json",
            traditional: true})
            // Success!
            .done(function (result) {

                if (result.Authorized != null && result.Authorized == false) {
                    redirectToLogin();
                }
                else {
                    if (x) {
                        window.location.href = window.location.protocol + '//' + window.location.host + '/All';
                    }
                    else {
                        window.location.href = window.location.protocol + '//' + window.location.host;
                    }
                }
            })
            // Error!
            .fail(function (result) {
                redirectToLogin();
            });
}

function closeMessage() {
    $(".sticky-footer").hide();

    $.ajax({
        url: "/Main/CloseMessage",
        type: "POST",
        async: true,
        dataType: "json"
    });
}

function closeCustomerBranding() {
    $.ajax({
        url: "/Main/CloseCustomerBranding",
        type: "POST",
        async: true,
        dataType: "json"
    });
}

function updateTermsOfUseAgreement() {
    $(".sticky-footer").hide();

    $.ajax({
        url: "/Main/UpdateTermsOfUseAgreement",
        type: "POST",
        async: true,
        dataType: "json"
    });
}

function TotalHeight(currItemObj)
{

    var totalHeight = 0;
    $(currItemObj).children().each(function () {
        totalHeight = totalHeight + $(this).outerHeight(true);
    });

    return totalHeight;
}
function LoadCategory(categoryID, isTravelDestination, isEcommerce, latlon, rootLink, locationText)
{
    $.ajax({
    url: "/Main/ChangeRootCategory",
    type: "POST",
    data: AddAntiForgeryToken({ cat_id: categoryID, is_travel: isTravelDestination, is_ecommerce: isEcommerce, latlon: latlon, location_name: locationText, root_name: rootLink }),
    async: true,
    dataType: "json",
    traditional: true
    }).done(function (result) {

        if (result.Authorized != null && result.Authorized == false) {
            redirectToLogin();
        }
        else {
            window.location = rootLink;
        }
    });
}
function privateVendorClick(objBtn) {
    if (!$(objBtn).hasClass('guest-tip')) {
        $(objBtn).addClass('guest-tip');
        Tipped.create($(objBtn), 'Please sign in to access this offer. \n<a href="/Account/Logout" style="font-weight:700; color:#fff; text-decoration:underline;">Sign In</a>', { hideOthers: true, showOn: 'focus mouseover', hideOn: 'blur mouseout' });
        Tipped.show($(objBtn));
    }
    return false;
}

function KeepAlive() {
    $.ajax({
            url: "/Main/KeepAlive",
            type: "POST",
            async: true,
            dataType: "json"
        })
        .done(function(result) {

            if (result.Authorized != null && result.Authorized == false) {
                redirectToLogin();
            }

        });
}

function onBreadCrumbClick(CategoryID) {

    // update the category flyout selected state
    $("a.L2selected").removeClass("L2selected");
    $('a[data-category="' + CategoryID + '"]').addClass('L2selected');

    queryModel.CurrentCategoryID = CategoryID;
    queryModel.Category = null;

    if (queryModel.HiddenLocation != null) {
        queryModel.HiddenLocation = null;
        queryModel.HiddenLatitude = null;
        queryModel.HiddenLongitude = null;
        LocationView.UpdateApplied(queryModel.Location);
    }

    queryModel.PageIndex = 1;

    queryModel.IsMapNeedData = true;
    queryModel.IsListNeedData = true;
    queryModel.IsFilterApply = true;
    queryModel.IsEcommerce = false;
    queryModel.IsFilterUpdate = true;

    $('#location-container').removeClass("disabled");
    if (queryModel.IsListView) {
        ListView.Clear();
        ListView.GetVendors();
    }
    else {
        MapView.Clear();
        MapView.loadBingMapData();
    }

    autoScrollup();

    return false;
}

/* Bind Skip Nav Links */
var bindSkipNavLinks = function() {

    $(".skip-nav")
        .click(function(event) {
            handleSkipNavToMain(this);
        });
};

/** Handle Skip Nav To Main */
var handleSkipNavToMain = function ($el) {

    var skipTo = "#" + $el.href.split('#')[1];
    $(skipTo)
        .attr('tabindex', -1)  
        .focus();
}

/* handle keybaord onFocus of keystrokes surrounding the search radius flyout menu */
function hideSearchRadiusFlyoutMenu() {
    $('#search-radius-flyout-menu').removeClass('open');
}

AddAntiForgeryToken = function (data) {
    data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
    return data;
};


function checkWidth() {
    if (true === $('.user-dashboard .flat-list #fw2').hasClass('fixed-width2') && $(window).width() <= 768) {
        $('.user-dashboard .flat-list #fw2').removeClass('fixed-width2');
        $('div.user-dashboard').css('font-size', '85%');
    }
    if (false === $('.user-dashboard .flat-list #fw2').hasClass('fixed-width2') && $(window).width() > 768) {
        $('.user-dashboard .flat-list #fw2').addClass('fixed-width2');
        $('div.user-dashboard').css('font-size', '100%');
    }

}
function isEmpty(str) {
    return (!str || 0 === str.length);
}

$(document).ready(function () {
    $('#bs-5-card-input').on('keyup', function () {
        let val = $(this).val();
        
        const length = val.length;
        
    })
})

var keyboardHelper = {
    previousNavItem: null,
    isKeyboardNavigating: false,
    focusedElement: null,
    KeyCode: {
        TAB: 9,
        ENTER: 13,
        SPACE: 32,
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        ESCAPE: 27
    },
    init: function () {
        //Set default focus to not use IE 11 address bar.
        $(document).on('keydown', function (e) {
            if (e.which == keyboardHelper.KeyCode.TAB) {

                if (keyboardHelper.focusedElement == null) {
                    var tabindex = -1;
                    if ($(document.activeElement).attr('tabindex') != undefined && $(document.activeElement).attr('tabindex') != null) {
                        tabindex = parseInt($(document.activeElement).attr('tabindex'));
                    }
                    if (tabindex <= 0) {
                        e.preventDefault();
                        $('.skip-nav').focus();
                        keyboardHelper.focusedElement = $('.skip-nav');
                    }
                    else {
                        keyboardHelper.focusedElement = $(document.activeElement);
                    }

                }
                else {
                    keyboardHelper.focusedElement = $(document.activeElement);
                }
            }
        });
        initGlobalKeyboardHelper();
        initTabindexForFeaturedSlider();
    },
    initElementData: function () {
        $('.infobox-close-img').attr('alt', 'close map info');
    },
    updateAnchorItemsIndex: function (anchors, tabindex) {
        if (anchors != undefined && anchors != null) {
            for (var i = 0; i < anchors.length; i++) {
                $(anchors[i]).attr('tabindex', tabindex);
            }
        }
    }
};

function initGlobalKeyboardHelper() {
    $(document).on('keydown', onGlobalKeydown);
}

function initTabindexForFeaturedSlider() {
    var dots = $('.owl-dot');
    for (var i = 0; i < dots.length; ++i) {
        $(dots[i]).attr('tabindex', 201);
    }
}

function onGlobalKeydown(e) {
    var currentActiveItem = $(document.activeElement);

    if (e.which == keyboardHelper.KeyCode.ESCAPE) {
        if (currentActiveItem.hasClass('dropdown-minmax') && !currentActiveItem.hasClass('dropdown-minmax-collapsed')) {
            e.preventDefault(); //dropdown-minmax-collapsed
            currentActiveItem.click();
        }
        else if (currentActiveItem.hasClass('location-container') || currentActiveItem.hasClass('location-item') || currentActiveItem.hasClass('location-recent') || currentActiveItem.hasClass('location-detect') )
        {
            var locationFlyout = $('.location-flyout');
            locationFlyout.removeClass('visible');
            $('.location-container').focus();
        }
    }
    else if (e.which == keyboardHelper.KeyCode.TAB) {
        if (currentActiveItem.hasClass('list-item-container')) {
            keyboardHelper.isKeyboardNavigating = true;
        }
    }
    else if (e.which == keyboardHelper.KeyCode.ENTER || e.which == keyboardHelper.KeyCode.SPACE) {
        //Specific items binding that able to generate itself by demand.
        if (currentActiveItem.hasClass('skip-nav')) {
            e.preventDefault();
            currentActiveItem.click();
            location.hash = '#PageContentOuter';

        } else if (currentActiveItem.hasClass('owl-dot') ||
            currentActiveItem.hasClass('owl-play')) {
            e.preventDefault();
            currentActiveItem.click();
            if (currentActiveItem.hasClass('play')) {
                $('.owl-play.pause').focus();
                $('#playpause-state-announcement').html('playing, activate again to pause')
            }
            else {
                $('.owl-play.play').focus();
                $('#playpause-state-announcement').html('paused, activate again to play')
            }
        }
        else if (currentActiveItem.is('#sliderClickProxy')) {
            var currentImage = currentActiveItem.parent().find('.owl-item.active a img');
            if (currentImage.length > 0) {
                currentImage[0].click();
            }
        }
        else if (currentActiveItem.hasClass('filterPanel')) {
            var innerItems = currentActiveItem.find('[tabindex=302]');
            if (innerItems.length > 0) {
                e.preventDefault();
                var index = 0;
                while (!$(innerItems[index]).is(':visible')) {
                    index++;
                }
                if (index < innerItems.length) {
                    $(innerItems[index]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('list-item-container') || currentActiveItem.hasClass('grid-item-container')) {
            e.preventDefault();
            if (currentActiveItem.find('.dropdown-minmax').length > 0) {
                currentActiveItem.find('.dropdown-minmax').click();
            }
            else {
                var innerItems = currentActiveItem.find('[tabindex=501]');
                if (innerItems.length > 0) {
                    innerItems[0].focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('dropdown-minmax')) {
            e.preventDefault();
            currentActiveItem.click();
        }
        else if (currentActiveItem.is('div')) //Start generic items binding
        {
            if (currentActiveItem.hasClass('panel') ||
                currentActiveItem.attr('role') == 'listitem') {
                e.preventDefault();
                var innerBtn = currentActiveItem.find('a');
                if (innerBtn.length > 0) {
                    innerBtn.click();
                }
            }
            else if (currentActiveItem.hasClass('loadButton')) {
                e.preventDefault();
                var listItems = $('.list-item-container');
                currentActiveItem.click();
                if (listItems.length > 0) {
                    setTimeout(function () {
                        var newListItems = $('.list-item-container');
                        var firstNewListItem = $(newListItems[listItems.length]); //eg:.. next list-item-container occuring after the previous last item
                        firstNewListItem.focus();
                    }, 300);
                }
                else {
                    var lastListItem = $(listItems[listItems.length - 1]);
                    lastListItem.find('[tabindex^=501]')[0].focus(); //else, fallback:... focus on next DOM element with tabindex 501
                }
            }
            else if (currentActiveItem.hasClass('hot-deal-details')) {
                e.preventDefault();
                currentActiveItem.click();
            }
        }
        //else if (currentActiveItem.is('span')) {
        //    if (currentActiveItem.hasClass('panel-title')) {
        //        e.preventDefault();
        //        var innerBtn = currentActiveItem.find('a');
        //        if (innerBtn.length > 0) {
        //            innerBtn.click();
        //        }
        //    }
        //}
        else if (currentActiveItem.is('i')) {
            e.preventDefault();
            currentActiveItem.click();
        }
        else if (currentActiveItem.is('li')) {
            if (currentActiveItem.find('input[type=checkbox]').length > 0) {
                e.preventDefault();
                currentActiveItem.find('input[type=checkbox]')[0].click();
            } else if (currentActiveItem.find('input[type=radio]').length > 0) {
                e.preventDefault();
                currentActiveItem.find('input[type=radio]')[0].click();
            }
        }
        else if (currentActiveItem.is('a')) {
            e.preventDefault();
            var href = currentActiveItem.attr('href');
            if (href == '#' || href.indexOf('javascript') > -1) {
                currentActiveItem.click();
            }
            else {
                if (currentActiveItem.attr('target') == '_blank') {
                    window.open(href);
                }
                else {
                    window.location = href;
                }
            }
        }
    }
    else if (e.which == keyboardHelper.KeyCode.UP) {
        if (currentActiveItem.attr('tabindex') == 1 && currentActiveItem.is('[class=search-suggestion]')) {
            var searchInput = $('.search-text');
            var searchSuggestions = $('.search-suggestion');
            var prevSuggestion = searchSuggestions.eq(searchSuggestions.index(currentActiveItem) - 1);
            console.log(prevSuggestion);
            if (searchSuggestions.index(currentActiveItem) == 0) {
                e.preventDefault();
                searchInput.focus();
            }
            else if (prevSuggestion.length > 0) {
                e.preventDefault();
                prevSuggestion.focus();
            }
            else {
                e.preventDefault();
                searchInput.focus();
            }
        }
        else if ((currentActiveItem.is('[class*=owl]') || currentActiveItem.parent().is('[class*=owl]')) && (currentActiveItem.closest('#layerslider').length > 0 || currentActiveItem.is('#sliderClickProxy')))
        {
            var firstNavItem = $('.first-navigation-item');
            if (firstNavItem) {
                e.preventDefault();
                firstNavItem.focus();
            }
        }
        //else if (currentActiveItem.is('[tabindex^=250]')) //User dashboard area
        //{
        //    e.preventDefault();
        //    if ($('#sliderClickProxy').length > 0) {
        //        e.preventDefault();
        //        $('#sliderClickProxy').focus();
        //    }
        //    else {
        //        var firstNavItem = $('.first-navigation-item');
        //        if (firstNavItem) {
        //            e.preventDefault();
        //            firstNavItem.focus();
        //        }
        //    }
        //}
        //else if (currentActiveItem.attr('tabindex') == 301 || currentActiveItem.attr('tabindex') == 302) //Filter bar area
        //{
        //    //TODO: add more interaction later.
        //    var userdashboards = $('[tabindex^=250]');
        //    if (userdashboards.length > 0) {
        //        e.preventDefault();
        //        $(userdashboards[0]).focus();
        //    }
        //    else if ($('#sliderClickProxy').length > 0) {
        //        e.preventDefault();
        //        $('#sliderClickProxy').focus();
        //    }
        //    else {
        //        var firstNavItem = $('.first-navigation-item');
        //        if (firstNavItem) {
        //            e.preventDefault();
        //            firstNavItem.focus();
        //        }
        //    }
        //}
        //else if (currentActiveItem.is('#list_summary_text') ||
        //    currentActiveItem.closest('#list_summary_text').length > 0 ||
        //    currentActiveItem.is('[id*=btn-display-]')) {
        //    var userdashboards = $('[tabindex^=250]');
        //    if (userdashboards.length > 0) {
        //        e.preventDefault();
        //        $(userdashboards[0]).focus();
        //    }
        //    else if ($('#sliderClickProxy').length > 0) {
        //        e.preventDefault();
        //        $('#sliderClickProxy').focus();
        //    }
        //    else {
        //    var firstNavItem = $('.first-navigation-item');
        //    if (firstNavItem) {
        //        e.preventDefault();
        //        firstNavItem.focus();
        //    }
        //    }
        //}
        else if (currentActiveItem.hasClass('list-item-container') || currentActiveItem.hasClass('map-list-item')) {
            keyboardHelper.isKeyboardNavigating = true;
            if (currentActiveItem.prev().length > 0) {
                var prevItem = currentActiveItem.prev();
                if (prevItem.attr('tabindex') != undefined && prevItem.attr('tabindex') != null && prevItem.attr('tabindex') >= 0) {
                    e.preventDefault();
                    prevItem.focus();
                }
                else
                {
                    e.preventDefault();
                    var prevFocusItem = $(prevItem.find('[tabindex^=501]'));
                    if (prevFocusItem.length > 0) {
                        prevFocusItem.focus();
                    }
                    else {
                        var viewBtns = $('[id*=btn-display-]');
                        if (viewBtns.length > 0) {
                            e.preventDefault();
                            $(viewBtns[0]).focus();
                        } else if ($('#sliderClickProxy').length > 0) {
                            e.preventDefault();
                            $('#sliderClickProxy').focus();
                        }
                    }
                }
            }
            //else if ($('#list_summary_text').length > 0) {
            //    e.preventDefault();
            //    $('#list_summary_text').focus();
            //}
            else
            {
                var viewBtns = $('[id*=btn-display-]');
                if (viewBtns.length > 0) {
                    e.preventDefault();
                    $(viewBtns[0]).focus();
                } else if ($('#sliderClickProxy').length > 0) {
                    e.preventDefault();
                    $('#sliderClickProxy').focus();
                }
            }
        }
        //else if (currentActiveItem.closest('.list-item-container').length > 0)
        //{
        //    keyboardHelper.isKeyboardNavigating = true;
        //    var parent = currentActiveItem.closest('.list-item-container');
        //    if (parent.prev().length > 0) {
        //        var prevItem = parent.prev();
        //        if (prevItem.attr('tabindex') != undefined && prevItem.attr('tabindex') != null && prevItem.attr('tabindex') >= 0) {
        //            e.preventDefault();
        //            prevItem.focus();
        //        }
        //        else {
        //            e.preventDefault();
        //            prevItem.find('[tabindex^=501]')[0].focus();
        //        }
        //    }
        //    //else if ($('#list_summary_text').length > 0) {
        //    //    e.preventDefault();
        //    //    $('#list_summary_text').focus();
        //    //}
        //}
        else if (currentActiveItem.hasClass('timeline-panel')) {
            keyboardHelper.isKeyboardNavigating = true;
            if (currentActiveItem.parent().prev().length > 0) {
                var prevItem = currentActiveItem.parent().prev();
                if (prevItem.attr('tabindex') != undefined && prevItem.attr('tabindex') != null && prevItem.attr('tabindex') >= 0) {
                    e.preventDefault();
                    prevItem.focus();
                }
                else {
                    e.preventDefault();
                    var prevFocusItem = $(prevItem.find('[tabindex^=502]'));
                    if (prevFocusItem.length > 0) {
                        prevFocusItem.focus();
                    }
                    else {
                        prevFocusItem = $(prevItem.find('[tabindex^=501]'));
                        if (prevFocusItem.length > 0) {
                            prevFocusItem.focus();
                        }
                        else {
                            var viewBtns = $('[id*=btn-display-]');
                            if (viewBtns.length > 0) {
                                e.preventDefault();
                                $(viewBtns[0]).focus();
                            } else if ($('#sliderClickProxy').length > 0) {
                                e.preventDefault();
                                $('#sliderClickProxy').focus();
                            }
                        }
                    }
                }
            }
            //else if ($('#list_summary_text').length > 0)
            //{
            //    e.preventDefault();
            //    $('#list_summary_text').focus();
            //}
            else
            {
                var viewBtns = $('[id*=btn-display-]');
                if (viewBtns.length > 0) {
                    e.preventDefault();
                    $(viewBtns[0]).focus();
                } else if ($('#sliderClickProxy').length > 0) {
                    e.preventDefault();
                    $('#sliderClickProxy').focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('loadButton')) {
            e.preventDefault();
            var listItems = $('.list-item-container');
            if (listItems.length > 0) {
                var lastListItem = $(listItems[listItems.length - 1]);
                if (lastListItem.attr('tabindex') != undefined && lastListItem.attr('tabindex') != null && lastListItem.attr('tabindex') >= 0) {
                    e.preventDefault();
                    lastListItem.focus();
                }
                else {
                    e.preventDefault();
                    lastListItem.find('[tabindex^=501]')[0].focus();
                }
            }
        }
        else if (
            (currentActiveItem.attr('tabindex') == 900 || currentActiveItem.attr('tabindex') == undefined || currentActiveItem.attr('tabindex') == null) &&
            !currentActiveItem.is('input[type=radio]') && //allow arrow key interactions on radiogroups
            !currentActiveItem.is('input[type=checkbox]') //allow arrow key interactions on checkboxes
        )    
        {
            var lastItem = $('[tabindex^=502]'); //footer
            if (lastItem.length > 0) {
                e.preventDefault();
                $(lastItem[lastItem.length - 1]).focus();
            }
            else {
                lastItem = $('[tabindex^=501]');
                if (lastItem.length > 0) {
                    e.preventDefault();
                    var index = lastItem.length - 1;
                    while (!$(lastItem[index]).is(':visible') && index > 0) {
                        index--;
                    }
                    $(lastItem[index]).focus();

                }
                else {
                    var viewBtns = $('[id*=btn-display-]');
                    if (viewBtns.length > 0) {
                        e.preventDefault();
                        $(viewBtns[0]).focus();
                    } else if ($('#sliderClickProxy').length > 0) {
                        e.preventDefault();
                        $('#sliderClickProxy').focus();
                    }
                    else {
                        var firstNavItem = $('.first-navigation-item');
                        if (firstNavItem) {
                            e.preventDefault();
                            firstNavItem.focus();
                        }
                    }
                }
            }
        }
    }
    else if (e.which == keyboardHelper.KeyCode.DOWN) {
        if (currentActiveItem.attr('tabindex') == 1 && currentActiveItem.is('input[name=SearchText]')){
            firstNavItem = $('.first-navigation-item');
            setTimeout(function () {
                var searchSuggestions = $('.search-suggestion');
                if (searchSuggestions.length > 0) {
                    e.preventDefault();
                    $(searchSuggestions[0]).focus();
                }
                else {
                    e.preventDefault();
                    firstNavItem.focus();
                }
            }, 200); //wait 200ms for hints list to populate into the DOM...
        }
        else if (currentActiveItem.attr('tabindex') == 1 && currentActiveItem.is('[class=search-suggestion]')) {
            var searchInput = $('.search-text');
            var searchSuggestions = $('.search-suggestion');
            var nextSuggestion = searchSuggestions.eq(searchSuggestions.index(currentActiveItem)+1);
            console.log(nextSuggestion);
            if (nextSuggestion.length > 0) {
                e.preventDefault();
                nextSuggestion.focus();
            }
            else {
                e.preventDefault();
                searchInput.focus();
            }
        }
        else if (currentActiveItem.attr('tabindex') <= 2 && currentActiveItem.closest('[class*=navbar-L1tab]').length == 0) {
            firstNavItem = $('.first-navigation-item');
            if (firstNavItem) {
                e.preventDefault();
                firstNavItem.focus();
            }
            else {
                var genericInput = $('[tabindex^=101]');
                if (genericInput.length > 0) {
                    $(genericInput[0]).focus();
                } else {
                    genericInput = $('[tabindex^=501]');
                    if (genericInput.length > 0) {
                        $(genericInput[0]).focus();
                    }
                    else {
                        genericInput = $('[tabindex^=502]');
                        if (genericInput.length > 0) {
                            $(genericInput[0]).focus();
                        }
                        else {
                            var footerLinks = $('.footer-inner-container').find('a');
                            if (footerLinks.length > 0) {
                                e.preventDefault();
                                $(footerLinks[0]).focus();
                            }
                        }
                    }
                }
            }
        }
        //else if (currentActiveItem.is('[class*=last-navigation-item'))
        //{
        //    e.preventDefault();
        //    var isFocus = false;

        //    if (!isFocus) {
        //        var slider = $('[class*=owl]');
        //        var isGoNext = false;
        //        if (slider.length > 0) {
        //            if ($(slider[0]).attr('id') === 'layerslider') {
        //                $(slider[0]).find('#sliderClickProxy').focus();
        //                isGoNext = true;
        //            }
        //            else {
        //                var genericItem = $('[tabindex^=250]');
        //                if (genericItem.length > 0) {
        //                    $(genericItem[0]).focus();
        //                    isGoNext = true;
        //                }
        //                else {
        //                    genericItem = $('[tabindex^=502]');
        //                    if (genericItem.length > 0) {
        //                        $(genericItem[0]).focus();
        //                        isGoNext = true;
        //                    }
        //                    else {
        //                        var footerLinks = $('.footer-inner-container').find('a');
        //                        if (footerLinks.length > 0) {
        //                            e.preventDefault();
        //                            $(footerLinks[0]).focus();
        //                            isGoNext = true;
        //                        }
        //                    }
        //                }

        //            }

        //        }
        //    }

        //}
        //else if ((currentActiveItem.is('[class*=owl]') || currentActiveItem.parent().is('[class*=owl]')) && (currentActiveItem.closest('#layerslider').length > 0 || currentActiveItem.is('#sliderClickProxy'))) {
        //    var userdashboards = $('[tabindex^=250]');
        //    if (userdashboards.length > 0) {
        //        e.preventDefault();
        //        $(userdashboards[0]).focus();
        //    }
        //    else if ($('#list_summary_text').length > 0) {
        //        e.preventDefault();
        //        $('#list_summary_text').focus();
        //    }
        //    else {
        //        var viewBtns = $('[id*=btn-display-]');
        //        if (viewBtns.length > 0) {
        //            e.preventDefault();
        //            $(viewBtns[0]).focus();
        //        }
        //        else {
        //            var genericItem = $('[tabindex^=502]');
        //            if (genericItem.length > 0) {
        //                $(genericItem[0]).focus();
        //            }
        //            else {
        //                var footerLinks = $('.footer-inner-container').find('a');
        //                if (footerLinks.length > 0) {
        //                    e.preventDefault();
        //                    $(footerLinks[0]).focus();
        //                }
        //            }
        //        }
        //    }
        //}
        //else if (currentActiveItem.is('[tabindex^=250]')) //User dashboard area
        //{
        //    if ($('#list_summary_text').length > 0) {
        //        e.preventDefault();
        //        $('#list_summary_text').focus();
        //    }
        //    else {
        //        var viewBtns = $('[id*=btn-display-]');
        //        if (viewBtns.length > 0) {
        //            e.preventDefault();
        //            $(viewBtns[0]).focus();
        //        }
        //        else {
        //            var genericItem = $('[tabindex^=502]');
        //            if (genericItem.length > 0) {
        //                $(genericItem[0]).focus();
        //            }
        //        }
        //    }
        //}
        //else if (currentActiveItem.attr('tabindex') == 301 || currentActiveItem.attr('tabindex') == 302) //Filter bar area
        //{
        //    var footerLinks = $('.footer-inner-container').find('a');
        //    if (footerLinks.length > 0) {
        //        e.preventDefault();
        //        $(footerLinks[0]).focus();
        //    }
        //}
        else if (currentActiveItem.is('#list_summary_text') || currentActiveItem.closest('#list_summary_text').length > 0 || currentActiveItem.is('[id*=btn-display-]'))
        {
            var mapBtns = $('.NavBar_Button'); //bingMaps class for zoom buttons
            var listItems = $('.list-item-container');

            if (mapBtns.length > 0)//map is displayed, arrow down to first 501 (zoom button)
            {
                e.preventDefault();
                $('#ZoomInButton').focus();
            }
            else if (listItems.length > 0) {
                var firstItem = $(listItems[0]);
                if (firstItem.attr('tabindex') != undefined && firstItem.attr('tabindex') != null && firstItem.attr('tabindex') >= 0) {
                    e.preventDefault();
                    firstItem.focus();
                }
                else {
                    e.preventDefault();
                    firstItem.find('[tabindex^=501]')[0].focus();
                }
            }
        }
        else if (
            currentActiveItem.hasClass('list-item-container') ||
            currentActiveItem.hasClass('map-list-item') ||
            currentActiveItem.hasClass('NavBar_Button') ||
            currentActiveItem.hasClass('map-pane-toggle-button')
        )
        {
            keyboardHelper.isKeyboardNavigating = true;

            if (currentActiveItem.hasClass('NavBar_zoomOut') || currentActiveItem.hasClass('map-pane-toggle-button')) {
                //focus currently on zoomOut, focus hack: force user to *TAB* to next item
                e.preventDefault();
            }
            else if (currentActiveItem.next().length > 0) {
                var nextItem = currentActiveItem.next();
                if (nextItem.attr('tabindex') != undefined && nextItem.attr('tabindex') != null && nextItem.attr('tabindex') >= 0) {

                    ////logging... for WCAG troubleshooting
                    //console.log('next has tabindex');
                    //console.log(nextItem);

                    e.preventDefault();
                    nextItem.focus();
                }
                else {

                    ////logging... for WCAG troubleshooting
                    //console.log('next no tabindex... find the next 501 for focus');
                    //console.log($(currentActiveItem.find('[tabindex^=501]')[0]));

                    e.preventDefault();
                    $(currentActiveItem.find('[tabindex^=501]')[0]).focus();
                }
            }
            else if ($('#loadButton').length > 0 && $('#loadButton').is(':visible')) {
                e.preventDefault();
                $('#loadButton').focus();
            }
            else {
                var footerLinks = $('.footer-inner-container').find('a');
                if (footerLinks.length > 0) {
                    e.preventDefault();
                    $(footerLinks[0]).focus();
                }
            }
        }
        else if (currentActiveItem.closest('.list-item-container').length > 0) {
            keyboardHelper.isKeyboardNavigating = true;
            var parent = currentActiveItem.closest('.list-item-container');
            if (parent.next().length > 0) {
                var nextItem = parent.next();
                if (nextItem.attr('tabindex') != undefined && nextItem.attr('tabindex') != null && nextItem.attr('tabindex') >= 0) {
                    nextItem.focus();
                }
                else {
                    $(nextItem.find('[tabindex^=501]')[0]).focus();
                }
            }
            else if ($('#loadButton').length > 0 && $('#loadButton').is(':visible')) {
                e.preventDefault();
                $('#loadButton').focus();
            }
            else {
                var footerLinks = $('.footer-inner-container').find('a');
                if (footerLinks.length > 0) {
                    e.preventDefault();
                    $(footerLinks[0]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('timeline-panel')) {
            keyboardHelper.isKeyboardNavigating = true;
            if (currentActiveItem.parent().next().length > 0) {
                var nextItem = currentActiveItem.parent().next();
                if (!nextItem.hasClass('clearfix')) {
                    if (nextItem.attr('tabindex') != undefined && nextItem.attr('tabindex') != null && nextItem.attr('tabindex') >= 0) {
                        e.preventDefault();
                        nextItem.focus();
                    }
                    else {
                        e.preventDefault();
                        $(nextItem.find('[tabindex^=502]')[0]).focus();
                    }
                }
                else {
                    var footerLinks = $('.footer-inner-container').find('a');
                    if (footerLinks.length > 0) {
                        e.preventDefault();
                        $(footerLinks[0]).focus();
                    }
                }
            }
            else {
                var footerLinks = $('.footer-inner-container').find('a');
                if (footerLinks.length > 0) {
                    e.preventDefault();
                    $(footerLinks[0]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('loadButton')) {
            var footerLinks = $('.footer-inner-container').find('a');
            if (footerLinks.length > 0) {
                e.preventDefault();
                $(footerLinks[0]).focus();
            }
        }
    }
    else if (e.which == keyboardHelper.KeyCode.LEFT) {

        if (currentActiveItem.is('#list_summary_text') ||
            currentActiveItem.closest('#list_summary_text').length > 0 ||
            currentActiveItem.is('[id*=btn-display-]')) {
            var filterItems = $('[tabindex^=302]');
            if (filterItems.length > 0) {
                e.preventDefault();
                $(filterItems[0]).focus();
            }
        }
        else if (currentActiveItem.hasClass('featured-offer-anchor')) {
            var parent = currentActiveItem.closest('.owl-item');
            if (parent.length > 0) {
                if (parent.prev().length > 0) {
                    e.preventDefault();
                    parent.prev().find('.featured-offer-anchor').focus();
                }
            }
        }
        else if (currentActiveItem.parent().hasClass('hotdeal-item')) {
            var parent = currentActiveItem.closest('.owl-item');
            if (parent.length > 0) {
                if (parent.prev().length > 0) {
                    e.preventDefault();
                    $(parent.prev().find('a')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('selection-thumbnail')) {
            var parent = currentActiveItem.parent();
            if (parent.length > 0) {
                if (parent.prev().length > 0) {
                    e.preventDefault();
                    $(parent.prev().find('a')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.parent().hasClass('result-item')) {
            var parent = currentActiveItem.parent();
            if (parent.length > 0) {
                if (parent.prev().length > 0) {
                    e.preventDefault();
                    $(parent.prev().find('div[tabindex^=501]')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('home-view-list-item')) {
            var parent = currentActiveItem.closest('.owl-item');
            if (parent.length > 0) {
                if (parent.prev().length > 0) {
                    e.preventDefault();
                    $(parent.prev().find('div[tabindex^=501]')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.parent().hasClass('top-offer-item')) {
            var parent = currentActiveItem.parent();
            if (parent.length > 0) {
                if (parent.prev().length > 0) {
                    e.preventDefault();
                    $(parent.prev().find('a[tabindex^=501]')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('list-item-container')) {
            keyboardHelper.isKeyboardNavigating = true;
            var filterItems = $('[tabindex^=302]');
            if (filterItems.length > 0) {
                e.preventDefault();
                $(filterItems[0]).focus();
            }

        } else if (currentActiveItem.closest('.list-item-container').length > 0) {
            keyboardHelper.isKeyboardNavigating = true;
            var filterItems = $('[tabindex^=302]');
            if (filterItems.length > 0) {
                e.preventDefault();
                $(filterItems[0]).focus();
            }
        }
    }
    else if (e.which == keyboardHelper.KeyCode.RIGHT) {

        if (currentActiveItem.attr('tabindex') == 302 || currentActiveItem.tabIndex == 302) //Filter bar area
        {
            var summaryText = $('[tabindex^=499]');
            if (summaryText.length > 0) {
                e.preventDefault();
                $(summaryText[0]).focus();
            }
            else {
                var viewBtns = $('[id*=btn-display-]');
                if (viewBtns.length > 0) {
                    e.preventDefault();
                    $(viewBtns[0]).focus();
                }
                else {
                    var genericItem = $('[tabindex^=502]');
                    if (genericItem.length > 0) {
                        e.preventDefault();
                        $(genericItem[0]).focus();
                    }
                }
            }
        }
        else if (currentActiveItem.hasClass('featured-offer-anchor')) {
            var parent = currentActiveItem.closest('.owl-item');
            if (parent.length > 0) {
                if (parent.next().length > 0) {
                    e.preventDefault();
                    parent.next().find('.featured-offer-anchor').focus();
                }
            }
        }
        else if (currentActiveItem.parent().hasClass('hotdeal-item')) {
            var parent = currentActiveItem.closest('.owl-item');
            if (parent.length > 0) {
                if (parent.next().length > 0) {
                    e.preventDefault();
                    $(parent.next().find('a')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('selection-thumbnail')) {
            var parent = currentActiveItem.parent();
            if (parent.length > 0) {
                if (parent.next().length > 0) {
                    e.preventDefault();
                    $(parent.next().find('a')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.parent().hasClass('result-item')) {
            var parent = currentActiveItem.parent();
            if (parent.length > 0) {
                if (parent.next().length > 0) {
                    e.preventDefault();
                    $(parent.next().find('div[tabindex^=501]')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.hasClass('home-view-list-item')) {
            var parent = currentActiveItem.closest('.owl-item');
            if (parent.length > 0) {
                if (parent.next().length > 0) {
                    e.preventDefault();
                    $(parent.next().find('div[tabindex^=501]')[0]).focus();
                }
            }
        }
        else if (currentActiveItem.parent().hasClass('top-offer-item')) {
            var parent = currentActiveItem.parent();
            if (parent.length > 0) {
                if (parent.next().length > 0) {
                    e.preventDefault();
                    $(parent.next().find('a[tabindex^=501]')[0]).focus();
                }
            }
        }
    }
}

function onGlobalFocus() {
    var currentActiveItem = document.activeElement;
}
/*******************************
*   List Panel - JavaScript    *
*   Loads a list of Vendors
********************************/

var ListView = {
    listItemsLoaded: 0,
    additonalListItemsLoaded: 0,
    haveLoadedAdditionalOffers: false,
    loaderHtml: '<div class="vendor-list-loader vendor-loader-border"><span></span><p style="margin-top:2em;">Loading data...</p></div>',
    loadMore: $('.loadButton'),
    mainContent: null,
    isLoadMore: null,
    isLoadingMore: false,
    eventType: 'click',
    xhr: null,
    Init: function (mainContent, isLoadMore) {

        ListView.mainContent = $(mainContent);
        ListView.isLoadMore = isLoadMore;

        ////Bind to List_content
        //$(mainContent).off("click",".color_bar")
        //$(mainContent).on("click", ".color_bar", function (e) {
        //    e.stopPropagation();
        //    var div = $(this);
        //    div.animate({ width: '112px', height: '86px' }, "swing");
        //    div.children('.categoryName').show();
        //});
        //$(mainContent).off("mouseleave", ".color_bar")
        //$(mainContent).on("mouseleave", ".color_bar", function (e) {
        //    e.stopPropagation();
        //    var div = $(this);
        //    div.animate({ width: '9px', height: '100%' }, "fast");
        //    div.children('.categoryName').hide();
        //});

        //set the expand/collapse click event on the minmax button
        $(mainContent).off("click", ".dropdown-minmax");
        $(mainContent).on("click", ".dropdown-minmax", function (e) {
            e.stopPropagation();

            if ($(this).hasClass("grid")) {
                ListView._expandGridCollapseDetail(this);
            }
            else {
                ListView._expandCollapseDetail(this);
            }

        });

        //set the expand/collapse click event on the center and left columns of the listing header (not in the content areas)
        $(mainContent).off("click", ".vendor-body-center");
        $(mainContent).on("click", ".vendor-body-center", function (e) {
            var parent = $(this).parent();
            if (parent.hasClass('vendor-listing-header')) {
                e.stopPropagation();
                ListView._expandCollapseDetail($(this).siblings('.dropdown-minmax'));
            }
        });
        $(mainContent).off("click", ".vendor-body-left");
        $(mainContent).on("click", ".vendor-body-left", function (e) {
            var parent = $(this).parent();
            if (parent.hasClass('vendor-listing-header')) {
                e.stopPropagation();
                ListView._expandCollapseDetail($(this).siblings('.dropdown-minmax'));
            }
        });

        ////set the expand/collapse click event on the featured preview and fadeout overlay (when they exist)
        //$(mainContent).off("click", ".featured-preview")
        //$(mainContent).on("click", ".featured-preview", function (e) {
        //    e.stopPropagation();
        //    ListView._expandCollapseDetail($(this).siblings('.vendor-list-item-header').children('.dropdown-minmax'));
        //});
        //$(mainContent).off("click", ".featured-preview-fadeout")
        //$(mainContent).on("click", ".featured-preview-fadeout", function (e) {
        //    e.stopPropagation();
        //    ListView._expandCollapseDetail($(this).siblings('.vendor-list-item-header').children('.dropdown-minmax'));
        //});


        //Load LoadButton Event
        $(".page-content").on('click keyup', "#loadButton", function (e) {
            e.stopPropagation();
            ListView.eventType = e.type;
            ListView.LoadMoreListItem();
        });

        if (isLoadMore) {
            // Load content when scrolling
            $(window).scroll(function () {
                var offsetscroll = 0;
                var pageIndex = 0;
                var totalCount = 0;

                pageIndex = queryModel.PageIndex;
                totalCount = parseInt(FilterBar.List_Count.val());

                var loadThreshhold = ($(document).height() / pageIndex) / 2;
                if (!keyboardHelper.isKeyboardNavigating) {
                    if ((!queryModel.IsListView) &&
                        (!ListView.haveLoadedAdditionalOffers) && !ListView.isLoadingMore
                        && (($(window).scrollTop() + $(window).height()) > ($(document).height() - (loadThreshhold + 480)))) {

                        ListView.LoadMoreListItem();

                        // Calc If Loading More?
                    }
                    else if (//!isKeyboardNavigationOnList &&
                        queryModel.IsListView
                        && !ListView.isLoadingMore
                        && ($(window).scrollTop() + $(window).height()) > ($(document).height() - loadThreshhold - offsetscroll)) {
                        ListView.LoadMoreListItem();
                    }
                    // Re-enable List Content Auto-loading
                    //if ($(window).scrollTop() === 0) ListView.listLoadingPaused = false;
                }
            });
        }
    },

    Clear: function () {
        queryModel.PageIndex = 1;
        ListView.listItemsLoaded = 0;
        //queryModel.Count = 0;
        FilterBar.List_Count.val(15);
        ListView.mainContent.empty();
    },
    ResetFlags: function () {
        queryModel.IsListNeedData = true;
    },
    /** Get Vendor (load more results for the content list) */
    GetVendors: function (isAdditionalOffer) {

        ListView.DeactivateLoadMoreButton();
        loadingInProgress = true;
        if (ListView.xhr && ListView.xhr.readyState != 4) { ListView.xhr.abort(); /* console.log("abort"); */ }
        if ((queryModel.PageIndex === 1) && queryModel.IsListNeedData) ListView.Clear();

        queryModel.IsPremium = false;
        queryModel.IsLoadingBody = false;
        queryModel.SearchID = -1;

        ListView.xhr = $.ajax({
            url: "/Main/GetVendorList",
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            async: true,
            dataType: "json",
            traditional: true
        })
            // Success!
            .done(function (result) {
                if (result.Authorized != null && result.Authorized == false) {
                    redirectToLogin();
                }
                else {

                    queryModel.IsFilterApply = false;
                    queryModel.IsListNeedData = false;

                    FilterBar.List_Count.val(result.list_count).change();

                    if (FilterBar.List_Count.val() == 0) {
                        $('#favorite_no_content').show();
                    }

                    FilterBar.Additional_Count.val(result.additional_offer_count).change();
                    //FilterBar.Category_Text.val(result.category_text).change();
                    if (!isAdditionalOffer) {
                        FilterBar.Summary_Text.val(result.summary_text).change();
                        FilterBar.SuggestedResult_Text.val(result.suggested_text).change();
                    }

                    FilterBar.Hotdeal_Count.val(result.hotdeal_count).change();
                    FilterBar.New_Count.val(result.new_count).change();
                    FilterBar.Location_Applied.val(result.location_applied).change();
                    FilterBar.Previous_Location.val(result.previous_location).change();
                    //FilterBar.Is_Suggest_Result.val(result.is_suggest_result).change();
                    FilterBar.Is_KeywordRelevanceSort.val(result.is_keyword_relevance_sort).change();
                    FilterBar.Geolocation_Action.val(result.geolocation_action).change();
                    FilterBar.Search_Text.val(result.search_text).change();
                    FilterBar.Is_Vendor_Contains_Mappin.val(result.is_vendor_contains_mappin).change();

                    FilterBar.Green_Count.val(result.green_count).change();
                    FilterBar.Online_Count.val(result.online_count).change();
                    FilterBar.Local_Count.val(result.local_count).change();
                    FilterBar.Price1_Count.val(result.price1_count).change();
                    FilterBar.Price2_Count.val(result.price2_count).change();
                    FilterBar.Price3_Count.val(result.price3_count).change();
                    FilterBar.Price4_Count.val(result.price4_count).change();

                    FilterBar.Breakfast_Count.val(result.breakfast_count).change();
                    FilterBar.Brunch_Count.val(result.brunch_count).change();
                    FilterBar.Lunch_Count.val(result.lunch_count).change();
                    FilterBar.Dinner_Count.val(result.dinner_count).change();

                    FilterBar.Upscale_Count.val(result.upscale_count).change();
                    FilterBar.Casual_Count.val(result.casual_count).change();
                    FilterBar.Quick_Count.val(result.quick_count).change();
                    FilterBar.CoffeeDesserts_Count.val(result.coffee_desserts_count).change();
                    FilterBar.HappyHour_Count.val(result.happy_hour_count).change();
                    FilterBar.ToGo_Count.val(result.to_go_count).change();
                    FilterBar.Delivery_Count.val(result.delivery_count).change();
                    FilterBar.Banquets_Count.val(result.banquets_count).change();

                    if (queryModel.IsFilterUpdate) {
                        $("#CategoryFilterLegend").html(result.navigation_header.replace("\\", ""));
                        //$(".section-filters-filter.category .section-filters-filter-title").html(result.navigation_header.replace("\\", ""));
                        //no need to show a single filter selection (length = 2), only useful when there are at least 2 picks (length = 3)
                        if (result.navigation_list.length <= 2) {
                            $('#CategoryFilterPanel').hide();
                            //$(".section-filters-filter.category").hide();
                        }
                        else {
                            $('#CategoryFilterPanel').show();
                            //$(".section-filters-filter.category").show();
                        }

                        var data = $.map(result.navigation_list, function (item, a) {
                            var controlHTML = "";

                            if (item.IsPopularDestination) {
                                controlHTML = "" +
                                    "<input type='radio' name='Category' value='" + item.CategoryID + "' data-filtertype='pop-dest-radio' id='Category_" + item.CategoryID + "' " + ((item.IsSelected) ? "checked='checked'" : "") + ">" +
                                    "<label for='Category_" + item.CategoryID + "'>" + item.CategoryName + "</label>" +
                                    "<input type='hidden' id='destLatLon_" + item.CategoryID + "' value='" + item.HiddenLatLon + "' >" +
                                    "<input type='hidden' id='destName_" + item.CategoryID + "' value='" + item.CategoryName + "' >"
                            }
                            else if (item.CategoryID == 0) {
                                controlHTML = "" +
                                    "<input type='checkbox' role='button' class='clear-input' name='Category' value='" + item.CategoryID + "' id='Category_" + item.CategoryID + "' " + ((item.IsSelected) ? "checked='checked' tabindex='-1'" : "tabindex='302'") + ">" +
                                    "<label for='Category_" + item.CategoryID + "' class='clear-input'>" + item.CategoryName + "</label>"
                            }
                            else {
                                controlHTML = "" +
                                    "<input type='checkbox' tabindex='302' name='Category' value='" + item.CategoryID + "' id='Category_" + item.CategoryID + "' " + ((item.IsSelected) ? "checked='checked'" : "") + ">" +
                                    "<label for='Category_" + item.CategoryID + "'><i class='fa fa-square-o' aria-hidden='true'></i><i class='fa fa-check-square' aria-hidden='true'></i>" + item.CategoryName + "</label>"
                            }

                            return controlHTML;

                            //return "<li class='filters-checkbox' tabindex='302' role='" + ((item.IsPopularDestination) ? "radio" : "checkbox") + "' aria-label='" + ((item.CategoryID == 0) ? "clear selections'" : item.CategoryName + "'") + " aria-checked='" + ((item.IsSelected) ? "true" : "false") + "'" + ((item.CategoryID == 0) ? " id='clear-input'" : "") + "" + ((item.CategoryID == 0 && item.IsSelected) ? "style='display:none;'" : "") + "><label " + ((item.CategoryID == 0) ? "class='clear-input'" : "") + " aria-hidden='true'><input type='" + ((item.IsPopularDestination) ? "radio" : "checkbox") + "' name='Category' id='Category' value='" + item.CategoryID + "'" + ((item.IsSelected) ? "checked" : "") + "/> <span>" + item.CategoryName + "</span></label>" +
                            //        ((item.IsPopularDestination) ? "<input type='hidden' class='hidden-cat-latlon' value='" + item.HiddenLatLon + "'>" : "") +
                            //        "</li>";

                        });

                        //var mapdata = $.map(result.navigation_list, function (item, a) {
                        //    return "<div class='section-filters-checkbox filters-checkbox'><label><input type='" + ((item.IsPopularDestination) ? "radio" : "checkbox") + "' name='Category' value='" + item.CategoryID + "'" + ((item.IsSelected) ? "checked" : "") + ">" +
                        //        item.CategoryName + "</label>" + ((item.IsPopularDestination) ? "<input type='hidden' class='hidden-cat-latlon' value=" + item.HiddenLatLon + ">" : "") + "</div>";
                        //});

                        $("#CategoryList").html(data.join(""));
                        //$(".section-filters-options.category div").html(mapdata.join(""));
                        $('#filterPanel input[type=checkbox][name="Category"]:first').trigger('updatecheck');
                        queryModel.IsFilterUpdate = false;
                    }

                    ListView._loadContentData(result.html, isAdditionalOffer);

                    LocationView.Clear();
                    SearchView.Clear();
                    // HotDeal Event

                    loadingInProgress = false;
                    ListView.haveLoadedAdditionalOffers = false;
                    ListView.isLoadingMore = false;
                    if (isAdditionalOffer) {
                        queryModel.AdditionalOfferPageIndex++;
                        ListView.haveLoadedAdditionalOffers = true;
                    }
                    else {
                        queryModel.PageIndex++;
                    }
                    queryModel.Count = 15;
                }
            })
            // Error!
            .fail(function (result) {
                loadingInProgress = false;
            });
    },
    /** Get Vendor Content (vendor body content)*/
    GetVendorDetail: function (bIsBackground, isAdditionalOffer) {
        if (bIsBackground == null) bIsBackground = false;

        return $.ajax({
            url: "/Main/GetVendorContent",
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            cache: false,
            traditional: true,
            async: true
        })
            // Success!
            .done(function (result) {
                console.log()
                if (!result.Authorized) {
                    redirectToLogin();
                }
                else {
                    if (!bIsBackground) {
                        ListView._loadContentDetail(result.Url);

                    }
                    queryModel.IsLoadingBody = false;
                    loadingInProgress = false;
                }
            })
            // Error!
            .fail(function (result) {
                loadingInProgress = false;
            });
    },


    /** Find vendor record and append loaded html */
    _loadContentData: function (html, isAdditionalOffer) {

        if (queryModel.IsListNeedData) {
            ListView.listItemsLoaded = 0;
        }

        //set flag for load premium data

        var containerName = (!queryModel.IsListView ? '#map_list_content' : '#list_content');

        $(containerName).append($(html).hide());
        var visibleVendorCount = $('.vendor').length;

        // Next Slice
        var nextSliceIndex = 0;
        nextSliceIndex = (ListView.listItemsLoaded > 0) ? (ListView.listItemsLoaded - 1) : 0;

        // Wait For Last Field To Load
        var waitForNextSliceToLoadLimit = 0;
        var waitForNextSliceToLoad = setInterval(function () {

            var nextSlice = $('.list-item-container', containerName).slice(nextSliceIndex);

            if ((nextSlice !== undefined && nextSlice !== null) || (waitForNextSliceToLoadLimit === 200)) {
                clearInterval(waitForNextSliceToLoad);
                // Iterate and setup List Items
                $(nextSlice).each(function () {
                    var currItemObj = $(this);
                    Tipped.create($("a[target='_blank']", currItemObj), 'Opens a new window', { hideOthers: true, showOn: 'focus mouseover', hideOn: 'blur mouseout' });
                    Tipped.create($(".showTipped[title]", currItemObj), { hideOthers: true, showOn: 'focus mouseover', hideOn: 'blur mouseout' });
                    if ($(currItemObj).hasClass('hotdeal-panel')) {
                        if (queryModel.IsListView) {
                            bindOwlCarousel(currItemObj, '.owl-carousel',
                                {
                                    0: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 0
                                    },
                                    850: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 25
                                    },
                                    900: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 30
                                    },
                                    960: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 70
                                    },
                                    1060: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 130
                                    },
                                    1160: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 25
                                    }
                                }
                            );
                        }
                        else {
                            bindOwlCarousel(currItemObj, '.owl-carousel',
                                {
                                    0: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 50
                                    },
                                    900: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 100
                                    },
                                    960: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 30
                                    },
                                    1060: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 50
                                    },
                                    1160: {
                                        items: 4,
                                        slideBy: 4,
                                        stagePadding: 10
                                    }
                                }
                            );
                        }
                        bindHotDealDotDotDot(currItemObj);
                        $(currItemObj).show();
                        return;
                    }

                    //if ($(currItemObj).hasClass('top-offer-logo-panel')) {
                    //    bindOwlCarousel(currItemObj, '.owl-carousel', 6, 6);
                    //    $(currItemObj).show();
                    //    return;
                    //}

                    if ($(currItemObj).hasClass('featured-offer-panel-flex')) {
                        //bindOwlCarousel(currItemObj, '.owl-carousel', 4, 4, 50);


                        if (queryModel.IsListView) {
                            bindOwlCarousel(currItemObj, '.owl-carousel',
                                {
                                    0: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 50
                                    },
                                    830: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 75
                                    },
                                    900: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 15
                                    },
                                    960: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 50
                                    },
                                    1060: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 75
                                    },
                                    1160: {
                                        items: 4,
                                        slideBy: 4,
                                        stagePadding: 50
                                    }
                                }
                            );
                        }
                        else {
                            bindOwlCarousel(currItemObj, '.owl-carousel',
                                {
                                    0: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 50
                                    },
                                    830: {
                                        items: 2,
                                        slideBy: 2,
                                        stagePadding: 75
                                    },
                                    900: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 15
                                    },
                                    960: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 50
                                    },
                                    1060: {
                                        items: 3,
                                        slideBy: 3,
                                        stagePadding: 75
                                    },
                                    1160: {
                                        items: 4,
                                        slideBy: 4,
                                        stagePadding: 50
                                    }
                                }
                            );
                        }



                        bindOfferDotDotDot(currItemObj);
                        $(currItemObj).show();
                        return;
                    }
                    if ($(currItemObj).hasClass('portal-html-container')) {
                        $(currItemObj).show();
                        return;
                    }

                    // Tooltips
                    Tipped.create($(currItemObj).find('.span-actions i, .a-actions i'), { hideOthers: true, showOn: 'focus mouseover', hideOn: 'blur mouseout' });

                    // Display!
                    $(currItemObj).show();

                    if ($(currItemObj).css('display') !== 'none') {
                        ListView.listItemsLoaded++;
                    }

                });

                // Loading More Content Bar
                ListView.ActivateLoadMoreButton();

                if ((queryModel.PageIndex * queryModel.Count) >= parseInt(FilterBar.List_Count.val())) {
                    //add condition hide button when use deepling 
                    if ((window.location.href.indexOf('?vendor') > -1) || (window.location.href.indexOf('?cv') > -1)) {
                        $(".loadButton").show();
                    }
                    else {
                        $(".loadButton").hide();
                    }
                }
                else {
                    $(".loadButton").fadeIn('fast');
                    if (visibleVendorCount > 15 && ListView.eventType == 'keyup') {
                        const lastVendor = $('.vendor')[visibleVendorCount - 15];
                        $(lastVendor).find('.visit-website').focus();
                    }
                }


                //add margin top for first item
                //if ($('#loadButton').hasClass('deep-link-apply') && ($('#txtListOfferCategories').children().length === 0)) {
                //    $('#list_content').find('.list-item-container:first').css('margin-top', '4.5em');
                //}
                //else if ($('#txtListOfferCategories').children().length === 0) {
                //    $('#list_content').find('.list-item-container:first').css('margin-top', '0.5em');
                //}
                //>

                // Destroy Context Loading Spinner
                //if (activeContextLoadingSpinner !== null) {
                //    destroyContextLoadingSpinner(activeContextLoadingSpinner);
                //    activeContextLoadingSpinner = null;
                //}

                // Reset scroll loading
                loadingInProgress = false;

                // Cache Map Pins
                if (queryModel.PageIndex === 1) {
                    MapView.cacheMapPins();
                }
                //>

            }
            waitForNextSliceToLoadLimit++;
        }, 25);


    },
    _loadContentDetail: function (html) {
        var containerName = (!queryModel.IsListView ? '#map_list_content' : '#list_content');
        var bufferDiv = document.createElement('div');
        var items = $(bufferDiv).append(html);
        
        $(items).find('.vendor-listing-body').each(function () {

            var currItemObj = $(this);

            if ($(currItemObj).attr('id').indexOf('vendor-list-item-body-') > -1) {
                vendorId = $(currItemObj).attr('id').replace('vendor-list-item-body-', '');
                maindiv = $(containerName).find('#vendor-list-item-' + vendorId);
            }
            else if ($(currItemObj).attr('id').indexOf('chain-list-item-body-') > -1) {
                vendorId = $(currItemObj).attr('id').replace('chain-list-item-body-', '');
                maindiv = $(containerName).find('#chain-list-item-' + vendorId);
            }

            if ($(maindiv).length > 0) {
                if (($(maindiv).find('div[id^="vendor-list-item-body-"]').length == 0) && ($(maindiv).find('div[id^="chain-body-"]').length == 0)) {
                    ListView._appendBody(maindiv, currItemObj, vendorId);
                }
            }
        });
    },
    _appendBody: function (maindiv, currItemObj, vendorId) {
        if ((maindiv.find('#vendor-list-item-body-' + vendorId).length == 0) &&
            (maindiv.find('#chain-body-' + vendorId).length == 0)) {

            //add body content
            $(maindiv).addClass('appended-body');

            //add body content
            if (maindiv.hasClass('grid-item-container')) {
                var content = maindiv.next('.grid-item-content');
                content.html(currItemObj);
            }
            else {
                maindiv.find('.vendor-listing-header').after(currItemObj);
                $(currItemObj).slideToggle(500);
                $(maindiv).find('.vendor-offer-preview').fadeOut(200);
                $(maindiv).find('.hot-deal-preview').fadeOut(200);
            }
        }
    },

    /** Load Content Data */
    _expandCollapseDetail: function (context) {
        var blIsExpanded = false; //when true, the listing is currently expanded (should be collapsed)
        var blIsFeatured = false; //when true, the listing is currently in a partially-expanded "featured preview" state

        $(context).toggleClass('dropdown-minmax-collapsed').promise().done(function () {

            blIsExpanded = $(this).hasClass('dropdown-minmax-collapsed') ? true : false;
            var currItemObj = $(context).parents('.list-item-container');
            $(this).parents('.vendor.list-item-container').toggleClass('list-item-expanded', !blIsExpanded);
            var objectId = -1;

            if ($(currItemObj).attr('id').indexOf('vendor-list-item-') > -1) {
                objectId = $(currItemObj).attr('id').replace('vendor-list-item-', '');
                if (queryModel != null) {
                    queryModel.IsChain = false;
                }
            }
            if ($(currItemObj).attr('id').indexOf('chain-list-item-') > -1) {
                objectId = $(currItemObj).attr('id').replace('chain-list-item-', '');
                if (queryModel != null) {
                    queryModel.IsChain = true;
                }
            }

            blIsFeatured = $(currItemObj).hasClass('is-featured') ? true : false;
            if (blIsFeatured) {
                $(currItemObj).removeClass('is-featured'); //remove the is-featured class from the wrapper
                $(currItemObj).find('.dropdown-minmax').removeClass('is-featured'); //remove the is-featured class from the minmax button
                $(currItemObj).find('.featured-preview').remove(); //destroy the "featured preview" content
                $(currItemObj).find('.featured-preview-fadeout').remove(); //destroy the "featured preview" fadout overlay
            }

            if (blIsExpanded) {
                $(context)
                    .attr({
                        'aria-expanded': false,
                        'aria-label': 'Click to expand ' + $(currItemObj).attr('aria-label'),
                        'title': 'Click to expand ' + $(currItemObj).attr('aria-label')
                    });

                //$(currItemObj)
                //    .find('.inner-col-left, .inner-col-center')
                //    .attr({
                //        'aria-label': 'Expand ' + $(currItemObj).attr('aria-label'),
                //        'alt': 'Expand ' + $(currItemObj).attr('aria-label')
                //    });

                $(currItemObj).find('div[id^="vendor-list-item-body-"]').slideToggle(500);
                $(currItemObj).find('div[id^="chain-list-item-body-"]').slideToggle(500);
                $(currItemObj).find('.vendor-offer-preview').fadeIn(600);
                $(currItemObj).find('.hot-deal-preview').fadeIn(600);
            }
            else {

                $(context)
                    .attr({
                        'aria-expanded': true,
                        'aria-label': 'Click to collapse ' + $(currItemObj).attr('aria-label'),
                        'title': 'Click to collapse ' + $(currItemObj).attr('aria-label')
                    });

                //$(currItemObj)
                //    .find('.inner-col-left, .inner-col-center')
                //    .attr({
                //        'aria-label': 'Collapse ' + $(currItemObj).attr('aria-label'),
                //        'alt': 'Collapse ' + $(currItemObj).attr('aria-label')
                //    });

                var isWaitForLoadBody = false;
                //    var isFirstCall = false;

                if ($(currItemObj).find('div[id^="vendor-list-item-body-"]').length === 0 &&
                    $(currItemObj).find('div[id^="chain-list-item-body-"]').length === 0 &&
                    queryModel != null
                ) {
                    //        isFirstCall = true;
                    if (objectId > -1) {

                        //set id for load by vendor
                        isWaitForLoadBody = true;
                        queryModel.SearchID = objectId;
                        queryModel.IsLoadingBody = true;

                        var loaderObject = $(ListView.loaderHtml);

                        if ($(currItemObj).find('.mappin-loader').length === 0) {
                            $(currItemObj).append(loaderObject);

                            //chage to use image for improve speed
                            Spinners.create($(".mappin-loader span"), {
                                radius: 1.5,
                                height: 8,
                                width: 1.5,
                                dashes: 8,
                                opacity: 1,
                                padding: 0,
                                rotation: 700,
                                color: '#666666'
                            }).play();
                        }

                        var ajaxCalling = ListView.GetVendorDetail();
                        ajaxCalling.done(function () {
                            isWaitForLoadBody = false;
                            //Kill Spinner, and do setup
                            Spinners.remove($(".vendor-list-loader span"));
                            $(".vendor-list-loader").remove();

                            $('.hotdeal-detail-message').dotdotdot({
                                wrap: 'word',
                                height: 75
                            });

                            Tipped.create($("a[target='_blank']:not(.guest-tip)"), 'Opens a new window', { hideOthers: true, showOn: 'focus mouseover', hideOn: 'blur mouseout' });

                        });

                    }
                }
                else {
                    $(currItemObj).find('div[id^="vendor-list-item-body-"]').slideToggle(500);
                    $(currItemObj).find('div[id^="chain-list-item-body-"]').slideToggle(500);
                    $(currItemObj).find('.vendor-offer-preview').fadeOut(200);
                    $(currItemObj).find('.hot-deal-preview').fadeOut(200);
                }

                //var waitForLoadBody = setInterval(function () {
                //    if (!isWaitForLoadBody) {

                //        clearInterval(waitForLoadBody);


                //    }
                //}, 10)
            }
        });
    },

    /** Load Content Data */
    _expandGridCollapseDetail: function (context) {
        var blIsExpanded = false; //when true, the listing is currently expanded (should be collapsed)
        var blIsFeatured = false; //when true, the listing is currently in a partially-expanded "featured preview" state

        var currItemObj = $(context).parents('.result-item');
        $(currItemObj).siblings('.result-item-expanded').each(function () {
            $(this).removeClass('result-item-expanded');
            $(this).height(TotalHeight($(this)));
        });

        $(currItemObj).toggleClass('result-item-expanded').promise().done(function () {

            blIsExpanded = $(this).hasClass('result-item-expanded') ? false : true;
            var objectId = -1;

            if ($(currItemObj).children('.grid-item-container').attr('id').indexOf('vendor-list-item-') > -1) {
                objectId = $(currItemObj).children('.grid-item-container').attr('id').replace('vendor-list-item-', '');
                if (queryModel != null) {
                    queryModel.IsChain = false;
                }
            }
            if ($(currItemObj).children('.grid-item-container').attr('id').indexOf('chain-list-item-') > -1) {
                objectId = $(currItemObj).children('.grid-item-container').attr('id').replace('chain-list-item-', '');
                if (queryModel != null) {
                    queryModel.IsChain = true;
                }
            }

            //    blIsFeatured = $(currItemObj).hasClass('is-featured') ? true : false;
            //    if (blIsFeatured) {
            //        $(currItemObj).removeClass('is-featured'); //remove the is-featured class from the wrapper
            //        $(currItemObj).find('.dropdown-minmax').removeClass('is-featured');; //remove the is-featured class from the minmax button
            //        $(currItemObj).find('.featured-preview').remove(); //destroy the "featured preview" content
            //        $(currItemObj).find('.featured-preview-fadeout').remove(); //destroy the "featured preview" fadout overlay
            //    }

            if (blIsExpanded) {
                $(context)
                    .attr({
                        'aria-expanded': false,
                        'aria-label': 'Expand ' + $(currItemObj).children().first().attr('aria-label'),
                        'alt': 'Expand ' + $(currItemObj).children().first().attr('aria-label')
                    });

                //$(currItemObj)
                //    .find('.inner-col-left, .inner-col-center')
                //    .attr({
                //        'aria-label': 'Expand ' + $(currItemObj).attr('aria-label'),
                //        'alt': 'Expand ' + $(currItemObj).attr('aria-label')
                //    });

                $(currItemObj).height(TotalHeight($(currItemObj)));


                //        var ExpandContent = $(currItemObj).next('.vendor-grid-item-content');
                //        $(ExpandContent).find('div[id^="vendor-list-item-body-"]').slideToggle(500, function () { $(ExpandContent).hide(); });
                //        $(ExpandContent).find('div[id^="chain-list-item-body-"]').slideToggle(500, function () { $(ExpandContent).hide(); });

                //        $(currItemObj).removeClass("grid-item-expanded");
                //        //$(currItemObj).find('.vendor-offer-preview').fadeIn(600);
                //        //$(currItemObj).find('.hot-deal-preview').fadeIn(600);
            }
            else {

                $(context)
                    .attr({
                        'aria-expanded': true,
                        'aria-label': 'Collapse ' + $(currItemObj).children().first().attr('aria-label'),
                        'alt': 'Collapse ' + $(currItemObj).children().first().attr('aria-label')
                    });
                console.log($(currItemObj).children().first())
                //$(currItemObj)
                //    .find('.inner-col-left, .inner-col-center')
                //    .attr({
                //        'aria-label': 'Collapse ' + $(currItemObj).attr('aria-label'),
                //        'alt': 'Collapse ' + $(currItemObj).attr('aria-label')
                //    });

                var isWaitForLoadBody = false;


                if ($(currItemObj).find('div[id^="vendor-list-item-body-"]').length === 0 &&
                    $(currItemObj).find('div[id^="chain-list-item-body-"]').length === 0 &&
                    queryModel != null) {

                    if (objectId > -1) {
                        //set id for load by vendor
                        isWaitForLoadBody = true;
                        queryModel.SearchID = objectId;
                        queryModel.IsLoadingBody = true;

                        $(currItemObj).find('.grid-item-content').append('<div class="vendor-list-loader vendor-loader-border"><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading...</span></div>');
                        $(currItemObj).height(TotalHeight($(currItemObj)));


                        var ajaxCalling = ListView.GetVendorDetail();
                        ajaxCalling.done(function () {
                            isWaitForLoadBody = false;
                            //Kill Spinner, and do setup
                            $(".vendor-list-loader").remove();

                            $(currItemObj).height(TotalHeight($(currItemObj)));

                            //                    $('.hotdeal-detail-message').dotdotdot({
                            //                        wrap: 'word',
                            //                        height: 75
                            //                    });
                        });

                    }
                }
                else {

                    $(currItemObj).height(TotalHeight($(currItemObj)));
                    //            var ExpandContent = $(currItemObj).next('.vendor-grid-item-content');
                    //            $(ExpandContent).show()
                    //            $(ExpandContent).find('div[id^="vendor-list-item-body-"]').slideToggle(500);
                    //            $(ExpandContent).find('div[id^="chain-list-item-body-"]').slideToggle(500);

                    //            //$(currItemObj).find('.vendor-offer-preview').fadeOut(200);
                    //            //$(currItemObj).find('.hot-deal-preview').fadeOut(200);
                    //            $(currItemObj).addClass("grid-item-expanded");
                }

            }
        });
    },
    /** Load More button functionality */
    LoadMoreListItem: function () {
        // console.log("LoadMoreListItem");
        ListView.isLoadingMore = true;
        //isKeyboardNavigationOnList = false;
        if (!this.loadMore.hasClass('loadButton-loading')) {
            this.loadMore.addClass('loadButton-loading');
        }
        var pageIndex = 0;
        var totalCount = 0;

        if (queryModel.IsListView) {
            pageIndex = queryModel.PageIndex;
            totalCount = parseInt(FilterBar.List_Count.val());
        } else {
            pageIndex = queryModel.AdditionalOfferPageIndex;
            totalCount = parseInt(FilterBar.Additional_Count.val());
        }

        //number of list item to return is based on a ((pageidex - 1) * Total to Return)
        if (((pageIndex - 1) * queryModel.Count) < totalCount) {
            ListView.GetVendors(!queryModel.IsListView);
        }
    },
    /** Activate Load More Button */
    ActivateLoadMoreButton: function () {

        var lb = this.loadMore;

        destroyContextLoadingSpinner($(lb).find('span'));
        $(lb).find('p').html(defaultBtnText);
        $(lb).removeClass('loadButton-loading');
        //if ((window.location.href.indexOf('?vendor') > -1) || (window.location.href.indexOf('?cv') > -1)) {
        //    lb.css('margin-top', '5px');
        //    Tipped.create(lb, 'Click to load all offers.');
        //}
        //else {
        //    $(lb).removeClass('deep-link-apply');
        //}

        $(lb).on('click', function () {
            if ((window.location.href.indexOf('?vendor') > -1) || (window.location.href.indexOf('?cv') > -1)) {

                if (window.location.pathname != "/") {
                    window.location.href = window.location.href.split('?')[0];
                }
                else {
                    window.location.href = window.location.href.split('?')[0] + "all";
                }

            }
            else {
                ListView.GetVendors();
            }
        });
        //>
    },
    /** Deactivate Load More Button */
    DeactivateLoadMoreButton: function () {

        var lb = this.loadMore;
        $(lb).show();
        $(lb).off('click');
        $(lb).find('p').html(defaultBtnText);
        $(lb).addClass('loadButton-loading');
        addContextLoadingSpinner($(lb).find('span'), spinnerColorDefault, 8);
    }
}


/** Get Vendor (load more results for the content list) */
//function getVendor() {

//    loadingInProgress = true;
//    var activeBtn;

        // Move Loading bar location...
        //if ($('.map-content-container').find('.loadButton').length) {
        //    $('.loadButton').appendTo('.page-content');
        //}
        //if (($('#divListOfferTextDisplay').css('display') == 'block') && $('.loadButton').hasClass('deep-link-apply')) {
        //    $('.loadButton').css('margin-top', $('#divListOfferTextDisplay').outerHeight() + 15 + 'px');
        //}
        //else {
        //    $('.loadButton').css('margin-top', '');
        //}

        //if ((queryModel.PageIndex === 1) && queryModel.IsListNeedData) $('#list_content').empty();
        //if (queryModel.IsFilterApply) $('#map_list_content').empty();

        //activeBtn = $('#divBtnGroupMapAndList').find('.btn-active');
        //addContextLoadingSpinner(activeBtn);
        //activeContextLoadingSpinner = $(activeBtn);
//}
//-->

/** Bind List View Actions */



    //$(document).on("click", ".dropdown-minmax, .vendor-name, .hot_deal_flag, .vendor_name_highlighted", function () {
    //    $(this).parent(".list-item-header").siblings("#wrapper_bot").slideToggle("fast");
    //    $(this).parent(".list-item-header").children(".dropdown_button").toggleClass("active");
    //});

//-->


//-->

//function LoadMoreListItem() {
//    //isKeyboardNavigationOnList = false;


//    if (!loadMore.hasClass('loadButton-loading')) {
//        loadMore.addClass('loadButton-loading');
//    }
//    var pageIndex = 0;
//    var totalCount = 0;

//    //if (ListView.currentViewMode === ListView.viewModes.LIST_VIEW) {
//    //    pageIndex = queryModel.PageIndex;
//    //    totalCount = parseInt($('#list_content').find('#hidden_total_list_count').first().val());
//    //} else {
//    //    pageIndex = queryModel.AdditionalOfferPageIndex;
//    //    totalCount = parseInt($('#map_list_content').find('#hidden_total_additional_offer_count').first().val());
//    //}
//    //if ((pageIndex * queryModel.Count) < totalCount) {

//        //if (ListView.currentViewMode === ListView.viewModes.LIST_VIEW) {
//            queryModel.PageIndex++;
//        //} else {
//        //    queryModel.AdditionalOfferPageIndex++;
//        //}
//        //queryModel.Count = queryModelCount;
//        getVendor();
//   // }
//}


/****************************************
*   Search + Filter bar - JavaScript    *
*   Loads a list of Vendors
****************************************/

var FilterBar = {
    SearchLocationBar: $('#filterPanel'),
    LocationSearchText: $('#LocationSearchText'),
    IsApplyLocation: false,
    IsLocationUpdate: false,

    List_Count: $('#hidden_total_list_count'),
    Additional_Count: $('#hidden_total_additional_offer_count'),
    Category_Text: $('#hidden_category_text'),
    Summary_Text: $('#hidden_summary_text'),
    SuggestedResult_Text: $('#hidden_suggest_text'),
    Hotdeal_Count: $('#hidden_hotdeal_count'),
    New_Count: $('#hidden_new_count'),
    Green_Count: $('#hidden_green_count'),
    Online_Count: $('#hidden_online_count'),
    Local_Count: $('#hidden_local_count'),
    Price1_Count: $('#hidden_price1_count'),
    Price2_Count: $('#hidden_price2_count'),
    Price3_Count: $('#hidden_price3_count'),
    Price4_Count: $('#hidden_price4_count'),
    Breakfast_Count: $('#hidden_breakfast_count'),
    Brunch_Count: $('#hidden_brunch_count'),
    Lunch_Count: $('#hidden_lunch_count'),
    Dinner_Count: $('#hidden_dinner_count'),
    Upscale_Count: $('#hidden_upscale_count'),
    Casual_Count: $('#hidden_casual_count'),
    Quick_Count: $('#hidden_quick_count'),
    CoffeeDesserts_Count: $('#hidden_coffeedesserts_count'),
    HappyHour_Count: $('#hidden_happyhour_Count_count'),
    ToGo_Count: $('#hidden_togo_count'),
    Delivery_Count: $('#hidden_delivery_count'),
    Banquets_Count: $('#hidden_banquets_count'),
  
    Location_Applied: $('#hidden_location_applied'),
    Previous_Location: $('#hidden_previous_location'),
    Is_Suggest_Result: $('#hidden_is_suggest_result'),
    Is_KeywordRelevanceSort: $('#hidden_is_keyword_relevance_sort'),
    Geolocation_Action: $('#hidden_geolocation_action'),
    Search_Text: $('#hidden_search_text'),
    Is_Vendor_Contains_Mappin: $('#hidden_is_vendor_contains_mappin'),

    Init: function () {

        if ($(FilterBar.SearchLocationBar).length) {

            $('#list_summary_text').html(FilterBar.Summary_Text.val());
            $('#map_summary_text').html(FilterBar.Summary_Text.val());
            FilterBar.Summary_Text.on('change', function (e) {
                $('#list_summary_text').html(FilterBar.Summary_Text.val());
                $('#map_summary_text').html(FilterBar.Summary_Text.val());
            });

            $('#suggested_results_text').html(FilterBar.SuggestedResult_Text.val());
            FilterBar.SuggestedResult_Text.on('change', function (e) {
                $('#suggested_results_text').html(FilterBar.SuggestedResult_Text.val());
            });

            FilterBar.Hotdeal_Count.on('change', function (e) {
                if (FilterBar.Hotdeal_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=Hot]').prop('disabled', true);
                }
                else {
                    $('input[name=Filter][value=Hot]').prop('disabled', false);
                }
            });

            FilterBar.New_Count.on('change', function (e) {
                if (FilterBar.New_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=New]').prop('disabled', true);
                }
                else {
                    $('input[name=Filter][value=New]').prop('disabled', false);
                }
            });

            FilterBar.Green_Count.on('change', function (e) {
                if (FilterBar.Green_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=Green]').prop('disabled', true);
                }
                else {
                    $('input[name=Filter][value=Green]').prop('disabled', false);
                }
            });

            FilterBar.Online_Count.on('change', function (e) {
                if (FilterBar.Online_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=Online]').prop('disabled', true);
                }
                else {
                    $('input[name=Filter][value=Online]').prop('disabled', false);
                }
            });

            FilterBar.Local_Count.on('change', function (e) {
                if (FilterBar.Local_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=Local]').prop('disabled', true);
                }
                else {
                    $('input[name=Filter][value=Local]').prop('disabled', false);
                }
            });

            FilterBar.Price1_Count.on('change', function (e) {
                if (FilterBar.Price1_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                    $('input[name=Price][value=1]').prop('disabled', true);
                }
                else {
                    $('input[name=Price][value=1]').prop('disabled', false);
                }
            });

            FilterBar.Price2_Count.on('change', function (e) {
                if (FilterBar.Price2_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                    $('input[name=Price][value=2]').prop('disabled', true);
                }
                else {
                    $('input[name=Price][value=2]').prop('disabled', false);
                }
            });

            FilterBar.Price3_Count.on('change', function (e) {
                if (FilterBar.Price3_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                    $('input[name=Price][value=3]').prop('disabled', true);
                }
                else {
                    $('input[name=Price][value=3]').prop('disabled', false);
                }
            });

            FilterBar.Price4_Count.on('change', function (e) {
                if (FilterBar.Price4_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                    $('input[name=Price][value=4]').prop('disabled', true);
                }
                else {
                    $('input[name=Price][value=4]').prop('disabled', false);
                }
            });

            FilterBar.Breakfast_Count.on('change', function (e) {
                if (FilterBar.Breakfast_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                    $('input[name=Meal][value=Breakfast]').prop('disabled', true);
                }
                else {
                    $('input[name=Meal][value=Breakfast]').prop('disabled', false);
                }
            });

            FilterBar.Brunch_Count.on('change', function (e) {
                if (FilterBar.Brunch_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                    $('input[name=Meal][value=Brunch]').prop('disabled', true);
                }
                else {
                    $('input[name=Meal][value=Brunch]').prop('disabled', false);
                }
            });

            FilterBar.Lunch_Count.on('change', function (e) {
                if (FilterBar.Lunch_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                    $('input[name=Meal][value=Lunch]').prop('disabled', true);
                }
                else {
                    $('input[name=Meal][value=Lunch]').prop('disabled', false);
                }
            });

            FilterBar.Dinner_Count.on('change', function (e) {
                if (FilterBar.Dinner_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                    $('input[name=Meal][value=Dinner]').prop('disabled', true);
                }
                else {
                    $('input[name=Meal][value=Dinner]').prop('disabled', false);
                }
            });

            FilterBar.Upscale_Count.on('change', function (e) {
                if (FilterBar.Upscale_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=Upscale]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=Upscale]').prop('disabled', false);

                }
            });

            FilterBar.Casual_Count.on('change', function (e) {
                if (FilterBar.Casual_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=Casual]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=Casual]').prop('disabled', false);

                }
            });

            FilterBar.Quick_Count.on('change', function (e) {
               
                if (FilterBar.Quick_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=QuickServe]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=QuickServe]').prop('disabled', false);

                }
            });

            FilterBar.CoffeeDesserts_Count.on('change', function (e) {
                if (FilterBar.CoffeeDesserts_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=CoffeeDesserts]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=CoffeeDesserts]').prop('disabled', false);

                }
            });

            FilterBar.HappyHour_Count.on('change', function (e) {
                if (FilterBar.HappyHour_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=HappyHour]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=HappyHour]').prop('disabled', false);

                }
            });

            FilterBar.ToGo_Count.on('change', function (e) {
                if (FilterBar.ToGo_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=ToGo]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=ToGo]').prop('disabled', false);

                }
            });

            FilterBar.Delivery_Count.on('change', function (e) {
                if (FilterBar.Delivery_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=Delivery]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=Delivery]').prop('disabled', false);

                }
            });

            FilterBar.Banquets_Count.on('change', function (e) {
                if (FilterBar.Banquets_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline || queryModel.IsLocal || queryModel.IsUpscale || queryModel.IsCasual || queryModel.IsQuickServe || queryModel.IsCoffeeDesserts || queryModel.IsHappyHour || queryModel.IsToGo || queryModel.IsDelivery || queryModel.IsBanquetsCatering)) {
                    $('input[name=Filter][value=BanquetsCatering]').prop('disabled', true);

                }
                else {
                    $('input[name=Filter][value=BanquetsCatering]').prop('disabled', false);

                }
            });

            FilterBar.Is_KeywordRelevanceSort.on('change', function (e) {
                if (FilterBar.Is_KeywordRelevanceSort.val() == "true") {
                    $('input[name=Sort][value=0]').prop('disabled', true);
                    $('input[name=Sort][value=1]').prop('disabled', true);
                    $('input[name=Sort][value=2]').prop('disabled', true);
                    $('input[name=Sort][value=3]').prop('disabled', true);
                    $('input[name=Sort][value=4]').prop('disabled', true);
                    $('input[name=Sort][value=5]').prop('disabled', false); //Keyword relevance enabled

                    $('input[name=Sort][value=0]').prop('checked', false);
                    $('input[name=Sort][value=1]').prop('checked', false);
                    $('input[name=Sort][value=2]').prop('checked', false);
                    $('input[name=Sort][value=3]').prop('checked', false);
                    $('input[name=Sort][value=4]').prop('checked', false);
                    $('input[name=Sort][value=5]').prop('checked', true); //Keyword relevance checked
                }
                else {
                    $('input[name=Sort][value=0]').prop('disabled', false);
                    $('input[name=Sort][value=1]').prop('disabled', false);
                    $('input[name=Sort][value=2]').prop('disabled', false);
                    $('input[name=Sort][value=3]').prop('disabled', false);
                    $('input[name=Sort][value=4]').prop('disabled', false);
                    $('input[name=Sort][value=5]').prop('disabled', true); //Keyword relevance disabled

                    $('input[name=Sort][value=5]').prop('checked', false);
                }
            });


            FilterBar.SearchLocationBar.on("click", "#clearCategory", function () {
                $("input[name=Category]").val([]);
                $("#collapseCategoryText .collapseText").html("Expand for options");//$("#NavigationHeader").text()
                FilterBar.submitFilter(false);
            });

            FilterBar.SearchLocationBar.on("change", "input[type=radio]", function (e) {

                if (e.currentTarget.dataset.filtertype == "pop-dest-radio") {

                    var targetCategoryID = $(e.currentTarget).val();
                    var targetCategpryName_source = "#destName_" + targetCategoryID;
                    var targetLatLon_source = "#destLatLon_" + targetCategoryID;

                    RadionButtonSelectedValueSet('Category', targetCategoryID);

                    $('#location-container').addClass("disabled");
                    $('#location-container').attr('tabindex', -1);

                    LocationView.UpdateApplied($(targetCategpryName_source).val());

                    var latlon = $(targetLatLon_source).val().split(',');

                    queryModel.HiddenLocation = $(targetCategpryName_source).val();
                    queryModel.HiddenLatitude = latlon[0];
                    queryModel.HiddenLongitude = latlon[1];
                    
                    FilterBar.submitFilter();
                }
                else
                {
                    if (e.currentTarget.dataset.filtertype == "milebound-radio") {
                        queryModel.MilesBound = $(e.target).val();
                        LocationView.UpdateLocation();
                        RadionButtonSelectedValueSet('MileBound', $(e.target).val());
                        //to support keyboard interactions with legacy tabindex, allow tab key to focus on first selected radio in each fieldset
                        $('.milebound-radio').removeAttr("tabindex");
                        $(e.currentTarget).attr("tabindex", 302)
                    }
                    if (e.currentTarget.dataset.filtertype == "offertype-radio") {
                        RadionButtonSelectedValueSet('Filter', $(e.target).val());
                        $('.offertype-radio').removeAttr("tabindex");
                        $(e.currentTarget).attr("tabindex", 302)

                        if ($(e.target).val() === 'Online')
                        {
                            RadionButtonSelectedValueSet('Sort', 0);
                        }
                        else if(queryModel.IsOnline){
                            RadionButtonSelectedValueSet('Sort', 4);
                        }
                    }
                    if (e.currentTarget.dataset.filtertype == "mealtime-radio") {
                        RadionButtonSelectedValueSet('Meal', $(e.target).val());
                        $('.mealtime-radio').removeAttr("tabindex");
                        $(e.currentTarget).attr("tabindex", 302)
                    }
                    if (e.currentTarget.dataset.filtertype == "mealprice-radio") {
                        RadionButtonSelectedValueSet('Price', $(e.target).val());
                        $('.mealprice-radio').removeAttr("tabindex");
                        $(e.currentTarget).attr("tabindex", 302)
                    }
                    if (e.currentTarget.dataset.filtertype == "sortorder-radio") {
                        RadionButtonSelectedValueSet('Sort', $(e.target).val());
                        $('.sortorder-radio').removeAttr("tabindex");
                        $(e.currentTarget).attr("tabindex", 302)
                        queryModel.AlphabetFilterChar = null;
                    }
                    FilterBar.submitFilter();
                }            
            });

            FilterBar.SearchLocationBar.on("change", "input[type=checkbox]", function (e) {
                var uncheck = false;
                var a = [];
                if (e.currentTarget.value == "0") {
                    uncheck = true;
                }
                
                $('#filterPanel input[name="' + e.currentTarget.name + '"]:checked').each(function () {
                    if(this.value == 0) {
                        
                    }
                    else {
                        a.push(this.value);
                    }
                });

                if (a.length == 0)
                {
                    uncheck = true;
                }

                if (uncheck) {
                    $('input[type=checkbox][name="' + e.currentTarget.name + '"]').prop("checked", false);
                    $('input[type=checkbox][name="' + e.currentTarget.name + '"]').parents('.filters-checkbox').attr("aria-checked", false);
                    CheckboxButtonSelectedValueSet(e.currentTarget.name, ["0"]);
                    $('input[type=checkbox][name="' + e.currentTarget.name + '"][value=0]').prop("tabindex", "-1");

                } else {
                    $('input[type=checkbox][name="' + e.currentTarget.name + '"][value=0]').prop("checked", false);
                    $('input[type=checkbox][name="' + e.currentTarget.name + '"][value=0]').parents('.filters-checkbox').attr("aria-checked", false);
                    CheckboxButtonSelectedValueSet(e.currentTarget.name, a.unique());
                    $('input[type=checkbox][name="' + e.currentTarget.name + '"][value=0]').prop("tabindex", "302");

                }
                FilterBar.submitFilter(false);
            });

            $('input[name=Filter]:checked').trigger("update");
            $('input[name=Meal]:checked').trigger("update");
            $('input[name=MileBound]:checked').trigger("update");
            $('input[name=Sort]:checked').trigger("update");
            $('input[name=Price]:checked').trigger("update");

            $('.list-nav-char').off('click');
            $('.list-nav-char').on('click', function (e) {
                e.preventDefault();
                if (e.target.className.length == 1){
                    
                    $(e.target).parent().siblings().removeClass("active");
                    if (!$(e.target).parent().hasClass("active")) {
                        $(e.target).parent().addClass("active");
                        queryModel.AlphabetFilterChar = e.target.className;
                    }
                    else {
                        $(e.target).parent().removeClass("active");
                        queryModel.AlphabetFilterChar = null;
                    }
                    FilterBar.submitFilter();
                }
                else {
                    $(e.target).siblings().removeClass("active");
                    if (!$(e.target).hasClass("active")) {
                        $(e.target).addClass("active");
                        queryModel.AlphabetFilterChar = $(e.target).children('a')[0].className;
                    }
                    else {
                        $(e.target).removeClass("active");
                        queryModel.AlphabetFilterChar = null;
                    }

                    FilterBar.submitFilter();
                }
            });
            FilterBar.SearchLocationBar.on("click", "#profile_location", function (e) {
                event.preventDefault();
                queryModel.IsDefaultLocationApply = true;
                queryModel.CurrentLocationMode = enumLocationSearchMode.Default;
                FilterBar.submitFilter();
            });
        }
    },
    _updateFilter: function () {
        FilterBar._resetFilter();
        FilterBar._resetPrice();
        FilterBar._resetMeal();

        switch ($('#filterPanel input[name=Filter]:checked').val()) {
            case "New":
                queryModel.IsNew = true;
                break;
            case "Hot":
                queryModel.IsHot = true;
                break;
            case "Green":
                queryModel.IsGreen = true;
                break;
            case "Online":
                queryModel.IsOnline = true;
                break;
            case "Local":
                queryModel.IsLocal = true;
                break;
            case "Upscale":
                queryModel.IsUpscale = true;
                break;
            case "Casual":
                queryModel.IsCasual = true;
                break;
            case "QuickServe":
                queryModel.IsQuickServe = true;
                break;
            case "CoffeeDesserts":
                queryModel.IsCoffeeDesserts = true;
                break;
            case "HappyHour":
                queryModel.IsHappyHour = true;
                break;
            case "ToGo":
                queryModel.IsToGo = true;
                break;
            case "Delivery":
                queryModel.IsDelivery = true;
                break;
            case "BanquetsCatering":
                queryModel.IsBanquetsCatering = true;
                break;
            default:
                break;
        }
        switch ($('#filterPanel input[name=Meal]:checked').val()) {
            case "Breakfast":
                queryModel.IsBreakfast = true;
                break;
            case "Brunch":
                queryModel.IsBrunch = true;
                break;
            case "Lunch":
                queryModel.IsLunch = true;
                break;
            case "Dinner":
                queryModel.IsDinner = true;
                break;
            default:
                break;
        }
        switch ($('#filterPanel input[name=Price]:checked').val()) {
            case "1":
                queryModel.IsPrice1 = true;
                break;
            case "2":
                queryModel.IsPrice2 = true;
                break;
            case "3":
                queryModel.IsPrice3 = true;
                break;
            case "4":
                queryModel.IsPrice4 = true;
                break;
            case "5":
                queryModel.IsPrice5 = true;
                break;
            default:
                break;
        }

        queryModel.MilesBound = $('input[name=MileBound]:checked').val();
        queryModel.SortBy = $('input[name=Sort]:checked').val();

        if (queryModel.SortBy == 3)
        {
            $('.list-nav-char').show();
            
        }
        else {
            $('.list-nav-char').hide();
        }

        queryModel.Category = null;
        var a = [];
        $('#filterPanel input[name="Category"]:checked').each(function () {
            if (this.value !== "0") {
                a.push(this.value);
            }
            
        });
        queryModel.Category = a.join(",");
    },
    submitFilter: function (scrollUp) {
        queryModel.IsFilterApply = true;

        if (queryModel.IsListView) {
            FilterBar._updateFilter();
            ListView.Clear();
            ListView.ResetFlags();

            ListView.GetVendors();

            if (scrollUp == null || scrollUp) {
                autoScrollup();
            }
        }
        else {
            FilterBar._updateFilter();
            MapView.Clear();
            MapView.ResetFlags();
            MapView.loadBingMapData();
        }
    },
    clearFilter: function()
    {
        FilterBar._resetFilter();
        RadionButtonSelectedValueSet('Filter', '');
        FilterBar._resetPrice();
        RadionButtonSelectedValueSet('Price', '');
        FilterBar._resetMeal();
        RadionButtonSelectedValueSet('Meal', '');
        FilterBar.submitFilter();
    },
    applyVendorFilter: function (latitude, longitude, vendorName, uVendorId)
    {
        queryModel.CurrentLocationMode = enumLocationSearchMode.MapNearBy;
        queryModel.Latitude = latitude;
        queryModel.Longitude = longitude;
        queryModel.IsMapLocation = true;
        queryModel.NearByUniqueVendorID = uVendorId;
        queryModel.NearByVendorName = vendorName;
    },
    removeVendorFilter: function () {
        queryModel.NearByUniqueVendorID = -1;
        queryModel.NearByVendorName = '';

        MapView.ResetFlags();
    },
    _resetFilter:function()
    {
        queryModel.IsNew = false;
        queryModel.IsHot = false;
        queryModel.IsGreen = false;
        queryModel.IsOnline = false;
        queryModel.IsLocal = false;
        queryModel.IsUpscale = false;
        queryModel.IsCasual = false;
        queryModel.IsQuickServe = false;
        queryModel.IsCoffeeDesserts = false;
        queryModel.IsHappyHour = false;
        queryModel.IsToGo = false;
        queryModel.IsDelivery = false;
        queryModel.IsBanquetsCatering = false;
    },
    _resetMeal: function () {
        queryModel.IsBreakfast = false;
        queryModel.IsBrunch = false;
        queryModel.IsLunch = false;
        queryModel.IsDinner = false;
    },
    _resetPrice: function () {
        queryModel.IsPrice1 = false;
        queryModel.IsPrice2 = false;
        queryModel.IsPrice3 = false;
        queryModel.IsPrice4 = false;
    }
};

function removeFilter(x, t) {
    $(t).parent().hide();
    if (x === 'Search') {
        queryModel.SearchText = "";
        SearchView.searchForm.find("input[name=SearchText]").val('');
        SearchView.Submit();
    }
    else if (x === 'AlphabetFilter')
    {
        queryModel.AlphabetFilterChar = null;
        $('.list-nav-char').find('.ln-letters.active').removeClass("active");
        SearchView.Submit();
    }
    else {
        RadionButtonSelectedValueSet(x, '');
        FilterBar.submitFilter(false);
    }
}
function removeCategory(x,t) {

    $(t).parent().hide();

    if(x === '')
    {
        $('input[type=checkbox][name=Category][value=0]').click();
    }
    else {
        $('#filterPanel input[type=checkbox][name=Category][value=' + x + ']:first').prop("checked", false);
        $('#filterPanel input[type=checkbox][name=Category][value=' + x + ']:first').parents('.filters-checkbox').attr("aria-checked", false);
        $('#filterPanel input[type=checkbox][name=Category][value=' + x + ']').trigger('change');
    }
}



/*******************************
*   Home View - JavaScript     *
********************************/

// Variables
var listItemsLoaded = 0;
var additonalListItemsLoaded = 0;
var buttonLoadingText = "Loading...";
var defaultBtnText = "Load More Content";
var loadingInProgress = false;

var spinnerColorDefault = '#999999';

/** Bind Dot Dot Dot */
function bindDotDotDot(currentItem) {
    setTimeout(function () {
        //DotDotDot
        if ($('.item-content-inner-detail', currentItem).length) {
            $('.item-content-inner-detail', currentItem).dotdotdot({
                wrap: 'word',
                height: 90
            });
        }
        //
        if ($('.hotdeal-detail-message', currentItem).length) {
            $('.hotdeal-detail-message', currentItem).dotdotdot({
                ellipsis: " ... »",
                wrap: 'word',
                height: 60
            });
        }
        if ($('.hotdeal-detail-header', currentItem).length) {
            $('.hotdeal-detail-header', currentItem).dotdotdot({
                ellipsis: " ... ",
                wrap: 'word',
                height: 22
            });
        }
        
        //
        if ($('.list-item-chain-descr', currentItem).length) {
            $('.list-item-chain-descr', currentItem).dotdotdot({
                wrap: 'word',
                watch: true
            });
        }
    }, 0);
}
//-->

/** Add Context Loading Spinner */
function addContextLoadingSpinner(obj, color, size) {

    var colorLocal = color != null ? color : '#ffffff';
    var sizeLocal = size != null ? size : 5;

    if ($(obj).find('canvas').length === 0) {

        Spinners.create($(obj), {
            radius: 2,
            height: sizeLocal,
            width: 2,
            dashes: 8,
            opacity: 1,
            padding: 0,
            rotation: 700,
            color: colorLocal
        }).play();

        $(obj).find('i').css('visibility', 'hidden');
    }
}

/** Destroy Context Loading Spinner */
function destroyContextLoadingSpinner(obj) {

    Spinners.remove(obj);
    $(obj).find('i').css('visibility', 'visible');
}
//-->
var invisibleMapinfo = 0;
var MapView = {
    map:null,
    clusterLayer: null,
    infobox: null,
    MapPanel: null,
    infoboxView: false,
    doBestFit: true,
    minZoomLevel: null,
    isHomeView:false,
    isMapLoadFirst: true,
    zoomChangeNoLoad: false,
    currentZoomLevel: null,
    isGroupedLock:false,
    isLoadMapData: false,
    filterlistmin: 0, filterlistmax: 0,
    filterlist: [0],
    filterpos: 0,
    MapListingTemplate: null,

    List_Count: $('#hidden_total_map_count'),
    Hotdeal_Count: $('#hidden_map_hotdeal_count'),
    New_Count: $('#hidden_map_new_count'),
    Green_Count: $('#hidden_map_green_count'), 
    Price1_Count: $('#hidden_map_price1_count'),
    Price2_Count: $('#hidden_map_price2_count'),
    Price3_Count: $('#hidden_map_price3_count'),
    Price4_Count: $('#hidden_map_price4_count'),
    Breakfast_Count: $('#hidden_map_breakfast_count'),
    Brunch_Count: $('#hidden_map_brunch_count'),
    Lunch_Count: $('#hidden_map_lunch_count'),
    Dinner_Count: $('#hidden_map_dinner_count'),

    Init: function (mainContent, isHomeView) {

        MapView.MapPanel = $('#' + mainContent);
        
        if (MapView.MapPanel.length) {
            MapView.isHomeView = isHomeView;

            var source = $("#MapListing").html();
            MapView.MapListingTemplate = Handlebars.compile(source);

            MapView.map = new Microsoft.Maps.Map(document.getElementById(mainContent), {
                credentials: "AokAu5Qpyrj5Nu0GjCMXIuvl1yKT2lzipXXATxtsko5jGVcRUSDL4BhX-h9sGKhi", //Enterprise Key, Account 1212471
                mapTypeId: Microsoft.Maps.MapTypeId.road,
                showDashboard: true,
                disableKeyboardInput: true,
                disableStreetside: true,
                showMapTypeSelector: false,
                showLocateMeButton: false
            });

            // Register and load the Custom Infobox Module
            Microsoft.Maps.registerModule("CustomInfoboxModule", "/Scripts/plugins/bing/V7CustomInfobox.min.js");

            //

            Microsoft.Maps.loadModule("CustomInfoboxModule", {
                callback: function () {
                    //Create CustomInfobox
                    MapView.infobox = new CustomInfobox(MapView.map, {
                        orientation: 1,
                        color: '#ffffff',
                        arrowWidth: 20, offset: { x: 0, y: 5 },
                        borderColor: 'transparent'
                    });
                    
                }
            });

            //MapView.infobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude), { visible: false, showCloseButton: false, showPointer: false, offset: new Microsoft.Maps.Point(20, -8) });
            //MapView.infobox.setMap(MapView.map);
            
            Microsoft.Maps.loadModule('Microsoft.Maps.Clustering', function () {
                MapView.clusterLayer = new Microsoft.Maps.ClusterLayer(new Array(0), { gridSize: 50, clusteredPinCallback: customizeClusteredPin });
                MapView.map.layers.insert(MapView.clusterLayer);
            });

            
            MapView.SetDefaultMapAction();

            MapView.map.setOptions({
                maxZoom: 19,
                minZoom: 6
            });

            MapView.InitView();
            $("input[type=radio]:not(:checked)").parent().removeClass("section-filters-toggle-option-selected");
            $("input[type=radio]:checked").parent().addClass("section-filters-toggle-option-selected");

            //add Zoom In / Zoom Out buttons to tabindex, add event listeners to support spacebar to act as click
            setTimeout(function () {
                $('.NavBar_Button').attr('tabindex', 501);

                document.getElementById("ZoomInButton").addEventListener("keydown", function (event) {
                    if (event.keyCode === 32 || event.keyCode === 13) {
                        event.preventDefault();
                        document.getElementById('ZoomInButton').click()
                    }
                });

                document.getElementById("ZoomOutButton").addEventListener("keydown", function (event) {
                    if (event.keyCode === 32 || event.keyCode === 13) {
                        event.preventDefault();
                        document.getElementById('ZoomOutButton').click()
                    }
                });

            }, 200);

        }
        
        $('#searchbox_form').on("submit",function(e)
        {
            $("#mapContainer #loading-container").show();
            SearchView.searchForm.find("input[name=SearchText]").val($("#searchboxinput").val())
            SearchView.searchForm.submit();
        });

        $('#searchbox-searchbutton').on("click", function () { $('#searchbox_form').submit(); })

        $("#mapContainer").on("click", ".section-filters-overlay",function()
        {
            $(".section_filters_container").removeClass("section-filters-expanded");

        })

        $("#mapContainer").on("click", ".map-pane-toggle-button", function ()
        {
            $("#MapPanel").toggleClass("map-pane-collapsed");

            if ($("#MapPanel").hasClass("map-pane-collapsed")) {
                $(".map-pane-toggle-button").attr("aria-expanded", false);
                $(".map-pane-toggle-button").attr("aria-label", "expand side panel");
            }
            else {
                $(".map-pane-toggle-button").attr("aria-expanded", true);
                $(".map-pane-toggle-button").attr("aria-label", "collapse side panel");
            }
        });

        MapView._recalcFilterBar();

        $("#mapContainer").on("click", ".back_container a", function () {
            $("#MapPanel").removeClass("map-pane-detail");
        });

        $(".section-filters-options").on("change", 'input[type=checkbox]', function (e)
        {
            var uncheck = false;
            var a = [];
            if (e.currentTarget.value == "0") {
                uncheck = true;
            }

            $('.section-filters-options input[name="Category"]:checked').each(function () {
                if (this.value == 0) {

                }
                else {
                    a.push(this.value);
                }
            });

            if (a.length == 0) {
                uncheck = true;
            }

            if (uncheck) {
                $('input[type=checkbox][name="' + e.currentTarget.name + '"]').prop("checked", false);
                CheckboxButtonSelectedValueSet(e.currentTarget.name, ["0"]);
            } else {
                $('input[type=checkbox][name="' + e.currentTarget.name + '"][value=0]').prop("checked", false);
                CheckboxButtonSelectedValueSet(e.currentTarget.name, a.unique());
            }

            FilterBar.submitFilter();
        });

        $(".section-filters-options").on("change", 'input[type=radio]', function (e) {
            if ($(e.currentTarget).parent().siblings(".hidden-cat-latlon").length > 0) {
                RadionButtonSelectedValueSet('Category', $(e.target).val());
                $('#location-container').addClass("disabled");
                LocationView.UpdateApplied($(e.currentTarget).parent().text());
                $('.section-filters-filter.category .section-filters-filter-selection').html($(e.currentTarget).parent().text());
                var latlon = $(e.currentTarget).parent().siblings(".hidden-cat-latlon").val().split(',');
                queryModel.Category = $(e.currentTarget).val();
                queryModel.HiddenLocation = $(e.currentTarget).parent().text();
                queryModel.HiddenLatitude = latlon[0];
                queryModel.HiddenLongitude = latlon[1];


                MapView.map.setView({
                    center: new Microsoft.Maps.Location(queryModel.HiddenLatitude, queryModel.HiddenLongitude)
                })
            }
        });
        $(".section-filters-options").on("updatetext", 'input[type=radio]', function (e) {
            
            $('#location-container').addClass("disabled");
            LocationView.UpdateApplied($(e.currentTarget).parent().text());
            $('.section-filters-filter.category .section-filters-filter-selection').html($(e.currentTarget).parent().text());

        });

        $(".section-filters-toggle-options").on("change", function (e) {
 
            if ($(e.target).parent().children("input").prop("name") == "Filter") {
                RadionButtonSelectedValueSet('Filter', $(e.target).parent().children("input").val());
                RadionButtonSelectedValueSet('Meal', '');
                RadionButtonSelectedValueSet('Price', '');
            }
            if ($(e.target).parent().children("input").prop("name") == "Meal") {
                RadionButtonSelectedValueSet('Meal', $(e.target).parent().children("input").val());
                RadionButtonSelectedValueSet('Filter', '');
                RadionButtonSelectedValueSet('Price', '');
            }
            if ($(e.target).parent().children("input").prop("name") == "Price") {
                RadionButtonSelectedValueSet('Price', $(e.target).parent().children("input").val());
                RadionButtonSelectedValueSet('Filter', '');
                RadionButtonSelectedValueSet('Meal', '');
            }

            //hide the filter panel onselect of new filter
            $('.section-filters-filter').removeClass("selected");
            $('.section-filters-options').hide();
            $('.section_filters_container').removeClass("section-filters-expanded");
            $('#MapPanel').removeClass("section-filters-expanded");
            FilterBar.submitFilter();  
        });

        $(".section-filters-toggle-options").on("update", function (e) {
            $(e.currentTarget).children().removeClass("section-filters-toggle-option-selected");
            $(e.target).parent().addClass("section-filters-toggle-option-selected");
        });

        $("#mapContainer").on("click", ".section-filters-next-button", function () {

            MapView.filterpos++;

            var move = parseInt($(".section-filters-list").css("left"), 10) - MapView.filterlist[MapView.filterpos];

            if (move < MapView.filterlistmin) {
                $(".section-filters-previous-button-container").show();
            }
            else {
                $(".section-filters-previous-button-container").hide();
            }

            if (move > 0) {
                move = 0;
            }

            if (move <= -MapView.filterlistmax + 350) {
                $(".section-filters-next-button-container").hide();
            }
            else {
                $(".section-filters-next-button-container").show();
            }

            $(".section-filters-list").css("left", move);
        });

        $("#mapContainer").on("click", ".section-filters-previous-button", function () {
            
            var move = parseInt($(".section-filters-list").css("left"), 10) + MapView.filterlist[MapView.filterpos];
            MapView.filterpos--;

            if (MapView.filterpos == 0) { move = 0 }
            if (move < MapView.filterlistmin) {
                $(".section-filters-previous-button-container").show();
            }
            else {
                $(".section-filters-previous-button-container").hide();
            }

            if (move > 0) {
                move = 0;
            }

            if (move <= -MapView.filterlistmax + 350) {
                $(".section-filters-next-button-container").hide();
            }
            else {
                $(".section-filters-next-button-container").show();
            }

            $(".section-filters-list").css("left", move);
        });

        $("#mapContainer").on("click", ".section-filters-filter", function () {
            $('.section_filters_container').addClass("section-filters-expanded");
            $('#MapPanel').addClass("section-filters-expanded");
        });

        $("#mapContainer").on("click", ".section-filters-filter.category", function () {
            $('.section-filters-filter').removeClass("selected");
            $('.section-filters-filter.category').addClass("selected");
            $('.section-filters-options').hide();
            $('.section-filters-options.category').show();
        });

        $("#mapContainer").on("click", ".section-filters-filter.Meal", function () {
            $('.section-filters-filter').removeClass("selected");
            $('.section-filters-filter.Meal').addClass("selected");
            $('.section-filters-options').hide();
            $('.section-filters-options.Meal').show();
        });

        $("#mapContainer").on("click", ".section-filters-filter.Filter", function () {
            $('.section-filters-filter').removeClass("selected");
            $('.section-filters-filter.Filter').addClass("selected");
            $('.section-filters-options').hide();
            $('.section-filters-options.Filter').show();
        });

        $("#mapContainer").on("click", ".section-filters-filter.Price", function () {
            $('.section-filters-filter').removeClass("selected");
            $('.section-filters-filter.Price').addClass("selected");
            $('.section-filters-options').hide();
            $('.section-filters-options.Price').show();
        });

        $("#mapContainer").on("click", ".section-filters-filter.selected", function () {
            $('.section-filters-filter').removeClass("selected");
            $('.section-filters-options').hide();
            $('.section_filters_container').removeClass("section-filters-expanded");
            $('#MapPanel').removeClass("section-filters-expanded");
        });

        $("#mapContainer").on("click", ".section-filters-header-save-button", function () {
            $('.section-filters-filter').removeClass("selected");
            $('.section-filters-options').hide();
            $('.section_filters_container').removeClass("section-filters-expanded");
            $('#MapPanel').removeClass("section-filters-expanded");
        });

        $("#mapContainer").on("click", ".gsst_a", function () { FilterBar.clearFilter(); });
        $("#mapContainer").on("click", ".section-filters-header-clear-button", function () { FilterBar.clearFilter(); });

        MapView.Hotdeal_Count.on('change', function (e) {
            if (MapView.Hotdeal_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline)) {
                $('input[name=Filter][value=Hot]').prop('disabled', true);
                $('input[name=Filter][value=Hot]').parent().addClass('disabled');
            }
            else {
                $('input[name=Filter][value=Hot]').prop('disabled', false);
                $('input[name=Filter][value=Hot]').parent().removeClass('disabled');
            }
        });

        MapView.New_Count.on('change', function (e) {
            if (MapView.New_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline)) {
                $('input[name=Filter][value=New]').prop('disabled', true);
                $('input[name=Filter][value=New]').parent().addClass('disabled');
            }
            else {
                $('input[name=Filter][value=New]').prop('disabled', false);
                $('input[name=Filter][value=New]').parent().removeClass('disabled');
            }
        });

        MapView.Green_Count.on('change', function (e) {
            if (MapView.Green_Count.val() == 0 && !(queryModel.IsNew || queryModel.IsHot || queryModel.IsGreen || queryModel.IsOnline)) {
                $('input[name=Filter][value=Green]').prop('disabled', true);
                $('input[name=Filter][value=Green]').parent().addClass('disabled');
            }
            else {
                $('input[name=Filter][value=Green]').prop('disabled', false);
                $('input[name=Filter][value=Green]').parent().removeClass('disabled');
            }
        });

        MapView.Price1_Count.on('change', function (e) {
            if (MapView.Price1_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                $('input[name=Price][value=1]').prop('disabled', true);
                $('input[name=Price][value=1]').parent().addClass('disabled');
            }
            else {
                $('input[name=Price][value=1]').prop('disabled', false);
                $('input[name=Price][value=1]').parent().removeClass('disabled');
            }
        });

        MapView.Price2_Count.on('change', function (e) {
            if (MapView.Price2_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                $('input[name=Price][value=2]').prop('disabled', true);
                $('input[name=Price][value=2]').parent().addClass('disabled');
            }
            else {
                $('input[name=Price][value=2]').prop('disabled', false);
                $('input[name=Price][value=2]').parent().removeClass('disabled');
            }
        });

        MapView.Price3_Count.on('change', function (e) {
            if (MapView.Price3_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                $('input[name=Price][value=3]').prop('disabled', true);
                $('input[name=Price][value=3]').parent().addClass('disabled');
            }
            else {
                $('input[name=Price][value=3]').prop('disabled', false);
                $('input[name=Price][value=3]').parent().removeClass('disabled');
            }
        });

        MapView.Price4_Count.on('change', function (e) {
            if (MapView.Price4_Count.val() == 0 && !(queryModel.IsPrice1 || queryModel.IsPrice2 || queryModel.IsPrice3 || queryModel.IsPrice4)) {
                $('input[name=Price][value=4]').prop('disabled', true);
                $('input[name=Price][value=4]').parent().addClass('disabled');
            }
            else {
                $('input[name=Price][value=4]').prop('disabled', false);
                $('input[name=Price][value=4]').parent().removeClass('disabled');
            }
        });

        MapView.Breakfast_Count.on('change', function (e) {
            if (MapView.Breakfast_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                $('input[name=Meal][value=Breakfast]').prop('disabled', true);
                $('input[name=Meal][value=Breakfast]').parent().addClass('disabled');
            }
            else {
                $('input[name=Meal][value=Breakfast]').prop('disabled', false);
                $('input[name=Meal][value=Breakfast]').parent().removeClass('disabled');
            }
        });

        MapView.Brunch_Count.on('change', function (e) {
            if (MapView.Brunch_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                $('input[name=Meal][value=Brunch]').prop('disabled', true);
                $('input[name=Meal][value=Brunch]').parent().addClass('disabled');
            }
            else {
                $('input[name=Meal][value=Brunch]').prop('disabled', false);
                $('input[name=Meal][value=Brunch]').parent().removeClass('disabled');
            }
        });

        MapView.Lunch_Count.on('change', function (e) {
            if (MapView.Lunch_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                $('input[name=Meal][value=Lunch]').prop('disabled', true);
                $('input[name=Meal][value=Lunch]').parent().addClass('disabled');
            }
            else {
                $('input[name=Meal][value=Lunch]').prop('disabled', false);
                $('input[name=Meal][value=Lunch]').parent().removeClass('disabled');
            }
        });

        MapView.Dinner_Count.on('change', function (e) {
            if (MapView.Dinner_Count.val() == 0 && !(queryModel.IsBreakfast || queryModel.IsBrunch || queryModel.IsLunch || queryModel.IsDinner)) {
                $('input[name=Meal][value=Dinner]').prop('disabled', true);
                $('input[name=Meal][value=Dinner]').parent().addClass('disabled');
            }
            else {
                $('input[name=Meal][value=Dinner]').prop('disabled', false);
                $('input[name=Meal][value=Dinner]').parent().removeClass('disabled');
            }
        });
    },

    InitView: function () {
        MapView.isMapLoadFirst = true;
        var locations = new Array(0);

        if (queryModel.HiddenLocation != null && queryModel.HiddenLocation.length > 0) {
            MapView.map.setView({
                center: new Microsoft.Maps.Location(queryModel.HiddenLatitude, queryModel.HiddenLongitude),
                zoom: 9
            })
        }
        else {
            locations.push(new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude));

            // add 2 locations that push the bounding box in by a % of its size
            var pctBuffer = 0.35;
            var latBuffer = (queryModel.MaxLatitude - queryModel.MinLatitude) * pctBuffer;
            var lonBuffer = (queryModel.MaxLongitude - queryModel.MinLongitude) * pctBuffer;

            // add the two fakes pins to our location array
            locations.push(new Microsoft.Maps.Location(queryModel.MinLatitude + latBuffer, queryModel.MaxLongitude - lonBuffer));
            locations.push(new Microsoft.Maps.Location(queryModel.MaxLatitude - latBuffer, queryModel.MinLongitude + lonBuffer));

            var rect = Microsoft.Maps.LocationRect.fromLocations(locations);

            MapView.map.setView({
                bounds: rect
            })
        }
    },

    Clear: function () {
        if (MapView.map !== null) {
            MapView.map.entities.clear();
        }
        if (MapView.clusterLayer !== null) {
            MapView.clusterLayer.clear();
        }
        $('#list_items_container').html("");
        queryModel.Count = 0;
        queryModel.AdditionalOfferPageIndex = 1;
        FilterBar.Additional_Count.val(15);
        ListView.haveLoadedAdditionalOffers = false;
    },

    ResetFlags: function () {
        queryModel.IsMapNeedData = true;
        queryModel.IsFilterApply = true;
    },

    _closeExpand: function () {
        //map-pane-visible
        $(".section_filters_container").removeClass("section-filters-expanded");
        $(".section-filters-expanded-filter").children().hide();
    },

    _recalcFilterBar:function(){
        MapView.filterlist = [0];
        MapView.filterpos = 0;
        MapView.filterlistmax = 0;

        $.each($(".section-filters-list").children(), function () {
            var current = this;
            if ($(current).is(":visible")) {
                var width = parseInt($(current).css("width"), 10);
                MapView.filterlist.push(width);
                MapView.filterlistmax += width
            }
        });
        
        if (MapView.filterlistmax < 350) {
            $(".section-filters-next-button-container").hide();
            $(".section-filters-previous-button-container").hide();
        }
    },
    updateLocation: function () {
        queryModel.NearByUniqueVendorID = -1;
        MapView.map.setView({
            center: new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude)
        })
    },
    loadBingMapData: function () {
        
        
        var url = "/Main/GetMapPin";
        if (MapView.isHomeView)
            url = "/Main/GetMapPinHomeView";
        
        $.ajax({
            url: url,
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            dataType: "json",
            async: true,
            traditional: true
        })
            // Success!
            .done(function (result) {
                if (result.Authorized != null && result.Authorized == false) {
                    redirectToLogin();
                }
                $("#mapContainer #loading-container").show();
                MapView.List_Count.val(result.MapPinCount).change();
                MapView.Hotdeal_Count.val(result.HotdealCount).change();
                MapView.New_Count.val(result.NewCount).change();
                MapView.Green_Count.val(result.GreenCount).change();
                MapView.Price1_Count.val(result.Price1Count).change();
                MapView.Price2_Count.val(result.Price2Count).change();
                MapView.Price3_Count.val(result.Price3Count).change();
                MapView.Price4_Count.val(result.Price4Count).change();
                MapView.Breakfast_Count.val(result.BreakfastCount).change();
                MapView.Brunch_Count.val(result.BrunchCount).change();
                MapView.Lunch_Count.val(result.LunchCount).change();
                MapView.Dinner_Count.val(result.DinnerCount).change();
                queryModel.IsMapNeedData = false;
                queryModel.IsFilterApply = false;
        
                MapView.addBingMapData(result);

                MapView.isMapLoadFirst = false;

                //FilterBar.Summary_Text.val(result.SummaryText).change();
                //FilterBar.Location_Applied.val(result.AppliedLocationText).change();
                //LocationView.UpdateApplied(result.AppliedLocationText);
                
                if (queryModel.IsFilterUpdate) {
                    $("#NavigationHeader").html(result.NavigationHeader.replace("\\", ""));
                    $(".section-filters-filter.category .section-filters-filter-title").html(result.NavigationHeader.replace("\\", ""));
                    $(".section-filters-filter.category .section-filters-filter-selection").html(result.NavigationSubHeader);
                    if (result.NavigationList.length == 0) {
                        $('#L1FilterTopCategory').hide();
                        $(".section-filters-filter.category").hide();
                    }
                    else {
                        $('#L1FilterTopCategory').show();
                        $(".section-filters-filter.category").show();
                    }

                    var data = $.map(result.NavigationList, function (item, a) {
                        return "<li><label " + ((item.CategoryID == 0) ? "class='clear-input'" : "") + "><input type='" + ((item.IsPopularDestination) ? "radio" : "checkbox") + "' name='Category' id='Category' value='" + item.CategoryID + "'" + ((item.IsSelected) ? "checked" : "") + "/> <span>" + item.CategoryName + "</span></label>" +
                                ((item.IsPopularDestination) ? "<input type='hidden' class='hidden-cat-latlon' value='" + item.HiddenLatLon + "'>" : "") +
                                "</li>";
                    });
                    var mapdata = $.map(result.NavigationList, function (item, a) {
                        return "<div class='section-filters-checkbox'><label " + ((item.CategoryID == 0) ? "class='clear-input'" : "") + "><input type='" + ((item.IsPopularDestination) ? "radio" : "checkbox") + "' name='Category' value='" + item.CategoryID + "'" + ((item.IsSelected) ? "checked" : "") + "/> <span>" + item.CategoryName + "</span></label>" +
                               ((item.IsPopularDestination) ? "<input type='hidden' class='hidden-cat-latlon' value='" + item.HiddenLatLon + "'>" : "") + "</div>";
                    });

                    $("#CategoryList").html(data.join(""));
                    $(".section-filters-options.category div").html(mapdata.join(""));
                    $('.section-filters-filter.category input[type=checkbox][name="Category"]:first').trigger('updatecheck');

                    queryModel.IsFilterUpdate = false;
                }

                LocationView.Clear();
                SearchView.Clear();
            })
    },

    addBingMapData: function (data) {
        
        MapView.Clear();

        var locations = new Array(0);
        var location = new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude);
        locations.push(location);
        var pin = new Microsoft.Maps.Pushpin(location);
        //MapView.map.entities.push(pin);

        if (data.MapPins.length > 0) {
            $.each(data.MapPins, function () {
                var currentPin = this;
                var pin = MapView.AddBingMapPin(currentPin.Latitude, currentPin.Longitude, currentPin.MapPinImagePath, currentPin, data.MapPins.length <= 100);
                
                locations.push(new Microsoft.Maps.Location(currentPin.Latitude, currentPin.Longitude));
            });

            if (MapView.clusterLayer !== null) {
                MapView.clusterLayer.setPushpins(MapView.map.entities._primitives);
            }

            if (queryModel.NearByUniqueVendorID > 0 && MapView.doBestFit) {
                locations.push(new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude));

                var rect = Microsoft.Maps.LocationRect.fromLocations(locations);
                MapView.zoomChangeNoLoad = true;
                MapView.map.setView({
                    bounds: rect,
                    padding: 150
                });
                
                MapView.doBestFit = false;
            }

            MapView.DisplayGrouping();

            $("#mapContainer #loading-container").hide();//Loading done;
            
            $('.MapPushpinBase').attr('tabindex', -1);
        }
        else {
            $("#mapContainer #loading-container").hide();//Loading done;
        }
    },

    AddBingMapPin: function (latitude, longitude, imagePath, currentPin, AddOffer) {

        var loc = new Microsoft.Maps.Location(latitude, longitude)
        var pin = new Microsoft.Maps.Pushpin(loc, { icon: imagePath, anchor: new Microsoft.Maps.Point(12, 19) });
        pin.metadata = currentPin;
        
        Microsoft.Maps.Events.addHandler(pin, 'mouseover', MapView.displayBingMapInfobox);
        Microsoft.Maps.Events.addHandler(pin, 'mouseout', MapView.hideBingMapInfobox);
            //args.target.setOptions({ icon: pin.metadata.MapPinFocusImagePath, anchor: new Microsoft.Maps.Point(20, 29) });

            //var pinLoc = pin.getLocation();
            //var mapLoc = MapView.map.getCenter();

            //var offsetX = 0;
            //var offsetY = 0;

            //if (pinLoc.latitude > mapLoc.latitude) {
            //    offsetY = -133;
            //}
            //else {
            //    offsetY = -8;
            //}

            //if (pinLoc.longitude > mapLoc.longitude) {
            //    offsetX = -280; //-280; //this resolves a suspected Bing Maps v8 bug where the pin click event was blocked by infobox in lower-right quadrant of map
            //}
            //else {
            //    offsetX = 20;
            //}

            //MapView.infobox.setOptions({
            //    htmlContent: html.replace('map-list-item', 'map-infobox-item'),
            //    location: loc,
            //    visible: true,
            //    offset: new Microsoft.Maps.Point(offsetX, offsetY)
            //});
        //    MapView.infobox.currentPin = pin;
        //});

        //Microsoft.Maps.Events.addHandler(pin, 'mouseout', function (args) {
        //    MapView.infobox.setOptions({ visible: false });
        //    args.target.setOptions({ icon: pin.metadata.MapPinImagePath, anchor: new Microsoft.Maps.Point(12, 19) });
        //});

        Microsoft.Maps.Events.addHandler(pin, 'click', function () { MapView.populateMapSidePanel(pin.metadata); });
        MapView.map.entities.push(pin);

        if (AddOffer)
        {
            var html = MapView.MapListingTemplate(pin.metadata);
            MapView.AddBingMapOffer(currentPin, html, pin)
        }

        return pin;
    },

    displayBingMapInfobox: function (e) {

        if (e.from != null && e.from === 'list')
        {
            if (e.target.image.currentSrc.includes("dine-circle.svg"))
            { e.target.setOptions({ icon: "https://cdn.passportcorporate.com/webelements/circle-icons-2018pallette/dine-circle-focus.svg" });}
            if (e.target.image.currentSrc.includes("shop-circle.svg"))
            { e.target.setOptions({ icon: "https://cdn.passportcorporate.com/webelements/circle-icons-2018pallette/shop-circle-focus.svg" });}
            if (e.target.image.currentSrc.includes("travel-circle.svg"))
            { e.target.setOptions({ icon: "https://cdn.passportcorporate.com/webelements/circle-icons-2018pallette/travel-circle-focus.svg" });}
        }

        if (e.targetType == 'pushpin') {
   
            var html = MapView.MapListingTemplate(e.target.metadata).replace('map-list-item', 'map-infobox-item');
            MapView.renderBingMapInfobox(e.target.getLocation(), e.target.metadata.Title, html, true, e.target);
        }
    },

    /** Render Bing Map Infobox */
    renderBingMapInfobox: function (latlong, title, description, autoHidden, currentPin) {

        if (MapView.infobox != null) {
            MapView.infobox.currentPin = currentPin;
            $('#mapContainer_infobox').unbind('click');
            $('#mapContainer_infobox').bind('click', function () {
                Microsoft.Maps.Events.invoke(MapView.infobox.currentPin, 'click', { target: MapView.infobox.currentPin });
            });

            invisibleMapinfo = 0;
            $('#mapContainer_infobox').unbind('mouseenter');
            $('#mapContainer_infobox').bind('mouseenter', function () {
                invisibleMapinfo = 0;
            });

            $('#mapContainer_infobox').unbind('mouseleave');
            if (autoHidden) {
                $('#mapContainer_infobox').bind('mouseleave', MapView.hideBingMapInfobox);
            }
            MapView.infobox.setOptions({ visible: true });
            var classPortalTheme = 'portal-theme';
            var portalThemeClass = $('.page-content-outer').hasClass(classPortalTheme) ? classPortalTheme : '';
            var html = ['<div class="map-balloon-container ' + portalThemeClass + '">'];
            html.push(description);
            html.push('</div>');
            MapView.infobox.show(latlong, html.join(''));
            currentPinGeolocation = latlong;

            //reize div for header
            $('.list-item-header-title', $('#mapContent_infobox')).each(function () {

                var obj = $(this);

                // Calculate DotDotDot container size
                var parentWidth = $(obj).parent().parent().outerWidth();
                var expandCollapseWidth = 27;
                var averageIconWidth = 28;
                var actionItemsWidth = ($(obj).parent().find('.list-item-header-actions a').length * averageIconWidth) + expandCollapseWidth;
                //
                if (parentWidth > 0) {
                    $(obj).parent().parent().find('.list-item-header-title').css('width', (parentWidth - actionItemsWidth - expandCollapseWidth) + 'px');
                }
            });
            $('#mapContent_infobox').css('z-index', 1005);
            Tipped.create($('#mapContent_infobox').find('.span-actions i, .a-actions i'));
        }
},
//-->
    /** Auto hide Map Infobox */
    hideBingMapInfobox: function(e) {

        if (e.from != null && e.from === 'list') {
            if (e.target.image.currentSrc.includes("dine-circle-focus.svg"))
            { e.target.setOptions({ icon: "https://cdn.passportcorporate.com/webelements/circle-icons-2018pallette/dine-circle.svg" }); }
            if (e.target.image.currentSrc.includes("shop-circle-focus.svg"))
            { e.target.setOptions({ icon: "https://cdn.passportcorporate.com/webelements/circle-icons-2018pallette/shop-circle.svg" }); }
            if (e.target.image.currentSrc.includes("travel-circle-focus.svg"))
            { e.target.setOptions({ icon: "https://cdn.passportcorporate.com/webelements/circle-icons-2018pallette/travel-circle.svg" }); }
        }


        var delayHiddenInfoBox = setInterval(function () {
            if ($('#mapContainer_infobox:hover').length > 0) {
                invisibleMapinfo = 0;
            }
            if (invisibleMapinfo >= 2) {
                clearInterval(delayHiddenInfoBox);
                MapView.infobox.hide();
            }
            else {
                invisibleMapinfo++;
            }
        }, 1000);
},
//-->
    DisplayGrouping: function () {

        if (MapView.map.entities._primitives.length <= 100 && MapView.clusterLayer !== null)//Disable Cluster at zoom level 9
        {
            $('.map-pane').addClass('map-pane-visible');
            $('.map-pane-toggle-button').attr('tabindex', "501");

            //toggle aria-live reader announcement
            var readerText = $('.map-content-announcements').html();
            if (readerText != 'map side panel displayed; press tab to explore content') {
                $('.map-content-announcements').html('map side panel displayed; press tab to explore content');
            }

            MapView.clusterLayer.setVisible(false);
            MapView.map.entities.setVisible(true);
        }
        else if (MapView.clusterLayer !== null)
        {
            $('.map-pane').removeClass('map-pane-visible');
            $('.map-pane-toggle-button').attr('tabindex', "-1");

            //toggle aria-live reader announcement
            var readerText2 = $('.map-content-announcements').html();
            if (readerText2 != 'map side panel not displayed; zoom in to display side panel content') {
                $('.map-content-announcements').html('map side panel not displayed; zoom in to display side panel content');
            }

            MapView.clusterLayer.setVisible(true);
            MapView.map.entities.setVisible(false);
        }
    },

    AddBingMapOffer: function(MapPin, html, pin)
    {

        $("#mapContainer #list_items_container").append(html);
        keyboardHelper.updateAnchorItemsIndex($('.map-list-item'), 501);

        ($(".map-list-item").last().find(".vendor-name")).dotdotdot({
            wrap: 'letter',
            watch: false,
            height: 16
        });

        $("#mapContainer #list_items_container .map-list-item").last().on("click", function (e) {
            //MapView.DisplayBingMapInfobox(MapPin);
            MapView.populateMapSidePanel(MapPin);
        });
        $("#mapContainer #list_items_container .map-list-item").last().on("keydown", function (e) {
            if (e.keyCode === 32 || e.keyCode === 13) {
                e.preventDefault();
                MapView.populateMapSidePanel(MapPin);
                $('#MapPanel').focus();
            }
        });
        $("#mapContainer #list_items_container .map-list-item").last().on("mouseover", function (e) {
            Microsoft.Maps.Events.invoke(pin, 'mouseover', { target: pin, from: 'list' });
        });
        $("#mapContainer #list_items_container .map-list-item").last().on("mouseout", function (e) {
            Microsoft.Maps.Events.invoke(pin, 'mouseout', { target: pin, from: 'list' });
        });

    },

    //DisplayBingMapInfobox: function (currentPin)
    //{
    //    var source = $("#MapListingContent").html();
    //    var template = Handlebars.compile(source);
    //    var html = template(currentPin);

    //    $("#MapPanel").removeClass("map-pane-collapsed");
    //    $("#MapPanel").addClass("map-pane-detail");
    //    $("#MapPanel").removeClass("dine-pane");
    //    $("#MapPanel").removeClass("shop-pane");
    //    $("#MapPanel").removeClass("travel-pane");
    //    $("#MapPanel").addClass(currentPin.VendorTypeCSS + "-pane");

    //    $("#mapContainer #vendor_info_container").html(html);
    //    keyboardHelper.updateAnchorItemsIndex($('#vendor_info_container').find('a'), 501);
    //},

    populateMapSidePanel: function (currentPin)
    {
        $.ajax({
            data: AddAntiForgeryToken({ name: currentPin.Description, mapPinID: currentPin.MapPinID, vendorID: currentPin.VendorID  }),
            dataType: 'html',
            url: '/Main/GetMappinInfo',
            type: "POST"
        }).done(function (data) {
            $("#MapPanel").removeClass("map-pane-collapsed");
            $("#MapPanel").addClass("map-pane-detail");
            $("#MapPanel").removeClass("dine-pane");
            $("#MapPanel").removeClass("shop-pane");
            $("#MapPanel").removeClass("travel-pane");
            $("#MapPanel").addClass(currentPin.VendorTypeCSS + "-pane");

            $("#mapContainer #vendor_info_container").html(data);
            keyboardHelper.updateAnchorItemsIndex($('#vendor_info_container').find('a'), 501);

            var owl1 = $(".owl-carousel", $("#mapContainer #vendor_info_container"));
            owl1.owlCarousel({
                items: 1,
                dots: false,
                nav: true,
                //autoHeight: false,
                //slideBy: 1,
                navText: ["<i class='fa fa-lg fa-chevron-left' aria-hidden='true'></i>", "<i class='fa fa-lg fa-chevron-right' aria-hidden='true'></i>"],
            });
            $('.owl-item.cloned').find('img').attr('aria-hidden', true);

        }).fail(function (jqXHR, textStatus, errorThrown) {
            // If fail
            console.log(textStatus + ': ' + errorThrown);
        });


        var delayDisplayInfo = setInterval(function () {
            //if (!MapView.isLoadMapData) {
                clearInterval(delayDisplayInfo);
                MapView.isLoadMapData = true;



            //}
        }, 200);
    },
    /** Cache Map Pins */
    cacheMapPins: function () {
        $.ajax({
            url: "/Main/CacheMapPins",
            type: "POST"
        });
    },
    CloseBingMapInfobox:function()
    {
        MapView._closeExpand();
        $(".map-pane").removeClass("dine");
        $(".map-pane").removeClass("shop");
        $(".map-pane").removeClass("travel");

        $('#list_items_container').show();
        $('.back_to_results').hide();
        $('.section_filter').show();
        $('#vendor_info_container').hide();
    },

    SetDefaultMapAction: function () {

        Microsoft.Maps.Events.addThrottledHandler(MapView.map, "viewchangeend", function (e) { 
            if (e.cause != null && e.cause == 0)//View Change
            {
        
                if (queryModel.NearByUniqueVendorID < 0) {
                    queryModel.Latitude = e.target.getCenter().latitude;
                    queryModel.Longitude = e.target.getCenter().longitude;
                    queryModel.MinLatitude = e.target.getBounds().getSouth();
                    queryModel.MinLongitude = e.target.getBounds().getWest();
                    queryModel.MaxLatitude = e.target.getBounds().getNorth();
                    queryModel.MaxLongitude = e.target.getBounds().getEast();
                }
                if (!MapView.zoomChangeNoLoad) {
                    MapView.ResetFlags();
                    MapView.loadBingMapData();
                }

                MapView.zoomChangeNoLoad = false;
            }
        }, 250);

        Microsoft.Maps.Events.addHandler(MapView.map, "viewchangeend", function (e) {

            if (e.cause != null && e.cause == 1 )
            {
                queryModel.MapLocationLatLon = queryModel.Latitude + ',' + queryModel.Longitude;
                queryModel.CurrentLocationMode = enumLocationSearchMode.Map;
                queryModel.Latitude = MapView.map.getCenter().latitude;
                queryModel.Longitude = MapView.map.getCenter().longitude;

                queryModel.MinLatitude = MapView.map.getBounds().getSouth();
                queryModel.MinLongitude = MapView.map.getBounds().getWest();
                queryModel.MaxLatitude = MapView.map.getBounds().getNorth();
                queryModel.MaxLongitude = MapView.map.getBounds().getEast();
                MapView.ResetFlags();
                MapView.loadBingMapData();
            }
            else if ((!MapView.isMapLoadFirst) && !MapView.map.getBounds().contains(new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude)))
            {
                queryModel.IsMapLocation = true;

                queryModel.MapLocationLatLon = queryModel.Latitude + ',' + queryModel.Longitude;
                queryModel.CurrentLocationMode = enumLocationSearchMode.Map;
                queryModel.Latitude = MapView.map.getCenter().latitude;
                queryModel.Longitude = MapView.map.getCenter().longitude;

                queryModel.MinLatitude = MapView.map.getBounds().getSouth();
                queryModel.MinLongitude = MapView.map.getBounds().getWest();
                queryModel.MaxLatitude = MapView.map.getBounds().getNorth();
                queryModel.MaxLongitude = MapView.map.getBounds().getEast();

                MapView.ResetFlags();
                MapView.loadBingMapData();
            }

        });
    }
}


function customizeClusteredPin(cluster) {
    //Add click event to clustered pushpin
    Microsoft.Maps.Events.addHandler(cluster, 'click', function (e) {
        if (e.target.containedPushpins) {
            var locs = [];
            for (var i = 0, len = e.target.containedPushpins.length; i < len; i++) {
                //Get the location of each pushpin.
                locs.push(e.target.containedPushpins[i].getLocation());
            }

            //Create a bounding box for the pushpins.
            var bounds = Microsoft.Maps.LocationRect.fromLocations(locs);

            //Zoom into the bounding box of the cluster. 
            //Add a padding to compensate for the pixel area of the pushpins.
            MapView.map.setView({ bounds: bounds, padding: 100 });
        }
    });

    cluster.setOptions({
        icon: 'https://cdn.passportcorporate.com/webelements/circle-icons-2018pallette/multiple_circle.svg'
    });
}

/** Map Near By Location event */
function goMapNearbyLocations(e, latitude, longitude, vendorName, uniqueName, actionId, uVendorId, CurrentCategoryUrl) {
    FilterBar.applyVendorFilter(latitude, longitude, vendorName, uVendorId);

        $.ajax({
            url: "/Main/Redirect",
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            async: true,
            dataType: "json",
            traditional: true
        })
            // Success!
            .done(function (result) {

                if (result.Authorized != null && result.Authorized == false) {
                    redirectToLogin();
                }
                else {
                    mapClickHandling();
                }
            })
            // Error!
            .fail(function (result) {
                redirectToLogin();
            });


}


//-->
var HomeMapView = {
    map:null,
    clusterLayer: null,
    infobox: null,
    MapPanel: null,

    minZoomLevel: null,

    isMapLoadFirst: true,
    currentZoomLevel: null,
    isGroupedLock:false,
    
    filterlistmin: 0, filterlistmax: 0,
    filterlist: [0],
    filterpos: 0,
    MapListingTemplate: null,

    Init: function (mainContent) {
        HomeMapView.MapPanel = $('#' + mainContent);
        
        if (HomeMapView.MapPanel.length) {

            var source = $("#MapListing").html();
            HomeMapView.MapListingTemplate = Handlebars.compile(source);

            HomeMapView.map = new Microsoft.Maps.Map(document.getElementById(mainContent), {
                credentials: "AokAu5Qpyrj5Nu0GjCMXIuvl1yKT2lzipXXATxtsko5jGVcRUSDL4BhX-h9sGKhi", //Enterprise Key, Account 1212471
                mapTypeId: Microsoft.Maps.MapTypeId.road,
                showDashboard: true,
                disableScrollWheelZoom:true,
                showMapTypeSelector: false,
                showLocateMeButton:false
                
            });

            // Register and load the Custom Infobox Module
            Microsoft.Maps.registerModule("CustomInfoboxModule", "/Scripts/plugins/bing/V7CustomInfobox.min.js");

            Microsoft.Maps.loadModule("CustomInfoboxModule", {
                callback: function () {
                    //Create CustomInfobox
                    HomeMapView.infobox = new CustomInfobox(HomeMapView.map, {
                        orientation: 1,
                        color: '#ffffff',
                        arrowWidth: 20, offset: { x: 0, y: 5 },
                        borderColor: 'transparent'
                    });

                }
            });

            //HomeMapView.infobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude), { visible: false, showCloseButton: false, showPointer: false, offset: new Microsoft.Maps.Point(20, -8) });
            //HomeMapView.infobox.setMap(HomeMapView.map);
        }

        HomeMapView.loadBingMapData();

        //add Zoom In / Zoom Out buttons to tabindex, add event listeners to support spacebar to act as click
        setTimeout(function () {
            $('.NavBar_Button').attr('tabindex', 501);

            document.getElementById("ZoomInButton").addEventListener("keydown", function (event) {
                if (event.keyCode === 32 || event.keyCode === 13) {
                    event.preventDefault();
                    document.getElementById('ZoomInButton').click()
                }
            });

            document.getElementById("ZoomOutButton").addEventListener("keydown", function (event) {
                if (event.keyCode === 32 || event.keyCode === 13) {
                    event.preventDefault();
                    document.getElementById('ZoomOutButton').click()
                }
            });

        }, 200);

    },

    /** Load Bing Map Data */
    loadBingMapData: function () {
        var url = "/Main/GetMapPinHomeView";
        
        $.ajax({
            url: url,
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            dataType: "json",
            async: true,
            traditional: true
        })
            // Success!
            .done(function (result) {
                if (result.Authorized != null && result.Authorized == false) {
                    redirectToLogin();
                }
                $("#mapContainer #loading-container").show();
                queryModel.IsMapNeedData = false;
                queryModel.IsFilterApply = false;
        
                HomeMapView.addBingMapData(result);

                HomeMapView.isMapLoadFirst = false;

                //LocationView.UpdateApplied(result.AppliedLocationText);
                
                LocationView.Clear();
                SearchView.Clear();
            })
    },
    /** Add Bing Map Data */
    addBingMapData: function (data) {
        var i = 0;
        var locations = new Array(0);
        var location = new Microsoft.Maps.Location(queryModel.Latitude, queryModel.Longitude);
        locations.push(location);

        var pin = new Microsoft.Maps.Pushpin(location);
        //HomeMapView.map.entities.push(pin);

        if (data.MapPins.length > 0) {
            
            $.each(data.MapPins, function () {
                var currentPin = this;
                var pin = HomeMapView.AddBingMapPin(currentPin.Latitude, currentPin.Longitude, currentPin.MapPinImagePath, currentPin, data.MapPins.length <= 100);
                
                if (i < 11) {
                    locations.push(new Microsoft.Maps.Location(currentPin.Latitude, currentPin.Longitude));

                    i++;
                }
            });

            var rect = Microsoft.Maps.LocationRect.fromLocations(locations);

            HomeMapView.map.setView({
                bounds: rect
            });

            $("#mapContainer #loading-container").hide();//Loading done;
            $('.MapPushpinBase').attr('tabindex', -1);
        }
        else {
            $("#mapContainer #loading-container").hide();//Loading done;
        }
    },

    /** Add Bing Map Pin */
    AddBingMapPin: function (latitude, longitude, imagePath, currentPin, AddOffer) {

        var loc = new Microsoft.Maps.Location(latitude, longitude)
        var pin = new Microsoft.Maps.Pushpin(loc, { icon: imagePath, anchor: new Microsoft.Maps.Point(12, 19) });
        pin.metadata = currentPin;
        Microsoft.Maps.Events.addHandler(pin, 'mouseover', HomeMapView.displayBingMapInfobox);
        Microsoft.Maps.Events.addHandler(pin, 'mouseover', HomeMapView.hideBingMapInfobox);
        //var html = HomeMapView.MapListingTemplate(currentPin);

        //Microsoft.Maps.Events.addHandler(pin, 'mouseover', function (args) {

        //    args.target.setOptions({ icon: pin.metadata.MapPinFocusImagePath, anchor: new Microsoft.Maps.Point(20, 29) });

        //    var pinLoc = pin.getLocation();
        //    var mapLoc = HomeMapView.map.getCenter();

        //    var offsetX = 0;
        //    var offsetY = 0;

        //    if (pinLoc.latitude > mapLoc.latitude) {
        //        offsetY = -133;
        //    }
        //    else {
        //        offsetY = -8;
        //    }

        //    if (pinLoc.longitude > mapLoc.longitude) {
                
        //        offsetX = -280;
        //    }
        //    else {
        //        offsetX = 20;
        //    }


        //    HomeMapView.infobox.setOptions({
        //        htmlContent: html.replace('map-list-item', 'map-infobox-item'),
        //        location: loc,
        //        visible: true,
        //        offset: new Microsoft.Maps.Point(offsetX, offsetY)
        //    });
        //});

        //Microsoft.Maps.Events.addHandler(pin, 'mouseout', function (args) {
        //    HomeMapView.infobox.setOptions({ visible: false });
        //    args.target.setOptions({ icon: pin.metadata.MapPinImagePath, anchor: new Microsoft.Maps.Point(12, 19) });
        //});

        Microsoft.Maps.Events.addHandler(pin, 'click', function () { location.href = '../?vendor=' + pin.metadata.VendorID; });
        HomeMapView.map.entities.push(pin);

        return pin;
    },
    displayBingMapInfobox: function (e) {
        if (e.targetType == 'pushpin') {

            var html = HomeMapView.MapListingTemplate(e.target.metadata).replace('map-list-item', 'map-infobox-item');
            HomeMapView.renderBingMapInfobox(e.target.getLocation(), e.target.metadata.Title, html, true, e.target);
        }
    },
    /** Render Bing Map Infobox */
    renderBingMapInfobox: function (latlong, title, description, autoHidden, currentPin) {

        if (HomeMapView.infobox != null) {
            HomeMapView.infobox.currentPin = currentPin;
            $('#mapContainer_infobox').unbind('click');
            $('#mapContainer_infobox').bind('click', function () {
                Microsoft.Maps.Events.invoke(HomeMapView.infobox.currentPin, 'click', { target: HomeMapView.infobox.currentPin });
            });

            invisibleMapinfo = 0;
            $('#mapContainer_infobox').unbind('mouseenter');
            $('#mapContainer_infobox').bind('mouseenter', function () {
                invisibleMapinfo = 0;
            });

            $('#mapContainer_infobox').unbind('mouseleave');
            if (autoHidden) {
                $('#mapContainer_infobox').bind('mouseleave', HomeMapView.hideBingMapInfobox);
            }
            HomeMapView.infobox.setOptions({ visible: true });
            var classPortalTheme = 'portal-theme';
            var portalThemeClass = $('.page-content-outer').hasClass(classPortalTheme) ? classPortalTheme : '';
            var html = ['<div class="map-balloon-container ' + portalThemeClass + '">'];
            html.push(description);
            html.push('</div>');
            HomeMapView.infobox.show(latlong, html.join(''));
            currentPinGeolocation = latlong;

            //reize div for header
            $('.list-item-header-title', $('#mapContent_infobox')).each(function () {

                var obj = $(this);

                // Calculate DotDotDot container size
                var parentWidth = $(obj).parent().parent().outerWidth();
                var expandCollapseWidth = 27;
                var averageIconWidth = 28;
                var actionItemsWidth = ($(obj).parent().find('.list-item-header-actions a').length * averageIconWidth) + expandCollapseWidth;
                //
                if (parentWidth > 0) {
                    $(obj).parent().parent().find('.list-item-header-title').css('width', (parentWidth - actionItemsWidth - expandCollapseWidth) + 'px');
                }
            });
            $('#mapContent_infobox').css('z-index', 1005);
            Tipped.create($('#mapContent_infobox').find('.span-actions i, .a-actions i'));
        }
    },
    //-->
    /** Auto hide Map Infobox */
    hideBingMapInfobox: function () {

        var delayHiddenInfoBox = setInterval(function () {
            if ($('#mapContainer_infobox:hover').length > 0) {
                invisibleMapinfo = 0;
            }
            if (invisibleMapinfo >= 2) {
                clearInterval(delayHiddenInfoBox);
                HomeMapView.infobox.hide();
            }
            else {
                invisibleMapinfo++;
            }
        }, 1000);
    },
//-->

}
var LocationView = {
    locationContainer: $("#location-container"),
    locationForm: $("#locationFlyout"),
    IsHomeView: false,
    lockFlyout: false,
    init: function () {
        this.bindUIActions();
    },
    bindUIActions: function () {
        LocationView.locationForm.on("submit", function ()
        {
            queryModel.Location = LocationView.locationForm.find("input[name=Location]").val();
            queryModel.IsDefaultLocationApply = false; //As custom location applied.
            queryModel.CurrentLocationMode = enumLocationSearchMode.Custom;
    
            LocationView.Submit();
        });
        LocationView.locationForm.on("keypress", "input[name=Location]", function (e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                LocationView.locationForm.submit();
            }
        });
        LocationView.locationContainer.on("click", ".location-declaration", function () {
            $("input[name=Location]").focus();
        });
        LocationView.locationContainer.on("mouseenter",function()
        {
            if (!LocationView.locationContainer.hasClass("disabled")) {
                toggleLocationFlyout(1);
            }
        });
        LocationView.locationContainer.on("keydown", function (e) {
            var focus = $(document.activeElement);
            if (focus.is("#location-container") && (e.which == 13 || e.which == 32))
            {
                if ($(".location-flyout").hasClass("visible")) {
                    if (!LocationView.locationContainer.hasClass("disabled")) {
                        e.preventDefault();
                        LocationView.lockFlyout = false;
                        toggleLocationFlyout(0);
                    }
                }
                else {
                    if (!LocationView.locationContainer.hasClass("disabled")) {
                        e.preventDefault();
                        LocationView.lockFlyout = true;
                        toggleLocationFlyout(1);
                    }
                }
                
            }
        });
        LocationView.locationContainer.on("focusout", function () {
            setTimeout(function () {
                var focus = $(document.activeElement);
                if (!focus.is("#location-container") && !$('#location-container').has(focus).length && !focus.is(".location-recent")) {
                    toggleLocationFlyout(0);
                    LocationView.lockFlyout = false;
                }
            }, 0);
        });
        LocationView.locationContainer.on("mouseleave",function()
        {
            if (!LocationView.lockFlyout) {
                toggleLocationFlyout(0);
            }   
        });
  
        LocationView.locationForm.on("click", "#current_location", function () {

            if (queryModel.CurrentLocationMode != enumLocationSearchMode.Browser) {

                queryModel.CurrentLocationMode = enumLocationSearchMode.Browser;
                
                queryModel.IsDefaultLocationApply = false;
                queryModel.Location = null;
                //Checking geolocation support for current browser.
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(getPosition);
                }
                else {
                    //Browser is not support.
                    GEO_LOCATION.getLocation(geolocatioCallback, 12000);
                }
            }
        });
    },
    Submit: function () {
        $.ajax({
            url: "/Main/GetLocation",
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            dataType: "json",
            async: true,
            traditional: true
        })
            .done(function (result) {
                console.log(result);
            if (result.Authorized != null && result.Authorized == false) {
                redirectToLogin();
            }

            if (result.location.IsValidLocation) {
                $('#location-error').html(""); //clear error, if exists
                $('#location-success').html("Location updated to: " + queryModel.Location); //announce new location

                queryModel.Latitude = result.location.Latitude;
                queryModel.Longitude = result.location.Longitude;
                queryModel.Location = result.location.LocationText;
                LocationView.UpdateHistory(result.history);
                LocationView.Update();
            }
            else {
                $('#location-success').html(""); //clear sucess text, if exists

                if (queryModel.Location.length == 0) {
                    $('#location-error').html("Please enter a location.");
                }
                else
                {
                    $('#location-error').html("Could not find: " + queryModel.Location);
                }
                $('.location-flyout').addClass('visible'); //show error
                $('#location-input').focus(); //focus input
            }
        });
    },
    UpdateLocation: function () {
        $.ajax({
            url: "/Main/UpdateLocation",
            type: "POST",
            data: AddAntiForgeryToken(queryModel),
            dataType: "json",
            async: true
        }).done(function (result) {
            if (result.Authorized != null && result.Authorized == false) {
                redirectToLogin();
            }
        });
    },
    Update: function(){
        FilterBar.Location_Applied.val(queryModel.Location).change();
        LocationView.UpdateApplied(queryModel.Location);
        
        if (LocationView.IsHomeView) {
            redirectQuery(false);
        }
        else {
            if (queryModel.IsListView) {
                ListView.Clear();
                ListView.ResetFlags();
                ListView.GetVendors();
            }
            else {
                MapView.Clear();
                MapView.ResetFlags();
                MapView.updateLocation();
            }
        }
    },
    Clear: function () {
        toggleLocationFlyout(0);
        LocationView.locationForm.find("input[name=Location]").val("");
        $('#location-error').html("");
    },
    UpdateHistory: function (obj) {
        $('#recent-searches').html('');
        $('.recent-searches').hide();
        $('.location-flyout hr').hide();
        $.each(obj, function (i, val) {
            $('#recent-searches').append("<a href='javascript:void(0)' onclick='updateLocation(" + val.Latitude + "," + val.Longitude + ",\"" + val.LocationName + "\");' class='location-recent' aria-label='Update location to " + val.LocationName + "'>" + val.LocationName + "</a>");
            $('.recent-searches').show();
            $('.location-flyout hr').show();
        });
    },
    UpdateApplied: function (loc) {
        $('#LocationSearchText').html(loc);
    }
};

/** Get Position */
function geolocatioCallback(latitude, longitude) {

    queryModel.CurrentLocationMode = enumLocationSearchMode.Browser;
    var location = latitude + "," + longitude;
    
    queryModel.Latitude = latitude;
    queryModel.Longitude = longitude;
    queryModel.Location = "Browser Location";
    
    LocationView.UpdateLocation();
    LocationView.Update();
}

function getPosition(position) {
    queryModel.CurrentLocationMode = enumLocationSearchMode.Browser;
    
    var location = position.coords.latitude + "," + position.coords.longitude;

    queryModel.Latitude = position.coords.latitude;
    queryModel.Longitude = position.coords.longitude;
    queryModel.Location = "Browser Location";

    LocationView.UpdateLocation();
    LocationView.Update();
}

function updateLocation(latitude, longitude, location) {
    //For Popular Destinations in Travel
    queryModel.CurrentLocationMode = enumLocationSearchMode.Custom;
    queryModel.Location = location;
    queryModel.Latitude = latitude;
    queryModel.Longitude = longitude;

    LocationView.UpdateLocation();
    LocationView.Update();
}
//-->
var SearchView = {
    searchForm: $("#search-container"),
    IsHomeView: false,
    timer: null,
    xhr: null,
    lockFlyout: false,
    init: function () {
        SearchView.bindUIActions();
    },
    bindUIActions: function () {
        SearchView.searchForm.on("keyup", "input[name=SearchText]", function (e)
        {
            if (e.keyCode != 38 && e.keyCode != 40) //keyboard-helper will handle UP/DOWN
            {
                SearchView._searchHints();
            }
        });
        SearchView.searchForm.on("focusin", "input[name=SearchText]", function () {
            SearchView._searchHints();
        });

        SearchView.searchForm.on("focusout", function () {
            setTimeout(function () {
                var focus = $(document.activeElement);
                if (focus.is("#search-container") || $('#search-container').has(focus).length) {
                    //console.log("still focused");
                } else {
                    //console.log(".focusout");
                    if (SearchView.xhr) { SearchView.xhr.abort(); }
                    toggleSearchHints(0);
                }
            }, 500);
        });

        SearchView.searchForm.on("submit", function () {
            if (SearchView.xhr) { SearchView.xhr.abort() }
            queryModel.SearchText = SearchView.searchForm.find("input[name=SearchText]").val();
            $('#searchboxinput').val(queryModel.SearchText);
            SearchView.Submit();
        });
        SearchView.searchForm.on("click", "#SearchTextButton", function () {
            queryModel.SearchText = SearchView.searchForm.find("input[name=SearchText]").val();
            $('#searchboxinput').val(queryModel.SearchText);
            SearchView.Submit();
        });
        
    },
    Submit: function () {
        ListView.Clear();
        ListView.ResetFlags();
        MapView.Clear();
        MapView.ResetFlags();

        if (SearchView.IsHomeView) {
            searchTextCategory(queryModel.SearchText);
        }
        else if (queryModel.IsListView) {
            
            ListView.GetVendors();
        }
        else {
            queryModel.IsFilterApply = true;
            MapView.loadBingMapData();
        }
    },
    Clear: function () {
        toggleSearchHints(0);
    },
    _searchHints: function () {
        if (SearchView.xhr) { SearchView.xhr.abort() } // If there is an existing XHR, abort it.
        clearTimeout(SearchView.timer); // Clear the timer so we don't end up with dupes.
        SearchView.timer = setTimeout(function () { // assign timer a new timeout 
            if (SearchView.searchForm.find("input[name=SearchText]").val()) {
                SearchView.xhr = $.ajax({
                    url: "/Main/SearchHint",
                    type: "POST",
                    data: AddAntiForgeryToken({ 'searchText': SearchView.searchForm.find("input[name=SearchText]").val() }),
                    async: true,
                    dataType: "json",
                    traditional: true
                })
                        .done(function (result) {
                            if (result.Authorized != null && result.Authorized == false) {
                                redirectToLogin();
                            }
                            var html = "", hr = false;
                            var source = $("#SearchListing").html();
                            var template = Handlebars.compile(source, { noEscape: true });
                            var hintCount = 0;

                            if (result.AltCategory.length > 0) {
                                hintCount = hintCount + result.AltCategory.length;

                                if (hr) { html += "<hr aria-hidden='true'>" }
                                $.each(result.AltCategory, function (i, item) {
                                    html += template(item);
                                });
                                hr = true;
                            }
                            if (result.Category.length > 0) {
                                hintCount = hintCount + result.Category.length;
                                if (hr)
                                {
                                    html += "<hr aria-hidden='true'> <span class='hint-label' role='heading'>Categories</span>"
                                }
                                $.each(result.Category, function (i, item) {
                                    html += template(item);
                                });
                                hr = true;
                            }
                            if (result.Keyword.length > 0) {
                                hintCount = hintCount + result.Keyword.length;

                                if (hr)
                                {
                                    html += "<hr aria-hidden='true'> <span class='hint-label' role='heading'>Keywords</span>"
                                }
                                $.each(result.Keyword, function (i, item) {
                                    html += template(item);
                                });
                                hr = true;
                            }
                            if (result.Vendor.length > 0) {
                                hintCount = hintCount + result.Vendor.length;

                                if (hr) { html += "<hr aria-hidden='true'> <span class='hint-label' role='heading'>Vendors</span>" }
                                $.each(result.Vendor, function (i, item) {
                                    html += template(item);
                                });
                                hr = true;
                            }

                            //$('.search-flyout').dotdotdot({
                            //    watch: true,
                            //    wrap: 'word'
                            //});

                            $(".search-flyout").html(html);
                            var currentAria = $(".search-aria-live-region").html();
                            var newAria = "";
                            if (hintCount > 0) {
                                newAria = hintCount + " search suggestions available";
                            }
                            if (currentAria != newAria) {
                                $(".search-aria-live-region").html(newAria);
                            }

                            //$('.search-flyout').find('a').attr('tabindex', 1);
                            //keyboardHelper.updateAnchorItemsIndex($('.search-flyout').find('a'), 1);

                            toggleSearchHints(1);
                    }).fail(function (result) {
                        SearchView.xhr.abort();
                        clearTimeout(SearchView.timer); });
            }
            else {
                toggleSearchHints(0);
            }
        }, 300);
    }

}
function searchText(text) {
    SearchView.searchForm.find("input[name=SearchText]").val(text);
    queryModel.SearchText = text;
    SearchView.Submit();
}
function searchTextCategory(text, Category) {
    queryModel.IsRedirect = true;
    queryModel.CurrentCategoryID = Category;
    queryModel.SearchText = text;
    redirectQuery(true);
}
function searchCategory(x) {
   
    window.location = window.location.origin + "?category="+x;
}
function searchVendor(x) {
    window.location = window.location.origin + "/all/?vendor=" + x;
}
var Google = (function () {
    var auth2, googleUser;
    var settings = {
        login: '#GoogleAccount .abcRioButtonContents',
        loginButton: 'GoogleAccount',
        logout: '.GoogleLogout'
    }
    init = function () {
        if (typeof gapi !== "undefined") {
            gapi.load('auth2', initSignin);
        }
        else {
            setTimeout(init, 250);
        }
    };
    initSignin = function () {

        gapi.auth2.init({
            client_id: '215804768451-eu387cukdv8jo5oahcf6j6gddhmqek7n.apps.googleusercontent.com',
            scope: 'profile'
        }).then(function (auth) {
            auth2 = auth;
            renderSignIn();
            // Listen for sign-in state changes.
            auth.isSignedIn.listen(signinChanged);
            // Listen for changes to current user.
            auth.currentUser.listen(userChanged);
            refreshValues(auth);

            $(settings.logout).click(function (event) {
                event.preventDefault();
                signOut();
            });
        });
    };

    signinChanged = function (val) {
        if (!val && window.location.pathname != '/Account/Login') {
            window.location = '/Account/Logout';
        }
    };

    userChanged = function (user) {

        googleUser = user;
        updateGoogleUser();

    };

    refreshValues = function (auth) {

        googleUser = auth.currentUser.get();

        updateGoogleUser();

    };

    updateGoogleUser = function () {

        if (googleUser && googleUser.getBasicProfile() && isEmpty(firstLogin)) {

            var profile = googleUser.getBasicProfile();

            $.ajax({
                url: "/Account/UpdateGoogleUser",
                type: "POST",
                async: true,
                data: AddAntiForgeryToken({
                    email: profile.getEmail(),
                    GoogleIDToken: googleUser.getAuthResponse().id_token,
                    givenName: profile.getGivenName(),
                    familyName: profile.getFamilyName(),
                    sProgramID: 2
                }),
                dataType: "json"
            })
                .done(function (result) {
                    if (result.IsUpdate) {
                        toastr.info("Your email has been updated to " + profile.getEmail());
                    }
                });
        }
    };

    signOut = function () {
        auth2.signOut().then(function () {
            window.location = '/Account/Logout'
        });
    };

    signIn = function (googleUser) {
        var profile = googleUser.getBasicProfile();
        createLoadingSpinner(settings.login);
        $.ajax({
            url: "/Account/LoginByGoogleToken",
            type: "POST",
            async: true,
            data: AddAntiForgeryToken({
                email: googleUser.getBasicProfile().getEmail(),
                GoogleIDToken: googleUser.getAuthResponse().id_token,
                sProgramID: 2
            }),
            dataType: "json"
        })
            // Success!
            .done(function (result) {
                if (result != "") {
                    if (result.IsValidated) {
                        $.cookie('test-cookie', '1');
                        var cookie = $.cookie('test-cookie');
                        if (cookie != undefined || cookie == 1) {
                            $.removeCookie('test-cookie', { path: '/' }); //destroy cookie: we are done using this and it is not HttpOnly
                            window.location.href = window.location.protocol + '//' + window.location.host + window.location.search;
                        }
                        else {
                            destroyLoadingSpinner(settings.login);
                        }
                    }
                    else {
                        if (result.CurrentStatus == 0 || result.IsTransition) {
                            location.href = '/Account/SignUp'; //this will display the /_TransitionMsg partial after the TransitionDate occurs
                        } else {
                            $('#login-error-msg2').html(result.LoginMessage);

                            auth2.signOut();

                            destroyLoadingSpinner(settings.login);
                            //Applied UI logic
                            if (result.DefaultDivVisibility) {
                                $('#login_panel').show();
                                $('#update_panel_plastic').hide();
                                $('#update_panel_digital').hide();
                                $('#update_panel_convertdigital').hide();
                                $('#update_panel_prime').hide();
                                $('#update_panel_bankcard').hide();
                                $('#update_panel_coderequired').hide();
                                $('#update_panel_google').hide();
                                if (result.IsLoginFailed) {
                                    $('#CompanyEmail').addClass('error');
                                    $('#CompanyEmail').attr('aria-invalid', 'true');
                                    $('#CompanyEmail').focus();
                                    $('#CompanyEmail').select();
                                }
                            }
                            else {

                                $('#login_panel').hide();
                                //console.log('renewal prompt: hide login panel')
                                //console.log('result.IsDigital ' + result.IsDigital )
                                //console.log('result.IsGoogleRenewal ' + result.IsGoogleRenewal )

                                $('#convertID').val(result.MemberID);
                                $('#memberID').val(result.MemberID);
                                $('#primeID').val(result.MemberID);
                                $('#bankID').val(result.MemberID);
                                $('#plasticID').val(result.MemberID);
                                $('#codeID').val(result.MemberID);
                                $('#googleID').val(result.MemberID);

                                //GoogleAccountToken was validated above, show the update_google_panel
                                var oldTitle = document.title.split('-')[0];
                                document.title = oldTitle + '- Renew';
                                var isUpdateRequired = false;
                                if (result.IsDigital || result.IsGoogleRenewal) {
                                    $('#update_panel_google').show();
                                    $('#block_panel_google').hide();
                                    $('#googleForm').show();
                                    $('#googleButton').focus();
                                    $('a#googleButton.btn').attr('href', '/Account/Transition/?mpk=' + result.MemberProgramKey); //updates the transition anchor with the encrypted MPK value
                                }
                                else {
                                    $('#update_panel_google').hide();
                                    $('#block_panel_google').show();
                                    $('#googleForm').show();
                                    $('#googleButton').focus();
                                    $('a#googleButton.btn').attr('href', '/Account/Transition/?mpk=' + result.MemberProgramKey); //updates the transition anchor with the encrypted MPK value
                                }


                                //skip option or no?
                                if (result.UpdateSkipVisibility) {
                                    //show the prompt text
                                    $('#update_text_google').show();
                                    //hide the 45+ day expired text
                                    $('#expired_text_google').hide();
                                    //show the skip button
                                    $('#skip_panel_google').show();
                                    $('#skip_panel_digital').show();
                                }
                                else {
                                    //hide the prompt text
                                    $('#update_text_google').hide();
                                    $('#update_text_digital').hide();
                                    //show the 45+ day expired text
                                    $('#expired_text_google').show();
                                    $('#expired_text_digital').show();
                                    $('#expired_text2_digital').show();
                                    //hide the skip button
                                    $('#skip_panel_google').hide();
                                    $('#skip_panel_digital').hide();
                                }

                            }
                        }
                    }
                }

            });
    };

    renderSignIn = function () {

        gapi.signin2.render(settings.loginButton, {
            'scope': 'profile email',
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': signIn
        });
    }

    return {
        init: init
    };

})();
