var toggle = 1;
var controllers = {

  cart: {
    init: function(page){
      iElectro.pageShow(page);
      if(lStorage.cart.items.length > 0){
        $('.empty_cart').hide();
      }else{
        $('.empty_cart').show().find('.txt_message').html('Товары в корзине отсутствуют');
      }
      controllers.all();
    }
  },

  profile: {
    init: function(page){
      var profilePage = iElectro.posUrl().length > 1 ? iElectro.posUrl().pop() : 'total';

      if(!profile.auth){
        window.location.hash = '#main/0';
        return false;
      }

      // $.ajax({
      //   type: 'POST',
      //   url: appDomain + '/getProfile/',
      //   dataType: 'JSON',
      //   success: function(data){
          
      //   },
      //   complete: function(){
          
      //   }
      // })

      $('.profile_manager_name').html(typeof profile.manager.name != 'undefined' ? profile.manager.name : 'Менеджер не установлен');
      $('.profile_manager_phone').html(typeof profile.manager.phone != 'undefined' ? profile.manager.phone : '');
      
      if(profilePage == 'total'){
        iElectro.update.profile.orderHistory();
        $('.profile_page__total b.organization_name').html(profile.organization);
        $('.profile_page__total span.orders_sum_current').html(iElectro.priceFormat((parseFloat(profile.orders_sum_current)).toFixed(2)));
        $('.profile_page__total span.sum_discount').html(profile.sum_discount);
        $('.profile_page__total span.debt').html(iElectro.priceFormat((parseFloat(profile.debt)).toFixed(2)));
        $('.profile_page__total span.overdue_payment').html(iElectro.priceFormat((parseFloat(profile.overdue_payment)).toFixed(2)));
      }else if(profilePage == 'feedback'){
        iElectro.update.profile.feedback();
      }else if(profilePage == 'settings'){
        iElectro.update.profile.settings();
      }
      iElectro.pageShow(page);

      if(profilePage == 'feedback'){
        setTimeout(function(){
          $('.profile_page__feedback').scrollTop(1000000);
        },100);
      };
      
      $('.profile_page a.menu_list__link_profile').removeClass('menu_list__link_profile_active');
      $('.profile_page a.menu_list__link_profile[data-type="' + profilePage + '"]').addClass('menu_list__link_profile_active');
      $('.profile_page__pages').removeClass('flex');
      $('.profile_page__' + profilePage).addClass('flex');
      controllers.all();

     
    }
  },

  detailed_view: {
    init: function(page){
      var orderId = iElectro.posUrl().length > 1 ? iElectro.posUrl().pop() : '0';
      iElectro.pageShow(page);
      iElectro.update.profile.detailed_view(orderId);
      controllers.all();
    }
  },

  overlay:{
    init: function(page){
      var overlay = $('.' + page),
          overlayType = iElectro.posUrl().length > 1 ? iElectro.posUrl()[1] : false,
          overlayContain = $('.overlay .overlay__contain_' + overlayType);

      if(overlayType){
        $('.overlay .overlay__contain').removeClass('overlay__contain_active').css({
          '-webkit-transform': 'translateY(-100%)',
          '-moz-transform': 'translateY(-100%)',
          '-ms-transform': 'translateY(-100%)',
        });
        overlayContain.addClass('overlay__contain_active');
        setTimeout(function(){
          overlayContain.css({
            '-webkit-transition': '-webkit-transform 0.4s',
            '-moz-transition': '-moz-transform 0.4s',
            '-ms-transition': '-ms-transform 0.4s',
            '-webkit-transform': 'translateY(0%)',
            '-moz-transform': 'translateY(0%)',
            '-ms-transform': 'translateY(0%)',
          });
        }, 100);
        overlay.show();
      }
      controllers.all();
    }
  },

  main: {
    init: function(page){
      var posArr = iElectro.posUrl(),
          ifParentId = false;

      iElectro.pageShow(page);

      if(posArr.join('/') != 'main/' + mainNum && posArr.length <= 1){
        window.location.hash = 'main/' + mainNum;
        return false;
      }

      iElectro.update.folder(posArr[ posArr.length - 1 ], posArr[ posArr.length-1 ] != 0 ? 1 : 0 );
      iElectro.update.product(posArr[ posArr.length - 1 ]);
      iElectro.breadcrumbs.init();
      controllers.all();
    }
  },

  list: {
    init: function(page){
      var listTable = null;
      iElectro.pageShow(page);
      window.location.hash = 'list';
      iElectro.update.product_list();
      // if(toggle){
      //   iElectro.update.product_list();
      //   toggle = 0;
      // }else{
      //   listTable = $('.list_page.flex .goods_list_table');
      //   listTable.find('tbody').empty();
      //   listTable.each(function(i, table){
      //     var id = $(table).data('id'),
      //         tempAll = '';
      //     $.each(db.cat_idx.title[id], function(i, idx){
      //       var elem = db.cat[idx];
      //       _price = (elem.price - ((elem.price / 100) * (profile.auth ? profile.sum_discount : 0))).toFixed(2);
      //       tempAll += iElectro.product.add(elem.id, elem.code, elem.article, elem.name, _price, elem.min_purchase, elem.number_product, idx, elem.img, 1);

      //     });

      //     $(table).find('tbody').html(tempAll);
      //   });
      // }
      controllers.all();
    }
  },

  search: {
    init: function(page){
      var posArr = iElectro.posUrl(),
          tempAll = '',
          goodsSearchTable = document.getElementById('goods_search_table_tbody'),
          optArr = posArr.pop().split(':'),
          priceFrom = parseFloat(typeof optArr[1] == 'undefined' || optArr[1] == '' ? 0 : optArr[1]),
          priceTo = parseFloat(typeof optArr[2] == 'undefined' || optArr[2] == '' ? 10000000 : optArr[2]),
          id = typeof optArr[3] == 'undefined' || optArr[3] == '' ? '' : optArr[3],
          filterObj = [],
          filterArr = [],
          filterArrIdx = [],
          searchResult = null,
          searchResultIdx = [],
          counter = 0,
          sortable = lStorage.prop.sortable;

      iElectro.pageShow(page);
      goodsSearchTable.innerHTML = '';
      optArr[0] = decodeURIComponent(optArr[0].replace(/\+/g,  " "));
      optArr[0] = optArr[0].replace(/\|\|\|/g, '/').replace(/\^\^\^/g, ':');
      filterObj = db.cat;
      

      
      
    
      $.each(filterObj, function(i, item){
        filterArrIdx[i] = item;
      });

     
      searchResult = filterArrIdx.filter(function(item, i){
        
        var _price = (item.price - ((item.price / 100) * (profile.auth ? profile.sum_discount : 0))).toFixed(2);

        if(parseFloat(_price) >= priceFrom && parseFloat(_price) <= priceTo){
          if(id != ''){
            if(item.code == id){
              item.idx = i;
              return true;
            }else{
              return false;
            }
          }else{
            if(item.number_product > 0 && item.name.toLowerCase().indexOf(optArr[0].toLowerCase()) != -1){
              item.idx = i;
              if(optArr[0].length < 2 || optArr[0] == ''){
                ++counter;
                if(counter > 1024){
                  return false;
                }else{
                  return true;
                }
              }else{
                return true;
              }
            }else{
              return false;
            }
          }
        }else{
          return false;
        }
      });

      searchResult.sort(function(a, b){
        if(a[sortable.field] == b[sortable.field]){
          return 0;
        }
        if(sortable.type == 'asc'){
          return a[sortable.field] > b[sortable.field] ? 1 : -1;
        } else {
          return a[sortable.field] > b[sortable.field] ? -1 : 1;
        }
      });

      $.each(searchResult, function(i, item){
        var _price = (item.price - ((item.price / 100) * (profile.auth ? profile.sum_discount : 0))).toFixed(2);
        tempAll += iElectro.product.add(item.id, item.code, item.article, item.name, _price, item.min_purchase, item.number_product, item.idx, item.img, i < lStorage.prop.limVisGoods ? 1 : 0);
      });

      $('.search_page input.search__text').val(optArr[0]);
      $('.gooods_num').html(searchResult.length);
      $('.page.flex .search__price_from').val(optArr[1]);
      $('.page.flex .search__price_to').val(optArr[2]);
      $('.page.flex .search__article').val(optArr[3]);
      goodsSearchTable.innerHTML = tempAll;
      counter = 0;
      controllers.all();
    }
  },

  help: {
    init: function(page){
      var helpPage = iElectro.posUrl().length > 1 ? iElectro.posUrl().pop() : 'search';
      iElectro.pageShow(page);
      $('.help_page a.menu_list__link_help').removeClass('menu_list__link_help_active');
      $('.help_page a.menu_list__link_help[data-type="' + helpPage + '"]').addClass('menu_list__link_help_active');
      $('.help_page__pages').removeClass('flex');
      $('.help_page__' + helpPage).addClass('flex');
      controllers.all();
    }
  },

  settings: {
    init: function(page){
      var tempAll = '',
          settingsFolder = $('.settings__folder'),
          toggle = 0;

      iElectro.pageShow(page);
      settingsFolder.html('');
      $.each(db.catFolder[0].children, function(i, idx){
        var cat = db.catFolder[idx];
        tempAll += iElectro.settings.add(cat.id, cat.title, idx);
      })
      
      settingsFolder.html(tempAll);
      if(typeof profile.cat_images_idx == 'undefined' || profile.cat_images_idx == 'null'){
        return false;
      }
      if(profile.cat_images_idx.length == $('.settings__folder input[type="checkbox"]').length){
        $('.main_sync_checkbox').prop('checked', true);
      }
      $.each(profile.cat_images_idx, function(i, idx){
        $('.settings__folder').find('input[value="' + idx + '"]').prop('checked', true);
      });

      controllers.all();
    }
  },

  all: function(){
    $('.sortable')
      .removeClass('sorted')
      .removeClass('sorted_asc')
      .removeClass('sorted_desc');
      if(typeof lStorage.prop.sortable != 'undefined'){
        $('.page.flex .goods_header_table .sortable[data-field="' + lStorage.prop.sortable.field + '"]').addClass('sorted').addClass('sorted_' + lStorage.prop.sortable.type);
      }
  }

};