var site_url = 'http://' + window.location.hostname + '/';

//Для полей выбора даты, "календарного" типа:
jQuery(document).ready(function(){
	jQuery(document).ready(function() { //Предварительная подготовка страницы
			jQuery('#reg_dialog').hide(); //Скрыть форму регистрации
			jQuery('#auth_dialog').hide(); //Скрыть форму входа на сайт
			jQuery('#logout_dialog').hide(); //Скрыть форму выхода
	});
	//Применить настройки локали для календарного поля:
	jQuery(function(jQuery){
		jQuery.datepicker.regional['ru'] = {
			clearText: 'Очистить', clearStatus: '',
			closeText: 'Закрыть', closeStatus: '',
			closeAtTop: false,
			prevText: '&#x3c;Пред.',  prevStatus: '',
			prevBigText: '&#x3c;&#x3c;', prevBigStatus: '',
			nextText: 'След.&#x3e;', nextStatus: '',
			nextBigText: '&#x3e;&#x3e;', nextBigStatus: '',
			hideIfNoPrevNext: true,
			currentText: 'Сегодня', currentStatus: '',
			monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
			'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
			monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
			'Июл','Авг','Сен','Окт','Ноя','Дек'],
			monthStatus: '', yearStatus: '',
			changeMonth: true,
			changeYear: true,
			gotoCurrent: true,
			yearRange: '-50:+00',
			navigationAsDateFormat: true,
			weekHeader: 'Не', weekStatus: '',
			dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
			dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
			dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
			dayStatus: 'DD', dateStatus: 'D, M d',
			/*dateFormat: 'dd M, yy г.', firstDay: 1,
			altField: '#user_dob', altFormat: 'yy-mm-dd',*/
			initStatus: '', isRTL: false};
		jQuery.datepicker.setDefaults(jQuery.datepicker.regional['ru']);
	});
});

function clearForm(formId)
{
	jQuery(":input", "#" + formId).each(function(){
		var type = this.type;
		var tag = this.tagName.toLowerCase();
		if (type == "text" || type == "password" || tag == "textarea")
			this.value = "";
		else if (type == "checkbox" || type == "radio")
			this.checked = false;
		else if (tag == "select")
			this.selectedIndex = -1;
	});
}

