/*! jQuery UI - v1.12.1 - 2020-01-16
* http://jqueryui.com
* Includes: widget.js, position.js, keycode.js, unique-id.js, widgets/autocomplete.js, widgets/menu.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){t.ui=t.ui||{},t.ui.version="1.12.1";var e=0,i=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var s,n,o=i.call(arguments,1),a=0,r=o.length;r>a;a++)for(s in o[a])n=o[a][s],o[a].hasOwnProperty(s)&&void 0!==n&&(e[s]=t.isPlainObject(n)?t.isPlainObject(e[s])?t.widget.extend({},e[s],n):t.widget.extend({},n):n);return e},t.widget.bridge=function(e,s){var n=s.prototype.widgetFullName||e;t.fn[e]=function(o){var a="string"==typeof o,r=i.call(arguments,1),h=this;return a?this.length||"instance"!==o?this.each(function(){var i,s=t.data(this,n);return"instance"===o?(h=s,!1):s?t.isFunction(s[o])&&"_"!==o.charAt(0)?(i=s[o].apply(s,r),i!==s&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+o+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+o+"'")}):h=void 0:(r.length&&(o=t.widget.extend.apply(null,[o].concat(r))),this.each(function(){var e=t.data(this,n);e?(e.option(o||{}),e._init&&e._init()):t.data(this,n,new s(o,this))})),h}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(i,s){s=t(s||this.defaultElement||this)[0],this.element=t(s),this.uuid=e++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},s!==this&&(t.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===s&&this.destroy()}}),this.document=t(s.style?s.ownerDocument:s.document||s),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),i),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+o.eventNamespace,c=h[2];c?n.on(l,c,r):i.on(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){function e(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,o=Math.max,a=Math.abs,r=/left|center|right/,h=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,o="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:o?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType,o=!s&&!n;return{element:i,isWindow:s,isDocument:n,offset:o?t(e).offset():{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:i.outerWidth(),height:i.outerHeight()}}},t.fn.position=function(n){if(!n||!n.of)return d.apply(this,arguments);n=t.extend({},n);var u,p,f,g,m,_,v=t(n.of),b=t.position.getWithinInfo(n.within),y=t.position.getScrollInfo(b),w=(n.collision||"flip").split(" "),k={};return _=s(v),v[0].preventDefault&&(n.at="left top"),p=_.width,f=_.height,g=_.offset,m=t.extend({},g),t.each(["my","at"],function(){var t,e,i=(n[this]||"").split(" ");1===i.length&&(i=r.test(i[0])?i.concat(["center"]):h.test(i[0])?["center"].concat(i):["center","center"]),i[0]=r.test(i[0])?i[0]:"center",i[1]=h.test(i[1])?i[1]:"center",t=l.exec(i[0]),e=l.exec(i[1]),k[this]=[t?t[0]:0,e?e[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===n.at[0]?m.left+=p:"center"===n.at[0]&&(m.left+=p/2),"bottom"===n.at[1]?m.top+=f:"center"===n.at[1]&&(m.top+=f/2),u=e(k.at,p,f),m.left+=u[0],m.top+=u[1],this.each(function(){var s,r,h=t(this),l=h.outerWidth(),c=h.outerHeight(),d=i(this,"marginLeft"),_=i(this,"marginTop"),x=l+d+i(this,"marginRight")+y.width,C=c+_+i(this,"marginBottom")+y.height,D=t.extend({},m),T=e(k.my,h.outerWidth(),h.outerHeight());"right"===n.my[0]?D.left-=l:"center"===n.my[0]&&(D.left-=l/2),"bottom"===n.my[1]?D.top-=c:"center"===n.my[1]&&(D.top-=c/2),D.left+=T[0],D.top+=T[1],s={marginLeft:d,marginTop:_},t.each(["left","top"],function(e,i){t.ui.position[w[e]]&&t.ui.position[w[e]][i](D,{targetWidth:p,targetHeight:f,elemWidth:l,elemHeight:c,collisionPosition:s,collisionWidth:x,collisionHeight:C,offset:[u[0]+T[0],u[1]+T[1]],my:n.my,at:n.at,within:b,elem:h})}),n.using&&(r=function(t){var e=g.left-D.left,i=e+p-l,s=g.top-D.top,r=s+f-c,u={target:{element:v,left:g.left,top:g.top,width:p,height:f},element:{element:h,left:D.left,top:D.top,width:l,height:c},horizontal:0>i?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};l>p&&p>a(e+i)&&(u.horizontal="center"),c>f&&f>a(s+r)&&(u.vertical="middle"),u.important=o(a(e),a(i))>o(a(s),a(r))?"horizontal":"vertical",n.using.call(this,t,u)}),h.offset(t.extend(D,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-a-n;e.collisionWidth>a?h>0&&0>=l?(i=t.left+h+e.collisionWidth-a-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+a-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-a-n;e.collisionHeight>a?h>0&&0>=l?(i=t.top+h+e.collisionHeight-a-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+a-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,r=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-r-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-r-o,(0>i||a(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>a(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,r=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-r-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-r-o,(0>s||a(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,(i>0||u>a(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.ui.safeActiveElement=function(t){var e;try{e=t.activeElement}catch(i){e=t.body}return e||(e=t.body),e.nodeName||(e=t.body),e},t.widget("ui.menu",{version:"1.12.1",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target),s=t(t.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);i[0]===s[0]&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){var i=!t.contains(this.element[0],t.ui.safeActiveElement(this.document[0]));i&&this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),i=e.children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),i.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",o=!1,n=e.keyCode>=96&&105>=e.keyCode?""+(e.keyCode-96):String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i,s,n,o,a=this,r=this.options.icons.submenu,h=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),s=h.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("<span>").data("ui-menu-submenu-caret",!0);a._addClass(s,"ui-menu-icon","ui-icon "+r),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(s,"ui-menu","ui-widget ui-widget-content ui-front"),e=h.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);a._isDivider(e)&&a._addClass(e,"ui-menu-divider","ui-widget-content")}),n=i.not(".ui-menu-item, .ui-menu-divider"),o=n.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(n,"ui-menu-item")._addClass(o,"ui-menu-item-wrapper"),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){if("icons"===t){var i=this.element.find(".ui-menu-icon");this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)}this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t+""),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(t.trim(t(this).children(".ui-menu-item-wrapper").text()))})}}),t.widget("ui.autocomplete",{version:"1.12.1",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n;this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,this.element[0]!==t.ui.safeActiveElement(this.document[0])&&this.element.trigger("focus")})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,i){var s=i.item.data("ui-autocomplete-item"),n=this.previous;this.element[0]!==t.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=n,this._delay(function(){this.previous=n,this.selectedItem=s})),!1!==this._trigger("select",e,{item:s})&&this._value(s.value),this.term=this._value(),this.close(e),this.selectedItem=s}}),this.liveRegion=t("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")},this)},__response:function(t){t&&(t=this._normalize(t)),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this._off(this.document,"mousedown"),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({},e,{label:e.label||e.value,value:e.value||e.label})})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(),this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").append(t("<div>").text(i.label)).appendTo(e)},_move:function(t,e){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[t](e),void 0):(this.search(null,e),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(t,e),e.preventDefault())},_isContentEditable:function(t){if(!t.length)return!1;var e=t.prop("contentEditable");return"inherit"===e?this._isContentEditable(t.parent()):"true"===e}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.children().hide(),t("<div>").text(i).appendTo(this.liveRegion))}}),t.ui.autocomplete});
// window.addEventListener("orientationchange", function () { fnDelay(function () { WindowRotationEvent() }, 300) }, false);
// window.addEventListener("resize", function () { fnDelay(function () { WindowResizeEvent() }, 300) }, false);
document.addEventListener("click", eventDocClick, false);
window.addEventListener("load", eventWinLoad, false);
window.addEventListener("touchend", handleEnd, false);
document.addEventListener("keyup", eventDocKeyup, false);
document.addEventListener("keydown", eventDocKeydown, false);
// window.addEventListener("scroll", eventWinScrollCommon, false);

window.addEventListener("popstate", function (event) {
    if (event.state && event.state.type == "filter") {
        catalogFilter.loadProducts(document.location, true);
    }
    else if (event.state && event.state.type == "paging") {
        window.ajaxpager.loadPage(document.location, event.state.targetSelector);
    }
    else {
        document.location.reload();
    }
}, false);

function handleEnd(e) {
    var tappedEl = e.target;

    if (tappedEl.getAttribute("data-reit") && tappedEl.parentNode.classList.contains("ratingDinamic-star")) {
        var targ = tappedEl.parentNode;
        if (targ.querySelector(".active")) {
            targ.querySelector(".active").classList.remove("active");
        }
        tappedEl.classList.add("active");
        targ.classList.add("rated");
        if (targ.querySelector("input")) {
            targ.querySelector("input").value = tappedEl.getAttribute("data-reit");
        }
        if (targ.querySelector(".vld-field")) {
            vld.checkForm($(targ).closest(".vld-form")[0]);
        }
        vld.checkForm($(tappedEl).closest(".vld-form")[0]);
    }
}

var tipingTimer = 0;
function eventDocKeyup(e) {
    // Escape
    if (e.keyCode == 27) {
        if (document.querySelector(".oneProd-photos-fullscreen.shown")) {
            oneProdGal.fullscreenExit();
        }
    }

    /*window.isTipingFlag = true;
    clearTimeout(tipingTimer);
    tipingTimer = setTimeout(function() {
         window.isTipingFlag = false;
    }, 1000);*/
}

function eventDocKeydown(e) {
    // Enter
    if (e.keyCode == 13) {
        if (window.catalogFilter && window.catalogFilter.selectedInput) {
            window.catalogFilter.keyCodeEnter = true;
            window.catalogFilter.selectedInput = "";
        }
    }

}

var fnDelay = function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
}();

window.addScript = function (scriptPath, callback) {
    if ($("script[src='" + scriptPath + "']").length == 0) {
        var scr = document.createElement("script");
        scr.type = "text/javascript";
        scr.src = scriptPath;
        if (callback) scr.onload = function () {
            callback();
        };
        $("body")[0].appendChild(scr);
    } else if (callback) callback();
};
window.addScript2 = function (src) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script');
        script.type = "text/javascript";
        script.async = true;
        script.src = src;
        script.onload = function () {
            resolve(script);
        };
        script.onerror = function () {
            reject(new Error(`Script load error for ${src}`))
        };
        if (document.querySelectorAll(`script[src*="${src}"]`).length <= 0) {
            document.body.appendChild(script);
        }
    })
};
window.addCss = function (cssPath, name) {
    if (!document.querySelector(`link[href*="${cssPath}"]`)) {
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = cssPath;
        document.body.appendChild(link);
        if (name) {
            document.body.classList.add(name);
        }
    }
};
function stringToBoolean(string) {
    switch (string.toLowerCase()) {
        case "false":
        case "no":
        case "0": case "":
            return false;
        default: return true;
    }
}


// window.datepickerParams_bd = {};

//срабатывает после docready
//сюда писать скрипт, который нелючевой и допускает более поздней загрузки
function eventWinLoad(e) {
    googleAnaliticsData.init();
    setTimeout(function () { window.initSlick() }, 4000);
    // lazyLoad.update(0, document.getElementById("target-load-ajaxpager"));
    lazyLoad.pageload();
    loadProdsToDemand.init();
    sticky.init();
    shortenedContent.init();
    langPnl.init();

    if (window.location.pathname.indexOf("/delivery/") != -1) {
        if (window.location.hash) {
            var tab;
            if (tab = document.querySelector("[href='" + window.location.hash + "']")) {
                tab.click();
            }
        }
    }

    initDatePicker();
    initMask();

    if (document.querySelector(".vld-form")) {
        vld.onload();
    }


    /* if (getMQ("max-width", "sm")) {
        headerMainSliding.init();
    } */

    if (getMQ("max-width", "md") && document.querySelector(".tab-pane_params.active")) {
        document.querySelector(".tab-pane_params").classList.remove("active");
        document.querySelector(".tab-pane_params").classList.remove("show");
    }
    /* if (getMQ("max-width", "sm") && document.querySelector(".cards-slick")) {
        $(".cards-slick").on("scroll", lazyLoad.onscroll);
    } */

    var ps = document.querySelectorAll(".ps-wrapper");
    if (ps.length) {
        for (var i = 0, k = ps.length; i < k; i++) {
            perfectScrollInit(ps[i]);
        }
    }

    if (document.getElementsByClassName("scroll-seo").length) {
        perfectScrollInit(document.querySelector(".scroll-seo"));
    }

    // проверки на показ popup-sputnik
    setTimeout(function () {
        if (!document.body.classList.contains("logined")) {
            if (!getCookie("sputnikBonusActivated")) {
                SetCookie("sputnikBonusActivated", "1", 360);
                popup.show({ id: "sputnik" });
                sputnikBonusData.init();
            }
        }
        if (!window.getCookie("cookieAgreeToUse")) {
            window.addScript2("/js/cookieAlert.js").then(() => { window.cookieAlert.check() });
        }
    }, 6000);

    // проверка наличия в адресной строке authSuccess=1
    if (window.location.search.includes('authSuccess=1')) {
        dataLayer.push({ 'event': 'GAevent', 'eventCategory': 'sign_in', 'eventAction': 'A_2' });
    }

    userInfo.init();
    cartAddedProducts();
    //window.digiLayer.createLink();
    memoryForm.onload();
}
document.addEventListener("DOMContentLoaded", function (event) {

    if (document.querySelector(".oneProd-page")) {
        addScript2(`/js/ProductMdl.js?v=${new Date().valueOf()}`).then(() => {
            launchProductPageJs();
        })
    }
    // if(document.querySelector(".vld-form-cart")) {
    // 	vld.onload();
    // }
    checkAge.init();
    // warning1Cstuck.init();
    ddl.init('setReady');
    // jsTobg();
    headerFixedPnl.init();


    /* var ps = document.querySelectorAll(".ps-wrapper");
    if (ps.length) {
        for (var i = 0, k = ps.length; i < k; i++) {
            perfectScrollInit(ps[i]);
        }
    } */

    /* if (document.getElementsByClassName("scroll-seo").length) {
         perfectScrollInit(document.querySelector(".scroll-seo"));		
    } */

    // userInfo.init();

    /* setTimeout(function() {
        googleAnaliticsData.init();
    }, 2000); */
});

/* var scheduledAnimationFrame = false;
function eventWinScrollCommon() {
    eventWinScrollNoDelay();
    fnDelay(function () { eventWinScrollWithDelay() }, 150);

    if (scheduledAnimationFrame) return;

    scheduledAnimationFrame = true;
    requestAnimationFrame(eventWinScrollCommon);
} */
/* function eventWinScrollWithDelay() {
    // googleAnaliticsData.init();
    // loadProdsToDemand.init();
} */
var timerQuickCall = 0;
/* function eventWinScrollNoDelay() {
    // lazyLoad.onscroll();
    if (getMQ("max-width", "sm")) {
        headerMainSliding.onscroll();
    }
    if (getMQ("min-width", "sm")) {
        headerFixedPnl.check();
    }
} */
function WindowResizeEvent() {
    if (!getMQ("min-width", "sm")) {
        headerFixedPnl.clean();
    }
    else {
        headerFixedPnl.calc();
    }
}
function WindowRotationEvent() {
    if (!getMQ("min-width", "sm")) {
        headerFixedPnl.clean();
    }
    else {
        headerFixedPnl.calc();
    }
}

