/*
//= require '../../../../lib/js/fastdom.js'
//= require '../../../../lib/js/jquery-3.3.1.min.js'
//= require '../../../../lib/js/bws/ui.js'
//= require '../../../../lib/js/mask.js'
//= require '../../../../lib/js/bws/form.js'
//= require '../../../../lib/js/owlcarousel/owl.carousel.js'
//= require '../../../../lib/js/perfect-scrollbar/js/perfect-scrollbar.jquery.js'
//= require '../../../../lib/js/perfect-scrollbar/js/perfect-scrollbar.min.js'
//= require '../../../../lib/js/elevatezoom/jquery.elevateZoom-3.0.8.min.js'
//= require '../../../../lib/js/date/jquery.datetimepicker.js'
//= require '../../../../lib/js/fancybox3/dist/jquery.fancybox.min.js'
//= require '../../../../lib/js/tinymce/js/tinymce/tinymce.min.js'
*/
var A;

A = {
  init: function() {
    A.w = $(window);
    A.W.init();
    A.P.init();
    A.FORM.init();
    return A.w.scroll(A.scroll);
  },
  scroll: function() {
    return A.P.scroll();
  },
  isMobile: function() {
    return $(window).width() <= 520;
  },
  // Работа с формами в этом проекте
  mail: /^([A-Za-z0-9_-]+\.)*[A-Za-z0-9_-]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.[A-Za-z]{2,6}$/,
  FORM: {
    globalPrepareValidate: function(i, r) {
      $(".error_text", i.$wrap).remove();
      return i.$wrap.removeClass('error good');
    },
    globalGood: function(i, r) {
      return i.$wrap.addClass('good');
    },
    globalBad: function(i, r) {
      i.$wrap.addClass('error');
      return $(i.$wrap).append($('<div class="error_text">' + r.errors.join("<br/>") + '</div>'));
    },
    init: function() {
      $.fn.FORM('setGlobalGood', A.FORM.globalGood);
      $.fn.FORM('setGlobalBad', A.FORM.globalBad);
      return $.fn.FORM('setPrepareValidate', A.FORM.globalPrepareValidate);
    }
  },
  setCookie: function(k, v, date) {
    var cook, domain;
    domain = ' domain=' + window.location.host + ';';
    cook = k + "=" + v + '; expires=' + new Date(date ? date : new Date().getTime() + 5184000000).toGMTString() + '; path=/;';
    document.cookie = cook + domain;
    console.log(cook + domain);
    return cook;
  },
  getCookie: function(name) {
    var pattern, regexp;
    pattern = "(?:; )?" + name + "=([^;]*);?";
    regexp = new RegExp(pattern);
    if (regexp.test(document.cookie)) {
      return decodeURIComponent(RegExp["$1"]);
    }
    return false;
  },
  reach: function(x) {
    A.reachYandex(x);
    return A.reachGoogle(x);
  },
  reachYandex: function(x) {
    return console.log('yandex', x);
  },
  //yaCounter56139889?.reachGoal(x)
  reachGoogle: function(x, y, z) {
    console.log('google', x, y, z);
    return typeof gtag === "function" ? gtag('event', x, {
      'event_category': 'conversion',
      'event_action': x
    }) : void 0;
  },
  ecommerce: {
    add: function(products) {
      var s;
      window.dataLayer = window.dataLayer || [];
      s = {
        ecommerce: {
          currencyCode: "RUB",
          add: {
            products: products
          }
        }
      };
      console.log('add', s);
      return window.dataLayer.push(s);
    },
    remove: function(products) {
      var s;
      window.dataLayer = window.dataLayer || [];
      s = {
        ecommerce: {
          currencyCode: "RUB",
          remove: {
            products: products
          }
        }
      };
      console.log('remove', s);
      return window.dataLayer.push(s);
    },
    detail: function(products) {
      var s;
      window.dataLayer = window.dataLayer || [];
      s = {
        ecommerce: {
          currencyCode: "RUB",
          detail: {
            products: products
          }
        }
      };
      console.log('detail', s);
      return window.dataLayer.push(s);
    },
    purchase: function(id, products) {
      var s;
      window.dataLayer = window.dataLayer || [];
      s = {
        ecommerce: {
          currencyCode: "RUB",
          purchase: {
            actionField: {
              id: id
            },
            products: products
          }
        }
      };
      console.log('purchase', s);
      return window.dataLayer.push(s);
    }
  }
};

$(document).ready(A.init);

// u - url
// d - data
// c - callback
// cd - callback data
var API, API_THEME;

API = function(u, d = {}, c = null, cd = {}) {
  var url;
  d['nocache'] = (new Date()).getTime();
  url = "/api/" + u + "/";
  console.log(url, d);
  return $.ajax({
    url: url,
    type: "POST",
    dataType: d.dataType !== void 0 ? d.dataType : "html",
    data: d,
    success: function(data) {
      if (c !== null) {
        return typeof c === "function" ? c(data, cd) : void 0;
      }
    },
    error: function() {
      return typeof c === "function" ? c({
        error: 1
      }, cd) : void 0;
    }
  });
};

API_THEME = 'themes.flavomarket/';

A.F = {
  recall: function(f) {
    var $f, $res, s;
    f = ($f = $(f)).FORM();
    s = f.json();
    //s.dataType="JSON"
    $res = $(".res", $f).hide(300);
    console.log('recall', s);
    f.validate({
      success: function() {
        console.log(s);
        if (s.phone === '' || s.phone === void 0) {
          return alert('Введите номер телефона');
        } else {
          API(API_THEME + 'sendForm', s, function(data) {
            return console.log(data);
          });
          A.W.openThankYou();
          return $f.replaceWith('<p class="send_success">Данные успешно отправлены</p>');
        }
      }
    });
    return false;
  }
};

/*
review:(f)->
  f = ($f = $(f)).FORM()
  s = f.json()
  $res = $(".res",$f).hide(300)
  s.mark = parseInt($(".catalog-rate",$f).attr('data-value'));
  #console.log s
  if(s.mark < 0)
    A.notify($res,'Выберите оценку')
    return false
  f.validate
    success:->
      if s.phone==''
        A.notify($res,'Введите номер телефона')
      else if s.text==''
        A.notify($res,'Введите текст отзыва')
      else
        API API_THEME+'addReviewForItem',s, #(data)->console.log(data)
        A.W.openThankYouReview()
        #$f.replaceWith('<p>Данные успешно отправлены</p>')

  false
 */

var H;

H = {
  menu: {},
  selected: {},
  top_selected: null,
  inited: false,
  dir: '', // up | down | left | right
  title: null,
  data: null,
  scroll: [],
  isLoading: false,
  ready: function() {
    if (!H.inited) {
      $(window).on('popstate', H.switchByWindow);
      H.inited = true;
      H.body = $("#content");
      H.title = $("title");
      H.keywords = $("meta[name=keywords]");
      H.description = $("meta[name=description]");
      H.title = $("title");
      //H.switch()
      H.$html = $("html,body");
      $(window).on('scroll', H.onScroll);
      return typeof callibriInit === "function" ? callibriInit() : void 0;
    }
  },
  onScroll: function() {
    if (!H.isLoading) {
      return H.scroll[window.location.href] = H.$html.scrollTop();
    }
  },
  reload: function() {
    return H.switch();
  },
  formGo: function(form) {
    var $f, action, path, s;
    s = ($f = $(form)).serialize();
    action = $f.attr('action');
    if (action === void 0) {
      action = window.location.pathname;
    }
    //console.log action
    H.go(path = action + '?' + s);
    return false;
  },
  go: function(x, data = null, title = '', reload = true) {
    var y;
    if (!x) {
      return false;
    }
    if (x.substr(0, 1) === '/') {
      x = x.substr(1);
    }
    y = '/' + x;
    H.data = data;
    history.pushState(data, title, y);
    if (reload) {
      return H.switch();
    }
  },
  setTitle: function(x) {
    return H.title.text(x);
  },
  switchByWindow: function(x) {
    console.log('switchByWindow', x);
    //if x == null
    return H.switch(x);
  },
  switch: function(event = null) {
    var path, url;
    //console.log 'switch',x
    path = H.parse();
    url = path.join("/");
    if (url === "/" || url === "") {
      url = "/?justContent=1";
    } else {
      url = `/${url}/?justContent=1`;
    }
    if (window.location.search.length > 0) {
      url += '&' + window.location.search.substr(1);
    }
    //console.log url
    H.isLoading = true;
    A.P.$show_more = null;
    $(".zoomContainer").remove();
    return $.ajax({
      url: url,
      //url:"/#{url}/?mini=1"
      dataType: "JSON",
      success: function(data) {
        var $data, $html, i, j, ref, ref1, s, scrollTo;
        //console.log data
        console.log('time_compile', data.time_compile, 'bd_time', data.time_bd, data.logs);
        if (typeof data.location === "string" && data.location !== "") {
          return H.go(data.location);
        } else {
          //console.log 'TITLE',data.title
          H.title.text(data.title);
          $data = $(data.content);
          $html = $($data[0]);
          H.setTitle(data.data.title);
          H.keywords.attr('content', data.keywords);
          H.description.attr('content', data.description);
          $('head meta[property^="og"]').remove();
          $('head').append($(data.og));
          scrollTo = 0;
          if (H.scroll[window.location.href] !== void 0 && event !== null) {
            scrollTo = H.scroll[window.location.href];
          }
          //$hide = $(".b_content:not(.hide)").addClass('hide')
          //$(".b_content").remove()
          //$.fn.TABLE('allDestroy')
          H.body.html($html);
          A.P.initMini($html);
          if ($data.length > 1) {
            for (i = j = 1, ref = $data.length - 1; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) {
              s = document.createElement('script');
              if ((ref1 = $data[i].tagName) === 'SCRIPT' || ref1 === 'script') {
                s.innerHTML = $($data[i]).html();
                H.body[0].appendChild(s);
              }
            }
          }
          A.P.initLazy($html);
          H.$html.scrollTop(scrollTo);
          A.P.scroll();
          H.isLoading = false;
          return setTimeout(function() {
            return typeof callibriInit === "function" ? callibriInit() : void 0;
          }, 10);
        }
      },
      error: function() {
        return console.log('history error ');
      }
    });
  },
  SEARCH: {
    set: function(s, reload = false) {
      var x;
      x = window.location.pathname + '?' + s;
      return H.go(x, null, '', reload);
    },
    parse: function() {
      var i, pos, res, v, x;
      res = {};
      if (window.location.search.length > 0) {
        x = window.location.search.substr(1).split('&');
        for (i in x) {
          v = x[i];
          pos = v.indexOf('=');
          if (pos >= 0) {
            res[v.substr(0, pos)] = v.substr(pos + 1);
          } else {
            res[v] = null;
          }
        }
      }
      return res;
    },
    setValue: function(key, value, reload = false) {
      var s, x;
      x = H.SEARCH.parse();
      x[key] = value;
      s = H.SEARCH.toString(x);
      return H.SEARCH.set(s);
    },
    toString: function(a) {
      var i, res, v;
      res = [];
      for (i in a) {
        v = a[i];
        res.push(i + '=' + (v != null ? v : ''));
      }
      return res.join('&');
    },
    get: function(x) {
      var e;
      try {
        return decodeURI(H.SEARCH.parse()[x]);
      } catch (error) {
        e = error;
        return H.SEARCH.parse()[x];
      }
    }
  },
  //H.SEARCH.parse()[x]
  parse: function(x = null) {
    var a, i, j, len, o;
    a = x !== null ? x.split('/') : window.location.pathname.split("/");
    o = [];
    for (j = 0, len = a.length; j < len; j++) {
      i = a[j];
      if (i !== "") {
        o.push(i);
      }
    }
    return o;
  }
};

