// флаг отвечает за то, чтобы менюшка с логином не прыгала по двойному (случайному) нажатию
var flag_login = 0;

//	Для прибитой к верху формы логина. Задается при клике по #loginLink
var flag_top = 0;

// проверки для "Войти"
function check_form_login() {
	var errors = false;

	$('input#login_to_enter').removeClass('error');

	if ($('form#login_form input#login_to_enter').val().length == 0 || !isEmail($('form#login_form input#login_to_enter').val())){
		$('input#login_to_enter').addClass('error');
		errors = true;
	}

	if ($('form#login_form input#pass').val().length == 0)
		errors = true;

	if(!errors)
		button_action(true,'login-submit');
	else
		button_action(false,'login-submit');
}
// проверки для "Забыли пароль"
function check_form_lostpass() {
	if (
		isEmail($('form#pass_lost_form input#mail_lostpass').val())
	)
		button_action(true,'lostpass-submit');
	else
		button_action(false,'lostpass-submit');
}
// проверки для "Зарегистрироваться"
	function check_form_registration() {
	if (
		!isEmail($('form#registration-form input#mail_reg').val()) &&
		$('form#registration-form input#mail_reg').val().length > 0
		) {
			$('#mail_reg').addClass('error');
			$('#mail_reg').prev().addClass('error');
		}
	else {
		$('#mail_reg').removeClass('error');
		$('#mail_reg').prev().removeClass('error');
	}

	if (
		$('form#registration-form input#pass_reg').val().length > 0 &&
		$('form#registration-form input#pass_reg_two').val().length > 0 &&
		$('form#registration-form input#pass_reg').val() !=
		$('form#registration-form input#pass_reg_two').val()
	){
		//$('#pass_reg').prev().addClass('error');
		$('#pass_reg_two').addClass('error');
		$('#pass_reg_two').prev().addClass('error');
	}
	else {
		//$('#pass_reg').prev().removeClass('error');
		$('#pass_reg_two').removeClass('error');
		$('#pass_reg_two').prev().removeClass('error');
	}

	if (
		isEmail($('form#registration-form input#mail_reg').val())  &&
		$('form#registration-form input#pass_reg').val().length > 0 &&
		$('form#registration-form input#pass_reg').val() == $('form#registration-form input#pass_reg_two').val()
// NEW
//		&& $('form#registration-form input#confirm:checked').length > 0
	)
		button_action(true,'registration-submit');
	else
		button_action(false,'registration-submit');
}
// показываем или выключаем кпопки submit
function button_action(action,id){
	if ( action == true ){
		// включить кнопку
		$('#' + id+ ' img.disab').hide();
		$('#' + id + ' img.enab').show();
		$('#' + id).addClass('enab');
	}
	else if ( action == false ){
		// выключить кнопку
		$('#' + id + ' img.enab').hide();
		$('#' + id + ' img.disab').show();
		$('#' + id).removeClass();
	}
}

// узнаём и выставляем высоту боковых теней в ИЕ7
function resize_login_l_r() {
	// if ($.browser.msie && $.browser.version >= 7 && flag_top == 0) {
	//
	// 	var i = $('#login .line-left').height();
	// 	if ( $('#login div.registration-form').css('display') != 'none' ) {}
	// 	else i -= 40;
	//
	// 	$('#login .line-left .l-left').height(i);
	// 	$('#login .line-right .l-right').height(i);
	//  	}
}

function isEmail(email)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(email);
}

