$(window).ready(function() {
	// Свернуть/Развернуть категории
	$('#toggleCats').on('click', function() {
		toggleSubCat('sub-cat');
	});

	// Свернуть/Развернуть теги
	$('#toggleTags').on('click', function() {
		toggleLand();
	});

	// Свернуть/Развернуть На поиске
	$('#toggleSearchCats').on('click', function() {
		toggleSearchCat();
	});
});

function toggleSearchCat() {
	var $button = $('#toggleSearchCats');
	var a = $("#toggleSearchCats > a");
	if ($button.hasClass('show-search-cat')) {
		$('.js-search-category__list').fadeOut(150);
		a.text(a.data('show-text'));
	} else {
		$('.js-search-category__list').fadeIn(300);
		a.text(a.data('hide-text'));
	}
	$button.toggleClass('show-search-cat');
}

function toggleSubCat(par) {
	var $button = $('#toggleCats');
	var $a = $button.find('a');

	if ($button.hasClass('show-cat')) {
		if (par !== 'only-view') {
			if (par === 'sub-cat') {
				showSubCat();
			} else if (par === 'sub-attr') {
				showSubCat();
				showSubAttr();
			}
		}
		$a.text($a.data('hide-text'));
	} else {
		if (par !== 'only-view') {
			if (par === 'sub-cat') {
				hideSubCat();
			} else if (par === 'sub-attr') {
				hideSubCat();
			}
		}
		$a.text($a.data('show-text'));
	}

	$button.toggleClass('show-cat');
}
// Показывает категории
function showSubCat() {
	$('#foxdontshowcats').find('li').removeClass('hide');
}
// Скрывает категории
function hideSubCat() {
	var sub_cat_list = '';
	// если есть категории 3 уровня, то ниже скрывать будем только их
	if ($('.subcats > .sub_cat_list').length > 0) {
		sub_cat_list = '.sub_cat_list li';
	}
	$('#foxdontshowcats li ' + sub_cat_list).not('.active').addClass('hide');

	if (isAttr == 1) {
		e = $('.subsubcats.active');
		if (e.length) {
			if (e.find('ul > li').length) {
				e.find('ul').removeClass('hide');
				e.find('ul > li').removeClass('hide');
			}
		} else {
			a = $('.sub_attr_li.active');
			if (a.length) {
				a.parent().removeClass('hide').parent().removeClass('hide').parent().removeClass('hide');
			}
		}
	}
}

// Показывает атрибуты
function showSubAttr() {
	$('.sub_attr_list').find('li').removeClass('hide');

}
// Скрывает атрибуты
function hideSubAttr() {
	$('.sub_attr_list').not('.active').addClass('hide');
}

//////////////////
// Кнопка и контент Тегов (похожих лотов)
function toggleLand() {
	var $button = $('#toggleTags');
	if ($button.hasClass('show-land')) {
		showSubLand();
	} else {
		hideSubLand();
	}
	$button.toggleClass('show-land');
}

function showSubLand() {
	$('.sub_land').fadeIn();
}

function hideSubLand() {
	$('.sub_land').fadeOut(150);
}
/////////////////Кнопка и контент Тегов

