/**
 * @author Vlad Yakovlev (red.scorpix@gmail.com)
 * @link www.scorpix.ru
 * @requires jQuery
 * @requires jCommon
 * @version 0.1
 * @date
 */

$(function() {

	function eventsCalendar() {
		var
			rootEl = $('#content .events_calendar'),
			columns = 7;

		if (!rootEl.length) return;

		var
			leftEl = rootEl.find('.icon_calendar_left'),
			rightEl = rootEl.find('.icon_calendar_right'),
			daysEl = rootEl.find('.days'),
			ulEl = rootEl.find('.days ul'),
			liEls = rootEl.find('.days li'),
			linkEls = liEls.find('.pseudo'),
			sectionEls = rootEl.find('.events .day'),
			pos = liEls.filter('.selected').prevAll('li').length,
			linkWidth;

		if (liEls.length > 7) {
			leftEl.css('display', 'block');
			rightEl.css('display', 'block');
		}

		$('.pseudo', daysEl[0]).live('click', change);
		$(window).resize(onResize);
		onResize();
		leftEl.click(left);
		rightEl.click(right);

		function left() {
			if (0 >= pos) {
				return false;
			}

			pos--;
			onResize();

			return false;
		}

		function right() {
			if (pos >= liEls.length - columns) {
				return false;
			}

			pos++;
			onResize();

			return false;
		}

		function onResize() {
			if (pos + columns > liEls.length) {
				pos = liEls.length - columns;
			}
			if (pos < 0) {
				pos = 0;
			}

			linkWidth = liEls.first().width();
			ulEl.css('left', -pos * linkWidth);
		}

		function change() {
			var liEl = $(this).closest('li');

			if (liEl.hasClass('selected')) {
				return;
			}

			var index = liEl.prevAll('li').length;
			liEls.filter('.selected').removeClass('selected');
			liEl.addClass('selected');
			sectionEls.filter('.day_selected').removeClass('day_selected');
			sectionEls.eq(index).addClass('day_selected');
		}
	}

	function eventsTypes() {
		var
			rootEl = $('#content .events_types'),
			linksEl = rootEl.find('.filters'),
			eventEls = rootEl.find('.event');

		if (!rootEl.length) {
			return;
		}

		linksEl.find('li').each(function() {
			var el = $(this);

			el.find('.pseudo').click(function() {
				if (el.hasClass('selected')) return;

				update(parseInt($c.attrSuffix(el, 'type_')));
			});
		});

		function update(id) {
			if (id) {
				eventEls.addClass('event_hidden');
				eventEls.filter('.type_' + id).removeClass('event_hidden');
			} else {
				eventEls.removeClass('event_hidden');
			}

			linksEl.find('.selected').removeClass('selected');
			linksEl.find('.type_' + id).addClass('selected');
		}
	}

	eventsCalendar();
	eventsTypes();
});