$(document).ready(function(){
	// проверки для "Войти"
	$('form#login_form input').keyup(function(){
		check_form_login();
	});
	$('form#login_form input').click(function(){
		check_form_login();
	});

	// нажали на кнопку "Войти"
	$('#login-submit img.enab').click(function(){
		$('form#login_form').submit();
	});
	// нажали на кнопку "Войти"
	$('#login-submit img.enab').keypress(function(event){
		// нажали enter - работаем!
		if ( event.keyCode == 13 ){
			$('form#login_form').submit();
		}
	});
	$('#login_form').submit(function() {
		if($(this).find('img.enab:visible').length)
			return submitAuthorizeForm();
		else
			return false;
	});

	// проверки для "Забыли пароль"
	$('form#pass_lost_form input').keyup(function(){
		check_form_lostpass();
	});
	$('form#pass_lost_form input').click(function(){
		check_form_lostpass();
	});

	// нажали на кнопку "Забыли пароль"
	$('#lostpass-submit img.enab').click(function(){
		submitReminderForm();
		// $('form#pass_lost_form').submit();
	});
	// нажали на кнопку "Забыли пароль"
	$('#lostpass-submit img.enab').keypress(function(event){
		// нажали enter - работаем!
		if ( event.keyCode == 13 ){
			submitReminderForm();
			// $('form#pass_lost_form').submit();
		}
	});
	$('form#pass_lost_form').submit(function() {
		if($(this).find('img.enab:visible').length)
			submitReminderForm();
		return false;
	});

// проверки для "Регистрации"
	$('form#registration-form input').keyup(function(){
		check_form_registration();
	});
	$('form#registration-form input').click(function(){
		check_form_registration();
	});

	// нажали на кнопку "Регистрации"
	$('#registration-submit img.enab').click(function(){
		submitRegistrationForm();
		return false;
//		$('form#registration-form').submit();
	});
	// нажали на кнопку "Регистрации"
	$('#registration-submit img.enab').keypress(function(event){
		// нажали enter - работаем!
		if ( event.keyCode == 13 ){
			submitRegistrationForm();
			return false;
//			$('form#registration-form').submit();
		}
	});
	$('form#registration-form').submit(function() {
		if($(this).find('img.enab:visible').length)
			submitRegistrationForm();
		return false;
	});

	// нажимаем на "Забыли пароль"
	$('span.pass_lost').click(function() {
		pass_lost_func();
		$(this).blur();
	});
	$('span.pass_lost').keypress(function(event) {
		if ( event.keyCode == 13 ){
			pass_lost_func();
			$(this).blur();
		}
	});

	function pass_lost_func() {
		$('div.pass_lost_form').toggle();
		$('span.pass_lost').parent().toggleClass('selected');
		$('span.pass_lost').text('');
		$('span.pass_lost').append( '<p class="underline">Забыли пароль</p>' );

		resize_login_l_r ();
	}

	// нажимаем на "Регистрация"
	$('span.registration').click(function() {
		span_registration_func();
		$(this).blur();
	});
	$('span.registration').keypress(function(event) {
		if ( event.keyCode == 13 ){
			span_registration_func();
			$(this).blur();
		}
	});

	function span_registration_func() {
		$('span.registration').parent().toggleClass('selected');
		$('span.registration').text('');
		$('span.registration').append( '<p class="underline">Регистрация</p>' );

		var bottomItem = $('span.registration').parent().parent().parent().parent().parent().parent();
		bottomItem.parent().parent().find('div.iefix_select').toggleClass('iefix_select_hidden');

		if($('span.registration').parent().hasClass('selected')) {
			if ($.browser.msie && $.browser.version == 7)
				bottomItem.find('div#bottom_reg').show();
			else
				bottomItem.find('div#bottom_reg').show();
			bottomItem.find('div#bottom_usual').hide();
			$('#hidden-ie6fix').hide();
		} else {
			bottomItem.find('div#bottom_reg').hide();
			bottomItem.find('div#bottom_usual').show();
		}

		resize_login_l_r ();
		if ( $.browser.msie && $.browser.version == 6 ) {
			//hack for IE6 - resizing same element for rebilding all code model
			$('#bottom_reg').css('position','relative');
			$('#bottom_reg').css('position','absolute');
		}

	}


	// нажимаем на "Закрыть форму" - крестик
	$('div.login-close').click(function(){
		close_div_login();
		$(this).blur();
	});
	$('div.login-close').keypress(function(event){
		if ( event.keyCode == 13 ){
			close_div_login();
		}
	});

	function close_div_login() {
		$('#login').hide();
		flag_login = 0;
	}

	// нажимаем на "Открыть форму пароля"
	$('#loginLink').click(function() {
		flag_top = 1;
		open_div_login();
		$(this).blur();
		return false;
	});

// NEW
	// нажимаем на "Открыть форму пароля"
	$('div#header-link').click(function(){
		if ($("a", this).length) return;

		//	Этот код вызывается только на странице с заливкой фоток, чтобы вернуть блок
		//	авторизации на место
		if($('span#upload-auth').length > 0){
			$('#login').attr('style', '');
			$('#login').hide();
			flag_login = 0;
		}

		open_div_login();
		$(this).blur();

		return false;
	});
	$('div#header-link').keypress(function(event){
		$(this).click();
	});

	$('#btnRepeatReg').click(function() {
		$('#registration-exists').hide();
		$('#registration-form').show();
		$('#mail_reg').val('');
		$('#pass_reg').val('');
		$('#pass_reg_two').val('');
		$('#confirm').attr('checked', '');
	});

	$('#btnRepeatRemind').click(function() {
		$('#reminder-failed').hide();
		$('#pass_lost_form').show();
		$('#mail_lostpass').val('');
	});

	function open_div_login(){
		if ( flag_login == 0 ) {
			flag_login = 1;

			var el_t = "#login_background";
			var el = "#login";
			var border = 25;

			$(el_t).css({
				left:'auto',
				height:'2em',
				'margin-right':$(el).css("margin-right"),
				top:$(el).css("top"),
				width:$(el).css("width"),
				right:"32%",
				'display':'none'
			});

			var delay = 200;
			//$('#login').show(delay);

			var y = $(el).height();
			var x = $(el).width();
			var y_em = $(el_t).height()/2;
			var y_el_offset = y_em * 7.5;

			$(el_t).css({
			width:2+"px",
			top:y_el_offset+border+2+"px",
			height:2+"px"
			});//"top":y_login_offset+(y/2)+"px",

			$(el_t).show();
			var x_el_offset = $(el_t).offset().left;

			$(el_t).css({
			left:x_el_offset-border+"px",
			right:"0"
			});//"left":x_login_offset+"px",   left:x_login_offset+x/2+(border*2)+border/2+"px",

			if(flag_top){
				$(el_t).animate({
					width: x-(border*2)-2+"px",
					height: y-(border*2)-2+"px",
					left:x_el_offset-x+border+35+"px",
					top:"15px"
					}, delay );
			}else{
				$(el_t).animate({
					width: x-(border*2)-2+"px",
					height: y-(border*2)-2+"px",
					left:x_el_offset-x+border+2+"px",
					top:y_el_offset+border+2+"px"
					}, delay );
			}

			$('#bottom_usual').css('position','absolute');
			$('#bottom_usual').css('position','relative');

			if ( $.browser.msie && $.browser.version >= 7 ) {
				$('#login').css({top:'-1000px'});
				$('#login').show();
				resize_login_l_r();
				setTimeout("resize_login_l_r();",delay+50);
			}
			else setTimeout("$('#login').show();",delay);

			if ( $.browser.msie && $.browser.version >= 7 ) {
				if(flag_top){
					setTimeout("$('#login').css({top:'-12px'});",delay);
				}else{
					setTimeout("$('#login').css({top:'7.5em'});",delay);
				}
				setTimeout("$('#login_background').hide();",delay);
			}

			setTimeout("$('#login_background').hide();",delay+30);
			setTimeout("$('#login_background').hide();",delay+50);

			if ( $.browser.msie && $.browser.version >= 7 ) {
				setTimeout("$('#login_background').hide();",delay+100);
				setTimeout("resize_login_l_r();",delay+70);
				setTimeout("resize_login_l_r();",delay+100);
			}
		}
	}
});

