PageSourceSearch

https://tbk-systems.ru/t/v4385/images/js/shop2_local.js

js tbk-systems.ru collected 2026-09-29 13:44:25 UTC 105,456 bytes, 3,765 lines download raw bytes

1'use strict';
2
3(function($) {
4
5  var $document = $(document);
6
7  $.expr[':'].style = function(obj, index, meta) {
8    var $obj = $(obj),
9      params = meta[3].split(','),
10      property,
11      value;
12
13    params = $.map(params, function(n) {
14      return $.trim(n);
15    });
16
17    property = params[0];
18    value = params[1];
19
20    if ($obj.css(property) == value) {
21      return true;
22    }
23  };
24
25  $.s3throttle = function(name, func, time) {
26    var id = $.s3throttle.timeouts[name];
27    if (id) {
28      clearTimeout(id);
29    }
30
31    $.s3throttle.timeouts[name] = setTimeout(func, time);
32  };
33
34  $.s3escape = function(text) {
35    return $('<div>').text(text).html();
36  };
37
38  $.s3throttle.timeouts = {};
39
40  $.fn.s3center = function() {
41
42    return this.each(function() {
43      var $this = $(this),
44        isVisible = $this.is(':visible');
45
46      if (!isVisible) {
47        $this.show();
48      }
49
50      $this.css({
51        marginLeft: -$this.outerWidth() / 2,
52        marginTop: -$this.outerHeight() / 2
53      });
54
55      if (!isVisible) {
56        $this.hide();
57      }
58    });
59  };
60
61
62  $.fn.s3deserializeArray = function(arr) {
63    return this.each(function() {
64      var $this = $(this);
65      $.each(arr, function() {
66        var $el = $this.find('[name="' + this.name + '"]');
67        if (!$el.length) {
68          return;
69        }
70        if ($el.is('input[type=radio]')) {
71          $el.filter('[value="' + this.value + '"]').trigger('click');
72        } else {
73          $el.val(this.value).trigger('change');
74        }
75      });
76    });
77  };
78
79  $.fn.caret = function(begin, end) {
80    var range;
81
82    if (this.length === 0 || this.is(':hidden')) {
83      return;
84    }
85
86    if ($.type(begin) === 'number') {
87      end = ($.type(end) === 'number') ? end : begin;
88      return this.each(function() {
89        if (this.setSelectionRange) {
90          this.setSelectionRange(begin, end);
91        } else if (this.createTextRange) {
92          range = this.createTextRange();
93          range.collapse(true);
94          range.moveEnd('character', end);
95          range.moveStart('character', begin);
96          range.select();
97        }
98      });
99    } else {
100      if (this[0].setSelectionRange) {
101        begin = this[0].selectionStart;
102        end = this[0].selectionEnd;
103      } else if (document.selection && document.selection.createRange) {
104        range = document.selection.createRange();
105        begin = 0 - range.duplicate().moveStart('character', -100000);
106        end = begin + range.text.length;
107      }
108      return {
109        begin: begin,
110        end: end
111      };
112    }
113  };
114
115  $.keys = {};
116
117  $.KEYS = {
118    Digit: [48, 57],
119    Backspace: 8,
120    Comma: 44,
121    Point: 46
122  };
123
124  $.each($.KEYS, function(key, value) {
125    $.keys['is' + key] = function(code) {
126      if ($.isArray(value)) {
127        return (value[0] <= code && code <= value[1]);
128      } else {
129        return value === code;
130      }
131    };
132  });
133
134  $.fn.getVal = function() {
135    var values = [];
136
137    this.each(function() {
138      var v = $(this).val();
139      v = parseFloat(v);
140      if (!v) {
141        v = 0;
142      }
143      values.push(v);
144    });
145    return values;
146  };
147
148  $.fn.keyFilter = function(selector, settings) {
149    settings = $.extend({
150      type: 'int',
151      def: '',
152      callback: $.noop
153    }, settings);
154
155    return this.each(function() {
156      var $this = $(this);
157
158      $this.on('keypress', selector, function(e) {
159        var caret, isBackspace, isDigit, isPoint, val, input = $(this);
160
161        if (e.shiftKey || e.ctrlKey) {
162          return false;
163        }
164
165        if (e.which === 0) {
166          return true;
167        }
168
169        isDigit = $.keys.isDigit(e.which);
170        isPoint = $.keys.isPoint(e.which) || $.keys.isComma(e.which);
171        isBackspace = $.keys.isBackspace(e.which);
172
173        if (!isDigit && !isPoint && !isBackspace) {
174          return false;
175        }
176
177        if (settings.type === 'int' && isPoint) {
178          return false;
179        }
180
181        val = input.val().replace(/,/g, '.');
182        caret = input.caret();
183        input.val(val);
184        input.caret(caret.begin, caret.end);
185
186        if (isPoint && val.indexOf('.') !== -1) {
187          return false;
188        }
189      });
190
191      $this.on('keyup', selector, function() {
192        var input = $(this);
193        settings.callback(input);
194      });
195
196      $this.on('blur', selector, function() {
197        var input = $(this);
198        if (input.val() === '') {
199          input.val(settings.def);
200          settings.callback(input);
201        }
202      });
203    });
204  };
205
206  $.fn.getHeights = function() {
207    var values = [],
208      max = 0;
209
210    this.each(function() {
211      var $this = $(this),
212        height;
213
214      $this.css('min-height', 0);
215
216      height = $this.height();
217      values.push(height);
218
219      if (height > max) {
220        max = height;
221      }
222    });
223
224    return {
225      values: values,
226      max: max
227    };
228  };
229
230  $.fn.eachRow = function(processing, deleteMarginRight) {
231    var elements = this,
232      wrap = elements.parent(),
233      wrapWidth, elementWidth, inRow, left, right, i = 0,
234      len;
235
236    if (wrap.get(0) && elements.get(0)) {
237      wrapWidth = wrap.width();
238      elementWidth = elements.outerWidth(true);
239      if (deleteMarginRight) {
240        wrapWidth += parseFloat(elements.css('margin-right'));
241      }
242      inRow = Math.floor(wrapWidth / elementWidth);
243      if (inRow > 1) {
244        for (len = elements.length; i < len; i += inRow) {
245          left = i;
246          right = i + inRow;
247          if (right > len) {
248            right = len;
249          }
250          processing(elements.slice(left, right), elements.eq(left), elements.eq(right - 1));
251        }
252      }
253    }
254    return elements;
255  };
256
257  $.on = function(selector, obj) {
258
259    $.each(obj, function(key, value) {
260
261      $document.on(key, selector, value);
262
263    });
264
265  };
266
267  $.fn.s3tooltip = function(settings) {
268
269    settings = $.extend({
270      data: function() {
271        return this.alt || '';
272      },
273
274      cls: 'tooltip-1',
275      slide: true,
276      dir: 'bottom'
277
278    }, settings);
279
280    var tooltip = $('#shop2-tooltip');
281
282    if (!tooltip.get(0)) {
283      tooltip = $('<div id="shop2-tooltip"></div>');
284      $('body').append(tooltip);
285    }
286
287    var selector = this.selector;
288
289    var win = {
290        $el: $(window)
291      },
292      width,
293      height;
294
295    $.on(selector, {
296
297      mouseenter: function(e) {
298        var html = settings.data.call(this);
299
300        if (!html) {
301          return;
302        }
303
304        win.width = win.$el.width();
305        win.height = win.$el.height();
306
307        tooltip.html(html);
308        tooltip.addClass(settings.cls);
309        tooltip.show();
310
311        width = tooltip.outerWidth(true);
312        height = tooltip.outerHeight(true);
313      },
314
315      mouseleave: function(e) {
316        tooltip.hide();
317        tooltip.removeClass(settings.cls);
318      },
319
320      mousemove: function(e) {
321
322        var left = e.pageX,
323          top = e.pageY,
324          scrollTop = $document.scrollTop();
325
326        if (left + width > win.width) {
327          left -= width;
328        }
329
330        if (settings.dir == 'top') {
331          top -= height;
332
333          if (top < scrollTop) {
334
335            if (settings.slide) {
336
337              top = scrollTop;
338
339            } else {
340
341              top += height;
342            }
343
344          }
345
346        } else {
347
348          if (top + height > win.height + scrollTop) {
349
350            if (settings.slide) {
351
352              top = win.height + scrollTop - height;
353
354            } else {
355
356              top -= height;
357
358            }
359
360          }
361
362        }
363
364        tooltip.css({
365          left: left,
366          top: top
367        });
368
369      }
370    });
371
372  };
373
374})(jQuery);
375
376
377(function($, self) {
378
379  var shop2 = {
380    queue: {},
381    callbacks: {},
382    init: function(settings) {
383
384      $.extend(this, settings);
385
386      this.my = this.my || {};
387
388      $(function() {
389        var queue = shop2.queue;
390        $.each(queue, function(method) {
391          var f = queue[method];
392          if ($.isFunction(f)) {
393            f();
394          }
395        });
396      });
397
398    }
399  };
400
401  if (document.location.search.indexOf('debug') != -1) {
402    shop2.debug = true;
403  }
404
405  try {
406
407    if (window.sessionStorage) {
408      var current = sessionStorage.getItem('shop2_current_url');
409      var url = location.pathname + location.search;
410      if (current != url) {
411        sessionStorage.setItem('shop2_back_url', current);
412      }
413      sessionStorage.setItem('shop2_current_url', url);
414    }
415
416    shop2.back = function() {
417      var url;
418      if (window.sessionStorage) {
419        url = sessionStorage.getItem('shop2_back_url');
420        if (url === 'null') {
421          url = '/';
422        }
423      } else {
424        url = document.referrer;
425      }
426      document.location = url || '/';
427      return false;
428    };
429
430  } catch (e) {
431    shop2.back = function() {
432      document.location = document.referrer;
433    }
434  }
435
436  shop2.on = function(type, func) {
437    var _this = this;
438
439    $.each(type.split(','), function(index, type) {
440      type = $.trim(type);
441
442      if (!_this.callbacks[type]) {
443        _this.callbacks[type] = $.Callbacks();
444      }
445
446      _this.callbacks[type].add(func);
447    });
448  };
449
450  shop2.off = function(type, func) {
451    if (this.callbacks[type]) {
452      func ? this.callbacks[type].remove(func) : this.callbacks[type].empty();
453    }
454  };
455
456  shop2.trigger = function(type) {
457    if (this.callbacks[type]) {
458      this.callbacks[type].fireWith(self, [].slice.call(arguments, 1));
459    }
460  };
461
462  shop2.fire = function(type, func) {
463    if ($.isFunction(func)) {
464      var has = !!(this.callbacks && this.callbacks[type] && this.callbacks[type].has(func));
465
466      if (!has) {
467        func.apply(self, [].slice.call(arguments, 2));
468      }
469    }
470  };
471
472  shop2.filter = {
473    _pre_params: '',
474    init: function() {
475      var search = decodeURIComponent(document.location.search);
476      if (search) {
477        search = search.slice(1);
478      }
479      this.str = search;
480    },
481    escape: function(name) {
482      return name.replace(/(\[|\])/g, '\\$1');
483    },
484    remove: function(name, value) {
485      var str = name + '=';
486      if (typeof value !== 'undefined') {
487        str += value;
488      }
489      var re = new RegExp('(.*)(' + this.escape(str) + '[^&]*&*)(.*)', 'ig');
490      this.str = this.str.replace(re, '$1$3').replace(/&$/, '');
491      return this;
492    },
493    add: function(name, value) {
494      this.remove(name, value);
495      this.str += (this.str !== '') ? '&' : '';
496      this.str += name + '=' + value;
497      return this;
498    },
499    has: function(name, value) {
500      var str = name + '=';
501      if (typeof value !== 'undefined') {
502        str += value;
503      }
504      if (this.str.indexOf(str) > -1) {
505        return true;
506      }
507      return false;
508    },
509    get: function(name) {
510      var re = new RegExp(this.escape(name) + '=([^&]*)'),
511        matches = this.str.match(re);
512      if (matches && matches.length == 2) {
513        return matches[1];
514      }
515      return false;
516    },
517    toggle: function(name, value) {
518
519      if (name == 's[amount][min]') {
520        if (this.get('s[amount][max]') === '0') {
521          this.remove('s[amount][max]');
522          this.add('s[amount][min]', 0);
523          return this;
524        } else if (this.get('s[amount][min]') === '0') {
525          this.remove('s[amount][min]');
526          this.add('s[amount][max]', 0);
527          return this;
528        }
529      } else if (name == 's[amount][max]') {
530        if (this.get('s[amount][min]') === '1') {
531          this.remove('s[amount][min]');
532          this.add('s[amount][min]', 0);
533          return this;
534        } else if (this.get('s[amount][min]') === '0') {
535          this.remove('s[amount][min]');
536          this.add('s[amount][min]', 1);
537          return this;
538        }
539      }
540
541      if (this.has(name, value)) {
542        this.remove(name, value);
543      } else {
544        this.add(name, value);
545      }
546      return this;
547    },
548    sort: function(name) {
549      var re = new RegExp(this.escape('s[sort_by]') + '=([^&]*)'),
550        params = this.str.match(re),
551        desc = name + ' desc',
552        asc = name + ' asc';
553
554      params = (params && params.length > 1) ? params[1] : '';
555
556      if (params.indexOf(desc) !== -1) {
557        params = params.replace(desc, asc);
558      } else if (params.indexOf(asc) !== -1) {
559        params = params.replace(asc, desc);
560      } else if (params !== '') {
561        params += ',' + desc;
562      } else {
563        params = desc;
564      }
565
566      this.remove('s[sort_by]');
567      this.add('s[sort_by]', params);
568      return this;
569    },
570    go: function() {
571      var str = '';
572      if (this.str) {
573        str += (this.str.charAt(0) == '?') ? '' : '?';
574        str += this.str;
575      }
576
577      document.location =
578        document.location.pathname.replace(/\/p\/\d*/g, '') +
579        str +
580        document.location.hash;
581      return false;
582    },
583    count: function(func) {
584      var url = '/-/shop2-api/?cmd=getSearchMatches&hash=' +
585        shop2.apiHash.getSearchMatches +
586        '&ver_id=' + shop2.verId +
587        '&' + this.str +
588        this._pre_params;
589
590      shop2.trigger('beforeGetSearchMatches');
591
592      $.get(
593        url,
594        function(d, status) {
595          if (status == 'success') {
596            if ($.type(d) === 'string') {
597              d = $.parseJSON(d);
598            }
599          }
600
601          if (shop2.facets.enabled) {
602            shop2.facets.aggregation(d);
603          }
604
605          shop2.fire('afterGetSearchMatches', func, d, status);
606          shop2.trigger('afterGetSearchMatches', d, status);
607        }
608      );
609
610    }
611  };
612
613  shop2.search = {
614    getParams: function(folder_id, func) {
615      var url;
616
617      shop2.trigger('beforeGetFolderCustomFields');
618
619      if (folder_id > 0) {
620        url = '/-/shop2-api/?cmd=getFolderCustomFields' +
621          '&hash=' + shop2.apiHash.getFolderCustomFields +
622          '&ver_id=' + shop2.verId +
623          '&folder_id=' + folder_id +
624          '&' + decodeURIComponent(document.location.search).replace(/[^&]*=(&|$)/g, '');
625
626        $.getJSON(url, function(d, status) {
627          shop2.fire('afterGetFolderCustomFields', func, d, status);
628          shop2.trigger('afterGetFolderCustomFields', d, status);
629        });
630      }
631    }
632  };
633
634  shop2.facets = {
635    enabled: false,
636    aggs: null,
637    _data: {},
638    emptyClass: 'empty-val',
639
640    mask: '[data-name^="s[field]"][data-value="key"],' +
641      '[name="s[parentField][parentKey]"] [value="key"],' +
642      '[name="s[field]"] [value="key"],' +
643      '[data-name="s[field][index]"],' +
644      '[data-name="s[field][key]"],' +
645      '[name="s[field][key]"]',
646
647    filter: {
648      wrapper: '.shop2-filter, #shop2-color-ext-list',
649      items: '[data-name], [name], [name] [value]'
650    },
651
652    search: {
653      wrapper: '.shop2-block.search-form form, #shop2-color-ext-select',
654      items: '[data-name], [name], [name] [value]'
655    },
656
657    ignoreClear: function($item) {
658      this._data.attrName = $item.attr('name') ? $item.attr('name') : $item.parent().attr('name');
659      this._data.isSelect = $item.prop('tagName').toLowerCase() === 'select';
660      this._data.val = $item.prop('tagName').toLowerCase() === 'option' && $item.val() === '';
661      return /s\[(folder_id|products_per_page)\]/i.test(this._data.attrName) || this._data.isSelect || this._data.val;
662    },
663
664    set: function(mod /* module filter, search */ ) {
665      var module = shop2.facets[mod];
666
667      if (!module) {
668        return;
669      }
670
671      var $wrapper = $(module.wrapper);
672      var $items = $wrapper.find(module.items);
673
674      this._data.$wrapper = $wrapper;
675
676      this.clearItems($items);
677      this.insertData(this.aggs);
678
679      var eventName = 'afterFacets' + mod.charAt(0).toUpperCase() + mod.slice(1);
680
681      shop2.trigger(eventName, this.aggs);
682    },
683
684    searchSetup: function() {
685      if (!this.search) {
686        return;
687      }
688
689      var $form = $(this.search.wrapper);
690
691      if (!$form.length) {
692        return;
693      }
694
695      var $items = $form.find(this.search.items);
696      var self = this;
697      var url = '/-/shop2-api/?cmd=getSearchMatches&hash=' +
698        shop2.apiHash.getSearchMatches +
699        '&ver_id=' + shop2.verId + '&',
700        fullUrl = url + $form.serialize();
701
702      this.getDataSearch(fullUrl);
703
704      $items.on('change', function(e) {
705        if (e.target.name == "s[products_per_page]") {
706          return;
707        }
708
709        fullUrl = url + $form.serialize()
710
711        self.getDataSearch(fullUrl);
712      });
713    },
714
715    getDataSearch: function(url) {
716      $.get(
717        url,
718        function(d, status) {
719          if (status == 'success') {
720            if ($.type(d) === 'string') {
721              d = $.parseJSON(d);
722            }
723
724            shop2.facets.aggregation(d);
725            shop2.facets.set('search');
726          }
727        }
728      );
729    },
730
731    clearItems: function($items) {
732      var emptyClass = this.emptyClass;
733      var self = this;
734      var $item, nodeName;
735
736      $items.each(function(index, item) {
737        $item = $(item);
738
739        if (self.ignoreClear($item)) {
740          return true;
741        }
742
743        nodeName = $item.prop('tagName').toLowerCase();
744
745        switch (nodeName) {
746          case 'select':
747            break;
748          case 'input':
749            $item.attr('placeholder', '');
750            break;
751          case 'option':
752            if ($item.attr('value')) {
753              $item.attr('disabled', 'disabled');
754            }
755            break;
756        }
757
758        $item.attr('data-param-val', '0');
759        $item.addClass(emptyClass);
760      });
761    },
762
763    aggregation: function(d) {
764      if (typeof d === 'object' && d.data.aggs) {
765        this.aggs = this.dataSetup(d.data.aggs);
766      }
767
768      return this.aggs;
769    },
770
771    dataSetup: function(aggs) {
772      var cf = aggs.cf;
773      var key, field;
774
775      for (key in cf) {
776        field = cf[key];
777
778        if ($.isArray(field) && !field.length) {
779          delete cf[key];
780        }
781      }
782
783      return aggs;
784    },
785
786    insertData: function(aggs, field, parentField) {
787      $.each(aggs, $.proxy(function(key, value) {
788        if (typeof value === "object") {
789          this.insertData(value, key, field);
790        } else {
791          this._data.$item = this.getItem(field, key, parentField);
792
793          if (!this._data.$item.length || !value) {
794            return true;
795          }
796
797          switch (this._data.$item.prop('tagName').toLowerCase()) {
798            case 'input':
799              this._data.$item.attr('placeholder', value);
800              break;
801            case 'option':
802              this._data.$item.removeAttr('disabled');
803              break;
804          }
805
806          this._data.$item.attr('data-param-val', value);
807          this._data.$item.removeClass(this.emptyClass);
808        }
809      }, this));
810    },
811
812    getItem: function(field, key, parentField) {
813      if (parentField && parentField !== 'cf') {
814        this._data.selector = this.mask.replace(/parentField/g, parentField).replace(/parentKe
814y/g, field).replace(/key/g, key);
815      } else {
816        this._data.selector = this.mask.replace(/field/g, field).replace(/key/g, key);
817      }
818
819      return this._data.$wrapper.find(this._data.selector);
820    },
821
822    setMask: function(mask) {
823      this.mask = mask;
824    },
825
826    setEmptyClass: function(emptyClassName) {
827      this.emptyClass = emptyClassName;
828    },
829
830    setContainers: function(module, obj) {
831      this[module] = obj;
832    }
833  };
834
835  shop2.cart = {
836		add: function(kind_id, a4, func) {
837
838			shop2.trigger('beforeCartAddItem');
839
840			$.post(
841				'/-/shop2-api/?cmd=cartAddItem', {
842					hash: shop2.apiHash.cartAddItem,
843					ver_id: shop2.verId,
844					kind_id: kind_id,
845					amount: a4
846				},
847				function(d, status) {
848					shop2.fire('afterCartAddItem', func, d, status);
849					shop2.trigger('afterCartAddItem', d, status);
850				},
851				'json'
852			);
853		},
854
855		addMultiple: function(params, func) {
856
857			shop2.trigger('beforeCartAddMultipleItems');
858
859			params = $.extend({
860				hash: shop2.apiHash.cartAddItem,
861				ver_id: shop2.verId
862			}, params);
863
864			$.post('/-/shop2-api/?cmd=cartAddItem', params, function(d, status) {
865
866				shop2.fire('afterCartAddMultipleItems', func, d, status);
867				shop2.trigger('afterCartAddMultipleItems', d, status);
868
869			}, 'json');
870
871		},
872
873		remove: function(obj, func) {
874	
875			shop2.trigger('beforeCartRemoveItem');
876			var hash = shop2.cart.hash();
877			var f = function(d, status) {
878				shop2.fire('afterCartRemoveItem', func, d, status);
879				shop2.trigger('afterCartRemoveItem', d, status);
880			};
881		    
882		    if (hash) {
883				$.post(
884					'/-/x-api/v1/public/?method=cart/removeItem', {
885						hash: hash,
886						position: obj.data('pos')
887					},
888					f
889		        );
890			} else {
891				var kind_id = obj.data('id');
892				kind_id = kind_id.toString().replace(/\"/g, '\\"').replace(/\'/g, '"');
893				kind_id = $.parseJSON(kind_id);
894		
895				$.getJSON(
896					'/-/shop2-api/?cmd=cartRemoveItem', {
897						hash: shop2.apiHash.del,
898						ver_id: shop2.verId,
899						kind_id: kind_id
900					},
901					f
902				);
903			}
904			return false;
905		},
906		
907		removeSetItem: function(position, set_item_pos) {
908			$.post(
909				'/-/x-api/v1/public/?method=cart/removeSetItem', {
910					hash: shop2.cart.hash(),
911	                                position: position,
912					set_item_pos: set_item_pos
913				},
914				function(d, status) {
915					document.location.reload();
916				}
917			);
918	
919			return false;
920		}, /* changed */
921
922		clear: function() {
923
924			shop2.trigger('beforeCartClear');
925			$.get(shop2.uri + '?mode=cart&action=cleanup', function(d, status) {
926				shop2.trigger('afterCartClear', d, status);
927			});
928
929		}, /* changed */
930
931		update: function(form, obj, func) {
932			shop2.trigger('beforeCartUpdate');
933			var data = form.serialize();
934			console.log(data)
935			var hash = shop2.cart.hash();
936			if (hash) {
937	    		$.post(
938	    			'/-/x-api/v1/public/?method=cart/update',
939	    			'hash=' + shop2.cart.hash() +
940	    			'&' + data,
941	    			function(d, status) {
942	    				if (d.result.errstr) {
943	    					shop2.msg(d.result.errstr, $(obj));
944	    				} else {
945	    					shop2.fire('afterCartUpdate', func, d, status);
946	    					shop2.trigger('afterCartUpdate', d, status);
947	    				}
948	    			}
949	    		);
950			} else {
951				$.post(
952					'/-/shop2-api/?cmd=cartUpdate',
953					'ver_id=' + shop2.verId +
954					'&hash=' + shop2.apiHash.up +
955					'&' + data,
956					function(d, status) {
957						shop2.fire('afterCartUpdate', func, d, status);
958						shop2.trigger('afterCartUpdate', d, status);
959					}
960				);
961			}
962			return true;
963		}, /* changed */
964		
965		copy: function(obj, item_pos) {
966			$.post(
967				'/-/x-api/v1/public/?method=cart/copyItem', {
968					hash: shop2.cart.hash(),
969	                                position: item_pos
970				}, function(d, status) {
971					if (d.result.errstr) {
972						shop2.msg(d.result.errstr, $(obj));
973					} else {
974						document.location.reload();
975					}
976				}
977			);
978		}, /* changed */
979
980		addCoupon: function(coupon, func) {
981
982			shop2.trigger('beforeCartAddCoupon');
983
984			$.getJSON(
985				'/-/shop2-api/?cmd=cartAddCoupon', {
986					hash: shop2.apiHash.coupon_add,
987					ver_id: shop2.verId,
988					coupon: coupon
989				},
990				function(d, status) {
991					shop2.fire('afterCartAddCoupon', func, d, status);
992					shop2.trigger('afterCartAddCoupon', d, status);
993				}
994			);
995
996			return false;
997		},
998
999		removeCoupon: function(coupon, func) {
1000
1001			shop2.trigger('beforeCartRemoveCoupon');
1002
1003			$.getJSON(
1004				'/-/shop2-api/?cmd=cartRemoveCoupon', {
1005					hash: shop2.apiHash.coupon_del,
1006					ver_id: shop2.verId,
1007					coupon: coupon
1008				},
1009				function(d, status) {
1010					shop2.fire('afterCartRemoveCoupon', func, d, status);
1011					shop2.trigger('afterCartRemoveCoupon', d, status);
1012				}
1013			);
1014		},
1015		
1016		chooseSetItem: function(kind_id, self, item_pos) {
1017			var productRefs;
1018			$.post(
1019				'/-/x-api/v1/public/?method=cart/getProductSets', {
1020						kind_id: kind_id
1021				}, function(d, status) {
1022					if (d.result.errstr) {
1023						shop2.msg(d.result.errstr, $(self));
1024					} else {
1025						var $html = $(d.result.html);
1026						$(document).off('click', '.shop2-product-set').on('click', '.shop2-product-set', function(e) {
1027							var $this = $(this),
1028							$form = $this.closest('form'),
1029							form = $form.get(0),
1030							adds = $form.find('.additional-cart-params');
1031							var params = {};
1032							for (var i = 0; i < adds.length; i++) {
1033								if (adds[i].value) {
1034									params[adds[i].name] = adds[i].value;
1035								}							
1036							}
1037							shop2.cart.addSetItem(item_pos, form.kind_id.value, form.amount.value, params, $this);
1038							return false;
1039						});
1040
1041						$('html').addClass('stepsOverflow');
1042						$('.site_container').css('z-index', 300);
1043						$('.steps-popup').addClass('active');
1044						
1045						if ($('.steps-popup__body').children().length<1) {
1046							$('.steps-popup__body').html($html);
1047						}
1048
1049						shop2.queue.heights();
1050
1051						try {
1052							productRefs = JSON.parse($html.find('.productRefs').text());
1053						} catch (e) {
1054							productRefs = null;
1055							shop2.msg('Parse error. Product refs is undefined', $(self));
1056						}
1057
1058						if (productRefs) {
1059							shop2.productRefs = $.extend(shop2.productRefs, productRefs);
1060						}
1061					}
1062				}
1063			);
1064		}, /* changed */
1065	
1066		addSetItem: function(item_pos, set_kind_id, amount, params, obj) {
1067			$.post(
1068				'/-/x-api/v1/public/?method=cart/addSetItem', {
1069					hash: shop2.cart.hash(),
1070	                                position: item_pos,
1071					set_kind_id: set_kind_id,
1072					params: params,
1073					amount: amount
1074				}, function(d, status) {
1075					if (d.result.errstr) {
1076						shop2.msg(d.result.errstr, $(obj));
1077					} else {
1078						document.location.reload();
1079					}
1080				}
1081			);
1082		}, /* changed */
1083	
1084		hash: function() {
1085			return $("#cart_hash").val() ? $("#cart_hash").val() : "";
1086		} /* changed */
1087	};
1088
1089  shop2.delivery = {
1090    deligate: false,
1091    ymapsMap: null,
1092    ymapsData: [],
1093    ymapsIconsData: {
1094      'default': '/g/shop2v2/default/images/map-pin.svg',
1095      'spsr': '/g/shop2v2/default/images/map-pin-red.svg',
1096      'dellin': '/g/shop2v2/default/images/map-pin-purple.svg',
1097      'edostavka': '/g/shop2v2/default/images/map-pin-green.svg',
1098      'pickpoint': '/g/shop2v2/default/images/map-pin.svg',
1099      'boxberry': '/g/shop2v2/default/images/map-pin-boxberry.svg',
1100      'delica': '/g/shop2v2/default/images/map-pin.svg',
1101    },
1102    calc: function(attach_id, params, func) {
1103
1104      shop2.trigger('beforeDeliveryCalc');
1105
1106      $.getJSON(
1107        '/-/shop2-api/?cmd=deliveryCalc', {
1108          hash: shop2.apiHash.calc,
1109          ver_id: shop2.verId,
1110          attach_id: attach_id,
1111          params: params
1112        },
1113        function(d, status) {
1114          shop2.fire('afterDeliveryCalc', func, d, status);
1115          shop2.trigger('afterDeliveryCalc', d, status);
1116        }
1117      );
1118    },
1119    YmapsInit: function(service_code) {
1120      var obj = Object.keys(shop2.delivery.ymapsData).length,
1121        localize_text_div = $('.baloon-content-localize'),
1122        localize_text = {
1123          'point': localize_text_div.data('point-text'),
1124          'term': localize_text_div.data('term-text'),
1125          'price': localize_text_div.data('price-text'),
1126          'address': localize_text_div.data('address-text'),
1127          'phone': localize_text_div.data('phone-text'),
1128          'worktime': localize_text_div.data('worktime-text'),
1129          'url': localize_text_div.data('url-text'),
1130          'more': localize_text_div.data('more-text'),
1131          'choose': localize_text_div.data('choose-text'),
1132        };
1133      if (!obj) {
1134        $('.shop2-delivery--item__tab.points').addClass('disabled');
1135        return false;
1136      }
1137      var dadataJson = $.parseJSON($('#dadata').val()),
1138        coordsCenter = [dadataJson.geo_lat, dadataJson.geo_lon],
1139        options = {
1140          id: service_code,
1141          center: coordsCenter,
1142          zoom: 11,
1143        };
1144
1145      ymaps.ready(function() {
1146        shop2.delivery.ymapsMap = new ymaps.Map(options.id, {
1147          center: options.center,
1148          zoom: options.zoom,
1149          controls: ["zoomControl"]
1150        });
1151        var MyBalloonContentLayoutClass = ymaps.templateLayoutFactory.createClass(
1152          '<div class="delivery-baloon-content">' +
1153          '<h3>$[properties.address]</h3>' +
1154          '<div class="buttons"><button type="button" class="shop2-btn" id="balloon-select">' + localize_text.choose + '</button>[if properties.site]<a target="_blank" class="shop2-btn" href="$[properties.site]">' + localize_text.more + '</a>[endif]</div>' +
1155          '<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>' +
1156          '[if properties.phone]<div class="phone"><span>' + localize_text.phone + ':</span>$[properties.phone]</div>[endif]' +
1157          '[if properties.worktime]<div class="worktime"><span>' + localize_text.worktime + ':</span>$[properties.worktime]</div>[endif]' +
1158          '[if properties.desc]<div class="desc"><span>' + localize_text.url + ':</span>$[properties.desc]</div>[endif]' +
1159          '<form data-attach_id="$[properties.attach_id]"><input type="hidden" name="delivery_type" value="$[properties.delivery_type]">
1159<input class="point-address" type="hidden" name="$[properties.attach_id][0]" 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>' +
1160          '</div>', {
1161            build: function() {
1162              MyBalloonContentLayoutClass.superclass.build.call(this);
1163              $('#balloon-select').bind('click', this.onCounterClick);
1164            },
1165            clear: function() {
1166              $('#balloon-select').unbind('click', this.onCounterClick);
1167              MyBalloonContentLayoutClass.superclass.clear.call(this);
1168            },
1169            onCounterClick: function(e) {
1170              e.preventDefault();
1171              var balloonContent = $(this).parents('.delivery-baloon-content:first'),
1172                form = balloonContent.find('form'),
1173                pointName = balloonContent.find('h3').text(),
1174                pointCostInp = balloonContent.find('label.cost input:checked'),
1175                pointCost = pointCostInp.parent().data('cost'),
1176                pointTerm = balloonContent.find('.term').text(),
1177                attach_id = form.data("attach_id"),
1178                deliveryBlock = $('#shop2-order-delivery'),
1179                options = deliveryBlock.find('.option-label'),
1180                groups = deliveryBlock.find('.option-type'),
1181                details = deliveryBlock.find('.option-details'),
1182                pointTab = deliveryBlock.find('.shop2-delivery--item__tab.points'),
1183                pointFields = $(shop2.delivery.ymapsMap.container._parentElement).next(),
1184                pointAddress = form.find('input.point-address').val(),
1185                option = $(shop2.delivery.ymapsMap.container._parentElement).parents('.option-details:first');
1186
1187              $("#delivery_id_deligate").val(attach_id);
1188              form.find('input.tariff').val(pointCostInp.val());
1189              pointFields.find('.fields').html(form.html());
1190              pointFields.find('.point-name').html(pointName);
1191              pointFields.find('.point-cost').html(pointCost);
1192              pointFields.find('.point-term').html(pointTerm);
1193              pointFields.find('.point-address').html(pointAddress);
1194              option.addClass('selected');
1195              $('html, body').scrollTop(option.parent().offset().top - 60);
1196              //pointFields.show();
1197              shop2.delivery.ymapsMap.balloon.close();
1198            }
1199          }
1200        );
1201
1202        var myCollection = new ymaps.GeoObjectCollection();
1203
1204        $.each(shop2.delivery.ymapsData[service_code], function(key, item) {
1205          var iconPic = shop2.delivery.ymapsIconsData[service_code] || shop2.delivery.ymapsIconsData['default'];
1206          if (item.service_code == service_code) {
1207            myCollection.add(new ymaps.Placemark(
1208              item.coords,
1209              item, {
1210                balloonContentLayout: MyBalloonContentLayoutClass,
1211                iconLayout: 'default#image',
1212                iconImageHref: iconPic,
1213                iconImageSize: [26, 36], // размеры картинки
1214                iconImageOffset: [-13, -36], // смещение картинки
1215                balloonMaxWidth: 530,
1216                balloonPanelMaxMapArea: 'Infinity',
1217                balloonMinHeight: 330,
1218                balloonshadow: false,
1219
1220              }
1221            ));
1222          }
1223        });
1224
1225        shop2.delivery.ymapsMap.geoObjects.add(myCollection);
1226        shop2.delivery.ymapsMap.container.fitToViewport();
1227        shop2.delivery.ymapsMap.behaviors.disable('multiTouch');
1228      });
1229    },
1230    changeDeliveryPoint: function(obj, service_code) {
1231      var $this = $(obj),
1232        option = $this.parents('.option-details:first');
1233
1234      if (shop2.delivery.ymapsMap) {
1235        shop2.delivery.ymapsMap.destroy();
1236        shop2.delivery.ymapsMap = null;
1237      }
1238
1239      option.find('.map-select select option:first').prop('selected', true);
1240      option.find('.map-select select').trigger('refresh');
1241      option.find('.deligate_points_fields .fields').empty();
1242      option.removeClass('selected');
1243      $('html, body').scrollTop(option.parent().offset().top - 60);
1244      shop2.delivery.YmapsInit(service_code);
1245      return false;
1246    },
1247    selectSuggestion: function(value, enter) {
1248      var name = value;
1249      $.ajax({
1250        url: '/-/x-api/v1/public/?method=deligate/suggestAddress',
1251        type: 'POST',
1252        dataType: 'json',
1253        data: JSON.stringify({
1254          query: name,
1255          count: 1
1256        }),
1257        success: function(suggestion) {
1258          if (suggestion.result.suggestions) {
1259            suggestion.result.suggestions[0].data.source = name;
1260          }
1261          if (enter) {
1262            $('#shop2-deligate-calc').trigger('click');
1263          } else {
1264            $("#dadata").val(JSON.stringify(suggestion.result.suggestions[0].data));
1265            $("#address").val(name);
1266            $('#shop2-deligate-calc').trigger('click');
1267          }
1268        }
1269      });
1270    }
1271  };
1272
1273  shop2.compare = {
1274    add: function(kind_id, callback) {
1275      this.action('add', kind_id, callback);
1276    },
1277    remove: function(kind_id, callback) {
1278      this.action('del', kind_id, callback);
1279    },
1280    clear: function(callback) {
1281      this.action('clear', null, callback);
1282    },
1283    action: function(action, kind_id, func) {
1284
1285      var eventName = $.camelCase('Compare-' + action);
1286
1287      shop2.trigger('before' + eventName);
1288
1289      $.post(
1290        '/-/shop2-api/?cmd=compare', {
1291          hash: shop2.apiHash.compare,
1292          ver_id: shop2.verId,
1293          kind_id: kind_id,
1294          action: action
1295        },
1296        function(d, status) {
1297          shop2.fire('after' + eventName, func, d, status);
1298          shop2.trigger('after' + eventName, d, status);
1299        }
1300      );
1301    }
1302  };
1303
1304  shop2.product = {
1305		
1306		setChooseItem: function(kind_id, self) {
1307			var productRefs;
1308			
1309			$.post(
1310				'/-/x-api/v1/public/?method=cart/getProductSets', {
1311					kind_id: kind_id
1312				}, function(d, status) {
1313					if (d.result.errstr) {
1314						shop2.msg(d.result.errstr, self);
1315					} else {
1316						var $html = $(d.result.html);
1317						
1318						$(document).off('click', '.shop2-product-set').on('click', '.shop2-product-set', function(e) {
1319							var $this = $(this),
1320								$form = $this.closest('form'),
1321								form = $form.get(0),
1322								adds = $form.find('.additional-cart-params');
1323							var params = {};
1324							for (var i = 0; i < adds.length; i++) {
1325								if (adds[i].value) {
1326									params[adds[i].name] = adds[i].value;
1327								}
1328							}
1329
1330							shop2.product.setAddItem(kind_id, form.kind_id.value, form.amount.value, params, $this);
1331							return false;
1332						});
1333						
1334						if ($('.steps-popup__body').children().length<1) {
1335							$('.sets_container').append($html);
1336							console.log(12)
1337						};
1338						
1339						var setsWrap = $('.shop2-product.main_product_form'),
1340							kinds_arr = []
1341
1342						$('.shop2-product-set-wrap').find('.shop2-set-item').each(function(){
1343							var kind_id = $(this).find('.set-cart-params').attr('name')
1344							kinds_arr.push(kind_id)
1345						})
1346						
1347						var activeitems = setsWrap.find('#set-items-added .shop2-set-item');
1348						
1349												
1350						activeitems.each(function(e){
1351							var name = $(this).find('.set-cart-params').attr('name');
1352							
1353							$('.shop2-set .product-list .shop2-product-item').each(function(){
1354								var nameItem = $(this).find('.nab').val();
1355								
1356								if ( name == nameItem){
1357									$(this).find('.set-checkbox').addClass('checked');
1358									$(this).addClass('active_prod');
1359								}
1360							});
1361						});
1362						
1363						setsWrap.find('.shop2-product-item').each(function(){
1364							$(this).addClass('qqq')
1365							var button_disabled = $(this).find('.shop2-product-set.shop2-btn').prop('disabled'),
1366								amount = $(this).find('.shop2-product-amount'),
1367								kind_id = $(this).find('input[name="kind_id"]').val(),
1368								image = $(this).find('.product-image img'),
1369								$checkBox;
1370
1371							amount.on('click', function(e){
1372								let target = $(e.target);
1373								let _thisAmount = $(this);
1374								if(target.hasClass('amount-plus')){
1375									let items = $('.product-fast-view-wrap').find('.shop2-set-item');
1376									items.each(function(){
1377										let name = $(this).find('.set-cart-params').attr('name');
1378										if (name == kind_id) {
1379											let plus = $(this).find('.amount-plus');
1380											plus.click();
1381											setTimeout(() => {
1382												_thisAmount.find('input[type=text]').val($(this).find('input[type=text]').val());
1383											}, 0)
1384											
1385										}
1386									});
1387									
1388								} else if(target.hasClass('amount-minus')){
1389									let items = $('.product-fast-view-wrap').find('.shop2-set-item');
1390									items.each(function(){
1391										let name = $(this).find('.set-cart-params').attr('name');
1392										if (name == kind_id) {
1393											let minus = $(this).find('.amount-minus');
1394											minus.click();
1395											setTimeout(() => {
1396												_thisAmount.find('input[type=text]').val($(this).find('input[type=text]').val());
1397											}, 0);
1398										}
1399									});
1400								}
1401							})
1402
1403							$checkBox = $(this).find('.product-top .set-checkbox')
1404							$checkBox.addClass('sd')
1405							console.log(123)
1406							
1407							$checkBox.on('click', function(){
1408								
1409								if(!$(this).hasClass('checked')){
1410									
1411									$(this).addClass('checked')
1412									
1413									$(this).parents('.shop2-product-item').addClass('active_prod')
1414									
1415									$(this).parents('.shop2-product-item').find('.shop2-product-set').trigger('click')
1416									
1417								}
1418								else{
1419									
1420									let kind_id = $(this).parents('.shop2-product-item').find('input[name="kind_id"]').val();
1421									
1422									$(this).removeClass('checked');
1423									
1424									$(this).parents('.shop2-product-item').removeClass('active_prod')
1425									
1426									let items = $('.card-page .shop2-product').find('.shop2-set-item');
1427									
1428									items.each(function(){
1429										let name = $(this).find('.set-cart-params').attr('name');
1430										if (name == kind_id) {
1431											let delButton = $(this).find('.delete');
1432											delButton.click();
1433										}
1434									})
1435								}
1436							});
1437							
1438							
1439						});
1440						
1441						shop2.queue.heights();
1442						
1443						try {
1444							productRefs = JSON.parse($html.find('.productRefs').text());
1445						} catch (e) {
1446							productRefs = null;
1447							shop2.msg('Parse error. Product refs is undefined', $(self));
1448						}
1449
1450						if (productRefs) {
1451							shop2.productRefs = $.extend(shop2.productRefs, productRefs);
1452						}
1453					}
1454				}
1455			);
1456		}, /* changed */
1457
1458		setAddItem: function(kind_id, set_kind_id, amount, params, obj) {
1459			$.post(
1460				'/-/x-api/v1/public/?method=cart/addSetItemToProduct', {
1461					kind_id: kind_id,
1462					set_kind_id: set_kind_id,
1463					params: params,
1464					amount: amount
1465				}, function(d, status) {
1466					if (d.result.errstr) {
1467						shop2.msg(d.result.errstr, obj);
1468					} else {
1469						$("#set-items-added").html(d.result.html);console.log(d.result);
1470						//$("#shop2-set-total").text(d.result.total);
1471						$('.shop2-product .shop2-product-set-wrap').removeClass('empty');
1472						//shop2.msg(window._s3Lang.JS_ADDED, obj);
1473						//document.location.reload();
1474						recount_product_price();
1475					}
1476				}
1477			);
1478		}, /* changed */
1479
1480		setRemoveItem: function(kind_id, position, obj) {
1481			$.post(
1482				"/-/x-api/v1/public/?method=cart/removeSetItemFromProduct", {
1483					kind_id: kind_id,
1484					position: position,
1485				}, function(d, status) {
1486					if (d.result.errstr) {
1487						shop2.msg(d.result.errstr, obj);
1488					} else {
1489						$(obj).closest(".shop2-set-item").remove();
1490						if (!$('.shop2-product .shop2-product-set-wrap .shop2-set-item').size()) {
1491							$('.shop2-product .shop2-product-set-wrap').addClass('empty');
1492						}
1493						//$("#shop2-set-total").text(d.result.total);
1494						$("#set-items-added").html(d.result.html);
1495						// shop2.msg(window._s3Lang.JS_DELETED, $(obj));
1496						recount_product_price();
1497					}
1498				}
1499			);
1500		}, /* changed */
1501		
1502		removeAllSetItems: function(kind_id) {
1503			$.post(
1504				"/-/x-api/v1/public/?method=cart/removeAllSetItems", {
1505					kind_id: kind_id,
1506				}, function(d, status) {
1507					if (d.result.errstr) {
1508						shop2.msg(d.result.errstr, obj);
1509					} else {
1510						$("#set-items-added").empty();
1511						//$("#shop2-set-total").text(d.result.total);
1512						$('.shop2-product .shop2-product-set-wrap').addClass('empty');
1513						// shop2.msg(window._s3Lang.JS_DELETED, $(obj));
1514						recount_product_price();
1515					}
1516				}
1517			);
1518		}, /* changed */
1519
1520		setRecountItem: function(input) {
1521			var kind_id = input.data('parent'),
1522				position = input.data('position'),
1523				amount = Number(input.val());
1524			$.post(
1525				'/-/x-api/v1/public/?method=cart/changeSetItemAmount', {
1526					kind_id: kind_id,
1527					position: position,
1528					amount: amount,
1529				}, function(d, status) {
1530					if (d.result.errstr) {
1531						shop2.msg(d.result.errstr, input);
1532					} else {
1533						$("#set-items-added").html(d.result.html);
1534						//$("#shop2-set-total").text(d.result.total);
1535						$('.shop2-product-item, .shop2-product').attr('data-price', d.result.total.replace(/\s/g, ''));
1536						//shop2.msg(window._s3Lang.JS_CHANGES_APPLIED, input);
1537						recount_product_price();
1538					}
1539				}
1540			);
1541		}, /* changed */
1542		
1543		getProductListItem: function(product_id, kind_id, is_set, func) {
1544			
1545			var url = '/-/shop2-api/?cmd=getProductListItem&hash=' + shop2.apiHash.getProductListItem + '&ver_id=' + shop2.verId;
1546            var data = {
1547            	product_id: product_id,
1548                kind_id: kind_id
1549            };
1550            
1551            if (is_set) {
1552            	data.is_set = 1
1553            }
1554
1555            shop2.trigger('beforeGetProductListItem');
1556
1557            $.post(
1558                url, data,
1559                function(d, status) {
1560                    shop2.fire('afterGetProductListItem', func, d, status);
1561                    shop2.trigger('afterGetProductListItem', d, status);
1562                }
1563            );
1564			
1565		}, /* changed */
1566
1567		checkMetaItemValue: function(meta, key, value) {
1568
1569			var res = meta[key];
1570
1571			if (res == "undefined" || res == null) {
1572				return false;
1573			}
1574
1575			if (res == value) {
1576				return true;
1577			}
1578
1579			if (res instanceof Object) {
1580				for (var i in res) {
1581					if (res[i] == value) {
1582						return true;
1583					}
1584				}
1585			}
1586
1587			return false;
1588
1589		},
1590
1591		getMetaItemValue: function(meta, key) {
1592			var res = meta[key];
1593
1594			if ($.type(res) === 'undefined') {
1595				return false;
1596			}
1597
1598			if ($.type(res) === 'object') {
1599
1600				if ($.type(res.v) !== 'undefined') {
1601					return res.v;
1602				}
1603
1604				if ($.type(res.image_id) !== 'undefined') {
1605					return res.image_id;
1606				}
1607
1608			}
1609
1610			return res;
1611		},
1612
1613		findKindId: function(product_id, kinds, paramName, paramValue, meta, keys) {
1614			var i;
1615			var len;
1616			var d;
1617			var kind;
1618			var matches;
1619			var lastMatches = 0;
1620			var refs = $.extend(true, {}, shop2.productRefs[product_id]);
1621
1622			if (keys) {
1623				$.each(refs, function(key) {
1624					if (!keys[key]) {
1625						delete refs[key];
1626					}
1627				});
1628			}
1629
1630			if (kinds.length == 1) {
1631				return kinds[0];
1632			}
1633
1634			if ($.type(meta) !== 'object') {
1635				meta = $.parseJSON(meta);
1636			}
1637
1638			for (i = 0, len = kinds.length; i < len; i += 1) {
1639				d = Number(kinds[i]);
1640				matches = 0;
1641
1642				$.each(refs, function(p, ref) {
1643
1644					$.each(ref, function(v) {
1645
1646						if (p == paramName) {
1647
1648							if (v == paramValue) {
1649								matches += 1;
1650							}
1651
1652						} else {
1653
1654							if (String(refs[p][v]).indexOf(d) === -1) {
1655								return;
1656							}
1657
1658							matches += 1;
1659
1660							if (meta && shop2.product.checkMetaItemValue(meta, p, v)) {
1661								matches += 1;
1662							}
1663
1664						}
1665
1666					});
1667
1668				});
1669
1670				if (matches > lastMatches) {
1671					kind = d;
1672					lastMatches = matches;
1673				}
1674
1675			}
1676
1677			return kind;
1678		},
1679
1680		getNodeData: function(node, key, decode) {
1681			var data = false;
1682
1683			if (node.tagName == 'SELECT') {
1684				data = $(node.options[node.selectedIndex]).data(key);
1685			} else if (node.nodeType == 1) {
1686				data = $(node).data(key);
1687			}
1688
1689			if (decode) {
1690				data = this.decodeFieldData(data);
1691			}
1692
1693			return data;
1694		},
1695
1696		decodeFieldData: function(data) {
1697
1698			if ($.type(data) !== 'string') {
1699				return [data];
1700			}
1701
1702			data = data.split(',');
1703
1704			return $.map(data, function(n) {
1705				return $.trim(n);
1706			});
1707
1708		},
1709
1710		hasKindId: function(data, kinds) {
1711			var i, len;
1712			if (data) {
1713				for (i = 0, len = kinds.length; i < len; i += 1) {
1714					if (data.indexOf(kinds[i]) !== -1) {
1715						return true;
1716					}
1717				}
1718			}
1719			return false;
1720		}
1721	};
1722
1723  shop2.options = {
1724    amountDefaultValue: 1,
1725    amountDefaultInc: 1,
1726    amountType: 'int',
1727    msgTime: 3000,
1728    printCSS: '/g/shop2v2/default/css/print.less.css'
1729  };
1730
1731  //* client-order-cancelling *//
1732  shop2.orderCancelling = {
1733    alert: function() {
1734      var linkButton = $('.order-cancelling'),
1735        attrToLinkOrder = linkButton.data('href'),
1736        attrLinkTitle = linkButton.data('cancellingTitle'),
1737        attrLinkButtonTitle = linkButton.data('cancellingButtonTitle'),
1738        attrLinkButtonClose = linkButton.data('cancellingClose'),
1739
1740        html = '<div class="order-cancel-title">' + attrLinkTitle + '</div>' +
1741        '<div class="order-cancel-buttons">' +
1742        '<a class="shop2-btn" href="' + attrToLinkOrder + '">' + attrLinkButtonTitle + '</a>' +
1743        '<a class="shop2-alert-close" onclick="shop2.alert.hide(); return false;" href="#">' + attrLinkButtonClose + '</a>' +
1744        '</div>';
1745
1746      shop2.alert(html, '', 'shop2-alert--warning order-cancel');
1747    }
1748  };
1749  $(document).on('click', '.order-cancelling', function(e) {
1750    e.preventDefault();
1751    shop2.orderCancelling.alert();
1752  });
1753
1754  //* client-order-repeat *//
1755  shop2.orderRepeat = {
1756    alert: function($this) {
1757      var linkButton = $this.filter('.order-repeat'),
1758        attrToLinkOrder = linkButton.data('href'),
1759        attrLinkTitle = linkButton.data('repeatTitle'),
1760        attrLinkButtonTitle = linkButton.data('repeatButtonTitle'),
1761        attrLinkButtonClose = linkButton.data('repeatClose'),
1762
1763        html = '<div class="order-repeat-title">' + attrLinkTitle + '?</div>' +
1764        '<div class="order-repeat-buttons">' +
1765        '<a class="shop2-btn" href="' + attrToLinkOrder + '">' + attrLinkButtonTitle + '</a>' +
1766        //'<a class="shop2-btn" href="#" onclick="location.href=\'' + attrToLinkOrder + '\'">'+ attrLinkButtonTitle +'</a>' +
1767        '<a class="shop2-alert-close" onclick="shop2.alert.hide(); return false;" href="#">' + attrLinkButtonClose + '</a>' +
1768        '</div>';
1769      shop2.alert(html, 'Закрыть', 'shop2-alert--warning order-cancel');
1770    }
1771  };
1772  $(document).on('click', '.order-repeat', function(e) {
1773    e.preventDefault();
1774    shop2.orderRepeat.alert($(this));
1775  });
1776  
1777  //* client-order-payment-change *//
1778  shop2.paymentChange = {
1779      alert: function($this) {
1780          var linkButton = $this.filter('.order-payment-change'),
1781              url = linkButton.data('href'),
1782              title = linkButton.data('title'),
1783              button_title = linkButton.data('button-title'),
1784              button_close = linkButton.data('close');
1785
1786          $.ajax({
1787              url: url,
1788              type: 'POST',
1789              dataType: 'json',
1790              data: {},
1791              success: function(res) {
1792                  var html = '<div class="payment-change-title">' + title + '</div><div class="error"></div>' + res.data +
1793                      '<div class="payment-change-buttons">' +
1794                      '<a class="shop2-btn" onclick="shop2.paymentChange.save(\'' + url.replace('act=list', 'act=save') + '\');" href="#">' + button_title + '</a>' +
1795                      '<a class="shop2-alert-close" onclick="shop2.alert.hide(); return false;" href="#">' + button_close + '</a>' +
1796                      '</div>';
1797                  shop2.alert(html, button_close, 'shop2-alert--warning order-cancel');
1798              }
1799          });
1800      },
1801      save: function (url) {
1802          var form_data = $('#shop2-alert-body .shop2-payment-options').serialize();
1803          $.ajax({
1804              url: url + '&' + form_data,
1805              type: 'POST',
1806              dataType: 'json',
1807              data: {},
1808              success: function(res) {
1809                  if (res.data === "OK") {
1810                      document.location.reload();
1811                  } else {
1812                      $('#shop2-alert-body .error').html(res.data);
1813                  }
1814              }
1815          });
1816
1817          return false;
1818      }
1819  };
1820
1821  $(document).on('click', '.order-payment-change', function(e) {
1822    e.preventDefault();
1823    shop2.paymentChange.alert($(this));
1824  });
1825
1826  shop2.msg = function(text, obj) {
1827    var selector = '#shop2-msg',
1828      msg = $(selector),
1829      offset = obj.offset(),
1830      width = obj.outerWidth(true),
1831      height = obj.outerHeight(true);
1832
1833    if (!msg.get(0)) {
1834      msg = $('<div id="shop2-msg">');
1835      $(document.body).append(msg);
1836      msg = $(selector);
1837    }
1838
1839    msg.html(text).show();
1840
1841    var msgWidth = msg.outerWidth();
1842    var left = offset.left + width;
1843    var top = offset.top + height;
1844
1845    if (left + msgWidth > $(window).width()) {
1846      left = offset.left - msgWidth;
1847    }
1848
1849    msg.css({
1850      left: left,
1851      top: top
1852    });
1853
1854    $.s3throttle('msg', function() {
1855      msg.hide();
1856    }, shop2.options.msgTime);
1857
1858  };
1859
1860  shop2.queue = {
1861
1862    cookiesDisabled: function() {
1863      if (navigator && navigator.cookieEnabled == false) {
1864        $('.shop2-cookies-disabled')
1865          .html('<p>Внимание! Для корректной работы у Вас в браузере должна быть включена поддержка cookie. В случае если по каким-либо техническим причинам передача и хранение cookie у Вас не поддерживается оформление заказа невозможно.</p>')
1866          .removeClass('hide');
1867      }
1868    },
1869
1870    cartState: function() {
1871
1872      try {
1873        window.sessionStorage;
1874      } catch (e) {
1875        return;
1876      }
1877
1878      if (!window.chrome || !sessionStorage || !shop2.my.save_cart_state) {
1879        return;
1880      }
1881
1882      if (!readCookie('s3s2_cart')) {
1883        sessionStorage.removeItem('cart-reload');
1884        sessionStorage.removeItem('cart-state');
1885      }
1886
1887      function getHTML() {
1888        return $('<div>').append($('#shop2-cart-preview').clone()).html();
1889      }
1890
1891      function setHTML(html) {
1892        if (html) {
1893          $('#shop2-cart-preview').replaceWith(html);
1894        }
1895      }
1896
1897      if (sessionStorage.getItem('cart-reload') == 1) {
1898        sessionStorage.removeItem('cart-reload');
1899        sessionStorage.setItem('cart-state', getHTML());
1900      }
1901
1902      shop2.on('afterCartAddItem', function(res, status) {
1903        var html = res.data;
1904        if (status != 'success') {
1905          html = '';
1906        }
1907        sessionStorage.setItem('cart-state', html);
1908      });
1909
1910      shop2.on('afterCartRemoveItem, afterCartUpdate', function() {
1911        sessionStorage.setItem('cart-reload', 1);
1912      });
1913
1914      $(window).on('pageshow', function() {
1915        setHTML(sessionStorage.getItem('cart-state'));
1916      });
1917
1918    },
1919
1920    keys: function() {
1921
1922      $(document).keyFilter('input.shop2-input-int');
1923
1924      $(document).keyFilter('input.shop2-input-float', {
1925        type: 'float'
1926      });
1927
1928    },
1929
1930    heights: function() {
1931
1932      $('.product-list-thumbs').each(function() {
1933        var $this = $(this);
1934
1935        $this.find('.product-item-thumb').eachRow(function(group) {
1936          var heights;
1937          var names = group.find('.product-name');
1938          var nHeights;
1939
1940          names.css('min-height', 0);
1941          nHeights = names.getHeights();
1942          names.css('min-height', nHeights.max);
1943
1944          var $sp = group.find('.product-amount');
1945
1946          if ($sp.length) {
1947            $sp.css('margin-top', 0);
1948            heights = group.getHeights();
1949            group.each(function(i) {
1950              $(this).find('.product-amount').css('margin-top', heights.max - heights.values[i]);
1951            });
1952          } else {
1953            group.each(function() {
1954              var $this = $(this);
1955              var $sp = $this.find('.shop2-product-actions');
1956              if (!$sp.length) {
1957                $sp = $this.find('.product-bot');
1958              }
1959              var paddingTop = $sp.data('padding-top');
1960              if ($.type(paddingTop) === 'undefined') {
1961                paddingTop = parseInt($this.css('padding-top'));
1962                $sp.data('padding-top', paddingTop);
1963              }
1964              $sp.css('padding-top', paddingTop);
1965            });
1966            heights = group.getHeights();
1967            group.each(function(i) {
1968              var $this = $(this);
1969              var $sp = $this.find('.shop2-product-actions');
1970              if (!$sp.length) {
1971                $sp = $this.find('.product-bot');
1972              }
1973              var paddingTop = $sp.data('padding-top');
1974              $sp.css('padding-top', heights.max - heights.values[i] + paddingTop);
1975            });
1976          }
1977        });
1978      });
1979
1980    },
1981
1982    resize: function() {
1983
1984      $(window).resize(function() {
1985        shop2.queue.heights();
1986      });
1987
1988    },
1989
1990    product: function() {
1991
1992      shop2.product._reload = function(node) {
1993
1994        var $node = $(node);
1995        var kinds = shop2.product.getNodeData(node, 'kinds', true);
1996        var paramName = shop2.product.getNodeData(node, 'name');
1997        var paramValue = shop2.product.getNodeData(node, 'value');
1998        var $form = $node.closest('form');
1999        var form = $form.get(0);
2000        var meta;
2001        var kind_id;
2002        var product_id;
2003        var keys = {};
2004
2005        if (kinds && $.type(paramName) !== 'undefined' && $.type(paramValue) !== 'undefined' && form) {
2006
2007          meta = $form.find('input[name=meta]').val();
2008
2009          product_id = $form.find('input[name=product_id]').val();
2010
2011          $form.find('[name=submit]').prop('disabled', true);
2012
2013          $form.find('select.shop2-cf>option, li.shop2-cf, li.shop2-color-ext-selected, ul.shop2-color-ext-list>li').each(function() {
2014            var name = $(this).data('name');
2015            if (name) {
2016              keys[name] = true;
2017            }
2018          });
2019
2020          kind_id = shop2.product.findKindId(product_id, kinds, paramName, paramValue, meta, keys);
2021
2022          if (shop2.mode == 'product') {
2023
2024            if (shop2.uri) {
2025              document.location = shop2.uri + '/product/' + kind_id;
2026            } else {
2027              document.location = document.location.href.replace(/\/product\/.+/, '/product/' + kind_id);
2028            }
2029
2030          } else {
2031
2032            shop2.product.getProductListItem(product_id, kind_id, function(d, status) {
2033              var cont, newCont, body;
2034              if (status === 'success') {
2035              
2036              	shop2.trigger('afterProductReloaded');
2037
2038                cont = $node.closest('.shop2-product-item');
2039                cont.hide();
2040
2041                body = $.trim(d.data.body);
2042                newCont = $(body).insertBefore(cont);
2043
2044                cont.remove();
2045
2046                shop2.queue.heights();
2047              }
2048
2049            });
2050
2051          }
2052        }
2053
2054      };
2055
2056      $.on('select.shop2-cf', {
2057        change: function() {
2058          shop2.product._reload(this);
2059        }
2060      });
2061
2062      $.on('li.shop2-cf:not(.active-color, .active-texture)', {
2063        click: function() {
2064          shop2.product._reload(this);
2065        }
2066      });
2067
2068      $.on('span.shop2-path-show-folders', {
2069        click: function(e) {
2070          e.preventDefault();
2071          $(this).next().show();
2072          $(this).hide();
2073        }
2074      });
2075
2076    },
2077
2078    addToCart: function() {
2079
2080
2081      $(document).on('click', '.shop2-product-btn', function(e) {
2082
2083        var $this = $(this),
2084          $form = $this.closest('form'),
2085          form = $form.get(0),
2086          adds = $form.find('.additional-cart-params'),
2087          len = adds.length,
2088          i, el,
2089          a4 = form.amount.value,
2090          kind_id = form.kind_id.value;
2091
2092        e.preventDefault();
2093
2094        if (len) {
2095          a4 = {
2096            amount: a4
2097          };
2098
2099          for (i = 0; i < len; i += 1) {
2100            el = adds[i];
2101            if (el.value) {
2102              a4[el.name] = el.value;
2103            }
2104          }
2105        }
2106
2107        shop2.cart.add(kind_id, a4, function(d) {
2108
2109          $('#shop2-cart-preview').replaceWith(d.data);
2110
2111          if (d.errstr) {
2112            shop2.msg(d.errstr, $this);
2113          } else {
2114            var $text = window._s3Lang.JS_SHOP2_ADD_CART_WITH_LINK;
2115            // window._s3Lang.JS_ADDED - Добавлено
2116            shop2.msg($text.replace('%s', shop2.uri + '/cart'), $this);
2117          }
2118
2119          if (d.panel) {
2120            $('#shop2-panel').replaceWith(d.panel);
2121          }
2122        });
2123
2124      });
2125
2126    },
2127
2128    amount: function() {
2129
2130      var $document = $(document);
2131
2132      function validate(input) {
2133        var kind = input.data('kind'),
2134          max = input.data('max'),
2135          val = Number(input.val()),
2136          amount = 0,
2137          available;
2138
2139        if (kind && max > 0) {
2140          $('input[data-kind=' + kind + ']').each(function() {
2141            amount += Number(this.value);
2142          });
2143
2144          if (amount > max) {
2145            available = max - amount + val;
2146            input.val(available);
2147            shop2.msg(_s3Lang.JS_AVAILABLE_ONLY + ' ' + available, input);
2148          }
2149        }
2150      }
2151
2152      $document.on('click', '.amount-minus', function() {
2153        var $this = $(this),
2154          text = $this.siblings('input:text'),
2155          value = text.getVal();
2156
2157        if (value) {
2158          value = value[0];
2159        }
2160        value -= shop2.options.amountDefaultInc;
2161        value = value.toFixed(5) - 0;
2162
2163        if (value <= shop2.options.amountDefaultValue) {
2164          value = shop2.options.amountDefaultValue;
2165        }
2166
2167        text.val(value);
2168        text.trigger('keyup');
2169      });
2170
2171      $document.on('click', '.amount-plus', function() {
2172
2173        var $this = $(this),
2174          text = $this.siblings('input:text'),
2175          value = text.getVal();
2176
2177        if (value) {
2178          value = value[0];
2179        }
2180
2181        value += shop2.options.amountDefaultInc;
2182        value = value.toFixed(5) - 0;
2183
2184        text.val(value);
2185        text.trigger('keyup');
2186      });
2187
2188      $document.on('keyup', '.shop2-product-amount input:text', function() {
2189        var $this = $(this);
2190        validate($this);
2191        if ($this.hasClass("setAddedItems")) {
2192			shop2.product.setRecountItem($this);
2193        }
2194        
2195      });
2196
2197      $document.keyFilter('.shop2-product-amount input:text', {
2198        type: shop2.options.amountType
2199      });
2200      
2201      $(document).on('change', '.shop2-product-amount input[name="amount"]', function(){
2202	      var thisInput = $(this);
2203	      
2204	      if (!parseFloat(thisInput.val())) {
2205	        thisInput.val(shop2.options.amountDefaultValue);
2206	      }
2207	    });
2208    },
2209
2210    discounts: function() {
2211
2212      $(document).on('click', '.shop2-product-actions dt', function(e) {
2213        var $this = $(this),
2214          win = $this.next(),
2215          left = $this.position().left;
2216
2217        e.stopPropagation();
2218
2219        if (win.is(':hidden')) {
2220          $('.shop2-product-actions dd').hide();
2221          win.show();
2222          win.css('left', left);
2223        } else {
2224          win.hide();
2225        }
2226
2227      });
2228
2229      $(document).on('click', '.close-desc-action', function(e) {
2230        var $this = $(this),
2231          win = $this.closest('dd');
2232
2233        e.stopPropagation();
2234
2235        win.hide();
2236      });
2237
2238      $(document).on('click', function() {
2239        $('.shop2-product-actions dd').hide();
2240      });
2241
2242    },
2243
2244    question: function() {
2245      var cls = '.price-old.question, .shop2-cart-total .question';
2246
2247      $(document).on('mouseenter', cls, function() {
2248        var $this = $(this),
2249          win = $this.next().show(),
2250          position = $this.position(),
2251          height = win.outerHeight(true);
2252
2253        win.css({
2254          top: position.top - height - 5,
2255          left: position.left
2256        });
2257
2258      }).on('mouseleave', cls, function() {
2259
2260        var $this = $(this),
2261          win = $this.next();
2262
2263        win.hide();
2264
2265      });
2266
2267    },
2268
2269    tabs: function() {
2270
2271      var tabs = $('.shop2-product-tabs li'),
2272        btns = tabs.find('a'),
2273        texts = $('.shop2-product-desc > div');
2274
2275      btns.on('click', function(e) {
2276        var $this = $(this),
2277          href = $this.attr('href');
2278
2279        e.preventDefault();
2280
2281        tabs.removeClass('active-tab');
2282        $this.parent().addClass('active-tab');
2283
2284        texts.removeClass('active-area');
2285        $(href).addClass('active-area');
2286      });
2287
2288
2289    },
2290
2291    filter: function() {
2292
2293      var wrap = $('.shop2-filter'),
2294        result = $('.result');
2295
2296      shop2.filter.init();
2297
2298      shop2.on('afterGetSearchMatches', function(d, status) {
2299
2300        if (d.data.total_found === 0) {
2301
2302          result.addClass('no-result');
2303        } else {
2304          result.removeClass('no-result');
2305        }
2306
2307        if (shop2.facets.enabled) {
2308          shop2.facets.set('filter');
2309        }
2310
2311        $('#filter-result').html(d.data.total_found);
2312
2313        result.removeClass('hide');
2314      });
2315
2316      wrap.find('.param-val').on('click', function(e) {
2317        var $this = $(this),
2318          name = $this.data('name'),
2319          value = $this.data('value');
2320
2321        e.preventDefault();
2322
2323        $this.toggleClass('active-val');
2324        shop2.filter.toggle(name, value);
2325        shop2.filter.count();
2326      });
2327
2328      wrap.find('select').on('change', function() {
2329        var $this = $(this),
2330          name = this.name,
2331          value = $this.val();
2332
2333        shop2.filter.add(name, value);
2334        shop2.filter.count();
2335      });
2336
2337      wrap.find('input:text').keyup(function() {
2338        var $this = $(this),
2339          name = $this.attr('name');
2340
2341        $.s3throttle('filter: ' + name, function() {
2342          var value = $this.val();
2343
2344          shop2.filter.add(name, value);
2345          shop2.filter.count();
2346        }, 500);
2347      });
2348
2349      wrap.find('.shop2-filter-go').on('click', function(e) {
2350        e.preventDefault();
2351        shop2.filter.go();
2352      });
2353
2354    },
2355
2356    sort: function() {
2357      var wrap = $('.sorting');
2358
2359      wrap.find('.sort-param').on('click', function(e) {
2360        var $this = $(this),
2361          name = $this.data('name');
2362
2363        e.preventDefault();
2364        shop2.filter.sort(name);
2365        shop2.filter.go();
2366      });
2367
2368      wrap.find('.sort-reset').on('click', function(e) {
2369        e.preventDefault();
2370        shop2.filter.remove('s[sort_by]');
2371        shop2.filter.go();
2372      });
2373
2374    },
2375
2376    views: function() {
2377      $('.view-shop a').on('click', function(e) {
2378        var $this = $(this),
2379          value = $this.data('value');
2380
2381        e.preventDefault();
2382        shop2.filter.remove('view');
2383        shop2.filter.add('view', value);
2384        shop2.filter.go();
2385
2386      });
2387    },
2388
2389    toggle: function() {
2390
2391      function tgl(el, wrap, cls, cookie) {
2392        $(document).on('click', wrap + ' ' + el, function(e) {
2393          var w = $(wrap);
2394          e.preventDefault();
2395          if (w.hasClass(cls)) {
2396            w.removeClass(cls);
2397            eraseCookie(cookie);
2398          } else {
2399            w.addClass(cls);
2400            createCookie(cookie, 1, 7);
2401          }
2402        });
2403      }
2404
2405      tgl('.block-title', '.cart-preview', 'opened', 'cart_opened');
2406      tgl('.block-title', '.search-form', 'opened', 'search_opened');
2407      tgl('.block-title', '.login-form ', 'opened', 'login_opened');
2408
2409    },
2410
2411    search: function() {
2412      var custom = $('#shop2_search_custom_fields'),
2413        global = $('#shop2_search_global_fields');
2414
2415      shop2.on('afterGetFolderCustomFields', function(d, status) {
2416        custom.html(d.data);
2417        global.find('input, select').prop('disabled', true);
2418        global.hide();
2419      });
2420
2421      $('#s\\[folder_id\\]').on('change', function() {
2422        var $this = $(this),
2423          folder_id = $this.val();
2424
2425        if (folder_id) {
2426
2427          shop2.search.getParams(folder_id);
2428
2429        } else {
2430
2431          custom.html('');
2432
2433          global.find('input, select').prop('disabled', false);
2434
2435          global.show();
2436        }
2437      }).trigger('change');
2438
2439      if (shop2.facets.enabled) {
2440        shop2.facets.searchSetup();
2441      }
2442    },
2443
2444    cart: function() {
2445
2446      var updateBtn = $('.shop2-cart-update'),
2447        cartTable = $('.shop2-cart-product'),
2448        form = $('#shop2-cart');
2449
2450      shop2.on('afterCartRemoveItem, afterCartUpdate', function() {
2451        document.location.reload();
2452      });
2453
2454      function updateBtnShow() {
2455        updateBtn.show();
2456      }
2457
2458      var eventName;
2459
2460      ['keypress', 'keyup', 'keydown'].forEach(function(item) {
2461        if ('on' + item in document) {
2462          eventName = item;
2463          return false;
2464        }
2465      });
2466
2467      cartTable.find('input:text').on(eventName, function(e) {
2468        if (e.keyCode == 13) {
2469          shop2.cart.update(form, e.target);
2470        } else {
2471          updateBtnShow();
2472        }
2473      });
2474
2475      $(document).on('change, click', 'select.param-value, li.param-value:not(.shop2-color-ext-selected)', function() {
2476        updateBtnShow();
2477      });
2478
2479      cartTable.find('.amount-minus, .amount-plus').on('click', updateBtnShow);
2480
2481      updateBtn.on('click', function(e) {
2482        e.preventDefault();
2483        shop2.cart.update(form, e.target);
2484        return false;
2485      });
2486
2487
2488      $('.cart-delete a').on('click', function(e) {
2489        var $this = $(this),
2490          id = $this.data('id');
2491
2492        e.preventDefault();
2493
2494        shop2.cart.remove($this);
2495
2496      });
2497
2498      $('#shop2-deligate-calc').on('click', function(e) {
2499        var data = {},
2500          delivery = $('#shop2-order-delivery'),
2501          tabs = delivery.find('.shop2-delivery--item__tab');
2502
2503        $('#shop2-perfect-form').find('input, textearea, select').each(function() {
2504          var $this = $(this);
2505          if (this.tagName === 'INPUT' && this.type === 'checkbox') {
2506            if (this.checked) {
2507              data[this.name] = 'on';
2508            }
2509          } else {
2510            data[this.name] = $(this).val();
2511          }
2512        });
2513
2514        e.preventDefault();
2515        tabs.removeClass('active-tab');
2516        tabs.removeClass('point');
2517        delivery.addClass('preloader');
2518        $('#shop2-delivery-wait').show();
2519        $('input#address').blur();
2520        $('#shop2-deligate-calc').hide();
2521        //$('#form_g-anketa .text-right button').prop('disabled', true).addClass('g-button--disabled');
2522
2523        $.ajax({
2524          url: '/-/x-api/v1/public/?method=deligate/calc&param[get_vars][]',
2525          type: 'post',
2526          dataType: 'json',
2527          data: data,
2528          success: function(result) {
2529            delivery.removeClass('preloader');
2530            $('#shop2-delivery-wait').hide();
2531            $('#shop2-order-delivery').html(result.result.html);
2532            $('#shop2-order-delivery').append('<div class="preloader"><div class="spinner"></div></div>');
2533            $('#shop2-order-delivery').find('.delivery-items').each(function() {
2534              var $this = $(this);
2535              if ($.trim($this.text()) == "") {
2536                $this.parents('.shop2-delivery--item__tab:first').addClass('disabled');
2537              }
2538            });
2539            if (result.result.error) {
2540              shop2.alert(result.result.error);
2541            } else {
2542
2543              var dadataJson = $.parseJSON($('#dadata').val()),
2544                coordsCenter = [dadataJson.geo_lat, dadataJson.geo_lon];
2545
2546              shop2.queue.edost2();
2547              $('#shop2-ems-calc, #shop2-edost-calc').on('click', function(e) {
2548                var $this = $(this);
2549                var attach_id = $this.data('attach-id');
2550                var to = $('select[name=' + attach_id + '\\[to\\]]');
2551                var zip = $('input[name=' + attach_id + '\\[zip\\]]');
2552                var order_value = $('input[name=' + attach_id + '\\[order_value\\]]');
2553
2554                if (to.length == 0) {
2555                  to = $('#shop2-edost2-to');
2556                }
2557
2558                e.preventDefault();
2559
2560                to = to.get(0) ? to.val() : '';
2561                zip = zip.get(0) ? zip.val() : '';
2562                order_value = order_value.prop("checked") ? 'on' : '';
2563
2564                shop2.delivery.calc(attach_id, 'to=' + to + '&zip=' + zip + '&order_value=' + order_value, function(d) {
2565                  if (!d.data && d.errstr) {
2566                    shop2.alert(d.errstr);
2567                    $('#delivery-' + attach_id + '-cost').html(0);
2568                  } else {
2569                    $('#delivery-' + attach_id + '-cost').html(d.data.cost);
2570
2571                    if (d.data.html) {
2572                      $('#delivery-' + attach_id + '-html').html(d.data.html);
2573                      shop2.queue.edost();
2574                    }
2575                  }
2576                });
2577
2578              });
2579              $('#shop2-deligate-calc').hide();
2580            }
2581          }
2582        });
2583      });
2584    },
2585
2586    coupon: function() {
2587
2588      shop2.on('afterCartAddCoupon, afterCartRemoveCoupon', function() {
2589        document.location.reload();
2590      });
2591
2592      $('.coupon-btn').on('click', function(e) {
2593        var coupon = $('#coupon'),
2594          code = coupon.val();
2595
2596        e.preventDefault();
2597
2598        if (code) {
2599
2600          shop2.cart.addCoupon(code);
2601
2602        }
2603
2604      });
2605
2606
2607      $('.coupon-delete').on('click', function(e) {
2608        var $this = $(this),
2609          code = $this.data('code');
2610
2611        e.preventDefault();
2612
2613        if (code) {
2614
2615          shop2.cart.removeCoupon(code);
2616
2617        }
2618
2619      });
2620
2621    },
2622
2623    delivery: function() {
2624      $('#shop2-order-delivery').find('.delivery-items').each(function() {
2625        var $this = $(this);
2626        if ($.trim($this.text()) == "") {
2627          $this.parents('.shop2-delivery--item__tab:first').addClass('disabled');
2628        }
2629      });
2630      $(document).on('change', '.map-select select', function() {
2631        var $this = $(this),
2632          index = $this.find('option:selected').index(),
2633          pos = $this.find('option:selected').text(),
2634          id = $this.val();
2635
2636        if (index == 0) {
2637          shop2.delivery.ymapsMap.balloon.close();
2638          return;
2639        }
2640
2641        var it = shop2.delivery.ymapsMap.geoObjects.getIterator(),
2642          ss;
2643        while (ss = it.getNext()) {
2644          for (var i = 0, len = ss.getLength(); i < len; i++) {
2645            var placemark = ss.get(i);
2646            if (placemark.properties.get('id') === id) {
2647              if (placemark.balloon.isOpen()) {
2648                placemark.balloon.close();
2649              } else {
2650                placemark.balloon.open();
2651              }
2652              return;
2653            }
2654          }
2655        }
2656
2657      });
2658      $(document).on('click', '.option-label', function(e) {
2659        var options = $(document).find('.option-label'),
2660          groups = $(document).find('.option-type'),
2661          details = options.next();
2662
2663        var $this = $(this),
2664          index = $this.parent().index();
2665
2666        if (e.target.nodeName != 'INPUT' && shop2.delivery.deligate) {
2667          e.preventDefault();
2668        }
2669
2670        if (shop2.delivery.ymapsMap) {
2671          shop2.delivery.ymapsMap.destroy();
2672          shop2.delivery.ymapsMap = null;
2673        }
2674
2675        groups.removeClass('active-type');
2676        $this.parent().addClass('active-type');
2677        details.find('input, textarea, select').prop('disabled', true);
2678        $this.next().find('input, textarea, select').prop('disabled', false);
2679        if (shop2.delivery.deligate) {
2680          $this.find('input:first').prop('checked', true);
2681        }
2682
2683        if ($this.hasClass('ymap')) {
2684          shop2.delivery.YmapsInit($this.data('service-code'));
2685        }
2686
2687      });
2688      $(document).on('click', '.shop2-delivery--item__tab .tab-label', function() {
2689        var groups = $(document).find('.shop2-delivery--item__tab'),
2690          $this = $(this),
2691          parent = $this.parents('.shop2-delivery--item__tab:first'),
2692          index = parent.index();
2693
2694        if (parent.hasClass('disabled')) return false;
2695        if (parent.hasClass('active-tab')) {
2696          parent.removeClass('active-tab');
2697          return;
2698        }
2699
2700        groups.removeClass('active-tab').eq(index).addClass('active-tab');
2701        
2702        var activeTabOffsetTop = $('.active-tab .tab-label').offset().top - 10;
2703        $('html, body').animate({
2704			scrollTop: activeTabOffsetTop
2705		}, 800);
2706      });
2707
2708      $(document).on("click", ".option-label", function() {
2709        var $this = $(this),
2710          attach_id = $this.data("attach_id"),
2711          siblings = $this.parent().siblings(".option-type"),
2712          tabsSib = $this.parents('.shop2-delivery--item__tab:first').siblings();
2713        $("#delivery_id_deligate").val(attach_id);
2714        $("#deligate_points_fields .fields").empty();
2715        $("#deligate_points_fields").hide();
2716        tabsSib.find('.option-type input').prop('checked', false);
2717        tabsSib.removeClass('point');
2718        siblings.find('input').prop('checked', false);
2719      });
2720
2721      $('#shop2-ems-calc, #shop2-edost-calc').on('click', function(e) {
2722        var $this = $(this);
2723        var attach_id = $this.data('attach-id');
2724        var to = $('select[name=' + attach_id + '\\[to\\]]');
2725        var zip = $('input[name=' + attach_id + '\\[zip\\]]');
2726        var order_value = $('input[name=' + attach_id + '\\[order_value\\]]');
2727
2728        if (to.length == 0) {
2729          to = $('#shop2-edost2-to');
2730        }
2731
2732        e.preventDefault();
2733
2734        to = to.get(0) ? to.val() : '';
2735        zip = zip.get(0) ? zip.val() : '';
2736        order_value = order_value.prop("checked") ? 'on' : '';
2737
2738        shop2.delivery.calc(attach_id, 'to=' + to + '&zip=' + zip + '&order_value=' + order_value, function(d) {
2739          if (!d.data && d.errstr) {
2740            shop2.alert(d.errstr);
2741            $('#delivery-' + attach_id + '-cost').html(0);
2742          } else {
2743            $('#delivery-' + attach_id + '-cost').html(d.data.cost);
2744
2745            if (d.data.html) {
2746              $('#delivery-' + attach_id + '-html').html(d.data.html);
2747              shop2.queue.edost();
2748            }
2749          }
2750        });
2751
2752      });
2753    },
2754
2755    edost: function() {
2756      // см delivery
2757
2758      function find(name) {
2759        var selector = '[name=' + name.replace(/([\[\]])/g, '\\$1') + ']';
2760        return $(selector);
2761      }
2762
2763      var btn = $('#shop2-edost-calc'),
2764        attach_id = btn.data('attach-id'),
2765        address = find(attach_id + '[address]');
2766
2767      function setAddress(office) {
2768        var text = $.trim(office.text()).replace(/\s*\n\s*/g, '\n').split('\n').splice(1).join('\n');
2769        address.val(text).prop('readonly', true);
2770      }
2771
2772      find(attach_id + '[edost][office]').on('click', function() {
2773        var $this = $(this),
2774          wrap = $this.closest('.shop2-edost-office');
2775
2776        setAddress(wrap);
2777        $this.prop('checked', true);
2778      });
2779
2780      find(attach_id + '[edost][tarif]').on('click', function() {
2781        var $this = $(this),
2782          wrap = $this.closest('.shop2-edost-variant'),
2783          siblings = wrap.siblings(),
2784          office = wrap.find('.shop2-edost-office'),
2785          checked;
2786
2787        siblings.find('.shop2-edost-office input, .shop2-edost-pickpointmap input').prop({
2788          disabled: true,
2789          checked: false
2790        });
2791
2792        var radio = wrap.find('.shop2-edost-office input, .shop2-edost-pickpointmap input').prop({
2793          disabled: false
2794        }).filter(':radio');
2795
2796        checked = radio.filter(':checked');
2797
2798        if (radio.get(0)) {
2799
2800          if (checked.get(0)) {
2801            checked.trigger('click');
2802          } else {
2803            radio.eq(0).trigger('click');
2804          }
2805
2806        } else {
2807
2808          if (office.length == 1) {
2809            setAddress(office);
2810          } else if (address.prop('readonly')) {
2811            address.prop('readonly', false).val('');
2812          }
2813
2814        }
2815        shop2.trigger('afterEdostSet');
2816
2817      }).filter(':checked').trigger('click');
2818
2819
2820      $('.shop2-edost-pickpointmap a').on('click', function() {
2821        var $this = $(this),
2822          span = $this.children(),
2823          city = $this.data('city');
2824
2825        $this.closest('.shop2-edost-variant').find('> label input').trigger('click');
2826
2827        function cb(data) {
2828          var res = {};
2829          $.each(['name', 'address', 'id'], function(i, k) {
2830            res[k] = data[k];
2831          });
2832          $this.next().val(JSON.stringify(res));
2833          span.html(': ' + res.name);
2834          address.val(res.name + ',\n' + res.address).prop('readonly', true);
2835        }
2836
2837        PickPoint.open(cb, {
2838          city: city,
2839          ids: null
2840        });
2841
2842        return false;
2843      });
2844
2845      // if (address.prop('readonly')) {
2846      // 	address.prop('readonly', false).val('');
2847      // }
2848
2849    },
2850
2851    edost2: function() {
2852
2853      if (!window.shop2EdostRegions) {
2854        return;
2855      }
2856
2857      var $country = $('#shop2-edost2-country');
2858      var countryDef = $country.html();
2859      var $region = $('#shop2-edost2-region');
2860      var regionDef = $region.html();
2861      var $city = $('#shop2-edost2-city');
2862      var cityDef = $city.html();
2863      var $to = $('#shop2-edost2-to');
2864      var list;
2865
2866
2867      if ($country.length) {
2868        list = $.grep(shop2EdostRegions, function(item) {
2869          return item.is_country;
2870        });
2871        $country.html(countryDef + makeHTML(list));
2872        hide($region);
2873        hide($city);
2874
2875        $country.on('change', function() {
2876          var country = $(this).val();
2877          if ($region.length) {
2878            list = $.grep(shop2EdostRegions, function(item) {
2879              return item.is_region && item.country == country;
2880            });
2881            $region.html(regionDef + makeHTML(list));
2882            if (list.length == 0) {
2883              hide($region);
2884              hide($city);
2885              $to.val(country);
2886            } else {
2887              show($region);
2888              $to.val('');
2889            }
2890          } else if ($city.length) {
2891            list = $.grep(shop2EdostRegions, function(item) {
2892              return item.is_city && item.country == country;
2893            });
2894            $city.html(cityDef + makeHTML(list));
2895            if (list.length == 0) {
2896              hide($city);
2897              $to.val(country);
2898            } else {
2899              show($city);
2900              $to.val('');
2901            }
2902          } else {
2903            $to.val(country);
2904          }
2905        });
2906      }
2907
2908      if ($region.length) {
2909        if (!$country.length) {
2910          list = $.grep(shop2EdostRegions, function(item) {
2911            return item.is_region;
2912          });
2913          $region.html(regionDef + makeHTML(list));
2914          hide($city);
2915        }
2916
2917        $region.on('change', function() {
2918          var region = $(this).val();
2919          list = $.grep(shop2EdostRegions, function(item) {
2920            return item.is_city && item.region == region;
2921          });
2922          $city.html(cityDef + makeHTML(list));
2923          if (list.length == 0) {
2924            hide($city);
2925            $to.val(region);
2926          } else {
2927            show($city);
2928            $to.val(region);
2929          }
2930        });
2931      }
2932
2933      if (!$country.length && !$region.length) {
2934        list = $.grep(shop2EdostRegions, function(item) {
2935          return item.is_city;
2936        });
2937        $city.html(regionDef + makeHTML(list));
2938      }
2939
2940      $city.on('change', function() {
2941        var val = $(this).val();
2942        if (val === 'default') {
2943          if ($region.length) {
2944            $to.val($region.val());
2945          }
2946        } else if (val) {
2947          $to.val(val);
2948        }
2949      });
2950
2951      var countryValue = $country.data('value');
2952      var regionValue = $region.data('value');
2953      var cityValue = $city.data('value');
2954
2955      if (countryValue) {
2956        $country.val(countryValue);
2957      }
2958
2959      $country.trigger('change');
2960
2961      if (regionValue) {
2962        $region.val(regionValue);
2963      }
2964
2965      $region.trigger('change');
2966
2967      if (cityValue) {
2968        $city.val(cityValue);
2969      }
2970
2971      $city.trigger('change');
2972
2973      function makeHTML(arr) {
2974        var html = $.map(arr, function(item) {
2975          return '<option value="' + item.id + '">' + item.name + '</option>';
2976        });
2977        return html.join('');
2978      }
2979
2980      function hide($el) {
2981        $el.html('').closest('.option-item').addClass('hide');
2982      }
2983
2984      function show($el) {
2985        $el.closest('.option-item').removeClass('hide');
2986      }
2987
2988    },
2989
2990    print: function() {
2991
2992      $('#order-print').on('click', function() {
2993
2994        s3.printMe('shop2-order', {
2995          stylesheet: shop2.options.printCSS
2996        });
2997
2998        return false;
2999      });
3000
3001    },
3002
3003    hs: function() {
3004
3005      $('.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() {
3006        hs.expand(this);
3007        return false;
3008      }).addClass('highslide');
3009
3010      $(document).on('click', '.shop2-edost-office-address a', function() {
3011        hs.htmlExpand(this, {
3012          objectType: 'iframe',
3013          wrapperClassName: 'draggable-header',
3014          outlineType: 'rounded-white',
3015          width: 900,
3016          height: 600,
3017          align: 'center'
3018        });
3019        return false;
3020      });
3021
3022
3023    },
3024
3025    vendors: function() {
3026
3027      $('.shop2-vendor').eachRow(function(group) {
3028        var heights = group.getHeights();
3029
3030        group.each(function(i) {
3031          var $this = $(this),
3032            delta = heights.max - heights.values[i],
3033            name = $this.find('.vendor-name'),
3034            height = name.height();
3035
3036          name.css('min-height', height + delta);
3037
3038        });
3039      });
3040
3041    },
3042
3043    toggleFields: function() {
3044
3045      var fields = $('.shop2-filter-fields'),
3046        cookieName = 'filter_opened',
3047        opened = readCookie(cookieName),
3048        btn = $('.shop2-toggle-fields');
3049
3050      btn.on('click', function() {
3051        var $this = $(this),
3052          alt = $this.data('alt'),
3053          text = $this.html();
3054
3055        if (fields.hasClass('hide')) {
3056          createCookie(cookieName, 1, 7);
3057        } else {
3058          eraseCookie(cookieName);
3059        }
3060
3061        fields.toggleClass('hide');
3062        $this.html(alt);
3063        $this.data('alt', text);
3064
3065        return false;
3066      });
3067
3068      if (!opened) {
3069        btn.trigger('click');
3070      }
3071
3072    },
3073
3074    lazyLoad: function() {
3075
3076      var $document = $(document),
3077        $window = $(window),
3078        blocked = false,
3079        products = $('.product-list');
3080
3081      function path(url, param, value) {
3082        return url + (~url.indexOf('?') ? '&' : '?') + param + '=' + value;
3083      }
3084
3085      if (shop2.my.lazy_load_subpages && products.get(0)) {
3086        $document.scroll(function() {
3087          var pagelist = $('.shop2-pagelist:last');
3088          var next = pagelist.find('.active-num').next().find('a');
3089
3090          if (!next.length) {
3091            return;
3092          }
3093
3094          pagelist.addClass('show');
3095          var offsetTop = pagelist.offset().top;
3096          pagelist.removeClass('show');
3097
3098          if ($document.scrollTop() + $window.height() >= offsetTop && !blocked && next.get(0)) {
3099            blocked = true;
3100
3101            $.get(path(next.attr('href'), 'products_only', 1), function(data) {
3102              pagelist.after('<hr />' + data);
3103              pagelist = $('.shop2-pagelist:last');
3104              pagelist.find('a').each(function() {
3105                var $this = $(this),
3106                  href = $this.attr('href');
3107                $this.attr('href', href.replace(/[&|\?]*products_only=[^&]/, ''));
3108              });
3109
3110              shop2.queue.heights();
3111
3112              blocked = false;
3113            });
3114          }
3115        });
3116      }
3117
3118    },
3119
3120    compare: function() {
3121
3122      var $document = $(document);
3123
3124      function update(el, res) {
3125
3126        // el.closest('.product-compare').replaceWith(res.data);
3127        $('input[type=checkbox][value=' + el.val() + ']').closest('.product-compare').replaceWith(res.data);
3128
3129        $('.product-compare-added a span').html('(' + res.count + ')');
3130
3131        if (res.panel) {
3132          $('#shop2-panel').replaceWith(res.panel);
3133        }
3134
3135      }
3136
3137      $document.on('click', '.product-compare input:checkbox', function() {
3138        var $this = $(this),
3139          action = $this.attr('checked') ? 'del' : 'add';
3140
3141        shop2.compare.action(action, $this.val(), function(res, status) {
3142          if (status == 'success') {
3143
3144            if (res.errstr) {
3145              shop2.alert(res.errstr);
3146              $this.prop('checked', false);
3147            } else {
3148              update($this, res);
3149            }
3150          }
3151        });
3152      });
3153
3154    },
3155
3156    compareTable: function() {
3157
3158      $('.shop2-compare-table').each(function() {
3159        var $this = $(this),
3160          relay = $this.find('.shop2-compare-switch a'),
3161          options = $this.find('.shop2-compare-data');
3162
3163        $this.find('.shop2-compare-delete').on('click', function() {
3164          var $this = $(this),
3165            kind_id = $this.data().id;
3166
3167          shop2.compare.remove(kind_id, function() {
3168            document.location.reload();
3169          });
3170
3171          return false;
3172        });
3173
3174        function compareTd(tr) {
3175          var td = tr.find('td'),
3176            val = td.eq(1).html(),
3177            differ = false,
3178            i = 2,
3179            len = td.length;
3180
3181          if (len <= 2) {
3182            return false;
3183          }
3184
3185          for (; i < len; i += 1) {
3186            if (val != td.eq(i).html()) {
3187              differ = true;
3188              break;
3189            }
3190            val = td.eq(i).html();
3191          }
3192
3193          return differ;
3194        }
3195
3196        relay.on('click', function() {
3197
3198          var $this = $(this);
3199
3200          relay.removeClass('shop2-compare-switch-active');
3201          $this.addClass('shop2-compare-switch-active');
3202
3203          if ($this.index() === 0) {
3204            options.show();
3205          } else {
3206            options.each(function() {
3207              var $this = $(this),
3208                differ = compareTd($this);
3209
3210              if (differ) {
3211                $this.show();
3212              } else {
3213                $this.hide();
3214              }
3215            });
3216          }
3217
3218          return false;
3219
3220        }).eq(1).trigger('click');
3221
3222
3223      });
3224    },
3225
3226    alert: function() {
3227
3228      var tpl = [
3229          '<div id="shop2-alert">',
3230          '<div id="shop2-alert-body"></div>',
3231          '<a href="#" id="shop2-alert-ok" class="shop2-btn"></a>',
3232          '</div>',
3233          '<div id="shop2-alert-overlay"></div>'
3234        ].join('\n'),
3235
3236        win,
3237        overlay,
3238        body,
3239        ok,
3240        cls;
3241
3242      $(document.body).append(tpl);
3243
3244      win = $('#shop2-alert');
3245      overlay = $('#shop2-alert-overlay');
3246      body = $('#shop2-alert-body');
3247      ok = $('#shop2-alert-ok');
3248
3249      function hide() {
3250        overlay.hide();
3251        win.hide();
3252        win.removeAttr('class');
3253        cls = '';
3254        shop2.trigger('alertHide', win);
3255        return false;
3256      }
3257
3258      function show() {
3259        overlay.show();
3260        win.attr('class', cls);
3261        win.show().s3center();
3262        shop2.trigger('alertShow', win);
3263      }
3264
3265      overlay.on('click', hide);
3266      ok.on('click', hide);
3267
3268      shop2.alert = function(msg, btn, c) {
3269        ok.html(btn || 'Ok');
3270        body.html(msg);
3271        cls = c || 'shop2-alert--warning';
3272        show();
3273      };
3274
3275      shop2.alert.hide = hide;
3276
3277    },
3278
3279    tooltip: function() {
3280
3281      $('.shop2-tooltip').s3tooltip({
3282        cls: 'shop2-color-ext-tooltip',
3283        dir: 'top',
3284        data: function() {
3285          return $(this).data('tooltip');
3286        }
3287      });
3288
3289    },
3290
3291    colorTooltip: function() {
3292
3293      $('.shop2-color-ext-list li').s3tooltip({
3294
3295        cls: 'shop2-color-ext-tooltip',
3296        dir: 'top',
3297        data: function() {
3298          return $(this).children('div').html();
3299        }
3300
3301      });
3302
3303      $('.shop2-color-ext-multi').s3tooltip({
3304
3305        cls: 'shop2-color-ext-tooltip',
3306        dir: 'top',
3307        data: function() {
3308          var ul = this.getElementsByTagName('ul');
3309          if (ul.length) {
3310            return ul[0].outerHTML;
3311          }
3312        }
3313
3314      });
3315
3316    },
3317
3318    colorPopup: function() {
3319
3320      var popup = $('<div id="shop2-color-ext-popup"></div>');
3321      var close = $('<div id="shop2-color-ext-close"></div>');
3322      var list = $('<ul id="shop2-color-ext-list" class="shop2-color-ext-list"></ul>');
3323      var colors = null;
3324
3325      popup.append(close);
3326      popup.append(list);
3327      $(document.body).append(popup);
3328
3329      $.on('.shop2-color-ext-caption', {
3330
3331        click: function() {
3332          var caption = $(this);
3333          var wrap = caption.closest('.shop2-color-ext-popup');
3334          var ul = wrap.find('.shop2-color-ext-list');
3335          var offset = caption.offset();
3336
3337          colors = ul.children('li');
3338          list.html(ul.html());
3339
3340          popup.css(offset).show();
3341
3342          return false;
3343        }
3344
3345      });
3346
3347
3348      $(document).on('click', '.shop2-color-ext-list li', function() {
3349        var $this = $(this);
3350        var data = $this.data();
3351        var input = $this.parent().find('input.additional-cart-params');
3352        var isSelected = $this.is('.shop2-color-ext-selected');
3353
3354        if (typeof data.kinds !== 'undefined' || input.length) {
3355
3356          $this.addClass('shop2-color-ext-selected').siblings().removeClass('shop2-color-ext-selected');
3357
3358          if (input.length) {
3359            input.val(data.value);
3360          } else {
3361            if (!isSelected) {
3362              shop2.product._reload(this);
3363            }
3364          }
3365
3366        } else {
3367
3368          var index = $this.index();
3369          var isPopup = !!$this.closest('#shop2-color-ext-popup').length;
3370          if (isPopup) {
3371            $this.toggleClass('shop2-color-ext-selected');
3372            colors.eq(index).toggleClass('shop2-color-ext-selected');
3373            shop2.filter.toggle(data.name, data.value);
3374            shop2.filter.count();
3375          }
3376        }
3377      });
3378
3379      $(document).on('click', function(e) {
3380        var target = $(e.target);
3381        var wrap = target.closest('#shop2-color-ext-popup');
3382
3383        if (!wrap.get(0) || e.target == close.get(0)) {
3384          popup.hide();
3385        }
3386      });
3387
3388    },
3389
3390    colorSelect: function() {
3391
3392      var select = $('<div id="shop2-color-ext-select"><ins></ins></div>');
3393      var colors = null;
3394      var input = null;
3395      $(document.body).append(select);
3396
3397      function hide() {
3398        if (select.is(':visible')) {
3399          select.hide();
3400          return true;
3401        }
3402      }
3403
3404      $(document).on('click', hide);
3405
3406      $.on('.shop2-color-ext-select', {
3407
3408        click: function() {
3409
3410          if (hide()) {
3411            return;
3412          }
3413
3414          var wrap = $(this);
3415          var ul = wrap.find('.shop2-color-ext-options');
3416          var offset = wrap.offset();
3417
3418          var html =
3419            '<div class="baron-wrapper">' +
3420            '	<div class="baron-scroller">' +
3421            '		<div class="baron-container">' +
3422            '			<div class="shop2-color-ext-options">' +
3423            ul.html() +
3424            '			</div>' +
3425            '		</div>' +
3426            '		<div class="baron-scroller-bar"></div>' +
3427            '	</div>' +
3428            '</div>';
3429
3430          colors = ul.children('li');
3431          input = wrap.find('input');
3432
3433          select.html(html)
3434          select.show();
3435
3436          var wrapWidth = wrap.width();
3437          var selectWidth = select.data('width') || (function() {
3438            var width = select.width();
3439            select.data('width', width);
3440            return width;
3441          })();
3442
3443          if (wrapWidth > selectWidth) {
3444            select.css('width', wrapWidth);
3445          } else {
3446            select.css('width', selectWidth);
3447          }
3448
3449          baron(select, {
3450            scroller: '.baron-scroller',
3451            container: '.baron-container',
3452            bar: '.baron-scroller-bar'
3453          });
3454
3455          select.css(offset);
3456
3457          return false;
3458
3459        }
3460
3461      });
3462
3463      $.on('#shop2-color-ext-select li:not(.shop2-color-ext-selected)', {
3464
3465        click: function() {
3466          var $this = $(this);
3467          var index = $this.index();
3468          var data = $this.data();
3469
3470          $this.addClass('shop2-color-ext-selected').siblings().removeClass('shop2-color-ext-selected');
3471          colors.removeClass('shop2-color-ext-selected');
3472          colors.eq(index).addClass('shop2-color-ext-selected');
3473
3474
3475          if (data.kinds) {
3476            shop2.product._reload(colors.get(index));
3477          } else {
3478            input.val(data.value);
3479          }
3480
3481        }
3482
3483      });
3484
3485    },
3486
3487    coordinates: function() {
3488
3489      $(document).on('click', '.shop2-map-link', function(e) {
3490        e.preventDefault();
3491        var $this = $(this);
3492        var data = $this.data();
3493        var map = data.map;
3494        if (!map.title) {
3495          map.title = $this.text();
3496        }
3497        shop2.maps.alert(data.mapType, map);
3498      });
3499    },
3500
3501    /*restoreOrderForms: function() {
3502
3503     var key = 'shop2-order-in-one-page-form';
3504     var $form = $('.shop2-order-in-one-page-form');
3505
3506     if (!window.sessionStorage || $form.length === 0) {
3507     return;
3508     }
3509
3510     function getValues() {
3511     return JSON.parse(sessionStorage.getItem(key));
3512     }
3513
3514     function setValues() {
3515     var values = $form.serializeArray();
3516     var filled = [];
3517     $.each(values, function() {
3518     if (this.value) {
3519     filled.push(this);
3520     }
3521     });
3522     sessionStorage.setItem(key, JSON.stringify(filled));
3523     }
3524
3525     $form.on('change', ':input', setValues);
3526
3527     var values = getValues();
3528
3529     if (!values) {
3530     return;
3531     }
3532
3533     var hash = {};
3534     $.each(values, function() {
3535     hash[this.name] = this.value;
3536     });
3537
3538     if (values) {
3539     $form.s3deserializeArray(values);
3540     //sessionStorage.removeItem(key);
3541     }
3542
3543
3544     function afterDeliveryCalc() {
3545     var name;
3546     var $tarif;
3547     name = hash.delivery_id + '[edost][tarif]';
3548
3549     if (hash[name]) {
3550     $tarif = $form.find('[name="' + name + '"][value="' + hash[name] + '"]').trigger('click').trigger('change');
3551     }
3552
3553     name = hash.delivery_id + '[edost][office]';
3554     if (hash[name] && $tarif) {
3555     $tarif.closest('.shop2-edost-variant').find('[name="' + name + '"][value="' + hash[name] + '"]').trigger('click').trigger('change');
3556     }
3557     }
3558
3559     var $edostBtn = $('#shop2-edost-calc');
3560     var $edostTo = $('#shop2-edost2-to');
3561     var edostToValue = $edostTo.val();
3562
3563     if (hash.delivery_id && $edostBtn.is(':visible') && edostToValue && edostToValue != 'default') {
3564     shop2.on('afterDeliveryCalc', function() {
3565     afterDeliveryCalc();
3566     afterDeliveryCalc = $.noop;
3567     });
3568
3569     $edostBtn.trigger('click');
3570     }
3571
3572
3573
3574     setValues();
3575
3576     },*/
3577
3578
3579    fixDoubleOrders: function() {
3580
3581      var $form = $('.shop2-order-form, .shop2-order-in-one-page-form');
3582      var $submit = $form.find('[type=submit]');
3583
3584      $form.on('submit', function() {
3585        $submit.prop('disabled', true);
3586        setTimeout(function() {
3587          $submit.prop('disabled', false);
3588        }, 1000);
3589      });
3590
3591    },
3592
3593    paymentMethods: function() {
3594
3595      var $types = $('.shop2-payment-type input');
3596      var $methods = $('.shop2-payment-methods input');
3597
3598
3599      $types.on('change', function() {
3600        var $this = $(this);
3601        var $method = $this.closest('.shop2-payment-type').next('.shop2-payment-methods').find('input:first');
3602        $methods.prop('checked', false);
3603        $method.prop('checked', true);
3604      });
3605
3606      $methods.on('change', function() {
3607        var $this = $(this);
3608        var $type = $this.closest('.shop2-payment-methods').prev('.shop2-payment-type').find('input
3608:first');
3609        $types.prop('checked', false);
3610        $type.prop('checked', true);
3611      });
3612
3613    },
3614
3615    auth: function() {
3616
3617      $(document).on('click', '.js-shop2-cart-auth__expand', function(e) {
3618        e.preventDefault();
3619        $('.js-shop2-cart-auth__form').toggle();
3620      });
3621
3622    }
3623
3624  };
3625
3626  var maps = shop2.maps = {};
3627
3628  maps.alert = function(type, params) {
3629    shop2.alert('<div id="shop2-alert-map"></div>', 'Закрыть', 'shop2-alert--map');
3630    maps[type].ready(function() {
3631      maps[type].draw('shop2-alert-map', params);
3632    });
3633  };
3634
3635  maps.getCenter = function(arr) {
3636    var x = 0;
3637    var y = 0;
3638    $.each(arr, function() {
3639      x += this.x;
3640      y += this.y;
3641    });
3642
3643  };
3644
3645
3646  maps.yandex = {
3647    ymaps: window.ymaps,
3648    _loading: $.Deferred(),
3649    _loading_init: false,
3650    _loading_callback: function(ymaps) {
3651      this.ymaps = ymaps;
3652      this._loading.resolve(ymaps);
3653    },
3654    ready: function(callback) {
3655      this._loading.done(callback);
3656      if (this.ymaps) {
3657        this._loading.resolve(this.ymaps);
3658        return;
3659      }
3660      if (!this._loading_init) {
3661        $('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">');
3662        this._loading_init = true;
3663      }
3664    },
3665    draw: function(id, point) {
3666      point = $.extend({}, point);
3667      point.title = $.s3escape(point.title);
3668      point.text = $.s3escape(point.text);
3669
3670      var map = new this.ymaps.Map(id, {
3671        zoom: point.z,
3672        center: [point.x, point.y],
3673        behaviors: ['drag', 'rightMouseButtonMagnifier', 'scrollZoom']
3674      });
3675
3676      var MyBalloonContentLayoutClass = this.ymaps.templateLayoutFactory.createClass(
3677        '<div class="shop2-map-baloon-content">' +
3678        '<h3>$[properties.title]</h3>' +
3679        '$[properties.text]' +
3680        '</div>'
3681      );
3682      var placemark = new self.ymaps.Placemark([point.x, point.y], point, {
3683        balloonContentLayout: MyBalloonContentLayoutClass
3684      });
3685      map.geoObjects.add(placemark);
3686    }
3687  };
3688
3689
3690  maps.google = {
3691    gmaps: window.google && window.google.maps ? window.google.maps : false,
3692    _loading: $.Deferred(),
3693    _loading_init: false,
3694    _loading_callback: function() {
3695      try {
3696        this.gmaps = window.google.maps;
3697        this._loading.resolve(this.gmaps);
3698      } catch (e) {
3699        console.log(e);
3700      }
3701    },
3702    ready: function(callback) {
3703      this._loading.done(callback);
3704      if (this.gmaps) {
3705        this._loading.resolve(this.gmaps);
3706        return;
3707      }
3708      if (!this._loading_init) {
3709    	$('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">');
3710        this._loading_init = true;
3711      }
3712    },
3713    draw: function(id, point) {
3714      var map = new this.gmaps.Map(document.getElementById(id), {
3715        zoom: Number(point.z),
3716        center: new google.maps.LatLng(point.x, point.y)
3717      });
3718      var marker = new google.maps.Marker({
3719        position: new google.maps.LatLng(point.x, point.y),
3720        map: map,
3721        title: point.title
3722      });
3723      var infowindow = new google.maps.InfoWindow({
3724        content: '<div class="shop2-map-baloon-content">' +
3725          '<h3>' + $.s3escape(point.title) + '</h3>' +
3726          $.s3escape(point.text) +
3727          '</div>'
3728      });
3729      this.gmaps.event.addListener(marker, 'click', function() {
3730        infowindow.open(map, marker);
3731      });
3732    }
3733  };
3734
3735
3736  $(window).on('load', function() {
3737    shop2.queue.heights();
3738  });
3739
3740  self.shop2 = shop2;
3741
3742  $(function() {
3743    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/i.test(navigator.userAgent),
3744      clickStart = (isMobile) ? 'touchend.respons' : 'click.respons';
3745
3746
3747    $('.personal-html-btn, .close-btn').on(clickStart, function(e) {
3748      e.preventDefault();
3749      $('.personal-html-content').toggleClass('active');
3750    });
3751    
3752    
3753
3754    $(document).on(clickStart, function(event) {
3755      if ($(event.target).closest('.personal-html-content-in, .personal-html-btn').length) return;
3756      $('.personal-html-content').removeClass('active');
3757    });
3758    $(this).keydown(function(eventObject) {
3759      if (eventObject.which == 27) {
3760        $('.personal-html-content').removeClass('active');
3761      }
3762    });
3763  });
3764
3765})(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.