//глобальный обработчик кликов по документу
function eventDocClick(e) {
    var targ = e.target;
    var clickedEl = e.target;
    var ddlActive = null;

    while (targ && targ != this) {
        if (targ.tagName == "HTML") {
            var el;
            if (el = document.querySelector(".profile-userMenu-opened")) {
                el.classList.remove("profile-userMenu-opened");
            }
            /*if (el = document.querySelector(".headerMain-barsCnt")) {
                 if (el.classList.contains("opened")) {
                      el.classList.remove("opened");
                 }
            }   */
            if ((el = document.querySelector(".popup-outer.active"))
                && !clickedEl.closest(".popup-container")
                && !clickedEl.classList.contains("popup-outer-checkAge")
                && !clickedEl.classList.contains("popup-outer-sputnik")
            ) {
                popup.close(el.querySelector(".popup-container"));
            }
            if (el = document.querySelector(".quickCall.active")) {
                el.classList.remove("active");
            }

            var divCatalogMenu;
            if (divCatalogMenu = document.getElementById("divCatalogMenu")) {
                if (divCatalogMenu.classList.contains("opened")) {
                    divCatalogMenu.classList.remove("opened");
                    // document.body.classList.remove("catalogMenuOpened");
                    document.documentElement.classList.remove("catalogMenuOpened");
                    document.documentElement.classList.remove("startMenuOpened");
                }
            }
            if (document.body.classList.contains("searchMobOpened")) {
                document.body.classList.remove("searchMobOpened");
                document.querySelector(".headerMain-search").classList.remove("expanded");
            }

			let headerMainPhonesInner = document.querySelector(".headerMain-phones-inner");
			if(headerMainPhonesInner && headerMainPhonesInner.classList.contains("active")) {
				headerMainPhonesInner.classList.remove("active");
			}
            break;
        }

        if (targ.classList.contains("card-cart") && targ.parentNode.classList.contains("card-buttons")) {
            // событие клика по корзине в плитке товара
            if (targ.closest(".card-inCart")) return;
            targ.classList.add("spinner");
            userInfo.clickAddToCart(targ);
            break;
        }

        if (targ.classList.contains("oneProd-inCos")) {
            // клик был по кнопке в плавающей панеле внизу экрана
            // переназначаю targ
            if (targ.closest(".buyPnlForMobile")) {
                targ.classList.add("spinner");
                targ = document.querySelector(".oneProd-buyPnl-btns .oneProd-inCos");
            }
            // событие клика по корзине на странице товара
            if (targ.closest(".oneProd-inCart")) return;

            targ.classList.add("spinner");

            userInfo.clickAddToCart(targ);
            break;
        }

        // событие клика по favor
        if (targ.classList.contains("card-favor") || targ.classList.contains("favor-container-oneprodpage")
            ||
            targ.classList.contains("cartItem-favor")
        ) {
            userInfo.clickFavorite(targ);
            break;
        }

        if (targ.tagName.toLowerCase() == "a" && targ.parentNode.classList.contains("headerMain-lang-inner")) {
            if (!targ.classList.contains("aspNetDisabled")) {
                langPnl.click(targ);
            }
            break;
        }

        if (targ.classList.contains("check-container-compare") || targ.classList.contains("card-compare")) {
            userInfo.clickCompare(targ);
            if (document.querySelectorAll(".card").length <= 1 && targ.closest(".comparePage-inner")) {
                window.location.replace("/" + getLanguage() + "/compare/");
                // window.location.href = window.location.hostname + getLanguage() + /compare/
            }
            else {
                if (targ.closest(".comparePage-inner")) {
                    if (window.location.search) {
                        var prodId = targ.closest(".card").getAttribute("data-product");
                        var urlSearchPart = document.location.search.replace(prodId, "").replace("=,", "=").replace(",,", ",").replace(",&", "&");
                        // document.url = document.url.split("?")[0] + urlSearchPart;
                        window.location.href = document.URL.split("?")[0] + urlSearchPart;
                    }
                    else {
                        document.location.reload();
                    }
                }
            }
            break;
        }

        if (targ.classList.contains("profileIco")) {
            break;
        }

        if (targ.classList.contains("catalogMenu-container")) {
            break;
        }
        if (targ.classList.contains("catalogMenu-showMoreItems")) {
            if (targ.classList.contains("active")) {
                catalogMenu.showHiddenItems(targ, "hide");
            }
            else {
                catalogMenu.showHiddenItems(targ, "show");
            }
            targ.classList.toggle("active");
            break;
        }

        /* for phones */
        if (window.matchMedia("(max-width:991px)").matches) {
            if (targ.classList.contains("lnk_lvl") && !targ.parentNode.classList.contains("active")) {
                if (targ.classList.contains("lnk_lvl_1")) {
                    e.preventDefault();
                    window.catalogMenu.setActivelvl(targ.parentNode, "2");
                }
                if (targ.parentNode.classList.contains("hasInnerLvl")
                    && !targ.closest(".catalogMenu-lvl_last")
                ) {
                    e.preventDefault();

                    if (targ.parentNode.className.indexOf("item_lvl_") != -1) {
                        window.catalogMenu.setActivelvl(targ.parentNode, targ.parentNode.className.slice(targ.parentNode.className.indexOf("item_lvl_") + 9, targ.parentNode.className.indexOf("item_lvl_") + 10) * 1 + 1, "in");
                    }
                    else {
                        window.catalogMenu.setActivelvl();
                    }
                }
            }
            else {
                if (targ.classList.contains("lnk_lvl") && targ.parentNode.classList.contains("active")) {
                    e.preventDefault();
                    window.catalogMenu.setActivelvl(targ.parentNode, targ.parentNode.className.slice(targ.parentNode.className.indexOf("item_lvl_") + 9, targ.parentNode.className.indexOf("item_lvl_") + 10) * 1 + 1, "out");
                }
            }

            if (targ.classList.contains("searchPnl")) {
                break;
            }
            if (targ.classList.contains("searchPnl-btn") && !targ.closest(".headerMain-search").classList.contains("expanded")) {
                searchMobActive("open", targ);
                e.preventDefault();
                break;
            }

            if (targ.classList.contains("headerMain-search-closeBtn")) {
                searchMobActive("close", targ);
                break;
            }

            if (targ.classList.contains("startMenuForMob")) {
                catalogMenu.reset();
                break;
            }

            if (targ.classList.contains("startMenuForMob-close")) {
                if (document.querySelector(".catalogMenuOnMobActive")) {
                    catalogMenu.reset();
                    break;
                }
            }
            if (targ.classList.contains("headerMain-barsCnt-link")) {
                if (document.querySelector(".catalogMenuOnMobActive")) {
                    catalogMenu.reset(true);
                    break;
                }

            }
            if (targ.classList.contains("startMenuForMob-inner")) {
                break;
            }

            if (targ.classList.contains("startMenuForMob-nav-catalog")) {
                catalogMenu.catalogMenuOnMob();
                break;
            }

        }
		if (getMQ("max-width", "sm")) {
			if (targ.classList.contains("h5") && targ.parentNode.classList.contains("footerMain-oneList")) {
				var list = targ.parentNode.querySelector(".nav");
				targ.classList.toggle("active");
				if (targ.classList.contains("active")) {
					list.style.height = list.scrollHeight + "px";
				}
				else {
					list.style.height = "0px";
				}
				break;
			}
		}
        /* /for phones */

        /* for mob. devices upper 576 */
        if (getMQ("min-width", "sm")) {
            /*
            if (targ.tagName.toLowerCase() == "a"
                 && targ.classList.contains("lnk_lvl_3")
                 && targ.parentNode.classList.contains("hasInnerLvl")
                 && $(targ).closest(".catalogMenu-lvl_last").length == 0
            ) {
                 e.preventDefault();
                 if (targ.parentNode.classList.contains("active")) {
                      targ.parentNode.classList.remove("active");
                 }
                 else {
                      if (document.querySelector(".item_lvl_3.active")) {
                            document.querySelector(".item_lvl_3.active").classList.remove("active");
                            targ.parentNode.classList.add("active");
                      }
                      else {
                            targ.parentNode.classList.add("active");
                      }
                 }
            }
            */
        }
        /* /for mob. devices upper 576 */

        /* for mob. devices upper 576 and upto 1200 */
        if (getMQ("min-width", "lg") && getMQ("max-width", "lg")) {
            if (targ.classList.contains("lnk_lvl_1")) {
                e.preventDefault();
                window.catalogMenu.setActivelvl(targ.parentNode, "2");
            }
        }
        /* /for mob. devices upper 576 and upto 1200 */

        if (targ.classList.contains("nav-item-mob")) {
            let tab = targ,
                tabPane = tab.parentNode,
                tabPaneInner = tabPane.querySelector(".tab-pane-inner");

            tabPane.classList.toggle("active");

            if (tabPane.classList.contains("active")) {
                if (tabPaneInner) {
                    tabPaneInner.style.height = tabPaneInner.scrollHeight + "px";
                }
            }
            else {
                if (tabPaneInner) {
                    tabPaneInner.style.height = "0px";
                }
            }
            break;
        }

        if (targ.dataset.toggle == "tab") {
            e.preventDefault();
            let tab = targ,
                tabParent = tab.parentNode,
                tabPane = document.getElementById(tab.getAttribute("aria-controls")),
                tabPane_old = tabPane.parentNode.querySelector(".active");

            tabList = tab.closest("[role='tablist']");

            if (tab.classList.contains("active")) return false;

            tabList.querySelector(".active").parentNode.setAttribute("aria-selected", "false");
            tabList.querySelector(".active").classList.remove("active");
            tabPane_old.classList.remove("fade", "show", "active");

            tab.classList.add("active");
            tab.parentNode.setAttribute("aria-selected", "true");
            tabPane.classList.add("fade", "active");
            setTimeout(function () {
                tabPane.classList.add("show");
            }, 0);

            break;
        }

        if (targ.classList.contains("filterMain_section_title")) {
            let tab = targ,
                tabPane = tab.parentNode,
                tabPaneInner = tabPane.querySelector(".filterMain_section_listWrap");

            if (!tabPaneInner.hasAttribute("style")) {
                tabPaneInner.style.height = tabPaneInner.scrollHeight + "px";
            }
            setTimeout(function () {
                tabPane.classList.toggle("colapsed");

                if (!tabPane.classList.contains("colapsed")) {
                    if (tabPaneInner) {
                        tabPaneInner.style.height = tabPaneInner.scrollHeight + "px";
                        if (tabPaneInner.scrollHeight > 272) {
                            perfectScrollInit(tabPaneInner)
                        }
                    }
                }
                else {
                    if (tabPaneInner) {
                        tabPaneInner.style.height = "0px";
                    }
                }
                catalogFilter.saveViewSection(targ.parentNode);
            }, 50);
            break;
        }

        if (targ.classList.contains("catSections_catTitle")) {
            let tab = targ,
                tabPane = tab.parentNode.classList.contains("folding") ? tab.parentNode : "";

            if (tabPane) {
                let tabPaneInner = tabPane.querySelector(".catSections_subCat");

                if (!tabPaneInner.hasAttribute("style")) {
                    tabPaneInner.style.height = tabPaneInner.scrollHeight + "px";
                    tabPaneInner.style.minHeight = tabPaneInner.scrollHeight + "px";
                }
                if (tabPaneInner) {
                    tabPane.classList.toggle("folded");

                    if (!tabPane.classList.contains("folded")) {
                        tabPaneInner.style.height = tabPaneInner.scrollHeight + "px";
                        tabPaneInner.style.minHeight = tabPaneInner.scrollHeight + "px";
                    }
                    else {
                        tabPaneInner.style.height = "0px";
                        tabPaneInner.style.minHeight = "0px";
                    }
                    setTimeout(function () {
                        setParentHeightToAuto(tabPaneInner);
                    }, 500);

                    function setParentHeightToAuto(tabPaneInner) {
                        if (!tabPaneInner.parentNode.classList.contains("folded")) {
                            tabPaneInner.style.height = "auto";
                        }
                    }
                }
            }

            break;
        }

        if (targ.classList.contains("filterMain-toggleBtn")) {
            targ.classList.toggle("active");

            if (getMQ("max-width", "md")) {
                if (targ.classList.contains("active")) {
                    document.body.classList.add("filterMainOpened");
                }
                else {
                    document.body.classList.remove("filterMainOpened");
                    lazyLoad.update(300, document.getElementById("divAjaxTarget"));
                }
            }

            break;
        }
        if (targ.classList.contains("filterMain_closeBtn")) {
            document.body.classList.remove("filterMainOpened");
            document.querySelector(".filterMain-toggleBtn").classList.remove("active");
            lazyLoad.update(300, document.getElementById("divAjaxTarget"));
            catalogFilter.scrollTopPosition("reset");
            break;
        }
        if (targ.classList.contains("qPickupParams_reset")) {
            targ.parentNode.querySelector(".qPickupParams-input").value = "";
            // document.getElementsByClassName("searchBrands-input")[0].value = "";
            break;
        }

        if (ddlActive == null) {
            ddlActive = $('.ddlTpl.active');
        }

        if (ddlActive[0] && ddlActive[0] != targ) {
            ddl.setInActive(ddlActive[0]);
            return;
        }

        if (targ.classList.contains("ddlTpl__picked_inner") || targ.classList.contains("ddlTpl__picked")) {
            if (targ.closest(".ddlTpl").classList.contains("active")) {
                ddl.setInActive(targ.closest(".ddlTpl"));
            }
            else {
                ddl.setActive(targ.closest(".ddlTpl"), clickedEl);
            }
            break;
        }

        if (targ.classList.contains("popup-close")) {
            var popupLeaveInDom;
            popupLeaveInDom = stringToBoolean(targ.parentNode.getAttribute("data-leaveindom") ? targ.parentNode.getAttribute("data-leaveindom") : "false");
            if (targ.closest(".popup-container")) {
                popup.close(targ.closest(".popup-container"), popupLeaveInDom);
            }
            break;
        }

        if (targ.classList.contains("profile-userMenu")) {
            break;
        }

        if (targ.classList.contains("datepicker-setDate")) {
            if (clickedEl.tagName == "INPUT") {
                if (clickedEl.parentNode.classList.contains("datepicker-setDate-bd")) {
                    window.datepickerParams_bd.container = "#" + clickedEl.parentNode.id;
                    $(clickedEl).datepicker(window.datepickerParams_bd);

                    $(clickedEl).datepicker().on("changeDate", function () {
                        let input = this;
                        let form = input.closest(".vld-form");

                        setTimeout(function () {
                            vld.checkForm(form, input);
                        }, 500)
                    });
                }
                targ.classList.add("active");
                $(clickedEl).datepicker('show');
                /*$(clickedEl).datepickerBS().on("changeDate", function (e) {
                     $(clickedEl).datepickerBS("hide");
                });*/
                break;
            }
        }

        if (targ.classList.contains("profile-adrsTbl-setMain")) {
            profile.setAddressActive(targ);
            break;
        }

        if (targ.classList.contains("profile-adrsTbl-del")) {
            profile.deleteAddress(targ);
            break;
        }

        if (targ.classList.contains("btn-saveAddress")) {
            if (document.body.getAttribute("data-profileaddress") == "addaddress") {
                profile.addAddress();
            }
            else if (document.body.getAttribute("data-profileaddress") == "editaddress") {
                profile.editAddress();
            }
            break;
        }

        if ((targ.classList.contains("col") || targ.classList.contains("closeBtn")) && targ.parentNode.classList.contains("myOrders-brief")) {
            profile.myOrderDetails(targ.parentNode);
            break;
        }

        if (targ.classList.contains("lnk-profileAddAddress")) {
            popup.show({ id: 'profileAddress', callback: profile.addAddress });
            break;
        }

        if (targ.classList.contains("profile-adrsTbl-edit")) {
            var edit;
            if (edit = targ.parentNode.parentNode.querySelector(".editing")) {
                edit.classList.remove("editing");
            }
            if (!targ.parentNode.classList.contains("editing")) {
                targ.parentNode.classList.add("editing");
            }
            popup.show({ id: 'profileAddress', callback: profile.editAddress });
            break;
        }

        if (targ.classList.contains("js-comparePage-checkContainer")) {
            comparePage.showDiffs(targ);
            break;
        }

        if (targ.classList.contains("viewMode-cells") || targ.classList.contains("viewMode-rows")) {
            if (!targ.classList.contains("active")) {
                targ.parentNode.querySelector(".active").classList.remove("active");
                targ.classList.add("active");
                if (targ.getAttribute("data-target")) {
                    document.querySelector(targ.getAttribute("data-target")).classList.remove(targ.getAttribute("data-viewmoderemove"));
                    document.querySelector(targ.getAttribute("data-target")).classList.add(targ.getAttribute("data-viewmodeadd"));
                    SetCookie("cardsViewMode", targ.getAttribute("data-viewmodeadd"), 30);
                }
            }
        }

        if (targ.getAttribute("data-param-desc")) {
            var paramId = targ.getAttribute("data-param-desc");
            var options = {
                "url": '/standalone/parameterdescription.aspx?lng=' + getLanguage() + "&paramId=" + paramId
            };

            popup.show(options);

            break;
        }

        if (targ.classList.contains("quickCall")) {
            targ.classList.toggle("active");
            break;
        }

        if (targ.classList.contains("js-btn-showReviewForm")) {
            if (userInfo.isLogined) {
                e.stopPropagation();
                reviewForm.show();
            }
            else {
                document.location.href = "/" + getLanguage() + "/login/?returnUrl=" + document.location;
            }
            break;
        }

        if (targ.classList.contains("btn-SendComment")) {
            submitProductReview(e, targ);
            return;
        }

        if (targ.classList.contains("js-lnkGoToReview")) {
            var reviewTab;
            if (reviewTab = document.getElementById("reviews-tab")) {
                if (getMQ("max-width", "sm")) {
                    reviewTab = document.getElementById("reviews").querySelector(".nav-item-mob");
                }
                if (!reviewTab.classList.contains("active") && !reviewTab.parentNode.classList.contains("active")) {
                    reviewTab.click();
                }
                setTimeout(function () {
                    scrollToElement(reviewTab, -15);
                }, 150);
            }
            break;
        }

        if (targ.classList.contains("ratingDinamic")) {
            if (targ.querySelector(".active")) {
                targ.querySelector(".active").classList.remove("active");
            }
            clickedEl.classList.add("active");
            targ.classList.add("rated");
            if (targ.querySelector("input")) {
                targ.querySelector("input").value = clickedEl.getAttribute("data-reit");
            }
            if (targ.querySelector(".vld-field")) {
                vld.checkForm(targ.closest(".vld-form"), targ.querySelector(".vld-field"));
            }
            break;
        }

        if (targ.classList.contains("cartItem-delete") && targ.closest(".cartItem")) {
            Cart.deleteItem(targ);
        }

        if (targ.classList.contains("cart-giftCard-delete") && targ.closest(".cart-giftCard-oneCard")) {
            Cart.deleteGiftCard(targ);
        }

        /*if(targ.classList.contains("oneProd-photos-thumbnails-thumb")) {
             oneProdGal.clickthumb(targ, targ.parentNode, $(".oneProd-photos-galery-slick"));
             return;
        }*/
        /*if(targ.classList.contains("oneProd-photos-fullscreen-thumbnails-thumb")) {
             oneProdGal.clickthumb(targ, targ.parentNode, $(".oneProd-photos-fullscreen-slick"));
             return;
        }*/
        if (targ.classList.contains("oneProd-photos-picture")) {
            document.querySelector(".oneProd-photos-galery").classList.add("spinner");
            oneProdGal.fullscreen(false, targ.parentNode.getAttribute("data-slick-index") * 1);
            return;
        }
        if (targ.classList.contains("btnStartVideoOnFullScreen")) {
            oneProdGal.fullscreen(true, undefined);
            return;
        }
        if (targ.classList.contains("oneProd-photos-fullscreen-close")) {
            oneProdGal.fullscreenExit();
            return;
        }
        if (targ.classList.contains("oneProd-oneReview-photo")) {
            targ.parentNode.classList.add("spinner");
            oneProdReviewGal.fullscreen(false, targ.getAttribute("data-priority") * 1, targ.parentNode);
            return;
        }
        if (targ.classList.contains("oneProd-photosReview-fullscreen-close")) {
            oneProdReviewGal.fullscreenExit();
            return;
        }
        if (targ.getAttribute("type") == "submit") {
            targ.classList.add("disabled");
            setTimeout(function () {
                targ.classList.remove("disabled");
            }, 3000);
            break;
        }

        if (targ.classList.contains("slick-dots")) {
            lazyLoad.update(500, targ.parentNode);
            break;
        }
        if (targ.classList.contains("card-cart-goto")) {
            document.location.href = targ.getAttribute("data-href");
        }
        if (targ.classList.contains("tooltipCustom-trigger")) {
            tooltipCustom.action(targ);
        }
        if (targ.classList.contains("tooltipCustom-content-close")) {
            tooltipCustom.close(targ);
        }
        // препятствуем закрытие попапа "Добавление нового адреса" в профиле при выборе нас. пункта из списка autocomplete
        if (targ.classList.contains("ui-autocomplete")) {
            vld.onload();
            break;
        }
        if (targ.classList.contains("modal-popup-btn")) {
            let modal = targ.closest(".modal-popup");
            if (modal) {
                modal.parentNode.removeChild(modal);

                setTimeout(function () {
                    var loginPass = document.querySelector(".vld-form-login #txtPassword");

                    if (loginPass) {
                        loginPass.value = "";
                        loginPass.className = "vld-field vld-input form-control";
                    }
                }, 1000);
            }

        }
        if (targ.classList.contains("btn-iam18ageplus")) {
            checkAge.iam18ageplus(targ.closest(".popup-checkAge"));
            break;
        }
        /* if (targ.classList.contains("btn-warning1Cstuck")) {			
            warning1Cstuck.close(targ.closest(".popup-warning1Cstuck"));
            break;
        } */
        if (targ.classList.contains("closeShortenedContent-lnk")) {
            shortenedContent.close(targ);
            break;
        }
        if (targ.classList.contains("openShortenedContent-lnk")) {
            shortenedContent.open(targ);
            break;
        }
        if (
            (targ.classList.contains("card-img-top") && targ.parentNode.tagName.toLowerCase() == "a")
            ||
            (targ.classList.contains("card-title") && targ.tagName.toLowerCase() == "a")
        ) {
            let dataProduct = targ.closest(".card").getAttribute("data-product");
            let viewName = "";
            let dataGAnode;
            if (dataGAnode = targ.closest("[data-ga]")) {
                viewName = dataGAnode.getAttribute("data-ga");
            }
            let promoName = "", promoId = "";
            if (dataGAnode = targ.closest("[data-ga-promoname]")) {
                promoName = dataGAnode.getAttribute("data-ga-promoname");
            }
            if (dataGAnode = targ.closest("[data-ga-promoid]")) {
                promoId = dataGAnode.getAttribute("data-ga-promoid");
            }
            gtmSelectItem(viewName, dataProduct, promoName, promoId);
            break;
        }
        if (targ.classList.contains("profile-aside-backToProfile")) {
            e.preventDefault();
            document.querySelector(".headerMain-barsCnt-link").click();
            document.querySelector(".headerMain-row_2 > .wrapperDefault_inner").classList.add("profile-userMenu-opened");
            break;
        }
        if (targ.classList.contains("btn-showmore") && targ.parentNode.classList.contains("paging")) {
            if (typeof window.ajaxpager == 'undefined') {
                e.preventDefault();
                window.ajaxpager = new AjaxPager().init();
            }
        }
        if (targ.classList.contains("cart-btnSubmitOrder-container")) {
            if (document.querySelector(".btn-submitOrder").className.indexOf('disabled') != -1) {
                Cart.scrollToUncompleteSection();
            }
        }
        if (targ.getAttribute('data-toggle') && (targ.getAttribute('data-toggle') == "collapse")) {
            accordionAkaBS.init(targ);
            break;
        }
        if (targ.classList.contains("cart-selectAll")) {
            Cart.selectAll(targ);
            break;
        }
        if (targ.classList.contains("cart-deleteSelected")) {
            Cart.deleteSelected();
            break;
        }
        if (targ.classList.contains("check-container") && targ.closest(".cartItemsList")) {
            Cart.getStatusAllChecks();
            break;
        }
        if ((targ.classList.contains("monthVal") || targ.classList.contains("paymentVal"))
            &&
            targ.closest(".section_slider")
        ) {
            targ.querySelector("input").select();
            break;
        }
        if (targ.classList.contains("btn-agreeUseCookie")) {
            cookieAlert.agree(e);
            break;
        }
        if (targ.classList.contains("lnk-reviews") && targ.closest(".card-body")) {
            sessionStorage.setItem("gotoReviewsProdPage", "1");
            break;
        }
		if(targ.classList.contains("btn-getUserPhoneAuth")) {
			let popupBody = targ.closest(".popup-body");

			popupBody.classList.add("overlay", "overlay-white", "spinner");

			if(popupBody.querySelector("[name='sms']")) {
				authenticateUserCallback.sendSms(targ);
				break;
			}
			else {
				authenticateUserCallback.sendPhone(targ);
				break;
			}
			break;
		}
		if(targ.classList.contains("myLocation-current")) {
			myLocationPrepare(targ);
			break;
		}
		if(targ.classList.contains("headerMain-phones-inner") && !targ.classList.contains("active")) {
			e.preventDefault();
			targ.classList.add("active");
			break;
		}
		if(targ.classList.contains("headerMain-phones-inner") && targ.classList.contains("active")) {
			e.preventDefault();
			targ.classList.remove("active");
			break;
		}

        targ = targ.parentNode;
    }
};

function SetCookie(name, value, expires) {
    //alert(value);
    var dt = new Date();
    var dtt = "";
    dt.setTime(dt.getTime() + expires * 24 * 60 * 60 * 1000);
    dtt = dt.toGMTString();
    document.cookie = name + "=" + value + ";expires=" + dtt + ";path=/";
}

function getCookie(name) {
    var prefix = name + "=";
    var cookieStartIndex = document.cookie.indexOf(prefix);
    if (cookieStartIndex == -1)
        return null;
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1)
        cookieEndIndex = document.cookie.length;
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}
function deleteCookie(name) {
    if (getCookie(name)) {
        document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT;path=/";
    }
}
/* HTML
<div class="qty-container">
     <button class="btn-noap qty-minus"></button>
     <input name="ctl00$cphMain$txtQuantity" type="text" value="1" id="ctl00_cphMain_txtQuantity" class="qty-input" data-min="1">
     <button class="btn-noap qty-plus"></button>
</div>
*/
window.qty = new qty().init();
function qty() {
    var self = this;

    this.init = function () {
        $(document).on('click', '.qty-minus', function (e) {
            calc(e, this, "minus");
        });
        $(document).on('click', '.qty-plus', function (e) {
            calc(e, this, "plus");
        });
        $(document).on('click', '.qty-input', function (e) {
            this.select();
        });
        $(document).on('keyup', '.qty-input', function (e) {
            calc(e, this, "input");
        });
        return self;
    };

    function calc(e, sender, name) {
        var min, max, inpVal;
        var inp = sender.parentNode.querySelector(".qty-input");

        min = inp.getAttribute("data-min") ? parseInt(inp.getAttribute("data-min"), 10) : 1;
        max = inp.getAttribute("data-max") ? parseInt(inp.getAttribute("data-max"), 10) : Infinity;
        inpVal = parseInt(inp.value, 10);

        if (name == "minus") {
            if (inpVal - 1 >= min) {
                inp.value = --inpVal;
            }
        }
        else if (name == "plus") {
            if (inpVal + 1 <= max) {
                inp.value = ++inpVal;
            }
        }
        else if (name == "input") {
            if (isNaN(inpVal)) {
                inp.value = min;
            }
            if (inpVal > max) {
                inp.value = max;
            }
            if (inpVal < min) {
                inp.value = min;
            }
        }
        dsbld(sender, name, inpVal, min, max);
    }
    function dsbld(sender, name, inpVal, min, max) {
        if (name == "minus") {
            if (inpVal <= min) {
                sender.classList.add("disabled");
            }
            if (inpVal < max) {
                sender.parentNode.querySelector(".qty-plus").classList.remove("disabled");
            }
        }
        else if (name == "plus") {
            if (inpVal >= max) {
                sender.classList.add("disabled");
            }
            if (inpVal > min) {
                sender.parentNode.querySelector(".qty-minus").classList.remove("disabled");
            }
        }
        else if (name == "input") {
            if (inpVal <= min) {
                sender.parentNode.querySelector(".qty-minus").classList.add("disabled");
                if (inpVal < max) {
                    sender.parentNode.querySelector(".qty-plus").classList.remove("disabled");
                }
            }
            if (inpVal >= max) {
                sender.parentNode.querySelector(".qty-plus").classList.add("disabled");
                if (inpVal > min) {
                    sender.parentNode.querySelector(".qty-minus").classList.remove("disabled");
                }
            }
        }
    }
}
window.perfectScrollQueue = [];
window.perfectScrollFirstStart = true;
function perfectScrollInit(elName) {
    var el;
    if (typeof elName == "string") {
        el = document.querySelector(elName);
    }
    else {
        el = elName;
    }
    if (typeof PerfectScrollbar == "undefined") {
        perfectScrollQueue.push(el);
        if (perfectScrollFirstStart) {
            perfectScrollFirstStart = false;
            addScript2("/js/perfect-scrollbar.min.js").then(() => {
                if (!document.documentElement.classList.contains("perfectScrollCss")) {
                    document.documentElement.classList.add("perfectScrollCss")
                    addCss("/css/perfect-scrollbar.css?v2");
                }
                if (typeof PerfectScrollbar != "undefined") {
                    startLoop();
                }
            })
        }

    }
    else {
        perfectScrollRun(el);
    }

    function startLoop() {
        for (var i = 0, k = perfectScrollQueue.length - 1; i <= k; i++) {
            perfectScrollRun(perfectScrollQueue[i]);
        }
        perfectScrollQueue.length = 0;
    }

    function perfectScrollRun(el) {
        if (el.scrollHeight > el.clientHeight) {

            var Ps = new PerfectScrollbar(el, { suppressScrollX: true, swipeEasing: true });
            if (el) {
                const psWrapper = el;
                if (psWrapper) {
                    setTimeout(function () {
                        if (psWrapper.classList.contains("ps")) {
                            Ps.update(psWrapper);
                            psWrapper.scrollTop = 0;

                            psWrapper.addEventListener('ps-y-reach-end', function () {
                                this.parentNode.classList.add("ps-y-reach-end");
                            });
                            psWrapper.addEventListener('ps-y-reach-start', function () {
                                this.parentNode.classList.add("ps-y-reach-start");
                            });
                            psWrapper.addEventListener('ps-scroll-up', function () {
                                this.parentNode.classList.remove("ps-y-reach-end");
                            });
                            psWrapper.addEventListener('ps-scroll-down', function () {
                                this.parentNode.classList.remove("ps-y-reach-start");
                            });
                        }
                    }, 100);
                }
            }
        }
    }
};
function perfectScrollReset(elName) {
    var el = "";
    if (typeof elName == "string") {
        el = document.querySelector(elName);
    }
    else {
        el = elName;
    }
    if (el) {
        el.querySelector(".ps-wrapper").classList.remove("ps--active-y");
        var railX, railY;
        if (railX = el.querySelector(".ps__rail-x")) {
            railX.parentNode.removeChild(railX);
        }
        if (railY = el.querySelector(".ps__rail-y")) {
            railY.parentNode.removeChild(railY);
        }
        perfectScrollInit(el.querySelector(".ps-wrapper"));
    }
};
function scrollToElement(elemID, delta) {
    var elem = typeof elemID == "string" ? document.getElementById(elemID) : elemID;
    if (isNaN(delta))
        delta = 0;
    if (elem) {
        $('html, body').animate({
            scrollTop: parseInt($(elem).offset().top) + delta
        }, 1000);
    }
};
function jsTobg(el, p) {
    var tgt;
    if (el != undefined) {
        tgt = el;
    } else {
        tgt = $('img.js-tobg');
    }
    tgt.each(function () {
        var img = $(this),
            prnt = img.parent();

        if (prnt.is('picture') && p == undefined) {
            prnt = prnt.parent();
        }

        var interval = setInterval(function () {
            if (prnt.hasClass("js-tobg-cnt")) return;
            if (img.get()[0].currentSrc != '' && img.get()[0].currentSrc != undefined) {
                prnt.css({
                    "background-image": 'url("' + img.get()[0].currentSrc + '")'
                }).addClass('js-tobg-cnt');
                clearInterval(interval);
            } else if (img.get()[0].currentSrc == undefined) {
                let src = '';
                prnt.find('source').each(function () {
                    if (window.matchMedia($(this).attr('media')).matches) {
                        src = $(this).attr('srcset');
                    }
                });
                prnt.css({
                    "background-image": 'url("' + (src == '' ? img.get()[0].src : src) + '")'
                }).addClass('js-tobg-cnt');
                clearInterval(interval);
            } else {
                return;
            }
        }, 500);
    });
}
function initMask() {
    var phones = $("input[data-phone-mask]");
    if (phones.length > 0) {
        addScript("/js/jquery.maskedinput.min.js", function () {
            if ($.mask && $.mask.definitions) {
                $.mask.definitions['@'] = '6|7';
                phones.mask("0@9 999-999", { completed: function () { $(this).addClass("valid"); vld.checkField(phones[0]); } });
                phones.removeAttr("data-phone-mask");
            }
        });
    }
}
function initSlick() {
    // на стр. товара initSlick не запускаю
    if (!document.getElementById("oneProdGal")) {

        if (!document.documentElement.classList.contains("slickCss")) {
            document.documentElement.classList.add("slickCss")
            addCss("/css/slick181.min.css");
        }
        if (typeof $.fn.slick == "undefined") {
            addScript2("/js/slick1.8.1.min.js").then(() => {

                runSlick();
            })
        }
        else {
            runSlick();
        }
    }

    function runSlick() {
        if (document.getElementsByClassName("cards-slick")[0]) {
            /*$('.cards-slick').on('swipe', function(event, slick, direction) {
                    lazyLoad.check(slick.$slideTrack[0]);
            });*/

            $('.cards-slick').on('afterChange', function (event, slick, direction) {
                lazyLoad.update(100, slick.$slideTrack[0]);
            });
            if (getMQ("min-width", "md")) {
                setTimeout(function () {
                    $(".cards-slick").on("init", function (event, slick) {
                        if (slick.$slideTrack) {

                            // lazyLoad.check(slick.$slideTrack[0]);
                            lazyLoad.update();
                            if (slick.$dots[0].childElementCount > 1) {
                                slick.$dots.show();
                            }
                            else {
                                slick.$dots.hide();
                            }
                        }
                    });
                    $(".cards-slick").slick(window.cards5_slick);
                }, 100);
            }
        }
        if (document.getElementsByClassName("allWidth-slick")[0]) {

            $(".allWidth-slick").on("afterChange", function (event, slick, currentSlide) {
                lazyLoad.update(300, slick.$slideTrack[0]);
            });
            setTimeout(function () {

                $(".allWidth-slick").on("afterChange", function (slick, currentSlide) {
                    if (slick.currentTarget.parentNode.classList.contains("carousel-OnMain")) {
                        if (isScrolledIntoView(slick.currentTarget.parentNode, 0, true)) {
                            gtmViewPromotion(currentSlide.$slides[currentSlide.currentSlide].dataset.id, currentSlide.$slides[currentSlide.currentSlide].dataset.name);
                        }
                    }

                });
                $(".allWidth-slick").on("init", function (event, slick) {
                    if (slick.$slider[0].parentNode.classList.contains("carousel-OnMain")) {
                        if (isScrolledIntoView(slick.$slider[0].parentNode, 0, true)) {
                            let currentSlideNum = 0;
                            for (let i = 0, k = slick.$slides.length; i < k; i++) {
                                (function (i) {
                                    if (slick.$slides[i].classList.contains("active")) {
                                        currentSlideNum = i;
                                    }
                                })(i);
                            }
                            gtmViewPromotion(slick.$slides[currentSlideNum].dataset.id, slick.$slides[currentSlideNum].dataset.name);
                        }
                    }
                    // lazyLoad.check(slick.$slideTrack[0]);
                    lazyLoad.update();
                    if (slick.$dots[0]) {
                        if (slick.$dots[0].childElementCount > 1) {
                            slick.$dots.show();
                        }
                        else {
                            slick.$dots.hide();
                        }
                    }
                });
                if (document.querySelector(".allWidthBannerStripe-slick")) {
                    $(".allWidthBannerStripe-slick").slick(window.allWidthSlickNoArrowsParams);
                }
                else {
                    $(".allWidth-slick").slick(window.allWidthSlickParams);
                }

                // выпадайка поиска
                // после генерации булетов для слайрера slicka поправляю вертикальное позиционирование выпадайки 
                // относительно "input[type='search']"
                // 

                // let uiautocomplete = document.querySelector(".ui-autocomplete:not(.city)");
                let uiautocomplete = document.querySelector(".searchPnl-input");

                if (uiautocomplete && uiautocomplete.clientHeight) {

                    if (getMQ("min-width", "md")) {

                        let inputSearch = document.querySelector("input[type='search']");
                        let bodyInner = document.querySelector(".body-inner");

                        uiautocomplete.style.top = (bodyInner.clientHeight - window.scrollY - (inputSearch.getBoundingClientRect().top + inputSearch.clientHeight)) * -1 + "px";
                    }
                }
            }, 100);
        }
    }
}

