var list = {
  product: {
    template: '<tr class="js_cat_view__ct__tr">'+
    '<td width="1"><img src="/i/n.gif" width="50" height="50" style="%PRODUCT_IMG%" onclick="%PRODUCT_IMG_CLICK%" class="goods_item_img" data-id="%PRODUCT_ID%" /></td>'+
    '<td width="100%" style="min-width:210px;" class="print_name">%PRODUCT_NAME%%PRODUCT_BODY%</td>'+
    '<td width="80" class="print_article">%PRODUCT_CODE%</td>'+
    '<td width="90" align="right">%PRODUCT_PRICE_STR%</td>'+
    '<td width="70" class="align_center" align="center">%PRODUCT_MIN_PURCHASE%</td>'+
    '<td width="100" class="align_center max_product" align="center">%PRODUCT_NUMBER_PRODUCT%</td>'+
    '<td width="135" class="un_select nwrap">'+
    '<ul data-list="true" style="" data-view="tr" data-product-id="%PRODUCT_ID%" class="counter un_select list_goods">'+
    '<li onclick="basket.remove($(this));basketMemory.remove(%PRODUCT_ID%, %PRODUCT_MIN_PURCHASE%);" class="btn_all counter__button counter_button_minus red_button2 "></li>'+
    '<li class="counter__num">'+
    '<input name="" type="text" data-min-p="%PRODUCT_MIN_PURCHASE%" data-stock="%PRODUCT_NUMBER_MAX%" value="%COUNT%" autocomplete="off" onchange="basket.handWrite($(this));basket.check($(this))">'+
    '</li>'+
    '<li onclick="basket.add($(this));basketMemory.add(%PRODUCT_ID%, %PRODUCT_MIN_PURCHASE%);" class="btn_all counter__button counter_button_plus green_button2 "></li>'+
    '</ul>'+

    '</td>'+
    '</tr>',


    // template: '<tr class="js_cat_view__ct__tr">'+
    // '<td width="1"><img src="/i/n.gif" width="50" height="50" style="%PRODUCT_IMG%" onclick="%PRODUCT_IMG_CLICK%" class="goods_item_img" data-id="%PRODUCT_ID%" /></td>'+
    // '<td width="100%" style="min-width:210px;" class="print_name">%PRODUCT_NAME%%PRODUCT_BODY%</td>'+
    // '<td width="80" class="print_article">%PRODUCT_CODE%</td>'+
    // '<td width="90" align="right">%PRODUCT_PRICE_STR%</td>'+
    // '<td width="70" class="align_center" align="center">%PRODUCT_MIN_PURCHASE%</td>'+
    // '<td width="100" class="align_center max_product" align="center">%PRODUCT_NUMBER_PRODUCT%</td>'+
    // '<td width="135" class="un_select nwrap">'+
    // '<ul data-list="true" style="" data-view="tr" data-idx="%PRODUCT_IDX%" data-id="%PRODUCT_CODE%" data-article="%PRODUCT_CODE%" data-min="%PRODUCT_MIN_PURCHASE%" data-max="%PRODUCT_NUMBER_MAX%" data-price="%PRODUCT_PRICE%" class="counter un_select list_goods">'+
    // '<li onclick="js_cat.counter.counter_click($(this), event);" class="btn_all counter__button counter_button_minus red_button2 %MINUS_TRANSPARENT%"></li>'+
    // '<li class="counter__num">'+
    // '<input name="" onkeyup="js_cat.counter.counter_keyUp($(this), event);" onblur="js_cat.counter.counter_blur($(this));" onkeydown="js_cat.counter.counter_keyDown($(this), event);" onfocus="js_cat.counter.counter_focus($(this), event);" type="text" class="" value="%PRODUCT_COUNT%" autocomplete="off">'+
    // '</li>'+
    // '<li onclick="js_cat.counter.counter_click($(this), event);" class="btn_all counter__button counter_button_plus green_button2 %PLUS_TRANSPARENT%"></li>'+
    // '</ul>'+
    //
    // '</td>'+
    // '</tr>',

    add: function(id, code, article, name, price, min_purchase, number_product, index, img, visible, number_product_in_way, value){
      var template = list.product.template.replace(/%PRODUCT_ID%/g, id);
      var find = false;
      var sum = 0;
      var inc = 0;
      var _price = '';
      
      var number_product_v = '';
      var in_way = 0;
      var max = 0;
      if(typeof number_product != 'undefined'){
        number_product_v = '<span class="count_in_stock">' + number_product + '</span>';
        max = number_product;
        if(typeof number_product_in_way != 'undefined' && number_product_in_way > 0){
          in_way = number_product_in_way;
          max += number_product_in_way;
        }
      }
    
      _price = list.priceFormat(price);
      template = template.replace(/%PRODUCT_CODE%/g, typeof code != 'undefined' ? code : '');
      template = template.replace(/%PRODUCT_ARTICLE%/g, typeof article != 'undefined' ? article : '');
      template = template.replace(/%PRODUCT_NAME%/g, typeof name != 'undefined' ? name : '');
      template = template.replace(/%PRODUCT_BODY%/g, typeof body != 'undefined' ? ',&nbsp;' + body : '');
      template = template.replace(/%PRODUCT_PRICE%/g, typeof price != 'undefined' ? price : '');
      template = template.replace(/%PRODUCT_PRICE_STR%/g, typeof _price != 'undefined' ? _price : '');
      template = template.replace(/%PRODUCT_MIN_PURCHASE%/g, typeof min_purchase != 'undefined' ? min_purchase : '');
      template = template.replace(/%PRODUCT_NUMBER_PRODUCT%/g, number_product_v);
      template = template.replace(/%PRODUCT_NUMBER_MAX%/g, max);
      template = template.replace(/%PRODUCT_IDX%/g, index);

      if(typeof img == 'undefined'){
        template = template.replace(/%PRODUCT_IMG%/g, 'background-image:url(/i/no_photo.png);');
        template = template.replace(/%PRODUCT_IMG_PRESENCE%/g, 'no_image');
        template = template.replace(/%PRODUCT_IMG_CLICK%/g, '');
      }else{
        template = template.replace(/%PRODUCT_IMG%/g, 'background:url(/get_image/' + id + '?small) no-repeat 50% 50%;');
        template = template.replace(/%PRODUCT_IMG_CLICK%/g, 'js_cat.view_img(\'/get_image/' + id + '\');');
        template = template.replace(/%PRODUCT_IMG_PRESENCE%/g, '');
      }

      console.log(js_cat.js_cat__cart_article[code]);

      find = typeof js_cat.js_cat__cart_article[code] != 'undefined' ? js_cat.js_cat__cart_article[code] : 0;

      if(find){
        template = template.replace(/%PRODUCT_COUNT%/g, find);
        if(find == number_product){
          template = template.replace(/%MINUS_TRANSPARENT%/g, '');
          template = template.replace(/%PLUS_TRANSPARENT%/g, 'counter_button_transparent');
        }else if(find > 0 && find < number_product){
          template = template.replace(/%MINUS_TRANSPARENT%/g, '');
          template = template.replace(/%PLUS_TRANSPARENT%/g, '');
        }else if(find == 0){
          template = template.replace(/%MINUS_TRANSPARENT%/g, 'counter_button_transparent');
          template = template.replace(/%PLUS_TRANSPARENT%/g, '');
        }
      }else{
        template = template.replace(/%PRODUCT_COUNT%/g, '0');
        if(find == 0 && number_product == 0){
          template = template.replace(/%MINUS_TRANSPARENT%/g, 'counter_button_transparent');
          template = template.replace(/%PLUS_TRANSPARENT%/g, 'counter_button_transparent');
        }else{
          template = template.replace(/%MINUS_TRANSPARENT%/g, 'counter_button_transparent');
          template = template.replace(/%PLUS_TRANSPARENT%/g, '');
        }
      }

      template = template.replace('%COUNT%', value);

      return template;
    }
  },


  folder:{
    _template: '<div onclick="list.folder.onClick($(this), event);" data-id="%CATFOLDER_URL%" class="list_page__cont__link %CATFOLDER_PARENTFOLDER%%TOP_NEW%%CATFOLDER_CHECKED%%CATFOLDER_EXIST_NUM%">'+
    '%CATFOLDER_TITLE%%CATFOLDER_NUMBER%'+
    '</div>',

    _add: function(id, title, url, number, main, inner_id, checked){
      var template = list.folder._template.replace(/%CATFOLDER_ID%/g, id);

      template = template.replace(/%CATFOLDER_URL%/g, url);
      template = template.replace(/%CATFOLDER_PARENTFOLDER%/g, typeof main != 'undefined' ? 'parent_folder' : '');
      template = template.replace(/%CATFOLDER_TITLE%/g, typeof title != 'undefined' ? title : '');
      template = template.replace(/%CATFOLDER_NUMBER%/g, number != '' ? '&nbsp;(' + number + ')' : '');
      template = template.replace(/%CATFOLDER_EXIST_NUM%/g, number != '' ? ' parent_folder_num' : '');
      template = template.replace(/%CATFOLDER_CHECKED%/g, checked ? ' checked' : '');

      if(inner_id == 'TOP' || inner_id == 'NEW'){
        template = template.replace(/%TOP_NEW%/g, ' top_new_goods');
      }else{
        template = template.replace(/%TOP_NEW%/g, '');
      }
      return template;
    },



    onClick: function(_this, obj){
      var id = _this.data('id'),
        tempAll = '<div class="paste_folder">',
        _price = 0;

      if(_this.hasClass('checked')){
        _this.removeClass('checked').next().remove();
        return false;
      }

      if(db.catFolder[id].children.length > 0){
        _this.addClass('checked');
        $.each(db.catFolder[id].children, function(i, idx){
          var elem = db.catFolder[idx],
            num = 0;
          if(typeof elem != 'undefined'){
            if(elem.children.length == 0){
              num = db.cat_idx.title[idx].length;
            }
            tempAll += list.folder._add(elem.id, elem.title, idx, num, elem.inner_id);
          }
        });
        _this.after(tempAll);
        if(typeof obj.originalEvent != 'undefined'){
          $('.list_page__cont').trigger('scroll');
        }
      }else if(db.catFolder[id].children.length == 0){
        _this.addClass('checked');
        tempAll += '<table cellpadding="10" cellspacing="0" width="100%" class="std_table js_cat_view" data-id="' + id + '" style="margin-top: 20px;"><thead><tr>' +
            '<th class="sortable sorted sorted_asc" data-field="name" width="100%" colspan="2" align="left"><span class="sortable__txt">Название</span></th>' +
            '<th style="width: 80px;">Артикул</th>' +
            '<th class="sortable" data-field="price" style="width: 90px;"><span class="sortable__txt">Цена</span></th>' +
            '<th style="width: 70px;">Мин.&nbsp;п.</th>' +
            '<th class="sortable" data-field="number_product" style="width: 100px;"><span class="sortable__txt">В&nbsp;наличии</span></th>' +
            '<th class="sortable" data-field="number_product" style="width: 100px;"><span class="sortable__txt">В&nbsp;пути</span></th>' +
            '<th style="width: 135px;"></th>'+
          '</tr></thead><tbody class="js_cat_view__ct">';


        if(dbBackground == null){
          $.ajax({
            type: 'GET',
            url: 'http://app.' + window.location.host.replace('www.', '') + '/js/db.js?cat_idx=' + db.cat_idx.title[id].join(','),
            dataType: 'json',
            success: function(obj){

              $.each(obj, function(i, elem){
                if(typeof user_profile != 'undefined'){
                  _price = ( elem.auth_price - ( ( elem.auth_price / 100 ) * user_discount ) ).toFixed(2);
                }else{
                  _price = (parseFloat(elem.price)).toFixed(2);
                }

                // console.log(user_profile);


                tempAll += list.product.add(elem.id, elem.code, elem.article, elem.name, _price, elem.min_purchase, elem.number_product, i, elem.img, 1, elem.number_product_in_way);
              });

              tempAll += '</tbody></table>';
              tempAll += '</div>';
              _this.after(tempAll);
              if(typeof obj.originalEvent != 'undefined'){
                $('.list_page__cont').trigger('scroll');
              }
            }
          });
        }else{

          $.each(db.cat_idx.title[id], function(i, idx){
            var elem = dbBackground[idx];

            if(typeof user_profile != 'undefined'){
              _price = ( elem.auth_price - ( ( elem.auth_price / 100 ) * user_discount ) ).toFixed(2);
            }else{
              _price = (parseFloat(elem.price)).toFixed(2);
            }
            tempAll += list.product.add(elem.id, elem.code, elem.article, elem.name, _price, elem.min_purchase, elem.number_product, i, elem.img, 1, elem.number_product_in_way);
          });

          tempAll += '</tbody></table>';
          tempAll += '</div>';
          _this.after(tempAll);
          if(typeof obj.originalEvent != 'undefined'){
            $('.list_page__cont').trigger('scroll');
          }

        }
      };
    },

    min: function(){
      js_cat.preloader($('body'), 'Подождите, пожалуйста...');
      setTimeout(function(){
        $('.parent_folder_num.checked').click();
        js_cat.preloader($('body'));
      }, 100);
    }

  },

  priceFormat: function(num){
    var price = '';
    price = String(parseFloat(num).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, '&nbsp;');
    return price;
  },


  init: function(){
    var tempAll = '';

    $.each(db.catFolder[0].children, function(i, idx){
      if(typeof db.catFolder[idx] != 'undefined'){
        var elem = db.catFolder[idx];
        var existChild = elem.children.length > 0 ? 1 : 0;
        var num = existChild ? '' : db.cat_idx.title[idx].length;

        tempAll += list.folder._add(elem.id, elem.title, idx, num, 1, elem.inner_id, existChild);
        if(existChild){
          tempAll += '<div class="paste_folder">';
          $.each(elem.children, function(j, _idx){
            if(typeof db.catFolder[_idx] != 'undefined'){
              var _elem = db.catFolder[_idx];
              var _num = _elem.children.length == 0 ? db.cat_idx.title[_idx].length : '';
              tempAll += list.folder._add(_elem.id, _elem.title, _idx, _num, 1, _elem.inner_id);
            }
          });
          tempAll += '</div>';
        }
      }
    });
    $('.list_page__cont').html(tempAll);

    $('.parent_folder:not(.parent_folder_num)').each(function(i, item){
      if($(item).hasClass('checked') == false){
        $(item).click();
      }else{
        return;
      }
    });

    $(document).scroll(function(){
      var top = $(this).scrollTop();
      var w = $('.er_rows').outerWidth();
      var toggle_box = $('.toggle_box_wrap');
      if(top >= 220){
        toggle_box.addClass('fixed').outerWidth(w);
      }else{
        toggle_box.removeClass('fixed');
      }
    });
  }

};