﻿/**
	.bfilter — обязательный класс для всех элементов управляющих фильтрами
	++ нужен обязательный класс модификатор = определяет тип элемента и его обработку:
	.bdater — инпут, с привязкой календаря и первичной установкой из сканера //? и сокрытием если нет угодных
		должен иметь ID вида: #filtername_date_(from|to)
		формат даты '01.12.2009' изменяется регэкспами на обратный без делителей '20091201' == 'yyyymmdd'
		чейндж — устанавливает фильтр[filtername] = regex(value) содержимого => f.apply
		угодны — любые элементы с наличием в атрибуте filtername содержимого, которое
			для date_from больше значения фильтр[filtername]
			для date_from меньше значения фильтр[filtername]
		
	.bselector — селект, с хайдом отсутствующих опций из сканера если нет угодных
		должен иметь ID вида: #filtername
		чейндж — устанавливает фильтр[filtername] = value выбранной опции => f.apply
		угодны — любые элементы с наличием класса .filtername_value
		
	.bmarker — любой кликабельный элемент , с хайдом его из сканера если нет угодных
		должен иметь атрибут bfilter=filtername и атрибут value содержащий значение фильтра
		клик — устанавливает фильтр[filtername] = value => f.apply
		угодны — любые элементы с наличием класса .filtername_value
		
	.btexter — инпут, исходно пустой, доступен всегда
		должен иметь ID вида: #filtername
		чейндж — запускает таймер, который каждую секунду устанавливает фильтр[filtername] = value содержимого => f.apply
			если таймер обнаруживает пустой чейндж — самоуничтожается
	
	f.apply — устанавливает комбинацию видимостей путем отражения всего и постепенного скрытия элементов, неугодных отдельным фильтрам
		если какому-то фильтру нет ни одного угодного элемента — применяет всем управляющим им элементам
		класс .notfound и НЕ применяет сокрытие управляемых элементов,
		иначе проверяет, чтобы класса .notfound не было и добавляет класс .hlight
		в конце, устанавливает значения text внутри элементов с #bfilter_shown #bfilter_total (рекомендуется спан)
	
	.bfilter_item — обязательный класс для всех элементов управляемых фильтрами
		.bfilter_container - для контейнеров выбрасывает класс из подсчета отображенных и скрытых элементов,
			угоден фильтрам, когда внутри есть хотя бы 1 визибл .bfilter_item
		.bfilter_notext - выбрасывает класс из поиска текста внутри (для дат и служебки)
!!!		.bfilter_nocount - просто выбрасывает класс из подсчета отображенных и скрытых элементов, для ссылок синхронных содержимому
	
	.bfilter_drop — любой кликабельный элемент, будет сбрасывать фильтры
		чейндж f.drop => f.apply
		если добавлен вторичный класс bfilter_comfy — устанавливает комфортные значения f.drop => f.comfy => f.apply
		
	.bfilter-go  — любой кликабельный элемент, будет применять фильтры
		чейндж f.apply
 */


