new PeriodicalExecuter(function(pe){
	var ub = $('user_block');
	if (!Object.isElement(ub)) return;
	if (!meLightWindow) return;
	pe.stop();
	
	var loginHref = ub.down('a.ul');
	var registerHref = ub.down('a.ur');
	var lostPasswdHref = ub.down('a.lp');
	
	if (Object.isElement(loginHref)) {
		loginHref.observe('click', loginShowAuthWindow)
	}
	
	if (Object.isElement(registerHref)) {
		registerHref.observe('click', loginShowRegisterWindow)
	}
	
	if (Object.isElement(lostPasswdHref)) {
		lostPasswdHref.observe('click', loginShowLostPasswdWindow)
	}
	
	
	
}, 0.2);

function loginShowLostPasswdWindow() {
	meLightWindow.deactivate();
	
	meLightWindow.activateWindow({
		href:  '/login/lostpasswd.html',
		title: 'Напоминание пароля',
		width: 400,
		top :  250,
		height: 220,
		type : 'page'
	});
	
	new PeriodicalExecuter(function(pe){
		var rf = $('lostpasswd_form');
		if (!Object.isElement(rf)) return;
		pe.stop();
		registerCoverLEvents(rf);
		
		rf.addRules({
			'email' : [{
				'name'    :  'email',
				'message' : 'Недопустимый формат email'
			},{
				'name'    :  'required',
				'message' : 'Введите email'
			}]
		})
		.observe('form:invalidated', function(data){
			inpt = data.memo;
			alert(inpt._invalidRule.message);
			inpt.focus();
		})
		.observe('form:validated', function(){
			var inpSbmt = this.down('input[type=submit]');
			var prevValue = inpSbmt.getValue();
			this.request({
				onCreate : function () {
					inpSbmt.setValue('Ждите ...');
					inpSbmt.disable();
				},
				onSuccess : function (r) {
					json = r.responseJSON;
					if (json.status == true) {
						alert((json.message || 'Пароль успешно отправлен вам на email.'));
						rf.reset();
						meLightWindow.deactivate();
					}else {
						alert((json.message || 'Произошла неизвестная ошибка.'));
					}
				},
				onComplete : function () {
					inpSbmt.setValue(prevValue);
					inpSbmt.enable();
				}
			});
		})
		.observe('submit', Form.validate.curry(rf))
		.applyCapcha("capcha_c", "capcha_f");
	},0.2)
}

function loginShowAuthWindow() {
	meLightWindow.deactivate();
	
	meLightWindow.activateWindow({
		href:  '/login/auth.html',
		title: 'Авторизация на сайте',
		width: 400,
		top :  250,
		height: 220,
		type : 'page'
	});
	
	new PeriodicalExecuter(function(pe){
		var rf = $('auth_form');
		if (!Object.isElement(rf)) return;
		pe.stop();
		registerCoverLEvents(rf);
		
		rf.addRules({
			'handle' : [{
				'name'    : 'required',
				'message' : 'Введите имя пользователя'
			}],			
			'passwd' : [{
				'name'    :  'required',
				'message' : 'Введите пароль'
			}]
		})
		.observe('form:invalidated', function(data){
			inpt = data.memo;
			alert(inpt._invalidRule.message);
			inpt.focus();
		})
		.observe('form:validated', function(){
			var inpSbmt = this.down('input[type=submit]');
			var prevValue = inpSbmt.getValue();
			this.request({
				onCreate : function () {
					inpSbmt.setValue('Ждите ...');
					inpSbmt.disable();
				},
				onSuccess : function (r, json) {
					if (json == true) {
						alert('Авторизация прошла успешно');
						rf.reset();
						meLightWindow.deactivate();
						location.href = location.href.replace('logout=1', ""); 
					}else {
						alert('Введенные имя пользователя или пароль не верны.');
					}
				},
				onComplete : function () {
					inpSbmt.setValue(prevValue);
					inpSbmt.enable();
				}
			});
		})
		.observe('submit', Form.validate.curry(rf))
		.applyCapcha("capcha_c", "capcha_f");
	},0.2)
}