$(window).ready(H.ready);

//-------------------------------------------------
// A.I = РАБОТА С ПОЛЯМИ ВВОДА
//-------------------------------------------------
A.I = {
  waitInput: function(x) {
    return $(x).each(function() {
      var button, click, val;
      button = $(this);
      click = button.attr('onclick');
      val = $.trim(button.val());
      return button.attr('onclick', '').attr('data-val', val).val(val === "" ? '' : 'Отправляется...').addClass("wait").attr('data-onclick', click).attr('disabled', 'disabled');
    });
  },
  unwaitInput: function(x) {
    return $(x).each(function() {
      var b;
      b = $(this);
      return b.val(b.attr('data-val')).removeClass("wait").attr('onclick', b.attr('data-onclick')).removeAttr('disabled');
    });
  },
  waitButton: function(x) {
    return $(x).each(function() {
      var button, click, val;
      button = $(this);
      click = button.attr('onclick');
      val = $.trim(button.html());
      if (val !== "?") {
        return button.attr('onclick', '').attr('data-val', val).html(val === "" || val === "&nbsp;" ? '' : 'Отправляется...').addClass("wait").attr('data-onclick', click).attr('disabled', 'disabled');
      }
    });
  },
  unwaitButton: function(x) {
    return $(x).each(function() {
      var b;
      b = $(this);
      return b.html(b.attr('data-val')).removeClass("wait").attr('onclick', b.attr('data-onclick')).removeAttr('disabled');
    });
  }
};