//	Мы посылаем обращение на скрипт /ajax/_login.html и передаем ему параметры с логином, паролем и
//	состояние чекбокса "запомнить меня"
//	Все можно переименовать, разумеется.
function submitAuthorizeForm()
{
	var persistent = $('input#remember_login:checked').length;

// NEW
	$.ajax({
		url: '/ajax/login.php',
		data: {
			login: $('input#login_to_enter').val(),
			password: $('#pass').val(),
			persistent: persistent
		},
		type: 'POST',
	 	dataType: 'xml',
	 	cache: false,
	 	timeout: 20000,
		success: function(xml) {
	 		authorizeResultCheck(xml);
	 	},
	 	error: function() {
			shakeWindow();
	 	}
	});

	return false;
}

//	В этой функции проверяется ответ от сервера по поводу авторизации (пришедший в виде XML)
//	В данном случае мы бы искали <response-status>true</response-status> (или false) где-то внутри ответа,
//	но так как сервера нет считаем, что нас не пустили :)
function authorizeResultCheck( xml )
{
	var status = $(xml).find('status').text();
	var persistent = $(xml).find('persistent-key').text();

	if(status == 'true'){
		if (persistent) {
			$.cookie('user', $('input#login_to_enter').val(), {expires: 30, domain: "cosmocard.ru"});
			$.cookie('user_key', persistent, {expires: 30, domain: "cosmocard.ru"});
		}
		$('#login').hide();

		if (window.login_function) {
			window.login_function();
		} else {
			window.location.href="/cabinet/photos";
		}
	}else{
		shakeWindow();
	}
}

