var loginRegistered = false; //Флаг, зарегистрирован ли пароль. Для проверки перед отправкой. 
var city_id = 0, region_id = 0, country_id = 0; //Гео переменные
var set_city = false;

$(document).ready(function(){
    if($("#regregion > option:selected").size() == 0) {
        //Создание списка стран 
        $("#regregion").hide();
        $("#regregionLabelHolder").hide();        
    }
	if($("#regcity > option:selected").size() == 0) {
	    $("#regcity").hide();
	    $("#regcityLabelHolder").hide();
    }
	setGeoLoaders();
	
	
	function setGeoLoaders(){ //Ajax загрузка городов, регионов, стран
			$("select[name='regcountry']").change(function(e){
				e.preventDefault();
				$("#regcountry option[value=0]").attr('selected', false);
				$("#regregion").hide();
				$("#regionLabelHolder").hide();
				$("#regcity").hide();
				$("#regcityLabelHolder").hide();
				$.post("/xajax/xajax.php", {
					func: "getGeoList",
					geoParent: $(this).attr('value'),
					geoTarget: "region"
				}, function(xml){
					//Пришел ответ-список регионов
					$("select[name='regregion']").html($("option", xml).get());
					$("select[name='regregion'] > option[value=0]").attr('selected', true);
					$("select[name='regregion']").show();
					$("#regionLabelHolder").show();
					
					$("#regcity").hide();
					$("#regcityLabelHolder").hide();
					
					//Обработчик выбора региона 
					$("select[name='region']").change(function(){
						$.post("/xajax/xajax.php", {
							func: "getGeoList",
							geoParent: $("select[name='region']").attr('value'),
							geoTarget: "city"
						}, function(xml){
							$("#regcity").show();
							$("#regcityLabelHolder").show();
							//Пришел ответ-список городов
							$("select[name='regcity']").html($("option", xml).get());
							$("select[name='regcity'] > option[value=0]").attr('selected', true);
							
							if (city_id > 0) {
								$("#regcity").attr('value', city_id);
								city_id = 0;
							}
						}, "html");
					});
					
					if (region_id > 0) {
						$("#regregion").attr('value', region_id);
						region_id = 0;
						$("#regregion").change();
					}
					
				}, "html");
				
			});
					$("select[name='regregion']").change(function(){
						$.post("/xajax/xajax.php", {
							func: "getGeoList",
							geoParent: $("select[name='regregion']").attr('value'),
							geoTarget: "city"
						}, function(xml){
							$("#regcity").show();
							$("#regcityLabelHolder").show();
							//Пришел ответ-список городов
							$("select[name='regcity']").html($("option", xml).get());
							$("select[name='regcity'] > option[value=0]").attr('selected', true);
							
							if (city_id > 0) {
								$("#regcity").attr('value', city_id);
								city_id = 0;
							}
						}, "html");
					});
			
	};	
	//Получение дефолтных гео данных (по ip)
	$.post("/xajax/xajax.php", {
		func: "getCityByIP"
	}, function(xml){
		city_id = $("city_id", xml).text();
		region_id = $("region_id", xml).text();
		country_id = $("country_id", xml).text();
		
		if (city_id > 0 && region_id > 0 && country_id > 0) {
			//Положение определено	 
			set_city = true;
		}
		setGeoLoaders();
	}, "html");
	
	//Проверка свободности логина
	$("#regemail").change(function(){
		$.post("/xajax/xajax.php", {
			func: "checkLogin",
			login: $("#regemail").attr('value')
		}, function(xml){
			//Пришел ответ-корректен ли логин
			var loginStat = $("login_status", xml).text();
			if (loginStat != "correct") {
				$("#regInfoBlock").show();
				$("#regInfoBlock").html('<li>— Такой адрес уже зарегистрирован.</li>');
				loginRegistered = true;
			} else {

				if (loginRegistered) $("#regInfoBlock").hide();
				
				loginRegistered = false;
			}
		});
	})
	
	//Получение списка типов пользователей
	$.post("/xajax/xajax.php", {
		func: "getUsertypeList"
	}, function(xml){
		//Пришел ответ-список типов
		$("#regusertype").html('');
		$("#regusertype").append(xml);
        if($('#userType').size()>0 && $('#userType').attr('value')>0)
        {
            $("#regusertype option[value="+$('#userType').attr('value')+"]").attr('selected','selected');
        }
	}, "html");
	
	

	//События для кнопки submit
	$("#regSubmitReg, #sendBB").click(function(e){
if($('input[name="login"]').attr('value')==''){
		e.preventDefault();
		var email = $("#regemail");
		var password = $("#regpassword");
		var password2 = $("#regpassword2");
		var name = $("#regname");
		var surname = $("#regsurname");
		
		var cnt_code = $("#regcnt_code");
		var cty_code = $("#regcty_code");
		var phone = $("#regphone");
		var usertype = $("#regusertype");
		
		var country = $("#regcountry");
		var region = $("#regregion");
		var city = $("#regcity");
		
		var msg = new Array();
		var inp = email;
		if (city.length > 0 && city.attr('value') == -1) {
			msg.push("— Не выбран город<br />");
			inp = city.get();
		}
		if (region.length > 0 && region.attr('value') == -1) {
			msg.push("— Не выбран регион<br />");
			inp = region.get();
		}
		if (country.attr('value') == -1) {
			msg.push("— Не выбрана страна<br />");
			inp = country.get();
		}
		
		if (phone.attr('value').length == 0) {
			msg.push("— Не введен номер телефона<br />");
			inp = phone.get();
		}
	
		if (surname.attr('value').length == 0) {
			msg.push("— Не заполнена фамилия<br />");
			inp = surname;
		}
		if (name.attr('value').length == 0) {
			msg.push("— Не заполнено имя<br />");
			inp = name;
		}
		if (password.attr('value').length == 0) {
			msg.push("— Не заполнен пароль<br />");
			inp = password;
		}
		if (password.attr('value') != password2.attr('value')) {
			msg.push("— Пароли не совпадают<br />");
			inp = password.get();
		}
		if (password.attr('value').length < 6 && password.attr('value').length > 0) {
			msg.push("— Слишком короткий пароль<br />");
			inp = password.get();
		}
		if (password.attr('value').length > 20) {
			msg.push("— Слишком длинный пароль<br />");
			inp = password.get();
		}
		
		
		var mailRegExp = new RegExp("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})");
		
		if (email.attr('value').length == 0 || !(mailRegExp.test(email.attr('value')))) {
			msg.push("— Неверный email<br />");
			inp = email;
		}
		
		//Проверка на существующий логин
		if (loginRegistered) {
			msg.push("— Такой адрес уже зарегистрирован<br />");
			inp = email;
		}
		
		//Вывод
		if (msg.length == 0 && !loginRegistered) {
		
			if ($("#regInfoBlock").hasClass("err")) $("#regInfoBlock").removeClass("err");
			$("#regInfoBlock").addClass("mess");
			$("#regInfoBlock").html('Регистрация. Подождите, пожалуйста...');
			
			$("#regInfoBlock").hide();
			
			//Проверка пройдена. Отправляем форму
			$("#registerForm").submit();
		} else {
			$("#regInfoBlock").html('');
			
			//if (!$("#regInfoBlock").hasClass("err"))
			//$("#regInfoBlock").addClass("err");
			for (i = msg.length - 1; i >= 0; i--) {
				$("#regInfoBlock").append('<li>'+msg[i]+'</li>');
			}
			
			$("#regInfoBlock").show();
			//inp.focus();
			if ($(this).attr('id')=='sendBB') self.scroll(1, 950);
			else self.scroll(1, 1);
			
		}
	}
	})
	
});