A.P = {
  $lazy: null,
  $bg_lazy: null,
  $show_more: null,
  scrollTimeout: null,
  getScrollTop: function() {
    return Math.max(A.P.body.scrollTop(), A.P.$body.scrollTop(), A.P.$html.scrollTop());
  },
  scrollToTop: function(x = 0) {
    A.P.$body.scrollTop(x);
    return A.P.$html.scrollTop(x);
  },
  scrollToTopAnimate: function() {
    A.P.$body.animate({
      scrollTop: 0
    }, 500);
    return A.P.$html.animate({
      scrollTop: 0
    }, 500);
  },
  scrollToAnimate: function(x) {
    var offset;
    offset = $(x).offset().top - 100;
    A.P.$body.animate({
      scrollTop: offset
    }, 500);
    return A.P.$html.animate({
      scrollTop: offset
    }, 500);
  },
  playVideo: function() {
    var v;
    $(".video_wrap").remove();
    $("video").removeClass('dn');
    v = document.getElementById('video');
    return v.play();
  },
  init: function() {
    A.P.body = $("body");
    A.P.$body = $("body");
    A.P.$html = $("html");
    A.P.html = $("html,body");
    A.P.$show_more = null;
    A.P.initLazy();
    A.P.initMini();
    $('#b_add-basket .btn').click(function() {
      return $('#b_add-basket').removeClass('open');
    });
    $(document).click(function(e) {
      var $t;
      $t = $(this);
      if ($t.closest('.dadata_res').length > 0 || $t.hasClass('dadata_res')) {

      } else {
        return $(".dadata_res").hide();
      }
    });
    A.P.$totop = $("#totop");
    $("#mob_menu").on('touchstart', function(e) {
      console.log('move');
      return e.originalEvent.stopPropagation();
    });
    return $("#mob_menu").on('touchmove', function(e) {
      console.log('move');
      return e.originalEvent.stopPropagation();
    });
  },
  setFilial: function(x) {
    return API(API_THEME + '/setFilial', {
      filial: x
    }, function(data) {
      return window.location.reload();
    });
  },
  initCalculator: function($html) {
    return $(".calculator .el", $html).click(function() {
      $(this).toggleClass('selected');
      return A.P.loadCalculatorCount();
    });
  },
  loadCalculatorCount: function() {
    var s;
    s = {
      dataType: "JSON"
    };
    $(".calculator .el.selected").each(function() {
      var text_id;
      text_id = $(this).attr('data-text_id');
      if (!s[text_id]) {
        s[text_id] = [];
      }
      return s[text_id].push($(this).attr('data-id'));
    });
    //a.push($(@).attr('data-id'))
    //prop_id = $(".calculator").attr('data-prop')
    return API(API_THEME + 'getCalculatorCount', s, function(data) {
      $(".calculator_res").toggleClass('show', data.count > 0);
      $(".calculator_res .count").text(data.count);
      return $(".calculator_res .btn").attr('href', data.link);
    });
  },
  openMenu: function() {
    $("#mob_menu").addClass('open');
    return $("#d_top").addClass('open');
  },
  closeMenu: function() {
    $("#mob_menu").removeClass('open');
    return $("#d_top").removeClass('open');
  },
  toggleMenu: function() {
    if ($("#mob_menu").hasClass('open')) {
      return this.closeMenu();
    } else {
      return this.openMenu();
    }
  },
  scroll: function() {
    var bottom, height;
    //top = A.P.getScrollTop()
    height = window.innerHeight;
    bottom = height + 600;
    //console.log 'SCROLL'
    //A.P.$html.addClass('scroll')
    //if A.P.scrollTimeout!=null
    //  clearTimeout(A.P.scrollTimeout)
    //A.P.scrollTimeout = setTimeout(A.P.aScroll,300)
    //A.P.$totop.toggleClass('show',A.w.scrollTop()>100)
    A.P.$html.removeClass('scroll');
    if (A.P.$lazy != null) {
      A.P.$lazy.each(function() {
        var b;
        b = this.getBoundingClientRect();
        if (b.y <= height) {
          return this.src = this.getAttribute('data-img');
        }
      });
    }
    if (A.P.$bg_lazy != null) {
      A.P.$bg_lazy.each(function() {
        var b;
        b = this.getBoundingClientRect();
        //if($(@).hasClass('inst'))
        //  console.log(b,bottom)
        if (b.y <= height) {
          return this.style.backgroundImage = 'url(' + this.getAttribute('data-img') + ')';
        }
      });
    }
    if (A.P.$show_more) {
      return A.P.$show_more.each(function() {
        var b;
        b = this.getBoundingClientRect();
        if (b.y <= bottom) {
          return A.P.$show_more.click();
        }
      });
    }
  },
  aScroll: function() {},
  firstInit: function($html = A.P.body) {},
  dadataSearch: function() {
    var $par, $res, $t, val;
    $t = $(this);
    val = $t.val();
    $par = $t.closest("[data-input]");
    $res = $(".dadata_res", $par);
    console.log($res, $par);
    return API('common.dadata/searchAddressForShop', {
      q: val,
      dataType: 'JSON'
    }, function(data) {
      var $li, i, j, len, results;
      console.log(data);
      $res.html('').show();
      results = [];
      for (j = 0, len = data.length; j < len; j++) {
        i = data[j];
        if (i.title !== '') {
          $li = $('<div>' + i.title + '</div>');
          $li.click(function() {
            var $tt;
            $tt = $(this);
            $t.val($tt.text());
            return $res.hide();
          });
          results.push($res.append($li));
        } else {
          results.push(void 0);
        }
      }
      return results;
    });
  },
  //$(res).html($list)
  initLazy: function($html = A.P.$body) {
    A.P.$lazy = $(".lazy", $html);
    A.P.$bg_lazy = $(".bg_lazy", $html);
    return A.P.scroll();
  },
  checkItemPrice: function() {
    var count;
    count = $(".counter input").val();
    console.log('count', count);
    return $("#b_item .price_value").each(function() {
      var $t, price;
      $t = $(this);
      price = parseFloat($t.text().replace(/[^\d]/gi, ''));
      if ($t.attr('data-price')) {
        price = parseFloat($t.attr('data-price'));
      } else {
        $t.attr('data-price', price);
      }
      $t.text($.fn.CART('fprice', price * count));
      return console.log($t, $t.text(), price, $.fn.CART('fprice', price));
    });
  },
  initMini: function($html = A.P.body) {
    var $imgs;
    $.fn.SHOP('init', $html);
    $("#b_nav .menu a ", $html).click(function() {
      return $("#b_nav").removeClass('show');
    });
    $("#mob_menu,#mob_menu a", $html).click(function() {
      return A.P.closeMenu();
    });
    if ($(".show_more", $html).length > 0) {
      A.P.$show_more = $(".show_more", $html);
    }
    A.P.scroll();
    A.P.initCalculator($html);
    $.fn.FILTER('init', $html);
    $.fn.CART('initBasket', $html);
    $.fn.ITEM('init', $html);
    $.fn.CART('initConfirm', $html);
    $.fn.CONSTRUCTOR('init', $html);
    $(".faq .title", $html).click(function() {
      return $(this).parent().toggleClass('open');
    });
    $(".orders_list .more", $html).click(function() {
      return $(this).closest('.order').toggleClass('open');
    });
    ($imgs = $("#b_item .imgs .img", $html)).click(function() {
      var $c, $t;
      console.log('click');
      $t = $(this);
      $imgs.removeClass('selected');
      $t.addClass('selected');
      //$("#main_img").attr('data-fancybox-index',$t.index()).css('background-image','url('+$t.attr('data-src')+')')
      $("#main_img").attr('data-index', $t.index()).css('background-image', 'url(' + $t.attr('data-src') + ')');
      if (($c = $(`.video_wrap[data-id=${$t.index()}]`)).length > 0) {
        $c.show();
        $c.html($c.attr('data-text'));
        return $("#main_img").hide();
      } else {
        $(".video_wrap").html('');
        return $("#main_img").show().attr('data-index', $t.index()).css('background-image', 'url(' + $t.attr('data-src') + ')');
      }
    });
    $('#main_img', $html).click(function() {
      var map;
      map = [];
      $('[data-fancybox="gallery"]').each(function() {
        return map.push({
          src: $(this).attr('href')
        });
      });
      return $.fancybox.open(map, {
        hash: false,
        index: $(this).attr('data-index')
      });
    });
    $("[data-fancybox-group]", $html).fancybox({
      hash: false
    });
    $("[data-input=date] input", $html).datetimepicker({
      format: 'd-m-Y',
      timepicker: false,
      minDate: new Date(),
      scrollInput: false,
      closeOnDateSelect: true
    });
    $(".dadata_input", $html).keyup(A.P.dadataSearch).on('paste', A.P.dadataSearch);
    $(".toggler .toggle_title", $html).click(function() {
      return $(this).parent().toggleClass('open');
    });
    $("._cashback").change(function() {
      var $t, max, val;
      $t = $(this);
      max = parseFloat($t.attr('data-max'));
      val = parseFloat($t.val());
      if (isNaN(val)) {
        val = 0;
      }
      if (val < 0) {
        val = 0;
      }
      if (val > max) {
        val = max;
      }
      return $t.val(val);
    });
    $('#open-mob-menu', $html).click(function() {
      $('#mobile_menu').addClass('selected');
      $('#hover').addClass('selected');
      return $('body, html').addClass('hidden');
    });
    $('#close_mobile, #hover, #mobile_menu a', $html).click(function() {
      $('#mobile_menu').removeClass('selected');
      $('#hover').removeClass('selected');
      return $('body, html').removeClass('hidden');
    });
    $('._open-title', $html).click(function() {
      var b, p, t;
      t = $(this);
      p = t.closest('._open-parent');
      b = p.find('._open-body');
      return b.slideToggle(300);
    });
    $("._ps", $html).perfectScrollbar({
      suppressScrollX: true
    });
    $(".i-icon.i-calendar", $html).click(function() {
      return $("[data-name=ddate] input").datetimepicker('show');
    });
    $(".elite_item", $html).each(function() {
      var $elite, $img;
      $elite = $(this);
      $img = $(".img", $elite);
      $imgs = $(".imgs button", $elite);
      return $imgs.click(function() {
        var $t;
        $t = $(this);
        $imgs.removeClass('selected');
        $t.addClass('selected');
        return $img.css('background-image', 'url(' + $t.attr('data-src') + ')');
      });
    });
    $('.images', $html).owlCarousel({
      loop: true,
      nav: true,
      dots: false,
      autoplay: false,
      smartSpeed: 200,
      autoHeight: true,
      animateOut: 'fadeOut',
      navText: ['<div class="arrow prev"></div>', '<div class="arrow next"></div>'],
      items: 1
    });
    /*
    $('.main-slider',$html).owlCarousel
      loop: true
      nav: false
      dots: false
      autoplay: true
      smartSpeed: 1000
      autoplayTimeout: 10000
      autoHeight: true
      animateOut: 'fadeOut'
      #navText: ["<button class='btn-arrow btn-gray'><div class='animate-arrow aa-prev'></div></button>","<button class='btn-arrow btn-gray'><div class='animate-arrow'></div></button>"]
      responsive:
        0: items: 1
        521: items: 1
        1000: items: 1
     */
    $(".service_catalog2", $html).owlCarousel({
      loop: false,
      margin: 20,
      dots: true,
      nav: true,
      //slideBy: 1
      //autoHeight: true
      autoWidth: true
    });
    //items : 1
    $(".item_owl", $html).owlCarousel({
      loop: true,
      margin: 0,
      dots: true,
      nav: true,
      slideBy: 1,
      autoHeight: true,
      items: 1
    });
    $(".main_slider", $html).owlCarousel({
      loop: true,
      //nav: true
      margin: 0,
      dots: true,
      slideBy: 1,
      //smartSpeed: 500
      //autoplayTimeout: 10000
      autoHeight: true,
      //autoplay: true
      items: 1
    });
    //stopOnHover : true
    //autoplayHoverPause:true
    $('.main_slider').on('click', '.slide', function(e) {
      //console.log(e.target,e.target.tagName,$(e.target.tagName).attr('href'),e.target.tagName=="A",e.target.getAttribute('href'))
      e.preventDefault();
      e.stopPropagation();
      if (e.target.tagName === "A") {
        H.go(e.target.getAttribute('href'));
      }
      if (e.target.tagName === "IMG") {
        return H.go($(e.target).parent().attr('href'));
      }
    });
    $('.main_slider .slide,.main_slider_mob .slide', $html).on('mouseenter', function(e) {
      return $(this).closest('.owl-carousel').trigger('stop.owl.autoplay');
    });
    $('.main_slider .slide,.main_slider_mob .slide', $html).on('mouseleave', function(e) {
      return $(this).closest('.owl-carousel').trigger('play.owl.autoplay');
    });
    $(".f-price-box", $html).each(function() {
      var $bar, $max, $min, $p, $p1, $p2, blur, diff, getMax, getMaxPercent, getMin, getMinPercent, getMousePercent, getRect, getValueByPercent, max, min, moveMax, moveMin, setMax, setMin, startMoveMax, startMoveMin, stopMax, stopMin, timeout, touchMoveMax, touchMoveMin;
      $p = $(this);
      min = parseFloat($p.attr('data-min'));
      max = parseFloat($p.attr('data-max'));
      $bar = $(".fp-line", $p);
      diff = max - min;
      $p1 = $(".fpc1", $p);
      $p2 = $(".fpc2", $p);
      getRect = function() {
        return $(".filter-price", $p)[0].getBoundingClientRect();
      };
      getMousePercent = function(x) {
        var rect;
        rect = getRect();
        return Math.max(0, Math.min(100, (x - rect.x) / rect.width * 100));
      };
      setMax = function() {
        var p, page, url;
        url = new URL(window.location.href);
        url.searchParams.delete('max');
        url.searchParams.set('max', getMax());
        p = H.parse(url.pathname);
        page = parseInt(p[p.length - 1]);
        if (!isNaN(page)) {
          delete p[p.length - 1];
        }
        url.pathname = '/' + p.join("/");
        return H.go(url.pathname + url.search);
      };
      setMin = function() {
        var p, page, url;
        url = new URL(window.location.href);
        url.searchParams.delete('min');
        url.searchParams.set('min', getMin());
        p = H.parse(url.pathname);
        page = parseInt(p[p.length - 1]);
        if (!isNaN(page)) {
          delete p[p.length - 1];
        }
        url.pathname = '/' + p.join("/");
        return H.go(url.pathname + url.search);
      };
      getValueByPercent = function(x) {
        return ((diff * x / 100) + min).toFixed(0);
      };
      moveMax = function(e) {
        var minp, p;
        p = getMousePercent(e.clientX);
        p = Math.max(p, minp = getMinPercent());
        $max.val(getValueByPercent(p));
        return $bar.css({
          width: (p - minp) + '%'
        });
      };
      touchMoveMax = function(e) {
        var minp, p;
        p = getMousePercent(e.touches[0].clientX);
        p = Math.max(p, minp = getMinPercent());
        $max.val(getValueByPercent(p));
        return $bar.css({
          width: (p - minp) + '%'
        });
      };
      stopMax = function() {
        $(document).off('mousemove', moveMax);
        $(document).off('mouseup', stopMax);
        $(document).off('touchmove', touchMoveMax);
        $(document).off('touchend', stopMax);
        return setMax();
      };
      startMoveMax = function() {
        var rect;
        rect = $(".filter-price", $p)[0].getBoundingClientRect();
        $(document).on('mousemove', moveMax);
        $(document).on('mouseup', stopMax);
        $(document).on('touchmove', touchMoveMax);
        return $(document).on('touchend', stopMax);
      };
      moveMin = function(e) {
        var maxp, p;
        p = getMousePercent(e.clientX);
        p = Math.min(p, maxp = getMaxPercent());
        $min.val(getValueByPercent(p));
        return $bar.css({
          left: p + '%',
          width: (maxp - p) + '%'
        });
      };
      touchMoveMin = function(e) {
        var maxp, p;
        p = getMousePercent(e.touches[0].clientX);
        p = Math.min(p, maxp = getMaxPercent());
        $min.val(getValueByPercent(p));
        return $bar.css({
          left: p + '%',
          width: (maxp - p) + '%'
        });
      };
      stopMin = function() {
        $(document).off('mousemove', moveMin);
        $(document).off('mouseup', stopMin);
        $(document).off('touchmove', touchMoveMin);
        $(document).off('touchend', stopMin);
        return setMin();
      };
      startMoveMin = function() {
        var rect;
        rect = $(".filter-price", $p)[0].getBoundingClientRect();
        $(document).on('mousemove', moveMin);
        $(document).on('mouseup', stopMin);
        $(document).on('touchmove', touchMoveMin);
        return $(document).on('touchend', stopMin);
      };
      $p1.on('mousedown', startMoveMin);
      $p2.on('mousedown', startMoveMax);
      $p1.on('touchstart', startMoveMin);
      $p2.on('touchstart', startMoveMax);
      blur = function() {
        var _max, _min, left, width;
        _min = getMin();
        _max = getMax();
        if (_min > _max || _max < _min) {
          $max.val(_min);
        }
        left = getMinPercent();
        width = getMaxPercent() - left;
        return $bar.css({
          left: left + '%',
          width: width + '%'
        });
      };
      timeout = null;
      $min = $("input:eq(0)", $p).blur(function() {
        blur();
        return setMin();
      }).keyup(function() {
        clearTimeout(timeout);
        return setTimeout(setMin, 750);
      });
      $max = $("input:eq(1)", $p).blur(function() {
        blur();
        return setMax();
      }).keyup(function() {
        clearTimeout(timeout);
        return setTimeout(setMax, 750);
      });
      getMax = function() {
        var v;
        v = parseFloat($max.val());
        if (isNaN(v) || v > max) {
          v = max;
        }
        $max.val(v);
        return v;
      };
      getMin = function() {
        var v;
        v = parseFloat($min.val());
        if (isNaN(v) || v <= min) {
          v = min;
        }
        $min.val(v);
        return v;
      };
      getMinPercent = function() {
        var v;
        v = getMin();
        return (v - min) / diff * 100;
      };
      getMaxPercent = function() {
        var v;
        v = getMax();
        return (v - min) / diff * 100;
      };
      blur();
      return $p.on('destroyed', function() {
        return getMin = getMinPercent = getMaxPercent = $max = $min = $bar = null;
      });
    });
    $(".count_slider_wrap", $html).each(function() {
      var $bar, $min, $p, $p1, blur, diff, getMin, getMinPercent, getMousePercent, getRect, getValueByPercent, max, min, moveMin, setMin, startMoveMin, stopMin, touchMoveMin;
      $p = $(this);
      min = parseFloat($p.attr('data-min'));
      max = parseFloat($p.attr('data-max'));
      $bar = $(".bar", $p);
      diff = max - min;
      $p1 = $(".point", $p);
      getRect = function() {
        return $(".count_slider", $p)[0].getBoundingClientRect();
      };
      getMousePercent = function(x) {
        var rect;
        rect = getRect();
        return Math.max(0, Math.min(100, (x - rect.x) / rect.width * 100));
      };
      getValueByPercent = function(x) {
        return ((diff * x / 100) + min).toFixed(0);
      };
      setMin = function() {
        return $min.keyup();
      };
      touchMoveMin = function(e) {
        var p;
        p = getMousePercent(e.touches[0].clientX);
        $min.val(getValueByPercent(p)).keyup();
        return $bar.css({
          width: p + '%'
        });
      };
      moveMin = function(e) {
        var p;
        p = getMousePercent(e.clientX);
        $min.val(getValueByPercent(p)).keyup();
        return $bar.css({
          width: p + '%'
        });
      };
      stopMin = function() {
        $(document).off('mousemove', moveMin);
        $(document).off('mouseup', stopMin);
        $(document).off('touchmove', touchMoveMin);
        $(document).off('touchend', stopMin);
        return setMin();
      };
      startMoveMin = function() {
        //rect = $p[0].getBoundingClientRect()
        $(document).on('mousemove', moveMin);
        $(document).on('mouseup', stopMin);
        $(document).on('touchmove', touchMoveMin);
        return $(document).on('touchend', stopMin);
      };
      $p1.on('mousedown', startMoveMin);
      $p1.on('touchstart', startMoveMin);
      blur = function() {
        var m, width;
        m = getMin();
        if (m >= max) {
          m = max;
        }
        $min.val(m);
        width = (m - min) / diff * 100;
        return $bar.css({
          width: width + '%'
        });
      };
      $min = $("input:eq(0)", $p).blur(function() {
        blur();
        return setMin();
      });
      getMin = function() {
        var v;
        v = parseFloat($min.val());
        if (isNaN(v) || v <= min) {
          v = min;
        }
        $min.val(v);
        return v;
      };
      getMinPercent = function() {
        var v;
        v = getMin();
        return (v - min) / diff * 100;
      };
      blur();
      return $p.on('destroyed', function() {
        var $max, getMaxPercent;
        return getMin = getMinPercent = getMaxPercent = $max = $min = $bar = null;
      });
    });
    $(".counter", $html).each(function() {
      var $i, $minus, $plus, $t, getVal, max, setVal;
      $t = $(this);
      $plus = $(".plus,.up", $t);
      $minus = $(".minus,.down", $t);
      $i = $("input", $t);
      max = parseInt($i.attr('data-max'));
      getVal = function() {
        return parseInt($i.val());
      };
      $plus.click(function() {
        return setVal(getVal() + 1);
      });
      $minus.click(function() {
        return setVal(getVal() - 1);
      });
      $i.blur(function() {
        return setVal(getVal());
      });
      return setVal = function(x) {
        x = parseInt(x);
        if (isNaN(x)) {
          x = 1;
        }
        if (x <= 0) {
          x = 1;
        }
        if (!isNaN(max)) {
          if (x >= max) {
            x = max;
          }
        }
        $i.val(x).change();
        return A.P.checkItemPrice();
      };
    });
    $("._window_close", $html).click(A.W.close);
    $(".select:not(.inited)", $html).addClass('inited').each(function() {
      var $options, $t, $title;
      $t = $(this);
      $title = $("._text");
      $options = $(".options");
      $title.click(function() {
        return $t.toggleClass('open');
      });
      return $(".option").click(function() {
        var $option;
        $option = $(this);
        $title.text($option.text()).attr('data-value', $option.attr('data-value'));
        return $t.removeClass('open');
      });
    });
    $(".sizes_wrap", $html).each(function() {
      var $btns, $cashback, $def, $p, $price;
      $p = $(this);
      $price = $(".price .txt", $p);
      $cashback = $(".bonus .nowrap", $p);
      $btns = $(".sizes .btn", $p);
      console.log($price, $btns);
      $btns.click(function() {
        var $t;
        $("#b_item .price_value").attr('data-price', '');
        $(".sizes .btn", $p).removeClass('fill').addClass('outline');
        console.log('click', $btns);
        $t = $(this);
        $t.addClass('fill').removeClass('outline');
        $price.html($t.attr('data-fprice'));
        $cashback.html($t.attr('data-fcashback'));
        return A.P.checkItemPrice();
      });
      $def = $(".sizes .default", $p);
      console.log('def', $def, $btns);
      if ($def.length > 0) {
        return $def.click();
      } else {
        return $($btns[0]).click();
      }
    });
    $(".item_price_wrap", $html).each(function() {
      var $buy_button, $cashback, $labels, $old, $price, $wrap, cashback_percent, id, per_count, percent, price;
      $wrap = $(this);
      if (($buy_button = $(".buy_button:not(.inited)", $wrap)).addClass('inited').length > 0) {
        $old = $(".old_price span", $wrap);
        $price = $(".total_item_price span", $wrap);
        $cashback = $(".total_cashback span", $wrap);
        price = parseFloat($buy_button.attr('data-price'));
        per_count = parseFloat($buy_button.attr('data-per_count'));
        cashback_percent = parseFloat($buy_button.attr('data-cashback_percent'));
        id = parseInt($buy_button.attr('data-id'));
        percent = parseFloat($buy_button.attr('data-percent'));
        if (isNaN(percent)) {
          percent = 1;
        }
        switch (parseInt($buy_button.attr('data-type'))) {
          case 1:
            $(".count", $wrap).change(function() {
              var cashback, old, prop_prices, real_price, total, val;
              val = parseInt($(this).val());
              if (isNaN(val)) {
                val = 1;
              }
              prop_prices = A.P.getPropPrices(id);
              real_price = price + prop_prices.item_value + parseFloat((price * prop_prices.item_percent).toFixed(0));
              total = val * real_price;
              old = total;
              total *= percent;
              cashback = total * cashback_percent;
              total = parseFloat(total.toFixed(0));
              $old.html($.fn.CART('fprice', old));
              $price.html($.fn.CART('fprice', total));
              return $cashback.html($.fn.CART('fprice', cashback));
            });
            break;
          case 2:
            $(".per_count", $wrap).keyup(function() {
              var add_real_per_count, add_real_price, cashback, old, prop_prices, real_per_count, real_price, total, val;
              val = parseInt($(this).val());
              if (isNaN(val)) {
                val = 1;
              }
              if (val < 1) {
                val = 1;
              }
              prop_prices = A.P.getPropPrices(id);
              add_real_price = parseFloat((price * prop_prices.item_percent).toFixed(0));
              if (isNaN(add_real_price)) {
                add_real_price = 0;
              }
              add_real_per_count = parseFloat((per_count * prop_prices.component_percent).toFixed(0));
              if (isNaN(add_real_per_count)) {
                add_real_per_count = 0;
              }
              real_price = price + prop_prices.item_value + add_real_price;
              real_per_count = per_count + prop_prices.component_value + add_real_per_count;
              //console.log 'real_per_count',price,per_count,real_price,real_per_count,add_real_price,add_real_per_count
              total = real_price + val * real_per_count;
              old = total;
              total *= percent;
              cashback = total * cashback_percent;
              $old.html($.fn.CART('fprice', old));
              $price.html($.fn.CART('fprice', total));
              return $cashback.html($.fn.CART('fprice', cashback));
            }).blur(function() {
              var val;
              val = parseInt($(this).val());
              if (isNaN(val)) {
                val = 1;
              }
              if (val < 1) {
                val = 1;
              }
              return $(this).val(val);
            });
            break;
          case 3:
            ($labels = $("._r-label", $wrap)).click(function() {
              var $cb, $r, $t, cashback, old, per_price, prop_prices, real_price, total;
              $t = $(this);
              $cb = $("input[type=radio]", $t);
              $r = $(".radio", $t);
              $labels.removeClass('selected');
              $(".radio", $labels).removeClass('selected');
              $t.addClass('selected');
              $r.addClass('selected');
              price = parseFloat($t.attr('data-price'));
              per_price = parseFloat($t.attr('data-per_price'));
              prop_prices = A.P.getPropPrices(id);
              real_price = price + prop_prices.item_value + parseFloat((price * prop_prices.item_percent).toFixed(0));
              total = real_price;
              old = total;
              total *= percent;
              cashback = total * cashback_percent;
              $old.html($.fn.CART('fprice', old));
              $price.html($.fn.CART('fprice', total));
              return $cashback.html($.fn.CART('fprice', cashback));
            });
        }
        $buy_button.click(function() {
          var ccount, count, cp_id, variant;
          count = parseInt($(".count", $wrap).val());
          switch (parseInt($buy_button.attr('data-type'))) {
            case 1:
              return $.fn.CART('buy', id, count);
            case 2:
              ccount = parseInt($(".per_count", $wrap).val());
              return $.fn.CART('buy_component', id, ccount, count);
            case 3:
              cp_id = parseInt($("._r-label.selected", $wrap).attr('data-id'));
              return $.fn.CART('buy_component_price_id', id, cp_id, count);
            case 6:
              variant = $(".sizes .btn.fill", $wrap).attr('data-id');
              return $.fn.CART('buy_variant', id, variant, count);
          }
        });
        $("._r-label:eq(0)", $wrap).click();
      }
      $(".prop_prices", $wrap).each(function() {
        var $par, $props;
        $par = $(this);
        $props = $(".prop_price", $par);
        return $props.click(function() {
          var $t;
          $t = $(this);
          $props.removeClass('selected');
          $t.addClass('selected');
          $(".count", $wrap).change();
          $(".per_count", $wrap).keyup();
          return $("._r-label.selected", $wrap).click();
        });
      });
      return $("[data-is_default=1]", $wrap).click();
    });
    $("#mobile_price .t1", $html).text($(".item_price_wrap .total_item_price").text());
    $("#mobile_price .t2", $html).text($(".item_price_wrap .cashback").text());
    $(".phone_mask").mask("+7 (999) 999-99-99");
    return A.P.initPreventLink($html);
  },
  getPropParent: function() {
    var $body;
    $body = $("body");
    if (A.W.back.hasClass('open')) {
      $body = A.W.i;
    }
    return $body;
  },
  getPropsForCart: function(id) {
    var $body, res;
    res = {};
    $body = A.P.getPropParent();
    $(".item_price_wrap[data-id=" + id + "] .prop_price.selected", $body).each(function() {
      var $t;
      $t = $(this);
      return res[$t.attr("data-prop-id")] = $t.attr("data-id");
    });
    return res;
  },
  getPropPrices: function(id) {
    var $body, res;
    res = {
      item_value: 0,
      item_percent: 0,
      component_value: 0,
      component_percent: 0
    };
    $body = A.P.getPropParent();
    $(".prop_price.selected", $(".item_price_wrap[data-id=" + id + "]", $body)).each(function() {
      var $t, c, price;
      $t = $(this);
      price = JSON.parse($t.attr('data-price'));
      switch (parseInt(price.item_type)) {
        case 1:
          res.item_value += (isNaN(c = parseFloat(price.item_price)) ? 0 : c);
          break;
        case 2:
          res.item_percent += (isNaN(c = parseFloat(price.item_price)) ? 0 : c);
      }
      switch (parseInt(price.component_type)) {
        case 1:
          return res.component_value += (isNaN(c = parseFloat(price.component_price)) ? 0 : c);
        case 2:
          return res.component_percent += (isNaN(c = parseFloat(price.component_price)) ? 0 : c);
      }
    });
    res.item_percent /= 100;
    res.component_percent /= 100;
    console.log(res);
    return res;
  },
  initForm: function($html) {
    return $("form [type=submit]", $html).click(function() {
      var $f, $t;
      $f = ($t = $(this)).closest('form');
      return $f.data('submit_clicked', $t);
    });
  },
  initPreventLink: function(x) {
    return $("a:not(.prevented):not(.slide)", $(x)).addClass('prevented').click(A.P.preventALink);
  },
  preventALink: function(e) {
    var $t, href;
    href = ($t = $(this)).attr('href');
    //console.log
    if ($t.hasClass('propagation')) {
      e.preventDefault();
      return e.stopPropagation();
    } else if (href === "" || href === "#") {
      return e.preventDefault();
    //e.stopPropagation()
    } else if (href !== void 0) {
      if ($t.hasClass('_to_card')) {
        e.preventDefault();
        e.stopPropagation();
        return $.fn.CARD('openNew', {
          api: $t.attr('data-module'),
          id: $t.attr('data-id')
        });
      } else if (href.substr(0, 1) === '/') {
        e.preventDefault();
        e.stopPropagation();
        console.log($(this), $(this).attr('href'));
        return H.go($(this).attr('href'));
      }
    }
  }
};

