$(document).ready(function() {
	//=======================
	//-----------------------
	//переменные необходимые для работы выбора страны/региона/города
	//*********************************
	//*********************************
	//*********************************
	//*********************************
	//*********************************
	//СТРАНА
	//=======================
	var delay_country=500;		// временная задержка по истечению которой система поймет, что можно отправлять запрос- влияет на загрузку
	var delay_region=400;		// -/-
	var delay_city=700;			// -/-
	var delay_all=jQuery.extend({	//суммарные задержки времени для страны, региона, города
		country:0,
		region:0,
		city:0
	});
	//=================================
	var id_country=0;			//идентификатор выбранной страны
	var id_region=0;			//идентификатор выбранного региона
	var id_city=0;				//идентификатор выбранного города
	//=================================
	var country_ready=0;		//готовность текстового блока выбора страны к отправки его содержимого для получения списка
								//доступных стран по шаблону
	var region_ready=0;			// -/-
	var city_ready=0;			// -/-
	//==================================
	//==================================
	// функция, делающая задержку для установки готовности блока выбора страны
	//==================================
	function countryDelay(){
		country_ready=0;			// устанавливаем в ноль готовность блока выбора страны
		delay_all.country=delay_all.country+delay_country;
		setTimeout(country_function,delay_all.country);
	}
	
	//==================================
	//==================================
	// функция, вызывает получение списка стран после окончания паузы
	//==================================
	function country_function(){
		if(country_ready!=1){
			delay_all.country=delay_all.country-delay_country;
			if(delay_all.country==0){
				country_ready=1;		//делаем доступным выбор страны
				getCountrys();			//вызываем функцию получения списка стран
			}
		}else{
			delay_all.country=0;
		}
	}
	//==================================
	//==================================
	// функция, получения списка стран
	//==================================
	function getCountrys(){
		$("select_").hide();
		if(country_ready==1){
			if($("#country").val().length==0){
				id_region=0;
				id_city=0;
				id_country=0;
			}
			if($("#country").val().length>-1){
				var id_block="country";
				$("#select_country").parent().parent().find('.ajax-star').show();
				var country_value=$("#country").val();
				$.get(
					"/index.php",
					{par1:"country",par2:"get_country",par4:country_value,ajax:"1"},
					function(data){
						var json = eval("(" + data + ")");
						var html_country='';
						if(json.site.count>1){
							var html_country='';
							$.each(json.site.countrys,function(id_c,name_country){
								html_country=html_country+" <div class='selected_ selected_"+id_block+"' id='"+id_block+"_n"+id_c+"'>"+name_country+"</div>  ";
							});
							$("#select_"+id_block).html(html_country);
							$("#select_"+id_block).parent().parent().find('.ajax-star').hide();
							$("#select_"+id_block).fadeIn(500);
						}else if(json.site.count==1){
							$.each(json.site.countrys,function(id_c,name_country){
								id_country=id_c;
								name_country=name_country.replace("<b>","");
								$("#select_country").parent().parent().find('.ajax-star').hide();
								name_country=name_country.replace("</b>","");
								$("#country").val(name_country);
							});							
						}else{
							$("#select_country").parent().parent().find('.ajax-star').hide();
							id_region=0;
							id_city=0;
							id_country=0;
						}
					}
				);
			}
			else{
				id_region=0;
				id_city=0;
				id_country=0;
				$("#country").val('');
				$("#region").val('');
				$("#city").val('');
			}
		}
	}
	//===================================
	$("#country").keydown(function(e){
		if($.inArray(e.which,[9,32,13,220,17,16,18,91,93,191,106,187,189,48,49,40,51,52,53,54,55,56,57,37,38,39,40])==-1){
			$("#select_country").fadeOut(500);
			id_region=0;
			id_city=0;
			id_country=0;
			$("#region").val('');
			$("#city").val('');
			if(($("#country").val().length==1)&&(e.which==8)){
				
			}
			else if($("#country").val().length>-1)
				countryDelay();
		}
	});
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	$(".country_select").live("click",function(e){
		var id_block=$(this).parent().children(".contry_input").attr('id');
		if(id_block=='country'){
			country_ready=1;
			$("#select_country").fadeOut(500);
			getCountrys();			
		}
		if(id_block=='region'){
			region_ready=1;
			$("#select_region").fadeOut(500);
			getRegions();
		}	
		if(id_block=='city'){
			city_ready=1;
			$("#select_city").fadeOut(500);
			getCitys();
		}
	});
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	$(".selected_country").live("click",function(){
		var this_id=$(this).attr('id');
		var country_id=this_id.substr(9,this_id.length);
		$("#country_id").val(id_country);
		id_country=country_id;
		$("#country").val($(this).text());
		$("#select_country").fadeOut(500);
		id_region=0;
		id_city=0;
		$("#region_id").val(id_region);
		$("#region").val('');
		$("#city_id").val(id_city);
		$("#city").val('');
	});
		
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//РЕГИОН
	//==================================
	// функция, делающая задержку для установки готовности блока выбора региона
	//==================================
	function regionDelay(){
		region_ready=0;			// устанавливаем в ноль готовность блока выбора региона
		delay_all.region=delay_all.region+delay_region;
		setTimeout(region_function,delay_all.region);
	}
	
	//==================================
	//==================================
	// функция, вызывает получение списка регионов после окончания паузы
	//==================================
	function region_function(){
		if(region_ready!=1){
			delay_all.region=delay_all.region-delay_region;
			if(delay_all.region==0){
				region_ready=1;		//делаем доступным выбор региона
				getRegions();			//вызываем функцию получения списка регионов
			}
		}else{
			delay_all.region=0;
		}
	}
	//==================================
	//==================================
	// функция, получения списка регионов
	//==================================
	function getRegions(){
		$("select_").hide();
		if(region_ready==1){
			if($("#region").val().length==0){
				id_region=0;
				id_city=0;
			}
			if($("#region").val().length>-1){
				var id_block="region";
				$("#select_region").parent().parent().find('.ajax-star').show();
				var region_value=$("#region").val();
				$.get(
					"/index.php",
					{par1:"country",par2:"get_region",par3:id_country,par4:region_value,ajax:"1"},
					function(data){
						var json = eval("(" + data + ")");
						var html_region='';
						if(json.site.count>1){
							var html_region='';
							$.each(json.site.regions,function(id_r,name_region){
								html_region=html_region+" <div class='selected_ selected_"+id_block+"' id='"+id_block+"_n"+id_r+"'>"+name_region+"</div>  ";
							});
							$("#select_"+id_block).html(html_region);
							$("#select_"+id_block).parent().parent().find('.ajax-star').hide();
							$("#select_"+id_block).fadeIn(500);
						}else if(json.site.count==1){
							$.each(json.site.regions,function(id_r,name_region){
								id_region=id_r;
								name_region=name_region.replace("<b>","");
								$("#select_region").parent().parent().find('.ajax-star').hide();
								name_region=name_region.replace("</b>","");
								$("#region").val(name_region);
							});
							if(id_country==0){
								getCountryByRegion();
							}
						}else{
							$("#select_region").parent().parent().find('.ajax-star').hide();
							id_region=0;
							id_city=0;
						}
					}
				);
			}
			else{
				id_region=0;
				id_city=0;
				$("#region").val('');
				$("#city").val('');
			}
		}
	}
	//===================================
	//функция для получения страны, если она не выбрана по региону
	//===================================
	//===================================
	function getCountryByRegion(){
		$("select_").hide();
		$.get(
			"/index.php",
			{par1:"country",par2:"getcountryfromregion",par4:id_region,ajax:"1"},
			function(data){
				var json = eval("(" + data + ")");
				if(json.site.count>1){
					alert("Ошибка выполнения сценария!");
					id_region=0;
					id_city=0;
					id_country=0;
					$("#country").val('');
					$("#region").val('');
					$("#city").val('');
				}else if(json.site.count==1){
					$.each(json.site.countrys,function(id_c,name_country){
						id_country=id_c;
						name_country=name_country.replace("<b>","");
						$("#select_country").parent().parent().find('.ajax-star').hide();
						name_country=name_country.replace("</b>","");
						$("#country").val(name_country);
					});							
				}else{
					alert("Ошибка выполнения сценария! Данный регион не соответствует ни одной из стран!");
					id_region=0;
					id_city=0;
					id_country=0;
					$("#country").val('');
					$("#region").val('');
					$("#city").val('');
				}
			}
		);
	}
	//===================================
	//функция для получения региона, если он не выбран по городу
	//===================================
	//===================================
	function getRegionByCity(){
		$("select_").hide();
		$.get(
			"/index.php",
			{par1:"country",par2:"getregionfromcity",par4:id_city,ajax:"1"},
			function(data){
				var json = eval("(" + data + ")");
				if(json.site.count>1){
					alert("Ошибка выполнения сценария!");
					id_region=0;
					id_city=0;
					$("#region").val('');
					$("#city").val('');
				}else if(json.site.count==1){
					$.each(json.site.regions,function(id_r,name_region){
						id_region=id_r;
						name_region=name_region.replace("<b>","");
						$("#select_region").parent().parent().find('.ajax-star').hide();
						name_region=name_region.replace("</b>","");
						$("#region").val(name_region);
					});							
				}else{
					alert("Ошибка выполнения сценария! Данный город не соответствует ни одному из регионов!");
					id_region=0;
					id_city=0;
					$("#region").val('');
					$("#city").val('');
				}
				if(id_country==0)
					getCountryByRegion();
			}
		);
	}
	//===================================
	$("#region").keydown(function(e){
		if($.inArray(e.which,[9,32,13,220,17,16,18,91,93,191,106,187,189,48,49,40,51,52,53,54,55,56,57,37,38,39,40])==-1){
			$("#select_region").fadeOut(500);
			id_region=0;
			id_city=0;
			$("#city").val('');
			if(($("#region").val().length==1)&&(e.which==8)){
				
			}
			else if($("#region").val().length>-1)
				regionDelay();
		}
	});
	//===================================
	$(".selected_region").live("click",function(){
		var this_id=$(this).attr('id');
		var region=this_id.substr(8,this_id.length);
		$("#region_id").val(id_region);
		id_region=region;
		$("#region").val($(this).text());
		$("#select_region").fadeOut(500);
		city=0;
		$("#city_id").val(city);
		$("#city").val('');
		if(id_country==0)
			getCountryByRegion();
	});
	//===================================
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//????????????????????????????????????????????????????????????
	//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	//ГОРОД
	//==================================
	// функция, делающая задержку для установки готовности блока выбора города
	//==================================
	function cityDelay(){
		city_ready=0;			// устанавливаем в ноль готовность блока выбора города
		delay_all.city=delay_all.city+delay_city;
		setTimeout(city_function,delay_all.city);
	}
	
	//==================================
	//==================================
	// функция, вызывает получение списка городов после окончания паузы
	//==================================
	function city_function(){
		if(city_ready!=1){
			delay_all.city=delay_all.city-delay_city;
			if(delay_all.city==0){
				city_ready=1;		//делаем доступным выбор города
				getCitys();			//вызываем функцию получения списка городов
			}
		}else{
			delay_all.city=0;
		}
	}
	//==================================
	//==================================
	// функция, получения списка городов
	//==================================
	function getCitys(){
		$("select_").hide();
		if(city_ready==1){
			if($("#city").val().length==0){
				id_city=0;
			}
			if($("#city").val().length>-1){
				var id_block="city";
				$("#select_city").parent().parent().find('.ajax-star').show();
				var city_value=$("#city").val();
				if(id_region!=0){
					var type='region';
					var id_parent=id_region;
				}
				else if(id_country!=0){
					var type='country';
					var id_parent=id_country;
				}
				else{ 
					var type='orther';
					var id_parent='0';
				}
				$.get(
					"/index.php",
					{par1:"country",par2:"get_city",par3:id_parent,par4:city_value,par5:type,ajax:"1"},
					function(data){
						var json = eval("(" + data + ")");
						if(json.site.count>1){
							var html_city='';
							$.each(json.site.citys,function(id_c,name_city){
								html_city=html_city+" <div class='selected_ selected_"+id_block+"' id='"+id_block+"_n"+id_c+"'>"+name_city+"</div>  ";
							});
							$("#select_"+id_block).html(html_city);
							$("#select_"+id_block).parent().parent().find('.ajax-star').hide();
							$("#select_"+id_block).fadeIn(500);
						}else if(json.site.count==1){
							$.each(json.site.citys,function(id_c,name_city){
								id_city=id_c;
								name_city=name_city.replace("<b>","");
								$("#select_city").parent().parent().find('.ajax-star').hide();
								name_city=name_city.replace("</b>","");
								$("#city").val(name_city);
							});
							if(id_region==0){
								getRegionByCity();
							}
						}else{
							$("#select_city").parent().parent().find('.ajax-star').hide();
							id_city=0;
						}
					}
				);
			}
			else{
				id_city=0;
				$("#city").val('');
			}
		}
	}
	//===================================
	$("#city").keydown(function(e){
		if($.inArray(e.which,[9,32,13,220,17,16,18,91,93,191,106,187,189,48,49,40,51,52,53,54,55,56,57,37,38,39,40])==-1){
			$("#select_city").fadeOut(500);
			id_city=0;
			if(($("#city").val().length==1)&&(e.which==8)){
				
			}
			else if($("#city").val().length>-1)
				cityDelay();
		}		
	});
	//===================================
	$(".selected_city").live("click",function(){
		var this_id=$(this).attr('id');
		var city=this_id.substr(6,this_id.length);
		$("#city_id").val(id_city);
		id_city=city;
		$("#city").val($(this).text());
		$("#select_city").fadeOut(500);
		if(id_region==0)
			getRegionByCity();
	});
	
	
});