function shakeWindow()
{
	var limit = 10;
	var defaultOffset = 0;
	var time = 20;
	$('#login-form').animate({marginLeft: + (defaultOffset - limit) +"px"}, (time/2)).animate({marginLeft: (defaultOffset + limit) + "px"}, time).animate({marginLeft: (defaultOffset - limit) +"px"}, time).animate({marginLeft: (defaultOffset + limit) + "px"}, time).animate({marginLeft: (defaultOffset - limit) +"px"}, time).animate({marginLeft: "0px"}, (time / 2));
}

function submitLostPassForm()
{
}

//	Отправляем форму регистрации на сервер, аяксом
function submitRegistrationForm()
{
	$.ajax({
		url: '/ajax/registration.php',
		data: {
			mail: $('#mail_reg').val(),
			password: $('#pass_reg').val()
		},
		type: 'POST',
	 	dataType: 'xml',
	 	cache: false,
	 	timeout: 50000,
		async: false,
		success: function(xml) {
			registrationResultCheck(xml);
	 	},
	 	error: function() {
			shakeWindow();
	 	}
	});
}

function registrationResultCheck( xml )
{
	var status = $(xml).find('status').text();

	if(status == 'true'){
		showRegistrationComplete();
	}else{
		showRegistrationFailed();
		shakeWindow();
	}
}

function showRegistrationComplete()
{
	$('#registration-form').hide();
	$('#registration-ok').show();
}

function showRegistrationFailed()
{
	$('#registration-exists strong').text($('#mail_reg').val());
	$('#registration-form').hide();
	$('#registration-exists').show();
}

//	Отправляем форму напоминания пароля на сервер, аяксом
function submitReminderForm()
{
	$.ajax({
		url: '/ajax/lost_password.php',
		data: {
			mail: $('#mail_lostpass').val()
		},
		type: 'POST',
		dataType: 'xml',
		cache: false,
		timeout: 20000,
		success: function(xml) {
			reminderResultCheck(xml);
		},
		error: function() {
			shakeWindow();
		}
	});
//	$('span.pass_lost').click();
}

function reminderResultCheck( xml )
{
	var status = $(xml).find('status').text();
	var exists = $(xml).find('exists').text();

	if(status == 'true'){
		showReminderComplete();
	}else{
		if (exists == 'true') {
			showReminderNotActivate();
		} else {
			showReminderFailed();
			shakeWindow();
		}
	}
}

function showReminderComplete()
{
	$('#reminder-ok strong').text($('#mail_lostpass').val());
	$('#pass_lost_form').hide();
	$('#reminder-ok').show();
}

function showReminderFailed()
{
	$('#reminder-failed strong').text($('#mail_lostpass').val());
	$('#pass_lost_form').hide();
	$('#reminder-failed').show();
}

function showReminderNotActivate()
{
	$('#reminder-notactivate strong').text($('#mail_lostpass').val());
	$('#pass_lost_form').hide();
	$('#reminder-notactivate').show();
}