//-----------------------------------------------
// A.W - Работа со всплывающими окнами
//-----------------------------------------------
A.W = {
  back: null,
  w: null,
  i: null,
  init: function() {
    console.log('ready', $("#wback"));
    A.W.back = $("#wback");
    if (A.W.back.length > 0) {
      A.W.w = $("#window");
      return A.W.i = $("#w_inner");
    } else {
      return delete A.W;
    }
  },
  startLoad: function() {
    return A.W.i.addClass("load").html("Загрузка данных");
  },
  finishLoad: function(data) {
    var $data;
    $data = $(data);
    A.W.i.removeClass("load").html($data);
    return A.P.initMini($data);
  },
  //$(".window_inner input[name=phone]").mask("+7 (999) 999-99-99");
  setHtml: function(data) {
    return A.W.finishLoad(data);
  },
  open: function(w) {
    A.P.body.css('overflow', 'hidden');
    A.W.back.addClass('open');
    return A.W.w.css({
      maxWidth: (w !== void 0 ? w : 800) + "px"
    });
  },
  close: function() {
    var base;
    A.W.back.removeClass('open');
    A.P.body.css('overflow', 'auto');
    A.W.i.html("");
    return typeof (base = A.W).onClose === "function" ? base.onClose() : void 0;
  },
  openRecall: function(data = {
      title: 'Обратный звонок',
      form_type: 'recall'
    }) {
    A.W.open(400);
    A.W.startLoad();
    return API(API_THEME + 'formRecall', data, A.W.setHtml);
  },
  openAuth: function() {
    A.W.open(600);
    A.W.startLoad();
    return API(API_THEME + 'formAuth', {}, A.W.setHtml);
  },
  openReg: function() {
    A.W.open(600);
    A.W.startLoad();
    return API(API_THEME + 'formReg', {}, A.W.setHtml);
  },
  openRestore: function() {
    A.W.open(600);
    A.W.startLoad();
    return API(API_THEME + 'formRestore', {}, A.W.setHtml);
  },
  openThankYou: function() {
    A.W.open(400);
    A.W.startLoad();
    return API(API_THEME + 'formThankYou', {}, A.W.setHtml);
  },
  openThankYou2: function() {
    A.W.open(400);
    A.W.startLoad();
    return API(API_THEME + 'formThankYou2', {}, A.W.setHtml);
  },
  openWantGift: function(id) {
    A.W.open(600);
    A.W.startLoad();
    return API(API_THEME + 'wantGift', {id}, A.W.setHtml);
  },
  openAbuy: function(id) {
    A.W.open(400);
    A.W.startLoad();
    return API(API_THEME + 'abuy', {
      id: id
    }, A.W.setHtml);
  },
  openOneClick: function(id) {
    var $body, $c, $per_count, $price_variant, component_count, count, price, price_variant, props;
    props = A.P.getPropsForCart(id);
    component_count = 0;
    price_variant = 0;
    $body = A.P.getPropParent();
    if (($per_count = $(".item_price_wrap[data-id=" + id + "] .per_count", $body)).length > 0) {
      component_count = $per_count.val();
    }
    if (($price_variant = $(".item_price_wrap[data-id=" + id + "] .radio_label input:checked", $body)).length > 0) {
      price_variant = $price_variant.closest('label').attr('data-id');
    }
    price = $(".item_price_wrap[data-id=" + id + "] .price.total_item_price", $body).text();
    count = $(".item_price_wrap[data-id=" + id + "] .count", $body).val();
    $c = $(".mobile_count:visible", $body);
    if ($c.length > 0) {
      count = $c.val();
    }
    A.W.open(400);
    A.W.startLoad();
    return API(API_THEME + 'oneClick', {id, props, component_count, price_variant, price, count}, A.W.setHtml);
  },
  openCartOneClick: function() {
    A.W.open(400);
    A.W.startLoad();
    return API(API_THEME + 'cartOneClick', {}, A.W.setHtml);
  },
  openMap: function() {
    A.W.open(1000);
    A.W.startLoad();
    return API(API_THEME + 'openMap', {}, A.W.setHtml);
  },
  openAuth: function() {
    A.W.open(420);
    A.W.startLoad();
    return API(API_THEME + 'formAuth', {}, A.W.setHtml);
  },
  openReg: function() {
    A.W.open(420);
    A.W.startLoad();
    return API(API_THEME + 'formReg', {}, A.W.setHtml);
  },
  openMap2: function() {
    A.W.open(1000);
    A.W.startLoad();
    return API(API_THEME + 'openMap2', {}, A.W.setHtml);
  },
  openCard: function() {
    A.W.open(1000);
    A.W.startLoad();
    return API(API_THEME + 'openCard', {
      text: $("#card").val()
    }, A.W.aOpenCard);
  },
  openCalc: function(id) {
    var $c, count;
    count = 1;
    $c = $(".mobile_count:visible");
    if ($c.length > 0) {
      count = $c.val();
    }
    A.W.open(420);
    A.W.startLoad();
    return API(API_THEME + 'openCalc', {id, count}, A.W.aOpenCard);
  },
  aOpenCard: function(data) {
    var $data;
    $data = $(data);
    return A.W.setHtml($data);
  }
};

