$(document).ready(function(){
	 /******* Search participant ******/
	var okrugs = $('#selectOkrug');
	var regions = $('#selectRegion');
	var cities = $('#selectCity');
	var MOSCOW_ID = $('#MOSCOW_ID').val();
	var PITER_ID = $('#PITER_ID').val();
	var MOSCOW_REGION_ID = $('#MOSCOW_REGION_ID').val();
	var sel_school = $('#selectSchool');
	var sel_uni = $('#selectUni');
	
	var get, edu;
	if(sel_school.length){
		edu = sel_school;
		get = 'schools';
	}
	if(sel_uni.length){
		edu = sel_uni;
		get = 'uni';
	}
	
	
	function show_flexbox(okrugs, regions, cities, id){
		var sel_school = $('#selectSchool');
		var sel_uni = $('#selectUni');
		var edu = null;
		var get = null;
		var city_id = null;
		if(sel_school.length){
			edu = sel_school;
			get = 'schools';
		}
		if(sel_uni.length){
			edu = sel_uni;
			get = 'uni';
		}
		//console.log(cities.val());
		edu.empty();
		$('#selectSchoolUniWrapper').show();
		
		if(id){
			city_id = id;
		}else{
			city_id = cities.val();
		}
		
		edu.flexbox('/search_selectors/?get='+get+'&city='+city_id, {
			onSelect: function() {
				var id = this.getAttribute('hiddenValue');
				var org_id = regions.val();
				if (org_id === null){
					org_id = okrugs.val();
				}
				var edu_type = $('#edu_type').val();
				if ($(".radio_age").length){
					window.location = '/edu/'+edu_type+'/organization/'+org_id+'/edu_entry/'+id+'/sex/'+$(".radio_sex[checked]").val()+'/age/'+$(".radio_age[checked]").val()+'/';
				}else{
					window.location = '/edu/'+edu_type+'/organization/'+org_id+'/edu_entry/'+id+'/sex/'+$(".radio_sex[checked]").val()+'/';
				}
			}
		});
		
		//$('#selectSchoolUniWrapper').show();
	}
	
	okrugs.change(function(){
		edu.empty();
		$('#selectSchoolUniWrapper').hide();
		if (($(this).val() == MOSCOW_ID) || ($(this).val() == PITER_ID)){
			regions.hide();
			cities.hide();
			show_flexbox(okrugs, regions, cities, $(this).val());
		}else if (MOSCOW_REGION_ID == $(this).val()){
			regions.show();
			cities.hide();
		}else{
			regions.show();
			cities.show();
		}
	});
	
	regions.change(function(){
		edu.empty();
		$('#selectSchoolUniWrapper').hide();
		if(okrugs.val() != MOSCOW_REGION_ID){
			cities.show();
		}else{
			show_flexbox(okrugs, regions, cities, $(this).val());
		}
	});
	
	cities.change(function(){
		if ($('#selectCity:visible').length != 0){
			show_flexbox(okrugs, regions, cities);
		}
	});
	
	
	okrugs.selectChain({
		target: regions,
		url: '/search_selectors/',
		type: 'get',
		value: 'value',
		data: { ajax: true, get: "regions" }
	});
	
	regions.selectChain({
		target: cities,
		url: '/search_selectors/',
		type: 'get',
		value: 'value',
		data: { ajax: true, get: "cities" }
	});
});