var CatFilterModule = (function() {
	var $_form = {};
	var _params = {};
	var _baseParams = {};
	var _clearClass = '.filter-clear';
	var _blockContentClass = '.card__content-body';
	var _onChangeInput = function() {
		var $currentEl = $(this);
		_params = _baseParams;
		_params['page'] = 1;
		_rebuildParam($currentEl);
		_reloadFilter();
	};

	var _reloadFilter = function() {
		_setLinkTypeParams();
		_pushUrlHistory();
		_load();
		_rebuildClearLinks();
	};

	var _preloaderIco = '<div style="height: 50px;position:relative;"><div class="preloader__ico preloader__ico_small"></div></div>';

	var _pushUrlHistory = function() {
		var newUrl = implodeURI(_params);
		window.history.pushState({
			urlPath: newUrl
		}, "", newUrl);
	};

	var _load = function() {
		_params['page'] = 1;
		_params['is_attr'] = isAttr;
		$('.cusongslist').html(_preloaderIco);
		$('.loadDodjis').hide();
		$.get('', _params, function(response) {
			$('.cusongslist').html(response.html);
			if (response.paging.page * response.paging.items_per_page < response.paging.total) {
				$('.loadDodjis').show();
			}
			if (response.paging.total > 0) {
				$('.prds-filter.no-results').hide();
			} else {
				$('.prds-filter.no-results').show();
			}
		}, 'json');
	};

	var _rebuildParam = function($currentEl) {
		var name = $currentEl.attr('name');
		var value = $currentEl.val();

		_params[name] = value;
	};

	var _resetFilter = function() {
		$('.js-prd-filter-input').each(function() {
			if ($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio') {
				$(this).prop('checked', false);
				if ($(this).data('default')) {
					$(this).prop('checked', true);
				}
			} else {
				$(this).val($(this).data('default'));
			}
		});
	};

	var _rebuildFilter = function() {
		_params = window
			.location
			.search
			.replace('?', '')
			.split('&')
			.reduce(
				function(p, e) {
					var a = e.split('=');
					if (decodeURIComponent(a[0]))
						p[decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
					return p;
				}, {}
			);

		for (var baseParam in _baseParams) {
			_params[baseParam] = _baseParams[baseParam];
		}
		var gp = getGetParams();
		for (var paramName in gp) {
			_params[paramName] = gp[paramName];
		}

		_resetFilter();

		for (var paramName in _params) {
			$filter = $('.js-prd-filter-input[name="' + paramName + '"]');
			if ($filter.length) {
				if ($filter.attr('type') == 'checkbox') {
					if (_params[paramName]) {
						$filter.prop('checked', true);
					} else {
						$filter.prop('checked', false);
					}
				} else if ($filter.attr('type') == 'radio') {
					$filter.each(function() {
						if ($(this).val() == _params[paramName]) {
							$(this).prop('checked', true);
						}
					});
				} else {
					$filter.val(_params[paramName]);
				}
			}
		}
	};

	var _setLinkTypeParams = function() {
		var $linkTypes = $('.js-prd-filter-lt-input');

		var name = $($linkTypes[0]).attr('name');
		var linkTypesValues = [];
		var hasUnchecked = false;
		$linkTypes.each(function() {
			if ($(this).is(':checked')) {
				linkTypesValues.push($(this).val());
			} else {
				hasUnchecked = true;
			}
		});

		if (hasUnchecked) {
			_params[name] = linkTypesValues;
		} else {
			delete _params[name];
		}
	};

	var _onChangeLinkTypeInput = function() {
		if (!$('.js-prd-filter-lt-input').filter(":checked").length) {
			$(this).prop('checked', true);
			return false;
		}

		_onChangeInput();
	};

	var _clearBlockFilter = function() {
		var $el = $(this);
		var $parent = $el.closest(_blockContentClass);
		var name = $el.attr('data-name');
		var nameArr = name.split(' ') || [];

		$el.hide();
		$parent.find('input').prop('checked', false).removeAttr('checked');
		_removeFilterForUrl(nameArr);
	};

	var _removeFilterForUrl = function(nameFilterArr) {
		var params = _getCurrentParams();

		for (var i in nameFilterArr) {
			var name = nameFilterArr[i];
			delete _params[name];
		}
		_pushUrlHistory();
		_load();
	};

	var _setEvents = function() {
		$_form.on('change', '.js-prd-filter-input:not(.js-prd-filter-input-text)', _onChangeInput);
		$_form.on('change', '.js-prd-filter-lt-input', _onChangeLinkTypeInput);
		$_form.on('change', 'input[type="radio"]', _setActiveInput);
		$_form.on('click', '.subId', _setActiveLanding);
		$_form.on('click', '.attrId', _setActiveSubAttr);
		$_form.on('click', _clearClass, _clearBlockFilter);
		$_form.on('click', '.js-prd-filter-input[name="price"]', _resetPriceFilterInputs);
		$_form.on('keyup', '.price-filter-input', _onKeyupPriceFilter);
		$_form.on('keydown', '.price-filter-input', _onKeydownPriceFilter);
		$_form.on('focusin', '.price-filter-input', _onFocusInPriceFilter);
		$_form.on('focusout', '.price-filter-input', _onFocusOutPriceFilter);
		$_form.on('click', '.price-filter-input__box', _triggerFocusOnField);
		$_form.on('click', '.price-filter-input__clear', _clearPriceFilterInput);

		var _onInput = Utils.debounce(_onChangeInput, 1000);
		$_form.on('input', '.js-prd-filter-input-text', _onInput);

		window.onpopstate = function() {
			//		_rebuildFilter();
			//		_load();
		};
	};

	var _setActiveLanding = function(e) {
		var $el = $(this);
		var subId = $el.data('land-id');

		$el.parents('ul').find('li.active a .arrow').removeClass('hide');
		$el.parents('ul').find('li.active').removeClass('active');
		$el.parent('li').addClass('active');

		if (e.originalEvent) {
			topFilters.setActiveFilter(subId);
		}

		if (isAttr == 1) {
			if ($el.parent().find('ul > li').length) {

				if ($('.subsubcats:visible').not('.active').length) {
					$('.subsubcats:visible').not('.active').addClass('hide');
					toggleSubCat('only-view');
				}

				$el.parent().find('ul').removeClass('hide');

				var nestedItems = $el.parent().find('ul > li');

				if (nestedItems.length) {
					nestedItems.removeClass('hide');

					var itemsObject = [];
					nestedItems.each(function(index) {
						var itemId = $(this).find('a').attr('data-land-id');
						if (typeof itemId === 'undefined') {
							itemId = $(this).find('a').attr('data-subattr-id');
						}
						itemsObject.push({
							seo: $(this).text(),
							id: itemId,
						});
					});
					topFilters
						.refresh({
							items: itemsObject
						});
				}

			} else {
				$('.sub_attr_list').addClass('hide');
			}
		}

		refreshBreadCrumbs($el, 'subid', subId);

		$('.sort-by_block').find('select.js-sort-by option').each(function() {
			var newHref = Utils.updateQueryString('subid', subId, $(this).val());
			newHref = Utils.updateQueryString('is_attr', isAttr, newHref);
			newHref = Utils.updateQueryString('id_sub_attr', null, newHref);
			$(this).val(newHref);
		});

		$('.sort-by_container').find('a').each(function() {
			var newHref = Utils.updateQueryString('subid', subId, $(this).attr('href'));
			newHref = Utils.updateQueryString('is_attr', isAttr, newHref);
			newHref = Utils.updateQueryString('id_sub_attr', null, newHref);
			$(this).attr('href', newHref);
		});

		refreshBreadCrumbs($el, 'subid', subId);

		$('.sort-by_block').find('select.js-sort-by option').each(function() {
			var newHref = Utils.updateQueryString('subid', subId, $(this).val());
			newHref = Utils.updateQueryString('is_attr', isAttr, newHref);
			newHref = Utils.updateQueryString('id_sub_attr', null, newHref);
			$(this).val(newHref);
		});

		$('.sort-by_container').find('a').each(function() {
			var newHref = Utils.updateQueryString('subid', subId, $(this).attr('href'));
			newHref = Utils.updateQueryString('is_attr', isAttr, newHref);
			newHref = Utils.updateQueryString('id_sub_attr', null, newHref);
			$(this).attr('href', newHref);
		});

		_params['subid'] = subId;
		_params['is_attr'] = isAttr;
		_params['recalculate_price_filters'] = 1;
		delete _params['price'];
		delete _params['id_sub_attr'];
		_reloadFilter();
		delete _params['recalculate_price_filters'];
		_pushUrlHistory();
	};

	var _setActiveSubAttr = function(e) {
		var $el = $(this);
		if ($el.parent().hasClass('active')) {
			return false;
		}
		var subAttrId = $el.data('subattr-id');
		if (subAttrId === undefined) {
			subAttrId = 0;
		}
		_params['id_sub_attr'] = subAttrId;

		$el.parents('ul').find('.arrow.hide').removeClass('hide');

		$el.parents('ul').find('li.active').removeClass('active');
		$el.parent('li').addClass('active');

		if (e.originalEvent !== undefined) {
			topFilters.setActiveFilter(subAttrId);
		}

		s = $el.parent('li').parent('ul').parent('li').siblings('li:visible');
		if (s.length) {
			s.fadeOut();
			toggleSubCat('only-view');
		}

		refreshBreadCrumbs($el, 'id_sub_attr', subAttrId);

		$('.sort-by_block').find('select.js-sort-by option').each(function() {
			var newHref = Utils.updateQueryString('id_sub_attr', subAttrId, $(this).val());
			$(this).val(newHref);
		});

		$('.sort-by_container').find('a').each(function() {
			var newHref = Utils.updateQueryString('id_sub_attr', subAttrId, $(this).attr('href'));
			$(this).attr('href', newHref);
		});

		_params['recalculate_price_filters'] = 1;
		delete _params['price'];
		_reloadFilter();
		delete _params['recalculate_price_filters'];
		_pushUrlHistory();
	};

	var refreshBreadCrumbs = function($el, queryKey, val) {
		var BCContainerSelector = $('.bread-crump'),
			attrLevel = parseInt($el.attr('data-level'));

		BCContainerSelector.find('li[data-item-type="attribute"]').each(function() {
			var itemLevel = parseInt($(this).attr('data-level'));
			if (itemLevel > attrLevel) {
				$(this).remove();
			}
		});

		var lastBCItem = BCContainerSelector.find('li:last');
		lastBCItem.find('a').removeAttr('href');
		lastBCItem.find('.bread-crump-delimiter').remove();

		var needBreadCrumbItem = BCContainerSelector.find('li[data-item-type="attribute"]').filter('[data-level="' + attrLevel + '"]');

		var prevHref = '',
			newHref = '';
		if (!needBreadCrumbItem.length) {
			var prevPosition = parseInt(lastBCItem.find('meta').attr('content'));
			prevHref = lastBCItem.find('a').attr('data-href');
			newHref = Utils.updateQueryString('is_attr', 1, prevHref);
			newHref = Utils.updateQueryString(queryKey, val, newHref);

			var newListItem = lastBCItem.clone(true);
			newListItem.attr('data-item-type', 'attribute');
			newListItem.attr('data-level', attrLevel);
			newListItem.find('a').removeAttr('href');
			newListItem.find('a').attr('data-href', newHref);
			newListItem.find('.bread-crumb-title').text($el.find('.left-filters-attr-title').text());
			newListItem.find('meta').attr('content', prevPosition + 1);

			lastBCItem.append('<span class="bread-crump-delimiter">&nbsp;&nbsp;</span>');
			lastBCItem.find('a').attr('href', lastBCItem.find('a').attr('data-href'));
			BCContainerSelector.find('ol').append(newListItem)
		} else {
			needBreadCrumbItem.find('.bread-crumb-title').text($el.find('.left-filters-attr-title').text());
			prevHref = needBreadCrumbItem.find('a').attr('data-href');
			newHref = Utils.updateQueryString(queryKey, val, prevHref);
			needBreadCrumbItem.find('a').attr('data-href', newHref);
		}
	};

	var _setActiveInput = function() {
		var $el = $(this);
		var name = $el.attr('name');

		$_form.find('input[name="' + name + '"]').prop('checked', false).removeAttr('checked');
		$el.prop('checked', true).attr('checked', 'checked');
	};

	var _initClearLinksForBlocks = function() {
		var $blocks = $_form.find(_blockContentClass);

		$blocks.each(function() {
			var $el = $(this);
			var $link = $el.find(_clearClass);
			var names = [];

			// собрать все имена input-ов блока
			$el.find('input').each(function() {
				names.push($(this).attr('name'));
			});
			names = Utils.uniqueArray(names);
			names = names.join(' ');

			$link.attr('data-name', names);
		});
	};

	var _initActiveSubCategory = function() {
		var params = _getCurrentParams();

		if (isAttr != 1) {
			hideSubCat();
		}

		if (params['subid']) {
			var subid = params['subid'];
			var subCat = $('#foxdontshowcats').find('a[data-land-id="' + subid + '"]');

			$('.subcats').removeClass('active');
			subCat.parents('ul').removeClass('active');

			$('.sub_attr_list').addClass('hide');
			if (isAttr == 1 && params['is_attr'] == 1 && subCat.parent().find('ul > li').length) {
				subCat.parent().find('ul').removeClass('hide');
				subCat.parent().find('ul > li').removeClass('hide');
			}
		} else {
			if (isAttr == 1) {
				$('.sub_attr_list').addClass('hide');
			}
		}
	};

	var allowedKeyCodes = [8, 9, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105],
		arrowsKeyCodes = [37, 38, 39, 40];
	var _onKeydownPriceFilter = function(e) {
		var keyCode = e.keyCode || e.which;
		if (allowedKeyCodes.concat(arrowsKeyCodes).indexOf(keyCode) === -1) {
			return false;
		}
	};

	var priceFilterInputTimer,
		timeoutValue = 800,
		priceFiltersTestRegExp = new RegExp(/^[0-9]*$/);

	var _onKeyupPriceFilter = function(e) {
		var _this = $(this),
			keyCode = e.keyCode || e.which;

		if (allowedKeyCodes.indexOf(keyCode) === -1) {
			return false;
		}

		if (_this.val().length && _this.next('.price-filter-input__clear').hasClass('input__clear-hidden')) {
			_this.next('.price-filter-input__clear').removeClass('input__clear-hidden');
		} else if (!_this.val().length && !_this.next('.price-filter-input__clear').hasClass('input__clear-hidden')) {
			_this.next('.price-filter-input__clear').addClass('input__clear-hidden');
		}

		if (_this.hasClass('price-filter-input-error')) {
			_this.removeClass('price-filter-input-error');
		}

		clearTimeout(priceFilterInputTimer);
		priceFilterInputTimer = setTimeout(function() {
			$('.js-prd-filter-input[name="price"]')
				.prop('checked', false)
				.removeAttr('checked');

			_this
				.closest('.card__content-body')
				.find(_clearClass)
				.hide();

			var priceValue = '',
				inputError = false;
			$('.price-filter-input').each(function() {
				var elementValue = $(this).val();
				if (priceFiltersTestRegExp.test(elementValue)) {
					var fieldVal = elementValue.length ? parseFloat(elementValue) : '';
					priceValue += priceValue.length ? fieldVal : fieldVal;// + '_';
				} else {
					$(this).addClass('price-filter-input-error');
					inputError = true;
				}
			});

			_params[_this.attr('name')] = priceValue;

			if (!inputError) {
				_load();
				if (priceValue === '_') {
					delete _params[_this.attr('name')];
				}
				_pushUrlHistory();
			}
			timeoutValue = 1000;
		}, timeoutValue);
	};

	var _onFocusInPriceFilter = function() {
		$(this)
			.closest('.price-filter-input__box')
			.addClass('price-filter-input__box-focused');
	};

	var _onFocusOutPriceFilter = function() {
		$(this)
			.closest('.price-filter-input__box')
			.removeClass('price-filter-input__box-focused');
	};

	var _triggerFocusOnField = function() {
		if (!$(this).find('input').is(':focus')) {
			$(this).find('input').trigger('focus');
		}
	};

	var _clearPriceFilterInput = function(e) {
		e.stopPropagation();
		var customEvent = $.Event('keyup');
		customEvent.which = 8;
		timeoutValue = 200;
		$(this).prev('input').val('').trigger(customEvent);
		$(this).addClass('input__clear-hidden');
	};

	var _resetPriceFilterInputs = function() {
		$('.price-filter-input').val('');
	};

	var _rebuildClearLinks = function() {
		var params = _getCurrentParams();
    var getparams = getGetParams();
    var paramname = '';

		for (var i in params) {
			var clearLink = $_form.find(_clearClass + '[data-name~="' + i + '"]');
			if (typeof clearLink.attr('data-hidden-at-start') === 'undefined') {
        paramname = clearLink.attr('data-name');
				if(typeof paramname != 'undefined' && typeof getparams[paramname] != 'undefined' && getparams[paramname] != '') {
          clearLink.css('display', 'block');
        }
			} else {
				clearLink.removeAttr('data-hidden-at-start');
			}
      var inpSetVal = $_form.find('[type][name="' + i + '"]');

      if(inpSetVal.length) {
        var inpSetType = inpSetVal.eq(0).attr('type');
        if(inpSetType == 'radio') {
          inpSetVal.attr('checked', false).filter('[value="' + params[i] + '"]').attr('checked', 'checked');
        } else if(inpSetType == 'text') {
          inpSetVal.val(params[i]);
        }
      }
		}
	};

	var _init = function(currentParams) {
		_baseParams = currentParams;
		_params = _baseParams;

		var gp = getGetParams();
		for (var paramName in gp) {
			_params[paramName] = gp[paramName];
		}

		$_form = $('.js-prds-filter');
		_setEvents();
		_initClearLinksForBlocks();
		_rebuildClearLinks();
		_getCurrentParams();
		_initActiveSubCategory();
	};

	var _getCurrentParams = function() {
		var params = window.location.search;
		if (params) {
			params = params.replace('?', '');
			params = JSON.parse('{"' + decodeURI(params).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
		}
		return params;
	};

	var _getParams = function() {
		return _params;
	};

	return {
		init: _init,
		getParams: _getParams
	}
})();

/**
 * Создание объекта слайдера фильтров в виде тегов
 */
function TopFilters($mainElement, options) {
	if (!$mainElement instanceof jQuery) {
		throw new Error('First argument must be type of jQuery');
	}

	var opts = {
		filtersHolderWrapSelector: '.top-filters-holder-wrap',
		filtersHolderSelector: '.top-filters-holder',
		rightNavSelector: '.top-filters-right-nav',
		leftNavSelector: '.top-filters-left-nav',
		filterItemWrapSelector: '.top-filter-item-wrap',
		filterItemSelector: '.filter-item',
		filterItemActiveSelector: '.filter-item-active',
		subCatsLeftSideListSelector: '.sub_cat_list',
		navWrapSelector: '.top-filters-nav',
		navLeftControlSelector: '.top-filters-left-nav',
		navRightControlSelector: '.top-filters-right-nav',
		navLeftControlIconClass: 'icon-arrow-left',
		navRightControlIconClass: 'icon-arrow-right',
		animationSpeed: 700,
		appearControlsAnimationSpeed: 500,
		appearSliderAnimationSpeed: 250,
		filterItemLeftOffset: 50,
		additionItemWidth: 30,
		scrollItemsCount: 3,
		itemsOffset: 3,
		isMobile: false,
		items: []
	};

	var isLocked,
		scrollPosition,
		defaultScrollPosition,
		filterItemsStartLeftPoint,
		maxScrollPosition,
		navigationWidth,
		elementsPositions,
		currentFirstItemIdx,
		isResizeEventsBound = false;

	/**
	 * Инициализация слайдера фильтров
	 */
	function _init(options) {
		_destroy();

		for (var key in options) {
			if (options.hasOwnProperty(key)) {
				opts[key] = options[key];
			}
		}

		_makeSlider();
		_bindEvents();

		if (typeof $(opts.leftNavSelector) !== 'undefined' && $(opts.leftNavSelector).length) {
			filterItemsStartLeftPoint = parseInt($(opts.leftNavSelector).offset().left) + opts.filterItemLeftOffset;
		}

		if (typeof $(opts.filtersHolderWrapSelector) !== 'undefined' && $(opts.filtersHolderWrapSelector).length) {
			scrollPosition = defaultScrollPosition = parseInt($(opts.filtersHolderWrapSelector).scrollLeft());
		}
	}

	function _onScreenResize() {
		if (typeof window.reInitTopFiltersTimer !== 'undefined') {
			clearTimeout(window.reInitTopFiltersTimer);
		}

		window.reInitTopFiltersTimer = setTimeout(function() {
			_init(options);
		}, 300);
	}

	function _bindEvents() {
		$mainElement.off('click', opts.rightNavSelector);
		$mainElement.off('click', opts.leftNavSelector);
		$mainElement.off('click', opts.filterItemSelector);
		$mainElement.on('click', opts.rightNavSelector, _scrollRight);
		$mainElement.on('click', opts.leftNavSelector, _scrollLeft);
		$mainElement.on('click', opts.filterItemSelector, _onClickFilterItem);

		if (!isResizeEventsBound) {
			if (opts.isMobile) {
				window.addEventListener("orientationchange", function() {
					_onScreenResize()
				}, false);
			} else {
				$(window).on('resize', function() {
					_onScreenResize()
				});
			}
			isResizeEventsBound = true;
		}
	}

	/**
	 * Возвращает индекс элемента, до которого нужно проскроллить
	 *
	 * @param receivedArgs
	 * @param operation
	 * @private
	 */
	function _getCurrentFirstItemIdx(receivedArgs, operation) {
		var args = Array.prototype.slice.call(receivedArgs, 1, 2),
			needIdx;
		if (args.length && args[0] === parseInt(args[0], 10)) {
			needIdx = parseInt(args[0]) - opts.itemsOffset;
			needIdx = needIdx > 0 ? needIdx : 0;
		} else if (operation === '+') {
			needIdx = currentFirstItemIdx + opts.scrollItemsCount;
		} else if (operation === '-') {
			needIdx = currentFirstItemIdx - opts.scrollItemsCount;
		}

		return needIdx;
	}

	/**
	 * Действия, которые выполнятся при нажатии на кнопку прокрутки/стрелку вправо
	 *
	 * @param e
	 * @private
	 */
	function _scrollRight(e) {
		var el = $(e.target).is('i') ? $(e.target).closest('div') : $(e.target);
		if (!isLocked && !el.hasClass('nav-hidden')) {
			isLocked = true;
			$(opts.leftNavSelector)
				.removeClass('nav-hidden')
				.animate({
					opacity: 1
				}, opts.appearControlsAnimationSpeed);

			currentFirstItemIdx = _getCurrentFirstItemIdx(arguments, '+');

			var elementPosition;
			if (typeof elementsPositions[currentFirstItemIdx] !== 'undefined') {
				elementPosition = elementsPositions[currentFirstItemIdx];
			} else {
				var keys = Object.keys(elementsPositions);
				elementPosition = elementsPositions[keys[keys.length - 1]];
			}

			scrollPosition = elementPosition.left;

			if (scrollPosition >= maxScrollPosition) {
				scrollPosition = maxScrollPosition;

				$(opts.rightNavSelector)
					.addClass('nav-hidden')
					.animate({
						opacity: 0
					}, opts.appearControlsAnimationSpeed);
			}

			$(opts.filtersHolderWrapSelector).animate({
				scrollLeft: scrollPosition
			}, opts.animationSpeed, function() {
				isLocked = false;
			});
		}
	}

	/**
	 * Действия, которые выполнятся при нажатии на кнопку прокрутки/стрелку влево
	 *
	 * @param e
	 * @private
	 */
	function _scrollLeft(e) {
		var el = $(e.target).is('i') ? $(e.target).closest('div') : $(e.target);
		if (!isLocked && !el.hasClass('nav-hidden')) {
			isLocked = true;

			currentFirstItemIdx = _getCurrentFirstItemIdx(arguments, '-');
			currentFirstItemIdx = currentFirstItemIdx < 0 ? 0 : currentFirstItemIdx;

			if (currentFirstItemIdx === 0) {
				$(opts.leftNavSelector)
					.addClass('nav-hidden')
					.animate({
						opacity: 0
					}, opts.appearControlsAnimationSpeed);
			}

			var elementPosition;
			if (typeof elementsPositions[currentFirstItemIdx] !== 'undefined') {
				elementPosition = elementsPositions[currentFirstItemIdx];
			} else {
				var keys = Object.keys(elementsPositions);
				elementPosition = elementsPositions[keys[0]];
			}

			scrollPosition = elementPosition.left;

			if (scrollPosition < maxScrollPosition) {
				if (parseInt($(opts.rightNavSelector).css('opacity')) === 0) {
					$(opts.rightNavSelector)
						.removeClass('nav-hidden')
						.animate({
							opacity: 1
						}, opts.appearControlsAnimationSpeed);
				}
				$(opts.filtersHolderWrapSelector).animate({
					scrollLeft: scrollPosition
				}, opts.animationSpeed, function() {
					if (currentFirstItemIdx === 0) {
						scrollPosition = defaultScrollPosition;
					}
					isLocked = false;
				});
			} else {
				isLocked = false;
			}
		}
	}

	/**
	 * Действия, которые выполняются при клике на элемент фильтра
	 *
	 * @param e
	 * @private
	 */
	function _onClickFilterItem(e) {
		var el = $(e.target),
			landId = el.data('land-id');

		$(opts.filterItemSelector).filter(opts.filterItemActiveSelector).removeClass(opts.filterItemActiveSelector.substring(1));
		el.addClass(opts.filterItemActiveSelector.substring(1));
		$(opts.subCatsLeftSideListSelector).find('[data-land-id="' + landId + '"],[data-subattr-id="' + landId + '"]').trigger('click');
	}

	/**
	 * Устанавливает активный фильтр и при необходимости скроллит до него
	 * @param itemId
	 */
	function setActiveFilter(itemId) {
		$(opts.filterItemSelector).filter(opts.filterItemActiveSelector).removeClass(opts.filterItemActiveSelector.substring(1));
		var targetItem = $mainElement.find(opts.filterItemSelector + '[data-land-id="' + itemId + '"]'),
			targetItemIdx = targetItem.index();

		if ((currentFirstItemIdx + 3) < targetItemIdx && $(opts.rightNavSelector).length) {
			_scrollRight($(opts.navRightControlSelector), targetItemIdx);
		} else if ($(opts.leftNavSelector).length) {
			_scrollLeft($(opts.navRightControlSelector), targetItemIdx);
		}

		targetItem.addClass(opts.filterItemActiveSelector.substring(1));
	}

	/**
	 * Подготовка и рендеринг слайдера
	 */
	function _makeSlider() {
		var holderWrap = $('<div></div>', {
				'class': opts.filtersHolderWrapSelector.substring(1)
			}),
			filtersHolder = $('<div></div>', {
				'class': opts.filtersHolderSelector.substring(1)
			}),
			itemWrap = $('<div></div>', {
				'class': opts.filterItemWrapSelector.substring(1)
			}),
			itemsCount = Object.keys(opts.items).length;

		if (!itemsCount) {
			console.warn("Elements isn't set to top-filters slider");
			return;
		}

		// Создание элементов слайдера
		for (var i in opts.items) {
			if (opts.items.hasOwnProperty(i)) {
				var additionClass = '';
				if (parseInt(activeItemId) === parseInt(opts.items[i].id)) {
					additionClass = ' ' + opts.filterItemActiveSelector.substring(1);
					activeItemId = null;
				}
				var item = $('<div></div>', {
					'class': opts.filterItemSelector.substring(1) + additionClass,
					'text': typeof opts.items[i].title !== 'undefined' ? opts.items[i].title : opts.items[i].seo,
					'data-land-id': opts.items[i].id
				});
				itemWrap.append(item);
			}
		}

		filtersHolder.append(itemWrap);
		holderWrap.append(filtersHolder);
		$mainElement.append(holderWrap);

		var itemsCommonWidth = parseInt($(opts.filterItemWrapSelector).innerWidth()) + (itemsCount * opts.additionItemWidth);
		navigationWidth = parseInt($mainElement.innerWidth());

		if (itemsCommonWidth > navigationWidth) {
			var navWrap = $('<div></div>', {
					'class': opts.navWrapSelector.substring(1)
				}),
				leftNavControl = $('<div></div>', {
					'class': opts.navLeftControlSelector.substring(1)
				}),
				rightNavControl = $('<div></div>', {
					'class': opts.navRightControlSelector.substring(1)
				});

			leftNavControl.append($('<i></i>', {
				'class': opts.navLeftControlIconClass
			}));
			rightNavControl.append($('<i></i>', {
				'class': opts.navRightControlIconClass
			}));
			navWrap.append(leftNavControl).append(rightNavControl);
			$mainElement.append(navWrap);
		} else {
			var needMargin = (navigationWidth - itemsCommonWidth) / 2;
			filtersHolder.css('margin-left', (needMargin + 'px'));
		}

		$mainElement.find(opts.filterItemSelector).each(function(index) {
			var needWidth = parseInt($(this).innerWidth()) + opts.additionItemWidth;
			$(this).css('width', needWidth + 'px');
			var positionLeft = parseInt($(this).position().left) - parseInt($(opts.leftNavSelector).innerWidth()) - parseInt($(this).css('margin-right'));
			elementsPositions[index] = {
				left: positionLeft,
				right: positionLeft + needWidth,
				center: positionLeft + (needWidth / 2),
				width: needWidth
			};
		});

		var lastItemHRPosition = $mainElement.find(opts.filterItemSelector).last().position().left,
			lastItemWidth = $mainElement.find(opts.filterItemSelector).last().outerWidth();

		// Раскомментировать после того, как будет устранен баг с утечкой памяти при скролле на вложенных элементах,
		//  когда обыкновенный скролл расценивается как свайп
		//
		// if (opts.isMobile) {
		//     $(opts.filtersHolderSelector).css('width', (itemsCommonWidth + 10) + 'px');
		//     $(opts.filtersHolderWrapSelector).css('overflow-x', 'auto');
		// }

		maxScrollPosition = lastItemHRPosition + lastItemWidth - navigationWidth;

		$mainElement.animate({
			opacity: 1
		}, opts.appearSliderAnimationSpeed).css('margin-top', '0');
	}

	function _destroy() {
		$mainElement.css('opacity', 0).empty();
		isLocked = false;
		scrollPosition = 0;
		defaultScrollPosition = 0;
		filterItemsStartLeftPoint = 0;
		maxScrollPosition = 0;
		navigationWidth = 0;
		currentFirstItemIdx = 0;
		elementsPositions = {};

		return this;
	}

	_init(options);

	return {
		destroy: _destroy,
		refresh: _init,
		setActiveFilter: setActiveFilter,
	}
}