!function($) {
	// Sidebar
	$.fn.sideBar = function() {
		var   sidebar = $(this)
			, windowSwidth = 1076
			, header = $('.layout-header__main')
			, sidebarContent = sidebar.find('.side-bar__content-wrap')
			, headingClass = '.side-bar__heading'
			, heading = sidebar.find(headingClass)
			, banner = $('.banner_place_1')
			, scrollbar = $('.vertical-ribbon');

		var sidebarCollapsedClass = 'side-bar_collapsed';
		var sidebarCollapsedToSmallClass = 'side-bar_collapsed_to_small';
		var sidebartop = heading.offset().top;
		
		$(window).scroll(function() {
			var _top = $(document).scrollTop(),
				offset = $(".projects-bar").height();
			_top = _top > offset ? 0 : offset - _top;
			sidebarContent.css({'top': _top});
			heading.css({'top': _top});
			headingTopFunction(false);
		});
		
		function headingTopFunction(height) {
			if (height) {
				$(headingClass).css({'top': height});
			} else {
				$('.'+sidebarCollapsedToSmallClass).find(headingClass).css({'top': banner.length>0 ? banner.height() : '0'});
			}
		}
		
		function scrollCheck() {
			var   scrollTop = $(window).scrollTop()
				, contentHeight = sidebarContent.outerHeight();
			
			if (scrollTop > contentHeight) toggleSidebar(false);
		}

		function toggleSidebar(swtch) {
			var cclass = $('body').width()<windowSwidth ? cclass = sidebarCollapsedToSmallClass : cclass = sidebarCollapsedClass;
			var swtch = swtch === undefined ? swtch = sidebar.hasClass(cclass) : swtch;

			if (swtch) {
				$(window).on('scroll.sb', scrollCheck);
			} else {
				$(window).off('scroll.sb');
			}

			sidebar.toggleClass(cclass, !swtch);
			header.toggleClass($('body').width()<windowSwidth ? sidebarCollapsedToSmallClass : '', !swtch);
			if ($('body').width()<windowSwidth && !sidebar.hasClass(sidebarCollapsedToSmallClass)) {
				headingTopFunction(sidebartop);
			} else {headingTopFunction(false);}
		}
		
		function rechangeScrollTiny() {
			scrollbar.tinyscrollbar_update('relative');
		}

		function resizeSidebar() {
			rechangeScrollTiny();		
		}

		function toggleSubmenu(container) {
			var   title = container.children('.accordion-title')
				, arrow = container.children('.accordion-header')
				, content = container.children('.accordion-content');

			container.toggleClass('active');
			title.toggleClass('active');
			arrow.toggleClass('active');
			content
				.slideToggle('normal', function () { rechangeScrollTiny(); })
				.toggleClass('active');

			// I'm so sorry.
			var siblings = container.siblings();
			if (container.is('.side-navi__l2-item:not(.side-navi__l3-item-li)')) 
				siblings = $('.side-navi__l2-item:not(.side-navi__l3-item-li)').not(container);
			
			siblings.add(siblings.find('> .accordion-title, > .accordion-header, > .accordion-content')).toggleClass('active', false);
			siblings.find('> .accordion-content').slideUp('normal');
		}
		
		$(window).bind("resize", function(){
			if ($('body').width()<windowSwidth && !sidebar.hasClass(sidebarCollapsedToSmallClass)) {
				sidebar.removeClass(sidebarCollapsedClass).toggleClass(sidebarCollapsedToSmallClass);
				header.removeClass(sidebarCollapsedToSmallClass).addClass(sidebarCollapsedToSmallClass);
				headingTopFunction(false);
			}
			if ($('body').width()>=windowSwidth && !sidebar.hasClass(sidebarCollapsedClass)) {
				sidebar.removeClass(sidebarCollapsedToSmallClass).toggleClass(sidebarCollapsedClass);
				header.removeClass(sidebarCollapsedToSmallClass);
				headingTopFunction(sidebartop);
			}
			resizeSidebar();
		});

		$(document).on('scroll gestureend', function(){
			resizeSidebar();
		});

		heading.on('click', function(){ toggleSidebar(); });
	
		// side navigator accordion and tiny scrollbar
		$('.side-navi .accordion-content').hide();
		$('.side-navi .accordion-header, .side-navi .accordion-title a[href=#]').click(function() {
			toggleSubmenu($(this).offsetParent());
		});

		scrollbar.tinyscrollbar({
			invertscroll: true
		});
		resizeSidebar();	

		sidebar.hide();
		toggleSidebar(false);
		sidebar.show();
	}
	
	// Announce Gallery Plugin
	$.fn.announceGallery = function(){
		return $(this).each(function(){
			var   $this = $(this)
				, $main = $('.announce-gallery__main', $this)
				, $thumbs = $('.announce-gallery__thumbs', $this)
				, $thumbImages = $('.announce-gallery__thumb-image', $this)
				, $paginator = $('.announce-gallery__thumbs-paginator', $this);
			var thumbImageActiveClass = 'announce-gallery__thumb-image_state_active';

			$main.length && $main
				.carouFredSel({
					circular: false,
					infinity: false,
					auto: false,
					scroll: {
						items: 1,
						fx: 'crossfade'
					}
				});

			if (!$paginator.length){
				$thumbImages
					.each(function(i){
						var $this = $(this);

						$this.click(function(){
							$thumbImages.removeClass(thumbImageActiveClass);
							$this.addClass(thumbImageActiveClass);
							
							$main.trigger('slideTo', [i, true]);

							return false;
						});
					})
					.first().addClass(thumbImageActiveClass);
			}

			$thumbs
				.carouFredSel(
					{
						circular: false,
						width: $paginator.length ? null : $thumbs.width(),
						align: $paginator.length ? 'left' : 'center',
						auto: false,
						items: $paginator.length ? 4 : null,
						scroll: {
							items: $paginator.length ? null : 1
						},
						prev: $('.announce-gallery__button_dir_prev', $this),
						next: $('.announce-gallery__button_dir_next', $this),
						pagination: $paginator.length ? $paginator : null
					},
					{
						wrapper: {
							classname : 'announce-gallery__thumbs-wrap'
						}
					}
				);
		});
	};

	// Datepicker widget
	$(document).one('ready.wa', '.datepicker-widget', function(){
		var   widget = $(this)
			, button = widget.find('.datepicker-widget__button')
			, form = widget.find('form')
			, dateField = widget.find('input[name=date]')
			, containerParent = $('.layout__container')
			, pickerContainer = $('<div class="datepicker-widget datepicker-widget_container"><div class="datepicker-widget__picker-label">Анонсы событий:</div></div>');

		var   collapsedState = false
			, collapsedClass = 'datepicker-widget_collapsed';

		function positionPicker() {
			var widgetParent = widget.parent();
			var xOffset = widgetParent.offset().left + widgetParent.outerWidth() - widget.offset().left - widget.width();

			pickerContainer.position({
				my: "right top",
				at: "right+" + xOffset + " bottom+2",
				of: widget,
				collision: "fit flip"
			});
		}

		function togglePicker(swtch) {
			var swtch = swtch === undefined ? collapsedState : swtch;

			collapsedState = !swtch;
			pickerContainer.toggleClass(collapsedClass, !swtch);

			if (swtch) {
				positionPicker();
				$(document).on('mousedown.dpw', mouseDownOutside);
			} else {
				$(document).off('mousedown.dpw');
			}
		}

		function mouseDownOutside(e) {
			var   target = e.target
				, widgetTarget = target && ($(target).closest(pickerContainer).length || $(target).closest(widget).length) || null

			!widgetTarget && togglePicker(false);
		}

		$(function(){
			pickerContainer
				.appendTo(containerParent)
				.datepicker({
					showOtherMonths: true,
					altField: dateField,
					onSelect: function() {
						form.submit();
					}
				});

			togglePicker(false);

			button.click(function(e){
				e.preventDefault();
				togglePicker();
			});
		});
	});

	// Search widget
	$(document).one('ready.wa', '.search-widget', function(){
		var   searchWidget = $(this)
			, searchQuery = searchWidget.find('.search-widget__query')
			, searchSubmit = searchWidget.find('.search-widget__submit')
			, searchReset = searchWidget.find('.search-widget__reset');

		var   foldedClass = 'search-widget_collapsed'
			, foldedState = true;

		function toggleSearchWidget(swtch) {
			var swtch = swtch === undefined ? swtch = searchWidget.hasClass(foldedClass) : swtch;

			foldedState = !swtch;
			searchWidget.toggleClass(foldedClass, !swtch)
		}

		function foldWidget() {
			toggleSearchWidget(false);
			searchQuery.add(searchSubmit).trigger('blur');
			searchWidget.trigger('swfold');
		}

		function unfoldWidget() {
			toggleSearchWidget(true);
			searchWidget.trigger('swunfold');
		}

		function queryHasValue() {
			return !!$.trim(searchQuery.val());
		}

		function documentFocusHandler(e) {
			var   target = e.target
				, isFormTarget = target && searchWidget.find(target).length;

			if (!isFormTarget && !queryHasValue()) {
				foldWidget();
			};
		}
			
		function searchSubmitClickHandler(e) {
			if (foldedState) {
				e.preventDefault();
				unfoldWidget();
			} else if (!queryHasValue()){
				e.preventDefault();
				foldWidget();
			}
		}
			
		function searchResetClickHandler(e) {
			if (!queryHasValue()){
				e.preventDefault();
				foldWidget();
			}
		}

		function searchQueryFocusHandler(e) {
			if (foldedState) {
				unfoldWidget();
			};
		}

		function searchWidgetUnfoldHandler(e) {
			searchQuery.focus();
		}

		function searchWidgetKeyDownHandler(e) {
			if (e.keyCode == 27 && !queryHasValue()) {
				foldWidget();
			};
		}

		$(document).on('mousedown focusin', documentFocusHandler);
		searchReset.on('click', searchResetClickHandler);
		searchSubmit.on('click', searchSubmitClickHandler);
		searchQuery.on('focus', searchQueryFocusHandler);
		searchWidget
			.on('keydown', searchWidgetKeyDownHandler)
			.on('swunfold', searchWidgetUnfoldHandler);
	});

	// Header navi ellipsis
	$(document).one('ready.wa', '.header-navi', function(){
		var   headerNavi = $(this)
			, headerNaviEllipsis = headerNavi.find('.header-navi__lvl-item_ellipsis')
			, ellipsis = headerNavi.find('.ellipsis')
			, ellipsisTable = ellipsis.find('.ellipsis__table')
			, ellipsisRow = ellipsis.find('.ellipsis__row')
			, ellipsisClose = ellipsis.find('.ellipsis__close');

		var collapsedClass = 'ellipsis_collapsed';
		
		function toggleEllipsis(swtch) {
			var swtch = swtch === undefined ? swtch = ellipsis.hasClass(collapsedClass) : swtch;

			if (swtch) {
				$(document).on('mousedown.ellipsis', mouseDownOutside);
			} else {
				$(document).off('mousedown.ellipsis');
			}
			
			ellipsis.toggleClass(collapsedClass, !swtch);
		}

		function mouseDownOutside(e) {
			var   target = e.target
				, ellipsisTarget = target && $(target).closest(ellipsis).length || null

			!ellipsisTarget && toggleEllipsis(false);
		}

		toggleEllipsis(true);
		ellipsisRow
			.width(ellipsisTable.innerWidth())
			.each(function(){
				var row = $(this);

				row.height(row.height());
			});
		toggleEllipsis(false);

		headerNaviEllipsis.click(function(e){
			e.preventDefault();
			toggleEllipsis(true);
		});
		ellipsisClose.click(function(e){
			e.preventDefault();
			toggleEllipsis(false);
		});
	});

	// multimedia side block
	$(document).one('ready.wa', '.multimedia', function(){
		var   multimedia = $(this)
			, announceGallery = multimedia.find('.announce-gallery ');
		
		announceGallery.announceGallery();
	});

	// news and popular block
	$(document).one('ready.wa', '.news-n-pop', function(){
		var newsAndPopular = $(this)

		newsAndPopular.tabs({
			heightStyle: 'auto'
		});
	});	

	$.fn.checkControl = function(options) {
		var options = $.extend({
			blockName: 'check-control',
			prewraped: false
		}, options);

		var b = options.blockName;
		var synchronizeState = function(elem) {
			$(elem).closest('.' + b).toggleClass(b + '_checked', $(elem).is(':checked'));
		}

		return this.each(function(){
			var $this = $(this), $wrap, $siblings;
			var type = $this.attr('type');

			var changeState = function() {
				$siblings.each(function(){
					synchronizeState(this);
				});
			};

			if (!options.prewraped) $wrap = $this.wrap('<span class="' + b + '" />').parent().addClass(b + '_type_' + type);

			if (type == 'radio') {
				$siblings = $this.parents('form, body').eq(0).find('input[name=' + $this.attr('name') + ']');
				$this.change(changeState);
			} else if (type == 'checkbox') {
				$this.change(function(){
					synchronizeState(this);
					delete $siblings;
				});
			}

			synchronizeState(this);
		});
	};

	$(document).one('ready.wa', '.victorina', function(){
		var   block = $(this)
			, form = block.find('form')
			, currentQuestion = block.find('.victorina__cur-question')
			, page = block.find('.victorina__q-page')
			, answerButton = block.find('.victorina__answer-btn');

		var   pageActiveClass = 'victorina__q-page_active'
			, answerButtonDisabledClass = 'victorina__answer-btn_disabled'
			, currentPage = page.index('.' + pageActiveClass);



		function isValidPage(p) {
			return !!p.find('input:checked').length;
		}

		function changePage(i) {
			var nextPage = page.removeClass(pageActiveClass).eq(i).addClass(pageActiveClass);

			answerButton.toggleClass(answerButtonDisabledClass, !isValidPage(nextPage));

			currentQuestion.text(i + 1);
		}

		function onAnswerButtonClick(e) {
			e.preventDefault();

			if (!$(this).hasClass(answerButtonDisabledClass)) {
				if (++currentPage < page.length) {
					changePage(currentPage);
				} else {
					form.submit();
				}
			};
		}

		function onPageValueChange(e) {
			answerButton.toggleClass(answerButtonDisabledClass, !isValidPage($(this)));
		}

		answerButton.click(onAnswerButtonClick);
		page.change(onPageValueChange);

		changePage(0);
	});

	$.fn.partnerFeed = function(options) {
		return this.each(function() {
			var   b = $(this)
				, options = $.extend({
					src: b.data('src'),
					title: b.data('title')
				}, options);

			if (options.src) {
				b
					.removeAttr('id data-src')
					.addClass('partner-feed-wrap')
					.load('/ajax/partner/feed.html?title=' + encodeURIComponent(options.title) + '&src=' + encodeURIComponent(options.src));
			} else {
				b.remove();
			}
		});
	}
}(jQuery);

