$(document).ready(function () {
    "use strict";
    
    var
        isLoadingStat = false,
        $table = $('table.table-striped'),
        $tableLoader = $('.table-data-loading'),
        $pager = $('.b-pager'),
        $pagerStep = $('.b-pager__step'),
        $pagerInfo = $('.b-pager__info'),
        $pagerItems = $('.b-pager__items'),
        $tableWrap = $('.panel-body'),
        $filtersItems = $('.b-filters__items'),
        $filtersCurrent = $('.b-filters__current'),
        $active = $('select.data-active', $tableWrap),
        $period = $('select.data-period', $tableWrap),
        $clicks = $('select.data-clicks', $filtersItems),
        $orders = $('select.data-orders', $filtersItems),
        $partner = $('select.data-partner', $filtersItems),
        $cat = $('select.data-category', $filtersItems),
        $subcat = $('select.data-subcategory', $filtersItems),
        $geo = $('select.data-geo', $filtersItems),
        $applyButton = $('button.btn.btn-primary.apply'),
        $exportExcelButton = $("#btnExport"),
        currentRequesData,
        currentFiltersUrl,
        currentSort,
        currentAsc,
        filtersNames = ['active', 'period', 'clicks', 'orders', 'cat', 'subcat', 'sort', 'asc', 'partner', 'geo'];
    
    
    // Переключение состояния isLoadingStat
    function EnableLoadingState(isLoading)
    {
        if (isLoading) {
            $pager.addClass('state-loading');
            $table.addClass('state-loading');
            $exportExcelButton.hide();
            $tableLoader.show();
        } else {
            $pager.removeClass('state-loading');
            $table.removeClass('state-loading');
            $exportExcelButton.show();
            $tableLoader.hide();
        }
    }
    
    // Устанавливаем данные фильтров:
    function selectFiltersData(isLocationHash)
    {
        var
            active = $active.val(),
            period = $period.val(),
            
            clicks = ($('select.data-clicks', $filtersCurrent).length>0) ? $('select.data-clicks', $filtersCurrent).val() : $clicks.val(),
            orders = ($('select.data-orders', $filtersCurrent).length>0) ? $('select.data-orders', $filtersCurrent).val() : $orders.val(),
            partner = ($('select.data-partner', $filtersCurrent).length>0) ? $('select.data-partner', $filtersCurrent).val() : $partner.val(),
            cat = ($('select.data-category', $filtersCurrent).length>0) ? $('select.data-category', $filtersCurrent).val() : $cat.val(),
            subcat = ($('select.data-subcategory', $filtersCurrent).length>0) ? $('select.data-subcategory', $filtersCurrent).val() : $subcat.val(),
            geo = ($('select.data-geo', $filtersCurrent).length>0) ? $('select.data-geo', $filtersCurrent).val() : $geo.val(),

            sort = currentSort,
            asc = currentAsc,
            filtersUrl = '',
            getHashVars = !(isLocationHash !== undefined && !isLocationHash);
        
        // Устанавливаем фильтры в url:
        if  (getHashVars) {
            filtersUrl += (active) ? '&active=' + active : '';
            filtersUrl += (period) ? '&period=' + period : '';
            filtersUrl += (clicks) ? '&clicks=' + clicks : '';
            filtersUrl += (orders) ? '&orders=' + orders : '';
            filtersUrl += (partner) ? '&partner=' + partner : '';
            filtersUrl += (cat) ? '&cat=' + cat : '';
            filtersUrl += (subcat) ? '&subcat=' + subcat : '';
            filtersUrl += (geo) ? '&geo=' + geo : '';
            filtersUrl += (sort) ? '&sort=' + sort : '';
            filtersUrl += (asc) ? '&asc=' + asc : '';
        }
        
        filtersUrl = (filtersUrl == '') ? '' : '#' + filtersUrl;
        
        history.replaceState( {} , null, location.pathname + filtersUrl);
        
        // Запрос данных в соответствии с установленнымифильтрами:
        var requestData = {
            list: $table.data('content'), 
            period: period
        };
        if (active) requestData['active'] = active;
        if (clicks) requestData['clicks'] = clicks;
        if (orders) requestData['orders'] = orders;
        if (partner) requestData['partner'] = partner;
        if (cat) requestData['cat'] = cat;
        if (subcat) requestData['subcat'] = subcat;
        if (geo) requestData['geo'] = geo;
        if (sort) requestData['sort'] = sort;
        if (asc) requestData['asc'] = asc;
        
        setFiltersControls(requestData);
        
        currentRequesData = requestData;
        currentFiltersUrl = filtersUrl
        
        requestDataFilters(requestData);
    }
    
    // Запрос данных для таблицы, в соответствии с фильтрами:
    function requestDataFilters(dataRequest)
    {
        dataRequest['step'] = parseInt($('select', $pagerStep).val());
        
        //console.log("AAA requestDataStatReport: ", dataRequest);
        
        isLoadingStat = true;
        EnableLoadingState(isLoadingStat);
        
        $.ajax({
            url: $applyButton.attr('data-link'),
            method: 'POST',
            data: dataRequest,
            success: function(res) {
                isLoadingStat = false;
                EnableLoadingState(isLoadingStat);
                
                if (res == null) {
                    console.log("AAA requestDataStatReport success res: NULL");
                } else if (res.status == 'Error') {
                    console.log("AAA requestDataStatReport error");
                } else {
                    //console.log("AAA requestDataStatReport success res: SUCCESS", res);
                    renderTable(res.data);
                    renderPager([res.pager, res.info]);
                    markSortTable(res.sort);
                }
            },
            error: function (e) {
                console.log('error: ', e);
                isLoadingStat = false;
                EnableLoadingState(isLoadingStat);
            }
        });
    }

    // Отрисовка таблицы:
    function renderTable(data)
    {
        var 
            $tableBody = $('tbody', $table),
            $tableContent = $('<tbody>');
    
        //console.log('AAA item = ', data[1]);
        for (var i = 0; i < data.length; i++) {
          
            var
                item = data[i],
                $tr;
            
            switch($table.data('content')) {
                case 'offers':
                    $tr = createOfferTr(item);
                break;
                case 'teasers':
                    $tr = createTeaserTr(item);
                break;
                case 'keys':
                    $tr = createKeyTr(item);
                break;
                case 'cpasites':
                    $tr = createSiteTr(item);
                break;
                case 'cpazones':
                    $tr = createZoneTr(item);
                break;
            }
            
            $tr.appendTo($tableContent);
        }

        $tableBody.html('').append($tableContent.children());
    }

    // Отрисовка пейджера:
    function renderPager(dataPager)
    {
        var
            data = dataPager[0],
            info = dataPager[1];
        
        if (data) {
            var $pagerContent = $('<ul>');

            // Отображать "<"
            if (data[1] > 1) {
                $('<li data-page="' + (data[1]-1) + '"> &lt; </li>').appendTo($pagerContent);
            }
            // Страниц не больше 7
            if (data[0] < 8) {
                for (var i = 0; i < data[0]; i++) {
                    $('<li' + ((i+1 == data[1]) ? ' class="current"' : '') + ' data-page="' + (i+1) + '">' + (i+1) + '</li>').appendTo($pagerContent);
                }
            } else {
                if (data[1]<5) {
                    for (var i = 0; i < 5; i++) {
                        $('<li' + ((i+1 == data[1]) ? ' class="current"' : '') + ' data-page="' + (i+1) + '">' + (i+1) + '</li>').appendTo($pagerContent);
                    }
                    $('<li class="not-active"> ... </li>').appendTo($pagerContent);
                    $('<li data-page="' + data[0] + '">' + data[0] + '</li>').appendTo($pagerContent);
                }
                if (data[1]>=5 && data[1]<=data[0]-3) {
                    $('<li data-page="' + 1 + '">' + 1 + '</li>').appendTo($pagerContent);
                    $('<li class="not-active"> ... </li>').appendTo($pagerContent);
                    for (var i = data[1]-2; i < data[1]+1; i++) {
                        $('<li' + ((i+1 == data[1]) ? ' class="current"' : '') + ' data-page="' + (i+1) + '">' + (i+1) + '</li>').appendTo($pagerContent);
                    }
                    $('<li class="not-active"> ... </li>').appendTo($pagerContent);
                    $('<li data-page="' + data[0] + '">' + data[0] + '</li>').appendTo($pagerContent);
                }
                if (data[1]>data[0]-3) {
                    $('<li data-page="' + 1 + '">' + 1 + '</li>').appendTo($pagerContent);
                    $('<li class="not-active"> ... </li>').appendTo($pagerContent);
                    for (var i = data[0]-5; i < data[0]; i++) {
                        $('<li' + ((i+1 == data[1]) ? ' class="current"' : '') + ' data-page="' + (i+1) + '">' + (i+1) + '</li>').appendTo($pagerContent);
                    }
                }
            }
            // Отображать ">"
            if (data[1] < data[0]) {
                $('<li data-page="' + (data[1]+1) + '"> &gt; </li>').appendTo($pagerContent);
            }
            
            $pagerItems.html('').append($pagerContent);
        }
        
        if (info) {
            $('.from', $pagerInfo).text(info.items_interval[0]);
            $('.to', $pagerInfo).text(info.items_interval[1]);
            $('.total', $pagerInfo).text(info.items_count);
        }
    }
    
    // Показываем сортировку в таблице:
    function markSortTable(dataSort)
    {
        var $sortTr = $('thead th span[data-sort="' + dataSort[0] + '"]', $table);
        $('thead th span', $table).removeClass('current').removeClass('asc').removeClass('desc');
        $sortTr.addClass('current').addClass((dataSort[1]>0) ? 'desc' : 'asc').attr('data-sortasc', (dataSort[1]>0) ? -1 : 1);
    }
    
    // Offers
    function createOfferTr(item)
    {
        var offerLink = $table.data('offerlink').replace("offer_id", item.id);
        var $tr = $('<tr ' + ((parseInt(item.disabled)) ? 'class="disabled"' : '') + ' data-id="' + item.id + '">');
        
        $('<td><input class="is-active" type="checkbox"><span class="item-id">' + item.id + '</span></td>').appendTo($tr);
        $('<td><a href="' + offerLink + '"><span class="item-title">' + item.title + '</span></a><div class="offer-info">объявлений: <b>' + item.adds_count + '</b> лендингов: <b>' + item.landings_count + '</b></div></td>').appendTo($tr);
        
        $('<td class="stat"><span class="item-views">' + ((item.Views) ? item.Views : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-clicks">' + ((item.Clicks) ? item.Clicks : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-ctr">' + ((item.ctr) ? item.ctr : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-orders">' + ((item.orders) ? item.orders : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cl">' + ((item.cl) ? item.cl : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-money">' + ((item.Money) ? item.Money : 0) + ' $</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpc">' + ((item.cpc) ? item.cpc : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpm">' + ((item.cpm) ? item.cpm : 0) + '</span></td>').appendTo($tr);
        
        return $tr;
    }

    // Teasers
    function createTeaserTr(item)
    {
        var offerLink = $table.data('offerlink').replace("offer_id", item.ad.offer_id);
        var $tr = $('<tr ' + ((parseInt(item.ad.disabled)) ? 'class="disabled"' : '') + ' data-id="' + item.id + '">');
        $('<td><input class="is-active" type="checkbox" ' + (!(parseInt(item.ad.disabled)) ? 'checked' : '') + ' disabled> <span class="item-id">' + item.ad.id + '</span></td>').appendTo($tr);
        $('<td><div class="image-wrap"><img src="' + item.ad.img + '?' + new Date().getTime() + '" width="100" height="100" /></div></td>').appendTo($tr);
        $('<td><div class="title">' + item.ad.title_value + '</div><div class="desc">' + item.ad.desc_value + '</div><div><a href="' + item.ad.link_value + '" target="_blank">' + item.ad.link_title + '</a></div><div class="price">' + item.ad.price_value + '</div><a class="link-offer" href="' + offerLink + '">Оффер объявления</a></td>').appendTo($tr);
        $('<td class="stat"><span class="item-views">' + ((item.Views) ? item.Views : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-clicks">' + ((item.Clicks) ? item.Clicks : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-ctr">' + ((item.ctr) ? item.ctr : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-orders">' + ((item.orders) ? item.orders : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cl">' + ((item.cl) ? item.cl : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-money">' + ((item.Money) ? item.Money : 0) + ' $</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpc">' + ((item.cpc) ? item.cpc : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpm">' + ((item.cpm) ? item.cpm : 0) + '</span></td>').appendTo($tr);
        
        return $tr;
    }

    // Keys
    function createKeyTr(item)
    {
        var offerLink = $table.data('offerlink').replace("offer_id", item.ad.offer_id);
        var $tr = $('<tr ' + ((parseInt(item.ad.disabled)) ? 'class="disabled"' : '') + ' data-id="' + item.ad_id + '" data-cat=\'' + item.ad.cat + '\' data-partners=\'' + item.ad.partners + '\'>');
        $('<td><input class="is-active" type="checkbox" ' + (!(parseInt(item.ad.disabled)) ? 'checked' : '') + ' disabled><span class="item-id">' + item.ad_id + '</span><br /><span style="padding-left: 17px; font-weight: normal; font-size: 12px;">' + item.ad.offer_id + '</span></td>').appendTo($tr);
        $('<td><div class="title">' + item.ad.title_value + '</div><div class="desc">' + item.ad.desc_value + '</div><div><a href="' + item.ad.link_value + '" target="_blank">' + item.ad.link_title + '</a></div><div class="price">' + item.ad.price_value + '</div><a class="link-offer" href="' + offerLink + '">Оффер объявления</a></td>').appendTo($tr);
        $('<td class="stat"><span style="white-space: normal;">[' + item.land_id + ']&nbsp;' + item.land_title + '<br/>' + item.ad_data_id + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-views">' + ((item.Views) ? item.Views : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-clicks">' + ((item.Clicks) ? item.Clicks : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-ctr">' + ((item.ctr) ? item.ctr : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-orders">' + ((item.orders) ? item.orders : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cl">' + ((item.cl) ? item.cl : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-money">' + ((item.Money) ? item.Money : 0) + ' $</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpc">' + ((item.cpc) ? item.cpc : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpm">' + ((item.cpm) ? item.cpm : 0) + '</span></td>').appendTo($tr);
        
        return $tr;
    }

    // CPA sites
    function createSiteTr(item)
    {
        var $tr = $('<tr data-id="' + item.id + '">');
        $('<td><span class="item-id">' + item.id + '</span></td>').appendTo($tr);
        $('<td><span class="item-title">' + item.title + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-views">' + ((item.Views) ? item.Views : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-clicks">' + ((item.Clicks) ? item.Clicks : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-ctr">' + ((item.ctr) ? item.ctr : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-orders">' + ((item.orders) ? item.orders : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cl">' + ((item.cl) ? item.cl : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-money">' + ((item.Money) ? item.Money : 0) + ' $</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpc">' + ((item.cpc) ? item.cpc : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpm">' + ((item.cpm) ? item.cpm : 0) + '</span></td>').appendTo($tr);
        
        return $tr;
    }
    
    // CPA zones
    function createZoneTr(item)
    {
        var $tr = $('<tr data-id="' + item.id + '">');
        $('<td style="font-size: 12px;line-height: 14px;"><span class="item-id">' + item.id + ' (' + item.size + ')<br /><b>' + item.site + '</b></span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-views">' + ((item.Views) ? item.Views : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-clicks">' + ((item.Clicks) ? item.Clicks : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-ctr">' + ((item.ctr) ? item.ctr : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-orders">' + ((item.orders) ? item.orders : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cl">' + ((item.cl) ? item.cl : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-money">' + ((item.Money) ? item.Money : 0) + ' $</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpc">' + ((item.cpc) ? item.cpc : 0) + '</span></td>').appendTo($tr);
        $('<td class="stat"><span class="item-cpm">' + ((item.cpm) ? item.cpm : 0) + '</span></td>').appendTo($tr);
        
        return $tr;
    }

    // Распарсиваем строку URL с фильтрами:
    var
        hashUrl = location.hash.replace('#', '').split('&'),
        isLocationHash = (location.hash == "") ? false : true,
        currentFilters = [];

    hashUrl.forEach(function(item) {
        if (item != '' && item.indexOf('=')>-1) {
            var
                filterItem = item.split('='),
                filterName = filterItem[0],
                filterValue = (filterItem[1] == '') ? null : filterItem[1].split(',');
            
            if (filtersNames.indexOf(filterName) != -1 && filterValue) {
                currentFilters[filterName] = filterValue;
            }
        }
    });
    
    // Устанавливаем по url фильтры в контролах:
    if (Object.keys(currentFilters).length > 0) {
        setFiltersControls(currentFilters);
        if (currentFilters['partner']) $partner.val(currentFilters['partner']);
        if (currentFilters['geo']) $geo.val(currentFilters['geo']);
        if (currentFilters['clicks']) $clicks.val(currentFilters['clicks']);
        if (currentFilters['orders']) $orders.val(currentFilters['orders']);
        if (currentFilters['cat']) $cat.val(currentFilters['cat']).change();
        if (currentFilters['subcat']) $subcat.val(currentFilters['subcat']);
        if (currentFilters['active']) $active.val(currentFilters['active']);
        if (currentFilters['period']) $period.val(currentFilters['period']);
        if (currentFilters['sort']) currentSort = currentFilters['sort'][0];
        if (currentFilters['asc']) currentAsc = currentFilters['asc'][0];
    }

    // Стартовая фильтрация:
    selectFiltersData(isLocationHash);
    
    function setCurrentFilters(filtersUrl)
    {
        var
            hashUrl = filtersUrl.replace('#', '').split('&'),
            currentFilters = [];
    
        hashUrl.forEach(function(item) {
            if (item != '' && item.indexOf('=')>-1) {
                var
                    filterItem = item.split('='),
                    filterName = filterItem[0],
                    filterValue = (filterItem[1] == '') ? null : filterItem[1].split(',');

                if (filtersNames.indexOf(filterName) != -1 && filterValue) {
                    currentFilters[filterName] = filterValue;
                }
            }
        });

        // Устанавливаем фильтры по url:
        $active.val((currentFilters['active']) ? currentFilters['active'] : '');
        $period.val((currentFilters['period']) ? currentFilters['period'] : 'total');
        $geo.val((currentFilters['geo']) ? currentFilters['geo'] : '');
        $partner.val((currentFilters['partner']) ? currentFilters['partner'] : '');
        $cat.val((currentFilters['cat']) ? currentFilters['cat'] : '');
        $subcat.val((currentFilters['subcat']) ? currentFilters['subcat'] : '');
        $clicks.val((currentFilters['clicks']) ? currentFilters['clicks'] : '');
        $orders.val((currentFilters['orders']) ? currentFilters['orders'] : '');
        setFiltersControls(currentFilters);
    }
    
    // Клик на "Применить"
    $applyButton.click(function(){
        selectFiltersData();
    });
    
    // Клик на страницу пейджера:
    $pager.on('click', 'li', function(){
        var $pagerItem = $(this);
        
        if (!$pagerItem.hasClass('current') && !$pagerItem.hasClass('not-active')) {
            setCurrentFilters(currentFiltersUrl);
            currentRequesData['page'] = parseInt($pagerItem.data('page'));
            requestDataFilters(currentRequesData);
        }
    });
    
    // Смена шага пейджера:
    $('select', $pagerStep).on('change', function(){
        var $stepValue = $(this).val();
        $('select', $pagerStep).val($stepValue);
        currentRequesData['page'] = null;
        setCurrentFilters(currentFiltersUrl);
        requestDataFilters(currentRequesData);
    });
    
    // Сортировка в таблице:
    $('table.table-striped thead th span.sort').on('click', function(){
        var
            $this = $(this),
            sort = $this.data('sort'),
            asc = $this.attr('data-sortasc'),
            filtersSortUrl = '',
            currentSortUrl = '';
        
        if (currentRequesData['sort']) {
            currentSortUrl += '&sort=' + currentRequesData['sort'];
        }
        if (currentRequesData['asc']) {
            currentSortUrl += '&asc=' + currentRequesData['asc'];
        }
        
        currentRequesData['sort'] = sort;
        currentRequesData['asc'] = asc;
        
        currentSort = sort;
        currentAsc = asc;
        
        if (currentSortUrl) {
            currentFiltersUrl = currentFiltersUrl.replace(currentSortUrl, '');
        }
        
        // Добавляем фильтры в url:
        filtersSortUrl += '&sort=' + sort + '&asc=' + asc;
        filtersSortUrl = (currentFiltersUrl == '') ? '#' + filtersSortUrl : currentFiltersUrl + filtersSortUrl;
        
        history.replaceState( {} , null, location.pathname + filtersSortUrl);
        
        setCurrentFilters(currentFiltersUrl);
        requestDataFilters(currentRequesData);
    });
    
    // Выгрузка таблицы в Excel
    $exportExcelButton.click(function(){
        $("#table2excel").table2excel({
            exclude: ".noExl",
            name: "Worksheet Name",
            filename: $table.data('content') + '.xls'
        });
    });
    
    // Управление фильтрами:
    (function(){
        var
            $filtersShow = $('.b-filters__show');
        
        // Показать фильтры:
        $filtersShow.on('click', function(){
           $filtersItems.toggle();
        });
        
    })();
    
    // Устанавливаем набор фильтров по данным:
    function setFiltersControls(filters)
    {
        var
            filtersList = ['clicks', 'orders', 'cat', 'partner', 'geo'],
            name;
        
        $filtersCurrent.empty();
        
        if (Object.keys(filters).length > 0) {
            
            filtersList.forEach(function(item) {
                
                name = item;
                if (item == 'cat') {
                    name = 'category';
                }
                
                var $filterItemList = $('.form-group.' + name, $filtersItems).parents('.b-filters__list-item');
                
                if (filters[item]) {
                    
                    var $itemFilter = $filterItemList.clone();

                    if (item == 'cat') {
                        $('select.form-control.data-category', $itemFilter).val(filters['cat']);
                        $('select.form-control.data-subcategory', $itemFilter).val(filters['subcat']);
                        $('select.form-control.data-category', $filtersItems).val(filters['cat']);
                        $('select.form-control.data-subcategory', $filtersItems).val(filters['subcat']);
                    } else {
                        $('select.form-control', $itemFilter).val(filters[name]);
                        $('select.form-control.data-' + name, $filtersItems).val(filters[name]);
                    }
                    $filterItemList.hide();
                    $itemFilter.show();
                    $filtersCurrent.append($itemFilter);
                } else {
                    if (item == 'cat') {
                        $('select.form-control.data-category', $filtersItems).val('');
                        $('select.form-control.data-subcategory', $filtersItems).val('');
                    } else {
                        $('select.form-control.data-' + name, $filtersItems).val('');
                    }
                    $filterItemList.show();
                }
                
            });
        }
            
    }
    
});