function validateRegForm(messageDivId)
{
	//-------------------------------Чекбокс "согласен с правилами сайта"----------------------------//
	//Проверка, нажат ли чекбокс "Согласен с правилами сайта"
	if(jQuery("input[name='rules_agreed']:checked", "#reg_form").length <= 0)
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Вы должны согласиться с правилами сайта</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='rules_agreed']", "#reg_form").focus();
		return false;
	}
	
	//-------------------------------Логин----------------------------//
	//Проверка, введён ли логин:
	var tmp_str = jQuery.trim( jQuery("input[name='user_login']", "#reg_form").val() );
	if(tmp_str.length <= 0)
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Вы должны ввести логин</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_login']", "#reg_form").select();
		return false;
	}
	//Проверка на длину логина (не должен быть короче 5 символов):
	if((tmp_str.length > 0) && (tmp_str.length < 5))
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Логин не должен быть короче 5 символов</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_login']", "#reg_form").select();
		return false;
	}
	//Проверка на символы, входящие в логин (должны быть только латинские буквы):
	if(!tmp_str.match( /^[a-zA-Z]+[0-9]*$/))
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введён некорректный логин</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_login']", "#reg_form").select();
		return false;
	}
	
	//-------------------------------Пароль----------------------------//
	//Проверка, введён ли пароль:
	var tmp_str = jQuery.trim( jQuery("input[name='user_pass']", "#reg_form").val() );
	if(tmp_str.length <= 0)
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Вы должны ввести пароль</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_pass']", "#reg_form").select();
		return false;
	}
	//Проверка на длину пароля (не должен быть короче 3 символов):
	if((tmp_str.length > 0) && (tmp_str.length < 3))
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Пароль не должен быть короче 3 символов</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_pass']", "#reg_form").select();
		return false;
	}
	//Проверка на символы, входящие в пароль (пробельных символов быть не должно):
	if(tmp_str.match( /\s+/))
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введён некорректный пароль</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_pass']", "#reg_form").select();
		return false;
	}
	
	if(tmp_str != jQuery.trim( jQuery("input[name='user_pass_conf']", "#reg_form").val() ))
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введены несовпадающие пароли</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_pass']", "#reg_form").select();
		jQuery("input[name='user_pass_conf']", "#reg_form").val('');
		return false;
	}
	
	//-------------------------------Имя----------------------------//
	//Проверка, введено ли имя:
	tmp_str = jQuery.trim( jQuery("input[name='user_firstname']", "#reg_form").val() );
	if(tmp_str.length <= 0)
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Вы должны указать Ваше имя</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_firstname']", "#reg_form").select();
		return false;
	}
	//Проверка на длину имени (не должно быть короче 2 символов):
	if((tmp_str.length > 0) && (tmp_str.length < 2))
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Имя не должно быть короче 2 символов</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_firstname']", "#reg_form").select();
		return false;
	}
	//Проверка на символы, входящие в имя (должны быть только латинские либо кириллические буквы):
	if(tmp_str.match( /[^A-Za-zА-Яа-я]+/ )) 
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введено некорректное имя</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_firstname']", "#reg_form").select();
		return false;
	}
	
	//-------------------------------Фамилия----------------------------//
	//Проверка, введена ли фамилия:
	tmp_str = jQuery.trim( jQuery("input[name='user_lastname']", "#reg_form").val() );
	if(tmp_str.length <= 0)
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Вы должны указать Вашу фамилию</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_lastname']", "#reg_form").select();
		return false;
	}
	//Проверка на длину фамилии (не должно быть короче 2 символов):
	if((tmp_str.length > 0) && (tmp_str.length < 2))
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Фамилия не должна быть короче 2 символов</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_lastname']", "#reg_form").select();
		return false;
	}
	//Проверка на символы, входящие в фамилию (должны быть только латинские либо кириллические буквы):
	if(tmp_str.match( /[^A-Za-zА-Яа-я]+/ )) 
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введена некорректная фамилия</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_lastname']", "#reg_form").select();
		return false;
	}
	
	//-------------------------------E-Mail----------------------------//
	//Проверка, введён ли email:
	tmp_str = jQuery.trim( jQuery("input[name='user_email']", "#reg_form").val() );
	if(tmp_str.length <= 0)
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Должен быть введён адрес Вашей электронной почты</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_email']", "#reg_form").select();
		return false;
	}
	//Проверка, корректен ли email:
	if(!tmp_str.match( /^[\w-\.]+(\.[\w-]+)*@{1}[\w-]+(\.{1}[a-zA-Z]{2,})+$/ )) 
	{
		jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введён некорректный адрес Вашей электронной почты</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
		jQuery("input[name='user_email']", "#reg_form").select();
		return false;
	}
	
	//-------------------------------ICQ----------------------------//
	//Если введён номер ICQ, выполнить проверки:
	tmp_str = jQuery.trim( jQuery("input[name='user_icq']", "#reg_form").val() );
	if(tmp_str.length > 0)
	{
		//Проверка на длину номера (не должен быть короче 2 символов):
		if(tmp_str.length < 2)
		{
			jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Номер ICQ не должен быть короче 2 символов</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
			jQuery("input[name='user_icq']", "#reg_form").select();
			return false;
		}
		//Проверка на символы, входящие в номер (должны быть только цифры 0-9):
		if(!tmp_str.match( /^[0-9]+$/ )) 
		{
			jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введён некорректный номер ICQ</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
			jQuery("input[name='user_icq']", "#reg_form").select();
			return false;
		}
	}
	
	//-------------------------------Skype----------------------------//
	//Если введён номер Skype, выполнить проверки:
	tmp_str = jQuery.trim( jQuery("input[name='user_skype']", "#reg_form").val() );
	if(tmp_str.length > 0)
	{
		//Проверка на длину номера (не должен быть короче 2 символов):
		if(tmp_str.length < 2)
		{
			jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Номер Skype не должен быть короче 2 символов</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
			jQuery("input[name='user_skype']", "#reg_form").select();
			return false;
		}
		//Проверка на символы, входящие в номер (должны быть только латинские буквы):
		if(!tmp_str.match( /^[a-zA-Z]+$/ )) 
		{
			jQuery("#" + messageDivId, "#reg_form").html("<span class=red_notice>Введён некорректный номер Skype</span>").fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
			jQuery("input[name='user_skype']", "#reg_form").select();
			return false;
		}
	}
	
	return true;
}