jQuery(function($) {
	
	// announces list & lazy load button init
	$('.announces-list').announcesList();
	$('.lazy-load-button-container[data-options]').each(function(){
		var $this = $(this);

		$this.lazyLoad($this.data('options'));
	});

	$.fn.pollForm = function() {
		var b = 'poll-form';
		var url = '/common/poll.ajax';
		

		return this.each(function(){
			var   $this = $(this)
				, $form = $this.find('form')
				, $submit = $this.find('.poll-form__button_submit')
				, $controls = $this.find('input:radio, input:checkbox');
			
			$this.find('.poll-form__item-control input').checkControl();

			$controls.change(function(){
				if ($controls.filter(':checked').length) $submit.removeAttr('disabled');
				else $submit.attr('disabled', 'disabled');
			});

			$form.submit(function(){
				$this.load(url, $form.serialize());

				return false;
			});
		});
	};

	(function() {
		var $tou = $('.terms-of-use');
		var $toul = $tou.find('.terms-of-use__lightbox');
		var $touc = $tou.find('.terms-of-use__close');
		var $touo = $tou.find('.terms-of-use__page-overlay');
		var $touToggler = $('.layout-footer__rules');

		var resize = function() {
			var dh = $(document).height();
			var ww = $(window).width();
			var wh = $(window).height();
			var lw = $toul.outerWidth(true);
			var lh = $toul.outerHeight(true);
			var st = $(window).scrollTop();

			$tou.css({
				width: ww,
				height: dh
			});

			$toul.css({
				left: (ww - lw) / 2,
				top: wh > lh ? st + (wh - lh) / 2 : st > dh - lh ? dh - lh : st
			});
		};

		var touToggle = function() {
			if ($tou.is(':visible')) {
				$tou.hide();
			} else {
				$tou.show();

				resize();
			}

			return false;
		}

		$touToggler.add($touc).add($touo).on('click', touToggle);
	})();


	$('.poll-form').pollForm();
	$(document).on('append', '.announces-list__announce:has(.poll-form)', function(){
		$(this).find('.poll-form').pollForm();
	});

	/* banner_place_6 spike */
	!function() {
		var   b6 = $('.announces-list__banner .banner_place_6')
			, b6c = b6.find('.banner__content > *')
			, b6p = b6.parent('.announces-list__banner');

		if (b6c.length && !b6c.html()) {
			var id = 'id' + ((100000 + Math.random() * 899999) | 0);
			var ival;

			b6c.html('<div id="' + id + '" />');
			b6p.removeClass('announces-list__banner').hide();

			ival = setInterval(function(){
				if (!b6c.is(':has(#' + id + ')')) {
					clearInterval(ival);
					b6p.addClass('announces-list__banner').show();
				}
			}, 500);
		}
	}();

	$('.opinions__author-image').each(function(){
		try {
			$(this).pixastic('desaturate', {average : false});
		} catch(e) {}
	});
});