﻿var close_flash;

$(function() {
	
	var strings = {
		login: 'Логин (ваш e-mail)',
		password: 'Пароль',
		voted: 'Вы уже проголосовали за эту работу'
	};
	
	/* стилизация прокрутки в блоках с текстом */
	var jScrollPaneOptions = {
		day: {
			scrollbarWidth: 18,
			scrollbarMargin: 20,
			dragMinHeight: 54,
			dragMaxHeight: 54
		},
		night: {
			scrollbarWidth: 8,
			scrollbarMargin: 20,
			dragMinHeight: 24,
			dragMaxHeight: 24,
			wheelSpeed: 50
		},
		draw: {
			scrollbarWidth: 8,
			scrollbarMargin: 20,
			dragMinHeight: 24,
			dragMaxHeight: 24
		},
		play: {
			scrollbarWidth: 8,
			scrollbarMargin: 20,
			dragMinHeight: 24,
			dragMaxHeight: 24
		}
	};
	
	var uid = $('body').attr('class').match(/uid:(\d?)/)[1] || 1;
	
	/* Проверка совершеннолетия
	 * Использование: set `onSuccess` - call `check` 
	 * Алгоритм: shows confirmation dialog - calls `set` - calls `onSuccess` / `onFailure`, remembers result (if major, next request goes without check, `onSuccess` executes immediately)
	------------------------------------------------------------------------------------------------------------------- */
	var majority = {
		major: $.cookie('major') == 1 && location.href.indexOf('skipcheck=0') == -1 || location.href.indexOf('skipcheck=1') != -1 || location.pathname == '/user/password/set' || $('#auth').is('.authorized') && location.href.indexOf('skipcheck=0') == -1,
		onSuccess: function() {
			//переопредели меня!
		}
	};
	
	majority.check = function() {
		if (majority.major) {
			majority.onSuccess();
		} else {
			var containerHtml = '<div id="check18">' +
			'<img class="bg" src="sites/default/themes/default/images/bg/majority.png" width="402" height="180" alt="" />' + 
			'<div class="checkbox"><input type="checkbox" id="checkbox-major" /><label for="checkbox-major"><img src="sites/default/themes/default/images/misc/majority-text.png" alt="Мне есть 18 лет" /></label></div>' +
			'<input class="enter" type="image" src="sites/default/themes/default/images/misc/majority-enter.png" alt="Войти на сайт" />' +
			'</div>';
			
			majority.dom = {
				container: $(containerHtml).appendTo('body')
			}
			
			$.extend(majority.dom, {
				bg: majority.dom.container.find('img.bg'),
				checkboxContainer: majority.dom.container.find('.checkbox'),
				checkbox: majority.dom.container.find('.checkbox input'),
				enterButton: majority.dom.container.find('.enter')
			});
			
			majority.dom.checkbox.change(function() {
				majority.dom.enterButton.toggleClass('available');
				if ($(this).is(':checked') ) {
					majority.dom.enterButton.css('opacity', 1);
				} else {
					majority.dom.enterButton.css('opacity', .5);
				}
			});
			
			majority.dom.enterButton.click(function() {
				if ($(this).is('.available') ) {
					$.cookie('major', '1', { expires: 365 });
					majority.dom.container.animate({
						'top': -400
					}, 750, function() {
						majority.onSuccess();
						//$('#background-animation')[0].SetVariable('fxs', '0');
						///swfobject.removeSWF('background-animation');
					});
					// easeInOutSine
				}
			});
			
			majority.dom.enterButton.css('opacity', .5);
			
			if ($.browser.msie) {
				majority.dom.checkboxContainer.find('label').click(function() {
					if (majority.dom.checkbox.is(':checked') ) {
						majority.dom.checkbox.removeAttr('checked');
					} else {
						majority.dom.checkbox.attr('checked', 'checked');
					}
					majority.dom.checkbox.trigger('change');
					return false;
				});
				//$('#background-animation')[0].SetVariable('fxs', 1);
			}
			
			if ($.browser.msie && $.browser.version < 7) {
				return;
			}
			
			majority.dom.container.animate({
				'left': '50%',
				'margin-left': -201,
				'top': 200
			}, 1000);
			
			var animationParams = {
				'width': 402,
				'height': 180,
				'margin-left': -201,
				'margin-top': -90
			}, preAnimationStyle = {};
			
			if (!$.browser.msie) {
				animationParams.opacity = 1;
				preAnimationStyle.opacity = .15;
			}
		
			majority.dom.bg.css(preAnimationStyle).show().animate(animationParams, 2000, function() {
				majority.dom.enterButton.show();
				majority.dom.checkboxContainer.show();
				//$('#background-animation')[0].SetVariable('fxs', 1);
			});
			
			//easeInOutQuart
		}
	};
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/*  Разделы
	------------------------------------------------------------------------------------------------------------------- */
	var section = {
		all: $('.section'),
		dom: {},
		nightSections: [/*'draw', 'gallery', 'view'*/],
		auth: $('#auth').is('.authorized'),
		drawUnauthElements: $('#draw-unauth-warning, #draw-unauth-masker'),
		tracked: [/*'main', 'rules', 'restaurants', 'registration', 'ratings', 'play', 'game-2', 'game-1', 'gallery', 'draw'*/]
	};
	
	if (location.pathname == '/user/edit' && location.hash == '') {
		section.current = 'user-edit';
	} else if (location.pathname == '/user/password/set') {
		section.current = 'user-password-set';
	} else {
		section.current = ($.address.path() == '/') ? 'intro' : $.address.path()
	}
	
	if (section.current == 'user-anonymous-profile' && section.auth == true) {
		section.current = 'user';
	}
	
	if (section.current == 'registration' && section.auth == true) {
			section.current = 'already-registered';
		}
	
	if ( (section.current == 'user' || section.current == 'user-edit') && section.auth == false) {
		section.current = 'user-anonymous-profile';
	}
	
	//if (section.current == 'game-1' && !section.auth) {
	//	section.current = 'registration';
	//}
	
	$('.section').each(function() {
		var el = $(this);
		section.dom[el.attr('class').replace('section ', '')] = el;
	});
	
	section.getTime = function(sectionName) {
		return $.inArray(section.current, section.nightSections) == -1 ? 'day' : 'night';
	}
	
	section.show = function(name) {
		var initialName = name;
		
		closeEndr();
		fader.hide();
		$('#sended').click();
		
		if (name == 'gallery') {
			var extras = '';
			
			$('#content .gallery.section .content').empty();
			
			if ($.address.parameter('user') ) {
				extras += '&user=' + $.address.parameter('user');
				$('#content .gallery.section a.show-all').show();
			} else {
				$('#content .section.gallery a.show-all').hide();
			}
			
			if ($.address.parameter('sort') ) {
				extras += '&sort=' + $.address.parameter('sort');
				$('#content .gallery.section a.sort-' + $.address.parameter('sort') ).addClass('active').siblings().removeClass('active');
			}
			
			$.get('?get-gallery-page=1' + extras, function(response) {
				$('#content .gallery.section .content').html(response);
				$('#content .gallery.section ul.gallery').jScrollPane(jScrollPaneOptions.night);
				$('#content .gallery.section ul.gallery p.user a').address();
				updateRatingState();
			});
		}
		
		if (name == 'user') {
			$.get('?get-user-ratings=1', function(response) {
				$('#content .user.section .user-ratings').html(response);
			});
		}
		
		if (name == 'ratings') {
			$.get('?get-global-ratings=1', function(response) {
				$('#content .ratings.section .ratings-container').html(response);
				
				$('#content .ratings.section .ratings-container a').address();
				
				$('#content .ratings.section .text-container .text').jScrollPane(jScrollPaneOptions.day);
				$('#content .ratings-container .draw-container ol').jScrollPane(jScrollPaneOptions.draw);
				$('#content .ratings-container .play-container ol').jScrollPane(jScrollPaneOptions.play);
			});
		}
		
		if (location.pathname == '/user/edit' && name == '') {
			name = 'user-edit';
		} 
		
		if (name == 'draw' && !section.auth) {
			//section.drawUnauthElements.show();
			//fader.show();
		} else {
			//section.drawUnauthElements.hide();
			//fader.hide();
		}
		
		if (name == 'draw' && !section.auth) {
			name = 'registration';
		}
		
		if (!section.dom[name] || section.current == name) {
			return;
		}
		
		if (name == 'user-anonymous-profile' && section.auth == true) {
			name = 'user';
		}
		
		if ( (name == 'user' || name == 'user-edit') && section.auth == false) {
			name = 'user-anonymous-profile';
		}
		
		if (name == 'registration' && section.auth == true) {
			name = 'already-registered';
		}
		
		//if (name == 'game-1' && !section.auth) {
		//	name = 'registration';
		//}
		
		$('#nav li').removeClass('active').find('img.highlight').stop().animate({
			'opacity': 0
		}, 250).end().find('img:not(.highlight)').stop().animate({
			'opacity': 1
		}, 250).end().filter(':has(a[rel="address:' + initialName + '"])').addClass('active').find('img.highlight').stop().css('opacity', 1);
		
		/*
		if (!$.browser.msie) {
			
			if (name == 'gallery' || name == 'draw' || name == 'view') {
				$('#nav li img').css('opacity', 0).filter('.highlight').stop().css('opacity', 1);
			} else {
				$('#nav li:not(".active")').find('img.highlight').stop().animate({
					opacity: 0
				}, 250).end().find('img:not(".highlight")').stop().animate({
					opacity: 1
				}, 250);
				
				$('#nav li.active img.highlight').css('opacity', 1);
			}
			
		}
		*/
		
		section.dom[section.current].hide();
		section.dom[name].show();
		
		if (name == 'draw') {
			$('#editor').show();
			swfobject.embedSWF('sites/default/themes/default/media/Editor.swf', 'editor-object', '1000', '620', '8.0.0', null, { userId: uid }, { wmode: 'opaque' });
		}
		
		if (section.current == 'draw') {
			swfobject.removeSWF('editor-object');
			$('#editor').append('<div id="editor-object" />');
			$('#editor').hide();
		}
		
		
		if (name == 'view') {
			swfobject.embedSWF('sites/default/themes/default/media/Player.swf', 'video-object', '670', '420', '8.0.0', null,  { id: $.address.parameter('video') }, { wmode: 'transparent' });
			
			$('.section.view .vk').html(VK.Share.button('http://www.corona.molinos.ru/#view?video=' + $.address.parameter('video'), {type: 'link'}) );
			$('.section.view .links').append('<iframe allowtransparency="true" src="http://www.facebook.com/plugins/like.php?href=http://www.corona.molinos.ru/#view?video=' + $.address.parameter('video') + '" scrolling="no" frameborder="0" style="border:none; width:450px; height:80px"></iframe>');
		}
		
		if (section.current == 'view') {
			swfobject.removeSWF('video-object');
			$('#video').append('<div id="video-object" />');
		}
		
		
		if (name == 'game-1') {
			//swfobject.embedSWF("sites/default/themes/default/media/FindBottleLoader.swf", "game-1-container", "712", "410", "9.0.0", null, { userId: uid }, { wmode: 'window' }); 
		}
		
		if (section.current == 'game-1') {
			//swfobject.removeSWF('game-1-container');
			//$('.section.game-1 .game-container').append('<div id="game-1-container" />');
		}
				
		section.prev = {
			'section': section.current,
			'time': section.time
		};
		
		section.current = name;
		section.time = this.getTime(name);
		
		if (section.time != section.prev.time) {
			background.change();
			$('body').removeClass('day night').addClass(section.time);
		}
		
		
		var s = name;
		if (name == '') {
			s = 'main';
		}
		
		/*
		if ($.inArray(s, section.tracked) != -1) {
			var ar_Tail='unknown'; if (document.referrer) ar_Tail = escape(document.referrer);
			$('#trackers').empty().append('<img src="http://ad.adriver.ru/cgi-bin/rle.cgi?sid=158787&sz=' + s + '&bt=21&pz=0&rnd=' + Math.round(Math.random() * 1000000000) + '&tail256=' + ar_Tail + '"  width="1" height="1" />');
		}
		*/
	};
	
	$('#content .text-container>.text').jScrollPane(jScrollPaneOptions.day);
	$('#content ul.gallery').jScrollPane(jScrollPaneOptions.night);
	
	if (section.current == 'game-1') {
		//swfobject.embedSWF("sites/default/themes/default/media/FindBottleLoader.swf", "game-1-container", "712", "410", "9.0.0", null, {'userId': 1}, { wmode: 'window' });
	}
	
	//section.dom[section.current].show();
	$('#content .section').not(section.dom[section.current]).hide();
	section.time = section.getTime(section.current);	
	$('body').addClass(section.time);
	

	
	var s = section.current;
	if (section.current == 'intro') {
		s = 'main';
	}
	
	/*
	if ($.inArray(s, section.tracked) != -1) {
		var ar_Tail='unknown'; if (document.referrer) ar_Tail = escape(document.referrer);
		$('#trackers').empty().append('<img src="http://ad.adriver.ru/cgi-bin/rle.cgi?sid=158787&sz=' + s + '&bt=21&pz=0&rnd=' + Math.round(Math.random() * 1000000000) + '&tail256=' + ar_Tail + '"  width="1" height="1" />');
	}
	*/
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/*  Фон
	------------------------------------------------------------------------------------------------------------------- */
	var background = {
		minHeight: 900,
		minWidth: 1050,
		dom: {}
	}
	
	background.dom.wrapper = $('#background');
	background.dom.wrapperElements = background.dom.wrapper.find('img, object').mousedown(function() { return false; });
	background.dom.defaultImage = background.dom.wrapper.find('.' + section.time).css({
		'opacity': 0.01,
		'z-index': 10,
		'display': 'block'
	}).siblings().css({
		'z-index': 5
	}).end();
	
	background.getAllowedWidth = function() {
		var windowWidth = $(window).width();
		return (windowWidth < this.minWidth) ? this.minWidth : windowWidth;
	}
	
	background.getAllowedHeight = function() {
		var windowHeight = $(window).height();
		return (windowHeight < this.minHeight) ? this.minHeight : windowHeight;
	}
	
	background.fit = function() {
		var allowedHeight = this.getAllowedHeight();
		background.dom.wrapper.height(allowedHeight);
		
		var allowedWidth = this.getAllowedWidth(), wrapperRatio = allowedWidth / allowedHeight, wrapperElementsRatio = 16 / 10;
		background.dom.wrapper.width(allowedWidth);
		
		if (wrapperRatio > wrapperElementsRatio) {
			background.dom.wrapperElements.width('100%').height(allowedWidth / 16 * 10).css('margin-left', '-50%');
		} else {
			background.dom.wrapperElements.height('100%').width(allowedHeight / 10 * 16).css('margin-left', - allowedHeight / 10 * 16 / 2);
		}
	};
	
	background.change = function() {
		bottle.dom.defaultImage.animate({
			'opacity': 'toggle'
		}, 750);
		
		this.dom.defaultImage.animate({
			'opacity': 'toggle'
		}, 750);
	};
	
	background.showDefaultImage = function(callback) {
		background.dom.defaultImage.animate({
			opacity: 1
		}, 1000, function() {
			background.dom.defaultImage.siblings().show();
			callback();
		});
	}
	
	background.fit();
	
	$(window).bind('resize', function() {
		background.fit.apply(background);
	}); 
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/*  Бутылка
	------------------------------------------------------------------------------------------------------------------- */
	var bottle = {
		visible: false,
		dom: {
			container: $('#bottle-container')
		}
	};
	
	bottle.dom.imagesContainer = bottle.dom.container.find('.img');
	bottle.dom.bottleImg = $('#bottle');
	bottle.dom.bottleStandImg = bottle.dom.imagesContainer.find('.bottle-stand');
	bottle.dom.defaultImage = bottle.dom.bottleStandImg.filter('.' + section.time).css('z-index', 10).siblings('.bottle-stand').css('z-index', 5).end();
	
	bottle.fit = function() {
		if (bottle.visible) {
			bottle.dom.container.height(background.getAllowedHeight.apply(background) - 700);
			bottle.dom.imagesContainer.css('bottom', bottle.dom.container.height() - 1065 + 700);
		}
	}
	
	bottle.show = function() {
		bottle.dom.container.height(background.getAllowedHeight.apply(background));
		bottle.dom.imagesContainer.animate({
			'bottom': bottle.dom.container.height() - 1065
		}, 750, function() {
			bottle.dom.container.css('top', '700px').height(background.getAllowedHeight.apply(background) - 700);
			bottle.dom.bottleImg.appendTo('body');
			//bottle.dom.container.css('z-index', 20);
			if (!bottle.visible) {
				bottle.visible = true;
			}
			$('#footer').fadeIn(500);
			
			if ($.address.path() == 'draw') {
				
				if (!section.auth) {
					$('#nav li:first img').click();
				} else {
					$('#editor').show();
					swfobject.embedSWF('sites/default/themes/default/media/Editor.swf', 'editor-object', '1000', '620', '8.0.0', null, { userId: uid }, { wmode: 'opaque' });
				}
			
			}
			
			if ($.address.path() == 'view') {
				swfobject.embedSWF('sites/default/themes/default/media/Player.swf', 'video-object', '670', '420', '8.0.0', null, { id: $.address.parameter('video') }, { wmode: 'transparent' });
				$('.section.view .vk').html(VK.Share.button('http://www.corona.molinos.ru/#view?video=' + $.address.parameter('video'), {type: 'round'}) );
				$('.section.view .links').append('<iframe allowtransparency="true" src="http://www.facebook.com/plugins/like.php?href=http://www.corona.molinos.ru/#view?video=' + $.address.parameter('video') + '" scrolling="no" frameborder="0" style="border:none; width:450px; height:80px"></iframe>');
			}
			
		});
	}
	
	$(window).resize(bottle.fit);
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	////////////////////////
	
	$(window).load(function() {
		
		background.showDefaultImage(majority.check);
		
		majority.onSuccess = function() {
			$('#wrapper').animate({
				'top': 0
			}, 1000, bottle.show);
		};
		
	});
	
	//////////////////////
	
	$.address.strict(false).change(function(event) {
		section.show(event.path);
	});
	
	/* Выбор города в Адресах ресторанов
	------------------------------------------------------------------------------------------------------------------- */
	var citySelectForm = $('#city-selector');
	$('.restaurants.section select').change(function() {
		$.ajax({
			'url': './',
			'data': {
				'get-city-restaurants': $(this).val()
			},
			'cache': true,
			'success': function(response) {
				$('#city-restaurants').remove();
				$(response).insertAfter(citySelectForm);
				$('.restaurants.section .text').jScrollPane(jScrollPaneOptions.day);			
			}
		});
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/* IE не сообщает о событии "change" при изменении флажков и переключателей, код ниже ему помогает */
	if ($.browser.msie) {
		$('input[type="checkbox"], input[type="radio"]').click(function() {
			$(this).trigger('change');
		});
	}
	
	/* преобразуем поля для ввода даты рождения в 3 селекта, для удобства */
	var birthInput = $('input[name = "birth"]');
	if (birthInput.length) {
		var html;
		var selectYear = '<select name="year">';
		var selectMonth = '<select name="month">';
		var selectDay = '<select name="day">';
		var monthNames = ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'];
		var form = birthInput.parents('form:first');
		
		var currentValue = birthInput.val().match(/(\d{4})-(\d{2})-(\d{2})/);
		var currentYear = currentValue && currentValue[1] || '';
		var currentMonth = currentValue && currentValue[2] || '';
		var currentDay = currentValue && currentValue[3] || '';
		
		birthInput.parents('label:first').click(function() {
			return false;
		});
		
		/* заполняем значения селектов */
		for (var i = 1992; i > 1900; i--) {
			selectYear += '<option value="' + i + '">' + i +  '</option>';
		}
		selectYear += '</select>';
		
		for (var i = 0; i < 12; i++) {
			var val = i + 1;
			if (val < 10) {
				val = '0' + val;
			}
			selectMonth += '<option value="' + val + '">' + monthNames[i] +  '</option>';
		}
		selectMonth += '</select>';
		
		for (var i = 1; i < 32; i++) {
			var val = i;
			if (val < 10) {
				val = '0' + val;
			}
			selectDay += '<option value="' + val + '">' + i +  '</option>';
		}
		selectDay += '</select>';
		
		html = selectDay + selectMonth + selectYear;
		birthInput.replaceWith(html);
		
		/* пользователю должно быть 18 или больше, уст. соот. ограничения */
		var maxDate = new Date(new Date().setFullYear(new Date().getFullYear() - 18) );
		var maxYear = maxDate.getFullYear();
		var maxMonth = maxDate.getMonth() + 1;
		var maxDay = maxDate.getDate();
		
		function setValuesAvailability() {
			if (selectYear.val() == maxYear) {
				selectMonth.find('option:gt(' + (maxMonth - 1) + ')').remove();
			} else if ($('option', selectMonth).length < 12) {
				selectMonth.append(selectMonthOptions.filter(':gt(' + ($('option', selectMonth).length - 1) + ')') );
			}
			
			if (parseInt(selectMonth.val() ) == maxMonth && selectYear.val() == maxYear) {
				selectDay.find('option:gt(' + (maxDay - 1) + ')').remove();
			} else {
				var daysInMonth = 32 - new Date(parseInt(selectYear.val() ), parseInt(selectMonth.val() ) - 1, 32).getDate();
				
				selectDay.append(selectDayOptions.filter(':gt(' + ($('option', selectDay).length - 1) + ')') );
				selectDay.find('option:gt(' + (daysInMonth - 1) + ')').remove();
			}
		}
		
		selectDay = $('select[name = "day"]', form);
		selectMonth = $('select[name = "month"]', form).change(setValuesAvailability);
		selectYear = $('select[name = "year"]', form).change(setValuesAvailability);
		
		selectDayOptions = selectDay.find('option').clone();
		selectMonthOptions = selectMonth.find('option').clone();
		
		/* выбираем ранее указанные данные */
		$('option[value = "' + currentDay + '"]', selectDay).attr('selected', 'selected');
		$('option[value = "' + currentMonth + '"]', selectMonth).attr('selected', 'selected');
		$('option[value = "' + currentYear + '"]', selectYear).attr('selected', 'selected');
		
		setValuesAvailability();
		
		/* при отправке формы собираем селекты обратно в одно поле */
		form.append('<input name="birth" type="hidden" />').submit(function() {
			var year = $('select[name = "year"]', this).val();
			var month = $('select[name = "month"]', this).val();
			var day = $('select[name = "day"]', this).val();
			
			$('input[name = "birth"]', this).val(year + '-' + month + '-' + day);
		});
	}
	
	/* Авторизация
	------------------------------------------------------------------------------------------------------------------- */
	$('#auth input[name=login]').val(strings.login).focusin(function() {
		if ($(this).val() == strings.login) {
			$(this).val('');
		}
	}).focusout(function() {
		if ($(this).val() == '') {
			$(this).val(strings.login);
		}
	});
	
	$('#auth input[name=password]').val(strings.password).focusin(function() {
		if (!$(this).data('focusedBefore') ) {
			$(this).data('focusedBefore', true);
			$(this).val('');
		}
	});
	
	/* выход */
	$('#auth a.exit').click(function() {
		$.get('user/logout', function() {
			location.href = './';
		});
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/*  Регистрация
	------------------------------------------------------------------------------------------------------------------- */	
	$('#register').submit(function() {
		var message = $('.section.registration .message').removeClass('success error').text(''), email = $(this).find('input[name = "email"]').val(), button =  $(this).find('input.submit').attr('disabled', 'disabled').css('opacity', .5);
		
		if (!/^([0-9a-zA-Z]+[-._+&amp;])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/.test(email) ) {
			message.addClass('error').text('Некорректный формат адреса электронной почты');
			button.removeAttr('disabled').css('opacity', 1);
			return false;
		}
		
		$.ajax({
			'type': 'POST',
			'url': 'user/login/register',
			'data': {
				'email': email
			},
			'success': function() {
				message.addClass('success').text('Инструкция по активации новой учётной записи отправлена на указанный почтовый ящик.');
				button.removeAttr('disabled').css('opacity', 1);
			},
			'error': function(XMLHttpRequest, textStatus, errorThrown) {
				message.addClass('error').text(XMLHttpRequest.responseText);
				button.removeAttr('disabled').css('opacity', 1);
			}
		});
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/*  Редактирование профиля
	------------------------------------------------------------------------------------------------------------------- */	
	// вместо autocomplete = off
	$('#profile-edit input[name = "password"]').val('').removeAttr('val');
	
	// пароль обязателен только при регистрации, зарегистрированные уже должны быть согласны с условиями
	if (location.href.indexOf('destination') != -1) {
		$('#profile-edit label:has(input[name = "password"])').addClass('required');
		if (!$('#profile-edit label.check input').is(':checked') ) {
			$('#profile-edit input.submit').attr('disabled', 'disabled').css('opacity', .5);
		}
	} else {
		$('#profile-edit label.check').remove();
	}
	
	// разрешаем регистрироваться только при согласии с условиями
	$('#profile-edit label.check input').change(function() {
		if ($(this).is(':checked') ) {
			$('#profile-edit input.submit').removeAttr('disabled').css('opacity', 1);
		} else {
			$('#profile-edit input.submit').attr('disabled', 'disabled').css('opacity', .5);
		}
	});
	
	/* отправка */
	$('#profile-edit').submit(function() {
		var that = this;
		var message = $(this).siblings('.message').removeClass('success error').text(''), button =  $(this).find('input.submit').attr('disabled', 'disabled').css('opacity', .5), codes = $(this).find('input[name = "_codes"]').val();
		var canBeSubmitted = true, errorMessage = '';
		
		$(this).find('label.required input').each(function() {
			if ($(this).val() == '') {
				errorMessage = 'Не все необходимые поля заполнены.';
				canBeSubmitted = false;
			}
		});
		
		if (/\d+/.test($(this).find('input[name = "name"]').val() ) ) {
			errorMessage += ' Неправильно заполнено поле "Имя и фамилия".';
			canBeSubmitted = false;
		}
		
		if (!/^[2345678abcdefhkmprstuxyz]{6}$/.test($(this).find('input[name = "code"]').val() ) && $(this).find('input[name = "code"]').val() != '') {
			errorMessage += ' Неверный формат промо-кода.';
			canBeSubmitted = false;
		}
		
		if (!canBeSubmitted) {
			message.addClass('error').text($.trim(errorMessage) );
			button.removeAttr('disabled').css('opacity', 1);
			return false;
		}
		
		var code = $(this).find('input[name = "code"]').attr('name', '_code').val();
		$(this).find('input[name = "_codes"]').attr('name', 'code').val(codes + ' ' + code);
		
		$(this).ajaxSubmit({
			'success': function() {
				//if (location.href.indexOf('user/edit') != -1) {
				//	location.href = './';
				//} else {
					$(that).find('input[name = "code"]').attr('name', '_codes')
					$(that).find('input[name = "_code"]').attr('name', 'code');
					message.addClass('success').html('Изменения сохранены. Желаете <a href="#" rel="address:intro">перейти на главную страницу</a>?');
					message.find('a').address();
					button.removeAttr('disabled').css('opacity', 1);
					$('#auth .name').text($(that).find('input[name = "name"]').val() );
					$('.section.user h2').text('Здравствуйте, ' + $(that).find('input[name = "email"]').val() + '!');
					
					$(that).find('input[name = "code"]').val('');
					
					if (code != '') {
						
						$.get('api/auth/info.xml', function(response) {
							var codes = $(response).find('code');
							
							codes.each(function() {
								if ($(this).text() == code && $(this).attr('valid') == 'yes') {
									$(that).find('.code-reg-result').text('Код принят');
								} else {
									$(that).find('.code-reg-result').text('Код не опознан');
								}
							});
		
						});
						
					}
				//}
			},
			'error': function(XMLHttpRequest, textStatus, errorThrown) {
				message.addClass('error').text(XMLHttpRequest.responseText);
				button.removeAttr('disabled').css('opacity', 1);
			}
		});
		
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/* Восстановление пароля
	------------------------------------------------------------------------------------------------------------------- */	
	$('#restore').submit(function() {
		var message = $(this).siblings('.message').removeClass('success error').text(''), email = $(this).find('input[name = "email"]').val(), button =  $(this).find('input.submit').attr('disabled', 'disabled').css('opacity', .5);
		
		if (!/^([0-9a-zA-Z]+[-._+&amp;])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/.test(email) ) {
			message.addClass('error').text('Некорректный формат адреса электронной почты');
			button.removeAttr('disabled').css('opacity', 1);
			return false;
		}
		
		$(this).ajaxSubmit({
			'success': function() {
				message.addClass('success').text('Инструкция по входу без использования пароля отправлена на указанный почтовый адрес.');
				button.removeAttr('disabled').css('opacity', 1);
			},
			'error': function(XMLHttpRequest, textStatus, errorThrown) {
				message.addClass('error').text(XMLHttpRequest.responseText);
				button.removeAttr('disabled').css('opacity', 1);
			}
		});
		
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/* Изменение пароля
	------------------------------------------------------------------------------------------------------------------- */	
	$('#password').submit(function() {
		var message = $(this).siblings('.message').removeClass('success error').text(''), button =  $(this).find('input.submit').attr('disabled', 'disabled').css('opacity', .5);
		
		$(this).ajaxSubmit({
			'success': function() {
				message.addClass('success').text('Пароль успешно изменен.');
				button.removeAttr('disabled').css('opacity', 1);
			},
			'error': function(XMLHttpRequest, textStatus, errorThrown) {
				message.addClass('error').text(XMLHttpRequest.responseText);
				button.removeAttr('disabled').css('opacity', 1);
			}
		});
		
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/* Вход
	------------------------------------------------------------------------------------------------------------------- */	
	$('#auth form').submit(function() {
		var button =  $(this).find('input.submit').attr('disabled', 'disabled').css('opacity', .5);
		
		$(this).ajaxSubmit({
			'success': function(response) {
				location.href = '/';
			},
			'error': function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
				button.removeAttr('disabled').css('opacity', 1);
			}
		});
		
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	
	/* Рейтинг
	------------------------------------------------------------------------------------------------------------------- */
	function updateRatingState() {
		var ratingContainers = $('.drawing-rating-container');
		if (ratingContainers.length) {
			var ids = [];
			ratingContainers.each(function(k, v) {
				ids.push($(this).attr('class').match(/node-(\d+)/)[1]);
			});
			$.getJSON('node/rate.json?ids=' + ids.join('+'), function(response) {
				$.each(response, function(k, v) {
					if (v.open == false) {
						ratingContainers.filter('.node-' + k).find('ul').replaceWith('<p class="unavailable">' + strings.voted + '</p>').end().find('span.title').remove();
					}
				});
			});
		}
	}
	
	$('ul.drawing-rating li').live('mouseenter', function() {
		var el = $(this);
		var affectedEls = el.prevAll().andSelf();
		var avgEl = el.parents('.drawing-rating-container:first').find('span.avg');
		affectedEls.addClass('active');
		avgEl.data('val', avgEl.text() ).addClass('active').text(affectedEls.length);
	});
	
	$('ul.drawing-rating li').live('mouseleave', function() {
		var el = $(this);
		var affectedEls = el.prevAll().andSelf();
		var avgEl = el.parents('.drawing-rating-container:first').find('span.avg');
		affectedEls.removeClass('active');
		avgEl.removeClass('active').text(avgEl.data('val') );
	});
	
	$('ul.drawing-rating li a').live('click', function() {
		var el = $(this);
		var node = el.attr('href').match(/node=(\d+)/)[1];
		var rate = el.attr('href').match(/rate=(.*)/)[1];
		$.post('node/rate', {
			'node': node,
			'rate': rate
		}, function(response) {
			el.parents('.drawing-rating-container').find('span.title').remove();
			el.parents('ul:first').replaceWith('<p class="unavailable">Спасибо за оценку этой работы</p>');
		});
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	/* Увеличенное изображение галерии
	------------------------------------------------------------------------------------------------------------------- */
	var wrapper = $('#wrapper');
	var fader = $('<div id="fader" />').appendTo(wrapper);
	var enlargedDrawingContainer = $('<div id="enlarged-drawing"><a class="close" href="">Закрыть</a><a href="#" class="prev"><img src="sites/default/themes/default/images/icons/endr-prev.png" alt="" /></a><img class="image" width="350" alt="" /><a href="#" class="next"><img src="sites/default/themes/default/images/icons/endr-next.png" alt="" /></a><div class="footer" /></div>').appendTo(wrapper);
	
	var endrPrev = enlargedDrawingContainer.find('a.prev');
	var endrNext = enlargedDrawingContainer.find('a.next');
	
	function closeEndr() {
		fader.hide();
		enlargedDrawingContainer.hide();
		$(document).unbind('click.endr');
		return false;
	};
	
	function setEndrContent(container) {
		enlargedDrawingContainer.find('img.image').attr('src', container.find('a.drawing').attr('href') ).end().find('.footer').empty().append(container.find('p.user').clone(), container.find('.drawing-rating-container').clone() );
		
		$('span.auth.title', enlargedDrawingContainer).siblings('span.avg').hide();
		
		if (container.prev().length) {
			endrPrev.show().unbind('click').click(function() {
				setEndrContent(container.prev() );
				return false;
			});
		} else {
			endrPrev.hide();
		}
		
		if (container.next().length) {
			endrNext.show().unbind('click').click(function() {
				setEndrContent(container.next() );
				return false;
			});
		} else {
			endrNext.hide();
		}
		
	}
	
	enlargedDrawingContainer.find('a.close').bind('click.endr', closeEndr);
	
	$('#content ul.gallery li.drawing a.drawing').live('click', function() {
		var el = $(this);
		var container = el.parents('li.drawing:first');
		fader.show();
		setEndrContent(container);
		enlargedDrawingContainer.show();
		$(document).bind('click.endr', function(e) {
			if ($(e.target).parents('#enlarged-drawing').length == 0 && !$(e.target).is('#enlarged-drawing') ) {
				closeEndr();
			}
		});
		return false;
	});
	/* ---------------------------------------------------------------------------------------------------------------- */
	
	$('#content .gallery.section .pager a').live('click', function() {
		var extras = '';
			
		if ($.address.parameter('user') ) {
			extras += '&user=' + $.address.parameter('user')
		}
		
		if ($.address.parameter('sort') ) {
			extras += '&sort=' + $.address.parameter('sort')
		}
		
		$.get('?get-gallery-page=' + $(this).text() + extras, function(response) {
			$('#content .gallery.section .content').html(response);
			$('#content .gallery.section ul.gallery').jScrollPane(jScrollPaneOptions.night);
			$('#content .gallery.section ul.gallery p.user a').address();
			updateRatingState();
		});
		return false;
	});
	
	$('#draw-unauth-warning a.continue').click(function() {
		$('#draw-unauth-warning').hide();
		fader.hide();
		return false;
	});
	
	$('#content .section.gallery a.show-all').click(function() {
		$(this).hide();
	});
	
	/* подсветка кнопок навигации */
	if (!$.browser.msie) {
		$('#nav li img.highlight').css('display', 'block');
		$('body.day #nav li:not(".active") img.highlight').css('opacity', 0);
		
		$('body.day #nav li:not(".active")').live('mouseenter', function() {
			$(this).find('img.highlight').stop().animate({
				'opacity': 1
			}, 250);
			
			$(this).find('img:not(.highlight)').stop().animate({
				'opacity': 0
			}, 250);
		});
		
		$('body.day #nav li:not(".active")').live('mouseleave', function() {
			$(this).find('img.highlight').stop().animate({
				'opacity': 0
			}, 250);
			
			$(this).find('img:not(.highlight)').stop().animate({
				'opacity': 1
			}, 250);
		});
		
		
		$('#nav li img').click(function() {
			$(this).parents('li:first').addClass('active').find('img.highlight').css('opacity', 1).end().siblings().removeClass('active').find('img.highlight').stop().animate({
				'opacity': 0
			}, 250).end().find('img:not(.highlight)').stop().animate({
				'opacity': 1
			}, 250);
		});
		
		
		$('#nav li:has(a[rel="address:' + $.address.path() + '"]) img.highlight').css('opacity', 1);
	} else if ($.browser.msie && $.browser.version > 6) {
		$('#nav li img').click(function() {
			$(this).parents('li:first').addClass('active').siblings().removeClass('active');
		});
	}
	
	$('#nav li:has(a[rel="address:' + $.address.path() + '"])').addClass('active');
	
	close_flash = function(data) {
		$.ajax({
			'type': 'POST',
			'url': 'api/node/create',
			'data': {
				'class': 'drawing',
				'_filename': data,
				'name': $('#auth span.name').text()
			},
			'success': function() {
				fader.show();
				$('<img id="sended" src="sites/default/themes/default/images/misc/sended.png" alt="" />').appendTo('#wrapper').click(function() {
					$(this).remove();
					fader.hide();
				});
			},
			'error': function(XMLHttpRequest, textStatus, errorThrown) {
				alert('Ошибка:' + XMLHttpRequest.status + ': ' + XMLHttpRequest.statusText);
			}
		});
	}
	
	$('#over a.close').click(function() {
		$('#over').hide();
		
		return false;
	});

});


function closeEditor(nodeId) {
	location.hash = '#view?video=' + nodeId;
}


