// Generated by CoffeeScript 1.7.1

/*
 * Скрипт сгенерирован из файла main.coffee, находящегося в папке source-scripts
 */

(function() {
  var addEvent, after, log, r;

  addEvent = function(evnt, elem, func) {
    if (elem.addEventListener) {
      return elem.addEventListener(evnt, func, false);
    } else if (elem.attachEvent) {
      return elem.attachEvent("on" + evnt, func);
    } else {
      return elem[evnt] = func;
    }
  };

  log = function() {
    log.history = log.history || [];
    log.history.push(arguments);
    if (this.console) {
      return console.log(Array.prototype.slice.call(arguments));
    }
  };


  /*
   * after 1000, -> addSec()
   */

  after = function(ms, fn) {
    return setTimeout(fn, ms);
  };


  /*
   * r 'plugin', -> block.plugin()
   */

  r = function(m, c) {
    var cb;
    cb = function() {
      if (typeof c === "function") {
        return c.call(this);
      } else {
        return true;
      }
    };
    if (require.defined(m)) {
      return cb();
    } else {
      return require([m], cb);
    }
  };


  /*
   * IOS Hover/Active
   * На случай, если в body не добавят ontouchstart=""
   */

  addEvent("touchmove", (function(event) {}), false);


  /*
   * IOS Scale Bug
   */

  (function(doc) {
    var fix, meta, qsa, scales, type;
    fix = function() {
      meta.content = "width=device-width, minimum-scale=" + scales[0] + ", maximum-scale=" + scales[1];
      return doc.removeEventListener(type, fix, true);
    };
    addEvent = "addEventListener";
    type = "gesturestart";
    qsa = "querySelectorAll";
    scales = [0, 1];
    meta = (qsa in doc ? doc[qsa]("meta[name=viewport]") : []);
    if ((meta = meta[meta.length - 1]) && addEvent in doc) {
      fix();
      scales = [.5, 1];
      return doc[addEvent](type, fix, true);
    }
  })(document);


  /*
   * После jQuery
   */

  (function($, window) {

    /*
     * Общие переменные
     */
    var LAST_SWIPER_ID, activeClass, add_qty_buttons_markup, add_swiper_markup, body, close_all_dropdowns, closedClass, create_tabs, currentClass, disabledClass, div, footer_tabs, getAutoHeight, getMedia, hiddenClass, init_chosen, init_qty_buttons, init_swipers, isMedia, items_list, lastMedia, layout_cookie, main_content_load_handlers, mediaMax, mediaMid, on_footer_data_load, on_main_content_load, openedClass, scroll_to_tab, set_cookie, w;
    disabledClass = 'tpl-state-disabled';
    activeClass = 'tpl-state-active';
    currentClass = 'tpl-state-current';
    openedClass = 'tpl-state-opened';
    closedClass = 'tpl-state-closed';
    hiddenClass = 'tpl-state-hidden';
    mediaMid = 1000;
    mediaMax = 1840;
    main_content_load_handlers = [];

    /*
     * Добавляем функции, которые нужно выполнить при готовности основной части страницы
     */
    window.tpl_on_main_content_load = on_main_content_load = function(fn) {
      if (typeof fn === 'function') {
        return main_content_load_handlers.push(fn);
      }
    };

    /*
     Узнаём будущую высоту элемента с height:auto
     */
    getAutoHeight = function(el) {
      var autoHeight, startHeight;
      startHeight = el.css('height');
      autoHeight = el.css('height', 'auto').css('height');
      el.css('height', startHeight);
      return autoHeight;
    };

    /*
     * Триггеры на разрешения экрана
     * $(window).on 'mediaMin' → < 320px
     * $(window).on 'mediaMid' → > 320px < 1850px
     * $(window).on 'mediaMax' → > 1850px
     * https://github.com/xoxco/breakpoints
     */
    w = $(window);
    body = $('body');

    /*
     * @param  {Number} vw [null, 40, 1200, 1300]
     * @return {String}
     */
    getMedia = function(vw) {
      if (vw == null) {
        vw = body.width();
      }
      if (vw >= mediaMid && vw < mediaMax) {
        return 'mediaMid';
      } else if (vw >= mediaMax) {
        return 'mediaMax';
      } else {
        return 'mediaMin';
      }
    };

    /*
     * @param  {String} sizes ['min', 'mid', 'max', 'mid max']
     * @return {Boolean}
     */
    isMedia = function(sizes) {
      var error, nowMedia;
      error = 0;
      nowMedia = getMedia();
      $.each(sizes.split(' '), function(i, size) {
        if (size !== nowMedia) {
          return error++;
        }
      });
      if (error > 0) {
        return false;
      } else {
        return true;
      }
    };
    lastMedia = getMedia();
    w.on('resize', function() {
      var nowMedia, vw;
      vw = body.width();
      nowMedia = getMedia(vw);
      if (nowMedia !== lastMedia) {
        lastMedia = nowMedia;
        return $(window).trigger(nowMedia);
      }
    });

    /*
     * Вверх
     */
    LAST_SWIPER_ID = 0;
    div = function(block_class_names, prefix) {
      var n;
      if (prefix == null) {
        prefix = 'tpl-block-';
      }
      return '<div class="' + ((function() {
        var _i, _len, _ref, _results;
        _ref = block_class_names.split(/\s/);
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          n = _ref[_i];
          _results.push(prefix + n);
        }
        return _results;
      })()).join(' ') + '" />';
    };

    /*
     * Создание разметки «свайпера» (aka «слайдера») вокруг одного указанного блока
     */
    add_swiper_markup = function(items_container, class_mod, prevnext) {
      var c, swiper_root;
      if (class_mod == null) {
        class_mod = null;
      }
      if (prevnext == null) {
        prevnext = false;
      }
      c = $(items_container);
      if (c.closest('.tpl-block-swiper').length) {
        return false;
      }
      c.children().wrap(div('swiper-item'));
      c.wrapAll(div("swiper" + (class_mod ? " swiper--" + class_mod : ""))).wrapAll(div('swiper-container')).addClass('tpl-block-swiper-wrapper');
      swiper_root = c.closest('.tpl-block-swiper');
      swiper_root.prepend(swiper_root.parent().children('h2, h3'));
      if (class_mod === 'with-scrollbar') {
        swiper_root.append(div('swiper-scrollbar'));
      }
      if (prevnext) {
        return $(div('prevnext')).append(div('tpl-link-prev', '')).append(div('tpl-link-next', '')).appendTo(swiper_root);
      }
    };
    items_list = function(t) {
      return ".tpl-widget-netshop-" + t + " .tpl-block-list-objects";
    };
    on_main_content_load(function() {
      add_swiper_markup(items_list('accessories'), null, true);
      add_swiper_markup(items_list('bought-together'), null, true);
      add_swiper_markup(items_list('viewed-together'), null, true);
      add_swiper_markup(items_list('viewed-by-user '), 'with-scrollbar');
      add_swiper_markup(items_list('compare'), 'with-scrollbar');
      return add_swiper_markup(items_list('favorite'), 'with-scrollbar');
    });

    /* front-page */
    $(function() {
      var fp;
      fp = $('.tpl-block-front-page');
      if (fp.length) {
        add_swiper_markup(fp.find(items_list('goods-offers')), '1or2', true);
        add_swiper_markup(fp.find(items_list('new-goods')), '1or2', true);
        add_swiper_markup(fp.find(items_list('viewed-now')), '1or3or4', true);
        return add_swiper_markup(fp.find(items_list('bought-recently')), '1or3or4', true);
      }
    });

    /*
     * Слайдеры карточек
     * http://www.idangero.us/sliders/swiper
     */
    init_swipers = function(swipers) {
      swipers = $(swipers);
      if (swipers[0]) {
        return r('swiper', function() {
          var addShadows, c, cd, defaultOptions, isMod, removeShadows, swipeIt;
          c = 'tpl-block-swiper';
          cd = false;
          removeShadows = function(e) {
            return after(300, function() {
              if (!cd) {
                return $(e).removeClass(c + '-container--grabbing');
              } else {
                return removeShadows(e);
              }
            });
          };
          addShadows = function(e) {
            cd = true;
            $(e).addClass(c + '-container--grabbing');
            return after(500, function() {
              return cd = false;
            });
          };
          isMod = function(node, mod) {
            return node.hasClass(c + '--' + mod);
          };
          swipeIt = function(id, defaultOptions, localOptions) {
            var options, slider;
            options = $.extend({}, defaultOptions, localOptions);
            slider = new Swiper('.' + id, options);
            $('.' + id).data('slider', slider);
            return slider;
          };
          defaultOptions = {
            speed: 200,
            autoplay: '',
            mode: 'horizontal',
            loop: false,
            slidesPerView: 4,
            calculateHeight: false,
            updateOnImagesReady: false,
            DOMAnimation: false,
            grabCursor: true,
            autoResize: true,
            resizeReInit: false,
            cssWidthAndHeight: false,
            wrapperClass: c + '-wrapper',
            slideClass: c + '-item',
            slideActiveClass: c + '-item--active',
            slideVisibleClass: c + '-item--visible',
            slideElement: 'div',
            noSwipingClass: c + '--no-swiping',
            moveStartThreshold: 5,
            onSlideChangeStart: function(e, a) {
              return addShadows(e.container);
            },
            onSlideChangeEnd: function(e, a) {
              return removeShadows(e.container);
            },
            onTouchMove: function(e, a) {
              return addShadows(e.container);
            },
            onSlideReset: function(e, a) {
              return removeShadows(e.container);
            },
            onFirstInit: function() {
              return $(window).trigger('swiper-first-init');
            }
          };

          /*
           * Проходимся по всем свайперам по очереди
           */
          return swipers.each(function() {
            var amount, buttons, container, getAmount, id, localOptions, nextClass, node, prevClass, setHeight, slider;
            node = $(this);
            id = c + '-container--id' + (LAST_SWIPER_ID++);
            container = node.find('.' + c + '-container').addClass(id);
            localOptions = defaultOptions;

            /*
             * Заморачиваемся с высотами
             */
            setHeight = function(newHeight) {
              if (newHeight == null) {
                newHeight = container.find('.tpl-block-swiper-item').first().outerHeight();
              }
              container.css('height', newHeight + 'px');
              return node.data('prevHeight', newHeight);
            };
            setHeight();

            /*
             * При ресайзе, раз в 100мс проверяет, не поменялась ли высота
             * первой карточки, и, если нужно, отправляет на изменение высоты враппера
             */
            $(window).on('resize.swiperHeight', function() {
              var timeoutResize;
              clearTimeout(timeoutResize);
              return timeoutResize = setTimeout(function() {
                var nowHeight, prevHeight;
                prevHeight = node.data('prevHeight');
                nowHeight = container.find('.tpl-block-swiper-item').first().outerHeight();
                if (node.data('prevHeight') !== nowHeight) {
                  return setHeight(nowHeight);
                }
              }, 100);
            });

            /*
             * Определяем, сколько карточек может показаться
             * на текущем брекпоинте
             */
            getAmount = function() {
              var media;
              media = getMedia();
              if (isMod(node, '1or2or3')) {
                switch (media) {
                  case 'mediaMin':
                    return 1;
                  case 'mediaMid':
                    return 2;
                  case 'mediaMax':
                    return 3;
                }
              } else if (isMod(node, '1or2or4')) {
                switch (media) {
                  case 'mediaMin':
                    return 1;
                  case 'mediaMid':
                    return 2;
                  case 'mediaMax':
                    return 4;
                }
              } else if (isMod(node, '1or3or4')) {
                switch (media) {
                  case 'mediaMin':
                    return 1;
                  case 'mediaMid':
                    return 3;
                  case 'mediaMax':
                    return 4;
                }
              } else if (isMod(node, '1or2')) {
                switch (media) {
                  case 'mediaMin':
                    return 1;
                  case 'mediaMid':
                    return 2;
                  case 'mediaMax':
                    return 2;
                }
              } else {
                if (media === 'min') {
                  return 1;
                } else {
                  return 4;
                }
              }
            };
            amount = getAmount();
            node.data('prevAmount', amount);
            localOptions.slidesPerView = amount;

            /*
             * Когда меняется брекпоинт, то, если нужно,
             * пересчитываем количество карточек и их высоты
             */
            $(window).on('mediaMin mediaMid mediaMax', function() {
              var nowAmount, prevAmount;
              nowAmount = getAmount();
              prevAmount = node.data('prevAmount');
              if (nowAmount !== prevAmount) {
                node.data('prevAmount', nowAmount);
                slider.params.slidesPerView = nowAmount;
                return slider.reInit();
              }
            });

            /*
             * Опции для свайпера со скроллбаром
             */
            if (isMod(node, 'with-scrollbar')) {
              localOptions = {
                scrollContainer: false,
                loop: false,
                onFirstInit: function() {
                  return after(500, function() {
                    return w.trigger('openFooterTabsBySwiper');
                  });
                },
                scrollbar: {
                  container: "." + id + " + ." + c + "-scrollbar",
                  hide: false,
                  draggable: true,
                  snapOnRelease: true
                }
              };
            }

            /*
             * Запускаем текущий свайпер с нужными опциями
             */
            slider = swipeIt(id, defaultOptions, localOptions);

            /*
             * Управление кнопками
             */
            prevClass = 'tpl-link-prev';
            nextClass = 'tpl-link-next';
            buttons = node.find('.tpl-block-prevnext').find("." + prevClass + ", ." + nextClass);
            return buttons.on('click', function() {
              var button;
              button = $(this);
              if (button.hasClass(prevClass)) {
                return slider.swipePrev();
              } else {
                return slider.swipeNext();
              }
            });
          });
        });
      }
    };
    on_main_content_load(function() {
      return init_swipers('.tpl-block-swiper');
    });

    /*
     * Табы
     */
    create_tabs = function(target, tabs) {
      var tab_container, tab_switchers;
      if (!tabs.length) {
        return false;
      }
      tab_container = $(div('tabs'));
      tab_switchers = $(div('tabs-switcher')).appendTo(tab_container);
      tabs.each(function() {
        var header, tab_contents;
        tab_contents = $(this);
        header = tab_contents.find('h3').eq(0);
        header.remove().addClass('tpl-block-tabs-tab').appendTo(tab_switchers);
        return $(div('tabs-content')).append(tab_contents).appendTo(tab_container);
      });
      tab_container.find('.tpl-block-tabs-tab').eq(0).addClass('tpl-state-current');
      tab_container.find('.tpl-block-tabs-content').eq(0).addClass('tpl-state-current');
      return tab_container.appendTo(target);
    };
    on_main_content_load(function() {
      var container;
      container = $('.tpl-block-full-more');
      return create_tabs(container, container.children('div').not('.tpl-block-tabs, :hidden'));
    });
    on_main_content_load(function() {
      var c, q;
      c = 'tpl-block-tabs';
      q = '.' + c;
      if ($(q)[0]) {
        return $(q).each(function() {
          var content, isFooterTabs, node, switcher, tabs, trigger, wrapper;
          node = $(this);
          tabs = node.find(q + '-tab');
          content = node.find(q + '-content');
          wrapper = node.find(q + '-wrapper');
          switcher = node.find(q + '-switcher');
          isFooterTabs = node.hasClass(c + '--footer') ? true : false;
          if (isFooterTabs) {
            trigger = node.find(q + '-trigger');
          }
          if (isFooterTabs) {
            w.on('openFooterTabs', function() {
              var wrapperAutoHeight;
              wrapperAutoHeight = getAutoHeight(wrapper);
              wrapper.removeClass(hiddenClass);
              trigger.addClass(activeClass);
              return wrapper.css('height', 'auto');
            });
            w.on('closeFooterTabs', function() {
              wrapper.addClass(hiddenClass);
              trigger.removeClass(activeClass);
              return wrapper.stop().animate({
                height: 0
              }, 200);
            });
            w.on('openFooterTabsBySwiper', function() {
              if (trigger.hasClass(activeClass)) {
                return w.trigger('openFooterTabs');
              }
            });
            trigger.on('click', function() {
              if (trigger.hasClass(activeClass)) {
                return w.trigger('closeFooterTabs');
              } else {
                return w.trigger('openFooterTabs');
              }
            });
          }
          return tabs.on('click', function() {
            var accordionToTabs, newHeight, nextContent, nextIndex, nextTab, oldHeight, prevContent, prevIndex, prevTab, tabsToAccordion;
            prevTab = tabs.filter('.' + currentClass);
            nextTab = $(this);
            prevIndex = tabs.index(prevTab);
            nextIndex = tabs.index(nextTab);
            prevContent = content.eq(prevIndex);
            nextContent = content.eq(nextIndex);
            if (isFooterTabs) {
              if (!trigger.hasClass(activeClass)) {
                w.trigger('openFooterTabs');
              }
            }
            if (nextIndex === prevIndex && !isFooterTabs) {
              return false;
            } else {
              oldHeight = prevContent.css('height');
              newHeight = getAutoHeight(nextContent);
              prevTab.removeClass(currentClass);
              nextTab.addClass(currentClass);
              prevContent.removeClass(currentClass).css('height', 0);
              nextContent.stop().css('height', oldHeight).animate({
                height: newHeight
              }, 200).addClass(currentClass);
              tabs.removeClass(currentClass);
              nextTab.addClass(currentClass);
            }
            if (!node.hasClass(c + '--footer')) {
              tabsToAccordion = function() {
                return tabs.each(function() {
                  var i;
                  nextTab = $(this);
                  i = tabs.index(nextTab);
                  return nextTab.insertBefore(content.eq(nextIndex));
                });
              };
              accordionToTabs = function() {
                return tabs.appendTo(switcher);
              };
              if (isMedia('mediaMin')) {
                tabsToAccordion();
              }
              $(window).on('mediaMin', function() {
                return tabsToAccordion();
              });
              return $(window).on('mediaMid mediaMax', function() {
                return accordionToTabs();
              });
            }
          });
        });
      }
    });

    /*
     * Фильтр каталога в телефоне
     */
    $(function() {
      var drop, q;
      q = 'aside .tpl-block-filter';
      if ($(q)[0]) {
        drop = $(q);
        return drop.find('h3').first().on('click', function() {
          var cssHeight, dropHide, dropShow;
          cssHeight = drop.css('height');
          dropHide = function() {
            drop.stop().animate({
              height: 150
            }, 200);
            return drop.removeClass(activeClass);
          };
          dropShow = function() {
            var autoHeight;
            autoHeight = drop.css('height', 'auto').outerHeight();
            drop.height(cssHeight).stop().animate({
              height: autoHeight
            }, 200);
            return drop.addClass(activeClass);
          };
          if (drop.hasClass(activeClass)) {
            return dropHide();
          } else {
            return dropShow();
          }
        });
      }
    });

    /*
     * Мобильная корзина
     */
    $(function() {
      var node, q;
      q = '.tpl-block-mobilecart';
      if ($(q)[0]) {
        node = $(q);
        node.find(q + '-showimage').on('click', function() {
          var image, item, showimg;
          showimg = $(this);
          item = showimg.parents(q + '-item');
          image = item.find('.tpl-property-image');
          image.stop().slideToggle(200);
          return item.toggleClass(activeClass);
        });
        return node.find(q + '-delete').on('click', function() {
          var del, item;
          del = $(this);
          item = del.parents(q + '-item');
          return item.stop().slideUp(200);
        });
      }
    });

    /*
     * Мобильный каталог
     */
    $(function() {
      var cats, drops, menu, q, titles;
      q = '.tpl-block-mobilemenu';
      if ($(q)[0]) {
        menu = $(q);
        titles = menu.find(q + '-title');
        cats = menu.find(q + '-category');
        drops = menu.find(q + '-drop');
        return titles.on('click', function() {
          var cat, drop, title;
          title = $(this);
          cat = title.parents(q + '-category');
          drop = title.siblings(q + '-drop');
          if (cat.hasClass(activeClass)) {
            drop.stop().slideUp(200);
            return cat.removeClass(activeClass);
          } else {
            drops.stop().slideUp(200);
            cats.removeClass(activeClass);
            cat.addClass(activeClass);
            return drop.stop().slideDown(200);
          }
        });
      }
    });

    /*
     * Выпадайки в мобильной навигации
     */
    $(function() {
      var drops, dropsSelector, itemClass, itemSelector, items, links, menuClass, menuSelector;
      menuClass = 'tpl-block-mobilenav';
      dropsSelector = '.tpl-block-headerdrop';
      menuSelector = '.' + menuClass;
      itemClass = menuClass + '-item';
      itemSelector = '.' + itemClass;
      if ($(menuSelector)[0]) {
        items = $(itemSelector);
        links = $('a', itemSelector);
        drops = $(dropsSelector);
        return links.on('click', function(e) {
          var closeDrops, item, openDrop;
          item = $(this).parents(itemSelector);
          if (!item.hasClass(itemClass + '--logo')) {
            e.preventDefault();
            closeDrops = function() {
              items.removeClass(activeClass);
              drops.removeClass(activeClass);
              return drops.stop().slideUp(200);
            };
            openDrop = function(id) {
              var drop;
              closeDrops();
              drop = $(dropsSelector + '--' + id);
              drop.addClass(activeClass);
              drop.stop().slideDown(200);
              return item.addClass(activeClass);
            };
            if (item.hasClass(activeClass)) {
              return closeDrops();
            } else {
              if (item.hasClass(itemClass + '--menu')) {
                openDrop('menu');
              }
              if (item.hasClass(itemClass + '--search')) {
                openDrop('search');
              }
              if (item.hasClass(itemClass + '--cart')) {
                openDrop('cart');
              }
              if (item.hasClass(itemClass + '--user')) {
                return openDrop('user');
              }
            }
          }
        });
      }
    });

    /*
     * Счётчик с плюсом/минусом
     */
    add_qty_buttons_markup = function(input) {
      var block;
      input = $(input);
      block = $(div('amountchoice')).append($(div('amountchoice-value')).append($('<input />', {
        type: 'hidden',
        value: input.val(),
        name: input.attr('name')
      }), '<span>' + input.val() + '</span> ', input.data('units') || ''), $(div('amountchoice-buttons')).append($(div('amountchoice-button amountchoice-button--more')).append('<i class="icon-angle-up"></i>'), $(div('amountchoice-button amountchoice-button--less')).append('<i class="icon-angle-down"></i>')));
      input.replaceWith(block);
      return true;
    };
    init_qty_buttons = function() {
      var blockSelector, buttonSelector, c, clickEvent, lessClass, moreClass, q, valueSelector;
      c = 'tpl-block-amountchoice';
      q = '.' + c;
      clickEvent = 'click.qty_buttons';
      if ($(q)[0]) {
        blockSelector = q;
        valueSelector = q + '-value span';
        buttonSelector = q + '-button';
        moreClass = c + '-button--more';
        lessClass = c + '-button--less';
        $(valueSelector).each(function() {
          var block, i, self;
          self = $(this);
          i = parseInt(self.text());
          if (i === 1) {
            block = self.parents(blockSelector);
            return block.find('.' + lessClass).addClass(disabledClass);
          }
        });
        return $(buttonSelector).off(clickEvent).on(clickEvent, function() {
          var block, button, buttons, i, value, valueInput;
          button = $(this);
          if (!button.hasClass(disabledClass)) {
            block = button.parents(blockSelector);
            value = block.find(valueSelector);
            valueInput = value.siblings('INPUT');
            buttons = block.find(buttonSelector);
            i = parseInt(value.text());
            if (i > 0) {
              if (button.hasClass(moreClass)) {
                value.text(i + 1);
                valueInput.val(i + 1);
                return buttons.removeClass(disabledClass);
              } else {
                if (i - 1 === 1) {
                  button.addClass(disabledClass);
                }
                valueInput.val(i - 1);
                return value.text(i - 1);
              }
            }
          }
        });
      }
    };
    on_main_content_load(function() {
      var inputs;
      inputs = $('.tpl-block-full.tpl-component-goods input[name^="cart["], .tpl-component-cart input[name^="cart["]').not(':hidden');
      inputs.each(function() {
        return add_qty_buttons_markup(this);
      });
      return init_qty_buttons();
    });

    /*
     * Изменённые селектбоксы
     * http://harvesthq.github.io/chosen/
     */
    init_chosen = function() {
      var selects;
      selects = $('select');
      if (selects[0]) {
        return r('chosen', function() {
          selects.chosen({
            disable_search: true,
            width: '100%'
          });
          return selects.trigger('chosen:updated');
        });
      }
    };
    on_main_content_load(function() {
      if (!isMedia('mediaMin')) {
        return init_chosen();
      }
    });
    $(window).on('mediaMin', function() {
      return $('select').chosen('destroy');
    });
    $(window).on('mediaMid mediaMax', function() {
      return init_chosen();
    });

    /*
    * Слайдеры значений
    * http://refreshless.com/nouislider/
     */
    $(function() {
      var q, range_rows;
      q = '.nc_netshop_filter_row_range';
      range_rows = $(q);
      if (!range_rows.length) {
        return false;
      }
      if (range_rows[0]) {
        return r('range-slider', function() {
          return range_rows.each(function() {
            var filterMax, filterMin, maxInput, minInput, rangeMax, rangeMin, resolution, row, slider, step;
            row = $(this);
            slider = $(div('range-slider')).appendTo(row);
            rangeMin = row.data('min');
            rangeMax = row.data('max');
            minInput = row.find('.nc_netshop_filter_field_min input').first();
            maxInput = row.find('.nc_netshop_filter_field_max input').first();
            filterMin = minInput.val().replace(/[^0-9.]/g, '') || rangeMin;
            filterMax = maxInput.val().replace(/[^0-9.]/g, '') || rangeMax;
            if (filterMin.toString().match(/\./) || filterMax.toString().match(/\./)) {
              step = 0.01;
              resolution = 0.1;
            } else {
              step = resolution = 1;
            }
            return slider.noUiSlider({
              range: [rangeMin, rangeMax],
              start: [filterMin, filterMax],
              handles: 2,
              step: step,
              serialization: {
                to: [minInput, maxInput],
                resolution: resolution
              }
            });
          });
        });
      }
    });
    set_cookie = function(key, value, days) {
      var date;
      if (days == null) {
        days = 3650;
      }
      date = new Date;
      date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
      return document.cookie = ("" + key + "=" + value + "; path=/; expires=") + date.toGMTString();
    };
    layout_cookie = 'tpl_default_list_layout';

    /*
     * Каталог
     */
    on_main_content_load(function() {
      var list, listClass, plateClass, switchToList, switchToPlate;
      list = $('.tpl-block-list.tpl-component-goods .tpl-block-list-objects');
      if (list.length) {

        /*
         * Переключалка список / плитка
         */
        plateClass = 'tpl-layout-tiles';
        listClass = 'tpl-layout-list';
        switchToPlate = $('.tpl-block-list-layout-tiles');
        switchToList = $('.tpl-block-list-layout-list');
        switchToPlate.on('click', function() {
          switchToList.removeClass(activeClass);
          switchToPlate.addClass(activeClass);
          list.removeClass(listClass).addClass(plateClass);
          return set_cookie(layout_cookie, 'tiles');
        });
        return switchToList.on('click', function() {
          switchToPlate.removeClass(activeClass);
          switchToList.addClass(activeClass);
          list.removeClass(plateClass).addClass(listClass);
          return set_cookie(layout_cookie, 'list');
        });
      }
    });

    /*
     * Галереи
     * http://fotorama.io
     */
    on_main_content_load(function() {
      var fotoraming, galleries;
      fotoraming = function(galleries) {
        return galleries.each(function() {
          return $(this).fotorama({
            nav: 'thumbs',
            arrows: false,
            height: 440,
            thumbwidth: 90,
            thumbheight: 90,
            thumbmargin: 20,
            thumbborderwidth: 5
          });
        });
      };
      galleries = $('.tpl-block-gallery');
      if (galleries[0]) {
        r('fotorama', function() {
          return fotoraming(galleries);
        });
      }
      return $(window).on('galleryPopup', function() {
        galleries = $('.tpl-block-gallery');
        return r('fotorama', function() {
          return fotoraming(galleries);
        });
      });
    });

    /*
     * Слайдер на главной
     * http://fotorama.io
     */
    $(function() {
      var getHeight, hero, next, prev, q, setHeight, slider;
      q = '.tpl-block-hero';
      if ($(q)[0]) {
        hero = $(q);
        slider = hero.find(q + '-slider');
        prev = hero.find('.tpl-link-prev');
        next = hero.find('.tpl-link-next');
        getHeight = function() {
          if (isMedia('mediaMin')) {
            return 630;
          } else {
            return '100%';
          }
        };
        setHeight = function(f, h) {
          return f.resize({
            height: h
          });
        };
        return r('fotorama', function() {
          var f;
          slider.on('fotorama:ready', function(e, fotorama, extra) {
            setHeight(fotorama, getHeight());
            return $(window).on('mediaMin mediaMid mediaMax', function() {
              return setHeight(slider, getHeight());
            });
          });
          slider.fotorama({
            nav: 'none',
            arrows: false,
            margin: 20,
            height: '100%',
            width: '100%',
            loop: true,
            shadows: false
          });
          f = slider.data('fotorama');
          prev.on('click', function() {
            return f.show('<');
          });
          return next.on('click', function() {
            return f.show('>');
          });
        });
      }
    });

    /*
     * Сравнение
     * http://www.fixedheadertable.com
     */
    $(function() {
      var area, areaWidth, c, calc, col, colw, doubler, next, node, nodeWidth, pos, prev, q, viewport;
      c = 'tpl-block-comparision';
      q = '.' + c;
      if ($(q)[0]) {
        node = $(q);
        viewport = node.find(q + '-original');
        doubler = node.find(q + '-doubler');
        doubler = viewport.clone().removeClass(c + '-original').addClass(c + '-doubler');
        doubler.find('td').detach();
        doubler.insertAfter(viewport);
        area = viewport.find('table');
        prev = doubler.find('.tpl-block-prevnext-button--prev').first();
        next = doubler.find('.tpl-block-prevnext-button--next').first();
        pos = 0;
        prev.addClass(disabledClass);
        col = area.find('td').first();
        nodeWidth = node.outerWidth();
        areaWidth = area.outerWidth();
        colw = col.outerWidth();
        calc = function() {
          nodeWidth = node.outerWidth();
          areaWidth = area.outerWidth();
          return colw = col.outerWidth();
        };
        if (area.find('tr:first td').length <= 3) {
          next.addClass(disabledClass);
        }
        $(window).on('mediaMid mediaMax', function() {
          calc();
          return viewport.scrollLeft(colw * pos);
        });
        next.on('click', function() {
          var l;
          l = viewport.scrollLeft();
          if (l + colw + nodeWidth >= areaWidth) {
            next.addClass(disabledClass);
          }
          if (l + nodeWidth < areaWidth) {
            prev.removeClass(disabledClass);
            return viewport.animate({
              scrollLeft: '+=' + colw
            }, 200, function() {
              return pos++;
            });
          }
        });
        return prev.on('click', function() {
          var l;
          l = viewport.scrollLeft();
          if (l - colw <= 0) {
            prev.addClass(disabledClass);
          }
          if (l > 0) {
            next.removeClass(disabledClass);
            return viewport.animate({
              scrollLeft: '-=' + colw
            }, 200, function() {
              return pos--;
            });
          }
        });
      }
    });

    /*
     * Перемещение блока с новостями в мобильной версии вниз
     */
    $(function() {
      var news, parent;
      if ($('.tpl-block-front-page')[0]) {
        news = $('.tpl-block-news');
        parent = news.parent();
        if (isMedia('mediaMin')) {
          news.appendTo(parent);
        }
        $(window).on('mediaMin', function() {
          return news.appendTo(parent);
        });
        return $(window).on('mediaMid mediaMax', function() {
          return news.insertAfter(parent.children('aside'));
        });
      }
    });

    /*
     * Лайтбоксы
     * http://dimsemenov.com/plugins/magnific-popup/
     */
    on_main_content_load(function() {
      return r('magnific-popup', function() {
        return $('.tpl-link-modal').magnificPopup({
          midClick: true,
          mainClass: 'tpl-block-mfp-animating',
          removalDelay: 200,
          type: 'inline',
          closeMarkup: '<div class="tpl-block-mfp-close"><i class="icon-popup-close"></i></div>'
        });
      });
    });

    /*
     * Переход по ссылке «Подробное описание» в полном просмотре товаров
     */
    on_main_content_load(function() {
      $('.tpl-block-full.tpl-component-goods .tpl-block-details-brief a.tpl-link-more').on('click', function() {
        var tabSwitcher;
        tabSwitcher = $('.tpl-block-tabs-switcher .tpl-block-tabs-tab').eq(0).click();
        $('HTML, BODY').animate({
          scrollTop: tabSwitcher.offset().top
        });
        return false;
      });
    });

    /*
     * Добавление/удаление в сравнение и избранное
     */
    footer_tabs = {
      recent: {
        tab_index: 0,
        source: '.tpl-widget-netshop-viewed-by-user'
      },
      compare: {
        tab_index: 1,
        source: '.tpl-widget-netshop-compare',
        additional_content: '.tpl-block-compare-button',
        link: '.tpl-link-compare-add, .tpl-link-compare-remove',
        popups: '#goodslist-compare-add, #goodslist-compare-remove',
        actions: {
          '.tpl-link-compare-add': {
            links_to_show: '.tpl-link-compare-remove, .tpl-link-compare',
            popup: '#goodslist-compare-add'
          },
          '.tpl-link-compare-remove': {
            links_to_show: false,
            popup: false
          }
        }
      },
      favorite: {
        tab_index: 2,
        source: '.tpl-widget-netshop-favorite',
        link: '.tpl-link-favorite-add, .tpl-link-favorite-remove',
        popups: '#goodslist-favorite-add, #goodslist-favorite-remove',
        actions: {
          '.tpl-link-favorite-add': {
            links_to_show: '.tpl-link-favorite-remove, .tpl-link-favorite',
            popup: '#goodslist-favorite-add'
          },
          '.tpl-link-favorite-remove': {
            links_to_show: false,
            popup: false
          }
        }
      }
    };
    on_footer_data_load = function(data) {
      var $data, current_tab, footer, new_items, new_swiper, scroll_top, swiper, swiper_x, tab, tab_name;
      scroll_top = $(window).scrollTop();
      $data = $('<div/>').html(data);
      footer = $('.tpl-block-tabs--footer .tpl-block-tabs-content');
      for (tab_name in footer_tabs) {
        tab = footer_tabs[tab_name];
        new_items = $data.find(tab.source);
        current_tab = footer.eq(tab.tab_index);
        swiper = current_tab.find('.tpl-block-swiper-container').data('slider');
        swiper_x = swiper ? swiper.getWrapperTranslate('x') : null;
        current_tab.empty().append(new_items);
        if (tab.additional_content) {
          current_tab.append($data.find(tab.additional_content));
        }
        add_swiper_markup(current_tab.find('.tpl-block-list-objects'), 'with-scrollbar');
        init_swipers(current_tab.find('.tpl-block-swiper'));
        new_swiper = current_tab.find('.tpl-block-swiper-container').data('slider');
        if (new_swiper && swiper_x) {
          new_swiper.setWrapperTranslate(swiper_x, 0, 0);
        }
        if (current_tab.is('.tpl-state-current')) {
          current_tab.css('height', 'auto');
        }
      }
      $(window).scrollTop(scroll_top);
      if (window.tpl_init_cart_buttons) {
        tpl_init_cart_buttons();
      }
      return true;
    };
    on_main_content_load(function() {
      var click, tab_name, tab_settings;
      click = 'click.footer_lists_link';
      $(document).off(click);
      $(document).on(click, '.tpl-link-favorite', function() {
        return scroll_to_tab(footer_tabs.favorite.tab_index);
      });
      for (tab_name in footer_tabs) {
        tab_settings = footer_tabs[tab_name];
        if (!tab_settings.link) {
          continue;
        }
        $(document).on(click, tab_settings.link, tab_name, function(event) {
          var $this, actions, href, tab, this_class, _ref;
          event.preventDefault();
          tab = footer_tabs[event.data];
          $this = $(this);
          href = $this.attr('href');
          if (href !== '#') {
            $.ajax({
              url: href,
              dataType: 'html',
              success: on_footer_data_load
            });
          }
          $this.hide();
          _ref = tab.actions;
          for (this_class in _ref) {
            actions = _ref[this_class];
            if (!($this.is(this_class))) {
              continue;
            }
            actions = $.extend({}, actions);
            if (actions.links_to_show) {
              $this.siblings(actions.links_to_show).show();
            } else {
              $this.show();
            }
            if (actions.popup) {
              (function(popup) {
                return r('magnific-popup', function() {
                  return $.magnificPopup.open({
                    items: {
                      src: popup
                    },
                    mainClass: 'tpl-block-mfp-animating',
                    removalDelay: 200,
                    type: 'inline',
                    closeMarkup: '<div class="tpl-block-mfp-close"><i class="icon-popup-close"></i></div>'
                  });
                });
              })(actions.popup);
            }
          }
          $(tab.popups).find('.tpl-link-scroll').off(click).on(click, tab.tab_index, function(event) {
            scroll_to_tab(event.data);
            r('magnific-popup', function() {
              return $.magnificPopup.close();
            });
            return false;
          });
        });
      }
      $(document).on('click', '.tpl-block-item-remove.tpl-link-favorite-item-remove A,.tpl-block-item-remove.tpl-link-compare-item-remove A', function(event) {
        var $popup, $this;
        event.preventDefault();
        $this = $(this);
        if ($this.closest('.tpl-block-item-remove').hasClass('tpl-link-favorite-item-remove')) {
          $popup = $('#goodslist-favorite-remove-confirm');
        } else {
          $popup = $('#goodslist-compare-remove-confirm');
        }
        $popup.find('INPUT[name=url]').val($this.attr('href'));
        $popup.find('INPUT[name=items]').val($this.closest('FORM').find('INPUT[name="items[]"]').val());
        r('magnific-popup', function() {
          return $.magnificPopup.open({
            items: {
              src: $popup
            },
            mainClass: 'tpl-block-mfp-animating',
            removalDelay: 200,
            type: 'inline',
            closeMarkup: '<div class="tpl-block-mfp-close"><i class="icon-popup-close"></i></div>'
          });
        });
        return false;
      });
      $(document).on('click', '#goodslist-compare-remove-confirm BUTTON, #goodslist-favorite-remove-confirm BUTTON', function(event) {
        var $this, items;
        $this = $(this);
        items = $this.closest('.tpl-block-popup').find('INPUT[name=items]').val();
        if ($this.hasClass('tpl-value-confirm')) {
          $.ajax({
            url: $this.closest('.tpl-block-popup').find('INPUT[name=url]').val(),
            dataType: 'html',
            success: on_footer_data_load
          });
          $('.tpl-block-content .tpl-block-list-object').each(function() {
            var $itemsInput;
            $itemsInput = $(this).find('FORM INPUT[name="items[]"]');
            if ($itemsInput.val() === items) {
              if ($this.closest('.tpl-block-popup').is('#goodslist-compare-remove-confirm')) {
                $(this).find('FORM .tpl-link-compare-add').show().siblings('.tpl-link-compare-remove').hide();
              } else {
                $(this).find('FORM .tpl-link-favorite-add').show().siblings('.tpl-link-favorite-remove').hide();
              }
            }
            return true;
          });
        }
        return r('magnific-popup', function() {
          return $.magnificPopup.close();
        });
      });
    });
    scroll_to_tab = function(tab_index) {
      var tabSwitcher;
      tabSwitcher = $('.tpl-block-tabs--footer .tpl-block-tabs-switcher .tpl-block-tabs-tab').eq(tab_index);
      r('magnific-popup', function() {
        $.magnificPopup.close();
        tabSwitcher.triggerHandler('click');
        return $('html, body').animate({
          scrollTop: tabSwitcher.offset().top - 30
        });
      });
      return false;
    };

    /*
     * Добавление комментария
     */
    on_main_content_load(function() {
      var tabSwitcher;
      if (window.location.hash === '#comment-added') {
        tabSwitcher = $('.tpl-block-tabs-switcher .tpl-block-tabs-tab').eq(2).click();
        return $('html, body').animate({
          scrollTop: tabSwitcher.offset().top - 30
        });
      }
    });

    /*
    * Добавление комментария
     */
    $(function() {
      $('.tpl-block-comments-form FORM').on('submit', function() {
        var $this, email, name, regexp, text;
        $this = $(this);
        name = $this.find('INPUT[name="nc_comments_guest_name"]').val();
        email = $this.find('INPUT[name="nc_comments_guest_email"]').val();
        text = $this.find('TEXTAREA[name="nc_commentTextArea"]').val();
        regexp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (name && regexp.test(email) && text) {
          return true;
        }
        return false;
      });
    });

    /*
     * Подписка
     */
    $(function() {
      $('FORM.tpl-block-subscribe').on('submit', function() {
        var $email, $this, regexp;
        $this = $(this);
        $email = $this.find('INPUT[name="fields[Email]"]');
        $email.removeClass('tpl-state-error');
        regexp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (regexp.test($email.val())) {
          $.post($this.attr('action'), $this.serializeArray());
          r('magnific-popup', function() {
            return $.magnificPopup.open({
              items: {
                src: '#subscriber-added'
              },
              mainClass: 'tpl-block-mfp-animating',
              removalDelay: 200,
              type: 'inline',
              closeMarkup: '<div class="tpl-block-mfp-close"><i class="icon-popup-close"></i></div>'
            });
          });
        } else {
          $email.addClass('tpl-state-error').focus();
        }
        return false;
      });
    });

    /*
     * Нажатие на звёздочки рейтинга
     */
    on_main_content_load(function() {
      $(document).on('click', '.tpl-block-rating > A', function() {
        var $block, $this, c, index, responseHandler;
        c = '.tpl-block-rating';
        $this = $(this);
        $block = $this.closest(c);
        index = $(c).index($block);
        responseHandler = function(data) {
          var $data;
          $data = $('<div/>').html(data);
          $block.replaceWith($data.find(c).eq(index));
        };
        $.post($this.attr('href'), responseHandler);
        return false;
      });
    });

    /*
     * Удаление товара из корзины
     */
    $(function() {
      $("#cart-item-remove-confirm").on("click", function() {
        var button, form;
        $.magnificPopup.close();
        button = $(this).data('button');
        form = button.closest('form');
        form.find("input[name='" + button.attr("name") + "']").val(0);
        form.submit();
      });
    });
    on_main_content_load(function() {
      $(document).on("click", ".tpl-link-cart-remove", function(e) {
        e.preventDefault();
        $('#cart-item-remove-confirm').data('button', $(this));
        r("magnific-popup", function() {
          return $.magnificPopup.open({
            items: {
              src: "#cart-item-remove"
            },
            mainClass: "tpl-block-mfp-animating",
            removalDelay: 200,
            type: "inline",
            closeMarkup: '<div class="tpl-block-mfp-close"><i class="icon-popup-close"></i></div>'
          });
        });
        return false;
      });
    });

    /*
     * Выпадающие списки
     */
    close_all_dropdowns = function() {
      return $('.tpl-block-dropdown ul').slideUp(150);
    };
    on_main_content_load(function() {
      $('.tpl-block-dropdown ul').click(function(e) {
        return e.stopPropagation();
      });
      $('body').click(function() {
        return close_all_dropdowns();
      });
      return $('.tpl-block-dropdown').click(function() {
        close_all_dropdowns();
        $($(this).data('target')).css({
          'min-width': $(this).width()
        }).slideDown(200);
        return false;
      });
    });

    /*
     * Фокус поля поиска при изменении значения в выпадающем списке «область поиска»
     */
    $(function() {
      var search_block;
      search_block = $('header .tpl-block-search');
      return search_block.find('select[name=area]').change(function() {
        return search_block.find('input[name=search_query]').focus();
      });
    });

    /*
     * Обработка главного меню навигации (отключить переход на текущую страницу)
     */
    $(function() {
      var $current_link, href;
      $current_link = $('body > header .tpl-block-menu > div a.tpl-state-current');
      href = window.location.href.replace(/^https?\:\/\/[^/]+/, '');
      if (href === $current_link.attr('href')) {
        return $current_link.css({
          pointerEvents: 'none'
        });
      }
    });

    /*
     * Amplify
     */
    on_main_content_load(function() {
      r("amplify", function() {
        var b1, b2, restore, store;
        if ($("#nc_netshop_add_order_form").length) {
          store = function() {
            $(this).on("change keyup", function() {
              amplify.store(this.name, $(this).val());
            });
          };
          restore = function() {
            var $this, stored_value;
            $this = $(this);
            stored_value = amplify.store(this.name);
            if (typeof stored_value === 'string') {
              if (typeof stored_value === 'string') {
                $this.val(stored_value);
              }
              if (this.tagName === 'SELECT') {
                $this.trigger('chosen:updated');
              }
            }
          };
          b1 = $(".tpl-block-order-customer").find(":input:not([name='f_SignUp']):not([type='checkbox'])").each(store);
          b2 = $(".tpl-block-order-address").find(":input:not([type='checkbox'])").each(store);
          if ($(".tpl-block-auth .tpl-link-login").length) {
            b1.each(restore);
            b2.each(restore);
          }
        }
      });
    });

    /*
     * Инициализация основной части страницы при загрузке всей страницы
     * и при обновлении основной части страницы «аяксом»
     */
    window.tpl_init_content = function() {
      var fn, _i, _len;
      for (_i = 0, _len = main_content_load_handlers.length; _i < _len; _i++) {
        fn = main_content_load_handlers[_i];
        fn();
      }
      return true;
    };

    /*
     *  Загрузка custom.js и вызов всех слушателей on_main_content_load при готовности
     */
    r('custom', function() {
      $(function() {
        tpl_init_content();
      });
    });
  })(window.jQuery, window);

}).call(this);