var cards5_slick = {
    dots: true,
    infinite: false,
    speed: 500,
    slidesToShow: 2,
    slidesToScroll: 2,
    slide: 'div',
    arrows: false,
    autoplay: false,
    mobileFirst: true,
    responsive: [
        {
            breakpoint: 1279,
            settings: {
                slidesToShow: 5,
                slidesToScroll: 5
            }
        },
        {
            breakpoint: 991,
            settings: {
                slidesToShow: 4,
                slidesToScroll: 4
            }
        },
        {
            breakpoint: 767,
            settings: {
                slidesToShow: 3,
                slidesToScroll: 3
            }
        },
        {
            breakpoint: 300,
            settings: "unslick"
        }
    ]
};
var allWidthSlickParams = {
    dots: true,
    infinite: false,
    speed: 1000,
    slidesToShow: 1,
    slidesToScroll: 1,
    autoplay: true,
    arrows: true,
    prevArrow: "<button type='button' class='carousel-control-prev slick-prev slick-arrow pull-left'><span class='carousel-control-prev-icon' aria-hidden='true'></span><span class='sr-only'><%=Language.Get('Previous') %></span></button>",
    nextArrow: "<button type='button' class='carousel-control-next slick-next slick-arrow pull-right'><span class='carousel-control-next-icon' aria-hidden='true'></span><span class='sr-only'><%=Language.Get('Next') %></span></button>"
};
var allWidthSlickNoArrowsParams = {
    dots: true,
    infinite: false,
    speed: 1000,
    slidesToShow: 1,
    slidesToScroll: 1,
    autoplay: true,
    arrows: false
    //  ,
    //  prevArrow: "<button type='button' class='carousel-control-prev slick-prev slick-arrow pull-left'><span class='carousel-control-prev-icon' aria-hidden='true'></span><span class='sr-only'><%=Language.Get('Previous') %></span></button>",
    //  nextArrow: "<button type='button' class='carousel-control-next slick-next slick-arrow pull-right'><span class='carousel-control-next-icon' aria-hidden='true'></span><span class='sr-only'><%=Language.Get('Next') %></span></button>"
};

$(".slick-dotted").on('breakpoint', function (event, slick, breakpoint) {
    if (slick.$dots[0].childElementCount > 1) {
        slick.$dots.show();
    }
    else {
        slick.$dots.hide();
    }
});

function getLanguage() {
    return $("html").attr("lang");
}
function isCyrillic(str) {
    return /[а-я]/i.test(str);
}
$("#divCatalogMenu .headerMain-barsCnt-link").click(function (event) {
    event.preventDefault();
    event.stopPropagation();
    var catalogMenu_wrapper = $(this).parent();
    if (window.matchMedia("(min-width:992px)").matches) {
        var catalogMenu_container = catalogMenu_wrapper.find("#catalogMenu-container");
        if (catalogMenu_container.length == 0) {
            catalogMenu_wrapper.addClass("loading");
            // catalogMenu_wrapper.append("<div id='catalogMenu-container' class='catalogMenu-container'></div>");
            $("<div id='catalogMenu-container' class='catalogMenu-container'></div>").insertBefore(".catalogMenu-wrapper .startMenuForMob");
            catalogMenu_wrapper.find("#catalogMenu-container").load("/standalone/CatalogMenu.ashx?lng=" + getLanguage());
            waitForLoad(".catalogMenu-lvl_1", catalogMenu.ready, 10, 500);
        }
        else {
            catalogMenu.ready(event);
            if (!catalogMenu_wrapper[0].getAttribute("data-firstloadmenu")) {
                catalogMenu_wrapper[0].setAttribute("data-firstloadmenu", "no");
            }
            waitForLoad(".catalogMenu-lvl_1", ff, 10, 100);
            function ff() {
                window.catalogMenu.setActivelvl(catalogMenu_wrapper[0].querySelector(".item_lvl_1"), "2");
            }
        }
    }
    else {
        searchMobActive("close");
        catalogMenu.ready(event, catalogMenu_wrapper);
        catalogMenu_wrapper[0].querySelector(".startMenuForMob").style.height = window.innerHeight + "px";
        // document.querySelector("#catalogMenu-container").style.height = (window.innerHeight - 153) + "px";
    }
});

var catalogMenu = {
    menuWrapper: undefined,
    menuContainer: undefined,
    listLvl_1: undefined,
    showMore: undefined,
    hideMore: undefined,
    ready: function (e, catalogMenu_wrapper) {
        var wrapperBCR,
            self = window.catalogMenu;
        self.showMore = getLanguageTag('showMoreCatMenuItems');
        self.hideMore = getLanguageTag('hideMoreCatMenuItems');
        if (self.menuContainer == undefined) {
            self.menuWrapper = document.getElementById("divCatalogMenu");
            self.menuContainer = document.getElementById("catalogMenu-container");
            /*if(self.menuContainer.getElementsByClassName("catalogMenu-lvl_1").length) {
                  self.listLvl_1 = self.menuContainer.getElementsByClassName("catalogMenu-lvl_1")[0];
            }
            else {
                  self.listLvl_1 = null;
            }*/
        }
        if (!e) {
            self.menuWrapper.classList.add("opened");
            if (getMQ("min-width", "lg")/*  && document.querySelector(".header_rowToSlide.slidingOnBigScreen") */) {
                // document.body.classList.add("catalogMenuOpened");
                document.documentElement.classList.add("catalogMenuOpened");
            }
            if (getMQ("max-width", "md")) {
                document.querySelector(".headerMain-row_2 > .wrapperDefault_inner").classList.remove("profile-userMenu-opened");
                document.documentElement.classList.add("startMenuOpened");
                self.menuWrapper.querySelector(".startMenuForMob").style.top = window.scrollY + "px";
                self.menuWrapper.querySelector(".startMenuForMob-close").style.top = window.scrollY - 23 + "px";
            }
        }
        else {
            if (e.target.classList.contains("headerMain-barsCnt-link") || e.target.parentNode.classList.contains("headerMain-barsCnt-link")) {
                document.querySelector(".headerMain-row_2 > .wrapperDefault_inner").classList.remove("profile-userMenu-opened");
                if (getMQ("max-width", "md")) {
                    if (document.documentElement.classList.contains("startMenuOpened")) {
                        self.reset(true);
                    }
                    else {

                        self.menuWrapper.classList.toggle("opened")
                        document.documentElement.classList.toggle("startMenuOpened");
                        self.menuWrapper.querySelector(".startMenuForMob").style.top = window.scrollY + "px";
                        self.menuWrapper.querySelector(".startMenuForMob-close").style.top = window.scrollY - 23 + "px";
                        if (!self.menuWrapper.classList.contains("opened")) {
                            self.reset();
                        }
                    }
                }
                else {
                    self.menuWrapper.classList.toggle("opened");
                    if (!self.menuWrapper.classList.contains("opened")) {
                        self.reset();
                        document.documentElement.classList.remove("catalogMenuOpened");
                    }
                    if (getMQ("min-width", "lg")/*  && document.querySelector(".header_rowToSlide.slidingOnBigScreen") */) {
                        // document.body.classList.add("catalogMenuOpened");
                        document.documentElement.classList.add("catalogMenuOpened");
                    }
                }
            }
        }
        if (getMQ("min-width", "lg")) {
            if (self.menuWrapper.classList.contains("opened")) {
                self.menuWrapper.classList.remove("loading");
                window.catalogMenu.setClasseslvls();

                if (!self.menuWrapper.getAttribute("data-firstloadmenu")) {
                    var itemsLvl_1 = self.menuContainer.getElementsByClassName("item_lvl_1");
                    for (var i = 0, k = itemsLvl_1.length; i < k; i++) {
                        (function (t) {
                            t.onmouseenter = function () { menter(t) };
                            t.onmouseleave = function () { mleave(t) };
                        })(itemsLvl_1[i]);
                    }

                    var timerMenterId = 0;
                    var timerMleaveId = 0;

                    function menter(item) {
                        fnDelay(function () {
                            window.catalogMenu.setActivelvl(item, "2");
                        }, 200);
                    }
                    function mleave(item) {
                        // console.log("mleave ", item);
                    }
                    var fnDelay = function () {
                        var timer = 0;
                        return function (callback, ms) {
                            clearTimeout(timer);
                            timer = setTimeout(callback, ms);
                        };
                    }();
                }
            }
        }
        else {
            var catalogMenu_container = catalogMenu_wrapper.find("#catalogMenu-container");
            if (catalogMenu_container.length == 0) {
                document.querySelector(".startMenuForMob-nav-catalog").classList.add("loading");
                $("<div id='catalogMenu-container' class='catalogMenu-container'></div>").insertBefore(".catalogMenu-wrapper .startMenuForMob");
                catalogMenu_wrapper.find("#catalogMenu-container").load("/standalone/CatalogMenu.ashx?lng=" + getLanguage());
                waitForLoad(".catalogMenu-lvl_1", window.catalogMenu.setClasseslvls, 10, 500);
            }
            else {
                if (getMQ("max-width", "md")) {
                    self.menuContainer.style.top = window.scrollY - 0 + "px";
                    self.menuContainer.parentNode.querySelector(".headerMain-barsCnt-link").style.top = window.scrollY - 0 + "px";
                }
            }
        }
        window.catalogMenu.setActivelvl();
    },
    setActivelvl: function (menuItem, lvl, dir) {
        var self = this;
        if (lvl == 2 && menuItem.getAttribute("data-id") && $(menuItem).find("ul").length == 0) {
            $.get("/standalone/CatalogMenu.ashx",
                { "lng": getLanguage(), "categoryId": $(menuItem).attr("data-id") },
                function (html) {
                    $(menuItem).append(html);
                    $(menuItem).addClass("innerCatsLoaded");
                    setTimeout(function () {
                        f();
                    }, 100);
                });
        }
        else {
            f();
        }
        function f() {
            self.menuWrapper = document.getElementById("divCatalogMenu");
            self.menuContainer = document.getElementById("catalogMenu-container");
            if (self.menuContainer.getElementsByClassName("catalogMenu-lvl_1").length) {
                self.listLvl_1 = self.menuContainer.getElementsByClassName("catalogMenu-lvl_1")[0];
            }
            else {
                self.listLvl_1 = null;
            }

            self.menuContainer.className = "catalogMenu-container";
            if (lvl) {
                self.menuContainer.classList.add("lvl_" + lvl);
            }
            /*if(menuItem) {
                  menuItem.classList.add("active");
            }*/
            if (getMQ("max-width", "md")) {
                if (!self.listLvl_1) return;
                var _dir = dir ? dir : "in";
                var listLvl_1 = self.listLvl_1;
                var firstLevelItems = listLvl_1.children,
                    firstLevelActive_old = listLvl_1.querySelector(".item_lvl_1.active"),
                    firstLevelActive = undefined;

                if (menuItem) {
                    firstLevelActive = menuItem;
                    /*
                    if(firstLevelActive_old) {
                          firstLevelActive_old.classList.remove("active");
                    }
                    */
                    if (_dir == undefined || _dir == "in") {
                        firstLevelActive.classList.add("active");
                    }
                    else if (_dir == "out") {
                        firstLevelActive.classList.remove("active");
                        self.menuContainer.className = "catalogMenu-container";
                        if (lvl) {
                            self.menuContainer.classList.add("lvl_" + (lvl - 1));

                            /*if ((lvl - 1) == 1) {
                                  self.menuContainer.style.width = "auto";
                                  self.menuContainer.style.height = "auto";
                            }*/
                        }
                        firstLevelActive = $(firstLevelActive).closest(".active")[0];
                    }
                }
                // catalogMenu.smallMenuAction();
            }
            else if (getMQ("min-width", "lg")) {
                var listLvl_1 = self.listLvl_1;
                var firstLevelItems = listLvl_1.children,
                    firstLevelActive_old = listLvl_1.querySelector(".item_lvl_1.active"),
                    firstLevelActive = undefined;

                if (menuItem) {

                    firstLevelActive = menuItem;
                    if (firstLevelActive_old) {
                        firstLevelActive_old.classList.remove("active");
                    }
                    firstLevelActive.classList.add("active");
                }
                else {
                    var firstLevelActive_new = listLvl_1.querySelector("li:first-child"),
                        firstLevelActive = firstLevelActive_new;

                    if (firstLevelActive_old) {
                        firstLevelActive_old.classList.remove("active");
                    }
                    if (firstLevelActive_new) {
                        firstLevelActive.classList.add("active");
                    }
                }
            }

            self.setStuctActiveItem(firstLevelActive);

            if (getMQ("min-width", "lg")) {
                if (self.menuWrapper.classList.contains("opened")) {
                    window.catalogMenu.msnr();
                    self.setSizeMenuContainer(firstLevelActive);
                }
            }
        }
    },
    setStuctActiveItem: function (activeItem) {
        if ((activeItem == undefined)/* || activeItem.classList.contains("structed")*/) return;

        activeItem.classList.add("structed")

        var lists = activeItem.getElementsByTagName("ul");
        for (var i = 0, k = lists.length; i < k; i++) {
            if (lists[i].parentNode.classList.contains("active") && lists[i].parentNode.classList.contains("item_lvl_1")) {
                lists[i].classList.add("catalogMenu-lvl_2");
            }
            if (true || getMQ("max-width", "md")) {
                lists[i].parentNode.classList.add("hasInnerLvl");
            }
            /*else {
                  if(lists[i].getElementsByTagName("ul").length == 0 && !lists[i].parentNode.parentNode.classList.contains("catalogMenu-lvl_2")) {
                         lists[i].classList.add("catalogMenu-lvl_last");
                         lists[i].parentNode.classList.add("hasInnerLvl");
                         continue;
                  }
            }*/
            /* if (lists[i].getElementsByTagName("ul").length == 0 && !lists[i].parentNode.parentNode.classList.contains("catalogMenu-lvl_2")) {
                lists[i].classList.add("catalogMenu-lvl_last");
                lists[i].parentNode.classList.add("hasInnerLvl");
                continue;
            } */
        }
        this.setClasseslvls();
    },
    setClasseslvls: function () {
        var self = window.catalogMenu;
        var itemsMoreThenQ = 6;
        self.menuWrapper = document.getElementById("divCatalogMenu");
        self.menuContainer = document.getElementById("catalogMenu-container");

        /* if (getMQ("max-width", "sm")) {
            self.menuContainer.style.top = window.scrollY + "px";
        } */

        if (self.menuContainer.getElementsByClassName("catalogMenu-lvl_1").length) {
            self.listLvl_1 = self.menuContainer.getElementsByClassName("catalogMenu-lvl_1")[0];
        }
        else {
            self.listLvl_1 = null;
        }

        if (getMQ("max-width", "md")) {
            document.getElementsByClassName("startMenuForMob-nav-catalog")[0].classList.remove("loading");
        }
        var items = catalogMenu.listLvl_1.getElementsByTagName("li");
        for (var i = 0, k = items.length; i < k; i++) {
            if (items[i].tagName.toLowerCase() == "li" && items[i].parentNode.classList.contains("catalogMenu-lvl_1")) {
                items[i].classList.add("item_lvl_1");
                items[i].querySelector("a").classList.add("lnk_lvl");
                items[i].querySelector("a").classList.add("lnk_lvl_1");
            }
            else if (items[i].tagName.toLowerCase() == "li" && items[i].parentNode.classList.contains("catalogMenu-lvl_2")) {
                items[i].classList.add("item_lvl_2");
                items[i].querySelector("a").classList.add("lnk_lvl");
                items[i].querySelector("a").classList.add("lnk_lvl_2");
            }

            else {
                continue;
            }
        }
        for (var i = 0, k = items.length; i < k; i++) {
            if (items[i].tagName.toLowerCase() == "li" && items[i].classList.contains("item_lvl_2")) {
                if (items[i].querySelector("ul")) {
                    items[i].querySelector("ul").classList.add("catalogMenu-lvl_3");
                }
            }
        }

        for (var i = 0, k = items.length; i < k; i++) {
            if (items[i].tagName.toLowerCase() == "li" && items[i].parentNode.classList.contains("catalogMenu-lvl_3")) {
                items[i].classList.add("item_lvl_3");

                if (!items[i].parentNode.classList.contains("checked") && getMQ("min-width", "lg")) {
                    let ULlvl_3 = items[i].parentNode;
                    ULlvl_3.classList.add("checked");
                    let itemsLvl3 = ULlvl_3.childNodes;
                    if (itemsLvl3.length > itemsMoreThenQ) {
                        var showMoreItems = "<div class='catalogMenu-showMoreItems'><span class='show'>" + self.showMore + "</span><span class='hide'>" + self.hideMore + "</span></div>";
                        for (let i = itemsMoreThenQ, j = itemsLvl3.length; i < j; i++) {
                            itemsLvl3[i].classList.add("hidden");
                        }
                        ULlvl_3.insertAdjacentHTML("afterEnd", showMoreItems);
                    }
                    window.catalogMenu.msnr();
                    window.catalogMenu.setSizeMenuContainer();
                }
            }
            if (items[i].classList.contains("item_lvl_3")) {
                if (items[i].classList.contains("hasInnerLvl")) {
                    items[i].querySelector("a").classList.add("lnk_lvl");
                    items[i].querySelector("a").classList.add("lnk_lvl_3");
                    items[i].classList.remove("positioned-ptr");
                    // items[i].querySelector(".catalogMenu-lvl_last").removeAttribute("style");
                    // items[i].querySelector(".catalogMenu-lvl_last").classList.remove("positioned-list");

                    /*if (getMQ("min-width", "xl")) {
                          items[i].addEventListener("mouseenter", function () { setUlPostion(event, this) }, false);
                    }
                    if (getMQ("min-width", "sm") && getMQ("max-width", "lg")) {
                          items[i].addEventListener("click", function () { setUlPostion(event, this) }, false);
                    }*/
                }
            }
        }
        /*function setUlPostion(e, sender) {
              var ulLvlLast = sender.getElementsByClassName("catalogMenu-lvl_last")[0];
              var container = document.getElementById("catalogMenu-container");
              var containerBottom = container.getBoundingClientRect().bottom;
              var availSpaceToBottom = containerBottom - event.clientY;
              var containerLeft = container.getBoundingClientRect().left;
              var itemLvl2_offsetLeft = sender.parentNode.parentNode.offsetLeft;
              var catalogMenuLvl2_offsetLeft = sender.parentNode.parentNode.parentNode.offsetLeft;

              if (container.clientWidth - (itemLvl2_offsetLeft + catalogMenuLvl2_offsetLeft + sender.querySelector(".lnk_lvl_3 span").clientWidth) > ulLvlLast.clientWidth) {
                     sender.classList.add("positioned-ptr");
                     ulLvlLast.style.left = sender.querySelector(".lnk_lvl_3 span").clientWidth + 23 + "px";
                     ulLvlLast.classList.add("positioned-list");
              }
              if (availSpaceToBottom < ulLvlLast.clientHeight) {
                     ulLvlLast.style.top = (ulLvlLast.clientHeight - availSpaceToBottom - event.offsetY - 25) * -1 + "px";
              }
        }*/
    },
    setSizeMenuContainer: function (activeItem) {
        console.log("setSizeMenuContainer");
        var row = this.menuWrapper.parentNode,
            up = row.querySelector(".headerMain-userPnl");

        if (getMQ("min-width", "lg")) {
            // menuContainer.style.width = (row.clientWidth - (up.clientWidth + (row.clientWidth * 3 / 100))) - 15 + "px";
            this.menuContainer.style.width = row.clientWidth + "px";
        }

        if (activeItem) {
            /*if (getMQ("max-width", "sm")) {
                  if (this.menuContainer.clientHeight < (activeItem.querySelector("ul").clientHeight + 85)) {
                         this.menuContainer.style.height = activeItem.querySelector("ul").clientHeight + 85 + "px";
                  }
            }*/

            if (getMQ("min-width", "lg")) {
                var lvl2List = activeItem.getElementsByClassName("catalogMenu-lvl_2")[0];
                /*var lis = lvl2List.childNodes;
                for (var i = 0, k = lis.length, h = 0; i < k; i++) {
                      if (lis[i].nodeType != 1) continue;
                      if (h < lis[i].clientHeight + lis[i].offsetTop) {
                             h = lis[i].clientHeight + lis[i].offsetTop;
                      }
                }*/
                var self = this;
                setTimeout(function () {
                    if (lvl2List) {
                        let h = activeItem.parentNode.clientHeight > lvl2List.clientHeight ? activeItem.parentNode.clientHeight : lvl2List.clientHeight;
                        self.menuContainer.style.height = h + 25 + "px";
                    }
                    // self.menuContainer.style.minHeight = activeItem.parentNode.clientHeight + 25 + "px";
                }, 100);
            }
        }
    },
    smallMenuAction: function () {
        var smallMenu = this.menuWrapper.querySelector(".catalogMenu-smallMenu");
        if (!smallMenu) return;
        if (getMQ("max-width", "md")) {
            var menuContainer = this.menuContainer,
                timeid1 = 0,
                timeid2 = 0;

            if (smallMenu) {
                clearTimeout(timeid1);
                clearTimeout(timeid2);
                if (this.menuWrapper.classList.contains("opened")) {
                    if (menuContainer.classList.contains("lvl_1") || menuContainer.className.split(" ").length == 1) {
                        timeid = setTimeout(function () {
                            smallMenu.style.top = menuContainer.clientHeight + 50 + "px";
                            timeid2 = setTimeout(function () {
                                smallMenu.classList.remove("d-none");
                            }, 500);
                        }, 2000);
                    }
                    else {
                        smallMenu.classList.add("d-none");
                        smallMenu.removeAttribute("style");
                    }
                }
                else {
                    smallMenu.classList.add("d-none");
                    smallMenu.removeAttribute("style");
                }
            }
        }
        else {
            smallMenu.classList.add("d-none");
            smallMenu.removeAttribute("style");
        }
    },
    catalogMenuOnMob: function () {
        var div = document.getElementById("divCatalogMenu");
        if (!div.classList.contains("catalogMenuOnMobActive")) {
            div.classList.add("catalogMenuOnMobActive");
        }
        else {
            div.classList.remove("catalogMenuOnMobActive");
            this.reset(true);
        }
    },
    reset: function (resetToStartMenu) {
        if ((typeof options === 'undefined') && !resetToStartMenu) {
            this.menuWrapper.classList.remove("opened");
            this.menuContainer.className = "catalogMenu-container";
            this.menuContainer.removeAttribute("style");
            document.documentElement.classList.remove("startMenuOpened");
        }
        this.menuWrapper.classList.remove("catalogMenuOnMobActive");
        var actives = this.listLvl_1.querySelectorAll(".active");
        if (actives.length) {
            for (var i = actives.length - 1; i >= 0; i--) {
                (function (a) {
                    a.classList.remove("active");
                })(actives[i]);
            }
        }
        if (resetToStartMenu) {
            this.menuContainer.className = "catalogMenu-container";
        }
    },
    msnr: function () {
        if (typeof window.Masonry != "function") {
            addScript("/js/masonry.pkgd.min.js", waitForLoad(".item_lvl_1.active .catalogMenu-lvl_2", msnrLoaded, 20, 300));
        }
        else {
            // waitForLoad(".item_lvl_1.active .catalogMenu-lvl_2", msnrLoaded, 20, 150);
            new Promise((resolve, reject) => {
                if (document.querySelector(".item_lvl_1.active .catalogMenu-lvl_2")) {
                    resolve();
                }
            }).then(() => {
                msnrLoaded();
            })
        }

        // addScript("/js/masonry.pkgd.min.js", msnrLoaded);

        function msnrLoaded() {
            // console.log("msnrLoaded");
            var $msnryCont = $(document.querySelector(".item_lvl_1.active .catalogMenu-lvl_2"));
            console.log($msnryCont);
            /* var $stamp = $msnryCont.find('.stamp');
            if($stamp.length) {
                 $msnryCont.masonry( 'stamp', $stamp );	
            } */

            $msnryCont.on('layoutComplete', window.catalogMenu.setSizeMenuContainer(document.querySelector(".item_lvl_1.active")));
            $msnryCont.masonry({ transitionDuration: 0 });
        }
    },
    showHiddenItems: function (sender, action) {
        var msnryCont = $(document.querySelector(".item_lvl_1.active .catalogMenu-lvl_2"));
        if (action == "show") {
            let hiddenItems = sender.closest("li").querySelectorAll(".catalogMenu-lvl_inner .hidden");

            if (hiddenItems.length) {
                hiddenItems.forEach((item, index) => {
                    item.classList.add("shown");

                    msnryCont.masonry("layout");
                    if (index >= hiddenItems.length - 1) {
                        setTimeout(function () {
                            hiddenItems.forEach((item, index) => {
                                item.classList.add("visible");
                            });
                            catalogMenu.msnr();
                        }, 300);
                    }
                })
            }
        }
        else if (action == "hide") {
            let shownItems = sender.closest("li").querySelectorAll(".catalogMenu-lvl_inner .shown");

            if (shownItems.length) {
                shownItems.forEach((item, index) => {
                    item.classList.remove("visible");

                    if (index >= shownItems.length - 1) {
                        setTimeout(function () {
                            shownItems.forEach((item, index) => {
                                item.classList.remove("shown");
                                msnryCont.masonry("layout");
                            })
                        }, 300);
                    }
                })
            }
        }
    }
};

