!function($) {
	"use strict";

	$(function(){
		var   $announcementSearch = $('.announcement-search')
			, $announcementSearchForm = $announcementSearch.find('.announcement-search__form')
			, $selectedRangeLabel     = $announcementSearch.find('.announcement-search__selected-range')
			, $selectedRangeTip       = $announcementSearch.find('.announcement-search__selected-range-tip')
			, $selectedRangePicker    = $announcementSearch.find('.announcement-search__selected-range-picker')
			, $selectedRangeDateFrom  = $announcementSearch.find('.announcement-search__selected-date_from')
			, $selectedRangeDateTo    = $announcementSearch.find('.announcement-search__selected-date_to')
			, $selectedQueryLabel = $announcementSearch.find('.announcement-search__query-field')
			, $inputRangeStart = $announcementSearch.find('input[name=date]')
			, $inputRangeEnd = $announcementSearch.find('input[name=date_to]')
			, $rangeOptionsItem = $announcementSearch.find('.announcement-search__options-item_type_range')
			, $rangeOptionsItemContent = $rangeOptionsItem.find('.announcement-search__options-item-content')
			, $resetButton = $announcementSearch.find('.announcement-search__reset')
			, $filterOptionsItem = $announcementSearch.find('.announcement-search__options-item_type_filter')
			, $filter = $filterOptionsItem.find('.filter-checkboxes')
			, $citySelect = $announcementSearch.find('.announcement-search__city-select')
			, $submitButton = $announcementSearch.find('.announcement-search__submit-btn')
			, $formFields = $inputRangeStart.add($inputRangeEnd).add($filter.find('.filter-checkboxes__checkbox input'));

		var formStartData, formCurrentData;

		formStartData = $announcementSearchForm.serialize();

		function onFormDataChange() {
			formCurrentData = $announcementSearchForm.serialize();;

			if (formStartData != formCurrentData) {
				$submitButton.removeAttr('disabled');
			} else {	
				$submitButton.attr('disabled', 'disabled');
			}
		}

		function parseDate(date) {
			return new Date(date.substring(0, 4), parseInt(date.substring(4, 6)) - 1,  date.substring(6, 8));
		}

		function resetDates() {
			$inputRangeStart.val($inputRangeStart.data('resetValue')).change();
			$inputRangeEnd.val($inputRangeEnd.data('resetValue')).change();
			syncDateValues();
		}

		function syncDateValues () {
			var   startDate      = parseDate($inputRangeStart.val())
				, endDate        = parseDate($inputRangeEnd.val())
				, formatSettings = { monthNames: $.datepicker._defaults.monthShortNames };

			$selectedRangeDateFrom.text($.datepicker.formatDate('d MM yy', startDate, formatSettings));
			$selectedRangeDateTo.text($.datepicker.formatDate('d MM yy', endDate, formatSettings));
		}

		function onDatePickerSelect(dateText, inst) {
			var dateType = $selectedRangeTip.data('dateType');

			if (dateType == 'from') {
				$inputRangeStart.val(dateText).change();
				if (dateText > $inputRangeEnd.val()) $inputRangeEnd.val(dateText).change();
			} else {
				$inputRangeEnd.val(dateText).change();
				if (dateText < $inputRangeStart.val()) $inputRangeStart.val(dateText).change();
			}

			syncDateValues();

			$selectedRangeTip.hide();
		}

		$selectedQueryLabel.find('input').keyup(onFormDataChange);
		$formFields.change(onFormDataChange);

		$selectedRangePicker
			.click(function(){ return false; })
			.datepicker({
				onSelect: onDatePickerSelect
			});
		$(document).click(function(){ $selectedRangeTip.hide(); });

		$selectedRangeDateFrom.add($selectedRangeDateTo).click(function(){
			var $this = $(this);
			var dateType, dateStr;

			if ($this.is($selectedRangeDateFrom)) {
				dateType = 'from';
				dateStr = $inputRangeStart.val();
			} else {
				dateType = 'to';
				dateStr = $inputRangeEnd.val();
			}

			$selectedRangePicker.datepicker('setDate', dateStr);

			$selectedRangeTip
				.data('dateType', dateType)
				.show()
				.position({
					of: $this,
					my: "center top+10",
					at: "center bottom",
					collision : "none",
					using: function(position, feedback){
						var $arrow = $(this).find('.date-picker-tip__arrow');

						$(this).css(position);
						$arrow.css({
							left:  feedback.horizontal == 'left'  ? feedback.target.width / 2 : feedback.horizontal == 'center' ? ($(this).width() + $arrow.width()) / 2 : 'auto', 
							right: feedback.horizontal == 'right' ? feedback.target.width / 2 : 'auto' 
						});
					}
				});

			return false;
		});

		function onRangePickerRangeSelect(dateRange) {
			if (!dateRange.start && !dateRange.end) {
				$inputRangeStart.removeAttr('value');
				$inputRangeEnd.removeAttr('value');
				return;
			}

			$inputRangeStart.val(dateRange.start);
			$inputRangeEnd.val(dateRange.end ? dateRange.end : null);

			var start_date = dateRange.start ? parseDate( dateRange.start ) : null;
			var end_date = dateRange.end ? parseDate( dateRange.end ) : null;

			var rangeLabelTextStart = "" ,
				rangeLabelTextEnd = "" ,
				formatSettings = { monthNames: $.datepicker._defaults.monthShortNames };
			if (start_date && end_date) {
				rangeLabelTextStart = $.datepicker.formatDate('d MM yy', start_date, formatSettings);	
				rangeLabelTextEnd = $.datepicker.formatDate('d MM yy', end_date, formatSettings);
				$selectedRangeLabel.find(".date-from").text(rangeLabelTextStart);
				$selectedRangeLabel.find(".date-to").text(rangeLabelTextEnd);
			} else {
				if (start_date) {
					rangeLabelTextStart = $.datepicker.formatDate('d MM yy', start_date, formatSettings);
					$selectedRangeLabel.find(".date-from").text(rangeLabelTextStart);
				}
				else {
					rangeLabelTextEnd = $.datepicker.formatDate('d MM yy', end_date, formatSettings);
					$selectedRangeLabel.find(".date-to").text(rangeLabelTextEnd);
				}
			}

			
		}

		// Filters
		$filter.addClass('filter-checkboxes_js');
		var $filterCheckboxTypeAll = $filter.find('.filter-checkboxes__checkbox_type_all');
		var $filterCheckboxes = $filter.find('.filter-checkboxes__checkbox').not($filterCheckboxTypeAll);

		function enableCheckbox(elem) {
			elem.addClass("filter-checkboxes__checkbox_state_checked").find("input").prop("checked", true).change();
		}
		function disableCheckbox(elem) {
			elem.removeClass("filter-checkboxes__checkbox_state_checked").find("input").prop("checked", false).change();
		}

		function checkCheckboxesState() {
			if($filterCheckboxes.length == $filterCheckboxes.find('input:checked').length)
				enableCheckbox($filterCheckboxTypeAll.find("input:not(:checked)").parent());
			else 
				disableCheckbox($filterCheckboxTypeAll.find("input:checked").parent());
		}

		$filterCheckboxTypeAll
			.on('click', function(){
				if ($(this).find('input').is(':checked')) {
					disableCheckbox($filterCheckboxes);
					disableCheckbox($(this));
				} else {
					enableCheckbox($filterCheckboxes);
					enableCheckbox($(this));
				}
				$(".announcement-search__toggler, w-submit").addClass("active");
			});

			
		$filterCheckboxes
			.on('click', function(e){
				if ($(this).find('input').is(':checked')) {
					disableCheckbox($(this));
				} else {
					enableCheckbox($(this));
				}
				checkCheckboxesState();
				$(".announcement-search__toggler, .w-submit").addClass("active");
			});
				
		enableCheckbox($filterCheckboxes.has('input:checked'));
		checkCheckboxesState();
		// /Filters

		$resetButton.click(function(){
			resetDates();
			$selectedQueryLabel.find('input').val('');
			disableCheckbox($filterCheckboxes);
			checkCheckboxesState();

			return false;
		});
		
		/*$clear.on('click', function(e){
			$selectedQueryLabel.find("input").removeAttr('value');
			$filter.find("label").removeClass("filter-checkboxes__checkbox_state_checked").find("input").removeAttr("checked");
			
			var current_date = new Date(),
				year_plus_date = new Date(),
				formatSettings = { monthNames: $.datepicker._defaults.monthShortNames };
			
			year_plus_date.setFullYear(current_date.getFullYear() + 1);
			
			$selectedRangeLabel.find(".date-from").text($.datepicker.formatDate('d MM yy', current_date, formatSettings));
			$selectedRangeLabel.find(".date-to").text($.datepicker.formatDate('d MM yy', year_plus_date, formatSettings));
			
			$(".announcement-search__toggler, .w-submit").removeClass("active");
			return false;
		});*/
		
		//QTIP2
		/*$('.date-from, .date-to').qtip({
			content: {
				text: function(api) {
					return $("#"+$(this).attr('class'));
				}
			},
			position: {
				my: 'top center',
				at: 'bottom center'
			},
			show: { event: 'click' },
			hide: { event: 'unfocus' },
			style: {
				tip: $.extend({
					corner: true,
					mimic: 'center',
					width: 16,
					height: 8
				}, {})
			},
			events: {
				show: function(event, api) {
					var	aria = $(this).attr("id"),
						objAria = $(".announcement-search__selected-range").find("span[aria-describedby='"+aria+"']");
					
					$(this).find(".range-picker__day span").live('click', function() {
						if ( $(this).hasClass("range-picker__day_month_other")) {return false;}
						
						var	pickerBl = $("#"+aria),
							day = $(this).parent().attr("data-day"),
							month = $(this).parent().attr("data-month"),
							year = $(this).parent().attr("data-year"),
							month_text = pickerBl.find(".range-picker__title span:first-child").text().substring(0,3),
							date = year+month+day;
						
						objAria.text($(this).text()+" "+month_text+" "+year);
						if (aria == "ui-tooltip-0") {$inputRangeStart.val(date);} else {$inputRangeEnd.val(date)}
						$(".announcement-search__toggler, .w-submit").addClass("active");
						pickerBl.find("span").removeClass("check");
						$(this).addClass("check");
						$('.qtip').hide(100);
					});
				}
			}
		});*/

		!function() {
			var   $cityMenu = $('<ul class="announcement-city-menu" />').appendTo('body')
				, $cityMenuButton = $('.announcement-events__title-city-select')
				, $cityMenuItems = $();

			function changeCity(val) {
				$citySelect.val(val);

				syncValue();

				$announcementSearchForm.submit();
			}

			function syncValue() {
				var val = $citySelect.val();
				var $item = $cityMenuItems.filter(':has(a[href=' + val + '])');

				$cityMenuButton.text($item.text());
				$cityMenuItems.removeClass('announcement-city-menu__item_selected');
				$item.addClass('announcement-city-menu__item_selected');
			}

			$citySelect.find('option').each(function(){
				var $this = $(this);

				var $item = $('<li class="announcement-city-menu__item" />')
					.append(
						$('<a class="announcement-city-menu__item-a" href="' + $this.val() + '"><span>' + $this.text() + '</span></a>')
							.click(function(){
								changeCity($(this).attr('href'));
								$cityMenu.hide();
								return false;
							})
					)
					.appendTo($cityMenu);

				$cityMenuItems = $cityMenuItems.add($item);
			});

			$cityMenuButton.click(function(){
				var offset = $(this).offset();

				$cityMenu
					.show()
					.offset({
						top: offset.top - 11,
						left: offset.left - 22
					});

				return false;
			});

			$cityMenu.click(function(e){ e.stopPropagation(); });
			$(document).click(function(){ $cityMenu.hide(); });

			syncValue();
		}();
	});

} (jQuery);