(function($) {
  var F;
  $.fn.CART = function(method) {
    if (F[method]) {
      return F[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === "object" || !method) {
      return F.init.apply(this, arguments);
    } else {
      return $.error('Метод с именем ' + method + ' не существует для jQuery.CART');
    }
  };
  return F = {
    bonus: 0,
    deliveryID: 0,
    paymentID: 0,
    deliveryPrice: 0,
    isDeliveryFree: false,
    isSelf: false,
    isCash: false,
    init: function() {},
    clear: function() {
      if (confirm("Вы уверены?")) {
        return API('shop.cart/clearMy', {}, function() {
          return H.reload();
        });
      }
    },
    withoutReg: function() {
      $("#auth_block").remove();
      return F.remath();
    },
    initConfirm: function($html) {
      var $total;
      $("._delivery", $html).click(function() {
        var $t, type;
        $t = $(this);
        type = parseInt($t.attr('data-type'));
        console.log($t, type);
        if (type === 3) {
          $(".delivery_row").toggle(false);
          $('#delivery_row [data-name=city] input').val('-');
          $('#delivery_row [data-name=address] input').val('-');
          $('.delivery_date').addClass('c-100').removeClass('c-1-3');
        } else {
          $(".delivery_row").toggle(true);
          $('.delivery_date').addClass('c-1-3').removeClass('c-100');
        }
        F.deliveryID = $t.val();
        return F.remath();
      });
      $total = $("#total_wrap", $html);
      F.bonus = 0;
      F.deliveryPrice = 0;
      F.deliveryID = 0;
      F.paymentID = 0;
      F.isSelf = false;
      F.isCash = false;
      F.isSuburban = false;
      F.total = parseFloat($total.attr('data-total'));
      F.isDeliveryFree = parseInt($total.attr('data-delivery_free')) === 1;
      return F.remath();
    },
    setBonus: function(bonus) {
      F.bonus = bonus;
      return F.remath();
    },
    submit: function() {
      var $f, $inputs, $res, d1, d2, err, f, s, time, time1, time2;
      err = null;
      $f = $(event.target);
      $res = $(".res", $f).hide(300);
      f = $f.FORM();
      s = f.json();
      s.delivery_id = parseInt(F.deliveryID);
      s.shop_id = SHOP_ID;
      s.filial_id = FILIAL_ID;
      s.data = {
        card: s.card,
        delivery_call: s.delivery_call,
        filial_id: FILIAL_ID
      };
      s.km = parseInt(s.km);
      if (isNaN(s.km)) {
        s.km = 0;
      }
      s.cashback = F.bonus;
      //if F.isCash
      //  s.cashback = 0

      //s.dprice = F.deliveryPrice
      if (s.delivery_id === 0) {
        err = "Выберите способ доставки";
      }
      if (($inputs = $("[name=delivery]:checked  + .cont_wrap .inputs")).length > 0) {
        s.ddate = $('[type=date]', $inputs).val();
        s.dtime = $('[type=time]', $inputs).val();
        if (s.ddate === "") {
          err = "Выберите дату доставки/самовывоза";
        }
        if (s.dtime === "") {
          err = "Выберите время доставки/самовывоза";
        }
        console.log(err);
        if (err === null) {
          d1 = s.ddate.split("-");
          d2 = s.dtime.split(":");
          //time = new Date(Date.parse(s.ddate + " " + s.dtime))
          time = new Date(d1[0], parseInt(d1[1]) - 1, parseInt(d1[2]), d2[0], d2[1]);
          time1 = parseInt(time.getTime());
          time2 = parseInt((new Date()).getTime()) + (60 * 60 * 2 * 1000);
          //alert( time1 + ':' + time2 + '=' + (time2-time1) + ' ? '+ (typeof time1)+' ? '+ (typeof time2))
          console.log(new Date(time1), new Date(time2));
          if (time1 < time2) {
            err = "Доставка/самовывоз не может быть ранее чем через два часа. <br/>Пожалуйста, выберите другое время.";
          }
          if (parseInt(time.getHours()) < 9) {
            err = "Доставка/самовывоз не могут быть ранее, чем 9 часов. <br/>Пожалуйста, выберите другое время.";
          }
          if (parseInt(time.getHours()) > 19) {
            err = "Доставка/самовывоз не могут быть позднее, чем 19 часов. <br/>Пожалуйста, выберите другое время.";
          }
        }
      }
      if (!err && s.payment_id === 0) {
        err = "Выберите способ оплаты";
      }
      if (!err) {
        if (!F.isSelf) {
          if (s.address === '') {
            err = "Укажите, пожалуйста, адрес доставки";
          }
        }
        if (F.isSuburban) {
          if (s.km === 0) {
            err = "Укажите, пожалуйста, количество КМ зм МКАД";
          }
        }
      }
      if (err) {
        $res.html(err).show(300);
      } else {
        f.validate({
          fail: function() {
            err = 'Заполните, пожалуйста, все обязательные поля';
            return $res.html(err).show(300);
          },
          success: function() {
            var $b;
            A.I.waitInput($b = $("#confirm"));
            s.dataType = "JSON";
            return API('shop.order/confirm', s, function(data) {
              if (data.id !== 0) {
                return API(API_THEME + 'addOrder', {
                  id: data.id,
                  dataType: "JSON"
                }, function(data) {
                  console.log('addOrder', data);
                  if (data !== 0) {
                    H.go(data.link);
                  } else {
                    A.I.unwaitInput($b);
                  }
                  return F.updateBasket();
                });
              }
            });
          }
        });
      }
      return false;
    },
    remove: function(id) {
      var e, ecomm;
      try {
        ecomm = JSON.parse($(`#item_${id}`).attr('data-ecommerce'));
        A.ecommerce.remove([ecomm]);
      } catch (error) {
        e = error;
      }
      $(`#item_${id}`).remove();
      return API('shop.cart/removeMyShopItem', {
        id: id
      }, F.updateBasket);
    },
    initBasket: function($html = A.P.body) {
      F.total = parseFloat($("#total").attr('data-total'));
      return $("#b_cart .count", $html).change(function() {
        var $t, cid, count;
        $t = $(this);
        count = $t.val();
        cid = $t.attr('data-id');
        return API('shop.cart/setMyCount', {
          id: cid,
          count: count
        }, F.updateBasket);
      });
    },
    getKM: function() {
      var res;
      res = 0;
      if (F.isSuburban) {
        res = parseInt($('[data-name="km"] input').val());
        if (isNaN(res)) {
          res = 0;
        }
      }
      return res;
    },
    getkMPrice: function() {
      var price, res;
      res = F.getKM();
      price = parseInt($("[name=delivery]:checked").attr('data-km'));
      if (isNaN(price)) {
        price = 0;
      }
      res *= price;
      return res;
    },
    remath: function() {
      var isShowBlock;
      F.kmPrice = F.getkMPrice();
      $("#cashback_total .price_value").text(F.fprice(F.bonus));
      $("#delivery_total .with_price .price_value").text(F.fprice(F.deliveryPrice + F.kmPrice));
      $("#total_with_cashback .price_value").text(F.fprice(F.total + F.deliveryPrice - F.bonus + F.kmPrice));
      $("#delivery_total .no_choosed").toggle(F.deliveryID === 0);
      $("#delivery_total .free").toggle(F.deliveryPrice === 0 && F.deliveryID !== 0);
      $("#delivery_total .with_price").toggle(F.deliveryPrice > 0 && F.deliveryID !== 0);
      isShowBlock = false;
      if ($("#auth_block").length === 0) {
        $(".step").show();
        isShowBlock = true;
      } else {
        $(".step").hide();
        $("#auth_block").show();
      }
      $(".no_self").toggle(!F.isSelf && isShowBlock);
      $(".no_self").toggle(!F.isSelf && isShowBlock);
      return $(".only_suburban").toggle(F.isSuburban && isShowBlock);
    },
    // $("#total_delivery span.price_value").text( F.fprice( F.deliveryPrice + km + add_price) )
    //$("#total_cart span.price_value").text( F.fprice( F.total) )
    // $("#total span.price_value").text( F.fprice( F.total + F.deliveryPrice + km + add_price) )
    updateBasket: function(data) {
      return API('shop.cart/getMyCartTotals', {
        dataType: "JSON"
      }, function(data) {
        var i;
        console.log(data);
        for (i in data.citems) {
          $(`#total_${i} span.price_value`).text(F.fprice(data.citems[i]));
        }
        F.total = data.total;
        // $("#total span").text( F.fprice( data.total ) )
        F.remath();
        return F.updateTotal();
      });
    },
    /*
    API API_THEME+'getCashbackTotal',{},(data)->
      console.log data
      $("#total_cashback span").html(data)
    */
    fprice: function(x) {
      var c, i, l, res;
      res = '';
      x = parseFloat(x.toFixed(0));
      x = (x + '').split(''); //.reverse()
      l = x.length;
      for (i in x) {
        c = l - i;
        if (c % 3 === 0) {
          res += ' ';
        }
        res += x[i];
      }
      return res;
    },
    oneclick: function() {
      var $f, $res, err, f, s;
      err = null;
      $f = $(event.target);
      $res = $(".res", $f).hide(300);
      f = $f.FORM();
      s = f.json();
      if (err) {
        $res.html(err).show(300);
      } else {
        f.validate({
          success: function() {
            var $b;
            A.I.waitInput($b = $("[type=submit]"));
            return API(API_THEME + '/buyOneClick', s, function(data) {
              console.log(data);
              return A.W.openThankYou();
            });
          }
        });
      }
      return false;
    },
    wantgift: function() {
      var $f, $res, err, f, s;
      err = null;
      $f = $(event.target);
      $res = $(".res", $f).hide(300);
      f = $f.FORM();
      s = f.json();
      if (err) {
        $res.html(err).show(300);
      } else {
        f.validate({
          success: function() {
            var $b;
            A.I.waitInput($b = $("[type=submit]"));
            return API(API_THEME + '/sendWantGift', s, function(data) {
              console.log(data);
              return A.W.openThankYou2();
            });
          }
        });
      }
      return false;
    },
    cartoneclick: function() {
      var $f, $res, err, f, s;
      err = null;
      $f = $(event.target);
      $res = $(".res", $f).hide(300);
      f = $f.FORM();
      s = f.json();
      s.shop_id = SHOP_ID;
      if (err) {
        $res.html(err).show(300);
      } else {
        f.validate({
          success: function() {
            var $b;
            A.I.waitInput($b = $("#confirm_button"));
            s.dataType = "JSON";
            return API('shop.order/confirm', s, function(data) {
              console.log(data);
              if (data.id !== 0) {
                return API(API_THEME + 'addOrder', {
                  id: data.id,
                  dataType: "JSON",
                  oneclick: 1
                }, function(data) {
                  console.log('addOrder', data);
                  if (data !== 0) {
                    H.go(data.link);
                  }
                  A.I.unwaitInput($b);
                  A.W.openThankYou();
                  F.updateTotal();
                  return A.ecommerce.purchase(data.id, data.ecommerce);
                });
              }
            });
          }
        });
      }
      return false;
    },
    reloadCart: function() {
      return API(API_THEME + '/getCart', {}, function(data) {
        var $data;
        $data = $(data);
        $(".orders-table").replaceWith($data);
        A.P.initMini($data);
        $.fn.CART('initBasket');
        return F.updateBasket();
      });
    },
    addGift: function(id) {
      var s;
      s = {
        count: 1,
        id: id,
        shop_id: SHOP_ID
      };
      return API('shop.cart/addToMyCart', s, function(data) {
        return F.reloadCart();
      });
    },
    buy: function(id, count) {
      var $body, $c, s;
      if (isNaN(count)) {
        $c = $("#count_" + id);
        if ($c.length > 0) {
          count = parseInt($c.val());
        }
        if (isNaN(count)) {
          count = 1;
        }
      }
      $body = A.P.getPropParent();
      $c = $(".mobile_count:visible", $body);
      if ($c.length > 0) {
        count = $c.val();
      }
      s = {
        count: count,
        id: id,
        shop_id: SHOP_ID,
        props: A.P.getPropsForCart(id)
      };
      return API('shop.cart/addToMyCart', s, function(data) {
        console.log('data', data);
        return F.aBuy(id);
      });
    },
    buy_component: function(id, ccount, count) {
      var s;
      s = {
        id: id,
        component_count: ccount,
        count: count,
        shop_id: SHOP_ID,
        props: A.P.getPropsForCart(id)
      };
      return API('shop.cart/addToMyCart', s, function(data) {
        console.log('data', data);
        return F.aBuy(id);
      });
    },
    buy_component_price_id: function(id, cp_id, count) {
      var s;
      s = {
        id: id,
        component_price_id: cp_id,
        count: count,
        shop_id: SHOP_ID,
        props: A.P.getPropsForCart(id)
      };
      return API('shop.cart/addToMyCart', s, function(data) {
        console.log('data', data);
        return F.aBuy(id);
      });
    },
    buy_variant: function(id, variant, count) {
      var $c, s;
      if (isNaN(count)) {
        $c = $("#count_" + id);
        if ($c.length > 0) {
          count = parseInt($c.val());
        }
        if (isNaN(count)) {
          count = 1;
        }
      }
      s = {
        count: count,
        id: id,
        variant: variant,
        shop_id: SHOP_ID,
        props: A.P.getPropsForCart(id)
      };
      return API('shop.cart/addToMyCart', s, function(data) {
        console.log('data', data);
        return F.aBuy(id);
      });
    },
    updateTotal: function() {
      return API(API_THEME + 'getMyCartData', {
        dataType: 'JSON'
      }, function(data) {
        $(".total").html(data.total);
        if (data.old) {
          $(".old_total").html(data.old);
        }
        return $(".total_count").html(data.count);
      });
    },
    aBuy: function(id) {
      F.updateTotal();
      return A.W.openAbuy(id);
    },
    saveCard: function() {
      var val;
      val = tinyMCE.get('window_card') != null ? tinyMCE.get('window_card').getContent() : $("#window_card").val();
      $("#card").val(val);
      return A.W.close();
    },
    add_promo: function() {
      var $f, $res, err, f, s;
      err = null;
      $f = $(event.target);
      $res = $(".res", $f).hide(300);
      f = $f.FORM();
      s = f.json();
      console.log(s);
      if (err) {
        $res.html(err).show(300);
      } else {
        f.validate({
          success: function() {
            s.dataType = "JSON";
            return API(API_THEME + 'addPromo', s, function(data) {
              console.log(data);
              $res.html(data.m).show(300);
              if (data.e === 0) {
                return $(".inputs", $f).replaceWith('<div class="h tal"><h3>' + data.promo + '</b></div>');
              }
            });
          }
        });
      }
      return false;
    }
  };
})(jQuery);

(function($) {
  var F;
  $.fn.CONSTRUCTOR = function(method) {
    if (F[method]) {
      return F[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === "object" || !method) {
      return F.init.apply(this, arguments);
    } else {
      return $.error('Метод с именем ' + method + ' не существует для jQuery.CONSTRUCTOR');
    }
  };
  return F = {
    init: function($html) {
      return $("#constructor", $html).each(function() {
        var $checkbox, $t, remath, structure;
        $t = $(this);
        structure = {
          flower: {},
          pack: {}
        };
        $(".btn", $t).click(function() {
          console.log('order ', structure);
          return API(API_THEME + 'addConstructor', {
            structure,
            dataType: "JSON"
          }, function(data) {
            console.log(data);
            return $.fn.CART('aBuy', data.id);
          });
        });
        $("#to_order").click(function() {
          return A.P.scrollToAnimate($("#constructor_order"));
        });
        remath = function() {
          var f, p, total;
          f = Object.values(structure.flower).reduceRight(function(prev, now, index, arr) {
            return prev + now.price * now.count;
          }, 0);
          p = Object.values(structure.flower).reduceRight(function(prev, now, index, arr) {
            return prev + now.price * now.count;
          }, 0);
          total = 1000 + f + p;
          structure.total = total;
          return $(".right .total_constructor .price_value").text($.fn.CART('fprice', total));
        };
        $checkbox = $(".left [type=checkbox]", $t);
        return $checkbox.click(function() {
          $checkbox = $(this);
          return (function($checkbox) {
            var $x, id, img, max, name, price, prop, setVal;
            id = $checkbox.attr('data-id');
            prop = $checkbox.attr('data-prop');
            price = $checkbox.attr('data-price');
            max = $checkbox.attr('data-max');
            img = $checkbox.attr('data-img');
            name = $checkbox.attr('data-name');
            if ($checkbox.is(":checked")) {
              structure[prop][id] = {
                id,
                prop,
                price,
                max,
                count: 1,
                img
              };
              console.log(price);
              $x = $('<div class="el" data-prop="' + prop + '" data-id="' + id + '"><div class="icon img square" style="background-image:url(' + img + ')"></div><div class="name">' + name + '<br/>' + $.fn.CART('fprice', parseFloat(price)) + ' ₸</div><input type="number" value="1" step="1" min="1" max="' + max + '" class="i"><span>шт.</span><div class="remove">✕</div></div>');
              $(".right .list", $t).append($x);
              $(".remove", $x).click(function() {
                return $checkbox.click();
              });
              setVal = function() {
                var $inp, count;
                $inp = $(this);
                max = parseInt($inp.attr("max"));
                count = parseInt($inp.val());
                if (isNaN(count)) {
                  count = 1;
                }
                if (count > max) {
                  count = max;
                  $inp.val(max);
                }
                structure[prop][id].count = count;
                return remath();
              };
              $("input", $x).keyup(setVal).change(setVal);
            } else {
              delete structure[prop][id];
              $(".right .el[data-prop=" + prop + "][data-id=" + id + "]", $t).remove();
            }
            return remath();
          })($checkbox);
        });
      });
    }
  };
})(jQuery);

(function($) {
  var F;
  $.fn.FILTER = function(method) {
    if (F[method]) {
      return F[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === "object" || !method) {
      return F.init.apply(this, arguments);
    } else {
      return $.error('Метод с именем ' + method + ' не существует для jQuery.FILTER');
    }
  };
  return F = {
    init: function($html) {
      return $(".filter [type=checkbox]", $html).click(F.set);
    },
    sortBy: function(sort_by, type) {
      var a, i, j, len, s, ss, v;
      s = window.location.search;
      if (s[0] === "?") {
        s = s.substr(1);
      }
      s = s.split("&");
      a = {};
      for (j = 0, len = s.length; j < len; j++) {
        i = s[j];
        if (i !== '') {
          v = i.split("=");
          if (v[0]) {
            a[v[0]] = v[1];
          }
        }
      }
      a.sort = sort_by;
      a.sort_type = type;
      s = [];
      for (i in a) {
        s.push(i + '=' + a[i]);
      }
      ss = s.join("&");
      s = s !== '' ? '?' + s.join("&") : '';
      return H.go(window.location.pathname + s);
    },
    reset: function() {
      return H.go(window.location.pathname);
    },
    set: function() {
      var filter, url;
      filter = {};
      $(".filter input:checked").each(function() {
        var $t, name;
        $t = $(this);
        name = $t.attr('name');
        if (filter[name] === void 0) {
          filter[name] = [];
        }
        return filter[name].push($t.val());
      });
      //H.go(window.location.pathname+'?filter='+JSON.stringify(filter))
      url = new URL(window.location.href);
      url.searchParams.delete('filter');
      url.searchParams.set('filter', JSON.stringify(filter));
      return H.go(url.pathname + url.search);
    }
  };
})(jQuery);

(function($) {
  var F;
  $.fn.ITEM = function(method) {
    if (F[method]) {
      return F[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === "object" || !method) {
      return F.init.apply(this, arguments);
    } else {
      return $.error('Метод с именем ' + method + ' не существует для jQuery.ITEM');
    }
  };
  return F = {
    init: function($html) {
      var $imgs;
      return ($imgs = $(".is-item", $html)).click(function() {
        var $t;
        console.log('LICK');
        $t = $(this);
        $imgs.removeClass('selected');
        $t.addClass('selected');
        return $("#item_main_img img").attr('src', $t.attr('data-image'));
      });
    },
    //$(".is-item:eq(0)",$html).click()
    favorite: function(id) {
      var s;
      s = {
        shop_id: SHOP_ID,
        item_id: id,
        dataType: 'JSON'
      };
      return API('shop.shop.wish/toggleMyWish', s, function(data) {
        $("#fav_count").text(data.length);
        return API(API_THEME + 'getFavoriteButton', {
          id: id
        }, function(data) {
          return $(".fav_" + id).replaceWith(data);
        });
      });
    }
  };
})(jQuery);

(function($) {
  var F;
  $.fn.PROFILE = function(method) {
    if (F[method]) {
      return F[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === "object" || !method) {
      return F.init.apply(this, arguments);
    } else {
      return $.error('Метод с именем ' + method + ' не существует для jQuery.PROFILE');
    }
  };
  return F = {
    init: function() {},
    exit: function() {
      return API('core.user.profile/exit', {
        a: 'a'
      }, function(data) {
        return window.location.reload();
      });
    },
    new_pass: function(f) {
      var $f, $res, s;
      f = ($f = $(f)).FORM();
      s = f.json();
      s.dataType = "JSON";
      $res = $(".res", $f).hide(300).html('');
      f.validate({
        success: function() {
          return API(API_THEME + '/new_pass', s, function(data) {
            //console.log(data)
            $res.html(data.m).show(300);
            if (data.e === 0) {
              return setTimeout(function() {
                return window.location.reload();
              }, 3000);
            }
          });
        }
      });
      return false;
    },
    remind: function(f) {
      var $f, $res, s;
      f = ($f = $(f)).FORM();
      s = f.json();
      s.dataType = "JSON";
      $res = $(".res", $f).hide(300);
      f.validate({
        success: function() {
          return API(API_THEME + '/remind', s, function(data) {
            console.log(data);
            return $res.html(data.m).show(300);
          });
        }
      });
      return false;
    },
    login: function(f) {
      var $f, $res, s;
      f = ($f = $(f)).FORM();
      s = f.json();
      s.dataType = "JSON";
      $res = $(".res", $f).hide(300);
      f.validate({
        success: function() {
          return API('core.user.profile/login', s, function(data) {
            if (data.e === 1) {
              return $res.html(data.m).show(300);
            } else {
              return window.location.reload();
            }
          });
        }
      });
      return false;
    },
    updatePass: function() {
      var $f, $res, f, s;
      f = ($f = $(event.target)).FORM();
      s = f.json();
      //s.dataType="JSON"
      $res = $(".res", $f).hide(300);
      console.log(s);
      f.validate({
        success: function() {
          if (s.pass1 !== s.pass2) {
            return $res.html("Новые пароли не совпадают").show(300);
          } else {
            return API('core.user.profile/updateMyPass', s, function(data) {
              var txt;
              console.log(data);
              data = parseInt(data);
              // 0 - не авторизован
              // 1 - старый пароль не верный
              // 2 - не прислан пароль
              // 3 - успешно обновили
              switch (data) {
                case 0:
                  txt = "Вы не авторизованы";
                  break;
                case 1:
                  txt = "Текущий пароль не верный";
                  break;
                case 2:
                  txt = "Не прислан новый пароль";
                  break;
                case 3:
                  txt = "Успешно обновлено";
              }
              return $res.html(txt).show(300);
            });
          }
        }
      });
      return false;
    },
    update: function() {
      var $f, $res, f, s;
      f = ($f = $(event.target)).FORM();
      s = f.json();
      s.dataType = "JSON";
      $res = $(".res", $f).hide(300);
      f.validate({
        success: function() {
          return API('core.user.profile/updateMy', s, function(data) {
            if (data.e === 1) {
              return $res.html(data.m).show(300);
            } else {
              return $res.html("Успешно сохранено").show(300);
            }
          });
        }
      });
      return false;
    },
    reg: function(f) {
      var $f, $res, s;
      f = ($f = $(f)).FORM();
      s = f.json();
      s.dataType = "JSON";
      $res = $(".res", $f).hide(300);
      f.validate({
        success: function() {
          return API('core.user.profile/reg', s, function(data) {
            if (data.e === 1) {
              return $res.html(data.m).show(300);
            } else {
              return window.location.reload();
            }
          });
        }
      });
      return false;
    }
  };
})(jQuery);

(function($) {
  var F;
  $.fn.SHOP = function(method) {
    if (F[method]) {
      return F[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === "object" || !method) {
      return F.init.apply(this, arguments);
    } else {
      return $.error('Метод с именем ' + method + ' не существует для jQuery.SHOP');
    }
  };
  return F = {
    loadingMore: false,
    init: function($html) {
      $(".search_open", $html).click(function() {
        $("#search_back").addClass("show");
        $("body,html").css('overflow', 'hidden');
        return $("#search_input_wrap input").focus();
      });
      $("#search_close", $html).click(function() {
        $("#search_back").removeClass("show");
        return $("body,html").css('overflow', 'auto');
      });
      (F.$isearch = $("#search_input_wrap input", $html)).keyup(F.searchItems).on('paste', F.searchItems);
      // .change(F.searchItems)
      F.$isearch_result = $("#search_back .results", $html);
      return F.$isearch_result.perfectScrollbar();
    },
    searchItems: function() {
      var val;
      val = F.$isearch.val().trim();
      return API(API_THEME + 'searchItems', {
        q: val
      }, function(data) {
        F.$isearch_result.html(data);
        return F.$isearch_result.perfectScrollbar('update');
      });
    },
    show_more: function(next_page, next) {
      var p, page, url;
      if (!F.loadingMore) {
        F.loadingMore = true;
        p = H.parse();
        page = parseInt(p[p.length - 1]);
        if (isNaN(page)) {
          p.push(next_page);
        } else {
          p[p.length - 1] = next_page;
        }
        url = '/' + p.join("/") + "/" + window.location.search;
        //H.go(url,null,null,false)
        history.pushState(null, null, url);
        return $.ajax({
          url: url,
          success: function(data) {
            var $c, $data;
            $data = $(data);
            $c = $("#catalog_wrap .catalog", $data);
            A.P.initMini($c);
            $("#catalog_content_wrap .catalog").append($c.children());
            //console.log $c
            A.P.$show_more = $(".show_more", $data);
            $(".show_more").replaceWith($(".show_more", $data));
            $(".pagination").replaceWith($(".pagination", $data));
            F.loadingMore = false;
            return A.P.initLazy();
          }
        });
      }
    },
    cloudpayments: function(o = {}) {
      var widget;
      console.log(o);
      widget = new (cp.CloudPayments)();
      widget.pay('charge', {
        publicId: o.token,
        description: 'Оплата товаров в gulmarket.kz',
        amount: o.amount,
        currency: 'KZT',
        invoiceId: o.invoiceId,
        //accountId: 'user@example.com'
        skin: 'mini',
        data: o.data
      }, {
        onSuccess: function(options) {
          // success
          //действие при успешной оплате
          A.W.openThankYou();
          H.go('/');
        },
        onFail: function(reason, options) {},
        // fail
        //действие при неуспешной оплате
        //F.cloudpayments(o)
        onComplete: function(paymentResult, options) {}
      });
    }
  };
//Вызывается как только виджет получает от api.cloudpayments ответ с результатом транзакции.
//например вызов вашей аналитики Facebook Pixel
})(jQuery);