/* var headerMainSliding = {
    headerMain: "undefined",
    init: function () {
        if (this.headerMain == "undefined") {
            this.headerMain = document.querySelector(".headerMain");
        }
        this.status();
    },
    onscroll: function () {
        this.status();
    },
    status: function () {
        if (window.scrollY >= this.headerMain.clientHeight) {
            if (!this.headerMain.classList.contains("sliding")) {
                setTimeout(function () {
                    window.headerMainSliding.headerMain.classList.add("sliding");
                }, 250);
            }
        }
        else {
            if (window.scrollY <= 0) {
                if (this.headerMain == "undefined") {
                    this.headerMain = document.querySelector(".headerMain");
                }
                this.headerMain.classList.remove("sliding");
                this.headerMain.querySelector(".container-fluid_wrapper").removeAttribute("style");
            }
        }
    }
}; */

String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

var isCatsSearchAutocomplete = false, isProdsSearchAutocomplete = false;
$("input[type='search']").autocomplete({
    delay: 400,
    minLength: 2,
    source: function (request, response) {
        $.ajax({
            url: "/handlers/SearchHelper.ashx?lng=" + window.getLanguage(),
            dataType: "json",
            data: {
                term: request.term
            },
            success: function (data) {
                var qCatsAllowed = 5, qProdsAllowed = 10;
                var qCatsInData = 0, qProdsInData = 0;
                var qCatsInDataRE = 0, qProdsInDataRE = 0;
                var qCatsInDataRE_0 = 0, qProdsInDataRE_0 = 0;
                var qCatsInDataAfterSplice = 0, qProdsInDataAfterSplice = 0;
                var dataCopy = [];
                var qCatsCopied = 0, qCatsCopiedRE = 0, qCatsCopiedRE_0 = 0;
                var qProdsCopied = 0, qProdsCopiedRE = 0, qProdsCopiedRE_0 = 0;

                var self = this;
                var re = new RegExp(request.term, "gi");
                var resultSearchRE;
                for (var i = 0, k = data.length; i < k; i++) {
                    if (data[i]) {
                        resultSearchRE = data[i].label.search(re);

                        if ("itemType" in data[i]) {
                            qCatsInData++;
                            if (resultSearchRE != -1) {
                                qCatsInDataRE++;
                                if (resultSearchRE == 0) {
                                    qCatsInDataRE_0++;
                                }
                            }
                        }
                        else {
                            qProdsInData++;
                            if (resultSearchRE != -1) {
                                qProdsInDataRE++;
                                if (resultSearchRE == 0) {
                                    qProdsInDataRE_0++;
                                }
                            }
                        }
                    }
                }

                for (var i = 0, k = data.length; i < k; i++) {
                    if (data[i]) {
                        resultSearchRE = data[i].label.search(re);
                        if (qCatsInData > 0) {
                            // вывод категорий
                            if ("itemType" in data[i]) {

                                if (resultSearchRE != -1) {
                                    if (resultSearchRE == 0) { // совпадение с ПЕРВОГО символа
                                        if (qCatsInDataRE_0 > 0) {
                                            if (qCatsInDataRE_0 >= qCatsAllowed) {
                                                if (qCatsCopied < qCatsAllowed) {
                                                    dataCopy.splice(qCatsCopiedRE_0, 0, data[i]);
                                                    qCatsCopied++;
                                                    qCatsCopiedRE_0++;
                                                }
                                            }
                                            else {
                                                if (qCatsCopied < qCatsAllowed) {
                                                    dataCopy.splice(qCatsCopiedRE_0, 0, data[i]);
                                                    qCatsCopied++;
                                                    qCatsCopiedRE_0++;
                                                }
                                            }
                                        }
                                    }
                                    else { //  // совпадение с НЕ ПЕРВОГО символа resultSearchRE > 0
                                        if (qCatsInDataRE_0 > 0) {
                                            if (qCatsInDataRE_0 >= qCatsAllowed) {
                                                continue;
                                            }
                                            else {
                                                // еще не все qCatsInDataRE_0 добавлены
                                                if (qCatsCopiedRE_0 < qCatsInDataRE_0) {
                                                    if ((qCatsAllowed - qCatsCopied) > (qCatsInDataRE_0 - qCatsCopiedRE_0)) {
                                                        if (qCatsCopied < qCatsAllowed) {
                                                            dataCopy.splice(qCatsCopiedRE + qCatsCopiedRE_0, 0, data[i]);
                                                            qCatsCopied++;
                                                            qCatsCopiedRE++;
                                                        }
                                                    }
                                                }
                                                // уже все qCatsInDataRE_0 добавлены
                                                else {
                                                    if (qCatsCopied < qCatsAllowed) {
                                                        dataCopy.splice(qCatsCopiedRE + qCatsCopiedRE_0, 0, data[i]);
                                                        qCatsCopied++;
                                                        qCatsCopiedRE++;
                                                    }
                                                }
                                            }
                                        }
                                        else { // qCatsInDataRE_0 < 0
                                            if (qCatsCopied < qCatsAllowed) {
                                                dataCopy.push(data[i]);
                                                qCatsCopied++;
                                                qCatsCopiedRE++;
                                            }
                                        }
                                    }
                                }
                                // нет совпадения
                                else { // resultSearchRE == -1
                                    if (qCatsInDataRE > 0) {
                                        if (qCatsInDataRE >= qCatsAllowed) {
                                            continue;
                                        }
                                        else {
                                            // еще не все qCatsInDataRE добавлены
                                            if (qCatsCopied < qCatsInDataRE) {
                                                if ((qCatsAllowed - qCatsCopied) > (qCatsInDataRE - qCatsCopied)) {
                                                    if (qCatsCopied < qCatsAllowed) {
                                                        dataCopy.push(data[i]);
                                                        qCatsCopied++;
                                                    }
                                                }
                                            }
                                            // уже все qCatsInDataRE_0 добавлены
                                            else {
                                                if (qCatsCopied < qCatsAllowed) {
                                                    dataCopy.push(data[i]);
                                                    qCatsCopied++;
                                                }
                                            }
                                        }
                                    }
                                    else if (qCatsCopied < qCatsAllowed) {
                                        dataCopy.push(data[i]);
                                        qCatsCopied++;
                                    }
                                }
                            }
                            // вывод товаров ПОСЛЕ категорий
                            else {
                                if (resultSearchRE != -1) {
                                    if (resultSearchRE == 0) { // совпадение с ПЕРВОГО символа
                                        if (qProdsInDataRE_0 > 0) {
                                            if (qProdsInDataRE_0 >= qProdsAllowed) {
                                                if (qProdsCopied < qProdsAllowed) {
                                                    dataCopy.splice(qCatsCopied + qProdsCopiedRE_0, 0, data[i]);
                                                    qProdsCopied++;
                                                    qProdsCopiedRE_0++;
                                                }
                                            }
                                            else {
                                                if (qProdsCopied < qProdsAllowed) {
                                                    dataCopy.splice(qCatsCopied + qProdsCopiedRE_0, 0, data[i]);
                                                    qProdsCopied++;
                                                    qProdsCopiedRE_0++;
                                                }
                                            }
                                        }
                                    }
                                    else { //  // совпадение с НЕ ПЕРВОГО символа resultSearchRE > 0
                                        if (qProdsInDataRE_0 > 0) {
                                            if (qProdsInDataRE_0 >= qProdsAllowed) {
                                                continue;
                                            }
                                            else {
                                                // еще не все qProdsInDataRE_0 добавлены
                                                if (qProdsCopiedRE_0 < qProdsInDataRE_0) {
                                                    if ((qProdsAllowed - qProdsCopied) > (qProdsInDataRE_0 - qProdsCopiedRE_0)) {
                                                        if (qProdsCopied < qProdsAllowed) {
                                                            dataCopy.splice(qCatsCopied + qProdsCopiedRE + qProdsCopiedRE_0, 0, data[i]);
                                                            qProdsCopied++;
                                                            qProdsCopiedRE++;
                                                        }
                                                    }
                                                }
                                                // уже все qProdsInDataRE_0 добавлены
                                                else {
                                                    if (qProdsCopied < qProdsAllowed) {
                                                        dataCopy.splice(qCatsCopied + qProdsCopiedRE + qProdsCopiedRE_0, 0, data[i]);
                                                        qProdsCopied++;
                                                        qProdsCopiedRE++;
                                                    }
                                                }
                                            }
                                        }
                                        else { // qProdsInDataRE_0 < 0
                                            if (qProdsCopied < qProdsAllowed) {
                                                dataCopy.push(data[i]);
                                                qProdsCopied++;
                                                qProdsCopiedRE++;
                                            }
                                        }
                                    }
                                }
                                // нет совпадения
                                else { // resultSearchRE == -1
                                    if (qProdsInDataRE > 0) {
                                        if (qProdsInDataRE >= qProdsAllowed) {
                                            continue;
                                        }
                                        else {
                                            // еще не все qProdsInDataRE добавлены
                                            if (qProdsCopied < qProdsInDataRE) {
                                                if ((qProdsAllowed - qProdsCopied) > (qProdsInDataRE - qProdsCopied)) {
                                                    if (qProdsCopied < qProdsAllowed) {
                                                        dataCopy.push(data[i]);
                                                        qProdsCopied++;
                                                    }
                                                }
                                            }
                                            // уже все qProdsInDataRE_0 добавлены
                                            else {
                                                if (qProdsCopied < qProdsAllowed) {
                                                    dataCopy.push(data[i]);
                                                    qProdsCopied++;
                                                }
                                            }
                                        }
                                    }
                                    else if (qProdsCopied < qProdsAllowed) {
                                        dataCopy.push(data[i]);
                                        qProdsCopied++;
                                    }
                                }
                            }
                        }
                        // вывод товаров БЕЗ катерогий
                        else {
                            if (resultSearchRE != -1) {
                                if (resultSearchRE == 0) { // совпадение с ПЕРВОГО символа
                                    if (qProdsInDataRE_0 > 0) {
                                        if (qProdsInDataRE_0 >= qProdsAllowed) {
                                            if (qProdsCopied < qProdsAllowed) {
                                                dataCopy.splice(qCatsCopied + qProdsCopiedRE_0, 0, data[i]);
                                                qProdsCopied++;
                                                qProdsCopiedRE_0++;
                                            }
                                        }
                                        else {
                                            if (qProdsCopied < qProdsAllowed) {
                                                dataCopy.splice(qCatsCopied + qProdsCopiedRE_0, 0, data[i]);
                                                qProdsCopied++;
                                                qProdsCopiedRE_0++;
                                            }
                                        }
                                    }
                                }
                                else { //  // совпадение с НЕ ПЕРВОГО символа resultSearchRE > 0
                                    if (qProdsInDataRE_0 > 0) {
                                        if (qProdsInDataRE_0 >= qProdsAllowed) {
                                            continue;
                                        }
                                        else {
                                            // еще не все qProdsInDataRE_0 добавлены
                                            if (qProdsCopiedRE_0 < qProdsInDataRE_0) {
                                                if ((qProdsAllowed - qProdsCopied) > (qProdsInDataRE_0 - qProdsCopiedRE_0)) {
                                                    if (qProdsCopied < qProdsAllowed) {
                                                        dataCopy.splice(qCatsCopied + qProdsCopiedRE + qProdsCopiedRE_0, 0, data[i]);
                                                        qProdsCopied++;
                                                        qProdsCopiedRE++;
                                                    }
                                                }
                                            }
                                            // уже все qProdsInDataRE_0 добавлены
                                            else {
                                                if (qProdsCopied < qProdsAllowed) {
                                                    dataCopy.splice(qCatsCopied + qProdsCopiedRE + qProdsCopiedRE_0, 0, data[i]);
                                                    qProdsCopied++;
                                                    qProdsCopiedRE++;
                                                }
                                            }
                                        }
                                    }
                                    else { // qProdsInDataRE_0 < 0
                                        if (qProdsCopied < qProdsAllowed) {
                                            dataCopy.push(data[i]);
                                            qProdsCopied++;
                                            qProdsCopiedRE++;
                                        }
                                    }
                                }
                            }
                            // нет совпадения
                            else { // resultSearchRE == -1
                                if (qProdsInDataRE > 0) {
                                    if (qProdsInDataRE >= qProdsAllowed) {
                                        continue;
                                    }
                                    else {
                                        // еще не все qProdsInDataRE добавлены
                                        if (qProdsCopied < qProdsInDataRE) {
                                            if ((qProdsAllowed - qProdsCopied) > (qProdsInDataRE - qProdsCopied)) {
                                                if (qProdsCopied < qProdsAllowed) {
                                                    dataCopy.push(data[i]);
                                                    qProdsCopied++;
                                                }
                                            }
                                        }
                                        // уже все qProdsInDataRE_0 добавлены
                                        else {
                                            if (qProdsCopied < qProdsAllowed) {
                                                dataCopy.push(data[i]);
                                                qProdsCopied++;
                                            }
                                        }
                                    }
                                }
                                else if (qProdsCopied < qProdsAllowed) {
                                    dataCopy.push(data[i]);
                                    qProdsCopied++;
                                }
                            }
                        }
                    }
                }

                response(dataCopy);
            }
        });
    },
    select: function (event, ui) { document.location = ui.item.url },
    open: function () { document.body.classList.add("autocompleteList-open"); isCatsSearchAutocomplete = false; isProdsSearchAutocomplete = false },
    close: function () { document.body.classList.remove("autocompleteList-open"); isCatsSearchAutocomplete = false; isProdsSearchAutocomplete = false }
}).autocomplete("instance")._renderItem = function (ul, item) {
    var catеgoryCls = (item.itemType == "category" ? "headerMain-search-item-category" : ""),
        lei = window.getLanguage() == "ro" ? "lei" : "леев",
        catsTitle = window.getLanguage() == "ro" ? "Categorii" : "Категории",
        prodsTitle = window.getLanguage() == "ro" ? "Mărfuri" : "Товары",
        li;


    if (item.itemType == "category") {
        if (!isCatsSearchAutocomplete) {
            isCatsSearchAutocomplete = true;
            li = $("<li class='headerMain-search-item headerMain-search-item-title'><span class='headerMain-search-item-title-inner'>" + catsTitle + "</span></li>");
            ul.append(li);
        }
    }

    // Выделяем поисковый запрос болдом в резалтах
    var self = this;
    var re = new RegExp(self.term, "gi");
    var resultSearchRE = item.label.search(re);
    var itemLabel = "";
    if (resultSearchRE != -1) {
        if (resultSearchRE == 0) {
            itemLabel = item.label.replace(self.term.capitalizeFirstLetter(), "<b>" + self.term.capitalizeFirstLetter() + "</b>");
        }
        else {
            itemLabel = item.label.replace(self.term, "<b>" + self.term + "</b>");
        }
    }
    else {
        itemLabel = item.label;
    }
    // /Выделяем поисковый запрос болдом в резалтах


    li = $("<li class='headerMain-search-item " + catеgoryCls + "'><a href='" + item.url + "' class='headerMain-search-item-inner'></a></li>");

    li.find(".headerMain-search-item-inner").append("<span class='headerMain-search-item-txt'>" + itemLabel + "</span>");

    if (item.itemType != "category") {
        if (isCatsSearchAutocomplete && !isProdsSearchAutocomplete) {
            isProdsSearchAutocomplete = true;
            li = $("<li class='headerMain-search-item headerMain-search-item-title'><span class='headerMain-search-item-title-inner'>" + prodsTitle + "</span></li>");
            ul.append(li);
        }
        if (item.price) {
            li.find(".headerMain-search-item-inner").append("<span class='headerMain-search-item-price'>" + item.price + "<span class='lei'>" + lei + "</span></span>");
        }
        if (item.img) {
            li.find(".headerMain-search-item-inner").prepend("<span class='headerMain-search-item-img'><img src='" + item.img + "' /></span>");
        }

    }

    ul.append(li);

    let searchPnl = document.querySelector(".searchPnl");

    if (searchPnl) {

        if (getMQ("min-width", "md")) {
            ul.get(0).style.maxWidth = searchPnl.clientWidth + 100 + "px";
        }
        if (getMQ("min-width", "lg")) {
            ul.get(0).style.maxWidth = searchPnl.clientWidth + "px";
        }

    }
    return li;
};

$.each($("[data-autocomplete]"), function () {
    var item = $(this);
    var inputAutocomplete = $(this);
    var isFirstItemGet = false;
    item.autocomplete({
        delay: 200,
        minLength: 0,
        source: getHelperSource(item),
        search: function (event, ui) {
            $(event.target).autocomplete("option", "source", getHelperSource($(event.target)));
        },
        select: function (event, ui) {

            var hiddenName = $(event.target).attr("data-hidden-name");
            if (hiddenName) {
                var form = $(event.target).closest("form");
                var hidden = form.find("[name='" + hiddenName + "']");
                hidden.val(ui.item.id);

                var child = form
                    .find("[data-parent='" + hiddenName + "']");
                if (child.length > 0) {
                    child.val("");
                    hiddenName = child.attr("data-hidden-name");
                    if (hiddenName) {
                        hidden = form.find("[name='" + hiddenName + "']");
                        hidden.val("");
                    }
                }
            }
        },
    })
        .focus(function (event) {
            event.target.setAttribute("value", " ");
            event.target.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
        })
        .autocomplete("instance")._renderItem = function (ul, item) {
            var li = $('<li class="ui-menu-item ' + inputAutocomplete.attr("name") + '" item-id="' + item.id + '"><div tabindex="-1" class="ui-menu-item-wrapper">'
                + item.label
                + '</div>'
                + '</li>');
            if (item.parentName) {
                li.find("div").append(
                    '<small> (' + item.parentName + ')</small>'
                );
            }

            ul.append(li);

            if (!isFirstItemGet) {
                isFirstItemGet = true;
                if (true /* inputAutocomplete[0].getAttribute("data-required") && (inputAutocomplete[0].getAttribute("data-required") === "true") */) {
                    ul.addClass(inputAutocomplete.attr("name"));
                    setTimeout(function () {
                        vld.validAutocompleteField(inputAutocomplete[0], ul);
                    }, 300);
                }
            }

            return li;
        };
});

function getHelperSource(item) {
    var result = "/handlers/Helper.ashx?lng=" + getLanguage() + "&cmd=" + item.attr("data-autocomplete");
    if (item.attr("data-parent")) {
        var parentItem = $("[name='" + item.attr("data-parent") + "']");
        result += "&parentId=" + parentItem.val();
    }
    return result;
}

var lazyLoad = {
    pageload: function () {
        // var slicks = document.querySelectorAll("[class*='-slick']:not(.cards-slickWrapper):not([data-lazyload-onloadpage='false'])");
        var self = this,
            timerId = 0,
            itr = 10; // 1sec

        // this.update(0, document.getElementsByClassName("categoriesList")[0]);

        // if (getMQ("min-width", "md")) {
        //     if (document.querySelectorAll("[class*='-slick']:not(.cards-slickWrapper):not([data-lazyload-onloadpage='false'])").length) {

        //         // checkSlicksLoaded();

        //         function checkSlicksLoaded() {
        //             clearTimeout(timerId);
        //             if ((itr > 0)
        //                 &&
        //                 (slicks.length != document.querySelectorAll("[class*='-slick'].slick-initialized:not(.cards-slickWrapper):not([data-lazyload-onloadpage='false'])").length)
        //             ) {
        //                 itr--;
        //                 timerId = setTimeout(checkSlicksLoaded, 100);
        //             }
        //             /* else {
        //                 for (var i = slicks.length - 1; i >= 0; i--) {
        //                     (function (i) {
        //                         // self.update(0, slicks[i]);
        //                     })(i);
        //                 }
        //             } */
        //         }
        //     }
        // }
        /* else {
            if (slicks.length) {

                for (var i = slicks.length - 1; i >= 0; i--) {
                    (function (i) {
                        // self.update(0, slicks[i]);
                    })(i);
                }
            }
        } */

        this.initIntersectionObserver();
    },
    onscroll: function () {
        window.lazyLoad.check();
    },
    update: function (delay, prnt) {
        var _delay = delay ? delay : 0;
        var self = this;
        /* if (prnt || (typeof options != 'undefined')) {
            setTimeout(function () { self.check(prnt) }, _delay);
        } */
        setTimeout(function () { self.initIntersectionObserver(); }, _delay);
    },
    check: function (prnt) {
        var self = window.lazyLoad;
        var imgs;

        if (prnt) {
            imgs = prnt.querySelectorAll("[data-lazyload='true']")
        }
        else {
            imgs = document.querySelectorAll("[data-lazyload='true']")
        }
        for (var i = 0, k = imgs.length; i < k; i++) {
            if (self.isImgInVP(imgs[i], false)) {
                self.setImg(imgs[i]);
            }
        }
    },
    getSizeBody: function () {
        return document.body.clientWidth;
    },
    setImg: function (img) {
        img.removeAttribute("data-lazyload");
        if (img.parentNode.tagName.toLowerCase() == "picture") {
            var ss = img.parentNode.getElementsByTagName("source");
            for (var i = 0, k = ss.length; i < k; i++) {
                if (!ss[i].getAttribute("data-srcset")) continue;

                ss[i].setAttribute("srcset", ss[i].getAttribute("data-srcset"));
                ss[i].removeAttribute("data-srcset");
            }
        }
        if (img.getAttribute("data-srcset")) {
            img.srcset = img.getAttribute("data-srcset");
            img.removeAttribute("data-srcset");
        }
        if (img.getAttribute("data-src")) {
            img.src = img.getAttribute("data-src");
            img.removeAttribute("data-src");
        }
    },
    isImgInVP: function (img, allImgInVp) {
        /* var imgBCR = img.getBoundingClientRect();
        var _allImgInVp = false;
        var res = false;

        if (allImgInVp) {
            _allImgInVp = allImgInVp ? allImgInVp : false;
        }

        var docViewTop = window.scrollY;
        var docViewBottom = docViewTop + window.innerHeight;

        var imgTop = imgBCR.top + docViewTop;
        var imgBottom = imgTop + imgBCR.height;
        if (
            ((imgTop >= docViewTop) && (imgTop < docViewBottom))
            &&
            ((imgBCR.left >= 0) && (imgBCR.left < this.getSizeBody()))
        ) {
            res = true;
        }

        return res; */
    },
    initIntersectionObserver: function () {
        lazyImages = document.querySelectorAll("[data-lazyload='true']");
        const callback = (entries, observer) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    window.lazyLoad.setImg(entry.target);
                    observer.unobserve(entry.target);
                }
            })
        }

        const options = {
            rootMargin: '0px 0px 0px 0px',
            threshold: 0,
        }

        const observer = new IntersectionObserver(callback, options);

        lazyImages.forEach((image) => observer.observe(image));
    }
}

function waitForLoad(elWhatSrt, callback, itr, timer) {
    var itr = itr ? itr : 20,
        timer = timer ? timer : 500;

    (function repeater() {
        var elWhat = document.querySelector(elWhatSrt);
        if (elWhat) {
            if (callback) {
                if (typeof callback == "function") {
                    return callback();
                }
                else {
                    if (typeof callback == "string") {
                        return eval(callback);
                    }
                }
            }
        }
        else {
            if (itr && (elWhat == undefined)) {
                setTimeout(repeater, timer);
            }
            itr--;
        }
    })(elWhatSrt, callback, itr, timer);
};

function getMQ(query, size) {
    // query, size - опциональные аргументы (работают только в паре)
    let mq = "";
    let ww = window.innerWidth;

    if (query) {
        mq = false;
        if (query == "min-width") {
            if (size == "xs" && (ww >= 320)) {
                mq = true;
            }
            else if (size == "sm" && (ww >= 576)) {
                mq = true;
            }
            else if (size == "md" && (ww >= 768)) {
                mq = true;
            }
            else if (size == "lg" && (ww >= 992)) {
                mq = true;
            }
            else if (size == "xl" && (ww >= 1200)) {
                mq = true;
            }
            else if (size == "xxl" && (ww >= 1400)) {
                mq = true;
            }
            else if (size == "3xl" && (ww >= 1600)) {
                mq = true;
            }
            else if (size == "4xl" && (ww >= 1880)) {
                mq = true;
            }
        }
        else if (query == "max-width") {
            if (size == "sm" && (ww <= 575)) {
                mq = true;
            }
            else if (size == "md" && (ww <= 991)) {
                mq = true;
            }
            else if (size == "lg" && (ww <= 1199)) {
                mq = true;
            }
            else if (size == "xl" && (ww <= 1399)) {
                mq = true;
            }
            else if (size == "xxl" && (ww <= 1599)) {
                mq = true;
            }
            else if (size == "3xl" && (ww <= 1879)) {
                mq = true;
            }
        }
    }
    else {
        if ((ww <= 575)) {
            mq = "xs";
        }
        else if ((ww >= 576) && (ww <= 767)) {
            mq = "sm";
        }
        else if ((ww >= 768) && (ww <= 991)) {
            mq = "md";
        }
        else if ((ww >= 992) && (ww <= 1199)) {
            mq = "lg";
        }
        else if ((ww >= 1200) && (ww <= 1399)) {
            mq = "xl";
        }
        else if ((ww >= 1400) && (ww <= 1599)) {
            mq = "xxl";
        }
        else if ((ww >= 1600) && (ww <= 1879)) {
            mq = "3xl";
        }
        else {
            mq = "4xl";
        }
    }

    return mq;
}

