PageSourceSearch

https://umdom123.ru/g/shop2v2/default/js/shop2.2.js

js umdom123.ru collected 2026-09-28 22:59:07 UTC 149,748 bytes, 4,901 lines download raw bytes

1'use strict';
2
3(function($) {
4
5  var $document = $(document);
6  var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/i.test(navigator.userAgent);
7
8  $.expr[':'].style = function(obj, index, meta) {
9    var $obj = $(obj),
10      params = meta[3].split(','),
11      property,
12      value;
13
14    params = $.map(params, function(n) {
15      return $.trim(n);
16    });
17
18    property = params[0];
19    value = params[1];
20
21    if ($obj.css(property) == value) {
22      return true;
23    }
24  };
25
26  $.s3throttle = function(name, func, time) {
27    var id = $.s3throttle.timeouts[name];
28    if (id) {
29      clearTimeout(id);
30    }
31
32    $.s3throttle.timeouts[name] = setTimeout(func, time);
33  };
34
35  $.s3escape = function(text) {
36    return $('<div>').text(text).html();
37  };
38
39  $.s3throttle.timeouts = {};
40
41  $.fn.s3center = function() {
42
43    return this.each(function() {
44      var $this = $(this),
45        isVisible = $this.is(':visible');
46
47      if (!isVisible) {
48        $this.show();
49      }
50
51      $this.css({
52        marginLeft: -$this.outerWidth() / 2,
53        marginTop: -$this.outerHeight() / 2
54      });
55
56      if (!isVisible) {
57        $this.hide();
58      }
59    });
60  };
61
62
63  $.fn.s3deserializeArray = function(arr) {
64    return this.each(function() {
65      var $this = $(this);
66      $.each(arr, function() {
67        var $el = $this.find('[name="' + this.name + '"]');
68        if (!$el.length) {
69          return;
70        }
71        if ($el.is('input[type=radio]')) {
72          $el.filter('[value="' + this.value + '"]').trigger('click');
73        } else {
74          $el.val(this.value).trigger('change');
75        }
76      });
77    });
78  };
79
80  $.fn.caret = function(begin, end) {
81    var range;
82
83    if (this.length === 0 || this.is(':hidden')) {
84      return;
85    }
86
87    if ($.type(begin) === 'number') {
88      end = ($.type(end) === 'number') ? end : begin;
89      return this.each(function() {
90        if (this.setSelectionRange) {
91          this.setSelectionRange(begin, end);
92        } else if (this.createTextRange) {
93          range = this.createTextRange();
94          range.collapse(true);
95          range.moveEnd('character', end);
96          range.moveStart('character', begin);
97          range.select();
98        }
99      });
100    } else {
101      if (this[0].setSelectionRange) {
102        begin = this[0].selectionStart;
103        end = this[0].selectionEnd;
104      } else if (document.selection && document.selection.createRange) {
105        range = document.selection.createRange();
106        begin = 0 - range.duplicate().moveStart('character', -100000);
107        end = begin + range.text.length;
108      }
109      return {
110        begin: begin,
111        end: end
112      };
113    }
114  };
115
116  $.keys = {};
117
118  $.KEYS = {
119    Digit: [48, 57],
120    Backspace: 8,
121    Comma: 44,
122    Point: 46
123  };
124
125  $.each($.KEYS, function(key, value) {
126    $.keys['is' + key] = function(code) {
127      if ($.isArray(value)) {
128        return (value[0] <= code && code <= value[1]);
129      } else {
130        return value === code;
131      }
132    };
133  });
134
135  $.fn.getVal = function() {
136    var values = [];
137
138    this.each(function() {
139      var v = $(this).val();
140      v = parseFloat(v);
141      if (!v) {
142        v = 0;
143      }
144      values.push(v);
145    });
146    return values;
147  };
148
149  $.fn.keyFilter = function(selector, settings) {
150    settings = $.extend({
151      type: 'int',
152      def: '',
153      callback: $.noop
154    }, settings);
155
156    return this.each(function() {
157      var $this = $(this);
158
159      $this.on('keypress', selector, function(e) {
160        var caret, isBackspace, isDigit, isPoint, val, input = $(this);
161		
162		if (e.shiftKey && e.key !== ',') {
163	        if (e.shiftKey || e.ctrlKey) {
164	          return false;
165	        }
166		}
167
168        if (e.which === 0) {
169          return true;
170        }
171
172        isDigit = $.keys.isDigit(e.which);
173        isPoint = $.keys.isPoint(e.which) || $.keys.isComma(e.which);
174        isBackspace = $.keys.isBackspace(e.which);
175
176        if (!isDigit && !isPoint && !isBackspace) {
177          return false;
178        }
179
180        if (settings.type === 'int' && isPoint) {
181          return false;
182        }
183
184        val = input.val().replace(/,/g, '.');
185        caret = input.caret();
186        input.val(val);
187        input.caret(caret.begin, caret.end);
188
189        if (isPoint && val.indexOf('.') !== -1) {
190          return false;
191        }
192      });
193
194      $this.on('keyup', selector, function() {
195        var input = $(this);
196        settings.callback(input);
197      });
198
199      $this.on('blur', selector, function() {
200        var input = $(this);
201        if (input.val() === '') {
202          input.val(settings.def);
203          settings.callback(input);
204        }
205      });
206    });
207  };
208
209  $.fn.getHeights = function() {
210    var values = [],
211      max = 0;
212
213    this.each(function() {
214      var $this = $(this),
215        height;
216
217      $this.css('min-height', 0);
218
219      height = $this.height();
220      values.push(height);
221
222      if (height > max) {
223        max = height;
224      }
225    });
226
227    return {
228      values: values,
229      max: max
230    };
231  };
232
233  $.fn.eachRow = function(processing, deleteMarginRight) {
234    var elements = this,
235      wrap = elements.parent(),
236      wrapWidth, elementWidth, inRow, left, right, i = 0,
237      len;
238
239    if (wrap.get(0) && elements.get(0)) {
240      wrapWidth = wrap.width();
241      elementWidth = elements.outerWidth(true);
242      if (deleteMarginRight) {
243        wrapWidth += parseFloat(elements.css('margin-right'));
244      }
245      inRow = Math.floor(wrapWidth / elementWidth);
246      if (inRow > 1) {
247        for (len = elements.length; i < len; i += inRow) {
248          left = i;
249          right = i + inRow;
250          if (right > len) {
251            right = len;
252          }
253          processing(elements.slice(left, right), elements.eq(left), elements.eq(right - 1));
254        }
255      }
256    }
257    return elements;
258  };
259
260  $.on = function(selector, obj) {
261
262    $.each(obj, function(key, value) {
263
264      $document.on(key, selector, value);
265
266    });
267
268  };
269
270  $.fn.s3tooltip = function(settings) {
271
272    settings = $.extend({
273      data: function() {
274        return this.alt || '';
275      },
276
277      cls: 'tooltip-1',
278      slide: true,
279      dir: 'bottom'
280
281    }, settings);
282
283    var tooltip = $('#shop2-tooltip');
284
285    if (!tooltip.get(0)) {
286      tooltip = $('<div id="shop2-tooltip"></div>');
287      $('body').append(tooltip);
288    }
289
290    var selector = this.selector;
291
292    var win = {
293        $el: $(window)
294      },
295      width,
296      height;
297
298    $.on(selector, {
299
300      mouseenter: function(e) {
301        var html = settings.data.call(this);
302
303        if (!html) {
304          return;
305        }
306
307        win.width = win.$el.width();
308        win.height = win.$el.height();
309
310        tooltip.html(html);
311        tooltip.addClass(settings.cls);
312        tooltip.show();
313
314        width = tooltip.outerWidth(true);
315        height = tooltip.outerHeight(true);
316      },
317
318      mouseleave: function(e) {
319        tooltip.hide();
320        tooltip.removeClass(settings.cls);
321      },
322
323      mousemove: function(e) {
324
325        var left = e.pageX,
326          top = e.pageY,
327          scrollTop = $document.scrollTop();
328
329        if (left + width > win.width) {
330          left -= width;
331        }
332        
333        if ((isMobile && left<0) && $('#shop2-tooltip').hasClass('shop2_multi_tooltip')) {
334        	left = 20;
335        };
336
337        if (settings.dir == 'top') {
338          top -= height;
339
340          if (top < scrollTop) {
341
342            if (settings.slide) {
343
344              top = scrollTop;
345
346            } else {
347
348              top += height;
349            }
350
351          }
352
353        } else {
354
355          if (top + height > win.height + scrollTop) {
356
357            if (settings.slide) {
358
359              top = win.height + scrollTop - height;
360
361            } else {
362
363              top -= height;
364
365            }
366
367          }
368
369        }
370
371        tooltip.css({
372          left: left,
373          top: top
374        });
375
376      }
377    });
378
379  };
380
381})(jQuery);
382
383
384(function($, self) {
385
386  var shop2 = {
387    queue: {},
388    callbacks: {},
389    init: function(settings) {
390
391      $.extend(this, settings);
392
393      this.my = this.my || {};
394
395      $(function() {
396        var queue = shop2.queue;
397        $.each(queue, function(method) {
398          var f = queue[method];
399          if ($.isFunction(f)) {
400            f();
401          }
402        });
403      });
404
405    }
406  };
407
408  if (document.location.search.indexOf('debug') != -1) {
409    shop2.debug = true;
410  }
411
412  try {
413
414    if (window.sessionStorage) {
415      var current = sessionStorage.getItem('shop2_current_url');
416      var url = location.pathname + location.search;
417      if (current != url) {
418        sessionStorage.setItem('shop2_back_url', current);
419      }
420      sessionStorage.setItem('shop2_current_url', url);
421    }
422
423    shop2.back = function() {
424      var url;
425      if (window.sessionStorage) {
426        url = sessionStorage.getItem('shop2_back_url');
427        if (url === 'null') {
428          url = '/';
429        }
430      } else {
431        url = document.referrer;
432      }
433      document.location = url || '/';
434      return false;
435    };
436
437  } catch (e) {
438    shop2.back = function() {
439      document.location = document.referrer;
440    }
441  }
442
443  shop2.on = function(type, func) {
444    var _this = this;
445
446    $.each(type.split(','), function(index, type) {
447      type = $.trim(type);
448
449      if (!_this.callbacks[type]) {
450        _this.callbacks[type] = $.Callbacks();
451      }
452
453      _this.callbacks[type].add(func);
454    });
455  };
456
457  shop2.off = function(type, func) {
458    if (this.callbacks[type]) {
459      func ? this.callbacks[type].remove(func) : this.callbacks[type].empty();
460    }
461  };
462
463  shop2.trigger = function(type) {
464    if (this.callbacks[type]) {
465      this.callbacks[type].fireWith(self, [].slice.call(arguments, 1));
466    }
467  };
468
469  shop2.fire = function(type, func) {
470    if ($.isFunction(func)) {
471      var has = !!(this.callbacks && this.callbacks[type] && this.callbacks[type].has(func));
472
473      if (!has) {
474        func.apply(self, [].slice.call(arguments, 2));
475      }
476    }
477  };
478
479  shop2.filter = {
480    _pre_params: '',
481    init: function() {
482      var search = decodeURIComponent(document.location.search);
483      if (search) {
484        search = search.slice(1);
485      }
486      this.str = search;
487    },
488    escape: function(name) {
489      return name.replace(/(\[|\])/g, '\\$1');
490    },
491    remove: function(name, value) {
492      var str = name + '=';
493      if (typeof value !== 'undefined') {
494        str += value;
495      }
496      var re = new RegExp('(.*)(' + this.escape(str) + '[^&]*&*)(.*)', 'ig');
497      this.str = this.str.replace(re, '$1$3').replace(/&$/, '');
498      return this;
499    },
500    add: function(name, value) {
501      this.remove(name, value);
502      this.str += (this.str !== '') ? '&' : '';
503      this.str += name + '=' + value;
504      return this;
505    },
506    has: function(name, value) {
507      var str = name + '=';
508      if (typeof value !== 'undefined') {
509        str += value;
510      }
511      if (this.str.indexOf(str) > -1) {
512        return true;
513      }
514      return false;
515    },
516    get: function(name) {
517      var re = new RegExp(this.escape(name) + '=([^&]*)'),
518        matches = this.str.match(re);
519      if (matches && matches.length == 2) {
520        return matches[1];
521      }
522      return false;
523    },
524    toggle: function(name, value) {
525
526      if (name == 's[amount][min]') {
527        if (this.get('s[amount][max]') === '0') {
528          this.remove('s[amount][max]');
529          this.add('s[amount][min]', 0);
530          return this;
531        } else if (this.get('s[amount][min]') === '0') {
532          this.remove('s[amount][min]');
533          this.add('s[amount][max]', 0);
534          return this;
535        }
536      } else if (name == 's[amount][max]') {
537        if (this.get('s[amount][min]') === '1') {
538          this.remove('s[amount][min]');
539          this.add('s[amount][min]', 0);
540          return this;
541        } else if (this.get('s[amount][min]') === '0') {
542          this.remove('s[amount][min]');
543          this.add('s[amount][min]', 1);
544          return this;
545        }
546      }
547
548      if (this.has(name, value)) {
549        this.remove(name, value);
550      } else {
551        this.add(name, value);
552      }
553      return this;
554    },
555    sort: function(name) {
556      var re = new RegExp(this.escape('s[sort_by]') + '=([^&]*)'),
557        params = this.str.match(re),
558        desc = name + ' desc',
559        asc = name + ' asc';
560
561      params = (params && params.length > 1) ? params[1] : '';
562
563      if (params.indexOf(desc) !== -1) {
564        params = params.replace(desc, asc);
565      } else if (params.indexOf(asc) !== -1) {
566        params = params.replace(asc, desc);
567      } else if (params !== '') {
568        params += ',' + desc;
569      } else {
570        params = desc;
571      }
572
573      this.remove('s[sort_by]');
574      this.add('s[sort_by]', params);
575      return this;
576    },
577    go: function() {
578      var str = '';
579      if (this.str) {
580        str += (this.str.charAt(0) == '?') ? '' : '?';
581        str += this.str;
582      }
583
584      document.location =
585        document.location.pathname.replace(/\/p\/\d*/g, '') +
586        str +
587        document.location.hash;
588      return false;
589    },
590    count: function(func) {
591      var url = '/-/shop2-api/?cmd=getSearchMatches&hash=' +
592        shop2.apiHash.getSearchMatches +
593        '&ver_id=' + shop2.verId +
594        '&' + this.str +
595        this._pre_params;
596
597      shop2.trigger('beforeGetSearchMatches');
598
599      $.get(
600        url,
601        function(d, status) {
602          if (status == 'success') {
603            if ($.type(d) === 'string') {
604              d = $.parseJSON(d);
605            }
606          }
607
608          if (shop2.facets.enabled) {
609            shop2.facets.aggregation(d);
610          }
611
612          shop2.fire('afterGetSearchMatches', func, d, status);
613          shop2.trigger('afterGetSearchMatches', d, status);
614        }
615      );
616
617    }
618  };
619
620  shop2.search = {
621    getParams: function(folder_id, func) {
622      var url;
623
624      shop2.trigger('beforeGetFolderCustomFields');
625
626      if (folder_id > 0) {
627        url = '/-/shop2-api/?cmd=getFolderCustomFields' +
628          '&hash=' + shop2.apiHash.getFolderCustomFields +
629          '&ver_id=' + shop2.verId +
630          '&folder_id=' + folder_id +
631          '&' + decodeURIComponent(document.location.search).replace(/[^&]*=(&|$)/g, '');
632
633        $.getJSON(url, function(d, status) {
634          shop2.fire('afterGetFolderCustomFields', func, d, status);
635          shop2.trigger('afterGetFolderCustomFields', d, status);
636        });
637      }
638    }
639  };
640
641  shop2.facets = {
642    enabled: false,
643    aggs: null,
644    _data: {},
645    emptyClass: 'empty-val',
646
647    mask: '[data-name^="s[field]"][data-value="key"],' +
648      '[name="s[parentField][parentKey]"] [value="key"],' +
649      '[name="s[field]"] [value="key"],' +
650      '[data-name="s[field][index]"],' +
651      '[data-name="s[field][key]"],' +
652      '[name="s[field][key]"]',
653
654    filter: {
655      wrapper: '.shop2-filter, #shop2-color-ext-list',
656      items: '[data-name], [name], [name] [value]'
657    },
658
659    search: {
660      wrapper: '.shop2-block.search-form form, #shop2-color-ext-select',
661      items: '[data-name], [name], [name] [value]'
662    },
663
664    ignoreClear: function($item) {
665      this._data.attrName = $item.attr('name') ? $item.attr('name') : $item.parent().attr('name');
666      this._data.isSelect = $item.prop('tagName').toLowerCase() === 'select';
667      this._data.val = $item.prop('tagName').toLowerCase() === 'option' && $item.val() === '';
668      return /s\[(folder_id|products_per_page)\]/i.test(this._data.attrName) || this._data.isSelect || this._data.val;
669    },
670
671    set: function(mod /* module filter, search */ ) {
672      var module = shop2.facets[mod];
673
674      if (!module) {
675        return;
676      }
677
678      var $wrapper = $(module.wrapper);
679      var $items = $wrapper.find(module.items);
680
681      this._data.$wrapper = $wrapper;
682
683      this.clearItems($items);
684      this.insertData(this.aggs);
685
686      var eventName = 'afterFacets' + mod.charAt(0).toUpperCase() + mod.slice(1);
687
688      shop2.trigger(eventName, this.aggs);
689    },
690
691    searchSetup: function() {
692      if (!this.search) {
693        return;
694      }
695
696      var $form = $(this.search.wrapper);
697
698      if (!$form.length) {
699        return;
700      }
701
702      var $items = $form.find(this.search.items);
703      var self = this;
704      var url = '/-/shop2-api/?cmd=getSearchMatches&hash=' +
705        shop2.apiHash.getSearchMatches +
706        '&ver_id=' + shop2.verId + '&',
707        fullUrl = url + $form.serialize();
708
709      this.getDataSearch(fullUrl);
710
711      $items.on('change', function(e) {
712        if (e.target.name == "s[products_per_page]") {
713          return;
714        }
715
716        fullUrl = url + $form.serialize()
717
718        self.getDataSearch(fullUrl);
719      });
720    },
721
722    getDataSearch: function(url) {
723      $.get(
724        url,
725        function(d, status) {
726          if (status == 'success') {
727            if ($.type(d) === 'string') {
728              d = $.parseJSON(d);
729            }
730
731            shop2.facets.aggregation(d);
732            shop2.facets.set('search');
733          }
734        }
735      );
736    },
737
738    clearItems: function($items) {
739      var emptyClass = this.emptyClass;
740      var self = this;
741      var $item, nodeName;
742
743      $items.each(function(index, item) {
744        $item = $(item);
745
746        if (self.ignoreClear($item)) {
747          return true;
748        }
749
750        nodeName = $item.prop('tagName').toLowerCase();
751
752        switch (nodeName) {
753          case 'select':
754            break;
755          case 'input':
756            $item.attr('placeholder', '');
757            break;
758          case 'option':
759            if ($item.attr('value')) {
760              $item.attr('disabled', 'disabled');
761            }
762            break;
763        }
764
765        $item.attr('data-param-val', '0');
766        $item.addClass(emptyClass);
767      });
768    },
769
770    aggregation: function(d) {
771      if (typeof d === 'object' && d.data.aggs) {
772        this.aggs = this.dataSetup(d.data.aggs);
773      }
774
775      return this.aggs;
776    },
777
778    dataSetup: function(aggs) {
779      var cf = aggs.cf;
780      var key, field;
781
782      for (key in cf) {
783        field = cf[key];
784
785        if ($.isArray(field) && !field.length) {
786          delete cf[key];
787        }
788      }
789
790      return aggs;
791    },
792
793    insertData: function(aggs, field, parentField) {
794      $.each(aggs, $.proxy(function(key, value) {
795        if (typeof value === "object") {
796          this.insertData(value, key, field);
797        } else {
798          this._data.$item = this.getItem(field, key, parentField);
799
800          if (!this._data.$item.length || (!value && value!=0)) {
801            return true;
802          }
803
804          switch (this._data.$item.prop('tagName').toLowerCase()) {
805            case 'input':
806              this._data.$item.attr('placeholder', value);
807              break;
808            case 'option':
809              this._data.$item.removeAttr('disabled');
810              break;
811          }
812
813          this._data.$item.attr('data-param-val', value);
814          this._data.$item.removeClass(this.emptyClass);
815        }
816      }, this));
817    },
818
819    getItem: function(field, key, parentField) {
820      if (parentField && parentField !== 'cf') {
821        this._data.selector = this.mask.replace(/parentField/g, parentField).replace(/parentKe
821y/g, field).replace(/key/g, key);
822      } else {
823        this._data.selector = this.mask.replace(/field/g, field).replace(/key/g, key);
824      }
825
826      return this._data.$wrapper.find(this._data.selector);
827    },
828
829    setMask: function(mask) {
830      this.mask = mask;
831    },
832
833    setEmptyClass: function(emptyClassName) {
834      this.emptyClass = emptyClassName;
835    },
836
837    setContainers: function(module, obj) {
838      this[module] = obj;
839    }
840  };
841
842  shop2.cart = {
843    add: function(kind_id, a4, func) {
844
845      shop2.trigger('beforeCartAddItem');
846
847      $.post(
848        '/-/shop2-api/?cmd=cartAddItem', {
849          hash: shop2.apiHash.cartAddItem,
850          ver_id: shop2.verId,
851          kind_id: kind_id,
852          amount: a4
853        },
854        function(d, status) {
855          shop2.fire('afterCartAddItem', func, d, status);
856          shop2.trigger('afterCartAddItem', d, status);
857        },
858        'json'
859      );
860    },
861
862    addMultiple: function(params, func) {
863
864      shop2.trigger('beforeCartAddMultipleItems');
865
866      params = $.extend({
867        hash: shop2.apiHash.cartAddItem,
868        ver_id: shop2.verId
869      }, params);
870
871      $.post('/-/shop2-api/?cmd=cartAddItem', params, function(d, status) {
872
873        shop2.fire('afterCartAddMultipleItems', func, d, status);
874        shop2.trigger('afterCartAddMultipleItems', d, status);
875
876      }, 'json');
877
878    },
879
880    remove: function(kind_id, func) {
881      kind_id = kind_id.toString().replace(/\"/g, '\\"').replace(/\'/g, '"');
882      kind_id = $.parseJSON(kind_id);
883
884      shop2.trigger('beforeCartRemoveItem');
885
886      $.getJSON(
887        '/-/shop2-api/?cmd=cartRemoveItem', {
888          hash: shop2.apiHash.del,
889          ver_id: shop2.verId,
890          kind_id: kind_id
891        },
892        function(d, status) {
893          shop2.fire('afterCartRemoveItem', func, d, status);
894          shop2.trigger('afterCartRemoveItem', d, status);
895        }
896      );
897
898      return false;
899    },
900
901    clear: function() {
902
903      shop2.trigger('beforeCartClear');
904      $.get(shop2.uri + '?mode=cart&action=cleanup', function(d, status) {
905        shop2.trigger('afterCartClear', d, status);
906      });
907
908    },
909
910    update: function(form, func) {
911      var data = form.serialize();
912
913      shop2.trigger('beforeCartUpdate');
914
915      $.post(
916        '/-/shop2-api/?cmd=cartUpdate',
917        'ver_id=' + shop2.verId +
918        '&hash=' + shop2.apiHash.up +
919        '&' + data,
920        function(d, status) {
921          shop2.fire('afterCartUpdate', func, d, status);
922          shop2.trigger('afterCartUpdate', d, status);
923        }
924      );
925
926      return false;
927    },
928
929    /*addCoupon: function(coupon, func) {
930
931      shop2.trigger('beforeCartAddCoupon');
932
933      $.getJSON(
934        '/-/shop2-api/?cmd=cartAddCoupon', {
935          hash: shop2.apiHash.coupon_add,
936          ver_id: shop2.verId,
937          coupon: coupon
938        },
939        function(d, status) {
940          shop2.fire('afterCartAddCoupon', func, d, status);
941          shop2.trigger('afterCartAddCoupon', d, status);
942        }
943      );
944
945      return false;
946    },
947
948    removeCoupon: function(coupon, func) {
949
950      shop2.trigger('beforeCartRemoveCoupon');
951
952      $.getJSON(
953        '/-/shop2-api/?cmd=cartRemoveCoupon', {
954          hash: shop2.apiHash.coupon_del,
955          ver_id: shop2.verId,
956          coupon: coupon
957        },
958        function(d, status) {
959          shop2.fire('afterCartRemoveCoupon', func, d, status);
960          shop2.trigger('afterCartRemoveCoupon', d, status);
961        }
962      );
963    }*/
964    /*1935 Вносил изменения по api */
965    addCoupon: function(coupon, func) {
966
967      shop2.trigger('beforeCartAddCoupon');
968
969      $.getJSON(
970        '/-/x-api/v1/public/?method=cart/addCoupon', {
971            param: {
972              	coupon: coupon
973            }
974        },
975        function(d, status) {
976          shop2.fire('afterCartAddCoupon', func, d, status);
977          shop2.trigger('afterCartAddCoupon', d, status);
978        }
979      );
980
981      return false;
982    },
983    
984    removeCoupon: function(coupon, func) {
985
986      shop2.trigger('beforeCartRemoveCoupon');
987      
988		$.getJSON('/-/x-api/v1/public/?method=cart/removeCoupon', {
989			param: {
990		  		coupon: coupon
991			}
992		}, function (d, status) {
993          shop2.fire('afterCartRemoveCoupon', func, d, status);
994          shop2.trigger('afterCartRemoveCoupon', d, status);
995		});
996    }
997  };
998
999  shop2.delivery = {
1000    deligate: false,
1001    ymapsMap: null,
1002    ymapsData: [],
1003    ymapsIconsData: {
1004      'default': '/g/shop2v2/default/images/map-pin-grey.svg',
1005      'spsr': '/g/shop2v2/default/images/map-pin-red.svg',
1006      'dellin': '/g/shop2v2/default/images/map-pin-purple.svg',
1007      'edostavka': '/g/shop2v2/default/images/map-pin-green.svg',
1008      'pickpoint': '/g/shop2v2/default/images/map-pin-grey.svg',
1009      'boxberry': '/g/shop2v2/default/images/map-pin-boxberry.svg',
1010      'delica': '/g/shop2v2/default/images/map-pin-grey.svg',
1011      'selected': '/g/shop2v2/default/images/map-pin-blue.svg',
1012    },
1013    calc: function(attach_id, params, func) {
1014
1015      shop2.trigger('beforeDeliveryCalc');
1016
1017      $.getJSON(
1018        '/-/shop2-api/?cmd=deliveryCalc', {
1019          hash: shop2.apiHash.calc,
1020          ver_id: shop2.verId,
1021          attach_id: attach_id,
1022          params: params
1023        },
1024        function(d, status) {
1025          shop2.fire('afterDeliveryCalc', func, d, status);
1026          shop2.trigger('afterDeliveryCalc', d, status);
1027        }
1028      );
1029    },
1030    YmapsInit: function(service_code, settings) {
1031      var obj = Object.keys(shop2.delivery.ymapsData).length,
1032        localize_text_div = $('.baloon-content-localize'),
1033        localize_text = {
1034          'point': localize_text_div.data('point-text'),
1035          'term': localize_text_div.data('term-text'),
1036          'price': localize_text_div.data('price-text'),
1037          'address': localize_text_div.data('address-text'),
1038          'phone': localize_text_div.data('phone-text'),
1039          'worktime': localize_text_div.data('worktime-text'),
1040          'url': localize_text_div.data('url-text'),
1041          'more': localize_text_div.data('more-text'),
1042          'choose': localize_text_div.data('choose-text'),
1043        };
1044      if (!obj) {
1045        $('.shop2-delivery--item__tab.points').addClass('disabled');
1046        return false;
1047      }
1048      var dadataJson = $.parseJSON($('#dadata').val()),
1049        coordsCenter = [dadataJson.geo_lat, dadataJson.geo_lon],
1050        options = {
1051          id: service_code,
1052          center: coordsCenter,
1053          zoom: 11,
1054        };
1055
1056      ymaps.ready(function() {
1057        shop2.delivery.ymapsMap = new ymaps.Map(options.id, {
1058          center: options.center,
1059          zoom: options.zoom,
1060          controls: ["zoomControl"]
1061        });
1062        
1063		var settingsProps = {};
1064		if(typeof settings != 'undefined'){
1065			settingsProps = settings;
1066
1067			if(settingsProps.context = 'lpc' ){
1068				settingsProps.baloonClassBtn1 = ' lp-button lpc-button--type-1';
1069				settingsProps.baloonClassBtn2 = ' lp-button lpc-button--type-2';
1070			}
1071		}
1072        
1073        var deligateAddressIndex = $('[data-deligate-address-index]').data('deligate-address-index') || 0;
1074        var MyBalloonContentLayoutClass = ymaps.templateLayoutFactory.createClass(
1075          '<div class="delivery-baloon-content">' +
1076          '<h3>$[properties.address]</h3>' +
1077          '<div class="buttons"><button type="button" class="shop2-btn' + (settingsProps.baloonClassBtn1||'') + '" id="balloon-select">' + localize_text.choose + '</button>[if properties.site]<a target="_blank" class="shop2-btn' + (settingsProps.baloonClassBtn2||'') + '" href="$[properties.site]">' + localize_text.more + '</a>[endif]</div>' +
1078          '<div class="note-block">[if properties.term] <p><span>' + localize_text.term + ':</span><strong class="term">$[properties.term]</strong></p>[endif] <p>$[properties.cost]</p> </div>' +
1079          '[if properties.phone]<div class="phone"><span>' + localize_text.phone + ':</span>$[properties.phone]</div>[endif]' +
1080          '[if properties.worktime]<div class="worktime"><span>' + localize_text.worktime + ':</span>$[properties.worktime]</div>[endif]' +
1081          '[if properties.desc]<div class="desc"><span>' + localize_text.url + ':</span>$[properties.desc]</div>[endif]' +
1082          '<form data-attach_id="$[properties.attach_id]"><input type="hidden" name="delivery_type" value="$[properties.delivery_type]"><input class="point-address" type="hidden" name="$[properties.attach_id]['+deligateAddressIndex+']" value="$[properties.address]"><input type="hidden" name="$[properties.attach_id][deligate][tarif]" class="tariff" value="$[properties.tariff_hash]"><input type="hidden" name="$[properties.attach_id][deligate][terminal]" value="$[properties.id]"></form>' +
1083          '</div>', {
1084            build: function() {
1085              MyBalloonContentLayoutClass.superclass.build.call(this);
1086              $('#balloon-select').bind('click', this.onCounterClick);
1087            },
1088            clear: function() {
1089              $('#balloon-select').unbind('click', this.onCounterClick);
1090              MyBalloonContentLayoutClass.superclass.clear.call(this);
1091            },
1092            onCounterClick: function(e) {
1093              e.preventDefault();
1094              var balloonContent = $(this).parents('.delivery-baloon-content:first'),
1095                form = balloonContent.find('form'),
1096                pointName = balloonContent.find('h3').text(),
1097                pointCostInp = balloonContent.find('label.cost input:checked'),
1098                pointCost = pointCostInp.parent().data('cost'),
1099                pointTerm = balloonContent.find('.term').text(),
1100                attach_id = form.data("attach_id"),
1101                deliveryBlock = $('#shop2-order-delivery'),
1102                options = deliveryBlock.find('.option-label'),
1103                groups = deliveryBlock.find('.option-type'),
1104                details = deliveryBlock.find('.option-details'),
1105                pointTab = deliveryBlock.find('.shop2-delivery--item__tab.points'),
1106                pointFields = $(shop2.delivery.ymapsMap.container._parentElement).next(),
1107                pointAddress = form.find('input.point-address').val(),
1108                option = $(shop2.delivery.ymapsMap.container._parentElement).parents('.option-details:first');
1109
1110              $("#delivery_id_deligate").val(attach_id);
1111              form.find('input.tariff').val(pointCostInp.val());
1112              pointFields.find('.fields').html(form.html());
1113              pointFields.find('.point-name').html(pointName);
1114              pointFields.find('.point-cost').html(pointCost);
1115              pointFields.find('.point-term').html(pointTerm);
1116              pointFields.find('.point-address').html(pointAddress);
1117              option.addClass('selected');
1118              $('html, body').scrollTop(option.parent().offset().top - 60);
1119              //pointFields.show();
1120
1121              // GR_Task/11
1122              if(shop2.shop2_cart_order_payments == 6){
1123                let deligate_this = {};
1124                deligate_this.property_attach = {
1125                    'delivery_type' :  form.find(`[name="delivery_type"]`).val(),
1126                    'deligate' : { 
1127                    'tarif' : pointCostInp.val(),
1128                    'terminal' : form.find(`[name="900[deligate][terminal]"]`).val()
1129                    }
1130                };
1131
1132                deligate_this.property_attach['0'] = pointAddress;
1133                deligate_this.value = attach_id;
1134
1135                $(this)
1136                    .closest('.option-details')
1137                    .find('.g-form-field__value .g-form-control-value')
1138                    .each(function(index, elem){
1139                    let i = index + 1;
1140                    deligate_this.property_attach[ `${i}` ] =  elem.value;
1141                });
1142
1143                shop2.queue.orderGetPayments(true, deligate_this );
1144                }
1145                // GR_Task/11
1146
1147              shop2.delivery.ymapsMap.balloon.close();
1148              /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
1149              if(true){
1150                let on_shop2_btn = shop2.my.on_shop2_btn ? '.shop2-btn' : '.g-button';
1151                if( $(`.form-item ${on_shop2_btn}.shop2-disabled`).length ){
1152                  $(`.form-item ${on_shop2_btn}.shop2-disabled`).removeClass('shop2-disabled');
1153                  $(`.order_design_five`).addClass('hide');
1154                }
1155              }
1156              /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
1157            }
1158          }
1159        );
1160
1161        var myCollection = new ymaps.GeoObjectCollection();
1162
1163        $.each(shop2.delivery.ymapsData[service_code], function(key, item) {
1164          var iconPic = shop2.delivery.ymapsIconsData[service_code] || shop2.delivery.ymapsIconsData['default'];
1165          if (item.service_code == service_code) {
1166          	var placemark = new ymaps.Placemark(
1167              item.coords,
1168              item, {
1169                balloonContentLayout: MyBalloonContentLayoutClass,
1170                iconLayout: 'default#image',
1171                iconImageHref: iconPic,
1172                iconImageSize: [26, 36], // размеры картинки
1173                iconImageOffset: [-13, -36], // смещение картинки
1174                balloonMaxWidth: 530,
1175                balloonPanelMaxMapArea: 'Infinity',
1176                balloonMinHeight: 330,
1177                balloonshadow: false,
1178
1179              }
1180            );
1181            
1182            placemark.events.add('click', function (e) {
1183           		for(var i = 0; i < myCollection.getLength(); i++) {
1184	                myCollection.get(i).options.set('iconImageHref', shop2.delivery.ymapsIconsData['default']);
1185	            }
1186			   	e.get('target')['options'].set('iconImageHref', shop2.delivery.ymapsIconsData['selected']);
1187			});
1188          
1189            myCollection.add(placemark);
1190          }
1191        });
1192
1193        shop2.delivery.ymapsMap.geoObjects.add(myCollection);
1194        shop2.delivery.ymapsMap.container.fitToViewport();
1195        shop2.delivery.ymapsMap.behaviors.disable('multiTouch');
1196        
1197      });
1198    },
1199    changeDeliveryPoint: function(obj, service_code, settings) {
1200      var $this = $(obj),
1201        option = $this.parents('.option-details:first');
1202
1203      if (shop2.delivery.ymapsMap) {
1204        shop2.delivery.ymapsMap.destroy();
1205        shop2.delivery.ymapsMap = null;
1206      }
1207
1208      option.find('.map-select select option:first').prop('selected', true);
1209      option.find('.map-select select').trigger('refresh');
1210      option.find('.deligate_points_fields .fields').empty();
1211      option.removeClass('selected');
1212      $('html, body').scrollTop(option.parent().offset().top - 60);
1213      
1214		if(typeof settings != 'undefined'){
1215			shop2.delivery.YmapsInit(service_code, settings);
1216		}else {
1217			shop2.delivery.YmapsInit(service_code);
1218		}	
1219      /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
1220      if(true){
1221        let on_shop2_btn = shop2.my.on_shop2_btn ? '.shop2-btn' : '.g-button';
1222        if( $(`.form-item ${on_shop2_btn}`).length ){
1223          $(`.form-item ${on_shop2_btn}`).addClass('shop2-disabled');
1224          $(`.order_design_five`).removeClass('hide');
1225          
1226        }
1227      }
1228      /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
1229      return false;
1230    },
1231    selectSuggestion: function(value, enter) {
1232      var name = value;
1233      $.ajax({
1234        url: '/-/x-api/v1/public/?method=deligate/suggestAddress',
1235        type: 'POST',
1236        dataType: 'json',
1237        data: JSON.stringify({
1238          query: name,
1239          count: 1
1240        }),
1241        success: function(suggestion) {
1242          if (suggestion.result.suggestions) {
1243            suggestion.result.suggestions[0].data.source = name;
1244          }
1245          if (enter) {
1246            $('#shop2-deligate-calc').trigger('click');
1247          } else {
1248            $("#dadata").val(JSON.stringify(suggestion.result.suggestions[0].data));
1249            $("#address").val(suggestion.result.suggestions[0].value);
1250            $('#shop2-deligate-calc').trigger('click');
1251          }
1252        }
1253      });
1254    }
1255  };
1256
1257  /*shop2.compare = {
1258    add: function(kind_id, callback) {
1259      this.action('add', kind_id, callback);
1260    },
1261    remove: function(kind_id, callback) {
1262      this.action('del', kind_id, callback);
1263    },
1264    clear: function(callback) {
1265      this.action('clear', null, callback);
1266    },
1267    action: function(action, kind_id, func) {
1268
1269      var eventName = $.camelCase('Compare-' + action);
1270
1271      shop2.trigger('before' + eventName);
1272
1273      $.post(
1274        '/-/shop2-api/?cmd=compare', {
1275          hash: shop2.apiHash.compare,
1276          ver_id: shop2.verId,
1277          kind_id: kind_id,
1278          action: action
1279        },
1280        function(d, status) {
1281          shop2.fire('after' + eventName, func, d, status);
1282          shop2.trigger('after' + eventName, d, status);
1283        }
1284      );
1285    }
1286  };*/
1287  /*1935 Вносил правки по api */
1288  shop2.compare = {
1289    add: function(kind_id, callback) {
1290      this.action('add', kind_id, callback);
1291    },
1292    remove: function(kind_id, callback) {
1293      this.action('del', kind_id, callback);
1294    },
1295    clear: function(callback) {
1296      this.action('clear', null, callback);
1297    },
1298    action: function(action, kind_id, func) {
1299
1300      var eventName = $.camelCase('Compare-' + action);
1301
1302      shop2.trigger('before' + eventName);
1303
1304      $.post(
1305        '/-/x-api/v1/public/?method=shop2/compare', {
1306        	kind_id,
1307	        action,
1308        },
1309        function(d, status) {
1310          shop2.fire('after' + eventName, func, d.result, status);
1311          shop2.trigger('after' + eventName, d.result, status);
1312        }
1313      );
1314    }
1315  };
1316
1317  shop2.product = {
1318    getProductListItem: function(product_id, kind_id, func, params) {
1319      var url = '/-/shop2-api/?cmd=getProductListItem&hash=' + shop2.apiHash.getProductListItem + '&ver_id=' + shop2.verId;
1320      shop2.trigger('beforeGetProductListItem');
1321      $.post(
1322        url, {
1323          product_id: product_id,
1324          kind_id: kind_id,
1325          params: params
1326        },
1327        function(d, status) {
1328          shop2.fire('afterGetProductListItem', func, d, status);
1329          shop2.trigger('afterGetProductListItem', d, status);
1330        }
1331      );
1332    },
1333
1334    checkMetaItemValue: function(meta, key, value) {
1335
1336      var res = meta[key];
1337
1338      if (res == "undefined" || res == null) {
1339        return false;
1340      }
1341
1342      if (res == value) {
1343        return true;
1344      }
1345
1346      if (res instanceof Object) {
1347        for (var i in res) {
1348          if (res[i] == value) {
1349            return true;
1350          }
1351        }
1352      }
1353
1354      return false;
1355
1356    },
1357
1358    getMetaItemValue: function(meta, key) {
1359      var res = meta[key];
1360
1361      if ($.type(res) === 'undefined') {
1362        return false;
1363      }
1364
1365      if ($.type(res) === 'object') {
1366
1367        if ($.type(res.v) !== 'undefined') {
1368          return res.v;
1369        }
1370
1371        if ($.type(res.image_id) !== 'undefined') {
1372          return res.image_id;
1373        }
1374
1375      }
1376
1377      return res;
1378    },
1379
1380    findKindId: function(product_id, kinds, paramName, paramValue, meta, keys) {
1381      var i;
1382      var len;
1383      var d;
1384      var kind;
1385      var matches;
1386      var lastMatches = 0;
1387      var refs = $.extend(true, {}, shop2.productRefs[product_id]);
1388
1389      if (keys) {
1390        $.each(refs, function(key) {
1391          if (!keys[key]) {
1392            delete refs[key];
1393          }
1394        });
1395      }
1396
1397      if (kinds.length == 1) {
1398        return kinds[0];
1399      }
1400
1401      if ($.type(meta) !== 'object') {
1402        meta = $.parseJSON(meta);
1403      }
1404
1405      for (i = 0, len = kinds.length; i < len; i += 1) {
1406        d = Number(kinds[i]);
1407        matches = 0;
1408
1409        $.each(refs, function(p, ref) {
1410
1411          $.each(ref, function(v) {
1412
1413            if (p == paramName) {
1414
1415              if (v == paramValue) {
1416                matches += 1;
1417              }
1418
1419            } else {
1420
1421              if (String(refs[p][v]).indexOf(d) === -1) {
1422                return;
1423              }
1424
1425              matches += 1;
1426
1427              if (meta && shop2.product.checkMetaItemValue(meta, p, v)) {
1428                matches += 1;
1429              }
1430
1431            }
1432
1433          });
1434
1435        });
1436
1437        if (matches > lastMatches) {
1438          kind = d;
1439          lastMatches = matches;
1440        }
1441
1442      }
1443
1444      return kind;
1445    },
1446
1447    getNodeData: function(node, key, decode) {
1448      var data = false;
1449
1450      if (node.tagName == 'SELECT') {
1451        data = $(node.options[node.selectedIndex]).data(key);
1452      } else if (node.nodeType == 1) {
1453        data = $(node).data(key);
1454      }
1455
1456      if (decode) {
1457        data = this.decodeFieldData(data);
1458      }
1459
1460      return data;
1461    },
1462
1463    decodeFieldData: function(data) {
1464
1465      if ($.type(data) !== 'string') {
1466        return [data];
1467      }
1468
1469      data = data.split(',');
1470
1471      return $.map(data, function(n) {
1472        return $.trim(n);
1473      });
1474
1475    },
1476
1477    hasKindId: function(data, kinds) {
1478      var i, len;
1479      if (data) {
1480        for (i = 0, len = kinds.length; i < len; i += 1) {
1481          if (data.indexOf(kinds[i]) !== -1) {
1482            return true;
1483          }
1484        }
1485      }
1486      return false;
1487    },
1488
1489
1490    deleteUploadProduct: function(name, kind_id){
1491        var data = new FormData();
1492        data.append('kind_id', kind_id);
1493        data.append('code', name);
1494        $.ajax({
1495            url: '/-/x-api/v1/public/?method=shop2/removeUploadFileProduct',
1496            type: 'post',
1497            dataType: 'json',
1498            processData: false,
1499            contentType: false,
1500            data: data,
1501            success: function(result) {
1502                var result = typeof result.result != 'undefined' ? result.result : result
1503                if (result.success) {
1504                    document.location.reload(true);
1505                  } else {
1506                      alert(result.error);
1507                  }
1508            }
1509        });
1510    },
1511    
1512    uploadProduct: function(name, kind_id, image, params){
1513      
1514        var data = new FormData(),
1515            parent = $('#_upload_'+name+kind_id).parent(),
1516            file = $('#_upload_'+name+kind_id).get(0).files,
1517            button_del = '<span class="delete-upload-file shop2-btn" onclick="shop2.product.deleteUploadProduct(\''+ name +'\',' + kind_id +')">удалить</span>';
1518            
1519            
1520        if (file.length == 0) {
1521            alert(_s3Lang.JS_FILES_NOT_SELECTED);
1522            return false;
1523        }
1524
1525        $.each(file, function(key, value){
1526            data.append(name, value);
1527        });
1528        data.append('kind_id', kind_id);
1529        data.append('code', name);
1530        if (image) {
1531            data.append('image', true);
1532            if (params) {
1533                data.append('params', JSON.stringify(params));
1534            }
1535        }
1536        $.ajax({
1537            url: '/-/x-api/v1/public/?method=shop2/uploadFileProduct',
1538            type: 'post',
1539            dataType: 'json',
1540            processData: false,
1541            contentType: false,
1542            data: data,
1543            success: function(result) {
1544                var result = typeof result.result != 'undefined' ? result.result : result;
1545                if (result.success) {
1546                    if (image) {
1547                        parent.empty().html('<img src="' + result.data + '">' + button_del);
1548                    } else {
1549                        parent.empty().html('<a href="' + result.data + '" target="_blank">' + result.data + '</a>' + button_del);
1550                    }
1551                  } else {
1552                      alert(result.error);
1553                  }
1554            }
1555        });
1556        
1557    },
1558    
1559    uploadInCart: function(kind_id, pos, name, image, params){
1560        var data = new FormData(),
1561            parent = $('#_upload_in_cart_'+ kind_id + '_' + pos + '_' + name).parent(),
1562            file = $('#_upload_in_cart_'+ kind_id + '_' + pos + '_' + name).get(0).files,
1563            button_del = '<span class="delete-upload-file shop2-btn" onclick="shop2.product.deleteUploadInCart('+ kind_id + ', ' + pos + ', ' + '\'' + name + '\')">удалить</span>';
1564        if (file.length == 0) {
1565            alert(_s3Lang.JS_FILES_NOT_SELECTED);
1566            return false;
1567        }
1568            
1569
1570        $.each(file, function(key, value){
1571            data.append(name, value);
1572        });
1573        data.append('kind_id', kind_id);
1574        data.append('code', name);
1575        data.append('pos', pos);
1576        if (image) {
1577            data.append('image', true);
1578            if (params) {
1579                data.append('params', JSON.stringify(params));
1580            }
1581        }
1582        $.ajax({
1583            url: '/-/x-api/v1/public/?method=shop2/uploadFileProductInCart',
1584            type: 'post',
1585            dataType: 'json',
1586            processData: false,
1587            contentType: false,
1588            data: data,
1589            success: function(result) {
1590                var result = typeof result.result != 'undefined' ? result.result : result;
1591                if (result.success) {
1592                    if (image) {
1593                        parent.empty().html('<img src="' + result.data + '">' + button_del);
1594                    } else {
1595                        parent.empty().html('<a href="' + result.data + '" target="_blank">' + result.data + '</a>' + button_del);
1596                    }
1597                  } else {
1598                      alert(result.error);
1599                  }
1600            }
1601        });
1602    },
1603    
1604    deleteUploadInCart: function(kind_id, pos, name){
1605        var data = new FormData();
1606        data.append('kind_id', kind_id);
1607        data.append('code', name);
1608        data.append('pos', pos);
1609        $.ajax({
1610            url: '/-/x-api/v1/public/?method=shop2/removeUploadFileProductInCart',
1611            type: 'post',
1612            dataType: 'json',
1613            processData: false,
1614            contentType: false,
1615            data: data,
1616            success: function(result) {
1617                var result = typeof result.result != 'undefined' ? result.result : result
1618                
1619                if (result.success) {
1620                    document.location.reload(true);
1621                  } else {
1622                      alert(result.error);
1623                  }
1624            }
1625        });
1626    },
1627    
1628    productDatePicker: function() {
1629      $(".shop2-date_interval , .shop2-date").each(function(index, el) {
1630        $(this).datepicker({
1631              minDate:0,
1632              changeMonth: false,
1633              numberOfMonths: 1,
1634              showOn: "button",
1635        buttonImage: "/g/shop2v2/default/images/shop2_calendar.svg",
1636        buttonImageOnly: false,
1637        buttonText: "Select date"
1638          });
1639      });
1640    }
1641  };
1642
1643  shop2.options = {
1644    amountDefaultValue: 1,
1645    amountDefaultInc: 1,
1646    amountType: 'float',
1647    msgTime: 3000,
1648    printCSS: '/g/shop2v2/default/css/print.less.css'
1649  };
1650  
1651  shop2.user = {
1652    activate: function(user_id, target) {
1653      var $target = $(target);
1654      
1655      $target.attr('disabled', true);
1656  
1657      $.post('/-/x-api/v1/public/?method=user/reactivation', {
1658        'user_id': user_id,
1659      }, function() {
1660        var $parent = $target.parent(),
1661            $message = $('<div>').addClass('shop2-info').html(window._s3Lang.ACTIVATION_MAIL_SENT);
1662      
1663        $target.hide();
1664        $parent.append($message);
1665      });
1666    },
1667  };
1668
1669  //* client-order-cancelling *//
1670  shop2.orderCancelling = {
1671    alert: function() {
1672      var linkButton = $('.order-cancelling'),
1673        attrToLinkOrder = linkButton.data('href'),
1674        attrLinkTitle = linkButton.data('cancellingTitle'),
1675        attrLinkButtonTitle = linkButton.data('cancellingButtonTitle'),
1676        attrLinkButtonClose = linkButton.data('cancellingClose'),
1677
1678        html = '<div class="order-cancel-title">' + attrLinkTitle + '</div>' +
1679        '<div class="order-cancel-buttons">' +
1680        '<a class="shop2-btn" href="' + attrToLinkOrder + '">' + attrLinkButtonTitle + '</a>' +
1681        '<a class="shop2-alert-close" onclick="shop2.alert.hide(); return false;" href="#">' + attrLinkButtonClose + '</a>' +
1682        '</div>';
1683
1684      shop2.alert(html, '', 'shop2-alert--warning order-cancel');
1685    }
1686  };
1687  $(document).on('click', '.order-cancelling', function(e) {
1688    e.preventDefault();
1689    shop2.orderCancelling.alert();
1690  });
1691
1692  //* client-order-repeat *//
1693  shop2.orderRepeat = {
1694    alert: function($this) {
1695      var linkButton = $this.filter('.order-repeat'),
1696        attrToLinkOrder = linkButton.data('href'),
1697        attrLinkTitle = linkButton.data('repeatTitle'),
1698        attrLinkButtonTitle = linkButton.data('repeatButtonTitle'),
1699        attrLinkButtonClose = linkButton.data('repeatClose'),
1700
1701        html = '<div class="order-repeat-title">' + attrLinkTitle + '?</div>' +
1702        '<div class="order-repeat-buttons">' +
1703        '<a class="shop2-btn" href="' + attrToLinkOrder + '">' + attrLinkButtonTitle + '</a>' +
1704        //'<a class="shop2-btn" href="#" onclick="location.href=\'' + attrToLinkOrder + '\'">'+ attrLinkButtonTitle +'</a>' +
1705        '<a class="shop2-alert-close" onclick="shop2.alert.hide(); return false;" href="#">
1705' + attrLinkButtonClose + '</a>' +
1706        '</div>';
1707      shop2.alert(html, 'Закрыть', 'shop2-alert--warning order-cancel');
1708    }
1709  };
1710  $(document).on('click', '.order-repeat', function(e) {
1711    e.preventDefault();
1712    shop2.orderRepeat.alert($(this));
1713  });
1714  
1715  //* client-order-payment-change *//
1716  shop2.paymentChange = {
1717      alert: function($this) {
1718          var linkButton = $this.filter('.order-payment-change'),
1719              url = linkButton.data('href'),
1720              title = linkButton.data('title'),
1721              button_title = linkButton.data('button-title'),
1722              button_close = linkButton.data('close');
1723
1724          $.ajax({
1725              url: url,
1726              type: 'POST',
1727              dataType: 'json',
1728              data: {},
1729              success: function(res) {
1730                  var html = '<div class="payment-change-title">' + title + '</div><div class="error"></div>' + res.data +
1731                      '<div class="payment-change-buttons">' +
1732                      '<a class="shop2-btn" onclick="shop2.paymentChange.save(\'' + url.replace('act=list', 'act=save') + '\');" href="#">' + button_title + '</a>' +
1733                      '<a class="shop2-alert-close" onclick="shop2.alert.hide(); return false;" href="#">' + button_close + '</a>' +
1734                      '</div>';
1735                  shop2.alert(html, button_close, 'shop2-alert--warning order-cancel');
1736              }
1737          });
1738      },
1739      save: function (url) {
1740          var form_data = $('#shop2-alert-body .shop2-payment-options').serialize();
1741          $.ajax({
1742              url: url + '&' + form_data,
1743              type: 'POST',
1744              dataType: 'json',
1745              data: {},
1746              success: function(res) {
1747                  if (res.data === "OK") {
1748                      document.location.reload();
1749                  } else {
1750                      $('#shop2-alert-body .error').html(res.data);
1751                  }
1752              }
1753          });
1754
1755          return false;
1756      }
1757  };
1758
1759  $(document).on('click', '.order-payment-change', function(e) {
1760    e.preventDefault();
1761    shop2.paymentChange.alert($(this));
1762  });
1763  
1764  $(document).on('click.getPromoLink', '.get-promo-link', function(e) {
1765    e.preventDefault();
1766    //shop2.paymentChange.alert($(this));
1767    var ver_id = $(this).data('ver-id'),
1768        cmd = $(this).data('cmd'),
1769        hash = shop2.apiHash.getPromoProducts,
1770        is_main = $(this).data('is-main'),
1771        kind_id = $(this).data('kind-id'),
1772        discount_id = $(this).data('discount-id');
1773          $.ajax({
1774              url: '/-/shop2-api/?ver_id=' + ver_id + '&cmd=' + cmd + '&hash=' + hash + '&kind_id=' + kind_id + '&discount_id=' + discount_id + '&is_main=' + is_main,
1775              type: 'POST',
1776              dataType: 'json',
1777              data: {},
1778              success: function(res) {
1779                  shop2.alert(res.data, 'Закрыть', 'promo-products-list');
1780              }
1781          });    
1782  });
1783  $(document).on('click.promoPagelist', '.promo-products-list li', function(e) {
1784          e.preventDefault();
1785          var url = $(this).find('a').attr('href');
1786          $.ajax({
1787              url: url,
1788              type: 'POST',
1789              dataType: 'json',
1790              data: {},
1791              success: function(res) {
1792                  shop2.alert(res.data, 'Закрыть', 'promo-products-list');
1793              }
1794          });            
1795  });
1796
1797  shop2.msg = function(text, obj) {
1798    var selector = '#shop2-msg',
1799      msg = $(selector),
1800      offset = obj.offset(),
1801      width = obj.outerWidth(true),
1802      height = obj.outerHeight(true);
1803
1804    if (!msg.get(0)) {
1805      msg = $('<div id="shop2-msg">');
1806      $(document.body).append(msg);
1807      msg = $(selector);
1808    }
1809
1810    msg.html(text).show();
1811
1812    var msgWidth = msg.outerWidth();
1813    var left = offset.left + width;
1814    var top = offset.top + height;
1815
1816    if (left + msgWidth > $(window).width()) {
1817      left = offset.left - msgWidth;
1818    }
1819
1820    msg.css({
1821      left: left,
1822      top: top
1823    });
1824
1825    $.s3throttle('msg', function() {
1826      msg.hide();
1827    }, shop2.options.msgTime);
1828
1829  };
1830
1831  shop2.queue = {
1832
1833    cookiesDisabled: function() {
1834      if (navigator && navigator.cookieEnabled == false) {
1835        $('.shop2-cookies-disabled')
1836          .html('<p>Внимание! Для корректной работы у Вас в браузере должна быть включена поддержка cookie. В случае если по каким-либо техническим причинам передача и хранение cookie у Вас не поддерживается оформление заказа невозможно.</p>')
1837          .removeClass('hide');
1838      }
1839    },
1840
1841    cartState: function() {
1842
1843      try {
1844        window.sessionStorage;
1845      } catch (e) {
1846        return;
1847      }
1848
1849      if (!window.chrome || !sessionStorage || !shop2.my.save_cart_state) {
1850        return;
1851      }
1852
1853      if (!readCookie('s3s2_cart')) {
1854        sessionStorage.removeItem('cart-reload');
1855        sessionStorage.removeItem('cart-state');
1856      }
1857
1858      function getHTML() {
1859        return $('<div>').append($('#shop2-cart-preview').clone()).html();
1860      }
1861
1862      function setHTML(html) {
1863        if (html) {
1864          $('#shop2-cart-preview').replaceWith(html);
1865        }
1866      }
1867
1868      if (sessionStorage.getItem('cart-reload') == 1) {
1869        sessionStorage.removeItem('cart-reload');
1870        sessionStorage.setItem('cart-state', getHTML());
1871      }
1872
1873      shop2.on('afterCartAddItem', function(res, status) {
1874        var html = res.data;
1875        if (status != 'success') {
1876          html = '';
1877        }
1878        sessionStorage.setItem('cart-state', html);
1879      });
1880
1881      shop2.on('afterCartRemoveItem, afterCartUpdate', function() {
1882        sessionStorage.setItem('cart-reload', 1);
1883      });
1884
1885      $(window).on('pageshow', function() {
1886        setHTML(sessionStorage.getItem('cart-state'));
1887      });
1888
1889    },
1890
1891    keys: function() {
1892
1893      $(document).keyFilter('input.shop2-input-int');
1894
1895      $(document).keyFilter('input.shop2-input-float', {
1896        type: 'float'
1897      });
1898
1899    },
1900
1901    heights: function() {
1902
1903      $('.product-list-thumbs').each(function() {
1904        var $this = $(this);
1905
1906        $this.find('.product-item-thumb').eachRow(function(group) {
1907          var heights;
1908          var names = group.find('.product-name');
1909          var nHeights;
1910
1911          names.css('min-height', 0);
1912          nHeights = names.getHeights();
1913          names.css('min-height', nHeights.max);
1914
1915          var $sp = group.find('.product-amount');
1916
1917          if ($sp.length) {
1918            $sp.css('margin-top', 0);
1919            heights = group.getHeights();
1920            group.each(function(i) {
1921              $(this).find('.product-amount').css('margin-top', heights.max - heights.values[i]);
1922            });
1923          } else {
1924            group.each(function() {
1925              var $this = $(this);
1926              var $sp = $this.find('.shop2-product-actions');
1927              if (!$sp.length) {
1928                $sp = $this.find('.product-bot');
1929              }
1930              var paddingTop = $sp.data('padding-top');
1931              if ($.type(paddingTop) === 'undefined') {
1932                paddingTop = parseInt($this.css('padding-top'));
1933                $sp.data('padding-top', paddingTop);
1934              }
1935              $sp.css('padding-top', paddingTop);
1936            });
1937            heights = group.getHeights();
1938            group.each(function(i) {
1939              var $this = $(this);
1940              var $sp = $this.find('.shop2-product-actions');
1941              if (!$sp.length) {
1942                $sp = $this.find('.product-bot');
1943              }
1944              var paddingTop = $sp.data('padding-top');
1945              $sp.css('padding-top', heights.max - heights.values[i] + paddingTop);
1946            });
1947          }
1948        });
1949      });
1950
1951    },
1952
1953    resize: function() {
1954
1955      $(window).resize(function() {
1956        shop2.queue.heights();
1957      });
1958
1959    },
1960
1961    product: function() {
1962
1963      shop2.product._reload = function(node) {
1964        var $node = $(node);
1965        var kinds = shop2.product.getNodeData(node, 'kinds', true);
1966        var paramName = shop2.product.getNodeData(node, 'name');
1967        var paramValue = shop2.product.getNodeData(node, 'value');
1968        var $form = $node.closest('form');
1969        var form = $form.get(0);
1970        var meta;
1971        var kind_id;
1972        var product_id;
1973        var keys = {};
1974        var params = {};
1975        var is_param_select = false;
1976        if (kinds && $.type(paramName) !== 'undefined' && $.type(paramValue) !== 'undefined' && form) {
1977          meta = $form.find('input[name=meta]').val();
1978          product_id = $form.find('input[name=product_id]').val();
1979          $form.find('[name=submit]').prop('disabled', true);
1980          $form.find('select.shop2-cf>option, li.shop2-cf, li.shop2-color-ext-selected, ul.shop2-color-ext-list>li').each(function() {
1981            var name = $(this).data('name');
1982            if (name) {
1983              keys[name] = true;
1984            }
1985          });
1986          kind_id = shop2.product.findKindId(product_id, kinds, paramName, paramValue, meta, keys);
1987          if (!kind_id) {
1988              kind_id = $form.find('[name=kind_id]').val();
1989              is_param_select = true;
1990          }
1991          // select
1992            $form.find('.js-calc-custom-fields.additional-cart-params').each(function() {
1993                var ref_code = $(this).attr('name');
1994                params[ref_code] = $(this).find('option:selected').data('item-id');
1995            });
1996          // colore ref
1997            $form.find('.js-calc-custom-fields.shop2-color-ext-selected').each(function() {
1998                var ref_code = $(this).data('name');
1999                params[ref_code] = $(this).data('item-id');
2000            });
2001          // Selected params
2002          if (is_param_select) {
2003              shop2.product.getProductListItem(product_id, kind_id, function (d, status) {
2004                  if (status === 'success') {
2005                      var body = $.trim(d.data.body);
2006                      var product_price = $(".product-price", body).html();
2007                      var product_actions = $(".shop2-product-actions", body).html();
2008                      $form.find('.product-price').html(product_price);
2009                      $form.find('.shop2-product-actions').html(product_actions);
2010                      shop2.trigger('afterProductReloaded');
2011                      shop2.queue.heights();
2012                  }
2013              }, params);
2014          } else {
2015              if (shop2.mode === 'product') {
2016                  if (shop2.uri) {
2017                      document.location = shop2.uri + '/product/' + kind_id;
2018                  } else {
2019                      document.location = document.location.href.replace(/\/product\/.+/, '/product/' + kind_id);
2020                  }
2021              } else {
2022                  shop2.product.getProductListItem(product_id, kind_id, function (d, status) {
2023                      var cont, newCont, body;
2024                      if (status === 'success') {
2025                          shop2.trigger('afterProductReloaded');
2026                          cont = $node.closest('.shop2-product-item');
2027                          cont.hide();
2028                          body = $.trim(d.data.body);
2029                          newCont = $(body).insertBefore(cont);
2030                          cont.remove();
2031                          shop2.queue.heights();
2032                      }
2033                  }, params);
2034              }
2035          }
2036        }
2037      };
2038
2039      $.on('select.shop2-cf', {
2040        change: function() {
2041          shop2.product._reload(this);
2042        }
2043      });
2044
2045      $.on('li.shop2-cf:not(.active-color, .active-texture)', {
2046        click: function() {
2047          shop2.product._reload(this);
2048        }
2049      });
2050
2051      $.on('span.shop2-path-show-folders', {
2052        click: function(e) {
2053          e.preventDefault();
2054          $(this).next().show();
2055          $(this).hide();
2056        }
2057      });
2058
2059    },
2060
2061    addToCart: function() {
2062
2063
2064      $(document).on('click', '.shop2-product-btn:not(.preorder-btn-js)', function(e) {
2065
2066        var $this = $(this),
2067          $form = $this.closest('form'),
2068          form = $form.get(0),
2069          adds = $form.find('.additional-cart-params'),
2070          len = adds.length,
2071          i, el,
2072          a4 = form.amount.value,
2073          kind_id = form.kind_id.value;
2074
2075        e.preventDefault();
2076
2077        if (len) {
2078          a4 = {
2079            amount: a4
2080          };
2081
2082          for (i = 0; i < len; i += 1) {
2083            el = adds[i];
2084            if (el.value) {
2085              a4[el.name] = el.value;
2086            }
2087          }
2088        }
2089
2090        shop2.cart.add(kind_id, a4, function(d) {
2091
2092          $('#shop2-cart-preview').replaceWith(d.data);
2093
2094          if (d.errstr) {
2095            shop2.msg(d.errstr, $this);
2096          } else {
2097            var $text = window._s3Lang.JS_SHOP2_ADD_CART_WITH_LINK;
2098            // window._s3Lang.JS_ADDED - Добавлено
2099            shop2.msg($text.replace('%s', shop2.uri + '/cart'), $this);
2100          }
2101
2102          if (d.panel) {
2103            $('#shop2-panel').replaceWith(d.panel);
2104          }
2105        });
2106
2107      });
2108
2109    },
2110
2111    amount: function() {
2112
2113	    var $document = $(document);
2114	
2115	    function validate(input) {
2116	        var kind = input.data('kind'),
2117	            max = input.data('max'),
2118	            val = Number(input.val()),
2119	            amount = 0,
2120	            available,
2121	            amount_min = parseFloat(input.data('min')),
2122	            multiplicity = parseFloat(input.data('multiplicity'));
2123	            
2124	        if (amount_min || multiplicity) {
2125	
2126	            if (multiplicity) {
2127	                var x = (val - amount_min) % multiplicity;
2128	
2129	                if (x < (multiplicity / 2)) {
2130	                    val -= x;
2131	                } else {
2132	                    val += multiplicity - x;
2133	                }
2134	
2135	                if (amount_min === 1 && multiplicity > 1) {
2136	                    val--;
2137	                }
2138	
2139	                val = val.toFixed(2) - 0;
2140	
2141	                input.val(val);
2142	            }
2143	
2144	            if (amount_min > 0) {
2145	                if (amount_min && val <= amount_min) {
2146	                    input.val(amount_min);
2147	                }
2148	            } else {
2149	                if (val <= shop2.options.amountDefaultValue) {
2150	                    input.val(shop2.options.amountDefaultValue);
2151	                }
2152	            }
2153	        }
2154	        
2155	
2156	        if (kind && max > 0) {
2157	            amount = Number(input.val());
2158	
2159	            if (amount > max) {
2160	                available = max - amount + val;
2161	
2162	                // Если multiplicity задан, округляем available до ближайшего кратного multiplicity
2163	                if (multiplicity > 0 && available >= multiplicity) {
2164	                    available = Math.floor(available / multiplicity) * multiplicity;
2165	                }
2166	
2167	                input.val(available);
2168	
2169	                available = available.toFixed(2) - 0;
2170	
2171	                shop2.msg(_s3Lang.JS_AVAILABLE_ONLY + ' ' + available, input);
2172	            }
2173	        }
2174	    }
2175	
2176	    $document.on('click', '.amount-minus', function () {
2177	        var $this = $(this),
2178	            text = $this.siblings('input:text'),
2179	            value = text.getVal(),
2180	            amount_min = parseFloat(text.data('min')),
2181	            multiplicity = parseFloat(text.data('multiplicity'));
2182	
2183	        if (value) {
2184	            value = value[0];
2185	        }
2186	
2187	        if (amount_min && value <= amount_min) {
2188	            return;
2189	        }
2190	
2191	        value = checkAmount(value, amount_min, multiplicity, -1);
2192	
2193	        if (amount_min > 0) {
2194	            if (value <= amount_min) {
2195	                value = amount_min;
2196	            }
2197	        } else {
2198	            if (value <= shop2.options.amountDefaultValue) {
2199	                value = shop2.options.amountDefaultValue;
2200	            }
2201	        }
2202	
2203	
2204	
2205	        text.val(value);
2206	        text.trigger('change');
2207	    });
2208	    $document.on('click', '.amount-plus', function () {
2209	        var $this = $(this),
2210	            text = $this.siblings('input:text'),
2211	            value = text.getVal(),
2212	            amount_min = parseFloat(text.data('min')),
2213	            multiplicity = parseFloat(text.data('multiplicity'));
2214	
2215	        if (value) {
2216	            value = value[0];
2217	        }
2218	
2219	        value = checkAmount(value, amount_min, multiplicity, 1);
2220	        text.val(value);
2221	        text.trigger('change');
2222	    });
2223	
2224	    // Если пользователь сделает некорректный ввод числа, то цифра должна изменяться в числовом окне в соответствии с кратным числом
2225	    // (система должна автоматически изменить его на ближайшее или на минимальное к указанному),
2226	
2227	    function checkAmount(amount, amount_min, multiplicity, sign) {
2228	
2229	        if (multiplicity > 0) {
2230	            amount += multiplicity * sign;
2231	        } else {
2232	            amount += shop2.options.amountDefaultInc * sign;
2233	        }
2234	
2235	        amount = amount.toFixed(2) - 0;
2236	
2237	        return amount
2238	    }
2239	
2240	    $document.on('change', '.shop2-product-amount input:text', function () {
2241	        var $this = $(this);
2242	        validate($this);
2243	    });
2244	
2245	    $document.keyFilter('.shop2-product-amount input:text', {
2246	        type: shop2.options.amountType
2247	    });
2248	
2249	},
2250
2251    kindAvailable: function(){
2252        var sentAjax_preorder = function(data, callback){
2253            $.ajax({
2254                url: '/-/x-api/v1/public/?method=shop2/addKindEmailNotification',
2255                method: 'post',
2256                xhrFields: {
2257                    withCredentials: true
2258                },
2259                data: data,
2260                success: function(result) {
2261                    callback(result);
2262                }
2263            });
2264        };
2265        
2266        var object_preorder = {};
2267        $(document).on('click', '.preorder-btn-js', function(e) {
2268            e.preventDefault();
2269            object_preorder.data = {};
2270            
2271            object_preorder.jQbtn = $(this);
2272            object_preorder.data.kind_id = object_preorder.jQbtn.data('product-kind_id');
2273            object_preorder.data.email = object_preorder.jQbtn.data('user-email') || 0;
2274            
2275            if( object_preorder.data.email ){
2276                var temp_email = `
2277                <div class="preorder-field preorder-email">
2278                    <span class="preorder-email_text">
2279                        ${shop2.my.preorder_email_text||'Данный email указан при регистрации.'}
2280                    </span>
2281                    <div class="preorder-email-input">
2282                        <div class="preorder-field-title">E-mail: <span class="preorder-mark">*</span></div>
2283                        <div class="preorder-field-value">
2284                            <input type="text" name="email" required value="${object_preorder.data.email}">
2285                        </div>
2286                    </div>
2287                </div>
2288                `;
2289    
2290            }else {
2291                var temp_email = `
2292                <div class="preorder-field preorder-email">
2293                    <div class="preorder-email-input">
2294                        <div class="preorder-field-title">E-mail: <span class="preorder-mark">*</span></div>
2295                        <div class="preorder-field-value">
2296                            <input type="text" name="email" required value="">
2297                        </div>
2298                    </div>
2299                </div>
2300                `;
2301            }
2302            
2303            let preorderPopupTitle = shop2.my.preorder_form_title || window._s3Lang.GR_ADMISSION_NOTICE;
2304            let preorderPopupText = shop2.my.preorder_form_title || window._s3Lang.GR_PREORDER_FORM_TEXT;
2305            let preorderFormSubmitt = shop2.my.preorder_form_submitt || window._s3Lang.SHOP2_SEND;
2306            
2307            let captchaSiteKey = $('#shop-captcha-sitekey').html() || '';
2308            var temp_html = `
2309                        <div class="preorder-form-wrap preorder-popup">
2310                            <form class="preorder-popup-body" action="/-/x-api/v1/public/?method=shop2/addKindEmailNotification" method="post">
2311                                <h2 class="preorder-popup-title">
2312                                    ${preorderPopupTitle}
2313                                </h2>
2314                                <div class="preorder-popup-text preorder-field type-html">
2315                                    ${preorderPopupText}
2316                                </div>
2317                                ${temp_email}
2318                                <input type="hidden" name="kind_id" value="${object_preorder.data.kind_id}">
2319                                
2320                                <div class="preorder-field preorder-field-button preorder_send">
2321                                    <button type="submit" class="shop2-btn">${preorderFormSubmitt}</button>
2322                                </div>
2323                                ${captchaSiteKey}
2324                            </form>
2325                            <div class="block-recaptcha"></div>
2326                        </div>
2327                        <div class="preorder-form-close"></div>
2328                            `;
2329            
2330            shop2.alert( temp_html, 'close', 'preorder-alert' ); 
2331        });
2332        
2333        $(document).on('click', '.preorder-form-close', function(e) {
2334        	$('#shop2-alert-ok').click();
2335        });
2336        
2337        $(document).on('submit', '.block-recaptcha form', function(e) {
2338            e.preventDefault();
2339            
2340            var serializeArray = $(this).serializeArray();
2341            
2342            for(let i = 0; i < serializeArray.length; i++){
2343                if( serializeArray[i]['name'] == '_sitekey' ){ object_preorder.data['_sitekey'] = serializeArray[i]['value'];}
2344                if( serializeArray[i]['name'] == 'g-recaptcha-response' ){ object_preorder.data['g-recaptcha-response'] = serializeArray[i]['value'];}
2345            };
2346    
2347            sentAjax_preorder( object_preorder.data, (data)=>{
2348                object_preorder.jQbtn.get(0).setAttribute('disabled', 'disabled');
2349    
2350                $('.preorder-form-wrap').html(`
2351                    <h3 class="preorder-popup-success">
2352                        ${shop2.my.preorder_form_success||'Спасибо!'}	
2353                    </h3>
2354                `);
2355
2356                if( object_preorder.jQbtn.closest('form').length ){
2357                	let $favorite_btn = object_preorder.jQbtn.closest('form').find('.favorite_btn');
2358                	
2359                	if( $favorite_btn.length && !$favorite_btn.is(":hidden") ){
2360                		$favorite_btn.trigger('click')
2361                	}
2362                }
2363            });
2364            
2365        });
2366        
2367        $(document).on('submit', '.preorder-popup-body', function(e) {
2368            e.preventDefault();
2369            var $form = $(this);
2370            
2371            object_preorder.data.email = this.email.value;
2372            const _regexEmeil = /^[\w-\.]+@[\w-]+\.[a-z]{2,4}$/i;
2373            
2374            let valid = _regexEmeil.test(object_preorder.data.email);
2375            object_preorder.data['smart-token'] = $('.preorder-popup-body textarea[name="smart-token"]').text();
2376            
2377            if (valid){
2378                $.get( '/-/x-api/v1/public/?method=shop2/addKindEmailNotification', function( data ) {
2379    
2380                    const _regexBody = new RegExp(/<body[^>]*>(.*?)<\/body>/ig);
2381                    
2382                    let body = data.result.html.match( _regexBody );
2383                    
2384                    $form.parent('.preorder-popup').find('.block-recaptcha').html( body );
2385                  });
2386            }else {
2387                
2388                if( !$form.find('.preorder-email').hasClass('field-error') )
2389                    $form
2390                        .find('.preorder-email')
2391                        .addClass('field-error')
2392                        .find('.preorder-email-input .preorder-field-value')
2393                        .before(`<div class="error-message">Неверный формат адреса электронной почты</div>`);
2394            }
2395    
2396        });
2397    },
2398
2399    discounts: function() {
2400
2401      $(document).on('click', '.shop2-product-actions dt', function(e) {
2402        var $this = $(this),
2403          win = $this.next(),
2404          left = $this.position().left;
2405
2406        e.stopPropagation();
2407
2408        if (win.is(':hidden')) {
2409          $('.shop2-product-actions dd').hide();
2410          win.show();
2411          win.css('left', left);
2412        } else {
2413            //win.hide();
2414        }   
2415
2416      });
2417
2418      $(document).on('click', '.close-desc-action', function(e) {
2419        var $this = $(this),
2420          win = $this.closest('dd');
2421
2422        e.stopPropagation();
2423
2424        win.hide();
2425      });
2426
2427      $(document).on('click', function() {
2428        $('.shop2-product-actions dd').hide();
2429      });
2430
2431    },
2432
2433    question: function() {
2434      var cls = '.price-old.question, .shop2-cart-total .question';
2435
2436      $(document).on('mouseenter', cls, function() {
2437        var $this = $(this),
2438          win = $this.next().show(),
2439          position = $this.position(),
2440          height = win.outerHeight(true);
2441
2442        win.css({
2443          top: position.top - height - 5,
2444          left: position.left
2445        });
2446
2447      }).on('mouseleave', cls, function() {
2448
2449        var $this = $(this),
2450          win = $this.next();
2451
2452        win.hide();
2453
2454      });
2455
2456    },
2457
2458    tabs: function() {
2459
2460      var tabs = $('.shop2-product-tabs li'),
2461        btns = tabs.find('a'),
2462        texts = $('.shop2-product-desc > div');
2463
2464      btns.on('click', function(e) {
2465        var $this = $(this),
2466          href = $this.attr('href');
2467
2468        e.preventDefault();
2469
2470        tabs.removeClass('active-tab');
2471        $this.parent().addClass('active-tab');
2472
2473        texts.removeClass('active-area');
2474        $(href).addClass('active-area');
2475      });
2476
2477
2478    },
2479
2480    filter: function() {
2481
2482      var wrap = $('.shop2-filter'),
2483        result = $('.result');
2484
2485      shop2.filter.init();
2486
2487      shop2.on('afterGetSearchMatches', function(d, status) {
2488
2489        if (d.data.total_found === 0) {
2490
2491          result.addClass('no-result');
2492        } else {
2493          result.removeClass('no-result');
2494        }
2495
2496        if (shop2.facets.enabled) {
2497          shop2.facets.set('filter');
2498        }
2499
2500        $('#filter-result').html(d.data.total_found);
2501
2502        result.removeClass('hide');
2503      });
2504
2505      wrap.find('.param-val').on('click', function(e) {
2506        var $this = $(this),
2507          name = $this.data('name'),
2508          value = $this.data('value');
2509
2510        e.preventDefault();
2511
2512        $this.toggleClass('active-val');
2513        shop2.filter.toggle(name, value);
2514        shop2.filter.count();
2515      });
2516
2517      wrap.find('select').on('change', function() {
2518        var $this = $(this),
2519          name = this.name,
2520          value = $this.val();
2521
2522        shop2.filter.add(name, value);
2523        shop2.filter.count();
2524      });
2525
2526      wrap.find('input:text').keyup(function() {
2527        var $this = $(this),
2528          name = $this.attr('name');
2529
2530        $.s3throttle('filter: ' + name, function() {
2531          var value = $this.val();
2532
2533          shop2.filter.add(name, value);
2534          shop2.filter.count();
2535        }, 500);
2536      });
2537
2538      wrap.find('.shop2-filter-go').on('click', function(e) {
2539        e.preventDefault();
2540        shop2.filter.go();
2541      });
2542
2543    },
2544
2545    sort: function() {
2546      var wrap = $('.sorting');
2547
2548      wrap.find('.sort-param').on('click', function(e) {
2549        var $this = $(this),
2550          name = $this.data('name');
2551
2552        e.preventDefault();
2553        shop2.filter.sort(name);
2554        shop2.filter.go();
2555      });
2556
2557      wrap.find('.sort-reset').on('click', function(e) {
2558        e.preventDefault();
2559        shop2.filter.remove('s[sort_by]');
2560        shop2.filter.go();
2561      });
2562
2563    },
2564
2565    views: function() {
2566      $('.view-shop a').on('click', function(e) {
2567        var $this = $(this),
2568          value = $this.data('value');
2569
2570        e.preventDefault();
2571        shop2.filter.remove('view');
2572        shop2.filter.add('view', value);
2573        shop2.filter.go();
2574
2575      });
2576    },
2577
2578    toggle: function() {
2579
2580      function tgl(el, wrap, cls, cookie) {
2581        $(document).on('click', wrap + ' ' + el, function(e) {
2582          var w = $(wrap);
2583          e.preventDefault();
2584          if (w.hasClass(cls)) {
2585            w.removeClass(cls);
2586            eraseCookie(cookie);
2587          } else {
2588            w.addClass(cls);
2589            createCookie(cookie, 1, 7);
2590          }
2591        });
2592      }
2593
2594      tgl('.block-title', '.cart-preview', 'opened', 'cart_opened');
2595      tgl('.block-title', '.search-form', 'opened', 'search_opened');
2596      tgl('.block-title', '.login-form ', 'opened', 'login_opened');
2597
2598    },
2599
2600    search: function() {
2601      var custom = $('#shop2_search_custom_fields'),
2602        global = $('#shop2_search_global_fields');
2603
2604      shop2.on('afterGetFolderCustomFields', function(d, status) {
2605        custom.html(d.data);
2606        global.find('input, select').prop('disabled', true);
2607        global.hide();
2608      });
2609
2610      $('#s\\[folder_id\\]').on('change', function() {
2611        var $this = $(this),
2612          folder_id = $this.val();
2613
2614        if (folder_id) {
2615
2616          shop2.search.getParams(folder_id);
2617
2618        } else {
2619
2620          custom.html('');
2621
2622          global.find('input, select').prop('disabled', false);
2623
2624          global.show();
2625        }
2626      }).trigger('change');
2627
2628      if (shop2.facets.enabled && !shop2.my.lazy_search_activation) {
2629        shop2.facets.searchSetup();
2630      }
2631    },
2632
2633    cart: function() {
2634
2635      var updateBtn = $('.shop2-cart-update'),
2636        cartTable = $('.shop2-cart-table'),
2637        form = $('#shop2-cart');
2638
2639      shop2.on('afterCartRemoveItem, afterCartUpdate', function() {
2640        document.location.reload();
2641      });
2642
2643      function updateBtnShow() {
2644        updateBtn.show();
2645      }
2646
2647      var eventName;
2648
2649      ['keypress', 'keyup', 'keydown'].forEach(function(item) {
2650        if ('on' + item in document) {
2651          eventName = item;
2652          return false;
2653        }
2654      });
2655
2656      cartTable.find('input:text').on(eventName, function(e) {
2657        if (e.keyCode == 13) {
2658          shop2.cart.update(form);
2659        } else {
2660          updateBtnShow();
2661        }
2662      });
2663
2664      $(document).on('click', 'li.param-value:not(.shop2-color-ext-selected)', function() {
2665        updateBtnShow();
2666      });
2667      
2668      $(document).on('change', 'select.param-value', function() {
2669        updateBtnShow();
2670      });
2671
2672      cartTable.find('.amount-minus, .amount-plus').on('click', updateBtnShow);
2673
2674      updateBtn.on('click', function(e) {
2675        e.preventDefault();
2676        shop2.cart.update(form);
2677        return false;
2678      });
2679
2680
2681      $('.cart-delete a').on('click', function(e) {
2682        var $this = $(this),
2683          id = $this.data('id');
2684
2685        e.preventDefault();
2686
2687        shop2.cart.remove(id);
2688
2689      });
2690
2691      $(document).on('click', '#shop2-deligate-calc', function(e) {
2692        var data = {},
2693          delivery = $('#shop2-order-delivery'),
2694          tabs = delivery.find('.shop2-delivery--item__tab');
2695
2696        $('#shop2-perfect-form').find('input, textearea, select').each(function() {
2697          var $this = $(this);
2698          if (this.tagName === 'INPUT' && this.type === 'checkbox') {
2699            if (this.checked) {
2700              data[this.name] = 'on';
2701            }
2702          } else {
2703            data[this.name] = $(this).val();
2704          }
2705        });
2706
2707        e.preventDefault();
2708        tabs.removeClass('active-tab');
2709        tabs.removeClass('point');
2710        delivery.addClass('preloader');
2711        $('#shop2-delivery-wait').show();
2712        $('input#address').blur();
2713        $('#shop2-deligate-calc').hide();
2714        //$('#form_g-anketa .text-right button').prop('disabled', true).addClass('g-button--disabled');
2715
2716        $.ajax({
2717          url: '/-/x-api/v1/public/?method=deligate/calc&param[get_vars][]',
2718          type: 'post',
2719          dataType: 'json',
2720          data: data,
2721          success: function(result) {
2722            delivery.removeClass('preloader');
2723            $('#shop2-delivery-wait').hide();
2724            $('#shop2-order-delivery').html(result.result.html);
2725            $('#shop2-order-delivery').append('<div class="preloader"><div class="spinner"></div></div>');
2726            $('#shop2-order-delivery').find('.delivery-items').each(function() {
2727              var $this = $(this);
2728              if ($.trim($this.text()) == "") {
2729                $this.parents('.shop2-delivery--item__tab:first').addClass('disabled');
2730              }
2731            });
2732            if (result.result.error) {
2733              shop2.alert(result.result.error);
2734              /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
2735              let on_shop2_btn = shop2.my.on_shop2_btn ? '.shop2-btn' : '.g-button';
2736              if( $('.order_design_five').length ){
2737                if( $('.order_design_five  ul li').length <= 1){
2738                  $('.order_design_five  ul li').before(`<li>${result.result.error}</li>`);
2739                }
2740                $(`.form-item ${on_shop2_btn}`).addClass('shop2-disabled');
2741                $(`.order_design_five`).removeClass('hide');
2742              }
2743              /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
2744            } else {
2745
2746              var dadataJson = $.parseJSON($('#dadata').val()),
2747                coordsCenter = [dadataJson.geo_lat, dadataJson.geo_lon];
2748
2749              /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
2750              let on_shop2_btn = shop2.my.on_shop2_btn ? '.shop2-btn' : '.g-button';
2751              if( $('.order_design_five ').length ){
2752                if( $('.order_design_five  ul li').length > 1){
2753                  $('.order_design_five  ul li').first().remove();
2754                }
2755                $(`.form-item ${on_shop2_btn}`).removeClass('shop2-disabled');
2756                $(`.order_design_five`).addClass('hide');
2757              }
2758              /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
2759              shop2.queue.edost2();
2760              $('#shop2-ems-calc, #shop2-edost-calc').on('click', function(e) {
2761                var $this = $(this);
2762                var attach_id = $this.data('attach-id');
2763                var to = $('select[name=' + attach_id + '\\[to\\]]');
2764                var zip = $('input[name=' + attach_id + '\\[zip\\]]');
2765                var order_value = $('input[name=' + attach_id + '\\[order_value\\]]');
2766
2767                if (to.length == 0) {
2768                  to = $('#shop2-edost2-to');
2769                }
2770
2771                e.preventDefault();
2772
2773                to = to.get(0) ? to.val() : '';
2774                zip = zip.get(0) ? zip.val() : '';
2775                order_value = order_value.prop("checked") ? 'on' : '';
2776
2777                shop2.delivery.calc(attach_id, 'to=' + to + '&zip=' + zip + '&order_value=' + order_value, function(d) {
2778                  if (!d.data && d.errstr) {
2779                    shop2.alert(d.errstr);
2780                    $('#delivery-' + attach_id + '-cost').html(0);
2781                  } else {
2782                    $('#delivery-' + attach_id + '-cost').html(d.data.cost);
2783
2784                    if (d.data.html) {
2785                      $('#delivery-' + attach_id + '-html').html(d.data.html);
2786                      shop2.queue.edost();
2787                    }
2788                  }
2789                });
2790
2791              });
2792              $('#shop2-deligate-calc').hide();
2793            }
2794          }
2795        });
2796      });
2797    },
2798
2799    coupon: function() {
2800
2801      shop2.on('afterCartAddCoupon, afterCartRemoveCoupon', function() {
2802        document.location.reload();
2803      });
2804
2805      $('.coupon-btn').on('click', function(e) {
2806        var coupon = $('#coupon'),
2807          code = coupon.val();
2808
2809        e.preventDefault();
2810
2811        if (code) {
2812
2813          shop2.cart.addCoupon(code);
2814
2815        }
2816
2817      });
2818
2819
2820      $('.coupon-delete').on('click', function(e) {
2821        var $this = $(this),
2822          code = $this.data('code');
2823
2824        e.preventDefault();
2825
2826        if (code) {
2827
2828          shop2.cart.removeCoupon(code);
2829
2830        }
2831
2832      });
2833
2834    },
2835
2836    delivery: function () {
2837    	
2838		// https://megagroup.fibery.io/GR/GR_Task/129
2839		function restoreTab() {
2840			var savedTab = localStorage.getItem('activeDeliveryTab');
2841	
2842			var tab = $('.shop2-delivery--item__tab[data-index="' + savedTab + '"]');
2843	
2844			if (tab.length && !tab.hasClass('disabled')) {
2845				$('.shop2-delivery--item__tab').removeClass('active-tab');
2846				tab.addClass('active-tab');
2847			}
2848		}
2849		function restoreAttachId() {
2850			var savedAttachId = localStorage.getItem('activeAttachId');
2851			
2852			var $activeTab = $('.shop2-delivery--item__tab.active-tab');
2853		
2854			setTimeout(function() {
2855				var optionLabel = $activeTab.find('.option-label[data-service-code="' + savedAttachId + '"]');
2856				optionLabel.find('input').prop('checked', true);
2857			}, 10);
2858		}
2859		function restoreSelectedOption() {
2860			var savedOption = localStorage.getItem('activeDeliveryOption');
2861			
2862			var $activeTab = $('.shop2-delivery--item__tab.active-tab');
2863	
2864			var tryRestore = function() {
2865				var option = $activeTab.find('.option-details[data-id="' + savedOption + '"]');
2866	
2867				if (option.length) {
2868					option.addClass('selected');
2869					option.closest('.option-type').addClass('active-type');
2870					option.find('input, textarea, select').prop('disabled', false);
2871					return true;
2872				}
2873				return false;
2874			};
2875	
2876			if (!tryRestore()) {
2877				var interval = setInterval(function() {
2878					if (tryRestore()) {
2879						clearInterval(interval);
2880					}
2881				}, 300);
2882	
2883				setTimeout(function() {
2884					clearInterval(interval);
2885				}, 5000);
2886			}
2887		}
2888	
2889		function initDeliveryObserver() {
2890			var observer = new MutationObserver(function(mutations) {
2891				mutations.forEach(function(mutation) {
2892					if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
2893						var el = $(mutation.target);
2894	
2895						if (el.hasClass('option-details') && el.hasClass('selected')) {
2896							
2897							var id = el.data('id');
2898							if (id) {
2899								localStorage.setItem('activeDeliveryOption', id);
2900							}
2901						}
2902					}
2903				});
2904			});
2905	
2906			observer.observe(document.body, {
2907				attributes: true,
2908				subtree: true,
2909				attributeFilter: ['class']
2910			});
2911		}
2912		// https://megagroup.fibery.io/GR/GR_Task/129
2913    	
2914    	
2915    	
2916        $('#shop2-order-delivery').find('.delivery-items').each(function () {
2917            var $this = $(this);
2918            if ($.trim($this.text()) == "") {
2919                $this.parents('.shop2-delivery--item__tab:first').addClass('disabled');
2920            }
2921        });
2922        $(document).on('change', '.map-select select', function () {
2923            var $this = $(this),
2924                index = $this.find('option:selected').index(),
2925                pos = $this.find('option:selected').text(),
2926                id = $this.val();
2927
2928            if (index == 0) {
2929                shop2.delivery.ymapsMap.balloon.close();
2930                return;
2931            }
2932
2933            var it = shop2.delivery.ymapsMap.geoObjects.getIterator(),
2934                ss;
2935            while (ss = it.getNext()) {
2936                for (var i = 0, len = ss.getLength(); i < len; i++) {
2937                    var placemark = ss.get(i);
2938                    if (placemark.properties.get('id') === id) {
2939                        placemark.options.set('iconImageHref', shop2.delivery.ymapsIconsData['selected']);
2940                        if (placemark.balloon.isOpen()) {
2941                            placemark.balloon.close();
2942                        } else {
2943                            placemark.balloon.open();
2944                        }
2945                        //return;
2946                    } else {
2947                        placemark.options.set('iconImageHref', shop2.delivery.ymapsIconsData['default']);
2948                    }
2949                }
2950                return;
2951            }
2952
2953        });
2954
2955        $(".shop2-payment-options .option-type").each(function () {
2956
2957            if ($(this).hasClass("option-payment-systems") && $(this).hasClass("active-type")) {
2958                var payment_btn = $('.shop2-payment-options .shop2-payment-btn');
2959                var continue_text = $('.shop2-payment-options .shop2-payment-btn').attr('data-continue-text');
2960                var pay_text = $('.shop2-payment-options .shop2-payment-btn').attr('data-pay-text');
2961
2962                payment_btn.text(pay_text);
2963            }
2964        });
2965
2966        $(document).on('click', '.shop2-cart-order-payments .options-list .option-type:not(.active-type) .option-label.payments-label', function (e) {
2967            e.stopPropagation();
2968            var $this = $(this),
2969                groups = $(document).find('.shop2-cart-order-payments .option-type');
2970
2971            groups.removeClass('active-type');
2972            $this.parent().addClass('active-type');
2973        }); // Обработка клика на полученные способы оплаты после выбора доставки
2974
2975        $(document).on('click', '.option-label:not(.payments-label)', function (e) {
2976            var $this = $(this),
2977            	$parent = $(this).parents('.options-list'),
2978                options = $parent.find('.option-label'),
2979                groups = $parent.find('.option-type'),
2980                details = options.next(),
2981                index = $this.parent().index();
2982
2983            if (e.target.nodeName != 'INPUT' && shop2.delivery.deligate  && shop2.mode != 'orders') {
2984                e.preventDefault();
2985            }
2986
2987            if (shop2.delivery.ymapsMap) {
2988                shop2.delivery.ymapsMap.destroy();
2989                shop2.delivery.ymapsMap = null;
2990            }
2991            /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
2992            if (true) {
2993            	
2994                let on_shop2_btn = shop2.my.on_shop2_btn ? '.shop2-btn' : '.g-button';
2995                let $selected = $this.parents('.option-type').find('.option-detail
2995s.map.selected');
2996                
2997                if ($this.hasClass('ymap') && !$selected.length) {
2998                    if ($(`.form-item ${on_shop2_btn}`).length) {
2999                        $(`.form-item ${on_shop2_btn}`).addClass('shop2-disabled');
3000                        $(`.order_design_five`).removeClass('hide');
3001                    }
3002                } else {
3003                    if ($(`.form-item ${on_shop2_btn}.shop2-disabled`).length) {
3004                        $(`.form-item ${on_shop2_btn}.shop2-disabled`).removeClass('shop2-disabled');
3005                        $(`.order_design_five`).addClass('hide');
3006                    }
3007                }
3008            }
3009            /* Deligate. Корзина. Доработка валидации поля для ввода города  /GR_Task/10 */
3010            groups.removeClass('active-type');
3011            $this.parent().addClass('active-type');
3012            details.find('input, textarea, select').prop('disabled', true);
3013            $this.next().find('input, textarea, select').prop('disabled', false);
3014            if (shop2.delivery.deligate) {
3015                $this.find('input:first').prop('checked', true);
3016            }
3017
3018            if ($this.hasClass('ymap')) {
3019                shop2.delivery.YmapsInit($this.data('service-code'));
3020            }
3021
3022            if ($(".shop2-payment-options .shop2-btn").hasClass("shop2-payment-btn")) {
3023
3024                var payment_btn = $('.shop2-payment-options .shop2-payment-btn');
3025                var continue_text = $('.shop2-payment-options .shop2-payment-btn').attr('data-continue-text');
3026                var pay_text = $('.shop2-payment-options .shop2-payment-btn').attr('data-pay-text');
3027
3028
3029                if ($this.parent().hasClass('option-payment-systems')) {
3030                    payment_btn.text(pay_text);
3031                } else {
3032                    payment_btn.text(continue_text);
3033                }
3034            }
3035
3036        });
3037        $(document).on('click', '.shop2-delivery--item__tab .tab-label', function () {
3038            var groups = $(document).find('.shop2-delivery--item__tab'),
3039                $this = $(this),
3040                parent = $this.parents('.shop2-delivery--item__tab:first'),
3041                index = parent.index();
3042			var dataIndex = parent.data('index'); // https://megagroup.fibery.io/GR/GR_Task/129
3043
3044            if (parent.hasClass('disabled')) return false;
3045            if (parent.hasClass('active-tab')) {
3046                parent.removeClass('active-tab');
3047                return;
3048            }
3049
3050            groups.removeClass('active-tab').eq(index).addClass('active-tab');
3051			localStorage.setItem('activeDeliveryTab', dataIndex); // https://megagroup.fibery.io/GR/GR_Task/129
3052
3053            var activeTabOffsetTop = $('.active-tab .tab-label').offset().top - 10;
3054            $('html, body').animate({
3055                scrollTop: activeTabOffsetTop
3056            }, 800);
3057        });
3058
3059        $(document).on("click", ".option-label:not(.payments-label)", function (e) {
3060		    // 1. Предотвращаем двойной вызов: если кликнули по самому input внутри label, 
3061		    // позволяем событию всплыть, но игнорируем выполнение здесь, 
3062		    // так как оно выполнится при клике на сам label.
3063		    if (e.target.tagName === 'INPUT') return;
3064        	
3065            var $this = $(this),
3066		        $input = $this.find('input[type="radio"]');
3067		
3068		    // Принудительно отмечаем radio внутри кликнутого label (для iOS)
3069		    $input.prop('checked', true);
3070		
3071		    var attach_id = $this.data("attach_id"),
3072		        siblings = $this.parent().siblings(".option-type"),
3073		        tabsSib = $this.parents('.shop2-delivery--item__tab:first').siblings();
3074                
3075            $("#delivery_id_deligate").val(attach_id);
3076            $("#deligate_points_fields .fields").empty();
3077            $("#deligate_points_fields").hide();
3078            
3079            tabsSib.find('.option-type input').prop('checked', false);
3080            tabsSib.removeClass('point');
3081            
3082            siblings.find('input').prop('checked', false);
3083			
3084			// https://megagroup.fibery.io/GR/GR_Task/129
3085			var service_code = $this.data("service-code");
3086			if (service_code) {
3087				localStorage.setItem('activeAttachId', service_code);
3088				
3089				if (service_code=="selfdelivery") {
3090					localStorage.setItem('activeDeliveryOption', 'selfdelivery');
3091				}
3092			}
3093			// https://megagroup.fibery.io/GR/GR_Task/129
3094        });
3095
3096        $('#shop2-ems-calc, #shop2-edost-calc').on('click', function (e) {
3097            var $this = $(this);
3098            var attach_id = $this.data('attach-id');
3099            var to = $('select[name=' + attach_id + '\\[to\\]]');
3100            var zip = $('input[name=' + attach_id + '\\[zip\\]]');
3101            var order_value = $('input[name=' + attach_id + '\\[order_value\\]]');
3102
3103            if (to.length == 0) {
3104                to = $('#shop2-edost2-to');
3105            }
3106
3107            e.preventDefault();
3108
3109            to = to.get(0) ? to.val() : '';
3110            zip = zip.get(0) ? zip.val() : '';
3111            order_value = order_value.prop("checked") ? 'on' : '';
3112
3113            shop2.delivery.calc(attach_id, 'to=' + to + '&zip=' + zip + '&order_value=' + order_value, function (d) {
3114                if (!d.data && d.errstr) {
3115                    shop2.alert(d.errstr);
3116                    $('#delivery-' + attach_id + '-cost').html(0);
3117                } else {
3118                    $('#delivery-' + attach_id + '-cost').html(d.data.cost);
3119
3120                    if (d.data.html) {
3121                        $('#delivery-' + attach_id + '-html').html(d.data.html);
3122                        shop2.queue.edost();
3123                    }
3124                }
3125            });
3126
3127        });
3128        
3129        // https://megagroup.fibery.io/GR/GR_Task/129
3130		restoreTab();
3131		restoreAttachId();
3132		restoreSelectedOption();
3133		initDeliveryObserver();
3134		
3135		function clearDeliveryState() {
3136			localStorage.removeItem('activeDeliveryTab');
3137		}
3138		// https://megagroup.fibery.io/GR/GR_Task/129
3139    },
3140
3141    edost: function() {
3142      // см delivery
3143
3144      function find(name) {
3145        var selector = '[name=' + name.replace(/([\[\]])/g, '\\$1') + ']';
3146        return $(selector);
3147      }
3148
3149      var btn = $('#shop2-edost-calc'),
3150        attach_id = btn.data('attach-id'),
3151        address = find(attach_id + '[address]');
3152
3153      function setAddress(office) {
3154        var text = $.trim(office.text()).replace(/\s*\n\s*/g, '\n').split('\n').splice(1).join('\n');
3155        address.val(text).prop('readonly', true);
3156      }
3157
3158      find(attach_id + '[edost][office]').on('click', function() {
3159        var $this = $(this),
3160          wrap = $this.closest('.shop2-edost-office');
3161
3162        setAddress(wrap);
3163        $this.prop('checked', true);
3164      });
3165
3166      find(attach_id + '[edost][tarif]').on('click', function() {
3167        var $this = $(this),
3168          wrap = $this.closest('.shop2-edost-variant'),
3169          siblings = wrap.siblings(),
3170          office = wrap.find('.shop2-edost-office'),
3171          checked;
3172
3173        siblings.find('.shop2-edost-office input, .shop2-edost-pickpointmap input').prop({
3174          disabled: true,
3175          checked: false
3176        });
3177
3178        var radio = wrap.find('.shop2-edost-office input, .shop2-edost-pickpointmap input').prop({
3179          disabled: false
3180        }).filter(':radio');
3181
3182        checked = radio.filter(':checked');
3183
3184        if (radio.get(0)) {
3185
3186          if (checked.get(0)) {
3187            checked.trigger('click');
3188          } else {
3189            radio.eq(0).trigger('click');
3190          }
3191
3192        } else {
3193
3194          if (office.length == 1) {
3195            setAddress(office);
3196          } else if (address.prop('readonly')) {
3197            address.prop('readonly', false).val('');
3198          }
3199
3200        }
3201        shop2.trigger('afterEdostSet');
3202
3203      }).filter(':checked').trigger('click');
3204
3205
3206      $('.shop2-edost-pickpointmap a').on('click', function() {
3207        var $this = $(this),
3208          span = $this.children(),
3209          city = $this.data('city');
3210
3211        $this.closest('.shop2-edost-variant').find('> label input').trigger('click');
3212
3213        function cb(data) {
3214          var res = {};
3215          $.each(['name', 'address', 'id'], function(i, k) {
3216            res[k] = data[k];
3217          });
3218          $this.next().val(JSON.stringify(res));
3219          span.html(': ' + res.name);
3220          address.val(res.name + ',\n' + res.address).prop('readonly', true);
3221        }
3222
3223        PickPoint.open(cb, {
3224          city: city,
3225          ids: null
3226        });
3227
3228        return false;
3229      });
3230
3231      // if (address.prop('readonly')) {
3232      //  address.prop('readonly', false).val('');
3233      // }
3234
3235    },
3236
3237    edost2: function() {
3238
3239      if (!window.shop2EdostRegions) {
3240        return;
3241      }
3242
3243      var $country = $('#shop2-edost2-country');
3244      var countryDef = $country.html();
3245      var $region = $('#shop2-edost2-region');
3246      var regionDef = $region.html();
3247      var $city = $('#shop2-edost2-city');
3248      var cityDef = $city.html();
3249      var $to = $('#shop2-edost2-to');
3250      var list;
3251
3252
3253      if ($country.length) {
3254        list = $.grep(shop2EdostRegions, function(item) {
3255          return item.is_country;
3256        });
3257        $country.html(countryDef + makeHTML(list));
3258        hide($region);
3259        hide($city);
3260
3261        $country.on('change', function() {
3262          var country = $(this).val();
3263          if ($region.length) {
3264            list = $.grep(shop2EdostRegions, function(item) {
3265              return item.is_region && item.country == country;
3266            });
3267            $region.html(regionDef + makeHTML(list));
3268            if (list.length == 0) {
3269              hide($region);
3270              hide($city);
3271              $to.val(country);
3272            } else {
3273              show($region);
3274              $to.val('');
3275            }
3276          } else if ($city.length) {
3277            list = $.grep(shop2EdostRegions, function(item) {
3278              return item.is_city && item.country == country;
3279            });
3280            $city.html(cityDef + makeHTML(list));
3281            if (list.length == 0) {
3282              hide($city);
3283              $to.val(country);
3284            } else {
3285              show($city);
3286              $to.val('');
3287            }
3288          } else {
3289            $to.val(country);
3290          }
3291        });
3292      }
3293
3294      if ($region.length) {
3295        if (!$country.length) {
3296          list = $.grep(shop2EdostRegions, function(item) {
3297            return item.is_region;
3298          });
3299          $region.html(regionDef + makeHTML(list));
3300          hide($city);
3301        }
3302
3303        $region.on('change', function() {
3304          var region = $(this).val();
3305          list = $.grep(shop2EdostRegions, function(item) {
3306            return item.is_city && item.region == region;
3307          });
3308          $city.html(cityDef + makeHTML(list));
3309          if (list.length == 0) {
3310            hide($city);
3311            $to.val(region);
3312          } else {
3313            show($city);
3314            $to.val(region);
3315          }
3316        });
3317      }
3318
3319      if (!$country.length && !$region.length) {
3320        list = $.grep(shop2EdostRegions, function(item) {
3321          return item.is_city;
3322        });
3323        $city.html(regionDef + makeHTML(list));
3324      }
3325
3326      $city.on('change', function() {
3327        var val = $(this).val();
3328        if (val === 'default') {
3329          if ($region.length) {
3330            $to.val($region.val());
3331          }
3332        } else if (val) {
3333          $to.val(val);
3334        }
3335      });
3336
3337      var countryValue = $country.data('value');
3338      var regionValue = $region.data('value');
3339      var cityValue = $city.data('value');
3340
3341      if (countryValue) {
3342        $country.val(countryValue);
3343      }
3344
3345      $country.trigger('change');
3346
3347      if (regionValue) {
3348        $region.val(regionValue);
3349      }
3350
3351      $region.trigger('change');
3352
3353      if (cityValue) {
3354        $city.val(cityValue);
3355      }
3356
3357      $city.trigger('change');
3358
3359      function makeHTML(arr) {
3360        var html = $.map(arr, function(item) {
3361          return '<option value="' + item.id + '">' + item.name + '</option>';
3362        });
3363        return html.join('');
3364      }
3365
3366      function hide($el) {
3367        $el.html('').closest('.option-item').addClass('hide');
3368      }
3369
3370      function show($el) {
3371        $el.closest('.option-item').removeClass('hide');
3372      }
3373
3374    },
3375
3376    print: function() {
3377
3378      $('#order-print').on('click', function() {
3379
3380        s3.printMe('shop2-order', {
3381          stylesheet: shop2.options.printCSS
3382        });
3383
3384        return false;
3385      });
3386
3387    },
3388
3389    hs: function() {
3390
3391      $('.shop2-compare-product-image a img, .shop2-compare-data a img, .shop2-product .product-image a img, .shop2-product .product-thumbnails li a img, .cart-product-image a img, .cart-product-param a img').closest('a').on('click', function() {
3392        hs.expand(this);
3393        return false;
3394      }).addClass('highslide');
3395
3396      $(document).on('click', '.shop2-edost-office-address a', function() {
3397        hs.htmlExpand(this, {
3398          objectType: 'iframe',
3399          wrapperClassName: 'draggable-header',
3400          outlineType: 'rounded-white',
3401          width: 900,
3402          height: 600,
3403          align: 'center'
3404        });
3405        return false;
3406      });
3407
3408
3409    },
3410
3411    vendors: function() {
3412
3413      $('.shop2-vendor').eachRow(function(group) {
3414        var heights = group.getHeights();
3415
3416        group.each(function(i) {
3417          var $this = $(this),
3418            delta = heights.max - heights.values[i],
3419            name = $this.find('.vendor-name'),
3420            height = name.height();
3421
3422          name.css('min-height', height + delta);
3423
3424        });
3425      });
3426
3427    },
3428
3429    toggleFields: function() {
3430
3431      var fields = $('.shop2-filter-fields'),
3432        cookieName = 'filter_opened',
3433        opened = readCookie(cookieName),
3434        btn = $('.shop2-toggle-fields');
3435
3436      btn.on('click', function() {
3437        var $this = $(this),
3438          alt = $this.data('alt'),
3439          text = $this.html();
3440
3441        if (fields.hasClass('hide')) {
3442          createCookie(cookieName, 1, 7);
3443        } else {
3444          eraseCookie(cookieName);
3445        }
3446
3447        fields.toggleClass('hide');
3448        $this.html(alt);
3449        $this.data('alt', text);
3450
3451        return false;
3452      });
3453
3454      if (!opened) {
3455        btn.trigger('click');
3456      }
3457
3458    },
3459
3460    lazyLoad: function () {
3461	    var $document = $(document),
3462	      $window = $(window),
3463	      blocked = false,
3464	      products = $('.product-list'),
3465	      pagesCount = 1000000,
3466	      page_num = 1;
3467	
3468	    if (shop2.my.lazy_load_subpages && products.get(0)) {
3469	      $document.scroll(function () {
3470	        var pagelist = $('.shop2-pagelist:last');
3471	        var productList = $('.product-list:last');
3472	        var offsetTop = productList.offset().top + productList.height();
3473	        
3474	         if (typeof shop2.page == 'undefined') {
3475				  shop2.page = 1;
3476				}
3477	
3478	        if ($document.scrollTop() + $window.height() >= offsetTop && !blocked && shop2.page < pagesCount) {
3479	          blocked = true;
3480	         
3481	          var lazyLoadUrl = '/-/x-api/v1/public/?method=shop2/lazyLoad',
3482	            params = {
3483	              param: {
3484	                page_num: shop2.page,
3485	                url: window.location.pathname,
3486	              }
3487	            };
3488	
3489	          if (window.location.search) {
3490	            lazyLoadUrl += "&" + window.location.search.substring(1);
3491	          }
3492			  if (pagelist.length && $('.custom-shop2-pagelist').length<1) {
3493		          $.ajax({
3494		            url: lazyLoadUrl,
3495		            type: 'GET',
3496		            dataType: 'json',
3497		            data: params,
3498		            success: function (response) {
3499		              productList.after('<hr />' + response.result.data.html);
3500		              shop2.page = parseInt(shop2.page) + 1;
3501		              shop2.productRefs = Object.assign(shop2.productRefs, response.result.data.product_refs);
3502		              pagesCount = response.result.data.pages;
3503		              pagelist.hide();
3504		              shop2.queue.heights();
3505		              blocked = false;
3506		              
3507		              shop2.trigger('afterProductsLazyLoaded');
3508		            }
3509		          });
3510	          };
3511	        }
3512	      });
3513	    }
3514	  },
3515
3516    compare: function() {
3517
3518      var $document = $(document);
3519
3520      function update(el, res) {
3521
3522        // el.closest('.product-compare').replaceWith(res.data);
3523        $('input[type=checkbox][value=' + el.val() + ']').closest('.product-compare').replaceWith(res.data);
3524
3525        $('.product-compare-added a span').html('(' + res.count + ')');
3526
3527        if (res.panel) {
3528          $('#shop2-panel').replaceWith(res.panel);
3529        }
3530
3531      }
3532
3533      $document.on('click', '.product-compare input:checkbox', function() {
3534        var $this = $(this),
3535          action = $this.attr('checked') ? 'del' : 'add';
3536
3537        shop2.compare.action(action, $this.val(), function(res, status) {
3538          if (status == 'success') {
3539
3540            if (res.errstr) {
3541              shop2.alert(res.errstr);
3542              $this.prop('checked', false);
3543            } else {
3544              update($this, res);
3545            }
3546          }
3547        });
3548      });
3549
3550    },
3551
3552    compareTable: function() {
3553
3554      $('.shop2-compare-table').each(function() {
3555        var $this = $(this),
3556          relay = $this.find('.shop2-compare-switch a'),
3557          options = $this.find('.shop2-compare-data');
3558
3559        $this.find('.shop2-compare-delete').on('click', function() {
3560          var $this = $(this),
3561            kind_id = $this.data().id;
3562
3563          shop2.compare.remove(kind_id, function() {
3564            document.location.reload();
3565          });
3566
3567          return false;
3568        });
3569
3570        function compareTd(tr) {
3571          var td = tr.find('td'),
3572            val = td.eq(1).html(),
3573            differ = false,
3574            i = 2,
3575            len = td.length;
3576
3577          if (len <= 2) {
3578            return false;
3579          }
3580
3581          for (; i < len; i += 1) {
3582            if (val != td.eq(i).html()) {
3583              differ = true;
3584              break;
3585            }
3586            val = td.eq(i).html();
3587          }
3588
3589          return differ;
3590        }
3591
3592        relay.on('click', function() {
3593
3594          var $this = $(this);
3595
3596          relay.removeClass('shop2-compare-switch-active');
3597          $this.addClass('shop2-compare-switch-active');
3598
3599          if ($this.index() === 0) {
3600            options.show();
3601          } else {
3602            options.each(function() {
3603              var $this = $(this),
3604                differ = compareTd($this);
3605
3606              if (differ) {
3607                $this.show();
3608              } else {
3609                $this.hide();
3610              }
3611            });
3612          }
3613
3614          return false;
3615
3616        }).eq(1).trigger('click');
3617
3618
3619      });
3620    },
3621    
3622    favorite: function() {
3623
3624		function popupDeleteFavorite($kind_id) {
3625		    var popupWr = '<div class="shop2-popup_favorite"><div class="popup_inner"><div class="text">Удалить товар из избранного?</div><div class="btns"><div class="shop2-btn delete_fovorite" data-kind_id="' + $kind_id + '">Удалить</div><div class="shop2-btn-close close_favorite">Закрыть</div></div></div></div>';
3626		    $(popupWr).appendTo('body');
3627		}
3628		
3629		function popupClearFavorite() {
3630		    var popupWr = '<div class="shop2-popup_favorite"><div class="popup_inner"><div class="text">Удалить все товары из избранного?</div><div class="btns"><div class="shop2-btn clear_fovorite">Удалить</div><div class="shop2-btn-close close_favorite">Закрыть</div></div></div></div>';
3631		    $(popupWr).appendTo('body');
3632		}
3633		$(document).on('click', '.favorite_btn', function() {
3634		    var $this = $(this),
3635		        kind_id = $this.parents('form').find('input[name="kind_id"]').val(),
3636		        active = $this.parents('.favorite_btn_wrapper').find('.favorite_btn_active');
3637		    $.ajax({
3638		        url: '/-/x-api/v1/public/?method=shop2/addFavoriteProduct&param[kind_id]=' + kind_id,
3639		        type: 'post',
3640		        dataType: 'json',
3641		        data: kind_id,
3642		        success: function(data) {
3643		            var res = data.result.count;
3644		            var $text = /*window._s3Lang.JS_ADD_FOVARITE;*/ "Добавлено в <a href='%s'>избранное</a>";
3645		            $('.favorite_btn_active a > span').text(res);
3646		            $('.shop2_favorite_cart_link span').text(res);
3647		            $('.favorite_panel').removeClass('not-null');
3648		            shop2.msg($text.replace('%s', shop2.uri + '/favorites'), $this);
3649		            $this.hide();
3650		            active.show();
3651		        }
3652		    });
3653		});
3654		$(document).on('click', '.favorite_btn_active .icon', function() {
3655		    var kind_id = $(this).parents('form').find('input[name="kind_id"]').val();
3656		    popupDeleteFavorite(kind_id);
3657		});
3658		$(document).on('click', '.delete_fovorite', function() {
3659		    var kind_id = $(this).data('kind_id'),
3660		        product = $('body').find('form input[value="' + kind_id + '"]').closest('form'),
3661		        active = product.find('.favorite_btn'),
3662		        noActive = product.find('.favorite_btn_active');
3663		    $.ajax({
3664		        url: '/-/x-api/v1/public/?method=shop2/removeFavoriteProduct&param[kind_id]=' + kind_id,
3665		        type: 'post',
3666		        dataType: 'json',
3667		        data: kind_id,
3668		        success: function(data) {
3669		            var res = data.result.count;
3670		            $('.favorite_btn_active a > span').text(res);
3671		            $('.shop2_favorite_cart_link span').text(res);
3672		            if (res == 0) {
3673		                $('.favorite_panel').addClass('not-null');
3674		            }
3675		            noActive.hide();
3676		            active.show();
3677		        }
3678		    });
3679		    $('.shop2-popup_favorite').remove();
3680		});
3681		$(document).on('click', '.close_favorite', function() {
3682		    $('.shop2-popup_favorite').remove();
3683		});
3684		$(document).on('click', '.shop2-btn_popup_favorite', function(e) {
3685		    popupClearFavorite();
3686		    e.preventDefault();
3687		});
3688		$(document).on('click', '.clear_fovorite', function(e) {
3689		    $.ajax({
3690		        url: '/-/x-api/v1/public/?method=shop2/clearFavoriteProducts',
3691		        type: 'post',
3692		        dataType: 'json',
3693		        success: function(data) {}
3694		    });
3695		    location.reload()
3696		});
3697
3698    },
3699    paySelected: function() {
3700		if( shop2.mode == 'orders' && $('[data-continue-text]').length){
3701			$('.options-list input').on('change', function(e){
3702				var $this = $(this);
3703				var btn_order = $('[data-continue-text]');
3704				var continue_order = btn_order.data('continue-text');
3705				var pay_order = btn_order.data('pay-text');
3706				
3707				if( !$this.hasClass('shop2-payments-radio') ){
3708					btn_order.text(pay_order);
3709				}else{
3710					btn_order.text(continue_order);
3711				}
3712			})
3713		}
3714    },
3715buyOneClick: function() {
3716	if(!$('.buy-one-click-js').length){
3717		return;
3718	}
3719	var current_obj = {};
3720	current_obj.status_modal = false;
3721
3722	if( $('[data-remodal-id="buy-in-one-click"]').length ){
3723		var modal = $('[data-remodal-id="buy-in-one-click"]').remodal();
3724		modal.str_block = '[data-remodal-id="buy-in-one-click"]';
3725		modal.str_btn = '.buy-one-click-js';
3726		modal.settings.hashTracking = false;
3727
3728		modal.open_modal = function(data){
3729			$( this.str_block ).find('.shop2-buy-one-click-block').html(data);
3730			this.open();
3731		};
3732
3733		modal.up_scroll = function(){
3734			this.$wrapper.scrollTop(0);
3735		}
3736		
3737	} else {
3738		var modal = {
3739			str_block: '.buy-one-click-container',
3740			str_btn: '.buy-one-click-js',
3741			open_modal: function(data){
3742				current_obj.opening( `
3743				<div class="${this.str_block.replace('.','')}">
3744					<div class="preorder-form-close"></div>
3745					<div class="shop2-buy-one-click-block">${data}</div>
3746				</div>
3747				`);
3748			},
3749			up_scroll: function(){
3750				$(this.str_block).parent().parent().scrollTop(0)
3751			}
3752		};
3753		$(document).on('keyup.esc_keyup', function(keyUp){
3754			if (keyUp.keyCode == 27 && current_obj.status_modal) {
3755				modal_close.apply(current_obj);
3756				return false;
3757			}else {
3758				return false;
3759			}
3760		});
3761		$(document).on('click', function(e){
3762				e.stopPropagation();
3763				let target =  $(e.target);
3764				if( target.is('.buy-one-click-container .preorder-form-close') || target.is('.shop2-buy-one-click-popup') ){
3765					modal_close.apply(current_obj);
3766				}
3767			}
3768		);
3769		function modal_close(){
3770			$('html').removeClass('oveflowHidden');
3771			this.current_modal.removeClass('opened');
3772			this.status_modal = false;
3773		};
3774		function modal_open(){
3775			$('html').addClass('oveflowHidden');
3776			this.current_modal.addClass('opened');
3777			this.status_modal = true;
3778		};
3779		(function modal_create(){
3780			window.$popup = $(
3781				`<div class="shop2-buy-one-click-popup">
3782					<div class="shop2-buy-one-click-popup__inner">
3783					</div>
3784				</div>`
3785			);
3786	
3787			$('body').append( $popup );
3788	
3789			current_obj.current_modal = $popup;
3790			current_obj.opening = function(data){
3791				this.current_modal.find('.shop2-buy-one-click-popup__inner').html(data);
3792				
3793				modal_open.apply(this);
3794			}
3795		})();
3796	};
3797
3798
3799	function modal_amountInit(){
3800		if( typeof shop2_gr == 'undefined') {
3801			return;
3802		} else {
3803			if( typeof shop2_gr.methods.amountInit == 'undefined') {
3804				return;
3805			}else{
3806				shop2_gr.methods.amountInit();
3807			}
3808		}
3809	};
3810	function modal_grFormDatePicker(){
3811		if( typeof grFormDatePicker != 'undefined' ){
3812			grFormDatePicker.init();
3813		}else {
3814			$( ".datepickerInit" ).each(function(index, el) {
3815				$(this).datepicker({
3816					minDate:0,
3817					changeMonth: false,
3818					numberOfMonths: 1
3819				});
3820			});
3821		}
3822	};
3823
3824	function sumTotal(_this){
3825		var
3826		inProduct     = _this.closest('.shop2-buy-one-click__product-right'),
3827		currentPrice  = +String(inProduct.find('.shop2-buy-one-click__total').data('price')).replace(/\u00A0/g, ''),
3828		amountMin 	  =	+inProduct.find('.shop2-product-amount input').data('min'),
3829		amountVal     = +inProduct.find('.shop2-product-amount input').val(),
3830		grandTotal    = currentPrice * amountVal;
3831		
3832		
3833		inProduct.find('.shop2-buy-one-click__total .price-current strong').text(formatNumberWithSpaces(Math.floor(grandTotal)));
3834	};
3835	function validateEmail(email) {
3836		var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
3837		return re.test(String(email).toLowerCase());
3838	}
3839	
3840	function formatNumberWithSpaces(number) {
3841  		return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
3842	}
3843
3844	$(document).on('click', modal.str_block + ' .order_one_click_amount_js', function(e){
3845		var $elem = $(e.target);
3846		
3847		if( $elem.hasClass('amount-plus') || $elem.hasClass('amount-minus') ){
3848			sumTotal($elem);
3849		}
3850	});
3851
3852	$(document).on('change', '.order_one_click_amount_js input', function() {
3853		var $this = $(this);
3854		setTimeout(function(){
3855			sumTotal($this);
3856		}, 100);
3857	});
3858
3859	$(document).on('click', modal.str_btn, function(e){
3860		e.preventDefault();
3861		current_obj._this = this;
3862		current_obj.kind_id = +$( current_obj._this ).data('product-kind_id');
3863		current_obj.form = $( current_obj._this ).closest('form');
3864
3865		getForm({
3866			requestType:"get",
3867			callback: function(response){
3868				let data = $.trim(response.result.html).replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
3869
3870				modal.open_modal(data);
3871				modal_grFormDatePicker();
3872				
3873				$('.order_one_click_amount_js input')
3874					.val( current_obj.form[0].amount.value )
3875					.trigger('change');
3876				modal_amountInit();
3877			}
3878		});
3879	});
3880
3881	$(document).on('submit', modal.str_block + ' form', function(e){
3882		e.preventDefault();
3883		var serialize_data = $(this).serializeArray();
3884		var $input_email = $(modal.str_block + ' .order_field_email');
3885		var emailFlag = true;
3886		
3887		$input_email.each(function(){
3888			if (!validateEmail($(this).val())) {
3889				$(this).closest('.tpl-field').addClass('field-error').find('.error-message').removeClass('hide');
3890				return emailFlag = false
3891			}
3892		});
3893		
3894		if (emailFlag) {
3895			getForm({
3896				requestType:"post",
3897				serializeData: serialize_data
3898			});
3899		};
3900	});
3901
3902	function getForm(obj) {
3903		let req = obj.requestType || 'post';
3904
3905		if (req == 'get') {
3906			let url = '/-/x-api/v1/public/?method=shop2/buyOneClick&param[kind_id]=' + current_obj.kind_id;
3907			let gr_images_size = $(modal.str_btn).data('images-size');
3908			let gr_images_view = $(modal.str_btn).data("images-view");
3909	
3910			if (gr_images_view){
3911				url += "&gr_images_view=" + gr_images_view;
3912			};
3913			
3914			if (gr_images_size){
3915				url += "&gr_images_size=" + gr_images_size;
3916			};
3917
3918			$.ajax({
3919				url: url,
3920				type: req,
3921				cache: false,
3922				dataType: 'json'
3923			}).done(function(response) {
3924				if (obj.callback) {
3925					obj.callback(response);
3926				};
3927			});
3928		} else {
3929			let url = '/-/x-api/v1/public/?method=shop2/buyOneClick';
3930			let ser = obj.serializeData;
3931			let gr_images_size = $(modal.str_btn).data('images-size');
3932			let gr_images_view = $(modal.str_btn).data("images-view");
3933	
3934			if (gr_images_view){
3935				url += "&gr_images_view=" + gr_images_view;
3936			};
3937			
3938			if (gr_images_size){
3939				url += "&gr_images_size=" + gr_images_size;
3940			};
3941
3942			$.ajax({
3943				url: url,
3944				data: ser,
3945				type: req,
3946				cache: false,
3947				dataType: 'json'
3948			}).done(function(response) {
3949				if(response.result.error) {
3950					$(modal.str_block + ' .shop2-warning').remove();
3951					$(modal.str_block + ' .shop2-buy-one-click__result').prepend('<div class="shop2-warning">'+response.result.error+'</div>');
3952					modal.up_scroll();
3953					return false;
3954				};
3955				if (response.result.redirect_payment_url) {
3956					window.location.replace(response.result.redirect_payment_url);
3957					return false;
3958				}
3959				let data = $.trim(response.result.html).replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
3960				$(modal.str_block).find('.shop2-buy-one-click-block').html(data);
3961				modal_grFormDatePicker();
3962				
3963				$('.order_one_click_amount_js input').trigger('change');
3964				modal_amountInit();
3965
3966				if (obj.callback) {
3967					obj.callback(response);
3968				};
3969			});
3970		};
3971	};
3972},
3973
3974    alert: function() {
3975
3976      var tpl = [
3977          '<div id="shop2-alert">',
3978          '<div id="shop2-alert-body"></div>',
3979          '<a href="#" id="shop2-alert-ok" class="shop2-btn"></a>',
3980          '</div>',
3981          '<div id="shop2-alert-overlay"></div>'
3982        ].join('\n'),
3983
3984        win,
3985        overlay,
3986        body,
3987        ok,
3988        cls;
3989
3990      $(document.body).append(tpl);
3991
3992      win = $('#shop2-alert');
3993      overlay = $('#shop2-alert-overlay');
3994      body = $('#shop2-alert-body');
3995      ok = $('#shop2-alert-ok');
3996
3997      function hide() {
3998        overlay.hide();
3999        win.hide();
4000        win.removeAttr('class');
4001        cls = '';
4002        shop2.trigger('alertHide', win);
4003        return false;
4004      }
4005
4006      function show() {
4007        overlay.show();
4008        win.attr('class', cls);
4009        win.show().s3center();
4010        shop2.trigger('alertShow', win);
4011      }
4012
4013      overlay.on('click', hide);
4014      ok.on('click', hide);
4015
4016      shop2.alert = function(msg, btn, c) {
4017        ok.html(btn || 'Ok');
4018        body.html(msg);
4019        cls = c || 'shop2-alert--warning';
4020        show();
4021      };
4022
4023      shop2.alert.hide = hide;
4024
4025    },
4026
4027    tooltip: function() {
4028
4029      $('.shop2-tooltip').s3tooltip({
4030        cls: 'shop2-color-ext-tooltip',
4031        dir: 'top',
4032        data: function() {
4033          return $(this).data('tooltip');
4034        }
4035      });
4036
4037    },
4038
4039    colorTooltip: function() {
4040
4041      $('.shop2-color-ext-list li').s3tooltip({
4042
4043        cls: 'shop2-color-ext-tooltip',
4044        dir: 'top',
4045        data: function() {
4046          return $(this).children('div').html();
4047        }
4048
4049      });
4050
4051      $('.shop2-color-ext-multi').s3tooltip({
4052
4053        cls: 'shop2-color-ext-tooltip shop2_multi_tooltip',
4054        dir: 'top',
4055        data: function() {
4056          var ul = this.getElementsByTagName('ul');
4057          if (ul.length) {
4058            return ul[0].outerHTML;
4059          }
4060        }
4061
4062      });
4063
4064    },
4065
4066    colorPopup: function() {
4067
4068      var popup = $('<div id="shop2-color-ext-popup"></div>');
4069      var close = $('<div id="shop2-color-ext-close"></div>');
4070      var list = $('<ul id="shop2-color-ext-list" class="shop2-color-ext-list"></ul>');
4071      var colors = null;
4072
4073      popup.append(close);
4074      popup.append(list);
4075      $(document.body).append(popup);
4076
4077      $.on('.shop2-color-ext-caption', {
4078
4079        click: function() {
4080          var caption = $(this);
4081          var wrap = caption.closest('.shop2-color-ext-popup');
4082          var ul = wrap.find('.shop2-color-ext-list');
4083          var offset = caption.offset();
4084
4085          colors = ul.children('li');
4086          list.html(ul.html());
4087
4088          popup.css(offset).show();
4089
4090          return false;
4091        }
4092
4093      });
4094
4095
4096      $(document).on('click', '.shop2-color-ext-list li', function() {
4097        var $this = $(this);
4098        var data = $this.data();
4099        var input = $this.parent().find('input.additional-cart-params');
4100        var isSelected = $this.is('.shop2-color-ext-selected');
4101
4102        if (typeof data.kinds !== 'undefined' || input.length) {
4103
4104          $this.addClass('shop2-color-ext-selected').siblings().removeClass('shop2-color-ext-selected');
4105
4106          if (input.length) {
4107            input.val(data.value);
4108          } else {
4109            if (!isSelected) {
4110              shop2.product._reload(this);
4111            }
4112          }
4113
4114        } else {
4115
4116          var index = $this.index();
4117          var isPopup = !!$this.closest('#shop2-color-ext-popup').length;
4118          if (isPopup) {
4119            $this.toggleClass('shop2-color-ext-selected');
4120            colors.eq(index).toggleClass('shop2-color-ext-selected');
4121            shop2.filter.toggle(data.name, data.value);
4122            shop2.filter.count();
4123          }
4124        }
4125      });
4126
4127      $(document).on('click', function(e) {
4128        var target = $(e.target);
4129        var wrap = target.closest('#shop2-color-ext-popup');
4130
4131        if (!wrap.get(0) || e.target == close.get(0)) {
4132          popup.hide();
4133        }
4134      });
4135
4136    },
4137
4138    colorSelect: function() {
4139
4140      var select = $('<div id="shop2-color-ext-select"><ins></ins></div>');
4141      var colors = null;
4142      var input = null;
4143      $(document.body).append(select);
4144
4145      function hide() {
4146        if (select.is(':visible')) {
4147          select.hide();
4148          return true;
4149        }
4150      }
4151
4152      $(document).on('click', hide);
4153
4154      $.on('.shop2-color-ext-select', {
4155
4156        click: function() {
4157
4158          if (hide()) {
4159            return;
4160          }
4161
4162          var wrap = $(this);
4163          var ul = wrap.find('.shop2-color-ext-options');
4164          var offset = wrap.offset();
4165
4166          var html =
4167            '<div class="baron-wrapper">' +
4168            ' <div class="baron-scroller">' +
4169            '   <div class="baron-container">' +
4170            '     <div class="shop2-color-ext-options">' +
4171            ul.html() +
4172            '     </div>' +
4173            '   </div>' +
4174            '   <div class="baron-scroller-bar"></div>' +
4175            ' </div>' +
4176            '</div>';
4177
4178          colors = ul.children('li');
4179          input = wrap.find('input');
4180
4181          select.html(html)
4182          select.show();
4183
4184          var wrapWidth = wrap.width();
4185          var selectWidth = select.data('width') || (function() {
4186            var width = select.width();
4187            select.data('width', width);
4188            return width;
4189          })();
4190
4191          if (wrapWidth > selectWidth) {
4192            select.css('width', wrapWidth);
4193          } else {
4194            select.css('width', selectWidth);
4195          }
4196
4197          baron(select, {
4198            scroller: '.baron-scroller',
4199            container: '.baron-container',
4200            bar: '.baron-scroller-bar'
4201          });
4202
4203          select.css(offset);
4204
4205          return false;
4206
4207        }
4208
4209      });
4210
4211      $.on('#shop2-color-ext-select li:not(.shop2-color-ext-selected)', {
4212        click: function() {
4213          var $this = $(this);
4214          var index = $this.index();
4215          var data = $this.data();
4216          $this.addClass('shop2-color-ext-selected').siblings().removeClass('shop2-color-ext-selected');
4217          colors.removeClass('shop2-color-ext-selected');
4218          colors.eq(index).addClass('shop2-color-ext-selected');
4219          if (data.kinds) {
4220              shop2.product._reload(colors.get(index));
4221          } else {
4222            input.val(data.value);
4223            
4224        	if(!$(input).closest('.search-form').length) {
4225	           if( shop2.cf_margin_price_enabled ){
4226		       		shop2.margin_price.price_change(input, 'form');
4227		       };
4228        	}
4229            if ($this.hasClass('js-calc-custom-fields')) {
4230                shop2.product._reload(colors.get(index));
4231            }
4232          }
4233        }
4234      });
4235		 $.on('.js-calc-custom-fields', {
4236            change: function() {
4237                var $this = $(this);
4238                shop2.product._reload($this.find(':selected').parent());
4239            }
4240        });
4241        $.on('.shop2-color-ext-list .js-calc-custom-fields:not(select)', {
4242            click: function() {
4243                var $this = $(this);
4244                shop2.product._reload($this.parent());
4245            }
4246        });
4247
4248    },
4249
4250    coordinates: function() {
4251
4252      $(document).on('click', '.shop2-map-link', function(e) {
4253        e.preventDefault();
4254        var $this = $(this);
4255        var data = $this.data();
4256        var map = data.map;
4257        if (!map.title) {
4258          map.title = $this.text();
4259        }
4260        shop2.maps.alert(data.mapType, map);
4261      });
4262    },
4263
4264    /*restoreOrderForms: function() {
4265
4266     var key = 'shop2-order-in-one-page-form';
4267     var $form = $('.shop2-order-in-one-page-form');
4268
4269     if (!window.sessionStorage || $form.length === 0) {
4270     return;
4271     }
4272
4273     function getValues() {
4274     return JSON.parse(sessionStorage.getItem(key));
4275     }
4276
4277     function setValues() {
4278     var values = $form.serializeArray();
4279     var filled = [];
4280     $.each(values, function() {
4281     if (this.value) {
4282     filled.push(this);
4283     }
4284     });
4285     sessionStorage.setItem(key, JSON.stringify(filled));
4286     }
4287
4288     $form.on('change', ':input', setValues);
4289
4290     var values = getValues();
4291
4292     if (!values) {
4293     return;
4294     }
4295
4296     var hash = {};
4297     $.each(values, function() {
4298     hash[this.name] = this.value;
4299     });
4300
4301     if (values) {
4302     $form.s3deserializeArray(values);
4303     //sessionStorage.removeItem(key);
4304     }
4305
4306
4307     function afterDeliveryCalc() {
4308     var name;
4309     var $tarif;
4310     name = hash.delivery_id + '[edost][tarif]';
4311
4312     if (hash[name]) {
4313     $tarif = $form.find('[name="' + name + '"][value="' + hash[name] + '"]').trigger('click').trigger('change');
4314     }
4315
4316     name = hash.delivery_id + '[edost][office]';
4317     if (hash[name] && $tarif) {
4318     $tarif.closest('.shop2-edost-variant').find('[name="' + name + '"][value="' + hash[name] + '"]').trigger('click').trigger('change');
4319     }
4320     }
4321
4322     var $edostBtn = $('#shop2-edost-calc');
4323     var $edostTo = $('#shop2-edost2-to');
4324     var edostToValue = $edostTo.val();
4325
4326     if (hash.delivery_id && $edostBtn.is(':visible') && edostToValue && edostToValue != 'default') {
4327     shop2.on('afterDeliveryCalc', function() {
4328     afterDeliveryCalc();
4329     afterDeliveryCalc = $.noop;
4330     });
4331
4332     $edostBtn.trigger('click');
4333     }
4334
4335
4336
4337     setValues();
4338
4339     },*/
4340
4341
4342    fixDoubleOrders: function() {
4343
4344      var $form = $('.shop2-order-form, .shop2-order-in-one-page-form');
4345      var $submit = $form.find('[type=submit]');
4346
4347      $form.on('submit', function() {
4348        $submit.prop('disabled', true);
4349        setTimeout(function() {
4350          $submit.prop('disabled', false);
4351        }, 1000);
4352      });
4353
4354    },
4355
4356    paymentMethods: function() {
4357
4358      var $types = $('.shop2-payment-type input');
4359      var $methods = $('.shop2-payment-methods input');
4360
4361
4362      $types.on('change', function() {
4363        var $this = $(this);
4364        var $method = $this.closest('.shop2-payment-type').next('.shop2-payment-methods').find('input
4364:first');
4365        $methods.prop('checked', false);
4366        $method.prop('checked', true);
4367      });
4368
4369      $methods.on('change', function() {
4370        var $this = $(this);
4371        var $type = $this.closest('.shop2-payment-methods').prev('.shop2-payment-type').find('input:first');
4372        $types.prop('checked', false);
4373        $type.prop('checked', true);
4374      });
4375
4376    },
4377
4378    auth: function() {
4379
4380      $(document).on('click', '.js-shop2-cart-auth__expand', function(e) {
4381        e.preventDefault();
4382        $('.js-shop2-cart-auth__form').toggle();
4383      });
4384
4385    },
4386    /* https://megagroup.fibery.io/GR/GR_Task/11 */
4387    orderGetPayments: function( is_call_fanction, this_item ){
4388
4389      let callGetPayments = is_call_fanction || false;
4390      let arg_item = this_item || false;
4391
4392      if (shop2.shop2_cart_order_payments == 6) {
4393    
4394        var shop2_delivery = $('.shop2-order-options.shop2-delivery');
4395        var option_type = shop2_delivery.find('.option-type');
4396        var label_delivery_id = shop2_delivery.find(`.option-label [name="delivery_id"]`);
4397        var cart_order_payments = $('.shop2-cart-order-payments');
4398
4399        function getPayments(e, callback){// Функция была для клика, из контекста взять айди доставки
4400          var _this = this;
4401          var property_attach_id = _this.value;
4402          var property_attach = _this.property_attach || 0;
4403          var tarif = _this.tarif || 0;
4404          var delivery_type = _this.delivery_type || 0;
4405
4406          if (property_attach_id) {
4407            let data_param = {
4408              "attach_id": property_attach_id,
4409              "html": true, // необазтельное, значение по умолчанию - true, если передать false то вместо верстки будет json
4410              "mode": "one-page", // необазтельное, значение по умолчанию - ''
4411            };
4412
4413            if(property_attach){
4414              data_param.attach = property_attach;
4415            }else if( tarif ){
4416              data_param.deligate = {}
4417              data_param.deligate.tarif = tarif;
4418            }
4419            if(delivery_type){
4420              let property_attach = {
4421                'delivery_type' :  delivery_type,
4422                'deligate' : {
4423                  'tarif' : _this.tarif,
4424                  'pos' :  _this.pos,
4425                  'code' :  _this.code,
4426                  'insurance_type' :  _this.insurance_type,
4427                  'tariff_id' :  _this.tariff_id,
4428                }
4429              };
4430              data_param.attach = property_attach;
4431              
4432            }
4433            $.ajax({
4434              method: "GET",
4435              url: "/-/x-api/v1/public/?method=shop2/getPayments",
4436              data: {
4437                param: data_param
4438              },
4439              success: function(data) {
4440              	
4441                if( typeof data.result != 'undefined' && typeof data.result.html != 'undefined' ){
4442                  cart_order_payments.html(data.result.html);
4443  
4444                  if( typeof callback != 'undefined' ){
4445                    callback();
4446                  }
4447                }else if( typeof data.error != 'undefined' ){
4448                  if( data.error.message ){
4449                    cart_order_payments.html(data.error.message);
4450                  }
4451                }
4452                //trigger
4453                shop2.trigger('afterGetDeliveryPayments');
4454              }
4455            });
4456          }
4457        }
4458        
4459        if(!callGetPayments){
4460          label_delivery_id.off('paymentClick').on('click.paymentClick', getPayments);
4461          
4462          if( $('#shop2-order-delivery .tab-label').length){
4463
4464              $(document).off('click.paymentClick').on('click.paymentClick', '#shop2-order-delivery .option-type:not(.active-type)', function(e){
4465                let payment_method = {},
4466                $this = $(this),
4467                option_label = $this.find('.option-label'),
4468                option_input = option_label.find('input')[0]; 
4469
4470                payment_method.value = option_label.data('attach_id'); // Очень важное для обычных кликов;
4471
4472
4473                if( typeof $this.attr('data-option-for-paymethod') != 'undefined' ){
4474                  let str_option_for_paymethod = $this.attr('data-option-for-paymethod');
4475                  let obj = JSON.parse(str_option_for_paymethod);
4476                  payment_method.delivery_type = obj.delivery_type;
4477                  payment_method.value = obj.attach_id;
4478                  payment_method.tarif = obj.tariff_hash;
4479                  payment_method.pos = obj.pos;
4480                  payment_method.code = obj.code;
4481                  payment_method.insurance_type = obj.insurance_type;
4482                  payment_method.tariff_id = obj.tariff_id;
4483                  
4484                } else if(option_input.name.match('tarif')){
4485                  
4486                  payment_method.tarif = option_input.value
4487                }
4488
4489                getPayments.call( payment_method, '');
4490              });
4491
4492              if( $('.shop2-warning').hasClass('hide') ) {
4493                let option_type_active = $('#shop2-order-delivery .option-type').filter('.active-type');
4494
4495                option_type_active
4496                  .trigger('click.paymentClick');
4497                
4498                option_type_active
4499                  .closest('.shop2-delivery--item__tab')
4500                  .addClass('active-tab');
4501                  
4502              	if (shop2.shop2_cart_order_payments == 6) {
4503                    shop2.queue.orderGetPayments(true, option_type_active.find('[name="delivery_id"]')[0]);
4504                };
4505              }
4506          }
4507        }
4508
4509        if(cart_order_payments.length && label_delivery_id.length && !localStorage.getItem('delivery_item_active') ){
4510
4511          var option_type_active = option_type.filter('.active-type');
4512          var delivery_elem = option_type_active.find(`.option-label [name="delivery_id"]`);
4513          
4514          
4515          getPayments.call( delivery_elem, '', ()=>{// функция вызывается без клика, контекст передается методом CALL
4516            
4517            let payment_id = cart_order_payments.attr('data-payment_id') || false;
4518            if(payment_id){
4519              var payment_system_list = cart_order_payments.find(`.option-label [name="payment_id"]`);
4520              payment_system_list.first().removeAttr('checked');
4521              var input_payment_id = payment_system_list.filter(function( i, elem ){
4522                return $(elem).val() == payment_id || $(elem).val() == ('-'+payment_id);
4523              });
4524              input_payment_id.attr('checked', 'checked');
4525              var parent_input_payment_id = input_payment_id.closest('.option-type');
4526    
4527              parent_input_payment_id.addClass('active-type').siblings().removeClass('active-type');
4528            }
4529          });
4530          
4531        }
4532        if(callGetPayments){// Вызов функции
4533          getPayments.call( arg_item );
4534        }
4535      }
4536    }
4537    /* https://megagroup.fibery.io/GR/GR_Task/11 */
4538  };
4539  
4540  shop2.cart.applyBonusPoint = function(bonus_points, func) {
4541
4542    shop2.trigger('beforeCartApplyBonus');
4543
4544    $.getJSON(
4545        '/-/x-api/v1/public/?method=cart/applyBonusPoints', {
4546            param: {
4547                hash: shop2.hash.cart,
4548                bonus_points: bonus_points
4549            }
4550        },
4551        function(d, status) {
4552            shop2.fire('afterCartApplyBonusPoints', func, d, status);
4553            shop2.trigger('afterCartApplyBonusPoints', d, status);
4554        }
4555    );
4556
4557    return false;
4558  };
4559
4560  shop2.cart.removeBonusPoint = function(func) {
4561
4562    shop2.trigger('beforeCartRemoveCartBonusPoints');
4563
4564    $.getJSON(
4565        '/-/x-api/v1/public/?method=cart/RemoveBonusPoints', {
4566            param: {
4567                hash: shop2.hash.cart
4568            }
4569        },
4570        function(d, status) {
4571            shop2.fire('afterCartRemoveCartBonusPoints', func, d, status);
4572            shop2.trigger('afterCartRemoveCartBonusPoints', d, status);
4573        }
4574    );
4575  };
4576
4577  shop2.margin_price = {
4578      price_change: function(j_this, selector_parent){
4579        
4580        if( shop2.mode == 'cart' ){
4581            form = $('#shop2-cart');
4582            shop2.cart.update(form);
4583          
4584          return;
4585        }
4586        
4587          var $form = $(j_this).closest(selector_parent);
4588          	if($form.hasClass('shop2-filter')){ return; }
4589          
4590          var form = $form.get(0),
4591          kind_id = form.kind_id.value,
4592                  
4593          adds = $form.find('.additional-cart-params'),
4594          len = adds.length,
4595          el;
4596          
4597
4598          var param = {
4599              'kind_id': form.kind_id.value,
4600              'params': {}
4601          }
4602          
4603          if (len) {
4604      
4605              for (var i = 0; i < len; i += 1) {
4606                  el = adds[i];
4607                  if (el.value) {
4608                      param.params[el.name] = el.value;
4609                  }
4610              }
4611          }
4612          $.ajax({
4613            url: '/-/x-api/v1/public/?method=shop2/getPrice',
4614        type: "get",
4615        data: {"param": param},
4616        dataType: "json",
4617        success: function(data){
4618          
4619          $form.find('.price-current').replaceWith( data.result.data.html.price );
4620          $form.find('.price-old ').replaceWith( data.result.data.html.price_old );
4621        }
4622        
4623          });
4624      },
4625      select_change: function(){
4626      if( !shop2.cf_margin_price_enabled ){
4627          return;
4628      }else{
4629        $(document).on('click', '.shop2-color-ext-list li', function() {
4630          var $this = $(this);
4631          
4632          setTimeout(function(){
4633                  shop2.margin_price.price_change($this, 'form');
4634          }, 10)
4635        })
4636        var additional_cart_params = $('select.additional-cart-params');
4637        
4638        if( additional_cart_params.length ){
4639          $.on('select.additional-cart-params', {
4640            change: function(e) {
4641              shop2.margin_price.price_change( $( e.target ), 'form');
4642            }
4643          });
4644        }else {
4645          return;	
4646        }
4647      }
4648      
4649      }
4650  };
4651  shop2.queue.margin_price = function() {
4652
4653    if( shop2.mode == 'cart' && !$('#delivery_id_deligate').length ){
4654    
4655      if( localStorage.getItem('delivery_item_active') ){
4656      
4657        let delivery_item_active = $('.shop2-order-in-one-page-form .shop2-delivery .options-list .option-type').eq( +localStorage.getItem('delivery_item_active') ).find('.option-label');
4658        
4659        delivery_item_active.trigger('click').addClass( 'active-type' );
4660        
4661
4662        shop2.queue.orderGetPayments(true, delivery_item_active.find('[name="delivery_id"]')[0] );
4663        
4664      }else if( shop2.shop2_cart_order_payments == 6 ){
4665        $('.shop2-order-in-one-page-form .shop2-delivery > .options-list > .option-type.active-type > .option-label input').trigger('click');
4666      }
4667      
4668		$('.shop2-order-in-one-page-form .shop2-delivery .options-list .option-type .option-label').on('click', function(){
4669			let index = $('.shop2-order-in-one-page-form .shop2-delivery .options-list .option-type.active-type').index();
4670			localStorage.setItem('delivery_item_active', index);
4671		});
4672    }
4673    
4674    shop2.margin_price.select_change();
4675  };
4676
4677  shop2.queue.bonus = function() {
4678
4679    shop2.on('afterCartApplyBonusPoints, afterCartRemoveCartBonusPoints', function() {
4680        document.location.reload();
4681    });
4682
4683    $('.bonus-apply').on('click', function(e) {
4684        var bonus = $('#bonus-points'),
4685            points = Number(bonus.val()),
4686            bonus_user = Number($('.bonus-amount').html());
4687            
4688    switch (true) {
4689          case points == "" || points > bonus_user:
4690            
4691            e.preventDefault();
4692            
4693          break;  
4694          case bonus_user >= points:
4695            
4696            shop2.cart.applyBonusPoint(points);
4697            
4698          break;
4699        };
4700    });
4701
4702    $('.bonus-delete').on('click', function(e) {
4703        shop2.cart.removeBonusPoint();
4704    });
4705  
4706  $.fn.inputFilter = function(inputFilter) {
4707      return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
4708        if (inputFilter(this.value)) {
4709            this.oldValue = this.value;
4710            this.oldSelectionStart = this.selectionStart;
4711            this.oldSelectionEnd = this.selectionEnd;
4712        } else if (this.hasOwnProperty("oldValue")) {
4713            this.value = this.oldValue;
4714            this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
4715        }
4716      });
4717    };
4718    
4719    $("#bonus-points").inputFilter(function(value) {
4720      return /^\d*$/.test(value); 
4721    });
4722  };
4723
4724  var maps = shop2.maps = {};
4725
4726  maps.alert = function(type, params) {
4727    shop2.alert('<div id="shop2-alert-map"></div>', 'Закрыть', 'shop2-alert--map');
4728    maps[type].ready(function() {
4729      maps[type].draw('shop2-alert-map', params);
4730    });
4731  };
4732
4733  maps.getCenter = function(arr) {
4734    var x = 0;
4735    var y = 0;
4736    $.each(arr, function() {
4737      x += this.x;
4738      y += this.y;
4739    });
4740
4741  };
4742
4743
4744  maps.yandex = {
4745    ymaps: window.ymaps,
4746    _loading: $.Deferred(),
4747    _loading_init: false,
4748    _loading_callback: function(ymaps) {
4749      this.ymaps = ymaps;
4750      this._loading.resolve(ymaps);
4751    },
4752    ready: function(callback) {
4753      this._loading.done(callback);
4754      if (this.ymaps) {
4755        this._loading.resolve(this.ymaps);
4756        return;
4757      }
4758      if (!this._loading_init) {
4759      	if (shop2.maps_yandex_key!='') {
4760        	$('head').append('<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU&onload=shop2.maps.yandex._loading_callback&apikey=' + shop2.maps_yandex_key +'" type="text/javascript">');
4761      	} else {
4762        	$('head').append('<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU&onload=shop2.maps.yandex._loading_callback" type="text/javascript">');
4763      	}
4764        this._loading_init = true;
4765      }
4766    },
4767    draw: function(id, point) {
4768      point = $.extend({}, point);
4769      point.title = $.s3escape(point.title);
4770      point.text = $.s3escape(point.text);
4771
4772      var map = new this.ymaps.Map(id, {
4773        zoom: point.z,
4774        center: [point.x, point.y],
4775        behaviors: ['drag', 'rightMouseButtonMagnifier', 'scrollZoom']
4776      });
4777
4778      var MyBalloonContentLayoutClass = this.ymaps.templateLayoutFactory.createClass(
4779        '<div class="shop2-map-baloon-content">' +
4780        '<h3>$[properties.title]</h3>' +
4781        '$[properties.text]' +
4782        '</div>'
4783      );
4784      var placemark = new self.ymaps.Placemark([point.x, point.y], point, {
4785        balloonContentLayout: MyBalloonContentLayoutClass
4786      });
4787		
4788      map.geoObjects.add(placemark);
4789    }
4790  };
4791
4792
4793  maps.google = {
4794    gmaps: window.google && window.google.maps ? window.google.maps : false,
4795    _loading: $.Deferred(),
4796    _loading_init: false,
4797    _loading_callback: function() {
4798      try {
4799        this.gmaps = window.google.maps;
4800        this._loading.resolve(this.gmaps);
4801      } catch (e) {
4802        console.log(e);
4803      }
4804    },
4805    ready: function(callback) {
4806      this._loading.done(callback);
4807      if (this.gmaps) {
4808        this._loading.resolve(this.gmaps);
4809        return;
4810      }
4811      if (!this._loading_init) {
4812      $('head').append('<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&callback=shop2.maps.google._loading_callback&key=' + shop2.maps_google_key + '" type="text/javascript">');
4813        this._loading_init = true;
4814      }
4815    },
4816    draw: function(id, point) {
4817      var map = new this.gmaps.Map(document.getElementById(id), {
4818        zoom: Number(point.z),
4819        center: new google.maps.LatLng(point.x, point.y)
4820      });
4821      var marker = new google.maps.Marker({
4822        position: new google.maps.LatLng(point.x, point.y),
4823        map: map,
4824        title: point.title
4825      });
4826      var infowindow = new google.maps.InfoWindow({
4827        content: '<div class="shop2-map-baloon-content">' +
4828          '<h3>' + $.s3escape(point.title) + '</h3>' +
4829          $.s3escape(point.text) +
4830          '</div>'
4831      });
4832      this.gmaps.event.addListener(marker, 'click', function() {
4833        infowindow.open(map, marker);
4834      });
4835    }
4836  };
4837
4838
4839  $(window).on('load', function() {
4840    shop2.queue.heights();
4841    shop2.product.productDatePicker();
4842  });
4843
4844  self.shop2 = shop2;
4845
4846  $(function() {
4847    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/i.test(navigator.userAgent),
4848      clickStart = (isMobile) ? 'touchend.respons' : 'click.respons';
4849
4850
4851    $('.personal-html-btn, .close-btn').on(clickStart, function(e) {
4852      e.preventDefault();
4853      $('.personal-html-content').toggleClass('active');
4854    });
4855    
4856    
4857    $(document).on('click','.btn_payment_rest', function(){
4858      $('.shop2-order-options-wrapper').slideToggle();
4859    });
4860    
4861
4862    $(document).on(clickStart, function(event) {
4863      if ($(event.target).closest('.personal-html-content-in, .personal-html-btn').length) return;
4864      $('.personal-html-content').removeClass('active');
4865    });
4866    $(this).keydown(function(eventObject) {
4867      if (eventObject.which == 27) {
4868        $('.personal-html-content').removeClass('active');
4869      }
4870    });
4871    
4872    
4873    $(document).on('click', '#shop2-color-ext-select li', function(){
4874        if (shop2.facets.enabled) {
4875	        setTimeout(function(){
4876	            var url = '/-/shop2-api/?cmd=getSearchMatches&hash=' +
4877	                shop2.apiHash.getSearchMatches +
4878	                '&ver_id=' + shop2.verId + '&',
4879	                fullUrl = url + $(shop2.facets.search.wrapper).serialize();
4880	        	
4881	            shop2.facets.getDataSearch(fullUrl);
4882            }, 100);
4883        };
4884    });
4885    
4886    $(document.body).on('change','.shop2-block.search-form #shop2_search_custom_fields select, .shop2-block.search-form #shop2_search_custom_fields input',function(){
4887        if (shop2.facets.enabled) {
4888	        setTimeout(function(){
4889	            var url = '/-/shop2-api/?cmd=getSearchMatches&hash=' +
4890	                shop2.apiHash.getSearchMatches +
4891	                '&ver_id=' + shop2.verId + '&',
4892	                fullUrl = url + $(shop2.facets.search.wrapper).serialize();
4893	            
4894	            shop2.facets.getDataSearch(fullUrl);
4895            }, 100);
4896        };
4897    });
4898    
4899  });
4900
4901})(jQuery, window);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.