function loginShowRegisterWindow(){
	var isLoggedIn = this.hasClassName('loggedin');
	meLightWindow.deactivate();
	meLightWindow.activateWindow({
		href:  '/login/register.html',
		title: isLoggedIn?'Редактирование персональных данных':'Регистрация на сайте',
		width: 400,
		top :  250,
		type : 'page'
	});
	
	new PeriodicalExecuter(function(pe){
		var rf = $('register_form');
		if (!Object.isElement(rf)) return;
		pe.stop();
		registerCoverLEvents(rf);
		
		rf.addRules({
			'author_email' : [{
				'name'    :  'email',
				'message' : 'Недопустимый формат email'
			},{
				'name'    :  'required',
				'message' : 'Введите email'
			}],
			'author_name' : [{
				'name'    :  'required',
				'message' : 'Введите ваше Ф.И.О.'
			}],
			'author_passwd' : [{
				'name'    : 'compare',
				'message' : 'Введенные пароли не совпадают',
				'params'  : 'author_passwd2'
			}]
		});
		
		if (!isLoggedIn){
			rf.addRules({
				'author_login' : [{
					'name'    : 'required',
					'message' : 'Введите имя пользователя'
				},{
					'name'    : 'regexp',
					'message' : 'Недопустимые символы в имя пользователя',
					'params'  : /^[a-z0-9\_\-]+$/i
				},{
					'tester' : {
						'test' : function (){
			        		r = new Ajax.Request('/login/check.html', {
			        			  asynchronous: false,
			        			  parameters  : {'login':this.getValue()},
			        			  method      : 'head'
			        		});
			        		return r.getHeader('X-JSON')=='1';
						}
					},
					'message' : 'Введенное имя пользователя используется'
				}],
				'author_email' : [{
					'tester' : {
						'test' : function (){
			        		r = new Ajax.Request('/login/check.html', {
			        			  asynchronous: false,
			        			  parameters  : {'email':this.getValue()},
			        			  method      : 'head'
			        		});
			        		return r.getHeader('X-JSON')=='1';
						}
					},
					'message' : 'Введенный email уже используется'
				}],
				'author_passwd' : [{
					'name'    :  'required',
					'message' : 'Введите пароль'
				}]
			});
		}
		rf.observe('form:invalidated', function(data){
			inpt = data.memo;
			alert(inpt._invalidRule.message);
			inpt.focus();
		})
		.observe('form:validated', function(){
			var inpSbmt = this.down('input[type=submit]');
			var prevValue = inpSbmt.getValue();
			this.request({
				onCreate : function () {
					inpSbmt.setValue('Ждите ...');
					inpSbmt.disable();
				},
				onSuccess : function (r) {
					json = r.responseJSON;
					if (json.status == true) {
						alert((json.message || 'Регистрация успешно прошла. На введенный вами email отправлена ссылка для подтвержения учетной записи.'));
						meLightWindow.deactivate();
					}else {
						alert('Произошла ошибка. Попробуйте позже');
					}
				},
				onComplete : function () {
					inpSbmt.setValue(prevValue);
					inpSbmt.enable();
				}
			});
		})
		.observe('submit', Form.validate.curry(rf))
		.applyCapcha("capcha_c", "capcha_f");

	},0.2)
}

function registerCoverLEvents(form){
	form = $(form);
	form.select('.coverlabel input.ioverlabel, .coverlabel label.loverlabel').invoke('observe', ['click', 'blur', 'focus'], function(evt){
		var inp, lbl;
		if (this.tagName == 'LABEL') {
			lbl = this;
			inp = this.next('input.ioverlabel');
		}else {
			inp = this;
			lbl = this.previous('label.loverlabel');
		}
	
		if (inp.getValue().blank()) {
			if (evt.type == 'click' || evt.type == 'focus')
				lbl.hide();
			else if (this.tagName == 'INPUT')
				lbl.show();
		}
	}).each(function(el){
		var inp, lbl;
		if (el.tagName == 'LABEL') {
			lbl = el;
			inp = el.next('input.ioverlabel');
		}else {
			inp = el;
			lbl = el.previous('label.loverlabel');
		}
		if (!inp.getValue().blank()) {
			lbl.hide();
		}
	})
}

var __loginConfirmParams = location.href.toQueryParams();
if (__loginConfirmParams['do'] && __loginConfirmParams['do'] == 'confirmr') {
	new Ajax.Request('/login/confirm.html', {
		parameters : __loginConfirmParams,
		method     : 'POST',
		onSuccess  : function (resp, json) {
			if (json == true){
				alert('Учетная запись успешно подтвержена');
			}else{
				alert('Произошла ошибка при подтвержении');
			}
		}
	})
}