function isValInArr(val, arr) {
    var inArray = false;
    for (var x = 0, y = arr.length; x < y; x++) {
        if (val == arr[x]) {
            inArray = x.toString();
        }
    }
    return inArray;
};
function isValInArr2(val, arr) {
    var inArray = false;
    for (var x = 0, y = arr.length; x < y; x++) {
        let firstLevel = arr[x];
        for (let m = 0, n = firstLevel.length; m < n; m++) {
            if (val == firstLevel[m]) {
                inArray = x.toString();
                break;
            }
        }
    }
    return inArray;
};

function blurPage(dir) {
    if (dir == "in") {
        document.body.classList.add("blured");
    }
    else if (dir == "out") {
        document.body.classList.remove("blured");
    }
}

function overlayedPage(dir) {
    if (dir == "in") {
        document.body.classList.add("overlayed");
    }
    else if (dir == "out") {
        document.body.classList.remove("overlayed");
    }
};

function searchMobActive(dir, closeBtn) {
    var btn = closeBtn ? closeBtn : document.querySelector(".headerMain-search-closeBtn");
    if (dir == "open") {
        $(btn).closest(".headerMain-search")[0].classList.add("expanded");
        document.getElementsByClassName("searchPnl-input")[0].focus();
        document.body.classList.add("searchMobOpened");
    }
    else if (dir == "close") {
        $(btn).closest(".headerMain-search")[0].classList.remove("expanded");
        document.body.classList.remove("searchMobOpened");
    }
}

var langPnl = {
    currLang: undefined,
    slider: undefined,
    init: function () {
        var left;
        if (!this.langPnl) {
            if (getMQ("min-width", "md")) {
                this.langPnl = document.querySelector(".headerMain-lang");
            }
            else {
                this.langPnl = document.querySelector(".startMenuForMob .headerMain-lang");
            }
            this.currLang = this.langPnl.querySelector(".aspNetDisabled");
            this.slider = this.langPnl.querySelector(".headerMain-lang-slider");
        }

        let id = "";
        if (getMQ("min-width", "md")) {
            id = this.currLang.id;
            left = this.currLang.offsetLeft - 1;
        }
        else {
            id = this.currLang.id.replace("Mobile", "");
            if (id.indexOf("Ro") != -1) {
                left = 28;
            }
            else if (id.indexOf("Ru") != -1) {
                left = -1;
            }
        }

        this.slider.classList.remove("hidden");
        this.slider.classList.add("noanim");
        this.slider.style.left = left + "px";
        setTimeout(function () {
            window.langPnl.slider.classList.remove("noanim");
            window.langPnl.slider.parentNode.classList.add("loaded");
        }, 300);
    },
    click: function (lang) {
        let langName = "";
        if (lang.id.indexOf("Ro") != -1) {
            langName = "ro";
        }
        else if (lang.id.indexOf("Ru") != -1) {
            langName = "ru";
        }
        changeLang(langName);
        lang.parentNode.classList.add("moving");
        lang.classList.add("active");
        this.move(lang);
        let id = "";
        if (getMQ("min-width", "md")) {
            id = lang.id;
        }
        else {
            id = lang.id.replace("Mobile", "");
        }
    },
    move: function (lang) {
        this.slider.style.left = lang.offsetLeft + "px";
    }
};

var vld = {
    keyupTimerId: 0,
    keyupDelay: 300,
    /*
    ////////////Example start/////////////////
    <div class="vld-form" data-validate-onload="false" data-btnlinked=".btnSaveNewCarGaraj">
         <div class="oneField-abs oneField_white oneField-w100">
              <div class="innerOneField">
                    <input name="" type="text" value="" data-required="true" pattern="\D{2,}" class="vld-field vld-input" placeholder="name" autocomplete="off" tabindex="0">
              </div>
         </div>
         <div class="oneField-abs oneField_white oneField-w100">
              <div class="innerOneField">
                    <input name="" type="text" value="" maxlength="17"  data-required="true" pattern="^[A-Z0-9]{17}$" class="vld-field vld-input" placeholder="VIN" autocomplete="off" tabindex="0">
              </div>
         </div>
         <div class="oneField-abs oneField_white oneField-w100">
              <div class="innerOneField">
                    <input autocomplete="off" pattern="^[\d]\s\(\d{3}\)\s\d{3}-\d{2}-\d{2}$" class="vld-field vld-input" data-required="true" data-phone-mask="1" placeholder="Телефон" type="tel" name="txtPhone" id="txtPhone" required="required"
              </div>
         </div>

         <div class="oneField-abs oneField-w100">
              <div class="innerOneField">
                    <div class="ddlWrap ddlWrap_white">
                         <select name="ctl00$cphCenter$ddlVendor" class="vld-field vld-select" data-required="true">
                              <option selected="selected" value="0">выбрать</option>
                              <option value="1">Acura</option>
                              <option value="2">Alfa Romeo</option>
                         </select>
                    </div>
              </div>
         </div>

         <div class="btn2-abs btn2-darkMaroon btn-noShadow btn2-noScale w-xxs-100 mt-40 btnSaveNewCarGaraj disabled">
              <input type="submit" value="Добавить автомобиль">
         </div>
    </div>
    /////////////Exampe end////////////////
    */
    init: function (currForm) {
        document.addEventListener("keyup", vldKeyup, false);
        document.addEventListener("input", vldInput, false);
        document.addEventListener("change", vldChange, false);

        function vldKeyup(e) {
            if (e.target.classList.contains("vld-input")) {
                if (e.target.getAttribute("type") == "tel") {
                    memoryForm.init(e.target);
                    e.target.classList.add("vld-field-activated")
                    vld.checkForm($(e.target).closest(".vld-form")[0], e.target);
                }
                else {

                    // работа с input autocomplete
                    if (
                        (e.target.getAttribute("data-required") && (e.target.getAttribute("data-required") === "true"))
                        &&
                        e.target.getAttribute("data-autocomplete")
                    ) {
                        function f() {
                            // нахожу ul связанный с input[data-autocomplete]
                            // и проверяю ul на видимость
                            if (document.querySelector("ul.ui-autocomplete." + e.target.getAttribute("name"))) {
                                if ((document.querySelector("ul.ui-autocomplete." + e.target.getAttribute("name")).clientHeight == 0)) {
                                    if (e.target.classList.contains("vld-field-autocompleted")) {
                                        e.target.value = "";
                                        e.target.classList.remove("vld-field-valid");
                                        e.target.classList.remove("vld-field-autocompleted");
                                        e.target.parentNode.querySelector("[type='hidden']").value = "";
                                        vld.checkForm($(e.target).closest(".vld-form")[0], e.target);
                                    }
                                }
                            }
                        }
                        function wrapper() {
                            f();
                        }
                        (function (wrapper, ms) {
                            clearTimeout(vld.keyupTimerId);
                            vld.keyupTimerId = setTimeout(wrapper, ms);
                        })(wrapper, vld.keyupDelay);


                    }
                }
            }

        }
        function vldInput(e) {
            if (e.target.classList.contains("vld-input")) {
                memoryForm.init(e.target);
                e.target.classList.add("vld-field-activated")
                vld.checkForm($(e.target).closest(".vld-form")[0], e.target);
            }

        }
        function vldChange(e) {
            if (e.target.classList.contains("vld-select")) {
                e.target.classList.add("vld-field-activated")
                vld.checkForm($(e.target).closest(".vld-form")[0], e.target);
            }
            else {
                vld.checkForm($(e.target).closest(".vld-form")[0]);
            }
        }
    },
    onload: function () {
        var forms = document.getElementsByClassName("vld-form");
        if (forms.length) {
            for (var i = 0, k = forms.length; i < k; i++) {
                if (forms[i].getAttribute("data-validate-onload") && forms[i].getAttribute("data-validate-onload") == "false") continue;
                (function (form) {
                    setTimeout(function () {
                        if (form.querySelector("[readonly]")) {
                            form.querySelector("[readonly]").removeAttribute("readonly");
                        }
                        // window.vld.checkForm(form);
                    }, 600);
                })(forms[i]);
            }
        }
    },
    checkForm: function (currForm, field) {
        // console.log("==== checkForm ====", currForm, field);
        if (!currForm) return;
        if (typeof currForm == "string") {
            if (document.querySelector(currForm)) {
                var currForm = document.querySelector(currForm);
            }
        }
        var form = currForm,
            fields = currForm.getElementsByClassName("vld-field");

        if (fields.length) {
            for (var i = 0, k = fields.length; i < k; i++) {
                /*(function(f) {
                     setTimeout(function() {f.focus()}, 500);
                     setTimeout(function() {f.blur();}, 1000);
                })(fields[i])*/

                if (
                    ($(fields[i]).closest(".targetChecked").length == 0)
                    ||
                    (($(fields[i]).closest(".targetChecked").length > 0) && ($(fields[i]).closest(".targetChecked").height() >= 24))
                ) {
                    (function (f) {
                        f.removeAttribute("readonly");
                    })(fields[i])

                    this.checkField(fields[i]);
                }
                if (i == k - 1) {
                    setTimeout(function () {
                        vld.isValidForm(currForm);
                    }, 100);
                }
            }
        }
    },
    checkField: function (f) {
        var isValid = false;
        if (f.parentNode.clientHeight <= 0) {
            f.classList.remove("vld-field-invalid");
            return;
        }

        if ((f.type != "hidden") && (f.tagName.toLowerCase() == "input" || f.tagName.toLowerCase() == "textarea")) {
            if (f.getAttribute("data-required") && f.getAttribute("data-required") == "true") {
                if (!f.value) f.value = "";
                var v = f.value;

                if (f.getAttribute("data-autocomplete")) {
                    if (f.getAttribute("name")) {
                        var fieldName = f.getAttribute("name");
                        var ulUiAutocomplete = document.querySelector("ul.ui-autocomplete." + fieldName);

                        if (ulUiAutocomplete) {
                            if (ulUiAutocomplete.clientHeight == 0) {
                                compareFieldValueWithUlAutocomplete(f, ulUiAutocomplete);
                            }
                        }
                        else {
                            if (f.parentNode.querySelector("[type='hidden']").value == "") {
                                f.value = "";
                                v = f.value;
                                this.statusField(f, "invalid");
                                isValid = false;
                            }
                        }

                        function compareFieldValueWithUlAutocomplete(f, ul) {
                            var items = ul.getElementsByClassName("ui-menu-item");
                            var isValuesEqual = false;
                            var valHidd = f.parentNode.querySelector("[type='hidden']").value;
                            for (var i = 0, k = items.length; i < k; i++) {
                                if (
                                    (valHidd == items[i].getAttribute("item-id"))
                                    &&
                                    (f.value.length == items[i].querySelector(".ui-menu-item-wrapper").childNodes[0].textContent.length)
                                ) {

                                    isValuesEqual = true;
                                    v = f.value;
                                    vld.statusField(f, "valid");
                                    isValid = true;
                                    break;
                                }
                                if (i == k - 1) {
                                    if (!isValuesEqual) {
                                        f.value = "";
                                        v = f.value;
                                        f.parentNode.querySelector("[type='hidden']").value = "";
                                        vld.statusField(f, "invalid");
                                        isValid = false;
                                    }
                                }
                            }
                        }
                    }
                }

                if (f.getAttribute("pattern")) {


                    var re = new RegExp(f.getAttribute("pattern"));
                    if (f.getAttribute("data-uppercase") && f.getAttribute("data-uppercase") == "true") {
                        v = v.toUpperCase();
                    }
                    // if(f.checkValidity()) {
                    if (re.test(v)) {
                        this.statusField(f, "valid");
                        isValid = true;
                    }
                    else {
                        this.statusField(f, "invalid");
                        isValid = false;
                    }
                }
                else {
                    if (f.type == "checkbox") {
                        if (f.checked) {
                            this.statusField(f, "valid");
                            isValid = true;
                        }
                        else {
                            this.statusField(f, "invalid");
                            isValid = false;
                        }
                    }
                    else {
                        if (!!v) {
                            this.statusField(f, "valid");
                            isValid = true;
                        }
                        else {
                            this.statusField(f, "invalid");
                            isValid = false;
                        }
                    }
                }
            }
        }
        else if (f.tagName.toLowerCase() == "select") {
            // if(!f.classList.contains("vld-activeted")) return;

            if (f.getAttribute("data-required") && f.getAttribute("data-required") == "true") {
                if (f.options[f.selectedIndex] && f.options[f.selectedIndex].getAttribute("value") && f.options[f.selectedIndex].getAttribute("value") !== "0") {
                    this.statusField(f, "valid");
                    isValid = true;
                }
                else {
                    this.statusField(f, "invalid");
                    isValid = false;
                }
            }
        }
        return isValid;
    },
    isValidForm: function (currForm) {
        var isValid = true;
        var btn = currForm.querySelector(currForm.getAttribute("data-btnLinked"));
        if (!btn) return;

        var allFields = currForm.querySelectorAll(".vld-field[data-required='true']"),
            fieldsToCheck = 0,
            fieldsExcluded = 0;

        for (var i = 0, k = allFields.length; i < k; i++) {
            if (
                (($(allFields[i]).closest(".targetChecked").length > 0) && ($(allFields[i]).closest(".targetChecked").height() < 24))
                ||
                $(allFields[i])[0].getAttribute("disabled") == "disabled"
            ) {
                fieldsExcluded++;
            }
            else if (
                ($(allFields[i]).closest(".targetChecked").length === 0)
                ||
                (($(allFields[i]).closest(".targetChecked").length > 0) && ($(allFields[i]).closest(".targetChecked").height() >= 24))
            ) {
                fieldsToCheck++;
                if (
                    allFields[i].classList.contains("vld-field-invalid")
                ) {
                    isValid = false;
                    btn.classList.add("disabled");
					btn.setAttribute("disabled", true);
                }
            }
            if (fieldsExcluded + fieldsToCheck == k) {
                if (isValid) {
                    btn.classList.remove("disabled");
                    btn.classList.remove("aspNetDisabled");
					btn.removeAttribute("disabled");
                }
            }
        }

        return isValid;
    },
    statusField: function (field, status) {
        if (status == "valid") {
            field.classList.add("vld-field-valid");
            field.classList.remove("vld-field-invalid");
        }
        else {
            field.classList.remove("vld-field-valid");
            field.classList.add("vld-field-invalid");
        }
    },
    // from 1674 ($.each($("[data-autocomplete]"), function (){})
    validAutocompleteField: function (fieldAutocomplete, ulUiAutocomplete) {
        var fieldName = fieldAutocomplete.getAttribute("name");
        var fieldInput = document.querySelector("[name='" + fieldName + "']");
        ulUiAutocomplete.on("click", function (argument) {
            fieldInput.classList.remove("vld-field-invalid");
            fieldInput.classList.add("vld-field-activated");
            fieldInput.classList.add("vld-field-valid");
            fieldInput.classList.add("vld-field-autocompleted");

            if (this.classList.contains("city")) {
                window.Cart.updateOptions();
            }
        });
    }
};
vld.init();

var memoryForm = {
    form: undefined,
    formName: undefined,
    onload: function () {
        // нахожу формы требующие востаноления инфы
        let forms = document.querySelectorAll("[data-restoredataonload='true']");
        if (forms.length) {
            forms.forEach((form) => {
                let formName = form.classList[1];
                memoryForm.restoreFormData(form, formName);
            })
        }
    },
    init: function (senderInput) {

        fnDelay(function () { _f() }, 400);

        function _f() {
            let self = window.memoryForm;
            self.form = senderInput.closest(".vld-form");
            self.formName = self.form.classList[1];

            // if(self.formName == "vld-form-registration") {
            if (self.form.dataset.restoredataonload) {
                self.checkInputs();
            }
        }
    },
    checkInputs: function () {
        let inputs = this.form.querySelectorAll(".vld-input:not([type='password'])");

        // проверка полей на предмет заполнености
        // если хотя бы один заполнен
        // сохраняю данные для кук
        let call = false;
        for (let i = 0, k = inputs.length; i < k; i++) {
            if (inputs[i].value) {
                call = true;
                break;
            }
        }
        if (call) {
            this.createStringData(inputs);
        }
        else {
            // удаляю куку
            // т.к. все поля формы пустые
            deleteCookie(this.formName);
        }
    },
    createStringData: function (inputs) {
        let str = "";
        let comm = ",";
        for (let i = 0, k = inputs.length; i < k; i++) {
            str += ((i > 0 ? comm : "") + inputs[i].id + ":" + inputs[i].value);
        }

        // кука на час
        SetCookie(this.formName, str, 1 / 6);
    },
    restoreFormData: function (form, formName) {
        let cookieData = "";
        if (cookieData = getCookie(formName)) {
            let data = cookieData.split(",");
            let inputId, inputVal, inputEl;
            for (let i = 0, k = data.length; i < k; i++) {
                inputId = data[i].split(":")[0];
                inputVal = data[i].split(":")[1];
                if (inputEl = document.querySelector("." + formName + " #" + inputId)) {
                    inputEl.value = inputVal;
                }
            }
        }
    }
}

var ddl = {
    init: function (dir) {
        var ddls = document.getElementsByClassName("ddlTpl");
        if (ddls.length) {
            for (var i = 0, k = ddls.length; i < k; i++) {
                if (dir == "inActive") {
                    this.setInActive(ddls[i]);
                }
                else if (dir == "setReady") {
                    this.setReady(ddls[i]);
                }
            }
        }
    },
    setReady: function (d) {
        if (d.querySelector(".custom-checkbox")) {
            var customCheck = d.getElementsByClassName("custom-checkbox");
            var vals = "";
            for (var i = 0, k = customCheck.length, firstCB = false; i < k; i++) {
                if (customCheck[i].getElementsByClassName("custom-control-input")[0].checked) {
                    if (!firstCB) {
                        firstCB = true;
                        if (customCheck[i].getElementsByClassName("custom-control-description__name")[0] != undefined) {
                            vals += customCheck[i].getElementsByClassName("custom-control-description__name")[0].textContent;
                        }
                    }
                    else {
                        if (customCheck[i].getElementsByClassName("custom-control-description__name")[0] != undefined) {
                            vals += ", " + customCheck[i].getElementsByClassName("custom-control-description__name")[0].textContent;
                        }
                    }
                }
            }
            if (!vals) {
                vals = d.getAttribute("data-initpicked");
            }
            d.getElementsByClassName("ddlTpl__picked_inner")[0].textContent = vals;
        }
    },
    setActive: function (d, sender) {
        d.classList.toggle("active");
    },
    setInActive: function (d) {
        d.classList.remove("active");
        /*if(d.querySelector("input:checked")) {
             var checkedName = d.querySelector("input:checked").parentNode.querySelector(".custom-control-description__name").textContent;
             if(checkedName) {
                  d.querySelector(".ddlTpl__picked_inner").textContent = checkedName;
             }
        }*/
    }
};

function isScrolledIntoView(elem, offset, allElInVp) {
    var _offset = offset ? parseInt(offset, 10) : 0;
    var _allElInVp = false;

    if (allElInVp) {
        _allElInVp = allElInVp ? allElInVp : false;
    }

    var vpH = $(window).height();
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + vpH;

    var elemBCRtop = elem.getBoundingClientRect().top;
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + ($(elem).height() == 0 ? 1 : $(elem).height());
    if (_allElInVp) {
        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }
    else {
        return (((elemBCRtop - _offset > 0) && (elemBCRtop < vpH)) || ((elemBCRtop < 0) && (elemBCRtop + $(elem).height()) > 0));
    }
};

var loadProdsToDemand = {
    ajaxPostQ: "",
    wrapperIdn: ".prodsToDemant__wrapper",

    init: function () {
        if (document.querySelector(this.wrapperIdn)) {
            /* if (typeof $.fn.slick == "undefined") {
                addScript("/js/slick1.8.1.min.js");
            } */
            // this.triggerOnVP();
            this.initIntersectionObserver();
        }
    },
    initIntersectionObserver: function () {

        let self = window.loadProdsToDemand;

        const prodsToDemant = document.querySelectorAll(self.wrapperIdn);

        const callback = (entries, observer) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    if (typeof $.fn.slick == "undefined") {
                        addScript("/js/slick1.8.1.min.js");
                    }
                    let wrapper = entry.target;
                    let isMQ = false;
                    let mq = wrapper.getAttribute("data-mq").split(" ");

                    if (mq[0] == "all") {
                        isMQ = true;
                    }
                    else if (isValInArr(getMQ(), mq)) {
                        isMQ = true;
                    }

                    if (isMQ && (!wrapper.classList.contains("loaded") && !wrapper.classList.contains("spinner"))) {
                        wrapper.classList.add("spinner");
                        wrapper.classList.remove("hiddenCnt");
                        self.loadProds(wrapper);
                    }
                    observer.unobserve(wrapper);
                }
            })
        }
        const options = {
            rootMargin: "0px",
            threshold: 0,
        }

        const observer = new IntersectionObserver(callback, options);
        prodsToDemant.forEach((item) => observer.observe(item));
    },
    /* triggerOnVP: function () {
        var self = window.loadProdsToDemand,
            wrapps = document.querySelectorAll(self.wrapperIdn);

        for (var i = 0, k = wrapps.length; i < k; i++) {
            (function (w) {
                var isMQ = false;
                var mq = w.getAttribute("data-mq").split(" ");

                if (mq[0] == "all") {
                    isMQ = true;
                }
                else if (isValInArr(getMQ(), mq)) {
                    isMQ = true;
                }

                if (isMQ && (!w.classList.contains("loaded") && !w.classList.contains("spinner"))) {
                    if (isScrolledIntoView(w, 0, false)) {
                        w.classList.add("spinner");
                        w.classList.remove("hiddenCnt");
                        self.loadProds(w);
                    }
                }
            })(wrapps[i]);
        }
    }, */
    loadProds: function (wrapperProds) {
        var self = window.loadProdsToDemand;
        self.ajaxPostQ = $.ajax({
            url: wrapperProds.getAttribute("data-ajaxurl"),
            dataType: 'html',
            success: function success(data) {
                if (wrapperProds.classList.contains("loaded") || wrapperProds.querySelector(".loadProdsToDemand-slickWrapper")) return;

                if (data.trim() && data.trim().length) {
                    window.loadProdsToDemand.insert(data, wrapperProds);
                    cartAddedProducts();
                }
                else {
                    wrapperProds.classList.add("hiddenCnt");
                    wrapperProds.classList.remove("spinner");
                    wrapperProds.classList.add("loaded");
                }
            },
            error: function error(ex) {
                self.abortAjaxPost();
                console.error(ex);
            },
            done: function () {
                self.abortAjaxPost();
            }
        });
    },
    insert: function (codHtml, wrapperProds) {
        var wrapper = document.getElementById(wrapperProds.id),
            loadProdsToDemandSlickWrapper = document.createElement("div");

        loadProdsToDemandSlickWrapper.className = "loadProdsToDemand-slickWrapper";
        loadProdsToDemandSlickWrapper.insertAdjacentHTML("afterBegin", codHtml);

        if (wrapperProds.getAttribute("data-appendlinkAsItem") && wrapperProds.getAttribute("data-appendlinkAsItem") == "true") {
            var allProdsLnk = '<div><a href="${URL}" class="lnk-blue novisited extraTilesOpener card flex flex-alignItems_center" tabindex="0">\
                    <div class="card-inner ta-center">\
                        <span class="lnk-abs">\
                            <span class="lnk-inner d-b">\
                                <span class="lnk-txt">${LNKTXT}</span>\
                            </span>\
                            <i class="${FA}"></i>\
                        </span>\
                    </div>\
                </a></div>';

            var lnk = allProdsLnk.replace(/\$\{URL\}/g, wrapper.getAttribute("data-linkurl"))
                .replace(/\$\{LNKTXT\}/g, wrapper.getAttribute("data-linktxt"))
                .replace(/\$\{FA\}/g, wrapper.getAttribute("data-fa") ? wrapper.getAttribute("data-fa") : "");

            loadProdsToDemandSlickWrapper.insertAdjacentHTML("beforeEnd", lnk);
        }
        // wrapper.querySelector(".container-prodsToDemant").innerHTML = "";

        // wrapper.querySelector(".container-prodsToDemant").appendChild(loadProdsToDemandSlickWrapper);
        wrapper.querySelector(".container-prodsToDemant").insertBefore(loadProdsToDemandSlickWrapper, wrapper.querySelector(".container-prodsToDemant").firstElementChild);
        if (wrapper.querySelector(".loadProdsToDemand-slickWrapper")) {
            var fl = wrapper.querySelector(".spaceOnLoading-wrapper");
            if (fl) {
                fl.parentNode.removeChild(fl);
            }
            // because of bug in FF
            if (document.querySelector(".oneProd-aside")) {
                document.querySelector(".oneProd-aside").style.position = "static";
            }
            wrapper.classList.remove("hiddenCnt");

            setTimeout(function () {

                $("#" + wrapperProds.id + ' .loadProdsToDemand-slickWrapper .cards-slick').slick(window.cards5_slick);
                wrapper.classList.remove("spinner");
                wrapper.classList.add("loaded");
                lazyLoad.update(300, document.querySelector("#" + wrapperProds.id + ' .loadProdsToDemand-slickWrapper .cards-slick'));
                $(".cards-slick").on("scroll", lazyLoad.onscroll);
                window.loadProdsToDemand.calcSlickDots(wrapper);
                userInfo.setFavorites();
                if (document.querySelector(".oneProd-aside")) {
                    document.querySelector(".oneProd-aside").removeAttribute("style");
                }
            }, 100);
        }
    },
    createPreload: function (wrapperProds) {
        wrapperProds.classList.add("hiddenCnt");
        var tplStr = '<div class="card card-spaceOnLoading">\
                            <div class="card-inner">\
                            </div>\
                        </div>',
            kolvoTpls = 1;

        if (getMQ("min-width", "xs")) {
            kolvoTpls = 1;
        }
        if (getMQ("min-width", "sm")) {
            kolvoTpls = 2;
        }
        if (getMQ("min-width", "md")) {
            kolvoTpls = 3;
        }
        if (getMQ("min-width", "lg")) {
            kolvoTpls = 4;
        }
        if (getMQ("min-width", "xl")) {
            kolvoTpls = 5;
        }

        for (var i = 0, str = '<div class="d-flex spaceOnLoading-wrapper">'; i < kolvoTpls; i++) {
            str += tplStr;
            if (i == kolvoTpls - 1) {
                str += "</div>";
            }
        }
        wrapperProds.querySelector(".container-prodsToDemant").insertAdjacentHTML("afterBegin", str);
    },
    calcSlickDots: function (prnt) {
        var dots = prnt.querySelector(".slick-dots");
        if (dots) {
            if (dots.childElementCount > 1) {
                dots.classList.remove('d-none');
            }
            else {
                dots.classList.add('d-none');
            }
        }
    },
    abortAjaxPost: function () {
        var self = window.loadProdsToDemand;
        if (self.ajaxPostQ) {
            self.ajaxPostQ.abort();
        }
    }
};

