// JavaScript Document
	function isValidEmail (email)
	{
		return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
	}

	function check_passport(passport)
	{
		return (/^[А-Я]{2}[\d]{6}$/).test(passport);
	}
	
	function check_phone(passport)
	{
		return (/^\+380[\d]{9}$/).test(passport);
	}
	function check_phone7(passport)
	{
		return (/^[\d]{7}$/).test(passport);
	}
	
$(document).ready(function()
{
	$("#logo").click(function(){
		location.href = "/";
	});
	
	$(".popup_closebutton").click(function(){
		
		$.fancybox.close();
		
	});

	//alert(location.href);
	//автооткрытие вопросов FAQ
	var faq_parts = location.href.split('#open_qw_');
	if (faq_parts.length >= 2)
	{
		$("#ans_"+faq_parts[1]).slideToggle();
		$("#qw_"+faq_parts[1]).toggleClass('qw_opened');
	}
	//alert (faq_parts.length);
	
	
	$(".qw_container a").click(function(){
		
		$("#faq_questions .qw_answer").each(function(){
			$(this).slideUp();
		});
		$("#faq_questions .qw_container a").each(function(){
			$(this).removeClass('qw_opened');
		});
		
		var params = $(this).attr('id').split('_');
		var cur_id = params[1];
		
		$("#ans_"+cur_id).slideToggle();
		$("#qw_"+cur_id).toggleClass('qw_opened');
	});
	
	$("#contacts_submit").click(function()
	{
		var name = $("#name").val();
		var email = $("#email").val();
		var message = $("#message").val();
		var captcha = $("#recaptcha_response_field").val();
		
		var error_message = '';
		$("#name").attr('class', '');
		$("#email").attr('class', '');
		$("#message").attr('class', '');
		
		$("#contacts_form_error").html('');
		

		if (name == '')
		{
			error_message += 'Введите Ваше имя<br />';	
			$("#name").attr('class', 'error');
		}

		if (email == '')
		{
			error_message += 'Введите Ваш почтовый адрес<br />';	
			$("#email").attr('class', 'error');
		}

		if (message == '')
		{
			error_message += 'Введите текст сообщения<br />';	
			$("#message").attr('class', 'error');
		}
		
		if ((email != '') && (!isValidEmail(email)))
		{
			error_message += 'Некорректный e-mail<br />';	
			$("#email").attr('class', 'error');
		}
		
		if (captcha == '')
		{
			error_message += 'Введите текст, который Вы видите на картинке. Если текст сложно различить, можно загрузить новый текст нажав на иконку справа.<br />';	
		}

		if (error_message == '')
		{
			document.contacts_form.submit();
		}
		else
		{
			$("#contacts_form_error").html(error_message);
		}
	});
	
	$("#passport").change(function(){
		
		var passport = $(this).val();		
		passport = passport.toUpperCase();
		$(this).val(passport.replace(/[^0-9А-Я]/g, ""));		
	});
	
	$("#phone, #profile_phone_edit").change(function(){
		
		var phone = $(this).val();		
		phone = phone.replace(/[^0-9]/g, "");
		
		if (phone.length > 7)
		{
			phone = phone.replace(/^38|^8/, "");
			phone = "+38"+phone;
		}
		
		$(this).val(phone);
	});
	
	$("#reg_submit").click(function()
	{
		var name = $("#name").val();
		var surname = $("#surname").val();
		var secondname = $("#secondname").val();
		var email = $("#email").val();
		var phone = $("#phone").val();
		var city = $("#city").val();
		var passport = $("#passport").val();
		var login = $("#login").val();
		var passw = $("#passw").val();
		var passw_again = $("#passw_again").val();

		var wmid = $("#wmid").val();
		var purse_wmz = $("#purse_wmz").val();
		var purse_wme = $("#purse_wme").val();
		var purse_wmr = $("#purse_wmr").val();
		var purse_wmu = $("#purse_wmu").val();
		
		var captcha = $("#recaptcha_response_field").val();

		var regexp_wmid = /^\d{12}$/;
		var regexp_wme = /^E\d{12}$/;
		var regexp_wmr = /^R\d{12}$/;
		var regexp_wmu = /^U\d{12}$/;
		var regexp_wmz = /^Z\d{12}$/;

		error_message = '';
		
		$("#reg_form input[type=text]").each(function(){
			if ($(this).attr("id") != 'recaptcha_response_field')
			$(this).attr('class', 'input_regular');
		});
		$("#reg_form input[type=password]").each(function(){
			$(this).attr('class', 'input_regular');
		});

		$("#reg_error").html('');


		function send_reg_form()
		{
			if (check_login && check_email)
			{
				$("#reg_error").html(error_message);
				
				if (error_message == '')
				{
					document.reg_form.submit();
				}
			}
		}

		if (surname == '')
		{
			error_message += 'Введите Вашу фамилию<br />';	
			$("#surname").attr('class', 'input_regular_error');
		}

		if (name == '')
		{
			error_message += 'Введите Ваше имя<br />';	
			$("#name").attr('class', 'input_regular_error');
		}

		if (secondname == '')
		{
			error_message += 'Введите Ваше отчество<br />';	
			$("#secondname").attr('class', 'input_regular_error');
		}

		if (email == '')
		{
			error_message += 'Введите Ваш e-mail<br />';	
			$("#email").attr('class', 'input_regular_error');
			check_email = true;	
		}
		if ((email != '') && (!isValidEmail(email)))
		{
			error_message += 'Некорректный e-mail<br />';	
			$("#email").attr('class', 'input_regular_error');
			check_email = true;	
		}
		
		if ((email != '') && (isValidEmail(email)))
		{
			check_email = false;
			$.post("/ajax/main.php?check_email", "email="+email, 
					function(data)
					{
						if (data != 0)
						{
							error_message += 'Указанный e-mail уже использован при регистрации<br />';
							$("#email").attr('class', 'input_regular_error');
						}
						check_email = true;
						send_reg_form();	
					});
		}

		if (phone == '')
		{
			error_message += 'Введите номер телефона для связи с Вами<br />';	
			$("#phone").attr('class', 'input_regular_error');
		}
		else
		{
			if ((phone.length > 7 && !check_phone(phone)) || (phone.length <= 7 && !check_phone7(phone)))
			{
				error_message += 'Введите номер телефона в формате xxxxxxx или +380xxxxxxxxx<br />';	
				$("#phone").attr('class', 'input_regular_error');
			}
		}
		if (city == '')
		{
			error_message += 'Укажите Ваш город<br />';	
			$("#city").attr('class', 'input_regular_error');
		}

		if (passport == '')
		{
			error_message += 'Укажите номер Вашего паспорта<br />';	
			$("#passport").attr('class', 'input_regular_error');
		}
		else if (passport != '' && !check_passport(passport))
		{
			
			error_message += 'Номер Вашего паспорта указан неверно. Правильный формат - АА999999<br />';	
			$("#passport").attr('class', 'input_regular_error');
		}
		
		if (wmid == '')
		{
			error_message += 'Укажите Ваш WMID<br />';	
			$("#wmid").attr('class', 'input_regular_error');
		}
		else
		if (wmid != '' && !regexp_wmid.test(wmid))
		{
			error_message += 'WMID должен состоять из 12 цифр<br />';	
			$("#wmid").attr('class', 'input_regular_error');
		}
		
		if (purse_wmz != '' && !regexp_wmz.test(purse_wmz))
		{
			error_message += 'Z кошелек должен начинаться на Z и содержать 12 цифр<br />';	
			$("#purse_wmz").attr('class', 'input_regular_error');
		}
		
		if (purse_wmu != '' && !regexp_wmu.test(purse_wmu))
		{
			error_message += 'U кошелек должен начинаться на U и содержать 12 цифр<br />';	
			$("#purse_wmu").attr('class', 'input_regular_error');
		}
		
		if (purse_wme != '' && !regexp_wme.test(purse_wme))
		{
			error_message += 'E кошелек должен начинаться на E и содержать 12 цифр<br />';	
			$("#purse_wme").attr('class', 'input_regular_error');
		}
		
		if (purse_wmr != '' && !regexp_wmr.test(purse_wmr))
		{
			error_message += 'R кошелек должен начинаться на R и содержать 12 цифр<br />';	
			$("#purse_wmr").attr('class', 'input_regular_error');
		}
		
		check_login = false;
		if (login == '')
		{
			error_message += 'Введите логин<br />';	
			$("#login").attr('class', 'input_regular_error');
			check_login = true;
		}
		else
		{
			$.post("/ajax/main.php?check_login", "login="+login, 
					function(data)
					{
						if (data != 0)
						error_message += 'Указанный логин уже использован при регистрации<br />';	
						check_login = true;
						send_reg_form();
					});
		}

		if (passw == '')
		{
			error_message += 'Введите пароль<br />';	
			$("#passw").attr('class', 'input_regular_error');
		}

		if (passw != '' && (passw != passw_again))
		{
			error_message += 'Введенные пароли не совпадают<br />';	
			$("#passw_again").attr('class', 'input_regular_error');
		}
		if (captcha == '')
		{
			error_message += 'Введите текст, который Вы видите на картинке. Если текст сложно различить, можно загрузить новый текст нажав на иконку справа.<br />';	
		}
		send_reg_form();
	});
	
	$("#login_submit").click(function(){
		
		var login = $("#login_login").val();
		var pwd = $("#login_pwd").val();
		
		if ((login != '' && pwd != '') && (login != 'Ваш логин' || pwd != 'Ваш пароль'))
			$.post("/ajax/main.php?check_user", "login="+login+"&pwd="+pwd, 
					function(data)
					{
						if (data == 1)
						document.login_form.submit();
						else
						$.fancybox({
										'transitionIn'	:	'fade',
										'transitionOut'	:	'fade',
										'speedIn'		:	200, 
										'speedOut'		:	200, 
										'width'			:	340,
										'height'		:	165,
										'autoDimensions':	false,
										'overlayShow'	:	true,
										'overlayColor'	:	'#ddd',
										'overlayOpacity':	0.6,
										'titlePosition' :	'inside',
										'hideOnContentClick': true,
										'padding'		: 	0,
										'margin'		: 	0,
										'showCloseButton':	false,
										'href'			:	'#login_error1'
							});
				});
						
		else 
		$.fancybox({
						'transitionIn'	:	'fade',
						'transitionOut'	:	'fade',
						'speedIn'		:	200, 
						'speedOut'		:	200, 
						'width'			:	340,
						'height'		:	165,
						'autoDimensions':	false,
						'overlayShow'	:	true,
						'overlayColor'	:	'#ddd',
						'overlayOpacity':	0.6,
						'titlePosition' :	'inside',
						'hideOnContentClick': true,
						'padding'		: 	0,
						'margin'		: 	0,
						'showCloseButton':	false,
						'href'			:	'#login_error2'
			});
	});
	
	$("#edit_email").click(function(){
		$.getJSON("/ajax/main.php?get_user_info=", {}, function (data) {
					$("#profile_email_edit").val(data.email);
					$("#profile_email_show").hide();	
					$("#profile_email_edit_container").show();
		});
	});
	
	$("#profile_email_submit").click(function()
	{
		var email = $("#profile_email_edit").val();
		if (email != '' && isValidEmail(email))
		$.post("/ajax/main.php?profile_email_edit", "email="+email, function(data) {
			if (data == 'success') 
			{
				$("#profile_email_error").html('');
				$("#profile_email").html(email);
				$("#profile_email_edit_container").hide();
				$("#profile_email_show").show();	
			}
			else $("#profile_email_error").html(data);
		});
		else $("#profile_email_error").html('Некорректный e-mail');
	});
	
	$("#edit_login").click(function(){
		$.getJSON("/ajax/main.php?get_user_info=", {}, function (data) {
					$("#profile_login_edit").val(data.login);
					$("#profile_login_show").hide();	
					$("#profile_login_edit_container").show();
		});
	});
	
	$("#profile_login_submit").click(function()
	{
		var login = $("#profile_login_edit").val();
		if (login != '')
		$.post("/ajax/main.php?profile_login_edit", "login="+login, function(data) {
			if (data == 'success') 
			{
				$("#profile_login_error").html('');
				$("#profile_login").html(login);
				$("#profile_login_edit_container").hide();
				$("#profile_login_show").show();	
			}
			else $("#profile_login_error").html(data);
		});
		else $("#profile_login_error").html('Введите логин');
	});
	
	$("#edit_passw").click(function(){
					$("#profile_passw_show").hide();	
					$("#profile_passw_edit_container").show();
	});
	
	$("#profile_passw_submit").click(function()
	{
		var passw_old = $("#profile_passw_old").val();
		var passw_new = $("#profile_passw_new").val();
		var passw_new_again = $("#profile_passw_new_again").val();
		
		$("#profile_passw_old").attr('class', 'input_regular');
		$("#profile_passw_new").attr('class', 'input_regular');
		$("#profile_passw_new_again").attr('class', 'input_regular');
		
		$("#profile_passw_error1").html('');
		$("#profile_passw_error2").html('');

		if (passw_old != '' && passw_new != '' && passw_new_again != '' && passw_new == passw_new_again)
		{
			$.post("/ajax/main.php?profile_passw_edit", "passw_old="+passw_old+"&passw_new="+passw_new, function(data) {
				if (data == 'success') 
				{
					$("#profile_passw_error1").html('');
					$("#profile_passw_error2").html('');
					$("#profile_passw").html(passw_new);
					$("#profile_passw_old").val('');
					$("#profile_passw_new").val('');
					$("#profile_passw_new_again").val('');
					$("#profile_passw_edit_container").hide();
					$("#profile_passw_show").show();	
				}
				else if (data = 'old_password mismatch') $("#profile_passw_error1").html("Старый пароль неверен.");
				else $("#profile_passw_error2").html(data);
			});
		}
		else
		{
			if (passw_old == '') 
			{
				$("#profile_passw_old").attr('class', 'input_regular_error');
				$("#profile_passw_error1").html("Укажите старый пароль.");	
			} 
			
			error_contaniner2 = '';
			if (passw_new == '') 
			{
				$("#profile_passw_new").attr('class', 'input_regular_error');
				error_contaniner2 += "Укажите новый пароль.<br />";
			} 
			if (passw_new_again == '') 
			{
				$("#profile_passw_new_again").attr('class', 'input_regular_error');
				error_contaniner2 += "Укажите новый пароль еще раз в поле ниже.<br />";
			} 
			if (passw_new != '' && passw_new_again != '' && passw_new != passw_new_again)
			{
				$("#profile_passw_new_again").attr('class', 'input_regular_error');
				error_contaniner2 += "Введенный повторно пароль не совпадает с указанным строкой выше.<br />";
			}
			$("#profile_passw_error2").html(error_contaniner2);	
		}		
	});
	
	
	$("#edit_city").click(function(){
		$.getJSON("/ajax/main.php?get_user_info=", {}, function (data) {
					$("#profile_city_edit").val(data.city);
					$("#profile_city_show").hide();	
					$("#profile_city_edit_container").show();
		});
	});
	$("#profile_city_submit").click(function()
	{
		var city = $("#profile_city_edit").val();
		if (city != '')
		$.post("/ajax/main.php?profile_city_edit", "city="+city, function(data) {
			if (data == 'success') 
			{
				$("#profile_city_error").html('');
				$("#profile_city").html(city);
				$("#profile_city_edit_container").hide();
				$("#profile_city_show").show();	
			}
			else $("#profile_city_error").html(data);
		});
		else $("#profile_city_error").html('Введите город');
	});
	
	$("#edit_phone").click(function(){
		$.getJSON("/ajax/main.php?get_user_info=", {}, function (data) {
					$("#profile_phone_edit").val(data.phone);
					$("#profile_phone_show").hide();	
					$("#profile_phone_edit_container").show();
		});
	});
	$("#profile_phone_submit").click(function()
	{
		var phone = $("#profile_phone_edit").val();
		if (phone != '')
		{
			if ((phone.length > 7 && !check_phone(phone)) || (phone.length <= 7 && !check_phone7(phone)))
			{
				$("#profile_phone_error").html('Введите номер телефона в формате xxxxxxx или +380xxxxxxxxx');	
			}
			else
			$.post("/ajax/main.php?profile_phone_edit", "phone="+phone, function(data) {
				if (data == 'success') 
				{
					$("#profile_phone_error").html('');
					$("#profile_phone").html(phone);
					$("#profile_phone_edit_container").hide();
					$("#profile_phone_show").show();	
				}
				else $("#profile_phone_error").html(data);
			});
		}
		else $("#profile_phone_error").html('Введите Ваш номер телефона');
	});
	
	$("#profile_add_purse").click(function(){
		$("#profile_add_purse_container").show();
	});
	
	$("#add_purse_submit").click(function(){
		
		var purse_type = $("#add_purse_type").val();
		var purse_num = $("#add_purse_num").val();
		$("#add_purse_num").attr("class", "input_regular");
		$("#add_purse_error").html("");
		
		if (purse_num == '') 
		{
			$("#add_purse_error").html("Введите номер кошелька");
			$("#add_purse_num").attr("class", "input_regular_error");
		}
		else
		{
			switch (purse_type)
			{
				case 'wme': var regexp_purse = /^E\d{12}$/; var purse_error = 'E кошелек должен начинаться на E и содержать 12 цифр'; break;
				case 'wmr': var regexp_purse = /^R\d{12}$/; var purse_error = 'R кошелек должен начинаться на R и содержать 12 цифр'; break;
				case 'wmu': var regexp_purse = /^U\d{12}$/; var purse_error = 'U кошелек должен начинаться на U и содержать 12 цифр'; break;
				case 'wmz': var regexp_purse = /^Z\d{12}$/; var purse_error = 'Z кошелек должен начинаться на Z и содержать 12 цифр'; break;
			}
			
			if (regexp_purse.test(purse_num))
			{
				// проверка нет ли такого кошелька
				$.post("/ajax/main.php?add_purse", "num="+purse_num+"&type="+purse_type, function(data) {
					if (data == 'success') 
					{
						/* получение списка кошельков */
						$.post("/ajax/main.php?get_purses", "", function(data2) {
						
							$("#add_purse_error").html('');
							$("#add_purse_num").val('');
							$("#add_purse_type :first").attr("selected", "selected");
							$("#profile_add_purse_container").hide();
							$("#profile_purses").html(data2);
						});
					}
					else if (data == 'purse already exists') $("#add_purse_error").html("Указанный кошелек уже существует в системе");
					else $("#add_purse_error").html(data);
				});
			}
			else
			$("#add_purse_error").html(purse_error);
			
		}
		
	});
	
	$(".profile_purse_remove").live('click', function(){
		
		var parts = $(this).attr("id").split("_");
		
		$.post("/ajax/main.php?remove_purse", "purse_id="+parts[2], function(data) {
				if (data == 'success') 
				{
					$("#pp_"+parts[2]).fadeOut();
				}
				else alert(data);
			});
	});
	
	/* home calc area */
	function calculate()
	{
		$("#home_calc_error").css('display', 'none');
		var calc_out = $("#calc_out").val();
		var calc_in = $("#calc_in").val();
		
		var calc_rate_out = $("#home_calc_out_selected").text();
		var calc_rate_in = $("#home_calc_in_selected").text();
		// если указано сколько дает пользователь, валюты не совпадают и одна из валют - гривна (без кросс-обмена)
		if (calc_in != '' && calc_rate_in != calc_rate_out && (calc_rate_in == 'UAH' || calc_rate_out == 'UAH'))
		$.getJSON("/ajax/main.php?calculate&calc_in="+calc_in+"&calc_rate_in="+calc_rate_in+"&calc_rate_out="+calc_rate_out, {}, function(data){
			
			$("#calc_out").val(data.amount_total);
		
		});
		else if (calc_rate_in != 'UAH' && calc_rate_out != 'UAH')
		{
			$("#home_calc_error").html('Одна из валют - обязательно гривна.');
			$("#home_calc_error").css('display', 'block');
		}
		else
		{
			// если валюты совпадают
			if (calc_rate_in == calc_rate_out)
				$("#calc_out").val(calc_in);
				/*
			else
			{
				$("#home_calc_error").html('Укажите параметры обмена');
				$("#home_calc_error").css('display', 'block');
			}*/
		}
	}
	
	function calculate_reverse()
	{
		$("#home_calc_error").css('display', 'none');
		// если указано сколько надо получить	
		var calc_out = $("#calc_out").val();
		var calc_in = $("#calc_in").val();
		
		var calc_rate_out = $("#home_calc_out_selected").text();
		var calc_rate_in = $("#home_calc_in_selected").text();
		// если указано сколько дает пользователь, валюты не совпадают и одна из валют - гривна (без кросс-обмена)
		if (calc_out != '' && calc_rate_in != calc_rate_out && (calc_rate_in == 'UAH' || calc_rate_out == 'UAH'))
		$.getJSON("/ajax/main.php?calculate_reverse&calc_in="+calc_out+"&calc_rate_in="+calc_rate_in+"&calc_rate_out="+calc_rate_out, {}, function(data){
			
			$("#calc_in").val(data.amount_total);
		
		});
		else if (calc_rate_in != 'UAH' && calc_rate_out != 'UAH')
		{
			$("#home_calc_error").html('Одна из валют - обязательно гривна.');
			$("#home_calc_error").css('display', 'block');
		}
		else
		{
			// если валюты совпадают
			if (calc_rate_in == calc_rate_out)
				$("#calc_out").val(calc_in);
				/*
			else
			{
				$("#home_calc_error").html('Укажите параметры обмена');
				$("#home_calc_error").css('display', 'block');
			}
			*/
		}
	}

	// при изменении входящей валюты
	$("#home_calc_in_container .home_calc_select_option, #home_calc_in_container .home_calc_select_option_last").click(function(){
		$("#home_calc_error").css('display', 'none');
/*
		if ($(this).text() == $("#home_calc_out_selected").text())
		{
			$("#home_calc_error").html('Валюты совпадают');
			$("#home_calc_error").css('display', 'block');
		}
*/
		var calc_rate_out = $("#home_calc_out_selected").text();
		var calc_rate_in = $(this).text();
		
		// если выбрана такая же валюта, как и исходящая
		if (calc_rate_in != 'UAH' && calc_rate_out != 'UAH')
		{
			$("#home_calc_in_selected").text($(this).text());
			$("#calc_in").val('');
			$("#calc_out").val('');
		}
		else
		{
			if (calc_rate_in == 'UAH' || calc_rate_out == 'UAH')
			{
				$("#home_calc_in_selected").text($(this).text());
				// если порядок следующий - поставили WM-WM, потом в "я получу" ввели число и поставили пару UAH-WM.
				if ($("#calc_in").val() == '') calculate_reverse(); else
				calculate();
			}
			else
			{
				$("#home_calc_error").html('Одна из валют - обязательно гривна.');
				$("#home_calc_error").css('display', 'block');
			}
		}
	});
	
	// при изменении исходящей валюты
	$("#home_calc_out_container .home_calc_select_option, #home_calc_out_container .home_calc_select_option_last").click(function(){
		$("#home_calc_error").css('display', 'none');
/*
		if ($(this).text() == $("#home_calc_in_selected").text())
		{
			$("#home_calc_error").html('Валюты совпадают');
			$("#home_calc_error").css('display', 'block');
		}
*/
		var calc_rate_out = $(this).text();
		var calc_rate_in = $("#home_calc_in_selected").text();

		// если выбрана такая же валюта, как и вхощящая
		if (calc_rate_in != 'UAH' && calc_rate_out != 'UAH')
		{
			$("#home_calc_out_selected").text($(this).text());
			$("#calc_in").val('');
			$("#calc_out").val('');
		}
		else
		if (calc_rate_in == 'UAH' || calc_rate_out == 'UAH')
		{
			$("#home_calc_out_selected").text($(this).text());
			calculate();
		}
		else
		{
			$("#home_calc_error").html('Одна из валют - обязательно гривна.');
			$("#home_calc_error").css('display', 'block');
		}
	});			
	
	
	// при изменении входящего количества
	$("#calc_in").keyup(function(){		
		calculate();
	});
	
	// при изменении исходящего количества
	$("#calc_out").keyup(function(){		
		calculate_reverse();
	});
	
// оформление заявки посчитанной на калькуляторе	
	$("#home_calc_submit").click(function(){
		$("#home_calc_error").css('display', 'none');
		var calc_out = $("#calc_out").val();
		var calc_in = $("#calc_in").val();
		var rate_out = $("#home_calc_out_selected").text();
		var rate_in = $("#home_calc_in_selected").text();

		if (calc_in != '' && calc_out != '')
		{
			if (rate_in == 'UAH' || rate_out == 'UAH')
			{
				location.href = '/order.htm?calc_in='+calc_in+'&calc_out='+calc_out+'&rate_in='+rate_in+'&rate_out='+rate_out;
			}
			else
			{
				$("#home_calc_error").html('Одна из валют - обязательно гривна.');
				$("#home_calc_error").css('display', 'block');
			}
		}
		else 
		{
			$("#home_calc_error").html('Вначале воспользуйтесь калькулятором');
			$("#home_calc_error").css('display', 'block');
		}
		
	});
	
	$("#home_calc_qw").fancybox({
					'transitionIn'	:	'fade',
					'transitionOut'	:	'fade',
					'speedIn'		:	200, 
					'speedOut'		:	200, 
					'width'			:	340,
					'height'		:	440,
					'autoDimensions':	false,
					'overlayShow'	:	true,
					'overlayColor'	:	'#ddd',
					'overlayOpacity':	0.6,
					'titlePosition' :	'inside',
					'hideOnContentClick': false,
					'padding'		: 	0,
					'margin'		: 	0,
					'showCloseButton':	false,
					'href'			:	"#home_calc_help"
		});
		
	$("#restore_pwd").fancybox({
					'transitionIn'	:	'fade',
					'transitionOut'	:	'fade',
					'speedIn'		:	200, 
					'speedOut'		:	200, 
					'width'			:	340,
					'height'		:	185,
					'autoDimensions':	false,
					'overlayShow'	:	true,
					'overlayColor'	:	'#ddd',
					'overlayOpacity':	0.6,
					'titlePosition' :	'inside',
					'hideOnContentClick': false,
					'padding'		: 	0,
					'margin'		: 	0,
					'showCloseButton':	false
		});
	
	$("#pwd_rec_submit").click(function(){
		$("#pwd_rec_error").html('');
		var email = $("#pwd_rec_email").val();
		if (email != '' && isValidEmail(email))
		$.post("/ajax/main.php?pwd_rec", "email="+email, function(data) {
			if (data == 'success') 
			{
				$("#pwd_rec_desc_container").html('Ваш пароль был выслан на e-mail <b>'+email+'</b>.<br /><br />Если по каким-то причинам в течении ближайших 10 минут Вы не получите письмо с напоминанием пароля, проверьте папку "Спам" - всякое бывает :)');
			}
			else $("#pwd_rec_error").html(data);
		});
		else $("#pwd_rec_error").html('Некорректный e-mail');
	});
	
	/* order area */
	$("#order_step2_submit").click(function()
	{
		var name = $("#name").val();
		var surname = $("#surname").val();
		var secondname = $("#secondname").val();
		var email = $("#email").val();
		var phone = $("#phone").val();
		var city = $("#city").val();
		var passport = $("#passport").val();
		var wmid = $("#wmid").val();
		var purse = $("#purse").val();
		var is_fast = $("#is_fast").val();
		
		var errors = false;
		
		$(".order_white_middle2 .input_container_error").each(function(){
			$(this).html('');
		});

		$(".order_white_middle2 input").each(function(){
			$(this).attr('class', 'input_regular');
		});

		if (surname == '')
		{
			errors = true;
			$("#surname_error").html('Введите Вашу фамилию');
			$("#surname").attr('class', 'input_regular_error');
		}

		if (name == '')
		{
			errors = true;
			$("#name_error").html('Введите Ваше имя');
			$("#name").attr('class', 'input_regular_error');
		}

		if (secondname == '')
		{
			errors = true;
			$("#secondname_error").html('Введите Ваше отчество');
			$("#secondname").attr('class', 'input_regular_error');
		}

		if (email == '')
		{
			errors = true;
			$("#email_error").html('Введите Ваш e-mail');
			$("#email").attr('class', 'input_regular_error');
		}
		if ((email != '') && (!isValidEmail(email)))
		{
			errors = true;
			$("#email_error").html('Некорректный e-mail');
			$("#email").attr('class', 'input_regular_error');
		}
		
		if (phone == '')
		{
			errors = true;
			$("#phone_error").html('Введите номер телефона для связи с Вами');
			$("#phone").attr('class', 'input_regular_error');
		}
		else
		{
			if ((phone.length > 7 && !check_phone(phone)) || (phone.length <= 7 && !check_phone7(phone)))
			{
				$("#phone_error").html('Правильный формат номера +380xxxxxxxxx или xxxxxxx');	
				$("#phone").attr('class', 'input_regular_error');
			}
		}

		if (city == '')
		{
			errors = true;
			$("#city_error").html('Укажите Ваш город');
			$("#city").attr('class', 'input_regular_error');
		}

		if (passport == '')
		{
			if (!is_fast)
			{
				errors = true;
				$("#passport_error").html('Укажите номер Вашего паспорта');
				$("#passport").attr('class', 'input_regular_error');
			}
		}
		else if (passport != '' && !check_passport(passport))
		{
			$("#passport_error").html('Правильный формат - АА999999');
			$("#passport").attr('class', 'input_regular_error');
		}
				
		var purse_type = ($("#rate_in").val() == 'UAH') ? $("#rate_out").val() : $("#rate_in").val();
		switch (purse_type)
		{
			case 'WME': var regexp_purse = /^E\d{12}$/; var purse_error = 'E кошелек должен начинаться на E и содержать 12 цифр'; break;
			case 'WMR': var regexp_purse = /^R\d{12}$/; var purse_error = 'R кошелек должен начинаться на R и содержать 12 цифр'; break;
			case 'WMU': var regexp_purse = /^U\d{12}$/; var purse_error = 'U кошелек должен начинаться на U и содержать 12 цифр'; break;
			case 'WMZ': var regexp_purse = /^Z\d{12}$/; var purse_error = 'Z кошелек должен начинаться на Z и содержать 12 цифр'; break;
		}
		//var regexp_purse = /^[Z|E|U|R]{1}\d{12}$/;
		if (purse == '')
		{
			errors = true;
			$("#purse_error").html('Укажите кошелек');
			$("#purse").attr('class', 'input_regular_error');
		}
		else if (purse != '' && !regexp_purse.test(purse))
		{
			errors = true;
			$("#purse_error").html(purse_error);
			$("#purse").attr('class', 'input_regular_error');
		}
		
		var regexp_wmid = /^\d{12}$/;
		if (wmid == '')
		{
			errors = true;
			$("#wmid_error").html('Укажите Ваш WMID');
			$("#wmid").attr('class', 'input_regular_error');
		}
		else if (wmid != '' && !regexp_wmid.test(wmid))
		{
			errors = true;
			$("#wmid_error").html('WMID должен состоять из 12 цифр');
			$("#wmid").attr('class', 'input_regular_error');
		}
				
		if (!errors)
		{
			var type = 1;
			if ($("#rate_out").val() == 'UAH')
			{
				var direction = 1;
				var pursetype = $("#rate_in").val();
				var amount = $("#calc_in").val();
			} else
			{
				var direction = 2;
				var pursetype = $("#rate_out").val();
				var amount = $("#calc_out").val();
			}
			
			if (is_fast)
			{
				document.order_form.submit();
			}
			else
			{
				$.getJSON("/ajax/wm_interface.php?check_user_x19", {"type" : type, "direction" : direction, "pursetype" : pursetype, "amount" : amount, "pnomer" : passport, "iname" : name, "fname" : surname, "wmid" : wmid}, function(data) {
					
					if (data['retval'] == 0)
					{
						$("#wmxml_code").val(data['retval']);
						$("#wmxml_descr").val(data['retdesc']);
						$("#wmxml_id").val(data['retid']);
						document.order_form.submit();
					}
					else
					{
						$("#order_2_error").html("<b>Обмен невозможен:</b> " + data['retdesc']);
					}
				});
			}
			//alert ('submit');
			//
		}
	});
	
	$("#order_2_purses div").click(function(){
		$("#purse").val($(this).text());
	});
	
}); 