function setGeoLoaders(){ //Ajax загрузка городов, регионов, стран
	$.post("/xajax/xajax.php", {
		func: "getGeoList",
		geoTarget: "country"
	}, function(xml){
		//Пришел ответ-список регионов
		$("select[name='regcountry']").html($("option", xml).get());
		if ($.browser.msie &&($.browser.version.substr(0,1)=='6')){
			$("#regcountry option[value='-1']").attr('checked','checked');
		}
		else $("#regcountry option[value='-1']").attr('selected','selected');
		
		//Обработчик выбора страны 
		$("select[name='regcountry']").change(function(e){
if ($(this).attr('value') == 1) {
$("#regcity").html('<option  value="1" selected >1</option>');

} else {
	//********
	e.preventDefault();
	$("#regregion").hide();
	$("#regregionLabelHolder").hide();
	$("#regcity").hide();
	$("#regcityLabelHolder").hide();
	$.post("/xajax/xajax.php", {
		func: "getGeoList",
		geoParent: $(this).attr('value'),
		geoTarget: "region"
	}, function(xml){
	
		//Пришел ответ-список регионов
		$("#regregion").html($("option", xml).get());
		//
		if ($.browser.msie && ($.browser.version.substr(0, 1) == '6')) {
			$("#regregion option[value='-1']").attr('checked', 'checked');
		} else $("#regregion option[value='-1']").attr('selected', 'selected');
		
		$("#regregion").show();
		$("#regregionLabelHolder").show();
		
		$("#regcity").hide();
		$("#regcityLabelHolder").hide();
		
		//Обработчик выбора региона 
		$("#regregion").change(function(){
			$.post("/xajax/xajax.php", {
				func: "getGeoList",
				geoParent: $("#regregion").attr('value'),
				geoTarget: "city"
			}, function(xml){
				$("#regcity").show();
				$("#regcityLabelHolder").show();
				//Пришел ответ-список городов
				$("#regcity").html($("option", xml).get());
				
				if ($.browser.msie && ($.browser.version.substr(0, 1) == '6')) {
					$("#regcity option[value='-1']").attr('checked', 'checked');
				} else $("#regcity option[value='-1']").attr('selected', 'selected');
				
				if (city_id > 0) {
					$("#regcity").attr('value', city_id);
					city_id = 0;
				}
			}, "html");
		});
		
		if (region_id > 0) {
			$("#regregion").attr('value', region_id);
			region_id = 0;
			$("#regregion").change();
		}
		
	}, "html");
	
}	
		//****************	
		});
		
		if (country_id > 0) {
			$("select[name='regcountry']").attr('value', country_id);
			country_id = 0;
			$("select[name='regcountry']").change();
		}
	}, "html");
}