var googleAnaliticsData = {
    dataGA: "[data-ga]",
    init: function () {
        if (document.querySelector(this.dataGA)) {
            /* if (!document.documentElement.classList.contains("gtmLoaded")) {
                addGTM().then(() => {
                    // this.triggerOnVP();
                    this.initIntersectionObserver();					
                })
            }
            else {
                // this.triggerOnVP();
                this.initIntersectionObserver();
            	
            } */
            this.initIntersectionObserver();
        }
    },
    initIntersectionObserver: function () {
        const gaDataEls = document.querySelectorAll(this.dataGA + ":not(.gaChecked-js)");

        const callback = ((entries, observer) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    let gaEl = entry.target;
                    gaEl.classList.add("gaChecked-js");

                    let arr = [];
                    let prodInSection = gaEl.querySelectorAll("[data-product]");

                    for (let m = 0, n = prodInSection.length; m < n; m++) {
                        arr.push(prodInSection[m].getAttribute("data-product"));
                    }

                    if (arr.length) {
                        gtmViewListProducts(gaEl.getAttribute("data-ga"), arr);
                    }
                    observer.unobserve(gaEl);
                }
            })
        })
        const options = {
            rootMargin: "0px",
            threshold: 0,
        }
        const observer = new IntersectionObserver(callback, options);
        gaDataEls.forEach((el) => { observer.observe(el) });
    },
    /* triggerOnVP: function () {
        var ga = document.querySelectorAll("[data-ga]:not(.gaChecked-js)");

        if (ga.length) {
            for (var i = 0, k = ga.length; i < k; i++) {
                (function (w) {
                    if (isScrolledIntoView(w, 0, false)) {
                        w.classList.add("gaChecked-js");

                        let arr = [];
                        let prodInSection = w.querySelectorAll("[data-product]");

                        for (let m = 0, n = prodInSection.length; m < n; m++) {
                            arr.push(prodInSection[m].getAttribute("data-product"));
                        }

                        if (arr.length) {
                            gtmViewListProducts(w.getAttribute("data-ga"), arr);
                        }
                    }
                })(ga[i]);
            }
        }
    }, */
};

var userInfo = {
    isLogined: false,
    callbacks: [],
    favorites: [],
    compared: [],
    init: function () {
        $.getJSON("/handlers/UserInfo.ashx?r=" + (new Date()).valueOf(), function (data) {
            userInfo.isLogined = data.Logined;
            userInfo.favorites = data.Favorites;
            userInfo.compared = data.Compared;
            userInfo.setFavorites();
            userInfo.setCompared();
            if (userInfo.isLogined) {
                document.body.classList.add("logined");
                //redirect to user lang
                if (getCookie("siteLang")) {
                    let cookielng = getCookie("siteLang").split(":")[1];
                    let pathname = window.location.pathname.substring(1);
                    //check only for main page
                    if (pathname.length < 4) {
                        if (pathname.length > 2) {
                            pathname = pathname.substring(0, 2);
                        }
                        let currentLng = pathname != '' ? pathname : 'ru';
                        if (cookielng != currentLng) {
                            if (cookielng == 'ru') {
                                window.location.replace('/');
                            }
                            else {
                                window.location.replace('/' + cookielng + '/');
                            }
                        }
                    }
                }
            }
            else {
                let oneClickCol;
                if (oneClickCol = document.querySelector(".oneProd-oneClick-col")) {
                    oneClickCol.classList.add("userNotLogined");
                }
            }

            for (var i = 0; i < userInfo.callbacks.length; i++) {
                userInfo.callbacks[i]();
            }
        });
    },
    setFavorites: function (scopedBlock) {
        if (!scopedBlock) scopedBlock = $("body");
        for (var i = this.favorites.length - 1; i >= 0; i--) {
            var cardFavor = scopedBlock.find("[data-product=" + userInfo.favorites[i] + "]");
            if (cardFavor.length > 0) {
                userInfo.setActiveFavoriteClass(cardFavor);
            }
        }
        this.setHeaderIcos("favorites", ".favorIco");
    },
    clickFavorite: function (element) {
        var product = $(element).closest("[data-product]");
        var productId = product.attr("data-product") * 1;

        var cardFavor = $(element).closest(".card").length ? $(element).closest(".card") : $(element).closest(".favor-container");
        if (!cardFavor.length && element.classList.contains("cartItem-favor")) {
            cardFavor = $(element).closest(".cartItem");
        }

        var cls;
        if (cardFavor.hasClass("card") || cardFavor.hasClass("cartItem")) {
            cls = "card-inFavor";
        }
        else {
            cls = "favor-container-active";
        }

        var index = $.inArray(productId, userInfo.favorites);
        var flayerSize = [];
        if (index == -1) {
            $.get("/handlers/favorites.ashx?productId=" + productId, function () {
                userInfo.setActiveFavoriteClass(cardFavor, cls);
                userInfo.favorites.push(productId);
                userInfo.setHeaderIcos("favorites", ".favorIco");
                if (element.classList.contains("card-favor")) {
                    flayerSize = [element.clientWidth, element.clientHeight];
                }
                flyToDestination(element, getMQ("min-width", "md") ? document.querySelector(".headerMain-userPnl .favorIco") : document.querySelector(".headerMain-barsCnt-link"), "favor", flayerSize);
            });
            //gtm
            gtmAddToWishlist(productId);
        }
        else {
            $.get("/handlers/favorites.ashx?cmd=delete&productId=" + productId, function () {
                // var heart = cardFavor.find(".fa-heart-o");
                // heart.removeClass("fa-heart-o");
                cardFavor.removeClass("card-inFavor");
                if (cardFavor.hasClass("favor-container")) {
                    cardFavor.removeClass("favor-container-active");
                }
                userInfo.favorites.splice(index, 1);
                userInfo.setHeaderIcos("favorites", ".favorIco");

                if (cardFavor.closest(".favoritesPage").length) {
                    cardFavor.addClass("d-none");
                }
            });
        }
    },
    setActiveFavoriteClass: function (cardFavor, cls) {
        if (!cardFavor) return;
        let _cardFavor = cardFavor;

        // определяю что cardFavor это объект jquery
        if (cardFavor.length) {
            _cardFavor = cardFavor.get(0);
        }

        if (!cls) cls = "card-inFavor";
        if (_cardFavor.classList.contains("oneProd-page")) {
            _cardFavor.querySelector(".favor-container-oneprodpage").classList.add("favor-container-active");
        }
        _cardFavor.classList.add(cls);
    },
    setCompared: function (scopedBlock) {
        if (!scopedBlock) scopedBlock = $("body");
        for (var i = userInfo.compared.length - 1; i >= 0; i--) {
            var card = scopedBlock.find("[data-product=" + userInfo.compared[i] + "]");
            if (card.length) {
                if (card.hasClass("card")) {
                    card.addClass("card-inCompare");
                }
                else {
                    if (card.find(".check-container :checkbox").length) {
                        card.find(".check-container :checkbox").attr("checked", true);
                    }
                }
            }
        }
        this.setHeaderIcos("compared", ".compareIco");
    },
    clickCompare: function (element) {
        var product = $(element).closest("[data-product]");
        var productId = product.attr("data-product") * 1;
        var card;
        var flayer;
        var flayerSize = [];
        if ($(element).closest(".check-container").length) {
            card = $(element).closest(".check-container");
            flayer = card[0];
        }
        else if ($(element).closest(".card").length) {
            card = $(element).closest(".card");
            flayer = card[0].querySelector(".card-compare");
            flayerSize = [flayer.clientWidth, flayer.clientHeight];
        }
        var index = $.inArray(productId, userInfo.compared);
        if (index == -1) {
            $.get("/handlers/compare.ashx?cmd=add&productId=" + productId, function () {
                //gtm
                dataLayer.push({ 'event': 'GAevent', 'eventCategory': 'click', 'eventAction': 'compare' });

                if (card.hasClass("card")) {
                    card.addClass("card-inCompare");
                }
                else {
                    card.addClass("active");
                }
                userInfo.compared.push(productId);
                userInfo.setHeaderIcos("compared", ".compareIco");
                userInfo.setCompareLink();

                flyToDestination(flayer, getMQ("min-width", "md") ? document.querySelector(".headerMain-userPnl .compareIco") : document.querySelector(".headerMain-barsCnt-link"), "compare", flayerSize);
            });
        }
        else {
            $.get("/handlers/compare.ashx?cmd=delete&productId=" + productId, function () {
                if (card.hasClass("card")) {
                    card.removeClass("card-inCompare");
                }
                else {
                    card.removeClass("active");
                }
                userInfo.compared.splice(index, 1);
                userInfo.setHeaderIcos("compared", ".compareIco");
                userInfo.setCompareLink();
            });
        }
    },
    setCompareLink: function () {
        let lnkGotocompare;
        if (lnkGotocompare = document.querySelector(".lnk-gotocompare")) {
            var href = document.querySelector(".lnk-gotocompare").getAttribute("data-base");
            href += "&products=" + userInfo.compared.join(",");
            document.querySelector(".lnk-gotocompare").setAttribute("href", href);
        }
    },
    clickAddToCart: function (element) {
        var product = element.closest("[data-product]");
        var productId = product.getAttribute("data-product");
        var flayer;

        if (product.classList.contains("card")) {
            flayer = product.querySelector(".card-img-picture img");
        }
        else {
            if (!!(product.querySelector(".oneProd-photos-galery .slick-active img"))) {
                flayer = product.querySelector(".oneProd-photos-galery .slick-active img");
            }
            else {
                flayer = product.querySelector(".oneProd-photos-picture img");
            }
        }

        var flayerSize = [flayer.clientWidth, flayer.clientHeight];
        $.get("/cart.ashx?cmd=add&productId=" + productId + "&lng=" + getLanguage(), function (response) {
            var kolvo = document.querySelector(".cartIco a .kolvo");
            if (!kolvo) {
                document.querySelector(".cartIco a").insertAdjacentHTML("afterBegin", '<div class="kolvo"></div>');
                kolvo = document.querySelector(".cartIco a .kolvo");
            }
            if (element.closest(".card")) {
                element.closest(".card").classList.add("card-inCart");
                element.classList.remove("spinner");
            }
            if (element.classList.contains("oneProd-inCos") && element.closest(".oneProd-page")) {
                element.closest(".oneProd-page").classList.add("oneProd-inCart");
                element.classList.remove("spinner");
            }
            flyToDestination(flayer, document.querySelector(".headerMain-userPnl .cartIco"), "cart", flayerSize);
            kolvo.textContent = response.Products.length;
            setTimeout(function () {
                popup.show({ id: "preCart", "url": "/standalone/AddedToCart.aspx?productId=" + productId + "&lng=" + getLanguage() });
            }, 1500);

            //esputnik event
            eSputnikStatusCartSendEvent();
            //gtm
            let viewName = "";
            let dataGAnode;
            if (dataGAnode = element.closest("[data-ga]")) {
                viewName = dataGAnode.getAttribute("data-ga");
            }
            let promoName = "", promoId = "";
            if (dataGAnode = element.closest("[data-ga-promoname]")) {
                promoName = dataGAnode.getAttribute("data-ga-promoname");
            }
            if (dataGAnode = element.closest("[data-ga-promoid]")) {
                promoId = dataGAnode.getAttribute("data-ga-promoid");
            }
            gtmAddToCart(productId, viewName, promoName, promoId);
        });
    },
    setHeaderIcos: function (type, elId) {
        var kolvo = userInfo[type].length;
        if (kolvo) {
            document.querySelector(elId + " .kolvo").textContent = kolvo;
            document.querySelector(".startMenuForMob-nav-" + type + " .kolvo").textContent = kolvo;
        }
        else {
            document.querySelector(elId + " .kolvo").textContent = '';
            document.querySelector(".startMenuForMob-nav-" + type + " .kolvo").textContent = '';
        }
    }
};

function authenticateUser(provider) {
    window.open("/handlers/authenticateUser.ashx?cmd=signin_social&provider=" + provider, "Authentication", "width=700,height=700");
}

function authenticateUserCallback(userData) {
	var ecode, phone;
	fetch('/handlers/authenticateUser.ashx?cmd=signin_social_callback&' + new URLSearchParams(userData).toString())
		.then((response) => response.json())
		.then((data) => {
			if (data.isSuccess) {
				if (data.isLogined) {
					//gtm
					dataLayer.push({ 'event': 'GAevent', 'eventCategory': 'sign_in', 'eventAction': 'B_2' });

					userInfo.isLogined = true;
					if (!document.location.search)
						document.location = document.location + '?reloaded=1';
					else
						document.location = document.location + '&reloaded=1';
				}
				else {
					// popup getPhone
					popup.show({id: "getUserPhoneAuth", cnt: window.getLanguageTag("Popup-getUserPhoneAuth") });

					//send sms
					// url: /Handlers/CheckPhoneNumber.ashx?cmd=sendSmsCode&phone=79090980&lng=ro

					//check sms code
					// url: /Handlers/CheckPhoneNumber.ashx?cmd=checkSmsCode&eCode=NDMwNA==&code=4304&lng=ro

					//register
					// url : '/handlers/authenticateUser.ashx?cmd=signin_social_registration&' + new URLSearchParams(userData).toString() + '&phone=phone'
					//reload
				}
			}
			else {
				alert(data.message);
			}
		})

	function _sendPhone(btn) {
		var popupBody = btn.closest(".popup-body");
		var userPhone = popupBody.querySelector("[type='tel']");
		authenticateUserCallback.phone = userPhone.value.replace(/^0|\D/g, '');

		fetch("/Handlers/CheckPhoneNumber.ashx?cmd=sendSmsCode&phone=" + userPhone.value.replace(/^0|\D/g, '') + "&lng=" + getLanguage())
			.then((response) => response.json())
			.then((data) => {
				popupBody.classList.remove("overlay", "overlay-white", "spinner");
				btn.classList.add("disabled");
				if(data.success) {
					userPhone.setAttribute("disabled", true);
					authenticateUserCallback.ecode = data.eCode;
					let smsHtml = window.getLanguageTag("Popup-getUserPhoneAuth_sms");
					popupBody.querySelector(".smsContainer").insertAdjacentHTML("afterBegin", smsHtml);
				}
				else {
					alert(data.message);
				}
			})
	};
	function _sendSms(btn) {
		var popupBody = btn.closest(".popup-body");
		var userSms = popupBody.querySelector("[name='sms']").value;
		fetch("/Handlers/CheckPhoneNumber.ashx?cmd=checkSmsCode&eCode=" + authenticateUserCallback.ecode + "&code=" + userSms.replace(/^\D/g, '') + "&lng=" + getLanguage())
			.then((response) => response.json())
			.then((data) => {
				if(data.success) {
					popup.close(".popup-getUserPhoneAuth", false);
					authenticateUserCallback.sendUserData();
				}
				else {
					popupBody.classList.remove("overlay", "overlay-white", "spinner");
					alert(data.message);
				}
			})
	};
	function _sendUserData() {
		fetch("/handlers/authenticateUser.ashx?cmd=signin_social_registration&" + new URLSearchParams(userData).toString() + "&phone=" + authenticateUserCallback.phone + "&lng=" + getLanguage())
			.then((response) => response.json())
			.then((data) => {
				if(data.success) {
					location.reload();				
				}
				else {
					alert(data.message);
				}
			})
	};

	authenticateUserCallback.sendPhone = _sendPhone;
	authenticateUserCallback.sendSms = _sendSms;
	authenticateUserCallback.sendUserData = _sendUserData;
	// authenticateUserCallback.ecode = _ecode;
    // $.getJSON('/handlers/authenticateUser.ashx?cmd=signin_social_callback&' + new URLSearchParams(userData).toString(), function (data) {
    //     if (data.isSuccess) {
    //         if (data.isLogined) {
    //             //gtm
    //             dataLayer.push({ 'event': 'GAevent', 'eventCategory': 'sign_in', 'eventAction': 'B_2' });

    //             userInfo.isLogined = true;
    //             if (!document.location.search)
    //                 document.location = document.location + '?reloaded=1';
    //             else
    //                 document.location = document.location + '&reloaded=1';
    //         }
    //         else {
    //             //send sms
    //             // url: /Handlers/CheckPhoneNumber.ashx?cmd=sendSmsCode&phone=79090980&lng=ro

    //             //check sms code
    //             // url: /Handlers/CheckPhoneNumber.ashx?cmd=checkSmsCode&eCode=NDMwNA==&code=4304&lng=ro

    //             //register
    //             // url : '/handlers/authenticateUser.ashx?cmd=signin_social_registration&' + new URLSearchParams(userData).toString() + '&phone=phone'
    //             //reload
    //         }
    //     }
    //     else {
    //         alert(data.message);
    //     }
    // });
}

var popup = {
    show: function (options) {
        if (typeof options === 'undefined' || typeof options != 'object') {
            return;
        }

        if (document.querySelector(".popup-" + options.id)) {
            let closePopEl;
            let pop = document.querySelector(".popup-" + options.id);

            if (
                !pop.hasAttribute("data-leaveindom")
                &&
                !pop.querySelector(".popup-close").hasAttribute("data-leaveindom")
            ) {

                if (!pop.hasAttribute("data-leaveindom")) {
                    pop.parentNode.parentNode.removeChild(pop.parentNode);
                }
                else {
                    if (closePopEl = pop.querySelector(".popup-close")) {
                        if (!closePopEl.hasAttribute("data-leaveindom")) {
                            pop.parentNode.parentNode.removeChild(pop.parentNode);
                        }
                    }
                }
            }
        }

        $(document.body).on('appendPopupCompleted', function () {
            document.body.classList.add("popupActive");
            initMask();
            if (options.callback) options.callback();
            if (options.id) {
                var form = $(".popup-" + options.id + " .vld-form");
                if (form && form.length > 0) {
                    setTimeout(function () {
                        window.vld.checkForm(form[0]);
                    }, 500);
                }
            }
            lazyLoad.update();
        });

        if (options.id && document.querySelector(".popup-" + options.id)) {
            var p;
            if (p = document.querySelector(".popup-" + options.id)) {
                if (p.parentNode.classList.contains("popup-outer")) {
                    p.parentNode.classList.add("active");

                    if (p.querySelector(".vld-form")) {
                        window.vld.checkForm(p.querySelector(".vld-form"));
                    }
                    initMask();
                    if (options.callback) options.callback();
                }
            }
        }
        else if (options.url) {
            $.get(options.url, function (data) {
                options.cnt = data;
                var pp = window.popup._create(options);
                document.body.insertAdjacentHTML("beforeEnd", pp);
                $(document.body).trigger('appendPopupCompleted');
            });
        } else if (options.cnt) {
            var pp = window.popup._create(options);
            document.body.insertAdjacentHTML("beforeEnd", pp);
            $(document.body).trigger('appendPopupCompleted');
        }
    },
    _create: function (options) {
        var struct = '<div class="active popup-outer ${POPUPCLASSOUTER}" ${POPUPATTR}>\
                        <div class="popup-container ${POPUPCLASS}">\
                            <div class="popup-close"></div>\
                            <div class="popup-body">\
                                <div class="popup-body-inner">\
                                    ${POPUPCNT}\
                                </div>\
                            </div>\
                        </div>\
                    </div>';
        var pp = struct.replace(/\$\{POPUPCLASSOUTER\}/, options.id ? ("popup-outer-" + options.id) : "")
            .replace(/\$\{POPUPCLASS\}/, options.id ? ("popup-" + options.id) : "")
            .replace(/\$\{POPUPATTR\}/, options.attr ? options.attr : "")
            //.replace(/\$\{POPUPTITLE\}/, options.title ? options.title : "")
            .replace(/\$\{POPUPCNT\}/, options.cnt);
        return pp;
    },
    close: function (popupEl, popupLeaveInDom) {
        var p;
        var _popupLeaveInDom = true;

        if (typeof popupEl == "object") {
            if (popupEl instanceof jQuery) {
                p = popupEl[0];
            }
            else {
                p = popupEl;
            }
        }
        else if (typeof popupEl == "string") {
            p = document.querySelector(popupEl);
        }

        if ((popupLeaveInDom === false) && !p.getAttribute("data-leaveindom")) {
            _popupLeaveInDom = false;
        }
        else if (typeof popupLeaveInDom == "undefined") {
            if (p.classList.contains("popup-close")) {
                if (p.getAttribute("data-leaveindom") === "false" || !p.getAttribute("data-leaveindom")) {
                    _popupLeaveInDom = false;
                }
            }
            else {
                if (p.querySelector(".popup-close") && !p.querySelector(".popup-close").getAttribute("data-leaveindom")) {
                    _popupLeaveInDom = false;
                }
            }
        }

        p.parentNode.classList.remove("active");
        document.body.removeAttribute("data-profileaddress");

        if (!_popupLeaveInDom) {
            if (p.closest(".popup-outer")) {
                p.closest(".popup-outer").parentNode.removeChild(p.closest(".popup-outer"));
            }
        }
        document.body.classList.remove("popupActive");
    }
};

function initDatePicker() {
    if ($(".datepicker-setDate").length > 0) {
        window.datepickerParams_bd = {
            format: "dd.mm.yyyy",
            todayBtn: false,
            maxViewMode: 2,
            startView: 2,
            language: document.documentElement.getAttribute("lang"),
            todayHighlight: true
            // ,
            // container: "#datepickerContainer"
        };

        if (!document.documentElement.classList.contains("datepickerCss")) {
            document.documentElement.classList.add("datepickerCss")
            addCss("/css/bootstrap-datepicker3.standalone.min.css");
        }

        addScript('/js/datepicker.1.9.0.min.js', function () {
            /*if (!$.fn.datepickerBS && $.fn.datepicker && $.fn.datepicker.noConflict) {
                 var datepicker = $.fn.datepicker.noConflict();
                 $.fn.datepickerBS = datepicker;
            }*/



            addScript("/js/locales/datepicker." + document.documentElement.getAttribute("lang") + ".min.js");
        });
    }
}

function getLanguageTag(tagName) {
    var url = "/handlers/helper.ashx?cmd=get-tag&term=" + tagName + "&lng=" + getLanguage();
    var result = tagName;
    $.ajax(url, { async: false })
        .done(function (data) {
            result = data;
        });

    return result;
}