function show_reg_form()
{
	var self = jQuery("#reg_dialog");
	if(jQuery('form', self).length == 0) // Если код формы регистрации ещё не загружался, загрузить
	{
		jQuery.post(
			site_url + 'wp-content/plugins/register-plus/reg-form-code.php',
			function(data)
			{
				self.html(data);
				jQuery('#user_dob', '#reg_form').datepicker({dateFormat: 'yy-mm-dd'});
			}
		);
	}
	if(typeof self.dialog('isOpen') == 'undefined')
	{
		var dialog = self.dialog({
			title: 'Регистрация',
			modal: true,
			position: 'center',
			open: function (event, ui)
			{
				self.dialog().parents('.ui-dialog').find('.ui-dialog-titlebar').removeClass('ui-dialog-titlebar').addClass('reg_titlebar');
			},
			width: 550,
			height: 500,
			resizable: false,
			draggable: true,
			show: 'drop',
			hide: 'drop',
			//overlay: { opacity: 0.5, background: "black" },
			buttons:
			{
				"Отмена": function()
				{
					clearForm("reg_form");
					//self.dialog('destroy').hide();
					self.dialog('close');
				},
				"Регистрация": function()
				{
					if(validateRegForm('dialogRegMessage') == true)
					{
						var message_div = jQuery('#reg_response_message');
						//Поле даты пока что является div-ом, сделать его скрытым полем формы:
						var user_dob = new Date(Date.parse( jQuery('#user_dob', '#reg_form').datepicker('getDate') ));
						user_dob = user_dob.getFullYear()+'-'+(user_dob.getMonth()+1)+'-'+user_dob.getDate();
						jQuery('#reg_form').append('<input type="hidden" name="user_dob" value="' + user_dob + '" />');
						message_div.load(
							site_url + 'wp-content/plugins/register-plus/reg-ajax.php',
							jQuery('#reg_form').serialize(),
							function (results)
							{
								//...
							}
						);
						message_div.dialog({
							title: 'Завершение регистрации',
							modal: true,
							position: 'center',
							open: function (event, ui)
							{
								self.dialog().parents('.ui-dialog').find('.ui-dialog-titlebar').removeClass('ui-dialog-titlebar').addClass('reg_titlebar');
							},
							width: 600,
							height: 700,
							resizable: false,
							draggable: true,
							stack: true,
							show: 'drop',
							hide: 'drop',
							//overlay: { opacity: 0.25, background: "black" },
							buttons:
							{
								"Ок, вернуться": function()
								{
									message_div.dialog('destroy').hide();
									show_reg_form();
								}
							}
						});
						
						clearForm("reg_form");
						//self.dialog('destroy').hide();
						self.dialog('close');
					}	
				}
			}
		});
		
		self.show();
	}
	else
	{
		if(!self.dialog('isOpen'))
			self.dialog('open');
	}
}

function show_auth_form()
{
	var self = jQuery('#auth_dialog');
	if(jQuery('form', self).length == 0) // Если код формы аутентификации ещё не загружался, загрузить
	{
		jQuery.post(
			site_url + 'wp-authform-customized.php',
			function(response)
			{
				self.html(response);
			}
		);
	}
	if(typeof self.dialog('isOpen') == 'undefined')
	{
		var dialog = self.dialog({
			title: 'Вход на сайт',
			modal: true,
			position: 'center',
			open: function (event, ui)
			{
				self.dialog().parents('.ui-dialog').find('.ui-dialog-titlebar').removeClass('ui-dialog-titlebar').addClass('auth_titlebar');
			},
			width: 550,
			height: 300,
			resizable: false,
			draggable: false,
			show: 'drop',
			hide: 'drop',
			//overlay: { opacity: 0.5, background: 'black' },
			buttons:
			{
				'Отмена': function()
				{
					clearForm('auth_form');
					//self.dialog('destroy').hide();
					self.dialog('close');
				},
				'Войти': function()
				{
					jQuery.post(
						site_url + 'wp-auth-customized.php',
						jQuery('#auth_form').serialize(),
						function(response)
						{
							if(response.length != 0)
								jQuery('#auth_error').html(response).fadeIn(200).fadeTo(3500, 1.0).fadeOut(1000);
							else
								location.href = '';
						}
					);	
				}
			}
		});
		
		self.show();
	}
	else
	{
		if(!self.dialog('isOpen'))
			self.dialog('open');
	}
}

function logout()
{
	var self = jQuery('#logout_dialog');
	jQuery.post(
		site_url + 'wp-logout-customized.php',
		function(response)
		{
			self.html(response);
		}
	);
	if(typeof self.dialog('isOpen') == 'undefined')
	{
		var dialog = self.dialog({
			title: 'Выход из системы',
			modal: true,
			position: 'center',
			open: function (event, ui)
			{
				self.dialog().parents('.ui-dialog').find('.ui-dialog-titlebar').removeClass('ui-dialog-titlebar').addClass('logout_titlebar');
			},
			width: 550,
			height: 200,
			resizable: false,
			draggable: false,
			show: 'drop',
			hide: 'drop',
			//overlay: { opacity: 0.5, background: 'black' },
			buttons:
			{
				'Нет': function()
				{
					//self.dialog('destroy').hide();
					self.dialog('close');
				},
				'Да': function()
				{
					jQuery.post(
						site_url + 'wp-auth-logout.php',
						function(response)
						{
							location.href = '';
						}
					);
				}
			}
		});
		
		self.show();
	}
	else
	{
		if(!self.dialog('isOpen'))
			self.dialog('open');
	}
}