var f = {
	zone: '',
	dropped: {},
	filters: {},
	scanned: {},
	fulldrop : function () {
		/* setting defaults by page == ultradrop */
		if (this.zone == 'news') { 
			this.dropped['news-date-from'] = 0;
			this.dropped['news-date-to'] = 0;
			this.dropped['news-type'] = 0;
			this.dropped['news-sezon'] = 0;
			this.dropped['news-text'] = '';
			this.dropped['news-year'] = 0;
		};
		if (this.zone == 'opinions') { 
			this.dropped['opinions-actype'] = 0;
			this.dropped['opinions-sezon'] = 0;
			this.dropped['opinions-age'] = 0;
			this.dropped['opinions-text'] = '';
			this.dropped['opinions-year'] = 0;
		};
		if (this.zone == 'archive') {
			this.dropped['archive-age'] = 0;
			this.dropped['archive-actype'] = 0;
			this.dropped['archive-sezon'] = 0;
			this.dropped['archive-text'] = '';
			this.dropped['archive-year'] = 0;
		};
		if (this.zone == 'gallery') {
			this.dropped['gallery-age'] = 0;
			this.dropped['gallery-actype'] = 0;
			this.dropped['gallery-sezon'] = 0;
			this.dropped['gallery-text'] = '';
			this.dropped['gallery-year'] = 0;
		};
		if (this.zone == 'catalog') {
			this.dropped['catalog-date-from'] = 0;
			this.dropped['catalog-date-to'] = 0;
			this.dropped['catalog-age'] = 0;
			this.dropped['catalog-actype'] = 0;
			this.dropped['catalog-region'] = 0;
			this.dropped['catalog-sezon'] = 0;
			this.dropped['catalog-text'] = '';
		};
		if (this.zone == 'catalog_sce') {
			this.dropped['catalog_sce-age'] = 0;
			this.dropped['catalog_sce-type'] = 0;
			this.dropped['catalog_sce-theme'] = 0;
			this.dropped['catalog_sce-text'] = '';
		};
		return true;
	},
	comfy : function () {
		/* setting comfort defaults */
		var today = new Date;
		var monthago = new Date;
		monthago.setMonth(monthago.getMonth()-2);
		if (this.zone == 'news') { 
			this.filters['news-date-from'] = monthago.getFullYear()+String(monthago.getMonth()).replace(/^(\d)$/,"0$1")+String(monthago.getDate()).replace(/^(\d)$/,"0$1");
			this.dropped['news-date-to'] = today.getFullYear()+String(today.getMonth()).replace(/^(\d)$/,"0$1")+String(today.getDate()).replace(/^(\d)$/,"0$1");
		};
		// if (this.zone == 'opinions') { 
			// this.filters['opinions-year'] = today.getFullYear();
		// };
		return true;
	},
	init : function () {
		if (/news/.test(document.location.href)) { 
			this.zone = 'news';
		};
		if (/opinions/.test(document.location.href)) { 
			this.zone = 'opinions';
		};
		if (/archive/.test(document.location.href)) { 
			this.zone = 'archive';
		};
		if (/gallery/.test(document.location.href)) { 
			this.zone = 'gallery';
		};
		if (/catalog/.test(document.location.href) || /classical-vacation/.test(document.location.href)) { 
			this.zone = 'catalog';
		};
		if (/catalog\/short-custom-events/.test(document.location.href)) { 
			this.zone = 'catalog_sce';
		};
		this.fulldrop();
		for (var filtername in this.dropped) {
			this.filters[filtername] = this.dropped[filtername]; 
		};
		
		if (!/classical-vacation/.test(document.location.href)){ // блокировка сканера для стартовой каникул — но лучше иметь заглушку в блоке!
			this.scan();
		};
		
		this.drop();
		this.comfy();
		this.load();
		this.apply();
		
		/* setting onclicks */
		$('.bfilter_drop').click(function () {
			f.drop();
			if ($(this).hasClass('bfilter_comfy')) {f.comfy();};
			f.apply();
		});
		$('.bfilter-go').click(function () {
			f.apply();
		});
		$('.bfilter.bdater').datepicker({
			dateFormat: 'dd.mm.yy'
		});
		for (var filtername in this.filters) {
			$('#'+filtername+'.bfilter.bselector').change(function () {
				f.filters[$(this).attr('id')] = $(this).val();
				f.apply();
			});
			$('.bfilter.bmarker[bfilter='+filtername+']').click(function () {
				f.filters[$(this).attr('bfilter')] = $(this).attr('value');
				if (/(?:news-year|news-sezon)/.test($(this).attr('bfilter'))) { 
					f.dropdates();
				};
				f.apply();
			});
			$('#'+filtername+'.bfilter.bdater').change(function () {
				f.filters[$(this).attr('id')] = $(this).val().replace(/(\d{2}).(\d{2}).(\d{4})/,'$3$2$1');
				f.apply();
			});
			$('#'+filtername+'.bfilter.btexter').change(function () {
				f.filters[$(this).attr('id')] = $(this).val();
				f.apply();
			});
			
			$('#'+filtername+'.bfilter.btexter').keypress(function () {
				$(this).removeClass('hlight notfound');
				if ($(this).val() > '') {
					$(this).addClass('hascontent');
				} else {
					$(this).removeClass('hascontent');
				};
			});
		};
		return true;
	},
	drop : function () {
		for (var filtername in this.filters) {
			this.filters[filtername] = this.dropped[filtername];
			if (this.scanned[filtername] > 0) {
				this.filters[filtername] = this.scanned[filtername];
			};
		};
		return true;
	},
	dropdates : function () {
		for (var filtername in this.filters) {
			if (/date/.test(filtername)) {
				this.filters[filtername] = this.dropped[filtername];
				if (this.scanned[filtername] > 0) {
					this.filters[filtername] = this.scanned[filtername];
				};
			};
		};
		return true;
	},
	scan : function () {
		for (var filtername in this.filters) {
			if (/date/.test(filtername)) {
				var dates = [];
				$('.bfilter_item').each(function(){
				   if ($(this).attr(filtername)) {dates.push(Number($(this).attr(filtername)));};
				   if ($(this).attr(filtername)) {dates.push(Number($(this).attr(filtername)));};
				});
				if (/date-from/.test(filtername)) {
					this.scanned[filtername] = String(Math.min.apply(null,dates));
				};
				if (/date-to/.test(filtername)) {
					this.scanned[filtername] = String(Math.max.apply(null,dates));
				};
			} else {
				$('.bfilter.bmarker[bfilter="'+filtername+'"]').each(function(){
					if (($(this).attr('value') > 0) && !$('.bfilter_item.'+filtername+'_'+$(this).attr('value')).length) {
						$(this).hide();
						$(this).addClass('hidden');
						$(this).remove();
					} else {
						// $('#report_area').append('mVal:'+$(this).attr('value')+'Len:'+$('.bfilter_item.'+filtername+'_'+$(this).attr('value')).length+'<br />');
					};
				});
				$('#'+filtername+'.bfilter.bselector option').each(function(){
					if (($(this).attr('value') > 0) && !$('.bfilter_item.'+filtername+'_'+$(this).attr('value')).length) {
						$(this).hide();
						$(this).addClass('hidden');
						$(this).remove();
					} else {
						// $('#report_area').append('sVal:'+$(this).attr('value')+'Len:'+$('.bfilter_item.'+filtername+'_'+$(this).attr('value')).length+'<br />');
					};
				});
			};
		};
		return true;
	},
	load : function () {
		if ($.cookie('bfilters_'+this.zone)) {
			cookfilt = $.evalJSON($.cookie('bfilters_'+this.zone));
			for (var filtername in cookfilt) {
				if (cookfilt[filtername] && !/text/.test(filtername) && !/date/.test(filtername)) {this.filters[filtername] = cookfilt[filtername];};
			};
		};
	},
	save : function () {
		$.cookie('bfilters_'+this.zone, $.toJSON(this.filters),{path: '/',expires: 0.01});
		return true;
	},
	apply : function () {
		total = $('.bfilter_item:not(.bfilter_container):not(.bfilter_nocount)').length;
		
		/* removing all marking classes and showall */
		$('.bfilter.bmarker').removeClass('hlight');
		$('.bfilter.bmarker').removeClass('notfound');
		$('.bfilter_item').show();
		$('.bfilter_container').show();
		
		/* applying filters */
		for (var filtername in f.filters) {
			//console.info('catch all .'+filtername+'_'+f.filters[filtername]);
			/* setting filters in inputs */
			$('#'+filtername+'.bfilter.bselector').val(String(f.filters[filtername]));
			$('.bfilter.bmarker[bfilter='+filtername+'][value='+f.filters[filtername]+']').addClass('hlight');
			$('#'+filtername+'.bfilter.bdater').val(String(f.filters[filtername]).replace(/(\d{4})(\d{2})(\d{2})/,'$3.$2.$1'));
			$('#'+filtername+'.bfilter.btexter').val(String(f.filters[filtername]))		
			if (f.filters[filtername] > 0 || f.filters[filtername] > '') {
				//console.info('catch all>0 .'+filtername+'_'+f.filters[filtername]);
				if (/date/.test(filtername)) {
					if (/date-from/.test(filtername)) {
						// var datefromattr = filtername;
						// var datefromval = f.filters[filtername];
						$('.bfilter_item').each(function(){
							if ($(this).attr($(this).attr('bfilter')+'-from') < f.filters[$(this).attr('bfilter')+'-from']) {
								$(this).hide();
							};
						});
					};
					if (/date-to/.test(filtername)) {
						$('.bfilter_item').each(function(){
							if ($(this).attr($(this).attr('bfilter')+'-to') > f.filters[$(this).attr('bfilter')+'-to']) {
								$(this).hide();
							};
						});
					};
				} else {
					if (/text/.test(filtername)) {
						//console.info('catch text .'+filtername+'_'+f.filters[filtername]);
						if ($('.bfilter_item:not(.bfilter_notext):contains('+f.filters[filtername]+'), .bfilter_container:not(.bfilter_notext):contains('+f.filters[filtername]+')').length) {
							$('.bfilter_item:not(.bfilter_notext):not(:contains('+f.filters[filtername]+')), .bfilter_container:not(.bfilter_notext):not(:contains('+f.filters[filtername]+'))').hide();
							$('#'+filtername+'.bfilter.btexter[value='+f.filters[filtername]+']').addClass('hlight').removeClass('notfound');
							//console.info(' okay .bfilter_item:contains('+f.filters[filtername]+')');
						} else {
							//console.info(' none .bfilter_item:contains('+f.filters[filtername]+')');
							$('#'+filtername+'.bfilter.btexter[value='+f.filters[filtername]+']').addClass('notfound').removeClass('hlight');
							alert('К сожалению, по вашему запросу: "'+f.filters[filtername]+'" ничего не найдено! \n\n — попробуйте изменить запрос\n — убедитесь в отсутствии опечаток\n — проверьте большие/маленькие буквы');
						};
					} else {
						if ($('.bfilter_item.'+filtername+'_'+f.filters[filtername]).length) {
							$('.bfilter_item:not(.'+filtername+'_'+this.filters[filtername]+')').hide();
							//console.info('markin .'+filtername+'_'+f.filters[filtername]);
						} else {
							//console.info('nomark .'+filtername+'_'+f.filters[filtername]);
						};
					};
				};
			};
		};
		
		/* hiding empty containers */
		$('.bfilter_container').each(function(){
			if (!$(this).contents('.bfilter_item:visible:not(.bfilter_container)').length && $(this).contents('.bfilter_item').length) {
				$(this).hide();
			};
		});
		
		/* showing results */
		shown = $('.bfilter_item:visible:not(.bfilter_container):not(.bfilter_nocount)').length;
		$('#bfilter_total').text(total);
		$('#bfilter_shown').text(shown);
		
		if (total > shown){
			$('#bfilter_total').addClass('hlight');
			$('#bfilter_shown').addClass('hlight');
			$('#dropfilters a.bfilter_drop').addClass('hlight');
		} else {
			$('#bfilter_total').removeClass('hlight');
			$('#bfilter_shown').removeClass('hlight');
			$('#dropfilters a.bfilter_drop').removeClass('hlight');
		};

		if (!/classical-vacation/.test(document.location.href) && !shown) {alert('К сожалению, по этому сочетанию опций ничего не найдено! \n\n — попробуйте изменить какое-нибудь из значений');}
		
		/* saving */
		this.save();
		return true;
	}
};

/**
 * Выполняем стартап процедуры
 */
$(document).ready(function() {

	f.init();
	

});