var sticky = {
    init: function () {
        this.pnls = document.getElementsByClassName("sticky");
        var self = this;
        for (var i = 0, k = this.pnls.length; i < k; i++) {
            (function (pnl) {
                if (pnl.getAttribute("data-glide") == "true") {
                    if (pnl.getAttribute("data-resolution") == "all") {
                        self.initOnePnl(pnl);
                    }
                    else {
                        var res = pnl.getAttribute("data-resolution").split(" ");

                        if (self.isValInArr(getMQ(), res)) {
                            self.initOnePnl(pnl);
                        }
                        else {
                            self.reset(pnl)
                        }
                    }
                }
            })(self.pnls[i]);
        }
    },
    initOnePnl: function (pnl) {
        var self = window.glidedPnl;

        var pnlH = pnl.clientHeight,
            vpH = document.documentElement.clientHeight,
            pnlCoords = getCoords(pnl),
            offset,
            parented,
            parentedH,
            parentCls;

        var positionToSticky = pnl.getAttribute("data-position");
        var parentCls = pnl.getAttribute("data-parentcls");

        if (parentCls && parentCls !== "") {
            if (parentCls == "parentNode") {
                parented = pnl.parentNode;
            }
            else {
                if (parentCls == "document.body") {
                    parented = document.body;
                }
                else {
                    if (parentCls.split(" ").length == 1) {
                        parented = document.querySelector(pnl.getAttribute("data-parentcls"));
                    }
                }
            }
        }

        if (parented) {
            parentedH = parented.clientHeight;
            offset = pnl.getAttribute("data-offset") ? parseInt(pnl.getAttribute("data-offset"), 10) : 0;
            if ((parentedH > pnlH)) {
                // window.sticky.eventWinScroll(event, pnl, parented, parentedH, vpH, pnlH, offset);
                if (!parented.classList.contains("scrollInited")) {
                    parented.classList.add("scrollInited");
                    window.addEventListener("scroll", function (event) { window.sticky.eventWinScroll(event, pnl, parented, parentedH, vpH, pnlH, offset) }, false);
                }
            }
        }
    },
    reset: function (pnl, parented) {
        setTimeout(function () {
            pnl.removeAttribute("style");
            pnl.classList.remove("sticking");
            if (parented) {
                parented.classList.remove("scrollInited");
            }
        }, 100);
    },
    isValInArr: function (val, arr) {
        var inArray = false;
        for (var x = 0, y = arr.length; x < y; x++) {
            if (val == arr[x]) {
                inArray = true;
            }
        }
        return inArray;
    },
    eventWinScroll: function (e, pnl, parented, parentedH, vpH, pnlH, offset) {
        var res = pnl.getAttribute("data-resolution").split(" "),
            self = window.sticky;

        if ((pnl.getAttribute("data-resolution") == "all") || self.isValInArr(getMQ(), res)) {
            if (parented.getBoundingClientRect().top - offset <= 0) {
                self.sticking(e, pnl, parented, parentedH, vpH, pnlH, offset);
            }
            else {
                self.reset(pnl, parented);
            }
        }
    },
    sticking: function (e, pnl, parented, parentedH, vpH, pnlH, offset) {
        pnl.classList.add("sticking");
        if (pnl.getAttribute("data-glide-method")) {
            if (pnl.getAttribute("data-glide-method") == "js") {
                if (parented.getBoundingClientRect().bottom > pnlH) {
                    pnl.style.top = Math.abs(parented.getBoundingClientRect().top - offset) + "px";
                }
            }
            else {
                pnl.style.top = offset + "px";
            }
        }
        else {
            pnl.style.top = offset + "px";
        }
    }
};

function submitProductReview(e, targetBtn) {
    e.preventDefault();
    var form = $(targetBtn).closest("form");
    if (!form[0].checkValidity()) return false; //TODO: validate using window.vld functionality
    $.post(form.attr("action"), form.serialize(), function (response) {
        popup.show({ "cnt": response.message });
        if (response.isSuccess) {
            // $("#divCommentForm").hide();
            popup.close(".popup-commentForm", true);
        }
    });
}

window.ajaxpager = new AjaxPager().init();
function AjaxPager() {
    var self = this;
    self.peventAjaxRepeatQuery = false;
    this.init = function () {
        var pagingEl;
        if (pagingEl = document.getElementsByClassName("paging")[0]) {
            if (!pagingEl.getElementsByClassName("pagingNumsList_wrap")[0]) {
                createNumBtns(pagingEl);
            }
        }
        // клик по "Показать еще"
        $(document).on('click', '.ajax-pager .btn-showmore', function (e) {
            if (!self.peventAjaxRepeatQuery) {
                pagen(e, this, this.getAttribute("href"), true);
                self.peventAjaxRepeatQuery = true;
            }
        });
        // клик по номеру страницы
        $(document).on('click', '.ajax-pager .btn-numPage', function (e) {
            if (!self.peventAjaxRepeatQuery) {
                if ($(this).attr("data-page") != "1") {
                    pagen(e, this, this.getAttribute("href"), false);
                    self.peventAjaxRepeatQuery = true;
                }
            }
        });
        return self;
    };

    /*
    addition_flag - добавлять новые товары к существующим или перезаписать на новые
    */
    function pagen(e, item, url, addition_flag) {
        var btn = item,
            nav = btn.closest('.ajax-pager'),
            targetSelector = nav.getAttribute('data-target'),
            target = document.querySelector(targetSelector);

        if (window.history && typeof (window.history.pushState) == 'function') {
            window.history.pushState({ "type": "paging", "targetSelector": targetSelector }, document.title, url);
        }

        if (target) {
            e.preventDefault();
            blurPage("in");

            window.ajaxpager.loadPage(url, targetSelector, addition_flag);
        }
    };

    this.loadPage = function (url, targetSelector, addition_flag) {
        $.get(url + '&ajax=1', function (data) {
            var target = document.querySelector(targetSelector);
            // var gTg = $(data).find(targetSelector);

            var template = document.createElement("template");
            template.innerHTML = data;
            var fragData = template.content;
            var gTg = fragData.querySelector(targetSelector);

            if (!gTg) return;

            var frag = document.createDocumentFragment(),
                pills = gTg.querySelectorAll(".js-itemsList-item");
            for (var i = 0, k = pills.length; i < k; i++) {
                frag.appendChild(pills[i]);
            }

            // клик по "Показать еще"
            // добавляем контент
            if (addition_flag) {
                target.getElementsByClassName("js-itemsList")[0].insertBefore(frag, target.getElementsByClassName("js-itemsList")[0].lastElementChild.nextSibling);
            }
            // клик по кнопкам страниц и стрелкам
            // заменяем контент
            else {
                target.getElementsByClassName("js-itemsList")[0].innerHTML = "";
                target.getElementsByClassName("js-itemsList")[0].appendChild(frag);
                scrollToElement(target);
            }

            target.replaceChild(gTg.querySelector("#pnlPaging"), target.querySelector("#pnlPaging"));

            createNumBtns(document.getElementsByClassName("paging")[0], addition_flag ? target.getElementsByClassName("js-itemsList-item").length : pills.length);

            setTimeout(function () {
                var timerScroll;
                var itrs = 0;

                if (window.ajaxpager.peventAjaxRepeatQuery) {
                    window.ajaxpager.peventAjaxRepeatQuery = false;
                }


                (function checkImgs() {
                    var imgs = document.getElementById("target-load-ajaxpager").getElementsByClassName("js-itemsList")[0].getElementsByTagName('img');
                    if (itrs >= 10) {
                        clearTimeout(timerScroll);
                        blurPage("out");
                        itrs = 0;

                        lazyLoad.update(300, document.getElementById("target-load-ajaxpager"));
                    }
                    else {
                        if (imgs.length && !imgs[imgs.length - 1].complete) {
                            clearTimeout(timerScroll);
                            itrs++;
                            timerScroll = setTimeout(checkImgs, 250);
                        }
                        else {
                            clearTimeout(timerScroll);

                            blurPage("out");
                            lazyLoad.update(300, document.getElementById("target-load-ajaxpager"));
                        }
                    }
                })();
            }, 150);
        });
    }

    function createNumBtns(pgn, cardsLenght) {
        // if(!pgn) return;
        var numListWrap;
        if (numListWrap = pgn.getElementsByClassName("pagingNumsList_wrap")[0]) {
            numListWrap.parentNode.removeChild(numListWrap);
        }
        if (!pgn.getElementsByClassName("pagingNumsList_wrap")[0]) {
            var cardsTotal = parseInt(pgn.querySelector(".cards-total").textContent, 10),
                cardsCurr = parseInt(pgn.querySelector(".cards-curr").textContent, 10),
                onePageSize = 40,
                qPages = Math.ceil(cardsTotal / onePageSize),
                pageCurr = Math.ceil(cardsCurr / onePageSize),
                pageNumsListStr = "";

            var url_part_1, url_part_2;
            url_part_1 = document.location.pathname;
            url_part_2 = document.location.search.replace(/\?page_=page_\d{1,}/, "").replace("?", "");

            var q = qPages,
                dottsLeft = [0, 0],
                dottsRight = [0, 0],
                showNumBtnsQ = 7,
                subsequenceQ = 4, // active page and left/right buttons
                neighborsOneSideQ = 1;

            if (getMQ("min-width", "md")) {
                showNumBtnsQ = 9;
                subsequenceQ = 5;
                neighborsOneSideQ = 2;
            }

            if (cardsLenght) {
                pgn.getElementsByClassName("cards-curr")[0].textContent = cardsLenght;
            }



            if (qPages > (showNumBtnsQ + 1)) {
                // dots с двух сторон
                if ((pageCurr > subsequenceQ) && ((qPages - pageCurr) > (subsequenceQ - 1))) {
                    dottsRight[0] = (pageCurr + neighborsOneSideQ + 1);
                    dottsRight[1] = qPages - (pageCurr + neighborsOneSideQ + 1);
                    dottsLeft[1] = (pageCurr - neighborsOneSideQ - 1);
                    dottsLeft[0] = neighborsOneSideQ;
                }
                else {
                    // dots только слева
                    if ((qPages - pageCurr) <= (subsequenceQ - 1)) {
                        dottsLeft[1] = (qPages - (showNumBtnsQ - 2));
                        dottsLeft[0] = neighborsOneSideQ;
                    }
                    // dots только справа
                    else if (pageCurr <= subsequenceQ) {
                        dottsRight[0] = (showNumBtnsQ - 1);
                        dottsRight[1] = dottsRight[0] + (qPages - dottsRight[0] - 1);
                    }
                }
                for (var j = 1; j <= q; j++) {
                    if (j == 1) {
                        pageNumsListStr += "<div class='pagingNumsList_wrap'><ul class='paging_list'>";
                        pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), j, "");
                        continue;
                    }
                    // dots с двух сторон
                    if (dottsLeft[0] != 0 && dottsRight[0] != 0) {
                        if ((j == dottsLeft[1])) {
                            pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), "...", "");
                            continue;
                        }
                        else if ((j == dottsRight[0])) {
                            pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), "...", "");
                            continue;
                        }

                        if (
                            (j > dottsLeft[1])
                            &&
                            (j < dottsRight[0])
                        ) {
                            pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), j, "");
                        }
                        if (j == q) {
                            pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), j, "");
                        }
                    }
                    else {
                        // dots только слева
                        if (dottsLeft[0] != 0) {
                            if (j == dottsLeft[1]) {
                                pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), "...", "");
                                continue;
                            }
                            if (j > dottsLeft[1] && j < q) {
                                pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), j, "");
                            }
                            if (j == q) {
                                pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), j, "");
                            }
                        }
                        // dots только справа
                        else if (dottsRight[0] != 0) {
                            if (j < dottsRight[0]) {
                                pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), j, "");
                            }
                            if (j == dottsRight[0]) {
                                pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), "...", "");
                                continue;
                            }
                            if (j > dottsRight[1]) {
                                pageNumsListStr += oneNumBtnStr(j, true, (j == pageCurr ? ' activePage' : ''), j, "");
                            }
                        }
                    }
                    if (j == q) {
                        pageNumsListStr += "</ul>";
                    }
                }
            }
            // qPages <= showNumBtnsQ
            else {

                for (var i = 1; i <= q; i++) {
                    if (i == 1) {
                        pageNumsListStr += "<div class='pagingNumsList_wrap'><ul class='paging_list'>";
                        pageNumsListStr += oneNumBtnStr(i, true, (i == pageCurr ? ' activePage' : ''), i, "");
                        continue;
                    }

                    pageNumsListStr += oneNumBtnStr(i, true, (i == pageCurr ? ' activePage' : ''), i, "");
                    if (i == q) {
                        pageNumsListStr += "</ul>";
                    }
                }

            }

            if (pageCurr > 1) {
                pageNumsListStr += oneNumBtnStr((pageCurr - 1), false, "", "<i class='fal fa-chevron-left'></i>", "btn-numPage-arrowL");
            }
            if (pageCurr < q) {
                pageNumsListStr += oneNumBtnStr((pageCurr + 1), false, "", "<i class='fal fa-chevron-right'></i>", "btn-numPage-arrowR");
            }
            pageNumsListStr += "</div>";
            pgn.insertAdjacentHTML("beforeEnd", pageNumsListStr);

            function oneNumBtnStr(itr, isLi, active, content, addedClass) {
                var str = "";

                if (url_part_2) {
                    url_part_2 = "&" + url_part_2;
                    url_part_2 = url_part_2.replace(/&{2,}/, "&").replace(/\?{1,}/, "");
                }
                else {
                    url_part_2 = "";
                }

                if (isLi) {
                    str += "<li>";
                }

                if (itr == 1) {
                    if (url_part_2) {
                        url_part_2 = url_part_2.replace(/&/, "?");
                    }
                    str += "<a class='btn btn-white btn-numPage " + addedClass + active + "' href='" + url_part_1 + url_part_2 + "' data-page='" + itr + "' aria-label='Go to page " + itr + "'>" + content + "</a>";
                }
                else {
                    str += "<a class='btn btn-white btn-numPage " + addedClass + active + "' href='" + url_part_1 + "?page_=page_" + itr + url_part_2 + "' data-page='" + itr + "'aria-label='Go to page " + itr + "'>" + content + "</a>";
                }


                if (isLi) {
                    str += "</li>";
                }

                return str;
            }

        }
    };
}

function eyeShowPass(btnEye) {
    btnEye.classList.toggle('shown');
    btnEye.classList.contains('shown') ? btnEye.parentNode.querySelector('input').setAttribute('type', 'text') : btnEye.parentNode.querySelector('input').setAttribute('type', 'password')
};

/*$(".oneProd-photos-fullscreen-slick").on("afterChange", function (event, slick) {
     window.oneProdGal.stopVideosoneProdGal
});
$(".oneProd-photos-galery-slick").on("afterChange", function (event, slick) {
     window.oneProdGal.stopVideos();
});*/

function flyToDestination(flayer, destination, clsStr, size) {
    var clone,
        flayerCoords = getCoords(flayer),
        destinCoords = getCoords(destination),
        cls = clsStr ? clsStr + "ToFly" : "",
        size = size.length ? "width:" + size[0] + "px; height:" + size[1] + "px;" : "",
        id_0 = id_1 = id_2 = 0;

    if (clsStr == "cart") {
        clone = "<span id='cloneFlying' class='cloneFlying " + cls + "' style='top:" + (flayerCoords.top) + "px; left:" + flayerCoords.left + "px;" + size + "'><img src='" + flayer.src + "'/></span>";
    }
    else {
        clone = "<span id='cloneFlying' class='cloneFlying " + cls + "' style='top:" + (flayerCoords.top) + "px; left:" + flayerCoords.left + "px;" + size + "'></span>";
    }
    document.body.insertAdjacentHTML("beforeEnd", clone);

    clearTimeout(id_1);
    clearTimeout(id_2);

    id_0 = setTimeout(function () {
        clone = document.querySelector(".cloneFlying");
        id_1 = setTimeout(function () {
            if (clsStr == "cart") {
                clone.style.cssText = "top:" + (destinCoords.top) + "px; left:" + destinCoords.left + "px; width:25px; height25px";
            }
            else {
                clone.style.cssText = "top:" + (destinCoords.top) + "px; left:" + destinCoords.left + "px";
            }
        }, 15);
        id_2 = setTimeout(function () {
            destination.className += " shaking";
            var clones = document.querySelectorAll(".cloneFlying"),
                clonesLen = clones.length - 1;

            while (clonesLen >= 0) {
                clones[clonesLen].parentNode.removeChild(clones[clonesLen]);
                clonesLen--;
            }
        }, 1000);
        setTimeout(function () { destination.classList.remove("shaking"); }, 2000);
    }, 100)
};

function getCoords(el) {
    var box = el.getBoundingClientRect();
    var html = document.documentElement;

    var scrollTop = window.pageYOffset || html.scrollTop;
    var scrollLeft = window.pageXOffset || html.scrollLeft;

    var top = box.top + scrollTop;
    var left = box.left + scrollLeft;
    var BCRleft = parseInt(box.left, 10);
    var BCRtop = parseInt(box.top, 10);
    var w = el.clientWidth;
    var h = el.clientHeight;

    return { top: Math.round(top), left: Math.round(left), w: w, h: h, BCRleft: BCRleft, BCRtop: BCRtop }
};

/*function onPlayerStateChange(player_id){
     console.log(player_id);
                return function(event) {
                     if(players[player_id].getPlayerState() == 3 || players[player_id].getPlayerState() == 1) {
                          console.log("3 1");
                     }

                     if(players[player_id].getPlayerState() == 0 || players[player_id].getPlayerState() == 2) {
                        console.log("0 2");
                     }
                };
          }*/

var tooltipCustom = {
    action: function (trigger) {
        var root = $(trigger).closest(".tooltipCustom-root")[0];
        if (root && (typeof root != "undefined")) {
            if (root.classList.contains("tooltipCustom-shown")) {
                tooltipCustom.hide(root);
            }
            else {
                tooltipCustom.show(root);
                if (root.classList.contains("oneProd-discont")) {
                    root.querySelector(".tooltipCustom-content").innerHTML = root.querySelector(".tooltipCustom-content").innerHTML.replace("XXX", root.querySelector(".discont").textContent);
                }
            }
        }
    },
    close: function (trigger) {
        var root = $(trigger).closest(".tooltipCustom-root")[0];
        if ((root && (typeof root != "undefined")) && root.classList.contains("tooltipCustom-shown")) {
            tooltipCustom.hide(root);
        }
    },
    hide: function (root) {
        root.classList.remove("tooltipCustom-shown");
    },
    show: function (root) {
        root.classList.add("tooltipCustom-shown");
    }
}

function showActionCategoriesPopup(e) {
    e.stopPropagation();
    var p = document.getElementsByClassName("popup-actionCategories")[0],
        m = document.getElementsByClassName("actionPage-aside-inner")[0];

    if (p) {
        p.getElementsByClassName("popup-body-cnt")[0].innerHTML = m.innerHTML;
        popup.show({ id: 'actionCategories' });
    }
}

var headerFixedPnl = {
    pnl: undefined,
    header: undefined,
    isNeedRecalc: true,

    init: function () {
        if (this.pnl = document.getElementsByClassName("header_rowToSlide")[0]) {
            this.header = document.getElementsByClassName("headerMain")[0];
            setTimeout(function () {
                window.headerFixedPnl.check();
            }, 500);
        }
    },
    check: function () {
        var self = this;
        if (!document.getElementsByClassName("header_rowToSlide")[0]) {
            return false;
        }
        if (self.header) {
            self.pnl = document.getElementsByClassName("header_rowToSlide")[0];

            if (!getMQ("min-width", "sm")) {
                self.clean();
            }
            else {
                const trigger = document.querySelector(".headerMain-row_2");
                const pnl = document.querySelector(".header_rowToSlide");
                const observer = new IntersectionObserver(([entry]) => {
                    if (entry.isIntersecting) {
                        self.clean();
                    }
                    else {
                        pnl.classList.add("slidingOnBigScreen");
                        setTimeout(function () {
                            window.headerFixedPnl.pnl.classList.add("showup");
                        }, 50);
                    }
                }, {
                    root: null,
                    threshold: 0,
                    rootMargin: "-80px 0px 0px 0px"
                })
                observer.observe(trigger);
            }
        }
    },
    /* check: function () {
        var self = this;
        if (!document.getElementsByClassName("header_rowToSlide")[0]) {
            return false;
        }
        if (self.header) {
            self.pnl = document.getElementsByClassName("header_rowToSlide")[0];

            if (!getMQ("min-width", "sm")) {
                self.clean();
            }
            else {
                if (Math.abs(self.header.getBoundingClientRect().top) > (self.pnl.clientHeight)) {
                    if (!self.pnl.classList.contains("slidingOnBigScreen")) {
                        if (self.isNeedRecalc) {
                            self.isNeedRecalc = false;
                            self.calc();
                        }
                        self.pnl.classList.add("slidingOnBigScreen");
                        setTimeout(function () {
                            window.headerFixedPnl.pnl.classList.add("showup");
                        }, 50);
                    }
                }
                else {
                    if (self.pnl.classList.contains("slidingOnBigScreen")) {
                        if (!self.isNeedRecalc) {
                            self.isNeedRecalc = true;
                            self.clean();
                        }
                    }
                }
            }
        }
    }, */
    calc: function () {
        if (!document.getElementsByClassName("header_rowToSlide")[0]) {
            return false;
        }
    },
    clean: function () {
        var self = window.headerFixedPnl;
        if (self.pnl == undefined) {
            if (self.pnl = document.getElementsByClassName("header_rowToSlide")[0]) {
                self.header = document.getElementsByClassName("headerMain")[0];
            }
        }
        self.pnl.classList.remove("showup");
        self.pnl.classList.remove("slidingOnBigScreen");

        self.pnl.removeAttribute("style");
        self.header.removeAttribute("style");
    }
};

var checkAge = {
    init: function () {
        if (document.querySelector("[data-age18plus='True']")) {
            if (!getCookie("checkAge")) {
                popup.show({ id: "checkAge", cnt: window.checkAgeTxt });
            }
        }
    },
    iam18ageplus: function (p) {
        SetCookie("checkAge", "1");
        popup.close(p);
    }
}

var shortenedContent = {
    init: function () {
        var sc;
        if (sc = document.querySelector(".js-shortenedContent")) {
            if (document.querySelector(".js-shortenedContent-inner").scrollHeight > (sc.getAttribute("data-init-h") * 1)) {
                sc.classList.add("collapsed");
            }
        }
    },
    open: function (lnk) {
        var sc = lnk.parentNode,
            scInner = sc.querySelector(".js-shortenedContent-inner");

        sc.classList.remove("collapsed");
        sc.classList.add("uncollapsed");
        scInner.style.height = sc.getAttribute("data-init-h") + "px";
        scInner.style.maxHeight = "none";
        scInner.style.height = scInner.scrollHeight + "px";
    },
    close: function (lnk) {
        var sc = lnk.parentNode,
            scInner = sc.querySelector(".js-shortenedContent-inner");

        sc.classList.remove("uncollapsed");
        sc.classList.add("collapsed");
        scInner.style.height = sc.getAttribute("data-init-h") + "px";
    }
}

String.prototype.hashCode = function () {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
        chr = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

// e-commerce
function addGTM() {
    let src = "/bundles/js/counters?v=1";
    return new Promise((resolve, reject) => {
        let script = document.createElement('script');
        script.type = "text/javascript";
        script.async = true;
        script.src = src;
        script.onload = function () {
            document.documentElement.classList.add("gtmLoaded");
            resolve(script);
        };
        script.onerror = function () {
            reject(new Error(`Script load error for ${src}`))
        };
        if (document.querySelectorAll(`script[src*="${src}"]`).length <= 0) {
            document.body.appendChild(script);
        }
    })
}
function isGtmLoaded() {
    window.dataLayer = window.dataLayer || [];
    let gtmStartedEvent = window.dataLayer.find(element => element['gtm.start']);
    if (!gtmStartedEvent) {
        return false; // Not even the GTM inline config has executed
    }
    else if (!gtmStartedEvent['gtm.uniqueEventId']) {
        return false; // GTM inline config has ran, but main GTM js is not loaded (likely AdBlock, NoScript, URL blocking etc.)
    }
    return true; // GTM is fully loaded and working
}
function gtmPurchase(order) {

    //gtag('set', { 'analyticsCookieId': get_ga_clientid() });

    var items = order.goods.map(p => {
        var r = {};
        r.item_name = p.name;
        r.item_id = p.code;
        r.currency = 'MDL';
        r.item_brand = p.brand;
        r.item_category = p.item_category;
        r.item_category2 = p.item_category2;
        r.item_category3 = p.item_category3;
        r.item_category4 = p.item_category4;
        r.price = p.price;
        r.quantity = p.quantity;
        return r;
    });

    dataLayer.push({ ecommerce: null });
    dataLayer.push({
        event: "purchase",
        ecommerce: {
            transaction_id: order.orderNumber, // Номер заказа
            value: order.price, // Общая стоимость заказа. Разделитель десятичных «точка»
            currency: "MDL",  // Валюта заказа
            payment_type: order.paymentType, // Тип оплати
            coupon: order.promoCode,  // Купон на скидку (если есть)
            bonuses: order.discount,   // Сумма бонусов (если есть)
            gift_card: order.gift, // Код подарочной карты (если есть)
            shipping_type: order.shippingType, // Вид доставки
            shipping: order.shipping, // Стоимость доставки. Разделитель десятичных «точка» 
            tax: "0",      // Налог в случае наличия
            items: items
        }
    });

    // gtag event
    //var gprods = order.goods.map(p => {
    //    var r = {};
    //    r.id = p.id.toString();
    //    r.name = p.name.toString();
    //    r.category = p.item_category3.toString();
    //    r.price = p.price;
    //    r.quantity = p.quantity;
    //    return r;
    //});

    //gtag('event', 'purchase', {
    //    "transaction_id": order.orderNumber,
    //    "value": order.price,
    //    "shipping": order.shipping,
    //    "items": gprods
    //});
}

function get_ga_clientid() {
    var cookie = {};
    document.cookie.split(';').forEach(function (el) {
        var splitCookie = el.split('=');
        var key = splitCookie[0].trim();
        var value = splitCookie[1];
        cookie[key] = value;
    });

    if ('undefined' === typeof cookie['_ga']) { return '' };

    return cookie['_ga'].substring(6);
}

// +
function gtmViewListProducts(viewName, ids) {
    $.getJSON("/handlers/ProductsGA.ashx?ids=" + ids.toString(), function (data) {
        item_list_name = viewName;
        var items = data.map(p => {
            return { ...p, item_list_name };
        });

        // console.log("gtmViewListProducts", viewName, " = ", items);

        //max 25 items in request
        for (let i = 1; i <= (items.length / 25) + 1; i++) {
            dataLayer.push({ ecommerce: null });
            dataLayer.push({
                event: "view_item_list",
                ecommerce: {
                    items: items.slice((i - 1) * 25, 25 * i)
                }
            });
        }
    });
}
// +
function gtmSelectItem(viewName, id, promoName, promoId) {

    SetCookie("gtmSenderCardInfo", "viewName:" + viewName + ",id:" + id + ",promoName:" + promoName + ",promoId:" + promoId);
    $.getJSON("/handlers/ProductsGA.ashx?ids=" + id, function (data) {
        let item_list_name = viewName;
        let promotion_name = promoName;
        let promotion_id = promoId;
        var items = data.map(p => {
            return { ...p, item_list_name, promotion_name, promotion_id };
        });

        // console.log("gtmSelectItem", " = ", items);

        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: "select_item",
            ecommerce: {
                item_list_name: item_list_name,
                promotion_name: promotion_name,
                promotion_id: promotion_id,
                items: items
            }
        });
    });
}
// +
function gtmViewItem(id) {

    var cookStr = "", cookObj = [];

    if (cookStr = getCookie("gtmSenderCardInfo")) {
        let cookArr = cookStr.split(",");

        cookArr.forEach((i) => {
            // создаю объпект cookObj c ключами 'viewName', 'id' и т.д.
            cookObj[i.split(":")[0]] = i.split(":")[1];
        });
        // для досупа к viewName => cookObj.viewName
        // console.log("gtmViewItem", " = ", cookObj);
        deleteCookie("gtmSenderCardInfo");
    }

    $.getJSON("/handlers/ProductsGA.ashx?ids=" + id, function (data) {
        let item_list_name = cookObj?.viewName;
        let promotion_name = cookObj?.promoName;
        let promotion_id = cookObj?.promoId;
        var items = data.map(p => {
            return { ...p, item_list_name, promotion_name, promotion_id };
        });
        // console.log("gtmViewItem view_item", " = ", items);        
        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: "view_item",
            ecommerce: {
                currency: "MDL",
                value: items.reduce((partialSum, a) => partialSum + (a.quantity * a.price), 0),
                items: items
            }
        });
    });
}
// +
function gtmAddToCart(id, viewName, promoName, promoId) {

    $.getJSON("/handlers/ProductsGA.ashx?ids=" + id, function (data) {
        // console.log("gtmAddToCart", " = ", data);
        let item_list_name = viewName;
        let promotion_name = promoName;
        let promotion_id = promoId;
        var items = data.map(p => {
            return { ...p, item_list_name, promotion_name, promotion_id };
        });
        // console.log("gtmAddToCart", " = ", items);
        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: "add_to_cart",
            ecommerce: {
                currency: "MDL",
                value: items.reduce((partialSum, a) => partialSum + (a.quantity * a.price), 0),
                items: items
            }
        });
    });
}
// +
function gtmRemoveFromCart(id, quantity) {

    $.getJSON("/handlers/ProductsGA.ashx?ids=" + id, function (data) {
        data[0].quantity = quantity;

        // console.log("gtmRemoveFromCart", " = ", data);

        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: "remove_from_cart",
            ecommerce: {
                items: data
            }
        });
    });
}
// +
function gtmBeginCheckout(goods) {

    var items = goods.map(p => {
        var r = {};
        r.item_name = p.name;
        r.item_id = p.code;
        r.currency = 'MDL';
        r.item_brand = p.brand;
        r.item_category = p.item_category;
        r.item_category2 = p.item_category2;
        r.item_category3 = p.item_category3;
        r.item_category4 = p.item_category4;
        r.price = p.price;
        r.quantity = p.quantity;
        return r;
    });

    // console.log("gtmBeginCheckout", " = ", items);

    dataLayer.push({ ecommerce: null });
    dataLayer.push({
        event: "begin_checkout",
        ecommerce: {
            currency: "MDL",
            value: items.reduce((partialSum, a) => partialSum + (a.quantity * a.price), 0),
            items: items
        }
    });
}
// +
function gtmAddShippingInfo(shippingType, ids) {

    $.getJSON("/handlers/ProductsGA.ashx?ids=" + ids.toString(), function (data) {
        // console.log("gtmAddShippingInfo", shippingType, data);

        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: "add_shipping_info",
            ecommerce: {
                shipping_type: shippingType,
                items: data
            }
        });
    });
}
// +
function gtmAddPaymentInfo(paymentType, ids) {

    $.getJSON("/handlers/ProductsGA.ashx?ids=" + ids.toString(), function (data) {
        // console.log("gtmAddPaymentInfo", paymentType, data);

        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: "add_payment_info",
            ecommerce: {
                payment_type: paymentType,
                items: data
            }
        });
    });
}

function gtmAddToWishlist(id) {

    $.getJSON("/handlers/ProductsGA.ashx?ids=" + id, function (data) {
        // console.log("gtmAddToWishlist", " = ", data);

        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: "add_to_wishlist",
            ecommerce: {
                items: data
            }
        });
    });
}
// +
function gtmViewPromotion(id, name) {

    // console.log("gtmViewPromotion", " = ", id, name);

    dataLayer.push({ ecommerce: null });
    dataLayer.push({
        event: "view_promotion ",
        ecommerce: {
            promotion_name: name,
            promotion_id: id,
            creative_name: "banner",
            location_id: "top slider",
            items: []
        }
    });
}
// +
function gtmSelectPromotion(id, name) {

    // console.log("gtmSelectPromotion", " = ", id, name);

    dataLayer.push({ ecommerce: null });
    dataLayer.push({
        event: "select_promotion ",
        ecommerce: {
            promotion_name: name,
            promotion_id: id,
            creative_name: "banner",
            location_id: "top slider",
            items: []
        }
    });
}

function changeLang(lang) {
    //if (userInfo.isLogined) {
    SetCookie("siteLang", "lang:" + lang, 180);
    //}
}

var accordionAkaBS = {
    init: function (toggler) {
        if (toggler.classList.contains("collapsed")) {
            this.open(toggler);
        }
        else {
            this.close(toggler);
        }
    },
    open: function (toggler) {
        toggler.classList.remove("collapsed");
        toggler.setAttribute("aria-expanded", "true");
        let target = toggler.getAttribute("data-target") ? toggler.getAttribute("data-target") : toggler.getAttribute("href");
        target = document.getElementById(target.replace("#", ""));
        if (target) {
            target.classList.add("show", "collapsing");
            target.classList.remove("collapse");
            target.style.height = target.scrollHeight + "px";
            setTimeout(function () {
                target.classList.remove("collapsing");
                setTimeout(function () {
                    target.classList.add("collapse")
                }, 0);
            }, 400);
        }
    },
    close: function (toggler) {
        toggler.classList.add("collapsed");
        toggler.setAttribute("aria-expanded", "false");
        let target = toggler.getAttribute("data-target") ? toggler.getAttribute("data-target") : toggler.getAttribute("href");
        target = document.getElementById(target.replace("#", ""));
        if (target) {
            target.classList.remove("collapse");
            target.classList.add("collapsing");
            target.style.height = "0px";
            setTimeout(function () {
                target.classList.remove("collapsing");
                target.classList.remove("show")
                setTimeout(function () {
                    target.classList.add("collapse");
                }, 0);
            }, 400);
        }
    }
};

var sputnikBonusData = {
    popupNode: undefined,
    formNode: undefined,
    SmsCodeEncoded: undefined,
    init: function () {

        document.addEventListener("keydown", eventDocKeydownPopupSputinik, false);

        function eventDocKeydownPopupSputinik(e) {
            // Enter
            if (e.keyCode == 13) {
                // prevent send form in popup		
                if (e.target.closest(".vld-form-sputnik")) {
                    e.preventDefault();
                }
            }
        }
    },
    check: function (e, sender) {

        e.preventDefault();

        this.popupNode = sender.closest(".popup-sputnik");
        this.formNode = this.popupNode.querySelector(".vld-form-sputnik");

        this.popupNode.classList.add("spinner");

        const data = this.serializeForm(this.formNode);
        this.sendRequest(data);
    },
    close: function () {
        popup.close(".popup-sputnik", false);
    },
    serializeForm: function (form) {
        let dataStr = {};
        const data = Array.from(form.elements)
            .filter((item) => !!item.name)
            .filter((item) => !item.hidden)
            .map((el) => {
                // const {name, value} = el;
                dataStr[el.name] = el.value;
            });
        dataStr['lang'] = getLanguage();

        if (this.SmsCodeEncoded) {
            dataStr['SmsCodeEncoded'] = this.SmsCodeEncoded;
            // this.SmsCodeEncoded = undefined;
        }
        return JSON.stringify(dataStr);
    },
    sendRequest: async function (data) {
        const url = "/Handlers/UserCreate.ashx";
        const response = await _getResponse(data);

        function _getResponse(data) {
            return fetch(url, {
                method: "POST",
                headers: { 'Content-type': 'application/json; charset=UTF-8' },
                body: data
            })
        };
        const jsonResponse = await response.json();

        // вывод сообщиний без участия SMS
        if (jsonResponse.isSuccess || (!jsonResponse.isSuccess && (typeof jsonResponse.SmsCodeEncoded == "undefined"))) {
            this.feedback(jsonResponse, response);
        }
        else {
            if (!jsonResponse.isSuccess) {
                if (typeof jsonResponse.SmsCodeEncoded != "undefined") {
                    // вывожу сообщение под полем SmsCode
                    if (jsonResponse.message) {
                        this.popupNode.classList.remove("spinner");

                        if (!this.popupNode.querySelector(".SmsCodeWrong")) {
                            let mess = document.createElement("div");
                            mess.className = "vld-field-wrongMessage SmsCodeWrong";
                            mess.textContent = jsonResponse.message;
                            this.popupNode.querySelector("[name='SmsCode']").parentNode.appendChild(mess);
                        }
                        else {
                            this.popupNode.querySelector(".SmsCodeWrong").textContent = jsonResponse.message;
                        }

                    }
                    // добавляю поле для sms
                    else {
                        this.SmsCodeEncoded = jsonResponse.SmsCodeEncoded;
                        if (this.popupNode.querySelector(".col-codesms").classList.contains("d-none")) {
                            this.popupNode.querySelector(".col-codesms").classList.remove("d-none");
                            this.popupNode.querySelector("[name='SmsCode']").removeAttribute("hidden");
                        }

                        // дизейблю все поля кроме SmsCode
                        Array.from(this.formNode.elements).forEach((item, itr) => {
                            if (item.type != "button" && item.name != "SmsCode") {
                                item.classList.add("disabled");
                            }
                        })

                        this.popupNode.classList.remove("spinner");

                        setTimeout(function () {
                            window.vld.checkForm(document.querySelector(".vld-form-sputnik"))
                        }, 30);

                    }
                }
            }

        }
    },
    feedback: function (jsonResponse, response) {
        if (response.ok) {
            this.popupNode.classList.remove("spinner");
            this.formNode.parentNode.removeChild(this.formNode);

            // обычный ответ isSuccess =  true
            if (jsonResponse.isSuccess) {
                this.popupNode.classList.add("feedbackPositive");
                this.popupNode.querySelector(".feedback-positive").innerHTML = jsonResponse.message;
            }
            else {
                // обычный ответ isSuccess =  false
                if (typeof jsonResponse.SmsCodeEncoded == "undefined") {
                    this.popupNode.classList.add("feedbackNegative");
                    this.popupNode.querySelector(".feedback-negative").innerHTML = jsonResponse.message;
                }
                // есть SmsCodeEncoded
                else {
                    if (jsonResponse.message) {
                        this.popupNode.classList.add("feedbackNegative");
                        this.popupNode.querySelector(".feedback-negative").innerHTML = jsonResponse.message;
                    }
                }
            }
        }
    }
};

var attachAvatar = {
    validTypes: ".webp, .jpeg, .jpg, .png, .gif, .svg, .heic",
    toggledClass: "attached",
    containerClass: "",
    base64string: "",
    get: function (sender, containerClass, fileSizeMB = 5, textSizeFile = "") {
        this.containerClass = containerClass;
        let fileInput = sender;
        if (fileInput.value) {
            if (fileInput.files.length) {
                var filename = fileInput.files[0].name;
                var file = fileInput.files[0];

                const maxAllowedSize = fileSizeMB * 1024 * 1024;

                let oldError;
                let container = sender.closest("." + this.containerClass);
                container.classList.remove(this.toggledClass);
                if (oldError = container.querySelector(".profile-shortInfo-fileError")) {
                    container.removeChild(oldError);
                }
                if (fileInput.files[0].size > maxAllowedSize) {
                    let error = document.createElement("div");
                    error.className = "profile-shortInfo-fileError";
                    if (!textSizeFile) {
                        error.textContent = "Файл не должен превышать " + fileSizeMB + "MB";
                    }
                    else {
                        error.textContent = textSizeFile.replace("N", fileSizeMB);
                    }

                    container.appendChild(error);
                    fileInput.value = ''
                }
                else {
                    this.output(file, filename, fileInput);
                }
            }
        }
    },
    output: function (file, nameStr, inputEl) {
        let container;
        let self = this;
        if (file && (container = inputEl.closest("." + this.containerClass))) {
            var preview = container.querySelector('.profile-shortInfo-avatar');
            var reader = new FileReader();

            reader.readAsDataURL(file);

            reader.onloadend = function () {
                container.classList.add("profile-shortInfo-avatarLoaded");
                self.base64string = reader.result;
                preview.style.backgroundImage = `url(${self.base64string})`;

                new Promise(resolve => {
                    if (reader.readyState == 2) {
                        resolve();
                    }
                }).then(() => {
                    self.send();
                });
            }
        }
        else {
            preview.style.backgroundImage = "";
        }
    },
    send: async function () {
        let data = this.base64string;
        try {
            let result = await fetch('/Handlers/Userapi.ashx', {
                method: "POST",
                headers: { 'Content-type': 'text/plain; charset=UTF-8' },
                body: data
            })
        }
        catch {
            console.error('При отправки аватара произошла ошибка!', err);
        }
    }
};

window.digiLayer = {
    offer_id: null,
    whishlistState: function () {

        return new Promise(function (resolve, reject) {

            fetch("/handlers/UserInfo.ashx?r=" + (new Date()).valueOf())
                .then(respons => respons.json())
                .then(r => {
                    let self = window.digiLayer;
                    self.offer_id = r.Favorites;
                    // console.log("window.digiLayer.offer_id = ", self.offer_id);
                    resolve(self.offer_id);
                })
        })
    },
    addToWishlist: function (productId) {
        return new Promise(function (resolve, reject) {

            var index = isValInArr(productId, userInfo.favorites);

            if (index === false) {
                fetch("/handlers/favorites.ashx?productId=" + productId)
                    .then(() => {
                        userInfo.setActiveFavoriteClass(document.querySelector(`.card[data-product="${productId}"]`));
                        userInfo.favorites.push(productId);
                        userInfo.setHeaderIcos("favorites", ".favorIco");
                        resolve();
                    })
                //gtm
                gtmAddToWishlist(productId);
            }
        })
    },
    removeFromWishlist: function (productId) {
        return new Promise(function (resolve, reject) {

            var index = isValInArr(productId, userInfo.favorites);

            if (index !== false) {
                fetch("/handlers/favorites.ashx?cmd=delete&productId=" + productId)
                    .then(() => {
                        let cardFavor = document.querySelector(`.card[data-product="${productId}"]`);
                        if (cardFavor) {
                            cardFavor.classList.remove("card-inFavor");
                            userInfo.favorites.splice(index, 1);
                            userInfo.setHeaderIcos("favorites", ".favorIco");

                            if (cardFavor.closest(".favoritesPage")) {
                                cardFavor.classList.add("d-none");
                            }
                        }
                        resolve();
                    })
            }
        })
    },
    comparesState: function () {

        return new Promise(function (resolve, reject) {

            fetch("/handlers/UserInfo.ashx?r=" + (new Date()).valueOf())
                .then(respons => respons.json())
                .then(r => {
                    let self = window.digiLayer;
                    self.offer_id = r.Compared;
                    // console.log("window.digiLayer.offer_id = ", self.offer_id);
                    resolve(self.offer_id);
                })
        })
    },
    addToCompare: function (productId) {
        return new Promise(function (resolve, reject) {

            var index = isValInArr(productId, userInfo.compared);

            if (index === false) {
                fetch("/handlers/compare.ashx?cmd=add&productId=" + productId)
                    .then(() => {
                        let card = document.querySelector(`.card[data-product="${productId}"]`);
                        if (card) {
                            if (card.classList.contains("card")) {
                                card.classList.add("card-inCompare");
                            }
                        }
                        userInfo.compared.push(productId);
                        userInfo.setHeaderIcos("compared", ".compareIco");
                        userInfo.setCompareLink();
                        resolve();
                    })
            }
        })
    },
    removeFromCompare: function (productId) {
        return new Promise(function (resolve, reject) {

            var index = isValInArr(productId, userInfo.compared);

            if (index !== false) {
                fetch("/handlers/compare.ashx?cmd=delete&productId=" + productId)
                    .then(() => {
                        let card = document.querySelector(`.card[data-product="${productId}"]`);
                        if (card) {
                            if (card.classList.contains("card")) {
                                card.classList.remove("card-inCompare");
                            }
                        }
                        userInfo.compared.splice(index, 1);
                        userInfo.setHeaderIcos("compared", ".compareIco");
                        userInfo.setCompareLink();
                        resolve();
                    })
            }
        })
    },
    addToCart: function (productId) {
        return new Promise(function (resolve, reject) {
            let card = document.querySelector(`.card[data-product="${productId}"]`);

            fetch("/cart.ashx?cmd=add&productId=" + productId + "&lng=" + getLanguage())
                .then(j => j.json())
                .then(response => {
                    var kolvo = document.querySelector(".cartIco a .kolvo");
                    if (!kolvo) {
                        document.querySelector(".cartIco a").insertAdjacentHTML("afterBegin", '<div class="kolvo"></div>');
                        kolvo = document.querySelector(".cartIco a .kolvo");
                    }
                    kolvo.textContent = response.Products.length;

                    if (card) {
                        card.classList.add("card-inCart");
                        card.querySelector(".card-cart").classList.remove("spinner");
                    }

                    setTimeout(function () {
                        popup.show({ id: "preCart", "url": "/standalone/AddedToCart.aspx?productId=" + productId + "&lng=" + getLanguage() });
                    }, 1500);

                    //esputnik event
                    eSputnikStatusCartSendEvent();
                    //gtm
                    let viewName = "";
                    let dataGAnode;

                    let promoName = "", promoId = "";
                    if (card) {
                        if (dataGAnode = card.closest("[data-ga]")) {
                            viewName = dataGAnode.getAttribute("data-ga");
                        }
                        if (dataGAnode = card.closest("[data-ga-promoname]")) {
                            promoName = dataGAnode.getAttribute("data-ga-promoname");
                        }
                        if (dataGAnode = card.closest("[data-ga-promoid]")) {
                            promoId = dataGAnode.getAttribute("data-ga-promoid");
                        }
                    }
                    gtmAddToCart(productId, viewName, promoName, promoId);

                    resolve(true);
                    window.digiLayer.cartState();
                })
        })
    },
    cartState: function () {
        return new Promise(function (resolve, reject) {
            fetch("/cart.ashx?cmd")
                .then(j => j.json())
                .then(response => {
                    let cartProds = {};
                    let _prodStr = "";
                    if (response.Products.length) {
                        response.Products.forEach((prod, index) => {
                            let comma = index > 0 ? ", " : "";
                            _prodStr += comma + "\"" + prod.ID + "\"" + ":" + prod.Quantity;
                        })
                        cartProds = JSON.parse("{" + _prodStr + "}");
                    }
                    else {
                        cartProds = JSON.parse('{ "products" : 0 }');
                    }
                    // console.log(cartProds);

                    resolve(cartProds);
                })
        })
    },
    //createLink: function () {
    //    var siteId = getLanguage() == "ro" ? 8039 : 7795;
    //    var digiScript = document.createElement('script');
    //    digiScript.src = '//cdn.diginetica.net/' + siteId + '/client.js';
    //    digiScript.defer = true;
    //    digiScript.async = true;
    //    document.head.appendChild(digiScript);
    //}
}

function cartAddedProducts() {
    fetch("/cart.ashx").then((respons) => respons.json())
        .then((dataCart) => {
            if (dataCart.Products.length) {
                let ids = [];
                let prodPage;
                dataCart.Products.forEach((item) => {
                    ids.push(item.ID);
                })
                let cards = document.querySelectorAll(".card:not(.card-inCart)");
                if (cards.length) {
                    cards.forEach((card) => {
                        if (ids.includes(card.dataset.product * 1)) {
                            card.classList.add("card-inCart");
                        }
                        if (prodPage = document.querySelector(".oneProd-page:not(.card-inCart)")) {
                            if (ids.includes(prodPage.dataset.product * 1)) {
                                prodPage.classList.add("oneProd-inCart");
                            }
                        }
                    })
                }
                else {
                    if (prodPage = document.querySelector(".oneProd-page:not(.oneProd-inCart)")) {
                        if (ids.includes(prodPage.dataset.product * 1)) {
                            prodPage.classList.add("oneProd-inCart");
                        }
                    }
                }
            }
        })
}

function myLocationPrepare(sender) {
	
	let src = "/js/myLocation.js?v=1";
	sender.classList.add("spinner");
	if (document.querySelectorAll(`script[src*="${src}"]`).length <= 0) {
		window.addScript2(src)
			.then(() => {
				addCss("/css/myLocation.min.css?v=2");
				myLocation.init(sender);
			}) 
	}
	else {
		myLocation.init(sender);
	}	
}
/* 
var warning1Cstuck = {
    init: function () {
        
        if (!getCookie("warning1Cstuck")) {
            popup.show({ id: "warning1Cstuck", cnt: window.getLanguageTag("Popup-warning1Cstuck") });
        }
        
    },
    close: function (p) {
        SetCookie("warning1Cstuck", "1", 0.3);
        popup.close(p);
    }	
}
*/


function eSputnikProductPageSendEvent() {
    //var productId = $(document).find("[data-product]").attr("data-product");
    //var price = $("meta[itemprop='price']").attr("content");
    //var instock = $("meta[itemprop='availability']").attr("content");
    //eS('sendEvent', 'ProductPage', {
    //    'ProductPage': {
    //        'productKey': productId,
    //        'price': price,
    //        'isInStock': instock == 'http://schema.org/InStock' ? 1 : 0
    //    }
    //});
}

function eSputnikStatusCartSendEvent() {
    //var url = "/cart.ashx?r=" + (new Date()).valueOf() + "&lng=" + $("html").attr("lang");
    //setTimeout(() => {
    //    $.getJSON(url, function (data) {
    //        let prods = [];
    //        $.each(data.Products, function (index, value) {
    //            prods.push({
    //                "productKey": value.ID.toString(),
    //                "price": value.Price.toString(),
    //                "quantity": value.Quantity.toString(),
    //                "currency": 'MDL'
    //            });
    //        });
    //        eS('sendEvent', 'StatusCart', {
    //            'StatusCart': prods,
    //            'GUID': getEsputnikCartGuid(prods)
    //        });
    //    });
    //}, 1000);
}

function eSputnikPurchasedItemsSendEvent(order) {
    //var prods = order.goods.map(p => {
    //    var r = {};
    //    r.productKey = p.id.toString();
    //    r.price = p.price.toString();
    //    r.quantity = p.quantity.toString();
    //    r.currency = 'MDL';
    //    return r;
    //});
    //eS('sendEvent', 'PurchasedItems', {
    //    "OrderNumber": order.orderNumber,
    //    "PurchasedItems": prods,
    //    "GUID": getEsputnikCartGuid(prods)
    //});

    //TODO: move to another js file
    //var gprods = order.goods.map(p => {
    //    var r = {};
    //    r.id = p.id.toString();
    //    r.name = p.name.toString();
    //    r.category = p.item_category3.toString();
    //    r.price = p.price;
    //    r.quantity = p.quantity;
    //    return r;
    //});
    //gtag('event', 'purchase', {
    //    "transaction_id": order.orderNumber,
    //    "value": order.price,
    //    "shipping": order.shipping,
    //    "items": gprods
    //});

    //gtag('set', { 'analyticsCookieId': get_ga_clientid() });
}

function get_ga_clientid() {
    var cookie = {};
    document.cookie.split(';').forEach(function (el) {
        var splitCookie = el.split('=');
        var key = splitCookie[0].trim();
        var value = splitCookie[1];
        cookie[key] = value;
    });

    if ('undefined' === typeof cookie['_ga']) { return '' };

    return cookie['_ga'].substring(6);
}

function eSputnikPurchasedItemsOneClickSendEvent(order) {
    //eSputnikPurchasedItemsSendEvent(order);
    //var prods = order.goods.map(p => {
    //    var r = {};
    //    r.productKey = p.id.toString();
    //    r.price = p.price.toString();
    //    r.quantity = p.quantity.toString();
    //    r.currency = 'MDL';
    //    return r;
    //});
    //eS('sendEvent', 'PurchasedItems', {
    //    "OrderNumber": order.orderNumber,
    //    "PurchasedItems": prods
    //});
}

function eSputnikCustomerDataSendEvent() {
    //var url = "/handlers/userinfo.ashx";
    //$.getJSON(url, function (data) {
    //    eS('sendEvent', 'CustomerData', {
    //        'CustomerData': {
    //            'user_email': data.UserData.Email,
    //            'user_name': data.UserData.Name,
    //            'user_client_id': data.UserData.ID.toString(),
    //            'user_phone': data.UserData.Phone.replace('+', '')
    //        }
    //    });
    //});
}

function getEsputnikCartGuid(prods) {
    //let eSputnikCartGuid = localStorage['esCartGuid'] != null ? localStorage['esCartGuid'].split(',')[0] : null;
    //let oldHash = localStorage['esCartGuid'] != null ? localStorage['esCartGuid'].split(',')[1] : null;
    //let newHash = JSON.stringify(prods).hashCode();
    //if (oldHash != newHash) {
    //    eSputnikCartGuid = GenerateGuid();
    //    oldHash = newHash;
    //    localStorage['esCartGuid'] = eSputnikCartGuid + ',' + oldHash;
    //}
    //return eSputnikCartGuid;
}

function GenerateGuid() {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    );
}
